From 5c1aea75330540a99ffa37c4c97a26461420770d Mon Sep 17 00:00:00 2001 From: KnottyDyes <47539659+KnottyDyes@users.noreply.github.com> Date: Sat, 10 Oct 2026 09:17:30 -0600 Subject: [PATCH 01/29] Place: an explicit x, y, spread or width puts the image in a new frame Explicit image placement leaves selected frames untouched; an explicit frame still wins. Null placement parameters behave like omitted values. Reject nonnumeric, nonfinite and nonpositive image widths before editing. Cover rejection without document changes, valid sizing and null selection behavior with regression tests. --- crates/engine/src/cmd/file.rs | 291 +++++++++++++++++++++++++++++++++- 1 file changed, 288 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index f63f0d6e9..f18f1d7b9 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -103,7 +103,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+D"), - "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?, pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|trim|bleed|art|media, loadCursor?: with no frame to fill and no x/y, an image loads into the place cursor (File › Place), layoutPage?: n (IDML / .designcraft: that page's objects as a group)} — places an image (into the selected empty frame if any); text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect` — {autoflow?: adds pages with threaded frames until the text fits, removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename, link?: keep the file linked (Links panel; default: the linkTextFiles preference)}", + "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?: finite number > 0 (null: absent), pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|trim|bleed|art|media, loadCursor?: with no frame to fill and no x/y, an image loads into the place cursor (File › Place), layoutPage?: n (IDML / .designcraft: that page's objects as a group)} — places an image into `frame` when given; otherwise any explicit x/y/spread/width creates a new frame; otherwise uses the selected empty or graphic frame, or creates a new frame; text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect` — {autoflow?: adds pages with threaded frames until the text fits, removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename, link?: keep the file linked (Links panel; default: the linkTextFiles preference)}", has_doc, file_place ), @@ -327,6 +327,16 @@ fn file_place(s: &mut Session, p: &Value) -> Result { if designcraft_textimport::is_text_file(&name) { return super::place_text::place_text(s, p, &name, &bytes, link, before); } + let want_w = p + .get("width") + .filter(|value| !value.is_null()) + .map(|value| { + value + .as_f64() + .filter(|width| width.is_finite() && *width > 0.0) + .ok_or_else(|| bad("file.place", "`width` must be a finite number greater than zero")) + }) + .transpose()?; // Image Import Options: which page of a PDF (1-based). let pdf_page = match p.get("pdfPage").and_then(Value::as_u64) { Some(n) if designcraft_render::is_pdf(&bytes) => { @@ -362,14 +372,20 @@ fn file_place(s: &mut Session, p: &Value) -> Result { None => None, }; let target_frame = super::id_param(p, "frame").or_else(|| { + if ["x", "y", "spread", "width"].iter().any(|key| p.get(*key).is_some_and(|value| !value.is_null())) { + return None; + } let st = s.active()?; st.selection.items.iter().copied().find(|i| st.doc.item(*i).is_some_and(|it| matches!(it.content, Content::Unassigned | Content::Graphic(_)))) }); - let spread = super::spread_param(p, "file.place")?; + // `"spread": null` counts as omitted, like the other placement parameters. + let spread = match p.get("spread") { + Some(Value::Null) => designcraft_doc::SpreadRef::Doc(0), + _ => super::spread_param(p, "file.place")?, + }; let lid = s.doc()?.active_layer; let px = p.get("x").and_then(Value::as_f64); let py = p.get("y").and_then(Value::as_f64); - let want_w = p.get("width").and_then(Value::as_f64); if target_frame.is_none() && px.is_none() && py.is_none() && p.get("loadCursor").and_then(Value::as_bool) == Some(true) { let mime = designcraft_render::image_mime(&bytes).to_string(); let asset = Asset { page: pdf_page, id: AssetId(0), name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)) }; @@ -734,6 +750,275 @@ fn file_revert(s: &mut Session, _: &Value) -> Result { } } +#[cfg(all(test, not(target_arch = "wasm32")))] +mod image_place_tests { + use designcraft_doc::{Content, ItemId}; + use designcraft_geom::Rect; + use serde_json::{Value, json}; + + use crate::Session; + + fn image_file() -> std::io::Result { + image_file_with_color(30) + } + + fn image_file_with_color(red: u8) -> std::io::Result { + let file = tempfile::Builder::new().suffix(".png").tempfile()?; + let png = designcraft_render::Rendered { width: 40, height: 20, pixels: [red, 90, 180, 255].repeat(800) }.to_png(); + std::fs::write(file.path(), png)?; + Ok(file) + } + + #[test] + fn consecutive_path_placements_create_distinct_graphics() { + let images = [image_file_with_color(30).unwrap(), image_file_with_color(31).unwrap(), image_file_with_color(32).unwrap()]; + let mut session = Session::new(); + session.execute("file.new", &json!({"pages": 3, "facingPages": false})).unwrap(); + let mut placements = Vec::new(); + let mut originals = Vec::new(); + + for ((spread, x, y), image) in [(0, 0.0, 0.0), (1, 70.0, 90.0), (2, 150.0, 210.0)].into_iter().zip(&images) { + let placed = session.execute("file.place", &json!({"path": image.path(), "spread": spread, "x": x, "y": y})).unwrap(); + let id = ItemId(placed["id"].as_u64().unwrap()); + assert!( + placements.iter().all(|previous: &Value| previous["id"] != placed["id"]), + "each explicit placement needs a distinct frame: {placed}" + ); + let document = &session.doc().unwrap().doc; + let item = document.item(id).unwrap(); + assert_eq!(item.bounds(), Rect::new(x, y, x + 40.0, y + 20.0)); + assert!(document.spreads[spread].items.iter().any(|item| item.id == id)); + originals.push(serde_json::to_value(item).unwrap()); + placements.push(placed); + } + + let document = &session.doc().unwrap().doc; + assert_eq!(document.spreads.iter().flat_map(|spread| &spread.items).filter(|item| matches!(item.content, Content::Graphic(_))).count(), 3); + assert_eq!(document.assets.len(), 3); + for (placed, original) in placements.iter().zip(originals) { + assert_eq!(serde_json::to_value(document.item(ItemId(placed["id"].as_u64().unwrap())).unwrap()).unwrap(), original); + } + let links = session.execute("links.list", &json!({})).unwrap(); + assert_eq!(links.as_array().unwrap().len(), 3); + for (placed, image) in placements.into_iter().zip(&images) { + let row = links.as_array().unwrap().iter().find(|row| row["asset"] == placed["asset"]).unwrap(); + assert_eq!(row["path"], json!(image.path())); + assert_eq!(row["uses"].as_array().unwrap().len(), 1); + assert_eq!(row["uses"][0]["id"], placed["id"]); + } + } + + #[test] + fn individual_placement_parameters_bypass_selected_frames() { + let image = image_file().unwrap(); + for graphic in [false, true] { + for (key, value, expected) in [ + ("x", 0, Rect::new(0.0, 36.0, 40.0, 56.0)), + ("y", 0, Rect::new(36.0, 0.0, 76.0, 20.0)), + ("spread", 0, Rect::new(36.0, 36.0, 76.0, 56.0)), + ("width", 0, Rect::ZERO), + ("width", 80, Rect::new(36.0, 36.0, 116.0, 76.0)), + ] { + let mut session = Session::new(); + session.execute("file.new", &json!({})).unwrap(); + let selected = session.execute("frame.create", &json!({"rect": [100, 120, 200, 220]})).unwrap(); + if graphic { + session.execute("file.place", &json!({"path": image.path()})).unwrap(); + } + let id = ItemId(selected["id"].as_u64().unwrap()); + let original = serde_json::to_value(session.doc().unwrap().doc.item(id).unwrap()).unwrap(); + let mut params = json!({"path": image.path()}); + params[key] = json!(value); + + let result = session.execute("file.place", ¶ms); + if key == "width" && value == 0 { + assert!(result.is_err(), "zero width must be rejected, graphic={graphic}"); + continue; + } + let placed = result.unwrap(); + + assert_ne!(placed["id"], selected["id"], "{key}={value}, graphic={graphic}"); + let document = &session.doc().unwrap().doc; + assert_eq!(serde_json::to_value(document.item(id).unwrap()).unwrap(), original); + let item = document.item(ItemId(placed["id"].as_u64().unwrap())).unwrap(); + assert_eq!(item.bounds(), expected); + let Content::Graphic(content) = &item.content else { panic!("placed frame must be graphic") }; + let [scale_x, _, _, scale_y, _, _] = content.xf.as_coeffs(); + assert!(scale_x > 0.0 && scale_y > 0.0); + } + } + } + + #[test] + fn explicit_frame_wins_over_placement_and_selection() { + let image = image_file().unwrap(); + let mut session = Session::new(); + session.execute("file.new", &json!({})).unwrap(); + let target = session.execute("frame.create", &json!({"rect": [100, 120, 200, 220]})).unwrap(); + let selected = session.execute("frame.create", &json!({"rect": [300, 320, 400, 420]})).unwrap(); + + let placed = + session.execute("file.place", &json!({"path": image.path(), "frame": target["id"], "x": 0, "y": 0, "spread": 99, "width": 80})).unwrap(); + + assert_eq!(placed["id"], target["id"]); + let document = &session.doc().unwrap().doc; + let item = document.item(ItemId(target["id"].as_u64().unwrap())).unwrap(); + assert_eq!(item.bounds(), Rect::new(100.0, 120.0, 200.0, 220.0)); + assert!(matches!(item.content, Content::Graphic(_))); + assert!(matches!(document.item(ItemId(selected["id"].as_u64().unwrap())).unwrap().content, Content::Unassigned)); + assert_eq!(document.spreads[0].items.len(), 2); + } + + fn assert_width_rejected(width: Value) -> std::result::Result<(), Box> { + let image = image_file()?; + for graphic in [false, true] { + for explicit_frame in [false, true] { + let mut session = Session::new(); + session.execute("file.new", &json!({}))?; + let target = session.execute("frame.create", &json!({"rect": [100, 120, 200, 220]}))?; + if graphic { + session.execute("file.place", &json!({"path": image.path()}))?; + } + let mut params = json!({"path": image.path(), "width": width}); + if explicit_frame { + params["frame"] = target["id"].clone(); + session.execute("frame.create", &json!({"rect": [300, 320, 400, 420]}))?; + } + let before = session.doc()?; + let document = before.doc.clone(); + let selection = before.selection.clone(); + let revision = before.revision; + let assets = document.assets.len(); + + let result = session.execute("file.place", ¶ms); + + assert!( + matches!(&result, Err(crate::EngineError::BadParams { .. })), + "width={width}, graphic={graphic}, explicit_frame={explicit_frame}: expected BadParams, got {result:?}" + ); + let error = result.err().ok_or_else(|| crate::EngineError::Other("expected placement error".into()))?; + let crate::EngineError::BadParams { cmd, msg } = error else { return Err(error.into()) }; + assert_eq!(cmd, "file.place"); + assert!(msg.contains("width") && msg.contains("finite") && msg.contains("greater than zero"), "{msg}"); + let after = session.doc()?; + assert!(std::sync::Arc::ptr_eq(&document, &after.doc)); + assert_eq!(after.selection, selection); + assert_eq!(after.revision, revision); + assert_eq!(after.doc.assets.len(), assets); + } + } + Ok(()) + } + + #[test] + fn width_rejected_when_zero() { + assert_width_rejected(json!(0)).unwrap(); + } + + #[test] + fn width_rejected_when_negative() { + assert_width_rejected(json!(-80)).unwrap(); + } + + #[test] + fn width_rejected_when_non_numeric() { + for width in [json!("80"), json!(true), json!([80]), json!({"value": 80})] { + assert_width_rejected(width).unwrap(); + } + } + + #[test] + fn numeric_overflow_rejected_when_parsing_json() { + let result = serde_json::from_str::(r#"{"width":1e400}"#); + let error = result.unwrap_err(); + assert!(error.is_data() || error.is_syntax(), "{error}"); + eprintln!("overflow parser rejected width=1e400: {error}"); + } + + fn assert_null_placement_uses_selection(keys: &[&str]) -> std::result::Result<(), Box> { + let image = image_file()?; + let previous_image = image_file_with_color(31)?; + for graphic in [false, true] { + let mut session = Session::new(); + session.execute("file.new", &json!({}))?; + let selected = session.execute("frame.create", &json!({"rect": [100, 120, 200, 220]}))?; + let previous = graphic.then(|| session.execute("file.place", &json!({"path": previous_image.path()}))).transpose()?; + let mut params = json!({"path": image.path()}); + for key in keys { + params[*key] = Value::Null; + } + + let placed = session.execute("file.place", ¶ms)?; + + assert_eq!(placed["id"], selected["id"], "keys={keys:?}, graphic={graphic}"); + if let Some(previous) = previous { + assert_ne!(placed["asset"], previous["asset"]); + } + let document = &session.doc()?.doc; + let id = ItemId(selected["id"].as_u64().ok_or_else(|| crate::EngineError::Other("frame.create returned no numeric id".into()))?); + let item = document.item(id).ok_or(designcraft_doc::DocError::NoItem(id))?; + assert_eq!(item.bounds(), Rect::new(100.0, 120.0, 200.0, 220.0)); + assert!(matches!(&item.content, Content::Graphic(_)), "placed frame must be graphic"); + let Content::Graphic(content) = &item.content else { + return Err(crate::EngineError::Other("placed frame must be graphic".into()).into()); + }; + assert_eq!(json!(content.asset.0), placed["asset"]); + assert_eq!(document.spreads[0].items.len(), 1); + } + Ok(()) + } + + #[test] + fn selection_used_when_x_null() { + assert_null_placement_uses_selection(&["x"]).unwrap(); + } + + #[test] + fn selection_used_when_y_null() { + assert_null_placement_uses_selection(&["y"]).unwrap(); + } + + #[test] + fn selection_used_when_spread_null() { + assert_null_placement_uses_selection(&["spread"]).unwrap(); + } + + #[test] + fn selection_used_when_width_null() { + assert_null_placement_uses_selection(&["width"]).unwrap(); + } + + #[test] + fn selection_used_when_all_placement_parameters_null() { + assert_null_placement_uses_selection(&["x", "y", "spread", "width"]).unwrap(); + } + + #[test] + fn implicit_placement_fills_empty_and_replaces_graphic_selection() { + let image = image_file().unwrap(); + let previous_image = image_file_with_color(31).unwrap(); + for graphic in [false, true] { + let mut session = Session::new(); + session.execute("file.new", &json!({})).unwrap(); + let selected = session.execute("frame.create", &json!({"rect": [100, 120, 200, 220]})).unwrap(); + let previous = graphic.then(|| session.execute("file.place", &json!({"path": previous_image.path()})).unwrap()); + + let placed = session.execute("file.place", &json!({"path": image.path()})).unwrap(); + + assert_eq!(placed["id"], selected["id"]); + if let Some(previous) = previous { + assert_ne!(placed["asset"], previous["asset"]); + } + let document = &session.doc().unwrap().doc; + let item = document.item(ItemId(placed["id"].as_u64().unwrap())).unwrap(); + assert_eq!(item.bounds(), Rect::new(100.0, 120.0, 200.0, 220.0)); + let Content::Graphic(content) = &item.content else { panic!("placed frame must be graphic") }; + assert_eq!(json!(content.asset.0), placed["asset"]); + assert_eq!(document.spreads[0].items.len(), 1); + } + } +} + #[cfg(test)] mod pdf_crop_tests { use serde_json::json; From 0613948d3d1da1d968a3333747eb890a62a21dc1 Mon Sep 17 00:00:00 2001 From: KnottyDyes <47539659+KnottyDyes@users.noreply.github.com> Date: Sat, 10 Oct 2026 09:53:25 -0600 Subject: [PATCH 02/29] SVG: a font family named in any case finds the installed font DesignCraft matched an SVG font-family case-insensitively when importing the installed faces, but the final fontdb query compares names exactly, so "DeJaVu SaNs" loaded DejaVu Sans and then set the text in the serif fallback (Source Serif 4) without a word. Text frames already accept any case. The SVG font selector now runs usvg default query with each named family spelled the way the font database spells it; family order, generics, weight, stretch and style are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BSB7fMQUccqFQekksDGWpo --- crates/images/src/lib.rs | 79 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 72 insertions(+), 7 deletions(-) diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 28a42522d..ece1697f1 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -73,14 +73,18 @@ fn svg_options() -> &'static usvg::Options<'static> { } /// A family the SVG names that isn't bundled comes from the shared fonts (installed ones too), -/// as it would in a text frame. A name that is no family's but a face's PostScript name (as -/// Illustrator's SVG export writes them: `font-family="'MyriadPro-Regular'"`) sets the text in -/// that face, whatever font-weight and font-style say: the name already picks the weight and -/// style, and a family's other faces would contradict it. Families listed before it come first. +/// as it would in a text frame, and matches in any case, as it does there. A name that is no +/// family's but a face's PostScript name (as Illustrator's SVG export writes them: +/// `font-family="'MyriadPro-Regular'"`) sets the text in that face, whatever font-weight and +/// font-style say: the name already picks the weight and style, and a family's other faces would +/// contradict it. Families listed before it come first. fn select_font() -> usvg::FontSelectionFn<'static> { - let bundled = usvg::FontResolver::default_font_selector(); + use usvg::fontdb::{Family, Query, Stretch, Style, Weight}; Box::new(move |font, db| { let fonts = designcraft_fonts::FontDb::global(); + let spelled = |db: &usvg::fontdb::Database, name: &str| { + db.faces().flat_map(|f| &f.families).find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(n, _)| n.clone()) + }; for family in font.families() { if let usvg::FontFamily::Named(name) = family && !has_family(db, name) @@ -103,11 +107,51 @@ fn select_font() -> usvg::FontSelectionFn<'static> { return Some(id); } } - // A family (or generic family) that matches: usvg's own selection. + // A family (or generic family) that matches: the query below. _ => break, } } - bundled(font, db) + // usvg's default query, but with each named family spelled as the database spells it: + // fontdb compares names exactly, so "DeJaVu SaNs" would quietly fall to the serif. + let names: Vec> = font + .families() + .iter() + .map(|f| match f { + usvg::FontFamily::Named(name) => Some(spelled(db, name).unwrap_or_else(|| name.clone())), + _ => None, + }) + .collect(); + let mut families: Vec = font + .families() + .iter() + .zip(&names) + .map(|(f, name)| match f { + usvg::FontFamily::Serif => Family::Serif, + usvg::FontFamily::SansSerif => Family::SansSerif, + usvg::FontFamily::Cursive => Family::Cursive, + usvg::FontFamily::Fantasy => Family::Fantasy, + usvg::FontFamily::Monospace => Family::Monospace, + usvg::FontFamily::Named(_) => Family::Name(name.as_deref().unwrap_or_default()), + }) + .collect(); + families.push(Family::Serif); + let stretch = match font.stretch() { + usvg::FontStretch::UltraCondensed => Stretch::UltraCondensed, + usvg::FontStretch::ExtraCondensed => Stretch::ExtraCondensed, + usvg::FontStretch::Condensed => Stretch::Condensed, + usvg::FontStretch::SemiCondensed => Stretch::SemiCondensed, + usvg::FontStretch::Normal => Stretch::Normal, + usvg::FontStretch::SemiExpanded => Stretch::SemiExpanded, + usvg::FontStretch::Expanded => Stretch::Expanded, + usvg::FontStretch::ExtraExpanded => Stretch::ExtraExpanded, + usvg::FontStretch::UltraExpanded => Stretch::UltraExpanded, + }; + let style = match font.style() { + usvg::FontStyle::Normal => Style::Normal, + usvg::FontStyle::Italic => Style::Italic, + usvg::FontStyle::Oblique => Style::Oblique, + }; + db.query(&Query { families: &families, weight: Weight(font.weight()), stretch, style }) }) } @@ -518,6 +562,27 @@ mod tests { assert_eq!(text_face(r#" font-family="NoSuch-Font""#), "SourceSerif4-Regular"); } + #[test] + fn svg_family_names_match_in_any_case() { + let font = designcraft_fonts::testing::font_with("DC Test SVG Casing", &['A', 'b']).unwrap(); + designcraft_fonts::FontDb::global().add_font(font); + let text = |family: &str, attrs: &str| { + format!( + r#"Ab"# + ) + }; + for family in ["DC Test SVG Casing", "dc test svg casing", "DC TEST svg Casing", "Nope, dc test SVG casing, serif"] { + let set = glyph_families(&text(family, "")); + assert!(set.len() == 2 && set.iter().all(|(f, gid)| f == "DC Test SVG Casing" && *gid != 0), "{family}: {set:?}"); + } + // Weight and style still reach the query: there's only a regular face, so it sets the text. + let set = glyph_families(&text("dc test svg casing", r#" font-weight="700" font-style="italic""#)); + assert!(set.len() == 2 && set.iter().all(|(f, _)| f == "DC Test SVG Casing"), "{set:?}"); + // A family nobody has still falls to the bundled serif. + let set = glyph_families(&text("DC Test SVG Nobody", "")); + assert!(set.len() == 2 && set.iter().all(|(f, _)| f == "Source Serif 4"), "{set:?}"); + } + /// A minimal Photoshop file: 2×1 RGB, no layers, raw merged image. fn tiny_psd() -> Vec { let mut b = Vec::new(); From 4a2f6037710a5722e0a7ecac05f68628d40233a9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 16 Oct 2026 14:14:34 +0000 Subject: [PATCH 03/29] Integration: #404's case test is already on main --- crates/images/src/lib.rs | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 382f8e245..25d042c43 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -607,27 +607,6 @@ mod tests { assert_eq!(text_face(r#" font-family="NoSuch-Font""#), "SourceSerif4-Regular"); } - #[test] - fn svg_family_names_match_in_any_case() { - let font = designcraft_fonts::testing::font_with("DC Test SVG Casing", &['A', 'b']).unwrap(); - designcraft_fonts::FontDb::global().add_font(font); - let text = |family: &str, attrs: &str| { - format!( - r#"Ab"# - ) - }; - for family in ["DC Test SVG Casing", "dc test svg casing", "DC TEST svg Casing", "Nope, dc test SVG casing, serif"] { - let set = glyph_families(&text(family, "")); - assert!(set.len() == 2 && set.iter().all(|(f, gid)| f == "DC Test SVG Casing" && *gid != 0), "{family}: {set:?}"); - } - // Weight and style still reach the query: there's only a regular face, so it sets the text. - let set = glyph_families(&text("dc test svg casing", r#" font-weight="700" font-style="italic""#)); - assert!(set.len() == 2 && set.iter().all(|(f, _)| f == "DC Test SVG Casing"), "{set:?}"); - // A family nobody has still falls to the bundled serif. - let set = glyph_families(&text("DC Test SVG Nobody", "")); - assert!(set.len() == 2 && set.iter().all(|(f, _)| f == "Source Serif 4"), "{set:?}"); - } - /// A minimal Photoshop file: 2×1 RGB, no layers, raw merged image. fn tiny_psd() -> Vec { let mut b = Vec::new(); From 8a6f9725b03c2ffd255cc582841e7f12f4d1a5ab Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 22 Oct 2026 01:25:12 -0400 Subject: [PATCH 04/29] IDML: test a ruler guide in a column gutter without facing pages (#1096) (#1170) --- crates/idml/src/tests.rs | 53 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs index 035333da4..81cebff70 100644 --- a/crates/idml/src/tests.rs +++ b/crates/idml/src/tests.rs @@ -4194,6 +4194,59 @@ mod liquid_page_rules { } } +/// #1096: a ruler guide inside the gutter of a two-column page, written the way InDesign writes +/// it (a `` child after its `MarginPreference`, with `Properties`/`GuideColor`, `PageIndex` +/// and `GuideZone`), in a document without facing pages. A spread guide sits beside it. +#[test] +fn ruler_guide_in_a_column_gutter_imports_without_facing_pages() { + use designcraft_doc::Orientation::{Horizontal, Vertical}; + let package = |view: &str| { + let prefs = + PREFS.replace(r#"FacingPages="true""#, r#"FacingPages="false""#).replace("", &format!("{view}")); + let spread = SPREAD.replace( + r#" + + "#, + r#" + UseMasterColor + + + + Cyan + + + Cyan + + "#, + ); + assert_ne!(spread, SPREAD, "the fixture's first page was replaced"); + import_idml(&zip_files(&[ + ("designmap.xml", DESIGNMAP), + ("Resources/Graphic.xml", GRAPHIC), + ("Resources/Styles.xml", STYLES), + ("Resources/Preferences.xml", &prefs), + ("MasterSpreads/MasterSpread_m1.xml", MASTER), + ("Spreads/Spread_sp1.xml", &spread), + ("Stories/Story_s1.xml", STORY), + ])) + .unwrap() + }; + let guides = + |d: &Document| d.spreads[0].pages[0].guides.iter().map(|g| (g.orientation, g.position, g.spread, g.layer.is_some())).collect::>(); + // The first page starts at x 0 in our spread coordinates, so the spread's and the page's ruler + // origins agree; no ViewPreference means InDesign's default, the spread. + for view in ["", r#""#, r#""#] { + let first = package(view); + assert!(!first.settings.facing_pages); + assert_eq!(guides(&first), [(Vertical, 180.0, false, true), (Horizontal, 300.0, true, true)], "{view:?}"); + // The guide sits between the page's left margin (20) and right margin (470). + let m = first.spreads[0].pages[0].margin_rect(); + assert!(m.x0 < 180.0 && 180.0 < m.x1); + let back = import_idml(&export_idml(&first)).unwrap(); + assert_eq!(guides(&back), guides(&first), "round trip, {view:?}"); + } +} + /// Cell Options › Text › First Baseline, set by a cell style that a table style applies to its body /// region (cells with `[None]` take it from there) and overridden on one cell. const FIRST_BASELINE_STYLES: &str = r#" From 2660395db553f182d23dadec8f4885c6498a0014 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 22 Oct 2026 01:31:36 -0400 Subject: [PATCH 05/29] macOS: a Language submenu in the app menu (#1541) --- ROADMAP.md | 1 + apps/designcraft/src/native_menu.rs | 12 ++++++++++++ crates/ui-egui/src/i18n.rs | 2 +- crates/ui-egui/src/menus.rs | 11 ++++++++++- 4 files changed, 24 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 013cc48db..9c4cb465c 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-22** · macOS: the app menu has a Language submenu after Settings… with each interface language in its own name and the current one checked, as in the suite's other apps; Preferences › General › Interface Language stays. No readiness percentage change. - **2026-10-22** · macOS menu bar: the menus keep working after the interface language or Show CJK Features changes (a rebuilt menu bar lost every click, Quit included), and its key equivalents are the shortcuts in effect, so a shortcut moved in the Keyboard Shortcuts editor leaves its old menu item. No readiness percentage change. - **2026-10-22** · Paragraph rules: Rule Above's offset is measured from the first line's baseline to the rule's bottom edge, as in InDesign. Rules sat one ascent too high and crossed the previous paragraph's text (reported from an imported INDD document). 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. diff --git a/apps/designcraft/src/native_menu.rs b/apps/designcraft/src/native_menu.rs index e444641bf..1ac9437d1 100644 --- a/apps/designcraft/src/native_menu.rs +++ b/apps/designcraft/src/native_menu.rs @@ -91,6 +91,18 @@ impl NativeMenu { items.insert(id.into(), (command.into(), Value::Null, Handle::Plain(item))); appended } + AppMenuItem::Language => { + let sub = Submenu::new(menu_title(app, "Language"), true); + for (code, name) in designcraft_ui_egui::i18n::LANGUAGES { + let id = format!("dc-language-{}", if code.is_empty() { "en" } else { code }); + let params = serde_json::json!({ "lang": code }); + let checked = menus::checked(app, "app.language", ¶ms).unwrap_or(false); + let item = CheckMenuItem::with_id(id.clone(), menus::native_label(name), true, checked, None); + let _ = sub.append(&item); + items.insert(id, ("app.language".into(), params, Handle::Check(item))); + } + app_menu.append(&sub) + } AppMenuItem::Sep => app_menu.append(&PredefinedMenuItem::separator()), AppMenuItem::Services => app_menu.append(&PredefinedMenuItem::services(None)), AppMenuItem::Hide => app_menu.append(&PredefinedMenuItem::hide(None)), diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index efe089ef9..c2abdb9a9 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -3155,7 +3155,7 @@ const TABLE: &[(&str, [&str; 5])] = &[ ("Graphic…", ["Graphic…", "Graphique…", "Graphic…", "Graphic…", "图形…"]), ("Home", ["Home", "Accueil", "Home", "Home", "主页"]), ("Join:", ["Join:", "Sommet :", "Join:", "Join:", "连接:"]), - ("Language", ["Language", "Langue", "Language", "Language", "语言"]), + ("Language", ["Sprache", "Langue", "Idioma", "言語", "语言"]), ("Last Spread", ["Last Spread", "Dernière planche", "Last Spread", "Last Spread", "最后一个跨页"]), ("Load DTD…", ["Load DTD…", "Charger la DTD…", "Load DTD…", "Load DTD…", "载入 DTD…"]), ("Location:", ["Location:", "Emplacement :", "Location:", "Location:", "位置:"]), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 5677c329e..c455b718d 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -2286,6 +2286,9 @@ pub enum AppMenuItem { command: &'static str, }, Sep, + /// Interface language: a submenu with each UI language in its own name, the current one + /// checked (`app.language {lang}`). + Language, Services, Hide, HideOthers, @@ -2298,6 +2301,7 @@ pub const MAC_APP_MENU: &[AppMenuItem] = &[ AppMenuItem::Cmd { id: "dc-discord", label: "Join the ArtCraft Discord…", command: "help.discord" }, AppMenuItem::Sep, AppMenuItem::Cmd { id: "dc-settings", label: "Settings…", command: "app.preferences" }, + AppMenuItem::Language, AppMenuItem::Sep, AppMenuItem::Services, AppMenuItem::Sep, @@ -5566,7 +5570,12 @@ mod tests { let (Some(about), Some(settings)) = (pos("help.about"), pos("app.preferences")) else { panic!("About and Settings are in the app menu") }; assert!(about < settings); assert_eq!(MAC_APP_MENU.get(settings - 1), Some(&AppMenuItem::Sep)); - assert_eq!(MAC_APP_MENU.get(settings + 1), Some(&AppMenuItem::Sep)); + // Language follows Settings, as in the suite's other apps, titled in the interface language. + assert_eq!(MAC_APP_MENU.get(settings + 1), Some(&AppMenuItem::Language)); + assert_eq!(MAC_APP_MENU.get(settings + 2), Some(&AppMenuItem::Sep)); + for (code, _) in crate::i18n::LANGUAGES.iter().filter(|(c, _)| !c.is_empty()) { + assert_ne!(crate::i18n::tr(code, "Language"), "Language", "{code}"); + } let label = |command: &str| { MAC_APP_MENU.iter().find_map(|m| match m { AppMenuItem::Cmd { label, command: c, .. } if *c == command => Some(*label), From 3be2736d0a05ad329c0a2494067d8c7f32181e50 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 22 Oct 2026 01:47:49 -0400 Subject: [PATCH 06/29] Guides: select ruler guides and set their position (#1282) (#1445) * Guides: a dragged guide shows where it is (#1282) While a guide is dragged out of a ruler or moved, a label beside the pointer reads X: or Y: and the guide's place, in the ruler units and measured the way the rulers measure (from the zero point, and from the page origin when rulers restart per page). * Guides: keep the drag readout inside the canvas Near the canvas's right or bottom edge the readout flips to the other side of the pointer, and it is kept inside the canvas in every case (readout_at). * Guides: the drag readout measures the spread under the pointer The readout measured from the spread in the middle of the view (where the rulers measure), but a guide is dropped on the spread under the pointer, so with spreads above one another the number shown could differ from the guide's place. It now measures that spread (ruler_pieces_of). * Guides: no readout for an existing guide over another spread An existing guide moves only on its own spread (guide_drag), so dropped over another it stays where it was: the readout no longer shows a place there it won't go. * #1282: guide selection commands (guide.select, guide.selectAll, guide.deselect, guide.moveBy) * #1282: select ruler guides on the canvas, X/Y in the Control bar and Properties * #1282: guides take clicks over objects, a new guide is selected, group drag preview * ROADMAP: the progress line lands in one commit after the guide PRs --------- Co-authored-by: SBaksa --- crates/doc/src/selection.rs | 14 + crates/engine/src/cmd/edit.rs | 53 +- crates/engine/src/cmd/guides.rs | 537 +++++++++++++++++++- crates/engine/src/cmd/mod.rs | 2 +- crates/engine/src/lib.rs | 11 + crates/engine/src/tests.rs | 3 +- crates/tools/src/lib.rs | 5 + crates/tools/src/select.rs | 61 ++- crates/ui-egui/src/canvas.rs | 315 +++++++++++- crates/ui-egui/src/guide_selection_tests.rs | 258 ++++++++++ crates/ui-egui/src/i18n.rs | 5 + crates/ui-egui/src/i18n/ar.rs | 2 + crates/ui-egui/src/i18n/cs.rs | 2 + crates/ui-egui/src/i18n/de.rs | 2 + crates/ui-egui/src/i18n/it.rs | 2 + crates/ui-egui/src/i18n/ja.rs | 2 + crates/ui-egui/src/i18n/ka.rs | 2 + crates/ui-egui/src/i18n/pl.rs | 2 + crates/ui-egui/src/i18n/pt_br.rs | 2 + crates/ui-egui/src/i18n/ru.rs | 2 + crates/ui-egui/src/i18n/uk.rs | 2 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/menus.rs | 39 +- crates/ui-egui/src/object_control.rs | 15 +- crates/ui-egui/src/panels/mod.rs | 43 ++ crates/ui-egui/src/panels/properties.rs | 29 ++ docs/target-app-parity.md | 2 +- 27 files changed, 1327 insertions(+), 86 deletions(-) create mode 100644 crates/ui-egui/src/guide_selection_tests.rs diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index 2d28bf2c2..11c4e2ab1 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -2,9 +2,19 @@ use serde::{Deserialize, Serialize}; +use crate::edit::SpreadRef; use crate::ids::{ItemId, StoryId}; use crate::table::CellRange; +/// A selected ruler guide: index `index` in the guides of page `page` of spread `spread`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GuideSel { + pub spread: SpreadRef, + pub page: usize, + pub index: usize, +} + /// A table cell: the table (in the selection's story) and the owning cell's grid position. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -83,6 +93,10 @@ pub struct Selection { /// The page selected with the Page tool (absolute index). #[serde(default, skip_serializing_if = "Option::is_none")] pub page: Option, + /// Selected ruler guides. Never together with items, text or cells: selecting one clears + /// the other. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub guides: Vec, } impl Selection { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 9ee963317..e5a2d2296 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -256,28 +256,39 @@ pub fn specs() -> Vec { st.bump_revision(); ok() }), - cmd!("edit.clear", "Clear", ["Edit"], Some("Delete"), "{ids?} — delete selected items (or the selected text)", has_doc, |s, p| { - if s.doc()?.selection.text.is_some() && p.get("ids").is_none() { - return super::text::delete_selection(s); - } - let ids = super::targets(s, p)?; - // With a placed graphic itself selected (Direct Selection), only the graphic goes: its - // frame stays, empty and selected (as in InDesign). Other items are deleted. - let content = s.doc()?.selection.content && p.get("ids").is_none(); - s.edit(|d, sel| { - let mut kept = Vec::new(); - for id in &ids { - if let Some(it) = d.item_mut(*id).filter(|it| content && matches!(it.content, designcraft_doc::Content::Graphic(_))) { - it.content = designcraft_doc::Content::Unassigned; - kept.push(*id); - } else { - let _ = d.remove_item(*id); - } + cmd!( + "edit.clear", + "Clear", + ["Edit"], + Some("Delete"), + "{ids?} — delete selected items (or the selected text or ruler guides)", + has_doc, + |s, p| { + if s.doc()?.selection.text.is_some() && p.get("ids").is_none() { + return super::text::delete_selection(s); } - *sel = Selection::items(kept); - Ok(json!({"deleted": ids.len()})) - }) - }), + if p.get("ids").is_none() && s.doc()?.selection.items.is_empty() && !s.doc()?.selection.guides.is_empty() { + return s.execute("guide.delete", &json!({})); + } + let ids = super::targets(s, p)?; + // With a placed graphic itself selected (Direct Selection), only the graphic goes: its + // frame stays, empty and selected (as in InDesign). Other items are deleted. + let content = s.doc()?.selection.content && p.get("ids").is_none(); + s.edit(|d, sel| { + let mut kept = Vec::new(); + for id in &ids { + if let Some(it) = d.item_mut(*id).filter(|it| content && matches!(it.content, designcraft_doc::Content::Graphic(_))) { + it.content = designcraft_doc::Content::Unassigned; + kept.push(*id); + } else { + let _ = d.remove_item(*id); + } + } + *sel = Selection::items(kept); + Ok(json!({"deleted": ids.len()})) + }) + } + ), cmd!(noundo "edit.copy", "Copy", ["Edit"], Some("Cmd+C"), "{} → {text} when text is selected (with formatting, footnotes, markers)", has_selection_or_text, |s, _| { if let Some(text) = copy_text(s)? { return Ok(json!({"text": text})); diff --git a/crates/engine/src/cmd/guides.rs b/crates/engine/src/cmd/guides.rs index e8be163ef..97bf4e9cc 100644 --- a/crates/engine/src/cmd/guides.rs +++ b/crates/engine/src/cmd/guides.rs @@ -1,18 +1,28 @@ -//! Ruler guides: add (dragged from the rulers), move, delete, list; Layout › Create Guides. +//! Ruler guides: add (dragged from the rulers), select, move, delete, list; Layout › Create +//! Guides. //! //! Guides are stored on their page in spread coordinates; a spread guide (dropped on the //! pasteboard) lives on the spread's first page with `spread: true` and crosses the pasteboard. +//! Selected guides are [`Selection::guides`], addressed as (spread, page, index): the commands +//! that delete guides renumber it, and [`keep_selection_valid`] drops what another command made +//! stale. -use designcraft_doc::{Document, Guide, Orientation, SpreadRef}; +use std::collections::{HashMap, HashSet}; + +use designcraft_doc::{Document, Guide, GuideSel, Orientation, Selection, SpreadRef}; use designcraft_geom::Rect; use serde_json::{Value, json}; -use super::{CommandSpec, bad, cmd, has_doc, str_param}; -use crate::{Result, Session}; +use super::{CommandSpec, bad, bool_or, cmd, has_doc, str_param}; +use crate::{DocState, Result, Session}; const MAX_GUIDE_DIVISIONS: u64 = 1000; const MAX_GUIDES_CREATED: usize = 10_000; const MAX_GUIDE_GUTTER: f64 = 1_000_000.0; +/// The farthest a guide may be from the spread origin, in points, either way. +const MAX_GUIDE_POSITION: f64 = 1_000_000.0; +/// The most guides one `guides` list may name. +const MAX_GUIDES_NAMED: usize = 10_000; pub fn specs() -> Vec { vec![ @@ -21,34 +31,87 @@ pub fn specs() -> Vec { "New Guide", [], None, - "{orientation: horizontal|vertical, position (spread coordinate), spread?, page? (index in the spread; default: the page under `at` or the position), at? (the other coordinate), spreadGuide?: bool, liquid?: bool (a liquid guide, as the Page tool draws from the rulers)} or {orientation: both, point: [x, y], spread?, page?, spreadGuide?: bool, liquid?: bool} → {page, index}; `both` adds a horizontal guide through y and a vertical guide through x as one undo step → {guides: [{page, index}, {page, index}]}", + "{orientation: horizontal|vertical, position (spread coordinate, at most 1000000 pt either way), spread?, page? (index in the spread; default: the page under `at` or the position), at? (the other coordinate), spreadGuide?: bool, liquid?: bool (a liquid guide, as the Page tool draws from the rulers)} or {orientation: both, point: [x, y], spread?, page?, spreadGuide?: bool, liquid?: bool} → {page, index}; `both` adds a horizontal guide through y and a vertical guide through x as one undo step → {guides: [{page, index}, {page, index}]}. The new guides become the selection; objects are deselected", has_doc, add ), - cmd!("guide.move", "Move Guide", [], None, "{spread?, page, index, position}", has_doc, move_guide), - cmd!("guide.delete", "Delete Guide", [], None, "{spread?, page, index}", has_doc, delete), + cmd!("guide.move", "Move Guide", [], None, "{spread?, page, index, position (at most 1000000 pt either way)}", has_doc, move_guide), + cmd!( + "guide.moveBy", + "Move Guides", + [], + None, + "{dx?, dy?, guides?: [{spread?, page, index}] (default: the selected guides)} — vertical guides move by dx, horizontal ones by dy, as one undo step", + has_doc, + move_by + ), + cmd!( + "guide.delete", + "Delete Guide", + [], + None, + "{spread?, page, index}, or {} for the selected guides; an address without page or index is an error", + has_doc, + delete + ), cmd!("guide.deleteAll", "Delete All Guides on Spread", ["View", "Grids & Guides"], None, "{spread?}", has_doc, |s, p| { let r = super::spread_param(p, "guide.deleteAll")?; - s.edit(|d, _| { + s.edit(|d, sel| { let sp = d.spread_mut(r).ok_or_else(|| bad("guide.deleteAll", "no such spread"))?; let mut n = 0; for pg in &mut sp.pages { n += pg.guides.len(); pg.guides.clear(); } + sel.guides.retain(|g| g.spread != r); Ok(json!({"deleted": n})) }) }), - cmd!(query "guide.list", "Guides", [], None, "{spread?} → [{page, index, orientation, position, spread}]", has_doc, |s, p| { - let d = &s.doc()?.doc; - let sp = d.spread(super::spread_param(p, "guide.list")?).ok_or_else(|| bad("guide.list", "no such spread"))?; - let mut out = Vec::new(); - for (pi, pg) in sp.pages.iter().enumerate() { - for (i, g) in pg.guides.iter().enumerate() { - out.push(json!({"page": pi, "index": i, "orientation": g.orientation, "position": g.position, "spread": g.spread})); + cmd!( + query "guide.list", + "Guides", + [], + None, + "{spread?} → [{page, index, orientation, position, spread, selected}]", + has_doc, + |s, p| { + let st = s.doc()?; + let r = super::spread_param(p, "guide.list")?; + let sp = st.doc.spread(r).ok_or_else(|| bad("guide.list", "no such spread"))?; + let picked: HashSet = st.selection.guides.iter().copied().collect(); + let mut out = Vec::new(); + for (pi, pg) in sp.pages.iter().enumerate() { + for (i, g) in pg.guides.iter().enumerate() { + let selected = picked.contains(&GuideSel { spread: r, page: pi, index: i }); + out.push(json!({"page": pi, "index": i, "orientation": g.orientation, "position": g.position, "spread": g.spread, "selected": selected})); + } } + Ok(Value::Array(out)) } - Ok(Value::Array(out)) + ), + cmd!( + noundo "guide.select", + "Select Guide", + [], + None, + "{spread?, page, index, guides?: [{spread?, page, index}] (several, in place of page and index), add?: bool (keep the guides already selected), toggle?: bool (deselect a selected guide instead: Shift-click)} — selects ruler guides and deselects objects → {selected: n}", + has_doc, + select + ), + cmd!( + noundo "guide.selectAll", + "Select All Guides", + ["Edit"], + Some("Cmd+Alt+G"), + "{spread?} — every guide on the spread that is not locked or on a locked or hidden layer → {selected: n}", + has_doc, + select_all + ), + cmd!(noundo "guide.deselect", "Deselect Guides", [], None, "{}", has_doc, |s, _| { + let st = s.doc_mut()?; + st.selection.guides.clear(); + st.bump_revision(); + super::ok() }), cmd!( "layout.createGuides", @@ -80,6 +143,14 @@ fn finite_number(p: &Value, key: &str, command: &str) -> Result> { Ok(Some(number)) } +/// `position` as a guide position: finite and within [`MAX_GUIDE_POSITION`] of the origin. +fn guide_position(position: f64, command: &str) -> Result { + if !position.is_finite() || position.abs() > MAX_GUIDE_POSITION { + return Err(bad(command, format!("a guide position must be between -{MAX_GUIDE_POSITION} and {MAX_GUIDE_POSITION}"))); + } + Ok(position) +} + fn orientation(p: &Value) -> Result { match str_param(p, "orientation") { Some("horizontal") => Ok(Orientation::Horizontal), @@ -115,6 +186,9 @@ fn add(s: &mut Session, p: &Value) -> Result { }; vec![(o, pos, x)] }; + for (_, pos, _) in &guides { + guide_position(*pos, "guide.add")?; + } let d = &s.doc()?.doc; let placed: Vec<(Orientation, f64, usize)> = guides .into_iter() @@ -128,11 +202,13 @@ fn add(s: &mut Session, p: &Value) -> Result { }) .collect(); let layer = s.doc()?.active_layer; - s.edit(|d, _| { + s.edit(|d, sel| { let sp = d.spread_mut(r).ok_or_else(|| bad("guide.add", "no such spread"))?; let mut out = Vec::new(); + let mut added = Vec::new(); for (o, pos, pi) in placed { let pg = sp.pages.get_mut(pi).ok_or_else(|| bad("guide.add", "no such page"))?; + let index = pg.guides.len(); pg.guides.push(Guide { orientation: o, position: pos, @@ -141,8 +217,11 @@ fn add(s: &mut Session, p: &Value) -> Result { layer: Some(layer), liquid: liquid && !spread_guide, }); - out.push(json!({"page": pi, "index": pg.guides.len() - 1})); + out.push(json!({"page": pi, "index": index})); + added.push(GuideSel { spread: r, page: pi, index }); } + // A new guide is selected, as in InDesign; nothing else stays selected. + *sel = Selection { guides: added, ..Default::default() }; match <[Value; 1]>::try_from(out) { Ok([one]) => Ok(one), Err(out) => Ok(json!({"guides": out})), @@ -168,6 +247,7 @@ fn check_editable(d: &Document, r: SpreadRef, pi: usize, i: usize, command: &str fn move_guide(s: &mut Session, p: &Value) -> Result { let (r, pi, i) = guide_ref(p, "guide.move")?; let pos = finite_number(p, "position", "guide.move")?.ok_or_else(|| bad("guide.move", "missing position"))?; + let pos = guide_position(pos, "guide.move")?; s.edit(|d, _| { check_editable(d, r, pi, i, "guide.move")?; let g = d @@ -181,18 +261,209 @@ fn move_guide(s: &mut Session, p: &Value) -> Result { } fn delete(s: &mut Session, p: &Value) -> Result { - let (r, pi, i) = guide_ref(p, "guide.delete")?; - s.edit(|d, _| { - check_editable(d, r, pi, i, "guide.delete")?; - let pg = d.spread_mut(r).and_then(|sp| sp.pages.get_mut(pi)).ok_or_else(|| bad("guide.delete", "no such page"))?; - if i >= pg.guides.len() { - return Err(bad("guide.delete", "no such guide")); + // An address names one guide: a partial one (only `spread`, say) is an error, not the selection. + let targets = if ["spread", "page", "index"].iter().all(|k| p.get(k).is_none()) { + s.doc()?.selection.guides.clone() + } else { + let (spread, page, index) = guide_ref(p, "guide.delete")?; + vec![GuideSel { spread, page, index }] + }; + if targets.is_empty() { + return Err(bad("guide.delete", "no guide selected")); + } + s.edit(|d, sel| { + for g in &targets { + check_editable(d, g.spread, g.page, g.index, "guide.delete")?; } - pg.guides.remove(i); - Ok(Value::Null) + let deleted = remove_guides(d, sel, &targets, "guide.delete")?; + Ok(json!({"deleted": deleted})) }) } +/// Removes `targets` (existing guides; repeats count once) and renumbers the guide selection to +/// match. Returns how many guides it removed. +fn remove_guides(d: &mut Document, sel: &mut Selection, targets: &[GuideSel], command: &str) -> Result { + let gone: HashSet = targets.iter().copied().collect(); + // Per page, the removed indices in ascending order. + let mut by_page: HashMap<(SpreadRef, usize), Vec> = HashMap::new(); + for g in &gone { + by_page.entry((g.spread, g.page)).or_default().push(g.index); + } + for ((spread, page), indices) in &mut by_page { + indices.sort_unstable(); + let pg = d.spread_mut(*spread).and_then(|sp| sp.pages.get_mut(*page)).ok_or_else(|| bad(command, "no such page"))?; + for &i in indices.iter().rev() { + if i >= pg.guides.len() { + return Err(bad(command, "no such guide")); + } + pg.guides.remove(i); + } + } + sel.guides = sel + .guides + .iter() + .filter(|g| !gone.contains(g)) + .map(|g| { + let below = by_page.get(&(g.spread, g.page)).map_or(0, |indices| indices.partition_point(|&i| i < g.index)); + GuideSel { index: g.index.saturating_sub(below), ..*g } + }) + .collect(); + Ok(gone.len()) +} + +/// The guides a `guides: [{spread?, page, index}]` list names, if the params have one. +fn guides_param(p: &Value, command: &str) -> Result>> { + let Some(list) = p.get("guides") else { return Ok(None) }; + let list = list.as_array().ok_or_else(|| bad(command, "`guides` must be a list of {spread?, page, index}"))?; + if list.len() > MAX_GUIDES_NAMED { + return Err(bad(command, format!("`guides` may name at most {MAX_GUIDES_NAMED} guides"))); + } + list.iter() + .map(|g| { + let (spread, page, index) = guide_ref(g, command)?; + Ok(GuideSel { spread, page, index }) + }) + .collect::>>() + .map(Some) +} + +/// The guide `g` addresses, if there is one. +fn guide_of(d: &Document, g: GuideSel) -> Option<&Guide> { + d.spread(g.spread)?.pages.get(g.page)?.guides.get(g.index) +} + +/// A guide that can be selected: it exists, and neither it nor its layer is locked or hidden. +pub(crate) fn selectable(d: &Document, g: GuideSel) -> bool { + guide_of(d, g).is_some_and(|guide| guide.editable_in(d)) +} + +fn select(s: &mut Session, p: &Value) -> Result { + let named = match guides_param(p, "guide.select")? { + Some(list) => list, + None => { + let (spread, page, index) = guide_ref(p, "guide.select")?; + vec![GuideSel { spread, page, index }] + } + }; + let (add, toggle) = (bool_or(p, "add", false), bool_or(p, "toggle", false)); + let st = s.doc_mut()?; + for g in &named { + check_editable(&st.doc, g.spread, g.page, g.index, "guide.select")?; + } + let mut guides = if add || toggle { st.selection.guides.clone() } else { Vec::new() }; + let mut have: HashSet = guides.iter().copied().collect(); + let mut seen = HashSet::new(); + let mut dropped = HashSet::new(); + for g in named.into_iter().filter(|g| seen.insert(*g)) { + if !have.insert(g) { + if toggle { + dropped.insert(g); + } + } else { + guides.push(g); + } + } + guides.retain(|g| !dropped.contains(g)); + let n = guides.len(); + st.selection = Selection { guides, ..Default::default() }; + st.bump_revision(); + Ok(json!({"selected": n})) +} + +fn select_all(s: &mut Session, p: &Value) -> Result { + let r = super::spread_param(p, "guide.selectAll")?; + let st = s.doc_mut()?; + let sp = st.doc.spread(r).ok_or_else(|| bad("guide.selectAll", "no such spread"))?; + let guides: Vec = sp + .pages + .iter() + .enumerate() + .flat_map(|(page, pg)| (0..pg.guides.len()).map(move |index| GuideSel { spread: r, page, index })) + .filter(|g| selectable(&st.doc, *g)) + .collect(); + let n = guides.len(); + st.selection = Selection { guides, ..Default::default() }; + st.bump_revision(); + Ok(json!({"selected": n})) +} + +fn move_by(s: &mut Session, p: &Value) -> Result { + let dx = finite_number(p, "dx", "guide.moveBy")?.unwrap_or(0.0); + let dy = finite_number(p, "dy", "guide.moveBy")?.unwrap_or(0.0); + let mut targets = match guides_param(p, "guide.moveBy")? { + Some(list) => list, + None => s.doc()?.selection.guides.clone(), + }; + let mut seen = HashSet::new(); + targets.retain(|g| seen.insert(*g)); + if targets.is_empty() { + return Err(bad("guide.moveBy", "no guide selected")); + } + s.edit(|d, _| { + for g in &targets { + check_editable(d, g.spread, g.page, g.index, "guide.moveBy")?; + } + for g in &targets { + let guide = d + .spread_mut(g.spread) + .and_then(|sp| sp.pages.get_mut(g.page)) + .and_then(|pg| pg.guides.get_mut(g.index)) + .ok_or_else(|| bad("guide.moveBy", "no such guide"))?; + let to = guide.position + + match guide.orientation { + Orientation::Vertical => dx, + Orientation::Horizontal => dy, + }; + guide.position = guide_position(to, "guide.moveBy").map_err(|_| bad("guide.moveBy", "the guide would move out of range"))?; + } + Ok(json!({"moved": targets.len()})) + }) +} + +/// After a command: guides stay selected only while nothing else is (objects, text, cells, a +/// page), and only those that are still there and can be selected. A command that changed +/// which guides a page holds without keeping the guide selection up to date clears it, since +/// its (page, index) addresses may name other guides now. `before` is the document and +/// selection before the command, when it ran on the same document. +pub(crate) fn keep_selection_valid(st: &mut DocState, before: Option<(&Document, &Selection)>, id: &str) { + let sel = &mut st.selection; + if sel.guides.is_empty() { + return; + } + if !sel.items.is_empty() || sel.text.is_some() || sel.cells.is_some() || sel.page.is_some() { + sel.guides.clear(); + return; + } + let kept_up = id.starts_with("guide.") || matches!(id, "edit.undo" | "edit.redo") || before.is_some_and(|(_, old)| old.guides != sel.guides); + if !kept_up + && let Some((old, _)) = before + && !std::ptr::eq(old, st.doc.as_ref()) + && !same_guide_addresses(old, &st.doc) + { + sel.guides.clear(); + return; + } + let mut seen = HashSet::new(); + sel.guides.retain(|g| selectable(&st.doc, *g) && seen.insert(*g)); +} + +/// Every (spread, page, index) of `old` still names a guide of the same orientation on the same +/// page in `new`: guides were only added at the end of their pages, or moved. +fn same_guide_addresses(old: &Document, new: &Document) -> bool { + let same = |a: &[std::sync::Arc], b: &[std::sync::Arc]| { + a.len() == b.len() + && a.iter().zip(b).all(|(a, b)| { + a.pages.len() == b.pages.len() + && a.pages.iter().zip(&b.pages).all(|(a, b)| { + a.id == b.id + && a.guides.len() <= b.guides.len() + && a.guides.iter().zip(&b.guides).all(|(a, b)| a.orientation == b.orientation) + }) + }) + }; + same(&old.spreads, &new.spreads) && same(&old.parents, &new.parents) +} + fn guide_divisions(p: &Value, key: &str) -> Result { let Some(value) = p.get(key) else { return Ok(0) }; let count = value.as_u64().ok_or_else(|| bad("layout.createGuides", format!("`{key}` must be an integer")))?; @@ -273,7 +544,11 @@ fn create_guides(s: &mut Session, p: &Value) -> Result { .filter(|count| *count <= MAX_GUIDES_CREATED) .ok_or_else(|| bad("layout.createGuides", format!("a single command may create at most {MAX_GUIDES_CREATED} guides")))?; let layer = s.doc()?.active_layer; - s.edit(|d, _| { + s.edit(|d, sel| { + if remove { + // The cleared pages' guide addresses name the new guides now. + sel.guides.retain(|g| g.spread != r || only.is_some_and(|o| o != g.page)); + } let sp = d.spread_mut(r).ok_or_else(|| bad("layout.createGuides", "no such spread"))?; let mut n = 0usize; for (pi, pg) in sp.pages.iter_mut().enumerate() { @@ -390,6 +665,214 @@ mod tests { } } +#[cfg(test)] +mod selection_tests { + use serde_json::{Value, json}; + + use crate::Session; + + /// A page with vertical guides at 100, 200, 300 and a horizontal one at 400. + fn guides() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + for x in [100.0, 200.0, 300.0] { + s.execute("guide.add", &json!({"orientation": "vertical", "position": x})).unwrap(); + } + s.execute("guide.add", &json!({"orientation": "horizontal", "position": 400.0})).unwrap(); + s + } + + fn selected(s: &Session) -> Vec { + s.doc().unwrap().selection.guides.iter().map(|g| g.index).collect() + } + + fn positions(s: &mut Session) -> Vec { + let l = s.execute("guide.list", &json!({})).unwrap(); + l.as_array().unwrap().iter().map(|g| g["position"].as_f64().unwrap()).collect() + } + + #[test] + fn selecting_guides_clears_objects_and_the_other_way_round() { + let mut s = guides(); + let id = s.execute("frame.create", &json!({"rect": [36, 36, 100, 100]})).unwrap()["id"].clone(); + s.execute("selection.set", &json!({"ids": [id]})).unwrap(); + s.execute("guide.select", &json!({"page": 0, "index": 1})).unwrap(); + assert!(s.doc().unwrap().selection.items.is_empty()); + assert_eq!(selected(&s), [1]); + // Shift-click adds, Shift-click again removes. + s.execute("guide.select", &json!({"page": 0, "index": 3, "toggle": true})).unwrap(); + assert_eq!(selected(&s), [1, 3]); + s.execute("guide.select", &json!({"page": 0, "index": 1, "toggle": true})).unwrap(); + assert_eq!(selected(&s), [3]); + let r = s.execute("guide.select", &json!({"guides": [{"page": 0, "index": 0}, {"page": 0, "index": 2}], "add": true})).unwrap(); + assert_eq!(r["selected"], 3); + let l = s.execute("guide.list", &json!({})).unwrap(); + assert_eq!(l.as_array().unwrap().iter().map(|g| g["selected"] == true).collect::>(), [true, false, true, true]); + // Selecting an object (Shift-click too) deselects the guides. + s.execute("selection.toggle", &json!({"id": id})).unwrap(); + assert!(selected(&s).is_empty()); + s.execute("guide.select", &json!({"page": 0, "index": 0})).unwrap(); + s.execute("edit.deselectAll", &json!({})).unwrap(); + assert!(selected(&s).is_empty()); + s.execute("guide.selectAll", &json!({})).unwrap(); + s.execute("guide.deselect", &json!({})).unwrap(); + assert!(selected(&s).is_empty()); + // No such guide. + assert!(s.execute("guide.select", &json!({"page": 0, "index": 9})).is_err()); + assert!(s.execute("guide.select", &json!({"page": 3, "index": 0})).is_err()); + assert!(s.execute("guide.select", &json!({"guides": "all"})).is_err()); + } + + #[test] + fn select_all_guides_skips_locked_ones() { + let mut s = guides(); + let layer = s.execute("layer.new", &json!({"name": "Grid"})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.activate", &json!({"id": layer})).unwrap(); + s.execute("guide.add", &json!({"orientation": "vertical", "position": 500.0})).unwrap(); + s.execute("layer.set", &json!({"id": layer, "locked": true})).unwrap(); + assert_eq!(s.execute("guide.selectAll", &json!({})).unwrap()["selected"], 4); + assert_eq!(selected(&s), [0, 1, 2, 3]); + assert!(s.execute("guide.select", &json!({"page": 0, "index": 4})).is_err()); + // Locking the layer of a selected guide deselects it. + s.execute("layer.set", &json!({"id": layer, "locked": false})).unwrap(); + s.execute("guide.selectAll", &json!({})).unwrap(); + s.execute("layer.set", &json!({"id": layer, "locked": true})).unwrap(); + assert_eq!(selected(&s), [0, 1, 2, 3]); + let spec = crate::cmd::find_command("guide.selectAll").unwrap(); + assert_eq!((spec.menu, spec.shortcut), (&["Edit"][..], Some("Cmd+Alt+G"))); + } + + #[test] + fn selected_guides_move_and_delete_as_one_undo_step() { + let mut s = guides(); + s.execute("guide.select", &json!({"guides": [{"page": 0, "index": 0}, {"page": 0, "index": 2}, {"page": 0, "index": 3}]})).unwrap(); + // Vertical guides move by dx, horizontal ones by dy. + s.execute("guide.moveBy", &json!({"dx": 10.0, "dy": -5.0})).unwrap(); + assert_eq!(positions(&mut s), [110.0, 200.0, 310.0, 395.0]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(positions(&mut s), [100.0, 200.0, 300.0, 400.0]); + assert_eq!(selected(&s), [0, 2, 3]); + // Delete (edit.clear, as the Delete key) takes all three; the guide left is the one at 200. + assert_eq!(s.execute("edit.clear", &json!({})).unwrap()["deleted"], 3); + assert_eq!(positions(&mut s), [200.0]); + assert!(selected(&s).is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(positions(&mut s), [100.0, 200.0, 300.0, 400.0]); + assert_eq!(selected(&s), [0, 2, 3]); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(positions(&mut s), [200.0]); + assert!(s.execute("guide.moveBy", &json!({"dx": 1.0})).is_err(), "nothing selected"); + // A guide stays within 1000000 pt of the origin. + assert!(s.execute("guide.moveBy", &json!({"dx": f64::MAX, "guides": [{"page": 0, "index": 0}]})).is_err()); + assert!(s.execute("guide.moveBy", &json!({"dx": 1e6, "guides": [{"page": 0, "index": 0}]})).is_err()); + assert_eq!(positions(&mut s), [200.0]); + s.execute("guide.moveBy", &json!({"dx": -1e6 - 200.0, "guides": [{"page": 0, "index": 0}]})).unwrap(); + assert_eq!(positions(&mut s), [-1e6]); + assert!(s.execute("guide.move", &json!({"page": 0, "index": 0, "position": 1e6 + 1.0})).is_err()); + assert!(s.execute("guide.add", &json!({"orientation": "vertical", "position": -2e6})).is_err()); + assert!(s.execute("guide.add", &json!({"orientation": "both", "point": [0.0, 1e300]})).is_err()); + assert_eq!(positions(&mut s), [-1e6]); + } + + #[test] + fn the_guide_selection_follows_deletes_and_drops_stale_guides() { + let mut s = guides(); + s.execute("guide.select", &json!({"guides": [{"page": 0, "index": 2}, {"page": 0, "index": 3}]})).unwrap(); + // Deleting a guide before them renumbers them. + s.execute("guide.delete", &json!({"page": 0, "index": 0})).unwrap(); + assert_eq!(selected(&s), [1, 2]); + assert_eq!(positions(&mut s), [200.0, 300.0, 400.0]); + // Deleting a selected one deselects it. + s.execute("guide.delete", &json!({"page": 0, "index": 1})).unwrap(); + assert_eq!(selected(&s), [1]); + // Undo puts back the selection that went with the document. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(selected(&s), [1, 2]); + // A new guide is the selection. + s.execute("guide.add", &json!({"orientation": "vertical", "position": 50.0})).unwrap(); + assert_eq!(selected(&s), [3]); + // Undoing the add to before the first delete: those addresses held other guides then. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(selected(&s), [2, 3]); + // Create Guides replacing the page's guides: their addresses name new guides, so the + // selection goes. + s.execute("layout.createGuides", &json!({"columns": 2, "removeExisting": true})).unwrap(); + assert!(selected(&s).is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("guide.select", &json!({"page": 0, "index": 0})).unwrap(); + s.execute("layout.createGuides", &json!({"columns": 2, "columnGutter": 0})).unwrap(); + assert_eq!(selected(&s), [0], "guides only added: the addresses still hold"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("guide.selectAll", &json!({})).unwrap(); + s.execute("guide.deleteAll", &json!({})).unwrap(); + assert!(selected(&s).is_empty()); + // Deleting the page goes with it. + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 2})).unwrap(); + s.execute("guide.add", &json!({"spread": 1, "orientation": "vertical", "position": 100.0})).unwrap(); + s.execute("guide.selectAll", &json!({"spread": 1})).unwrap(); + assert_eq!(selected(&s), [0]); + s.execute("layout.pages.delete", &json!({"pages": [1]})).unwrap(); + assert!(selected(&s).is_empty()); + let _: Value = s.execute("guide.list", &json!({})).unwrap(); + } +} + +#[cfg(test)] +mod new_guide_tests { + use designcraft_doc::GuideSel; + use serde_json::json; + + use crate::Session; + + fn selected(s: &Session) -> Vec { + s.doc().unwrap().selection.guides.clone() + } + + #[test] + fn a_new_guide_is_the_selection() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 2})).unwrap(); + let id = s.execute("frame.create", &json!({"rect": [36, 36, 100, 100]})).unwrap()["id"].clone(); + s.execute("selection.set", &json!({"ids": [id]})).unwrap(); + s.execute("guide.add", &json!({"orientation": "vertical", "position": 100.0})).unwrap(); + let spread = s.doc().unwrap().selection.guides[0].spread; + assert_eq!(selected(&s), [GuideSel { spread, page: 0, index: 0 }]); + assert!(s.doc().unwrap().selection.items.is_empty(), "objects are deselected"); + // Both ways (Cmd-drag from the ruler corner): the two new guides. + s.execute("guide.add", &json!({"orientation": "both", "point": [50.0, 60.0], "spreadGuide": true})).unwrap(); + assert_eq!(selected(&s), [GuideSel { spread, page: 0, index: 1 }, GuideSel { spread, page: 0, index: 2 }]); + // Undo gives back the selection from before. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(selected(&s), [GuideSel { spread, page: 0, index: 0 }]); + } + + #[test] + fn delete_takes_a_whole_address_or_the_selection() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 3})).unwrap(); + for spread in [0, 1] { + s.execute("guide.add", &json!({"spread": spread, "orientation": "vertical", "position": 100.0})).unwrap(); + } + s.execute("guide.select", &json!({"spread": 1, "page": 0, "index": 0})).unwrap(); + // A spread without page and index is not "the selection". + assert!(s.execute("guide.delete", &json!({"spread": 0})).is_err()); + assert!(s.execute("guide.delete", &json!({"spread": 1, "page": 0})).is_err()); + assert_eq!(selected(&s).len(), 1); + // A selection naming a guide twice, apart, deletes it once. + s.execute("guide.add", &json!({"spread": 1, "orientation": "vertical", "position": 200.0})).unwrap(); + s.execute("guide.add", &json!({"spread": 1, "orientation": "vertical", "position": 300.0})).unwrap(); + let spread = selected(&s)[0].spread; + let at = |index| GuideSel { spread, page: 0, index }; + s.doc_mut().unwrap().selection.guides = vec![at(0), at(2), at(0)]; + assert_eq!(s.execute("guide.delete", &json!({})).unwrap()["deleted"], 2); + let left = s.execute("guide.list", &json!({"spread": 1})).unwrap(); + assert_eq!(left.as_array().unwrap().iter().map(|g| g["position"].as_f64().unwrap()).collect::>(), [200.0]); + assert_eq!(s.execute("guide.list", &json!({"spread": 0})).unwrap().as_array().unwrap().len(), 1); + } +} + #[cfg(test)] mod layer_tests { use serde_json::json; diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 3b16b9cfc..a4d5413bb 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -20,7 +20,7 @@ pub(crate) mod find; pub use find::same_find_domain; pub(crate) mod flex; mod fonts; -mod guides; +pub(crate) mod guides; mod index; mod inspect; mod interactive; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 183b81c5c..d16dc9dd1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -571,6 +571,7 @@ impl Session { Ok(r) => r, Err(e) => { // What it did before it failed can be undone too. + self.keep_guide_selection_valid(before.as_ref(), id); self.record_undo_step(spec, before, nested); return Err(e); } @@ -613,6 +614,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(), params.clone())); @@ -621,6 +623,15 @@ impl Session { Ok(r) } + /// Drops selected guides the command `id` made stale, against the document as it will be + /// recorded: after the passes that run with the command (smart reflow, live captions, autosize). + fn keep_guide_selection_valid(&mut self, before: Option<&(u64, Arc, Selection)>, id: &str) { + if let Some(st) = self.active_mut() { + let old = before.filter(|(uid, _, _)| *uid == st.uid).map(|(_, d, sel)| (d.as_ref(), sel)); + cmd::guides::keep_selection_valid(st, old, id); + } + } + /// Record undo if the document changed (and we're not previewing an interaction), with the /// selection from before the command. A command run by an undoable one leaves the step to it: /// one command is one undo step. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9aacf469d..42f57b3a1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -294,8 +294,9 @@ fn cmd_move_does_not_snap() { fn cmd_resize_still_snaps_to_a_guide() { use designcraft_tools::{PointerEvent, PointerKind}; let mut s = session(); - s.execute("frame.create", &json!({"rect": [100.0, 100.0, 200.0, 180.0], "content": "unassigned"})).unwrap(); + // The new guide is selected: the frame created after it is the selection. s.execute("guide.add", &json!({"orientation": "vertical", "position": 250.0, "page": 0})).unwrap(); + s.execute("frame.create", &json!({"rect": [100.0, 100.0, 200.0, 180.0], "content": "unassigned"})).unwrap(); s.set_tool("selection"); let v = ViewInfo::at_zoom(1.0); let b0 = s.doc().unwrap().doc.spreads[0].items[0].bounds(); diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index a92f1c132..b5153e183 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -140,6 +140,9 @@ pub struct SnapView { pub smart_dimensions: bool, pub smart_spacing: bool, pub zone_px: f64, + /// View › Grids & Guides › Lock Guides: ruler guides can't be selected or moved. + #[serde(default)] + pub guides_locked: bool, } impl SnapView { @@ -153,6 +156,7 @@ impl SnapView { smart_dimensions: true, smart_spacing: true, zone_px: 4.0, + guides_locked: false, }; pub const OFF: Self = Self { snap_to_guides: false, @@ -164,6 +168,7 @@ impl SnapView { smart_dimensions: false, smart_spacing: false, zone_px: 4.0, + guides_locked: false, }; /// Guides, the document grid, or smart guides are on. diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 891f1d4ab..b3d3780f2 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -2,7 +2,8 @@ //! //! Click selects the frontmost item (Shift toggles), drag moves (Alt duplicates, Shift constrains), //! the 8 bounding-box handles resize (Shift keeps proportions, Alt from centre, Cmd scales content), -//! empty-canvas drags make a marquee, double-clicking a text frame switches to the Type tool and +//! empty-canvas drags make a marquee (it selects the ruler guides it crosses when it touches no +//! object), double-clicking a text frame switches to the Type tool and //! double-clicking a handle fits the frame to its content (corner: both sides, edge: that one). //! A click on a selected text frame's in or out port loads the text cursor (see [`crate::thread`]). //! @@ -179,6 +180,42 @@ fn spread_delta_to_canvas(xf: Affine, d: Vec2) -> Vec2 { (xf * Point::new(d.x, d.y)) - (xf * Point::ORIGIN) } +/// The ruler guides a marquee `r` (canvas) crosses that can be selected, as `guide.select` +/// takes them: none while guides are hidden or locked. +fn guides_crossing(cx: &ToolContext, r: Rect) -> Vec { + if !cx.snap.show_guides || cx.snap.guides_locked { + return vec![]; + } + let mut out = Vec::new(); + for slot in &cx.layout.slots { + let Some(sp) = cx.doc.spread(slot.spread) else { continue }; + let pasteboard = slot.xf.inverse().transform_rect_bbox(cx.layout.pasteboard); + for (pi, pg) in sp.pages.iter().enumerate() { + for (gi, g) in pg.guides.iter().enumerate() { + if !g.editable_in(cx.doc) { + continue; + } + // The line as the canvas draws it: a spread guide crosses the pasteboard (a + // vertical one the spread's height and a little), a page guide its page. + let span = match (g.spread, g.orientation) { + (false, _) => pg.bounds(), + (true, designcraft_doc::Orientation::Horizontal) => pasteboard, + (true, designcraft_doc::Orientation::Vertical) => sp.bounds().inflate(0.0, 36.0), + }; + let line = match g.orientation { + designcraft_doc::Orientation::Horizontal => Rect::new(span.x0, g.position, span.x1, g.position), + designcraft_doc::Orientation::Vertical => Rect::new(g.position, span.y0, g.position, span.y1), + }; + let b = slot.xf.transform_rect_bbox(line); + if b.x0 <= r.x1 && b.x1 >= r.x0 && b.y0 <= r.y1 && b.y1 >= r.y0 { + out.push(json!({"spread": slot.spread, "page": pi, "index": gi})); + } + } + } + } + out +} + pub struct SelectionTool { direct: bool, drag: Drag, @@ -1112,7 +1149,12 @@ impl Tool for SelectionTool { } } } - vec![Action::Exec("selection.set".into(), json!({"ids": ids, "add": ev.mods.shift}))] + let guides = if ids.is_empty() { guides_crossing(cx, r) } else { vec![] }; + if guides.is_empty() { + vec![Action::Exec("selection.set".into(), json!({"ids": ids, "add": ev.mods.shift}))] + } else { + vec![Action::Exec("guide.select".into(), json!({"guides": guides, "add": ev.mods.shift}))] + } } Drag::None | Drag::Place { .. } => vec![], } @@ -1133,7 +1175,20 @@ impl Tool for SelectionTool { } let mv = |dx: f64, dy: f64| vec![Action::Exec("transform.move".into(), json!({"dx": dx, "dy": dy, "copy": mods.alt}))]; if cx.selection.items.is_empty() { - return vec![]; + // Selected ruler guides: the arrows nudge them, Delete deletes them. + if cx.selection.guides.is_empty() { + return vec![]; + } + let nudge = |dx: f64, dy: f64| vec![Action::Exec("guide.moveBy".into(), json!({"dx": dx, "dy": dy}))]; + return match key { + ToolKey::Left => nudge(-inc, 0.0), + ToolKey::Right => nudge(inc, 0.0), + ToolKey::Up => nudge(0.0, -inc), + ToolKey::Down => nudge(0.0, inc), + ToolKey::Delete | ToolKey::Backspace => vec![Action::Exec("edit.clear".into(), json!({}))], + ToolKey::Escape => vec![Action::Exec("guide.deselect".into(), json!({}))], + _ => vec![], + }; } match key { ToolKey::Left => mv(-inc, 0.0), diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8d94f099f..322f75d80 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -2,7 +2,7 @@ //! selection, text ports and threads, the text caret, rulers, and pointer/keyboard input. use designcraft_compose as compose; -use designcraft_doc::{Content, Document, Item, SpreadRef}; +use designcraft_doc::{Content, Document, GuideSel, Item, SpreadRef}; use designcraft_engine::doc::Selection; use designcraft_geom::{Affine, Point, Rect as DRect, Vec2 as DVec2}; use designcraft_tools::{CanvasLayout, Cursor, Mods, Overlay, PointerEvent, PointerKind, SpreadSlot, ToolKey}; @@ -531,8 +531,11 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { painter.rect_stroke(xf.rect(slot.bounds), 0.0, Stroke::new(hair, Color32::from_rgb(0x4a, 0x4a, 0x4a)), StrokeKind::Outside); } if !preview { - draw_guides(app, &painter, &xf, &doc, &layout, &t); - if let Some(g) = ui.data(|d| d.get_temp::(egui::Id::new(GUIDE_DRAG))) + let drag = ui.data(|d| d.get_temp::(egui::Id::new(GUIDE_DRAG))); + let press = ui.data(|d| d.get_temp::(egui::Id::new(GUIDE_PRESS))); + let moving = drag.as_ref().zip(press).and_then(|(g, press)| moving_guides(app, &xf, rect, g, press)); + draw_guides(app, &painter, &xf, &doc, &layout, &t, moving.as_ref()); + if let Some(g) = drag && let Some(p) = g.at { let col = Color32::from_rgb(74, 227, 255); @@ -546,6 +549,15 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { } else { painter.line_segment([a, b], Stroke::new(1.0, col)); } + // Where it is, beside the pointer (#1282). + if let Some(text) = guide_readout(app, &xf, &g) { + let galley = painter.layout_no_wrap(text, egui::FontId::proportional(11.0), t.text); + let at = readout_at(p, galley.size(), rect); + let bg = Rect::from_min_size(at, galley.size()).expand(3.0); + painter.rect_filled(bg, 2.0, t.panel); + painter.rect_stroke(bg, 2.0, Stroke::new(1.0, t.border), StrokeKind::Inside); + painter.galley(at, galley, t.text); + } } draw_frames(app, &painter, &xf, &doc, &layout); if app.ui.hidden_characters { @@ -950,8 +962,11 @@ fn shown_area(app: &DesignApp, doc: &Document, xf: &Xf, slot: &SpreadSlot) -> Re boxes.iter().filter_map(|o| sp.outset_rect(*o)).map(|r| xf.rect(slot.xf.transform_rect_bbox(r))).fold(trim, |a, b| a.union(b)) } -fn draw_guides(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Document, layout: &CanvasLayout, t: &Tokens) { +/// `moving`: guides being dragged, drawn where they would be dropped instead of where they are. +fn draw_guides(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Document, layout: &CanvasLayout, t: &Tokens, moving: Option<&MovingGuides>) { let s = &doc.settings; + let selection: std::collections::HashSet = + app.session.active().map(|st| st.selection.guides.iter().copied().collect()).unwrap_or_default(); for slot in &layout.slots { let Some(sp) = doc.spread(slot.spread) else { continue }; // Everything below is in spread coordinates, placed through the slot (which may be turned). @@ -1007,8 +1022,21 @@ fn draw_guides(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Document } } } - // The page's own guides, then those it shows from its parent page. - for g in p.guides.iter().cloned().chain(doc.parent_guides(p)).filter(|g| g.visible_in(doc)) { + // The page's own guides, then those it shows from its parent page. Selected guides are + // drawn thicker, in their layer's color. + let own = p.guides.len(); + for (gi, mut g) in p.guides.iter().cloned().chain(doc.parent_guides(p)).enumerate().filter(|(_, g)| g.visible_in(doc)) { + let key = GuideSel { spread: slot.spread, page: pi, index: gi }; + let selected = gi < own && selection.contains(&key); + if gi < own + && let Some(m) = moving + && m.guides.contains(&key) + { + g.position += match g.orientation { + designcraft_doc::Orientation::Vertical => m.dx, + designcraft_doc::Orientation::Horizontal => m.dy, + }; + } // Spread guides cross the pasteboard; page guides their page. let span = if g.spread { pasteboard } else { pr }; let (a, bb) = match g.orientation { @@ -1018,7 +1046,12 @@ fn draw_guides(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Document (Point::new(g.position, span.y0), Point::new(g.position, span.y1)) } }; - let stroke = Stroke::new(hair(painter), Color32::from_rgb(74, 227, 255)); + let stroke = if selected { + let color = g.layer.and_then(|l| doc.layer(l)).map_or(Color32::from_rgb(79, 153, 255), |l| c32(l.color)); + Stroke::new(2.0, color) + } else { + Stroke::new(hair(painter), Color32::from_rgb(74, 227, 255)) + }; if g.liquid { // Liquid guides are dashed. painter.extend(egui::Shape::dashed_line(&[pt(a), pt(bb)], stroke, 6.0, 3.0)); @@ -2013,6 +2046,11 @@ fn draw_rulers(app: &DesignApp, ui: &egui::Ui, full: Rect, rect: Rect, xf: &Xf, /// coordinates: the ruler origin (one per page for a page origin) moved by zero point `zp`. fn ruler_pieces(app: &DesignApp, doc: &Document, layout: &CanvasLayout, zp: [f64; 2]) -> Vec<(f64, f64, Point)> { let Some(slot) = current_slot(app, layout).and_then(|i| layout.slots.get(i)) else { return Vec::new() }; + ruler_pieces_of(doc, slot, zp) +} + +/// [`ruler_pieces`] for the spread in `slot`. +fn ruler_pieces_of(doc: &Document, slot: &SpreadSlot, zp: [f64; 2]) -> Vec<(f64, f64, Point)> { let x = |v: f64, y: f64| if v.is_finite() { slot.to_canvas(Point::new(v, y)).x } else { v }; doc.ruler_pieces(slot.spread) .into_iter() @@ -2375,6 +2413,10 @@ fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, r if !space && !menu_open && xf.rot == 0 && zero_point_drag(app, ui, resp, rect, &xf) { return; } + // Hidden or locked guides can't stay selected. + if (!app.ui.guides || app.ui.guides_locked) && app.session.active().is_some_and(|st| !st.selection.guides.is_empty()) { + let _ = app.run("guide.deselect", json!({})); + } if !space && !menu_open && xf.rot == 0 && guide_drag(app, ui, resp, rect, &xf) { return; } @@ -2841,6 +2883,66 @@ struct GuideDrag { at: Option, } +const GUIDE_PRESS: &str = "canvas_guide_press"; + +/// A press on an existing guide: where it was (screen) and whether Shift was down. Released +/// where it was pressed, it is a click, which selects the guide. +#[derive(Clone, Copy, Debug)] +struct GuidePress { + origin: Pos2, + shift: bool, +} + +/// How far (screen pixels) the pointer may move between press and release for a click. +const GUIDE_CLICK_SLOP: f32 = 3.0; + +/// Where a dragged guide is, as the rulers measure it (#1282): `X: …` for a vertical guide, `Y: …` +/// for a horizontal one, from the zero point (and the page origin, when rulers restart per page) +/// in the document's ruler units. `None` with no document or rulers. +fn guide_readout(app: &DesignApp, xf: &Xf, g: &GuideDrag) -> Option { + let (label, value, unit) = guide_measure(app, xf, g)?; + Some(format!("{label}: {}", designcraft_geom::units::format_measure(value, unit))) +} + +/// Where a pointer readout of `size` goes for a pointer at `p`: below right of it, on the other +/// side where that would leave the canvas `area` (near its right or bottom edge), and kept inside +/// it (with the label's 3-point frame) however small the canvas is. +fn readout_at(p: Pos2, size: egui::Vec2, area: Rect) -> Pos2 { + const GAP: f32 = 12.0; + const PAD: f32 = 3.0; + let x = if p.x + GAP + size.x + PAD > area.max.x { p.x - GAP - size.x } else { p.x + GAP }; + let y = if p.y + GAP + size.y + PAD > area.max.y { p.y - GAP - size.y } else { p.y + GAP }; + let clamp = |v: f32, lo: f32, hi: f32| if hi < lo { lo } else { v.clamp(lo, hi) }; + pos2(clamp(x, area.min.x + PAD, area.max.x - PAD - size.x), clamp(y, area.min.y + PAD, area.max.y - PAD - size.y)) +} + +/// [`guide_readout`]'s parts: the axis label, the value (points) and its unit. +fn guide_measure(app: &DesignApp, xf: &Xf, g: &GuideDrag) -> Option<(&'static str, f64, designcraft_geom::Unit)> { + let p = g.at?; + let st = app.session.active()?; + let layout = CanvasLayout::new(&st.doc, st.editing_parents); + let c = xf.to_canvas(p); + // Measured on the spread under the pointer, which the guide is dropped on (`guide_drag`), + // as the rulers measure that spread: not the one in the middle of the view. + let slot = layout.spread_at(c).and_then(|(r, _)| layout.slot(r)).or_else(|| current_slot(app, &layout).and_then(|i| layout.slots.get(i)))?; + // An existing guide moves only on its own spread (`guide_drag`): over another, dropping it + // leaves it where it was, so there is no place to show. + if g.from.is_some_and(|(r, _, _)| r != slot.spread) { + return None; + } + let pieces = ruler_pieces_of(&st.doc, slot, st.doc.zero_point()); + let first = pieces.first()?; + let (label, value, unit) = match g.orientation { + designcraft_doc::Orientation::Vertical => { + // The horizontal ruler restarts at each page: the piece under the guide measures it. + let o = pieces.iter().find(|(from, to, _)| *from <= c.x && c.x < *to).unwrap_or(first).2; + ("X", c.x - o.x, st.doc.settings.horizontal_units) + } + designcraft_doc::Orientation::Horizontal => ("Y", c.y - first.2.y, st.doc.settings.vertical_units), + }; + value.is_finite().then_some((label, value, unit)) +} + /// The guide under a screen point (within 3 px), as (spread, page, index, orientation). fn guide_at(app: &DesignApp, xf: &Xf, p: Pos2) -> Option<(designcraft_doc::SpreadRef, usize, usize, designcraft_doc::Orientation)> { let st = app.session.active()?; @@ -2870,8 +2972,10 @@ fn guide_at(app: &DesignApp, xf: &Xf, p: Pos2) -> Option<(designcraft_doc::Sprea None } -/// Ruler guides: drag one out of a ruler, drag an existing one (Selection tools, not over an -/// object) to move it, drop it back on a ruler to delete it. Returns true while it owns the pointer. +/// Ruler guides: drag one out of a ruler, drag an existing one (Selection tools) to move it, drop +/// it back on a ruler to delete it. A press near an unlocked guide takes it even over an object: +/// the guide is selected and the object is not. Returns true from the press to the release, so +/// the tools never see that press. fn guide_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rect: Rect, xf: &Xf) -> bool { let id = egui::Id::new(GUIDE_DRAG); let (pressed, released, origin, latest) = @@ -2896,17 +3000,14 @@ fn guide_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rec && matches!(app.session.tool_id(), "selection" | "directSelection") && let Some((r, pi, gi, orientation)) = guide_at(app, xf, o) { - // Objects take precedence over the guides behind them. - let over_item = app.session.active().is_some_and(|st| { - let layout = CanvasLayout::new(&st.doc, st.editing_parents); - layout.spread_at(xf.to_canvas(o)).is_some_and(|(sr, p)| match sr { - designcraft_doc::SpreadRef::Doc(si) => st.doc.hit_item(si, p, 3.0 / xf.zoom).is_some(), - _ => false, - }) - }); - if !over_item { - drag = Some(GuideDrag { orientation, from: Some((r, pi, gi)), at: Some(o) }); + let shift = ui.input(|i| i.modifiers.shift); + // A press on a guide selects it (Shift: on release, as a click adds or removes it). + let selected = app.session.active().is_some_and(|st| st.selection.guides.contains(&GuideSel { spread: r, page: pi, index: gi })); + if !shift && !selected { + let _ = app.run("guide.select", json!({"spread": r, "page": pi, "index": gi})); } + ui.data_mut(|d| d.insert_temp(egui::Id::new(GUIDE_PRESS), GuidePress { origin: o, shift })); + drag = Some(GuideDrag { orientation, from: Some((r, pi, gi)), at: Some(o) }); } } let Some(mut g) = drag else { return false }; @@ -2922,7 +3023,23 @@ fn guide_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rec return true; } ui.data_mut(|d| d.remove::(id)); + let press: Option = ui.data_mut(|d| { + let press = d.get_temp(egui::Id::new(GUIDE_PRESS)); + d.remove::(egui::Id::new(GUIDE_PRESS)); + press + }); let Some(p) = g.at else { return true }; + if let (Some((r, pi, gi)), Some(press)) = (g.from, press) + && (p - press.origin).length() <= GUIDE_CLICK_SLOP + { + // A click: the guide is selected (at the press); Shift adds it or removes it. + if press.shift { + let _ = app.run("guide.select", json!({"spread": r, "page": pi, "index": gi, "toggle": true})); + } + return true; + } + // Dragging one of several selected guides moves (or deletes) them all. + let group = g.from.is_some_and(|(spread, page, index)| drags_group(app, GuideSel { spread, page, index })); let on_canvas = rect.contains(p); let target = app.session.active().and_then(|st| { let layout = CanvasLayout::new(&st.doc, st.editing_parents); @@ -2941,9 +3058,17 @@ fn guide_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rec }; match (g.from, on_canvas, target) { // Dropped back on a ruler: delete. + (Some(_), false, _) if group => { + let _ = app.run("guide.delete", json!({})); + } (Some((r, pi, gi)), false, _) => { let _ = app.run("guide.delete", json!({"spread": r, "page": pi, "index": gi})); } + (Some((r, _, _)), true, Some((tr, _, _))) if tr == r && group => { + if let Some((dx, dy)) = press.and_then(|press| guide_drag_delta(app, xf, &g, press.origin, p)) { + let _ = app.run("guide.moveBy", json!({"dx": dx, "dy": dy})); + } + } (Some((r, pi, gi)), true, Some((tr, sp, _))) if tr == r => { let _ = app.run("guide.move", json!({"spread": r, "page": pi, "index": gi, "position": pos_of(sp)})); } @@ -2962,6 +3087,55 @@ fn guide_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rec true } +/// Whether dragging guide `from` takes the other selected guides along: it is one of several +/// selected. +fn drags_group(app: &DesignApp, from: GuideSel) -> bool { + app.session.active().is_some_and(|st| st.selection.guides.len() > 1 && st.selection.guides.contains(&from)) +} + +/// How far a drag of the existing guide `g.from`, pressed at `origin` and now at `p` (screen), +/// moves guides, in spread coordinates: the dragged guide goes to the pointer, the other selected +/// guides as far along their own axis as the pointer moved. `None` while the pointer is not over +/// the guide's own spread, where a drop leaves it in place. +fn guide_drag_delta(app: &DesignApp, xf: &Xf, g: &GuideDrag, origin: Pos2, p: Pos2) -> Option<(f64, f64)> { + let (r, pi, gi) = g.from?; + let st = app.session.active()?; + let layout = CanvasLayout::new(&st.doc, st.editing_parents); + let (tr, sp) = layout.spread_at(xf.to_canvas(p))?; + if tr != r { + return None; + } + let start = layout.slot(r)?.to_spread(xf.to_canvas(origin)); + let at = st.doc.spread(r)?.pages.get(pi)?.guides.get(gi)?.position; + let (dx, dy) = match g.orientation { + designcraft_doc::Orientation::Vertical => (sp.x - at, sp.y - start.y), + designcraft_doc::Orientation::Horizontal => (sp.x - start.x, sp.y - at), + }; + (dx.is_finite() && dy.is_finite()).then_some((dx, dy)) +} + +/// Guides being dragged on the canvas and how far they have moved (spread coordinates). +struct MovingGuides { + guides: std::collections::HashSet, + dx: f64, + dy: f64, +} + +/// What a drag of an existing guide moves, for the preview: the dragged guide, or every selected +/// guide when it is one of several selected. `None` before the drag leaves the click distance, +/// over a ruler (a drop there deletes) and off the guide's spread. +fn moving_guides(app: &DesignApp, xf: &Xf, rect: Rect, g: &GuideDrag, press: GuidePress) -> Option { + let (spread, page, index) = g.from?; + let p = g.at?; + if !rect.contains(p) || (p - press.origin).length() <= GUIDE_CLICK_SLOP { + return None; + } + let (dx, dy) = guide_drag_delta(app, xf, g, press.origin, p)?; + let from = GuideSel { spread, page, index }; + let guides = if drags_group(app, from) { app.session.active()?.selection.guides.iter().copied().collect() } else { [from].into_iter().collect() }; + Some(MovingGuides { guides, dx, dy }) +} + /// Presses in a row on the canvas: the last press's count, and where and when it was released /// (`at` is −∞ while the button is down). #[derive(Clone, Copy, Debug)] @@ -2991,6 +3165,10 @@ fn release_clicks(press: Clicks, pos: Pos2, now: f64, dist: f32) -> Clicks { #[path = "parent_canvas_tests.rs"] mod parent_canvas_tests; +#[cfg(test)] +#[path = "guide_selection_tests.rs"] +mod guide_selection_tests; + #[cfg(test)] mod tests { use designcraft_geom::Unit; @@ -4033,6 +4211,105 @@ mod tests { assert_eq!(doc.settings.zero_point, [0.0, 0.0], "the zero point stays"); } + /// A guide being dragged out of a ruler says where it is, as the rulers measure it (#1282): + /// from the zero point, in the ruler units, and the label follows the pointer while it moves. + #[test] + fn a_dragged_guide_shows_where_it_is() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("view.zeroPoint", json!({"at": [100, 50]})).unwrap(); + let mut h = harness(app); + let rect = h.state().canvas_rect.unwrap(); + let dest = rect.min + vec2(160.0, 110.0); + let (xf, at) = { + let app = h.state(); + let xf = Xf::new(rect, app.view().unwrap()); + let st = app.session.active().unwrap(); + (xf, CanvasLayout::new(&st.doc, false).spread_at(xf.to_canvas(dest)).unwrap().1) + }; + let units = h.state().session.doc().unwrap().doc.settings.horizontal_units; + for (orientation, label, want) in + [(designcraft_doc::Orientation::Vertical, "X", at.x - 100.0), (designcraft_doc::Orientation::Horizontal, "Y", at.y - 50.0)] + { + let g = GuideDrag { orientation, from: None, at: Some(dest) }; + let (l, v, _) = guide_measure(h.state(), &xf, &g).unwrap(); + assert_eq!(l, label); + assert!((v - want).abs() < 1e-6, "{label}: {v} vs {want}"); + let text = guide_readout(h.state(), &xf, &g).unwrap(); + assert_eq!(text, format!("{label}: {}", designcraft_geom::units::format_measure(v, units))); + } + // While a guide is actually being dragged out of the top ruler, the readout is there. + let ruler = pos2(rect.min.x + 200.0, rect.min.y - RULER / 2.0); + h.hover_at(ruler); + h.step(); + primary(&mut h, ruler, true); + h.event(egui::Event::PointerMoved(dest)); + h.run_steps(2); + let g = h.ctx.data(|d| d.get_temp::(egui::Id::new(GUIDE_DRAG))).expect("dragging"); + assert_eq!(g.orientation, designcraft_doc::Orientation::Horizontal); + assert!(guide_readout(h.state(), &xf, &g).is_some_and(|t| t.starts_with("Y: "))); + primary(&mut h, dest, false); + } + + /// Over a spread other than the one in the middle of the view, the readout measures that + /// spread, the one the guide is dropped on: it reads the position the guide gets. + #[test] + fn the_guide_readout_measures_the_spread_under_the_pointer() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 5})).unwrap(); + app.run("view.zeroPoint", json!({"at": [100, 50]})).unwrap(); + let h = harness(app); + let rect = h.state().canvas_rect.unwrap(); + let xf = Xf::new(rect, h.state().view().unwrap()); + let st = h.state().session.active().unwrap(); + let layout = CanvasLayout::new(&st.doc, false); + let current = current_slot(h.state(), &layout).unwrap(); + // A point inside the last spread, well away from the one in view. + let last = layout.slots.last().unwrap(); + assert_ne!(layout.slots.iter().position(|s| s.spread == last.spread), Some(current), "the last spread isn't the one in view"); + let inside = Point::new(last.bounds.center().x, last.bounds.y0 + (last.bounds.y1 - last.bounds.y0) * 0.3); + let (r, sp) = layout.spread_at(inside).unwrap(); + assert_eq!(r, last.spread); + let g = GuideDrag { orientation: designcraft_doc::Orientation::Horizontal, from: None, at: Some(xf.to_screen(inside)) }; + let (label, v, _) = guide_measure(h.state(), &xf, &g).unwrap(); + assert_eq!(label, "Y"); + // The guide would be stored at `sp.y` on that spread, which its ruler reads from the zero point. + // (To screen and back in f32: a few hundred-thousandths of a point.) + assert!((v - (sp.y - 50.0)).abs() < 1e-3, "{v} vs {}", sp.y - 50.0); + // An existing guide of another spread can't be dropped there (it only moves on its own + // spread): no readout over this one, a readout over its own. + let first = layout.slots[current].spread; + let moving = GuideDrag { orientation: designcraft_doc::Orientation::Horizontal, from: Some((first, 0, 0)), at: Some(xf.to_screen(inside)) }; + assert!(guide_measure(h.state(), &xf, &moving).is_none(), "an existing guide over another spread"); + let own = layout.slots[current].bounds; + let over_own = Point::new(own.center().x, own.y0 + (own.y1 - own.y0) * 0.3); + let moving_here = GuideDrag { at: Some(xf.to_screen(over_own)), ..moving }; + assert!(guide_measure(h.state(), &xf, &moving_here).is_some(), "over its own spread"); + } + + /// The guide readout stays on the canvas: below right of the pointer in the open, flipped + /// left or up near the right or bottom edge, and inside the canvas in every corner. + #[test] + fn the_guide_readout_stays_inside_the_canvas() { + let area = Rect::from_min_max(pos2(50.0, 40.0), pos2(850.0, 640.0)); + let size = vec2(80.0, 14.0); + let inside = |at: Pos2| { + let r = Rect::from_min_size(at, size).expand(3.0); + r.min.x >= area.min.x - 1e-3 && r.min.y >= area.min.y - 1e-3 && r.max.x <= area.max.x + 1e-3 && r.max.y <= area.max.y + 1e-3 + }; + assert_eq!(readout_at(pos2(400.0, 300.0), size, area), pos2(412.0, 312.0), "in the open: below right"); + let right = readout_at(pos2(845.0, 300.0), size, area); + assert!(right.x + size.x < 845.0 && inside(right), "near the right edge: left of the pointer, {right:?}"); + let bottom = readout_at(pos2(400.0, 636.0), size, area); + assert!(bottom.y + size.y < 636.0 && inside(bottom), "near the bottom: above it, {bottom:?}"); + for p in [area.min, pos2(area.max.x, area.min.y), area.max, pos2(area.min.x, area.max.y), pos2(-500.0, 2000.0)] { + assert!(inside(readout_at(p, size, area)), "{p:?}"); + } + // A canvas narrower than the label: pinned to its top left, not past it. + let tiny = Rect::from_min_max(pos2(0.0, 0.0), pos2(40.0, 10.0)); + assert_eq!(readout_at(pos2(20.0, 5.0), size, tiny), pos2(3.0, 3.0)); + } + #[test] fn rulers_and_xy_fields_measure_from_the_zero_point_on_every_spread() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/guide_selection_tests.rs b/crates/ui-egui/src/guide_selection_tests.rs new file mode 100644 index 000000000..23ad14c91 --- /dev/null +++ b/crates/ui-egui/src/guide_selection_tests.rs @@ -0,0 +1,258 @@ +//! Ruler guides selected like objects (#1282): click, Shift-click, marquee, drag, keys, and the +//! X/Y fields. + +use egui::{Event, Modifiers, PointerButton}; +use egui_kittest::Harness; + +use super::*; + +fn harness(app: DesignApp) -> Harness<'static, DesignApp> { + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + h +} + +/// A page with vertical guides at x 200 and 300 and a horizontal one at y 400. +fn with_guides() -> Harness<'static, DesignApp> { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + for (orientation, position) in [("vertical", 200.0), ("vertical", 300.0), ("horizontal", 400.0)] { + app.run("guide.add", json!({"orientation": orientation, "position": position})).unwrap(); + } + harness(app) +} + +/// Screen position of spread 0's point (x, y). +fn screen_of(h: &Harness<'_, DesignApp>, x: f64, y: f64) -> Pos2 { + let app = h.state(); + let st = app.session.active().unwrap(); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + xf.to_screen(CanvasLayout::new(&st.doc, st.editing_parents).xf(SpreadRef::Doc(0)) * Point::new(x, y)) +} + +fn press(h: &mut Harness<'_, DesignApp>, pos: Pos2, pressed: bool, mods: Modifiers) { + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: mods }); + h.run_steps(2); +} + +fn click(h: &mut Harness<'_, DesignApp>, pos: Pos2, mods: Modifiers) { + h.event(Event::ModifiersChanged(mods)); + h.hover_at(pos); + h.step(); + press(h, pos, true, mods); + press(h, pos, false, mods); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); +} + +fn drag(h: &mut Harness<'_, DesignApp>, a: Pos2, b: Pos2) { + h.hover_at(a); + h.step(); + press(h, a, true, Modifiers::NONE); + for k in 1..=4 { + h.hover_at(a + (b - a) * (k as f32 / 4.0)); + h.step(); + } + press(h, b, false, Modifiers::NONE); + h.run_steps(2); +} + +fn selected(h: &Harness<'_, DesignApp>) -> Vec { + h.state().session.doc().unwrap().selection.guides.iter().map(|g| g.index).collect() +} + +fn positions(h: &Harness<'_, DesignApp>) -> Vec { + h.state().session.doc().unwrap().doc.spreads[0].pages[0].guides.iter().map(|g| g.position).collect() +} + +#[test] +fn clicking_guides_selects_them_and_shift_click_adds_or_removes() { + let mut h = with_guides(); + let id = h.state_mut().run("frame.create", json!({"rect": [400, 100, 500, 200]})).unwrap()["id"].as_u64().unwrap(); + h.state_mut().run("selection.set", json!({"ids": [id]})).unwrap(); + let at = screen_of(&h, 200.0, 600.0); + click(&mut h, at, Modifiers::NONE); + assert_eq!(selected(&h), [0]); + assert!(h.state().session.doc().unwrap().selection.items.is_empty(), "the object is deselected"); + assert_eq!(positions(&h), [200.0, 300.0, 400.0], "a click doesn't move the guide"); + let at = screen_of(&h, 100.0, 400.0); + click(&mut h, at, Modifiers::SHIFT); + assert_eq!(selected(&h), [0, 2]); + let at = screen_of(&h, 200.0, 650.0); + click(&mut h, at, Modifiers::SHIFT); + assert_eq!(selected(&h), [2]); + // A click on empty canvas, or on an object, clears the guide selection. + let at = screen_of(&h, 550.0, 650.0); + click(&mut h, at, Modifiers::NONE); + assert!(selected(&h).is_empty()); + let at = screen_of(&h, 300.0, 600.0); + click(&mut h, at, Modifiers::NONE); + assert_eq!(selected(&h), [1]); + let at = screen_of(&h, 450.0, 150.0); + click(&mut h, at, Modifiers::NONE); + assert!(selected(&h).is_empty()); + assert_eq!(h.state().session.doc().unwrap().selection.items, [designcraft_doc::ItemId(id)]); + // With View › Lock Guides on, guides can't be selected, and selected ones are deselected. + h.state_mut().run("guide.selectAll", json!({})).unwrap(); + h.state_mut().ui.guides_locked = true; + h.run_steps(2); + assert!(selected(&h).is_empty()); + let at = screen_of(&h, 200.0, 600.0); + click(&mut h, at, Modifiers::NONE); + assert!(selected(&h).is_empty()); +} + +#[test] +fn dragging_a_selected_guide_moves_all_selected_guides_as_one_step() { + let mut h = with_guides(); + h.state_mut().run("guide.select", json!({"guides": [{"page": 0, "index": 0}, {"page": 0, "index": 2}]})).unwrap(); + let undo = h.state().session.doc().unwrap().history.undo.len(); + let (a, b) = (screen_of(&h, 200.0, 600.0), screen_of(&h, 250.0, 620.0)); + drag(&mut h, a, b); + let p = positions(&h); + assert!((p[0] - 250.0).abs() < 1.0 && p[1] == 300.0 && (p[2] - 420.0).abs() < 1.0, "{p:?}"); + assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!(selected(&h), [0, 2]); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(positions(&h), [200.0, 300.0, 400.0]); + // Dragging an unselected guide selects it and moves only it. + let (a, b) = (screen_of(&h, 300.0, 600.0), screen_of(&h, 350.0, 600.0)); + drag(&mut h, a, b); + assert_eq!(selected(&h), [1]); + let p = positions(&h); + assert!(p[0] == 200.0 && (p[1] - 350.0).abs() < 1.0 && p[2] == 400.0, "{p:?}"); +} + +#[test] +fn a_marquee_selects_guides_only_when_it_touches_no_object() { + let mut h = with_guides(); + // Across both vertical guides, below the horizontal one, on empty page. + let (a, b) = (screen_of(&h, 150.0, 500.0), screen_of(&h, 350.0, 550.0)); + drag(&mut h, a, b); + assert_eq!(selected(&h), [0, 1]); + let id = h.state_mut().run("frame.create", json!({"rect": [220, 520, 260, 540]})).unwrap()["id"].as_u64().unwrap(); + h.state_mut().run("edit.deselectAll", json!({})).unwrap(); + let (a, b) = (screen_of(&h, 150.0, 500.0), screen_of(&h, 350.0, 550.0)); + drag(&mut h, a, b); + assert!(selected(&h).is_empty()); + assert_eq!(h.state().session.doc().unwrap().selection.items, [designcraft_doc::ItemId(id)]); +} + +#[test] +fn keys_nudge_and_delete_selected_guides() { + let mut h = with_guides(); + h.state_mut().run("guide.select", json!({"guides": [{"page": 0, "index": 1}, {"page": 0, "index": 2}]})).unwrap(); + let inc = h.state().session.doc().unwrap().doc.settings.keyboard_increment; + let vi = h.state().view_info(); + let key = |h: &mut Harness<'_, DesignApp>, k: ToolKey, shift: bool| { + let m = Mods { shift, alt: false, cmd: false, ctrl: false, space: false }; + assert!(h.state_mut().session.tool_key(k, m, vi).unwrap()); + }; + key(&mut h, ToolKey::Right, false); + key(&mut h, ToolKey::Down, true); + assert_eq!(positions(&h), [200.0, 300.0 + inc, 400.0 + 10.0 * inc]); + key(&mut h, ToolKey::Delete, false); + assert_eq!(positions(&h), [200.0]); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(positions(&h).len(), 3); + assert_eq!(selected(&h), [1, 2]); + key(&mut h, ToolKey::Escape, false); + assert!(selected(&h).is_empty()); +} + +#[test] +fn the_guide_field_measures_from_the_zero_point() { + let mut h = with_guides(); + h.state_mut().run("view.zeroPoint", json!({"at": [100, 50]})).unwrap(); + h.state_mut().run("guide.select", json!({"page": 0, "index": 0})).unwrap(); + let f = crate::panels::guide_field(h.state()).unwrap(); + assert_eq!((f.row(), f.value), (0, 100.0)); + h.state_mut().run("guide.move", f.move_to(36.0)).unwrap(); + assert_eq!(positions(&h)[0], 136.0); + h.state_mut().run("guide.select", json!({"page": 0, "index": 2})).unwrap(); + let f = crate::panels::guide_field(h.state()).unwrap(); + assert_eq!((f.row(), f.value), (1, 350.0)); + // Several guides: no field value. + h.state_mut().run("guide.selectAll", json!({})).unwrap(); + assert!(crate::panels::guide_field(h.state()).is_none()); +} + +#[test] +fn select_all_guides_is_in_the_edit_menu_on_the_spread_in_view() { + let mut h = with_guides(); + assert_eq!(crate::menus::default_shortcut("guide.selectAll"), Some("Cmd+Alt+G")); + crate::menus::activate(h.state_mut(), "guide.selectAll", &serde_json::Value::Null); + assert_eq!(selected(&h), [0, 1, 2]); + assert_eq!(crate::i18n::tr("de", "Select All Guides"), "Alle Hilfslinien auswählen"); + for (code, _) in crate::i18n::LANGUAGES.iter().filter(|(c, _)| !c.is_empty()) { + assert_ne!(crate::i18n::tr(code, "Select All Guides"), "Select All Guides", "{code}"); + assert_ne!(crate::i18n::tr(code, "Ruler Guide"), "Ruler Guide", "{code}"); + } + h.state_mut().ui.guides = false; + assert!(!crate::menus::menu_enabled(h.state(), "guide.selectAll")); +} + +#[test] +fn a_guide_over_a_frame_takes_the_click() { + let mut h = with_guides(); + h.state_mut().run("guide.deselect", json!({})).unwrap(); + // The vertical guide at x 200 crosses the frame. + let id = h.state_mut().run("frame.create", json!({"rect": [150, 500, 260, 560]})).unwrap()["id"].as_u64().unwrap(); + h.state_mut().run("edit.deselectAll", json!({})).unwrap(); + let bounds = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.spreads[0].items[0].bounds(); + let before = bounds(&h); + let at = screen_of(&h, 200.0, 530.0); + click(&mut h, at, Modifiers::NONE); + assert_eq!(selected(&h), [0]); + assert!(h.state().session.doc().unwrap().selection.items.is_empty(), "the frame is not selected"); + // Dragging it there moves the guide, not the frame. + let (a, b) = (screen_of(&h, 200.0, 530.0), screen_of(&h, 230.0, 530.0)); + drag(&mut h, a, b); + assert!((positions(&h)[0] - 230.0).abs() < 1.0, "{:?}", positions(&h)); + assert_eq!(bounds(&h), before); + assert!(h.state().session.doc().unwrap().selection.items.is_empty()); + // Away from the guide, a click inside the frame selects it. + let at = screen_of(&h, 160.0, 530.0); + click(&mut h, at, Modifiers::NONE); + assert_eq!(h.state().session.doc().unwrap().selection.items, [designcraft_doc::ItemId(id)]); + assert!(selected(&h).is_empty()); +} + +#[test] +fn a_guide_dragged_out_of_a_ruler_is_the_selection() { + let mut h = with_guides(); + h.state_mut().run("guide.select", json!({"page": 0, "index": 0})).unwrap(); + let rect = h.state().canvas_rect.unwrap(); + let ruler = pos2(rect.min.x + 200.0, rect.min.y - RULER / 2.0); + let dest = screen_of(&h, 250.0, 500.0); + drag(&mut h, ruler, dest); + let p = positions(&h); + assert!(p.len() == 4 && (p[3] - 500.0).abs() < 1.0, "{p:?}"); + assert_eq!(selected(&h), [3]); +} + +#[test] +fn dragging_one_of_several_selected_guides_previews_them_all() { + let mut h = with_guides(); + h.state_mut().run("guide.select", json!({"guides": [{"page": 0, "index": 0}, {"page": 0, "index": 2}]})).unwrap(); + let (a, b) = (screen_of(&h, 200.0, 600.0), screen_of(&h, 250.0, 620.0)); + let g = GuideDrag { orientation: designcraft_doc::Orientation::Vertical, from: Some((SpreadRef::Doc(0), 0, 0)), at: Some(b) }; + let press = GuidePress { origin: a, shift: false }; + let app = h.state(); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let m = moving_guides(app, &xf, app.canvas_rect.unwrap(), &g, press).expect("moving"); + assert!((m.dx - 50.0).abs() < 1.0 && (m.dy - 20.0).abs() < 1.0, "{} {}", m.dx, m.dy); + let mut moved: Vec = m.guides.iter().map(|g| g.index).collect(); + moved.sort_unstable(); + assert_eq!(moved, [0, 2]); + // The drop moves them by the same amounts. + let (dx, dy) = guide_drag_delta(app, &xf, &g, a, b).unwrap(); + assert_eq!((dx, dy), (m.dx, m.dy)); +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index c2abdb9a9..91c6db7de 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -318,6 +318,11 @@ const TABLE: &[(&str, [&str; 5])] = &[ ("Duplicate", ["Duplizieren", "Dupliquer", "Duplicar", "複製", "重复"]), ("Select All", ["Alles auswählen", "Tout sélectionner", "Seleccionar todo", "すべてを選択", "全选"]), ("Deselect All", ["Auswahl aufheben", "Tout désélectionner", "Deseleccionar todo", "すべての選択を解除", "取消全选"]), + ( + "Select All Guides", + ["Alle Hilfslinien auswählen", "Sélectionner tous les repères", "Seleccionar todas las guías", "すべてのガイドを選択", "选择所有参考线"], + ), + ("Ruler Guide", ["Hilfslinie", "Repère de règle", "Guía de regla", "定規ガイド", "标尺参考线"]), ("Find/Change…", ["Suchen/Ersetzen …", "Rechercher/Remplacer…", "Buscar/Cambiar…", "検索と置換…", "查找/更改…"]), ("Check Spelling…", ["Rechtschreibprüfung …", "Vérifier l'orthographe…", "Revisar ortografía…", "スペルチェック…", "拼写检查…"]), ("Preferences…", ["Voreinstellungen …", "Préférences…", "Preferencias…", "環境設定…", "首选项…"]), diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index b050de38b..11a01c1cc 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -147,6 +147,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Duplicate", "تكرار"), ("Select All", "تحديد الكل"), ("Deselect All", "إلغاء تحديد الكل"), + ("Select All Guides", "تحديد كل الأدلة"), + ("Ruler Guide", "دليل المسطرة"), ("Find/Change…", "البحث/التغيير…"), ("Find/Change", "البحث/التغيير"), ("Check Spelling…", "تدقيق إملائي…"), diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index e77e72a1c..b295e5e5b 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -37,6 +37,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Duplicate", "Duplikovat"), ("Select All", "Vybrat vše"), ("Deselect All", "Zrušit výběr"), + ("Select All Guides", "Vybrat všechna vodítka"), + ("Ruler Guide", "Vodítko pravítka"), ("Find/Change…", "Najít/Změnit…"), ("Check Spelling…", "Zkontrolovat pravopis…"), ("Preferences…", "Předvolby…"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index efc128858..7a5c5d17e 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -64,6 +64,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Duplicate", "Duplizieren"), ("Select All", "Alles auswählen"), ("Deselect All", "Auswahl aufheben"), + ("Select All Guides", "Alle Hilfslinien auswählen"), + ("Ruler Guide", "Hilfslinie"), ("Find/Change…", "Suchen/Ersetzen …"), ("Check Spelling…", "Rechtschreibprüfung …"), ("Preferences…", "Voreinstellungen …"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index a918a9829..e74d445fb 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -143,6 +143,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Duplicate", "Duplica"), ("Select All", "Seleziona tutto"), ("Deselect All", "Deseleziona tutto"), + ("Select All Guides", "Seleziona tutte le guide"), + ("Ruler Guide", "Guida del righello"), ("Find/Change…", "Trova/Sostituisci…"), ("Check Spelling…", "Controllo ortografico…"), ("Preferences…", "Preferenze…"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 5647ca940..072c188ff 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -145,6 +145,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Duplicate", "複製"), ("Select All", "すべてを選択"), ("Deselect All", "すべての選択を解除"), + ("Select All Guides", "すべてのガイドを選択"), + ("Ruler Guide", "定規ガイド"), ("Find/Change…", "検索と置換…"), ("Check Spelling…", "スペルチェック…"), ("Preferences…", "環境設定…"), diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index d938c2dc7..df9fabc07 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -66,6 +66,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Duplicate", "დუბლირება"), ("Select All", "ყველაფრის მონიშვნა"), ("Deselect All", "ყველა მონიშვნის მოხსნა"), + ("Select All Guides", "ყველა დამხმარე ხაზის მონიშვნა"), + ("Ruler Guide", "სახაზავის დამხმარე ხაზი"), ("Find/Change…", "ძებნა/ჩანაცვლება…"), ("Check Spelling…", "მართლწერის შემოწმება…"), ("Preferences…", "პარამეტრები…"), diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index 68d685d99..fca29c211 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -33,6 +33,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Duplicate", "Powiel"), ("Select All", "Zaznacz wszystko"), ("Deselect All", "Usuń zaznaczenie"), + ("Select All Guides", "Zaznacz wszystkie linie pomocnicze"), + ("Ruler Guide", "Linia pomocnicza"), ("Find/Change…", "Znajdź/zmień…"), ("Check Spelling…", "Sprawdź pisownię…"), ("Preferences…", "Preferencje…"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 8521de594..6d3a05793 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -154,6 +154,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Duplicate", "Duplicar"), ("Select All", "Selecionar tudo"), ("Deselect All", "Desmarcar tudo"), + ("Select All Guides", "Selecionar todas as guias"), + ("Ruler Guide", "Guia da régua"), ("Find/Change…", "Localizar/alterar…"), ("Find/Change", "Localizar/alterar"), ("Check Spelling…", "Verificar ortografia…"), diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 251555ca5..dc518b60c 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -37,6 +37,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Duplicate", "Дублировать"), ("Select All", "Выделить все"), ("Deselect All", "Снять выделение"), + ("Select All Guides", "Выделить все направляющие"), + ("Ruler Guide", "Направляющая"), ("Find/Change…", "Найти/заменить…"), ("Check Spelling…", "Проверка орфографии…"), ("Preferences…", "Установки…"), diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index dd4a1434d..223dba543 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -146,6 +146,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Duplicate", "Дублювати"), ("Select All", "Виділити все"), ("Deselect All", "Зняти всі виділення"), + ("Select All Guides", "Виділити всі напрямні"), + ("Ruler Guide", "Напрямна"), ("Find/Change…", "Знайти й замінити…"), ("Check Spelling…", "Перевірити орфографію…"), ("Preferences…", "Налаштування…"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index cb98cac7f..0844b95a4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -457,6 +457,7 @@ impl UiState { smart_dimensions: self.smart_dimensions, smart_spacing: self.smart_spacing, zone_px: self.snap_zone, + guides_locked: self.guides_locked, } } } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index c455b718d..da5819e6f 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -366,6 +366,7 @@ pub const MENUS: &[(&str, &[&str])] = &[ "cmd:edit.stepAndRepeat", "-", "cmd:edit.selectAll", + "cmd:guide.selectAll", "cmd:edit.deselectAll", "-", "ui:app.findChange", @@ -1320,16 +1321,7 @@ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option { - let Some(st) = app.session.active() else { return Some(Err("no document open".into())) }; - let page = crate::canvas::current_page(app).unwrap_or(0); - let spread = if st.editing_parents { - // The parent spread the canvas shows. - let layout = designcraft_tools::CanvasLayout::new(&st.doc, true); - let shown = crate::canvas::current_slot(app, &layout).and_then(|i| layout.slots.get(i)).map(|s| s.spread); - json!(shown.unwrap_or(designcraft_doc::SpreadRef::Parent(0))) - } else { - json!(st.doc.page_loc(page).map_or(0, |l| l.0)) - }; + let Some(spread) = guide_spread(app) else { return Some(Err("no document open".into())) }; return Some(app.run("guide.deleteAll", json!({"spread": spread}))); } "app.deletePage" | "app.duplicateSpread" => { @@ -2443,6 +2435,9 @@ pub fn menu_enabled(app: &DesignApp, id: &str) -> bool { if id.starts_with("fit.") { return enabled(app, "object.fit"); } + if id == "guide.selectAll" && (!app.ui.guides || app.ui.guides_locked) { + return false; + } if ui_label(id).is_some() { return app.session.active().is_some() || id.starts_with("app.") || id.starts_with("window.") || id.starts_with("help."); } @@ -2544,6 +2539,16 @@ fn activate_inner(app: &mut DesignApp, id: &str, params: &Value) { app.ui.dialog = Some(crate::dialogs::Dialog::new(&format!("cmd:{id}"), json!({}))); return; } + // Select All Guides: on the spread in view, while guides are shown and not locked. + if params.is_null() && id == "guide.selectAll" { + if app.ui.guides + && !app.ui.guides_locked + && let Some(spread) = guide_spread(app) + { + let _ = app.run(id, json!({"spread": spread})); + } + return; + } let p = if params.is_null() { json!({}) } else { params.clone() }; // Update Link asks before replacing edits made to linked text in the layout. if id == "links.update" { @@ -2553,6 +2558,20 @@ fn activate_inner(app: &mut DesignApp, id: &str, params: &Value) { let _ = app.run(id, p); } +/// The spread the guide commands of the menus act on: the one in view (a parent spread while +/// parents are edited). +fn guide_spread(app: &DesignApp) -> Option { + let st = app.session.active()?; + let page = crate::canvas::current_page(app).unwrap_or(0); + Some(if st.editing_parents { + let layout = designcraft_tools::CanvasLayout::new(&st.doc, true); + let shown = crate::canvas::current_slot(app, &layout).and_then(|i| layout.slots.get(i)).map(|s| s.spread); + json!(shown.unwrap_or(designcraft_doc::SpreadRef::Parent(0))) + } else { + json!(st.doc.page_loc(page).map_or(0, |l| l.0)) + }) +} + /// A menu button whose popup stays within the viewport and scrolls when needed. /// All menu buttons share this wrapper, including workspace, zoom and panel menus. pub fn menu_button<'a, R>( diff --git a/crates/ui-egui/src/object_control.rs b/crates/ui-egui/src/object_control.rs index 7c2634e23..0a845a38d 100644 --- a/crates/ui-egui/src/object_control.rs +++ b/crates/ui-egui/src/object_control.rs @@ -64,6 +64,8 @@ pub(crate) fn show(app: &mut DesignApp, ui: &mut Ui) { let selected = info.is_some(); let reference = app.ui.ref_point.min(8); let geometry = info.as_ref().map(|i| i.page_rect); + // One ruler guide selected: X (vertical guide) or Y (horizontal guide) is where it is. + let guide = panels::guide_field(app); group(ui, "reference", 26.0, |ui, rect| { let proxy = Rect::from_center_size(rect.center(), vec2(26.0, 26.0)); if let Some(point) = properties::ref_point_proxy(ui, proxy, reference) { @@ -81,10 +83,17 @@ pub(crate) fn show(app: &mut DesignApp, ui: &mut Ui) { for (column, (label, id, key, index)) in fields.into_iter().enumerate() { let x = column as f32 * 108.0; cell(ui, rect, x, row, 14.0, true, |ui| widgets::caption_w(ui, label, 14.0)); - let value = values.map(|v| v[index]); - if let Some(v) = cell(ui, rect, x + 15.0, row, 86.0, selected, |ui| { - NumField::measure(id, value, units).width(86.0).spinner().enabled(selected).show(ui) + let on_guide = guide.filter(|g| g.row() == index); + let value = if guide.is_some() { on_guide.map(|g| g.value) } else { values.map(|v| v[index]) }; + let enabled = selected || on_guide.is_some(); + let unit = on_guide.map_or(units, |g| g.unit); + if let Some(v) = cell(ui, rect, x + 15.0, row, 86.0, enabled, |ui| { + NumField::measure(id, value, unit).width(86.0).spinner().enabled(enabled).show(ui) }) { + if let Some(g) = on_guide { + let _ = app.run("guide.move", g.move_to(v)); + continue; + } set.insert(key.into(), json!(v)); if constrain && column == 1 diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs index 7c40f3b1b..f2229b604 100644 --- a/crates/ui-egui/src/panels/mod.rs +++ b/crates/ui-egui/src/panels/mod.rs @@ -117,6 +117,49 @@ pub fn sel_tint(app: &DesignApp, stroke: bool) -> f32 { st.selection.items.first().and_then(|id| st.doc.item(*id)).map_or(1.0, |it| if stroke { it.stroke.tint } else { it.fill.tint }) } +/// The one selected ruler guide, as the X field (vertical guide) or Y field (horizontal guide) +/// of the Control and Properties panels shows it: measured as the rulers measure, from the zero +/// point (and the page, when rulers restart per page), in that ruler's units. +#[derive(Clone, Copy, Debug)] +pub struct GuideField { + pub guide: designcraft_doc::GuideSel, + pub orientation: designcraft_doc::Orientation, + /// Points from the ruler origin. + pub value: f64, + /// Where `value` 0 is: a spread x for a vertical guide, a y for a horizontal one. + pub origin: f64, + pub unit: designcraft_geom::Unit, +} + +impl GuideField { + /// Which field shows it: 0 for X, 1 for Y. + pub fn row(&self) -> usize { + match self.orientation { + designcraft_doc::Orientation::Vertical => 0, + designcraft_doc::Orientation::Horizontal => 1, + } + } + /// The `guide.move` params that put it at `value` (as the field reads). + pub fn move_to(&self, value: f64) -> Value { + let g = self.guide; + json!({"spread": g.spread, "page": g.page, "index": g.index, "position": value + self.origin}) + } +} + +/// [`GuideField`] when exactly one ruler guide is selected. +pub fn guide_field(app: &DesignApp) -> Option { + let st = app.session.active()?; + let [g] = st.selection.guides.as_slice() else { return None }; + let pg = st.doc.spread(g.spread)?.pages.get(g.page)?; + let guide = pg.guides.get(g.index)?; + let (origin, unit) = match guide.orientation { + designcraft_doc::Orientation::Vertical => (st.doc.ruler_origin(g.spread, guide.position)?.x, st.doc.settings.horizontal_units), + designcraft_doc::Orientation::Horizontal => (st.doc.ruler_origin(g.spread, pg.x + pg.width / 2.0)?.y, st.doc.settings.vertical_units), + }; + let value = guide.position - origin; + value.is_finite().then_some(GuideField { guide: *g, orientation: guide.orientation, value, origin, unit }) +} + pub fn sel_info(app: &DesignApp) -> Option { let st = app.session.active()?; if st.selection.items.is_empty() { diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 44acf6e2c..399cc34e7 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -59,6 +59,9 @@ fn selection_title(app: &DesignApp, info: &Option) -> String { if st.selection.text.is_some() { return crate::i18n::tr(&app.ui.language, "Characters").into(); } + if info.is_none() && !st.selection.guides.is_empty() { + return crate::i18n::tr(&app.ui.language, "Ruler Guide").into(); + } match info { None => crate::i18n::tr(&app.ui.language, "No Selection").into(), Some(i) if i.count > 1 => crate::i18n::tr(&app.ui.language, "Multiple Objects").into(), @@ -106,6 +109,11 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { quick_actions_text(app, ui); return; } + if info.is_none() && app.session.active().is_some_and(|st| !st.selection.guides.is_empty()) { + section(ui, crate::i18n::tr(&app.ui.language, "Transform"), true); + guide_section(app, ui); + return; + } // The Page tool with no objects selected: the page's own settings, as InDesign's. if info.is_none() && app.session.tool_id() == "page" { let page = app.session.active().and_then(|st| st.selection.page).or_else(|| crate::canvas::current_page(app)); @@ -613,6 +621,27 @@ fn transform_section(app: &mut DesignApp, ui: &mut Ui, i: &SelInfo) { } } +/// Properties › Transform for selected ruler guides: X for one vertical guide, Y for one +/// horizontal guide; with several guides both fields are empty. +fn guide_section(app: &mut DesignApp, ui: &mut Ui) { + let guide = super::guide_field(app); + let b = block(ui, 2.0 * FIELD_H + 4.0); + for (row, (label, key)) in [("X:", "gx"), ("Y:", "gy")].into_iter().enumerate() { + let yy = row as f32 * 25.0; + let on = guide.filter(|g| g.row() == row); + place(ui, sub(b, 40.0, yy, 18.0, FIELD_H), |ui| widgets::caption_w(ui, label, 18.0)); + let typed = place(ui, sub(b, 59.0, yy, 135.0, FIELD_H), |ui| { + if on.is_none() { + ui.disable(); + } + measure(ui, key, on.map(|g| g.value), on.map_or_else(|| units(app), |g| g.unit), 135.0) + }); + if let (Some(v), Some(g)) = (typed, on) { + let _ = app.run("guide.move", g.move_to(v)); + } + } +} + /// Properties › Transform, below X/Y/W/H as in InDesign: rotation and shear angles beside the /// X and Y scales (totals, as Transformations are Totals), then rotate a quarter turn and flip. fn transform_angles(app: &mut DesignApp, ui: &mut Ui, rp: u8) { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cdd6da689..89fe4d401 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -283,7 +283,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Index: page references (topic from the selection or up to 4 levels, sort keys; current page, to end of story, next n paragraphs, suppressed, See / See also), Generate / Update Index (section headings, nested or run-in, page ranges merged, Index Title / Section Head / Level 1–4 styles); IDML export/import as InDesign topics, page references and topic cross-references (verified in InDesign 2026); `index.*` commands. - 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. +- Ruler guides: drag out of the rulers (page guides, or spread guides on the pasteboard), drag to move, drop on a ruler to delete; selected like objects with the Selection tools (click, Shift-click, a marquee that touches no object, Edit › Select All Guides ⌥⌘G), drawn highlighted, moved together by dragging or the arrow keys, deleted with Delete, and placed exactly with the X or Y field of the Control and Properties panels; 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. - Linked text files: `file.place {link: true}` or Preferences › File Handling › Create Links When Placing Text Files keeps a placed .docx/.rtf/.txt story linked to its file (path, size and hash, and the style map and conflict option used). The Links panel shows it OK / Modified / Missing; Update imports the file again into the same frames and thread with the saved style map, replacing edits made in the layout (the Links panel and menu ask first; the `links.update` command updates and returns a warning; undoable); Relink, Go To and Unlink. Saved in the native format; IDML exports the text unlinked. - Missing fonts: highlighted pink on screen (never in output), listed by Preflight; Type › Find/Replace Font (fonts in the document, missing first; replace in text, cells, footnotes and styles); `font.list` / `font.replace`. Type › Reload Fonts (`font.reload`) scans the font folders again and reads again the installed font files edited or removed since they were read, then recomposes the open documents: a font installed or edited while DesignCraft runs needs no restart (#328, #547). InDesign notices such changes by itself. From 6f7fc7134a487d9aa22aac4b173fa53ba5133403 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 22 Oct 2026 01:59:10 -0400 Subject: [PATCH 07/29] IDML: dragged column guides import, validated, and round-trip (#1096) (#1171) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * IDML: keep column guides that were dragged off centre (#1096) InDesign records dragged column guides in `MarginPreference ColumnsPositions`, as pairs of offsets from the margin box's left edge. The importer discarded them and divided the columns evenly, so a page whose gutter the designer had moved came back with it in the middle: on a 450 pt margin box, `0 150 170 450` was read as columns at 215 and 235. `Columns::positions` already existed, documented as "Custom column positions (after dragging column guides)", but nothing set it and nothing read it. Now `Page::column_rects` returns the custom rects when they are set — that one method is what the canvas guides, snapping, threading and the first frame of a placed story all go through, so they follow the dragged gutter — the importer fills it, and the exporter writes the page's real positions instead of recomputing an even split, so the round trip keeps them. `layout.marginsAndColumns` clears them when a count or gutter is set, which is what InDesign's Margins and Columns does. Without that the stale positions would outrank the new value and the dialog would look broken. Verified against InDesign-authored IDML rather than assumed, which settled two things. The attribute is written whether or not anything was dragged — a real page's values are exactly its even split — so an even set is dropped rather than marking every imported page custom and freezing its columns; the tolerance for that comparison only absorbs float noise, about 1e-14 pt on that page. And `` is a `` child, not a `` one, which is where this importer already looks: the reporter's missing ruler guide was 099fbd2, landed the day the ticket was filed, not a second bug. That commit left `lib.rs` still listing guides as ignored on import; corrected. * IDML: custom column positions are validated and round-trip (#1096) Columns::positions are used only when they are 2 x count finite edges, ascending from 0 to the margin box width (within 0.01 pt); anything else is the even split, in Page::column_rects, on IDML import (bounded parse, checked against the page's margin box) and on IDML export. Columns::with_gutter_moved moves one gutter's pair of guides between its neighbours for the coming column-guide command. ROADMAP: drop four progress-log lines the #1121 merge duplicated and move its line to the top. * IDML: a page without its own margins checks the default's column positions against its width (#1096) * ROADMAP: the progress line lands in one commit after the guide PRs --------- Co-authored-by: Hamza --- crates/doc/src/page.rs | 158 +++++++++++++++++++++++++++++++- crates/engine/src/cmd/layout.rs | 44 +++++++++ crates/idml/src/export.rs | 7 +- crates/idml/src/import.rs | 89 ++++++++++++++++-- crates/idml/src/lib.rs | 3 +- crates/idml/src/tests.rs | 69 ++++++++++++++ 6 files changed, 357 insertions(+), 13 deletions(-) diff --git a/crates/doc/src/page.rs b/crates/doc/src/page.rs index 862a1cda9..d1a77d78e 100644 --- a/crates/doc/src/page.rs +++ b/crates/doc/src/page.rs @@ -42,6 +42,77 @@ impl Default for Columns { } } +/// The most columns a page can have, as in InDesign. +pub const MAX_COLUMNS: u32 = 216; + +/// How far, in points, the first and last custom column positions may sit from the margin box's +/// edges: room for float noise in files and page arithmetic, far less than any dragged guide. +pub const COLUMN_POSITION_TOLERANCE: f64 = 0.01; + +/// Whether `positions` are usable custom column positions for `count` columns across a margin box +/// `margin_width` wide, in IDML's `ColumnsPositions` form: each column's left and right edge as an +/// offset from the margin box's left edge, so `2 × count` finite numbers, ascending across the +/// whole list, the first at 0 and the last at `margin_width` (within +/// [`COLUMN_POSITION_TOLERANCE`]). +pub fn valid_column_positions(positions: &[f64], count: u32, margin_width: f64) -> bool { + (1..=MAX_COLUMNS).contains(&count) + && positions.len() == 2 * count as usize + && margin_width.is_finite() + && positions.iter().all(|v| v.is_finite()) + && positions.windows(2).all(|w| matches!(w, [a, b] if a <= b)) + && positions.first().is_some_and(|v| v.abs() <= COLUMN_POSITION_TOLERANCE) + && positions.last().is_some_and(|v| (v - margin_width).abs() <= COLUMN_POSITION_TOLERANCE) +} + +impl Columns { + /// The custom positions when they are valid for a margin box `margin_width` wide (see + /// [`valid_column_positions`]). Anything else means the columns are evenly spaced: a stored set + /// that no longer fits (a page resized after the drag, a hostile file) is not drawn. + pub fn valid_positions(&self, margin_width: f64) -> Option<&[f64]> { + let positions = self.positions.as_deref()?; + valid_column_positions(positions, self.count, margin_width).then_some(positions) + } + + /// Every column's left and right edge as offsets from the margin box's left edge: the valid + /// custom positions, else the even split. This is what IDML writes as `ColumnsPositions`. + pub fn edges(&self, margin_width: f64) -> Vec { + let w = if margin_width.is_finite() { margin_width.max(0.0) } else { 0.0 }; + match self.valid_positions(w) { + Some(p) => p.iter().map(|&v| inside(v, w)).collect(), + None => column_rects(Rect::new(0.0, 0.0, w, 0.0), self.count.max(1), self.gutter).iter().flat_map(|r| [r.x0, r.x1]).collect(), + } + } + + /// The column edges (as [`Columns::edges`]) with gutter `gutter` (0 is the one between the first + /// two columns) moved so its left edge sits at `new_left`, an offset from the margin box's left + /// edge. Both of the gutter's guides move, so it keeps its width, and it stops at its + /// neighbouring gutters or the margins: no column gets a negative width. `None` when there is + /// no such gutter, `new_left` is not finite, or the result would not be valid. + pub fn with_gutter_moved(&self, margin_width: f64, gutter: usize, new_left: f64) -> Option> { + if !new_left.is_finite() { + return None; + } + let mut pos = self.edges(margin_width); + let i = gutter.checked_mul(2)?.checked_add(1)?; + let &[lo, left, right, hi] = pos.get(i - 1..i.checked_add(3)?)? else { + return None; + }; + let width = right - left; + let at = new_left.min(hi - width).max(lo); + let [l, r] = pos.get_mut(i..i + 2)? else { + return None; + }; + *l = at; + *r = (at + width).min(hi); + valid_column_positions(&pos, self.count, margin_width).then_some(pos) + } +} + +/// `v` limited to `0..=w` without `clamp`, which panics when `w` is NaN. +fn inside(v: f64, w: f64) -> f64 { + v.max(0.0).min(w) +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum Orientation { @@ -250,17 +321,23 @@ impl Page { let b = self.bounds(); Rect::new(b.x0 + l, b.y0 + self.margins.top, (b.x1 - r).max(b.x0 + l), (b.y1 - self.margins.bottom).max(b.y0 + self.margins.top)) } - /// Column rects within the margins. + /// Column rects within the margins: the custom positions when the column guides have been + /// dragged and still fit the margin box (see [`valid_column_positions`]), otherwise an even + /// split. pub fn column_rects(&self) -> Vec { let m = self.margin_rect(); - column_rects(m, self.columns.count.max(1), self.columns.gutter) + let w = m.width(); + match self.columns.valid_positions(w) { + Some(p) => p.as_chunks::<2>().0.iter().map(|&[a, b]| Rect::new(m.x0 + inside(a, w), m.y0, m.x0 + inside(b, w), m.y1)).collect(), + None => column_rects(m, self.columns.count.max(1), self.columns.gutter), + } } } /// Split `area` into `n` equal columns separated by `gutter`. pub fn column_rects(area: Rect, n: u32, gutter: f64) -> Vec { // The public allocator also receives native/imported options, outside command validation. - let n = n.clamp(1, 216) as usize; + let n = n.clamp(1, MAX_COLUMNS) as usize; let w = ((area.width() - gutter * (n as f64 - 1.0)) / n as f64).max(0.0); (0..n).map(|i| Rect::new(area.x0 + i as f64 * (w + gutter), area.y0, area.x0 + i as f64 * (w + gutter) + w, area.y1)).collect() } @@ -450,6 +527,81 @@ mod tests { assert!((cols[1].x0 - cols[0].x1 - 12.0).abs() < 1e-9); } + /// Dragged column guides place the columns; a set that cannot mean anything falls back to the + /// even split rather than producing nothing or a column outside the margins (#1096). + #[test] + fn custom_column_positions_place_the_columns() { + let mut p = page(PageSide::Single, 0.0); + let m = p.margin_rect(); + let w = m.width(); + let even = p.column_rects(); + + p.columns.positions = Some(vec![0.0, 100.0, 130.0, w]); + assert_eq!(p.column_rects(), vec![Rect::new(m.x0, m.y0, m.x0 + 100.0, m.y1), Rect::new(m.x0 + 130.0, m.y0, m.x1, m.y1)]); + // Float noise at the edges is absorbed and kept inside the box. + p.columns.positions = Some(vec![-0.001, 100.0, 130.0, w + 0.001]); + assert_eq!((p.column_rects()[0].x0, p.column_rects()[1].x1), (m.x0, m.x1)); + + let huge: Vec = (0..10_000).map(f64::from).collect(); + let unusable = [ + vec![], + vec![10.0], + vec![0.0, w], // one column's worth for two columns + vec![0.0, 100.0, 130.0, 200.0, 230.0, w], // three columns' worth + vec![0.0, 100.0, 90.0, w], // descending across pairs + vec![0.0, 130.0, 100.0, w], // an inverted gutter + vec![0.0, f64::NAN, 130.0, w], + vec![0.0, 100.0, f64::INFINITY, w], + vec![5.0, 100.0, 130.0, w], // not from the left margin + vec![0.0, 100.0, 130.0, w + 500.0], // a page narrowed after the drag + vec![0.0, 100.0, 130.0, w - 50.0], // a page widened after the drag + huge, + ]; + for bad in unusable { + p.columns.positions = Some(bad.clone()); + assert_eq!(p.column_rects(), even, "{:?}", bad.iter().take(6).collect::>()); + assert_eq!(p.columns.edges(w), even.iter().flat_map(|r| [r.x0 - m.x0, r.x1 - m.x0]).collect::>()); + } + p.columns.positions = None; + assert_eq!(p.column_rects(), even); + + // A count outside 1..=216 has no valid positions, however many are given. + for count in [0, 217, u32::MAX] { + let c = Columns { count, gutter: 0.0, positions: Some(vec![0.0, w]) }; + assert!(c.valid_positions(w).is_none(), "{count}"); + } + } + + /// Moving a gutter moves both its guides, keeps its width and stops at the neighbouring gutters + /// and the margins; the result is valid custom positions. + #[test] + fn with_gutter_moved_moves_a_gutter_pair_and_clamps() { + // Three columns across 450 with gutter 15: 0 140 155 295 310 450. + let c = Columns { count: 3, gutter: 15.0, positions: None }; + let even = c.edges(450.0); + assert_eq!(even, vec![0.0, 140.0, 155.0, 295.0, 310.0, 450.0]); + + assert_eq!(c.with_gutter_moved(450.0, 0, 100.0), Some(vec![0.0, 100.0, 115.0, 295.0, 310.0, 450.0])); + // Past the left margin: the first column closes to nothing. + assert_eq!(c.with_gutter_moved(450.0, 0, -50.0), Some(vec![0.0, 0.0, 15.0, 295.0, 310.0, 450.0])); + // Past the next gutter: the middle column closes to nothing, the next gutter stays put. + assert_eq!(c.with_gutter_moved(450.0, 0, 400.0), Some(vec![0.0, 280.0, 295.0, 295.0, 310.0, 450.0])); + // The last gutter stops at the right margin. + assert_eq!(c.with_gutter_moved(450.0, 1, 1000.0), Some(vec![0.0, 140.0, 155.0, 435.0, 450.0, 450.0])); + + // It starts from custom positions already there, and its result is accepted as custom. + let moved = Columns { positions: c.with_gutter_moved(450.0, 0, 100.0), ..c.clone() }; + assert!(moved.valid_positions(450.0).is_some()); + assert_eq!(moved.with_gutter_moved(450.0, 1, 200.0), Some(vec![0.0, 100.0, 115.0, 200.0, 215.0, 450.0])); + + // No such gutter, or no position to move it to. + assert_eq!(c.with_gutter_moved(450.0, 2, 100.0), None); + assert_eq!(c.with_gutter_moved(450.0, usize::MAX, 100.0), None); + assert_eq!(c.with_gutter_moved(450.0, 0, f64::NAN), None); + assert_eq!(Columns { count: 1, gutter: 12.0, positions: None }.with_gutter_moved(450.0, 0, 100.0), None); + assert_eq!(c.with_gutter_moved(f64::NAN, 0, 100.0), None); + } + #[test] fn spread_spine_and_hit() { let s = Spread { diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 615e7c1df..667bb927b 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -97,11 +97,15 @@ fn set_margins_columns(pg: &mut designcraft_doc::Page, p: &Value) { } _ => {} } + // Setting a count or a gutter re-divides the columns evenly, as InDesign's Margins and + // Columns does: dragged column positions are what the new value replaces. if let Some(c) = p.get("columns").and_then(Value::as_u64) { pg.columns.count = (c as u32).clamp(1, 216); + pg.columns.positions = None; } if let Some(g) = p.get("gutter").and_then(Value::as_f64) { pg.columns.gutter = g.max(0.0); + pg.columns.positions = None; } } @@ -1650,6 +1654,46 @@ mod adjust_tests { // An unknown parent is an error, not a silent no-op. assert!(s.execute("layout.marginsAndColumns", &json!({"parent": 9, "margins": 10})).is_err()); } + + /// Margins and Columns re-divides the columns: a new count or gutter replaces column guides + /// that were dragged (an imported Custom columns page), rather than being ignored by them. + #[test] + fn a_new_column_count_replaces_dragged_column_positions() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 1, "facingPages": false})).unwrap(); + // There is no command for dragging a column guide yet, so set what an import would leave. + let drag = |s: &mut Session| { + s.edit(|d, _| { + let pg = &mut std::sync::Arc::make_mut(&mut d.spreads[0]).pages[0]; + pg.columns = designcraft_doc::Columns { count: 2, gutter: 12.0, positions: Some(vec![0.0, 100.0, 130.0, 540.0]) }; + Ok(()) + }) + .unwrap(); + }; + + drag(&mut s); + let dragged = s.doc().unwrap().doc.page(0).unwrap().column_rects(); + assert_eq!(dragged.len(), 2); + assert!((dragged[0].x1 - dragged[0].x0 - 100.0).abs() < 1e-6, "the dragged gutter is in use: {dragged:?}"); + + // A new count: evenly divided again, and the stale positions are gone. + s.execute("layout.marginsAndColumns", &json!({"columns": 3})).unwrap(); + let pg = s.doc().unwrap().doc.page(0).unwrap().clone(); + assert_eq!((pg.columns.count, pg.columns.positions.clone()), (3, None)); + assert_eq!(pg.column_rects().len(), 3); + + // So does a new gutter on its own. + drag(&mut s); + s.execute("layout.marginsAndColumns", &json!({"gutter": 24})).unwrap(); + let pg = s.doc().unwrap().doc.page(0).unwrap().clone(); + assert_eq!(pg.columns.positions, None); + assert!((pg.column_rects()[1].x0 - pg.column_rects()[0].x1 - 24.0).abs() < 1e-6); + + // Margins alone leave them alone: the offsets are relative to the margin box. + drag(&mut s); + s.execute("layout.marginsAndColumns", &json!({"margins": 72})).unwrap(); + assert_eq!(s.doc().unwrap().doc.page(0).unwrap().columns.positions, Some(vec![0.0, 100.0, 130.0, 540.0])); + } } #[cfg(test)] diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs index 86fef8e46..bd1d117e0 100644 --- a/crates/idml/src/export.rs +++ b/crates/idml/src/export.rs @@ -8,7 +8,7 @@ use designcraft_doc::{ CharAttrs, CharFormat, ColumnsKind, Content, Document, Item, ListType, PageSide, ParaAttrs, ParaFormat, Rule, Shape, SpanColumns, Spread, Story, TextFrameOptions, story as st, }; -use designcraft_geom::{Affine, PathData, Rect}; +use designcraft_geom::{Affine, PathData}; use crate::names::{self, CHAR_BUILTINS, OBJECT_BUILTINS, PARA_BUILTINS, escape_id, num, pt}; use crate::xml::{El, Node, document, document_with_pi}; @@ -2901,8 +2901,9 @@ impl Group { fn margin_el(pg: &designcraft_doc::Page) -> El { let m = pg.margin_rect(); - let cols = designcraft_doc::column_rects(Rect::new(0.0, 0.0, m.width(), m.height()), pg.columns.count.max(1), pg.columns.gutter); - let pos: Vec = cols.iter().flat_map(|c| [num(c.x0), num(c.x1)]).collect(); + // Dragged column guides that still fit the margin box are written as they stand, so they + // survive the round trip; otherwise the even split, which InDesign writes for unmoved columns. + let pos: Vec = pg.columns.edges(m.width()).into_iter().map(num).collect(); El::new("MarginPreference") .attr("ColumnCount", pg.columns.count.max(1)) .attr("ColumnGutter", num(pg.columns.gutter)) diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs index d770aef79..271eba146 100644 --- a/crates/idml/src/import.rs +++ b/crates/idml/src/import.rs @@ -2534,9 +2534,15 @@ impl<'r> Importer<'r> { .map(|q| (q.margins, q.columns.clone())) }; let (margins, columns) = match (p.find("MarginPreference"), &from_parent) { - (Some(m), _) => margins_of(m), + (Some(m), _) => { + let (margins, columns) = margins_of(m); + (margins, fit_columns(columns, &margins, r.width())) + } (None, Some(own)) => own.clone(), - (None, None) => self.default_margins.clone().unwrap_or((Margins::uniform(36.0), Columns::default())), + (None, None) => { + let (margins, columns) = self.default_margins.clone().unwrap_or((Margins::uniform(36.0), Columns::default())); + (margins, fit_columns(columns, &margins, r.width())) + } }; let local_margins = from_parent.is_some_and(|(m, c)| m != margins || c != columns); out_pages.push(Page { @@ -3465,10 +3471,39 @@ fn composer_in(name: &str) -> designcraft_doc::Composer { fn margins_of(m: &El) -> (Margins, Columns) { let g = |k: &str, d: f64| m.num(k).filter(|v| v.is_finite()).unwrap_or(d); - ( - Margins { top: g("Top", 36.0), bottom: g("Bottom", 36.0), inside: g("Left", 36.0), outside: g("Right", 36.0) }, - Columns { count: g("ColumnCount", 1.0).clamp(1.0, 216.0) as u32, gutter: g("ColumnGutter", 12.0), positions: None }, - ) + let margins = Margins { top: g("Top", 36.0), bottom: g("Bottom", 36.0), inside: g("Left", 36.0), outside: g("Right", 36.0) }; + let count = g("ColumnCount", 1.0).clamp(1.0, f64::from(designcraft_doc::MAX_COLUMNS)) as u32; + let gutter = g("ColumnGutter", 12.0); + let positions = m.get("ColumnsPositions").and_then(|s| custom_columns(s, count, gutter)); + (margins, Columns { count, gutter, positions }) +} + +/// `ColumnsPositions` when the column guides have been dragged off the even split: `2 × count` +/// offsets from the margin box's left edge, valid as [`designcraft_doc::valid_column_positions`] +/// over the box they span. InDesign writes the attribute whether or not they have been moved, so +/// an even set is dropped: `positions` means "custom", and keeping an even copy would freeze the +/// columns against a later change of count or gutter. Anything malformed is the even split; at +/// most one number past `2 × count` is parsed, so a long list costs nothing. +fn custom_columns(s: &str, count: u32, gutter: f64) -> Option> { + let want = 2 * count as usize; + let pos = s.split_whitespace().take(want + 1).map(|v| v.parse::().ok()).collect::>>()?; + let width = *pos.last()?; + if !designcraft_doc::valid_column_positions(&pos, count, width) { + return None; + } + let even = Columns { count, gutter, positions: None }.edges(width); + // The tolerance only absorbs float noise in InDesign's arithmetic; a dragged guide moves far more. + pos.iter().zip(&even).any(|(a, b)| (a - b).abs() > 1e-4).then_some(pos) +} + +/// `columns` with custom positions only when they fit the margin box of a `page_width`-wide page +/// with these margins (the box's width doesn't depend on which side of the spine it is). +fn fit_columns(mut columns: Columns, margins: &Margins, page_width: f64) -> Columns { + let width = (page_width - margins.inside - margins.outside).max(0.0); + if columns.valid_positions(width).is_none() { + columns.positions = None; + } + columns } /// Text Frame Options from `TextFramePreference` elements: each attribute from the first that sets it. @@ -3995,6 +4030,48 @@ mod page_column_import_safety_tests { assert_eq!(margins, Margins::uniform(36.)); } } + + /// Hostile `ColumnsPositions` are the even split: never half-read, never a panic, and a long + /// list is not parsed past what `ColumnCount` allows (#1096). + #[test] + fn hostile_column_positions_fall_back_to_the_even_split() { + let positions = |count: &str, raw: &str| { + let m = El::new("MarginPreference").attr("ColumnCount", count).attr("ColumnGutter", "20").attr("ColumnsPositions", raw); + margins_of(&m).1.positions + }; + assert_eq!(positions("2", "0 150 170 450"), Some(vec![0., 150., 170., 450.])); + let huge = (0..10_000).map(|i| i.to_string()).collect::>().join(" "); + for (count, raw) in [ + ("2", "0 215 235 450"), // the even split + ("2", "0 150 170"), // odd + ("2", "0 450"), // too few for the count + ("2", "0 100 120 200 220 450"), // too many for the count + ("2", "0 150 90 450"), // descending + ("2", "0 NaN 170 450"), + ("2", "0 inf 170 450"), + ("2", "0 150 170 1e309"), + ("2", "0 x 170 450"), + ("2", "10 150 170 450"), // not from the margin + ("2", ""), + ("2", huge.as_str()), + ("4000000000", huge.as_str()), // the count is capped at 216, so is the list + ("216", huge.as_str()), + ("NaN", "0 150 170 450"), + ] { + assert_eq!(positions(count, raw), None, "{count}: {}", raw.get(..raw.len().min(40)).unwrap_or("")); + } + // The cap itself: 216 one-point columns with no gutter are the even split; one edge moved + // makes them custom. + let gapless = |raw: &str| { + let m = El::new("MarginPreference").attr("ColumnCount", "216").attr("ColumnGutter", "0").attr("ColumnsPositions", raw); + margins_of(&m).1.positions + }; + let edges = |first_right: &str| { + (0..432).map(|i| if i == 1 { first_right.to_string() } else { ((i + 1) / 2).to_string() }).collect::>().join(" ") + }; + assert_eq!(gapless(&edges("1")), None); + assert_eq!(gapless(&edges("0.5")).map(|p| p.len()), Some(432)); + } } #[cfg(test)] diff --git a/crates/idml/src/lib.rs b/crates/idml/src/lib.rs index 38c4fabbe..8f7b22ff9 100644 --- a/crates/idml/src/lib.rs +++ b/crates/idml/src/lib.rs @@ -17,7 +17,8 @@ //! ## Supported subset //! Swatches (process/spot CMYK, RGB and Lab colours, tints, linear/radial gradients), paragraph, //! character and object styles (with `BasedOn` and style groups), fonts, document preferences -//! (page size, facing pages, bleed/slug, margins and columns, units, grids), layers, sections, +//! (page size, facing pages, bleed/slug, margins and columns including dragged column positions, +//! units, grids), ruler guides, layers, sections, //! parent (master) spreads and applied parents, spreads and pages, page items (`TextFrame`, //! `Rectangle`, `Oval`, `Polygon`, `GraphicLine`, `Group`) with fill/stroke, corner options, text //! frame options (with column rules), text wrap, transparency (opacity, blend mode, drop shadow, diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs index 81cebff70..cf9ce28a4 100644 --- a/crates/idml/src/tests.rs +++ b/crates/idml/src/tests.rs @@ -4194,6 +4194,75 @@ mod liquid_page_rules { } } +/// A dragged column gutter (InDesign's Custom columns) survives an IDML import, and an even set — +/// which InDesign writes for every page, moved or not — does not pretend to be custom (#1096). +#[test] +fn custom_column_positions_import_and_round_trip() { + // Page 1 of SPREAD is 500 wide with Left=20 Right=30, so its margin box is 450 wide and + // starts at x=30. Two columns with gutter 20 split evenly as "0 215 235 450". + let with = |cols: &str| { + let spread = SPREAD.replace( + r#""#, + &format!( + r#""# + ), + ); + import_idml_with( + &zip_files(&[ + ("designmap.xml", DESIGNMAP), + ("Resources/Graphic.xml", GRAPHIC), + ("Resources/Styles.xml", STYLES), + ("Resources/Preferences.xml", PREFS), + ("MasterSpreads/MasterSpread_m1.xml", MASTER), + ("Spreads/Spread_sp1.xml", &spread), + ("Stories/Story_s1.xml", STORY), + ]), + &|_| None, + ) + .unwrap() + }; + let rects = |d: &designcraft_doc::Document| d.spreads[0].pages[0].column_rects().iter().map(|r| (r.x0, r.x1)).collect::>(); + + // Dragged: the gutter sits at 150..170 instead of 215..235, and the columns follow it. + let d = with(r#"ColumnsPositions="0 150 170 450""#); + assert_eq!(d.spreads[0].pages[0].columns.positions, Some(vec![0.0, 150.0, 170.0, 450.0])); + assert_eq!(rects(&d), vec![(30.0, 180.0), (200.0, 480.0)]); + + // The even set is dropped, so a later change of count or gutter is not frozen out. The + // geometry is the same either way, which is what makes keeping it pointless. + let even = with(r#"ColumnsPositions="0 215 235 450""#); + assert_eq!(even.spreads[0].pages[0].columns.positions, None); + assert_eq!(rects(&even), vec![(30.0, 245.0), (265.0, 480.0)]); + // Including when InDesign's own arithmetic leaves the last bits different. + assert_eq!(with(r#"ColumnsPositions="0 215.00000000000003 234.99999999999997 450""#).spreads[0].pages[0].columns.positions, None); + + // Malformed sets are ignored rather than half-read: an odd count, three columns' worth for a + // count of two, a descending pair, a NaN, a set that stops short of the page's margin box, and + // a list far longer than any count allows. Each page keeps the even split. + let huge = format!(r#"ColumnsPositions="{}""#, (0..10_000).map(|i| i.to_string()).collect::>().join(" ")); + for bad in [ + r#"ColumnsPositions="0 150 170""#, + r#"ColumnsPositions="0 100 120 200 220 450""#, + r#"ColumnsPositions="0 150 90 450""#, + r#"ColumnsPositions="0 x 170 450""#, + r#"ColumnsPositions="0 NaN 170 450""#, + r#"ColumnsPositions="0 150 170 400""#, + r#"ColumnsPositions="""#, + huge.as_str(), + ] { + let d = with(bad); + assert_eq!(d.spreads[0].pages[0].columns.positions, None, "{}", bad.get(..bad.len().min(60)).unwrap_or("")); + assert_eq!(rects(&d), rects(&even)); + } + + // And they come back from an export, so the round trip keeps the dragged gutter. + let back = import_idml(&export_idml(&d)).unwrap(); + assert_eq!(back.spreads[0].pages[0].columns.positions, Some(vec![0.0, 150.0, 170.0, 450.0])); + assert_eq!(rects(&back), rects(&d)); + // A page nobody dragged still exports the even split, not a frozen copy of it. + assert_eq!(import_idml(&export_idml(&even)).unwrap().spreads[0].pages[0].columns.positions, None); +} + /// #1096: a ruler guide inside the gutter of a two-column page, written the way InDesign writes /// it (a `` child after its `MarginPreference`, with `Properties`/`GuideColor`, `PageIndex` /// and `GuideZone`), in a document without facing pages. A spread guide sits beside it. From d7b9f716f131f21531c971e7eea5d2e18fc789f3 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 22 Oct 2026 02:12:42 -0400 Subject: [PATCH 08/29] View: Lock Guides and Lock Column Guides are commands (#1096) (#1174) * View: Lock Guides and Lock Column Guides are commands (#1096) view.lockGuides {on?} (Cmd+Alt+;) sets the Lock Guides UI state the Properties panel and ruler-guide drags use. view.lockColumnGuides {on?} is a document setting, on by default, saved with the document, not an undo step, and read from and written to IDML ColumnGuideLocked. Both are in View > Grids & Guides with checkmarks. * View: Lock Column Guides is translated wherever Lock Guides is (#1096) * View: Lock Column Guides is undoable (#1096) * ROADMAP: the progress line lands in one commit after the guide PRs --- crates/doc/src/lib.rs | 9 +++++ crates/engine/src/cmd/guides.rs | 54 +++++++++++++++++++++++++ crates/idml/src/export.rs | 2 +- crates/idml/src/import.rs | 3 ++ crates/idml/src/tests.rs | 12 ++++++ crates/ui-egui/src/i18n.rs | 4 ++ crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/cs.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ka.rs | 1 + crates/ui-egui/src/i18n/pl.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/ru.rs | 1 + crates/ui-egui/src/i18n/uk.rs | 1 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/menus.rs | 29 +++++++++++++ crates/ui-egui/src/panels/properties.rs | 4 +- docs/target-app-parity.md | 2 +- 20 files changed, 127 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 5c854ba9f..b2d3b4f4c 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -399,11 +399,19 @@ pub struct DocSettings { /// Lock Zero Point: dragging from the ruler corner leaves it where it is. #[serde(skip_serializing_if = "std::ops::Not::not")] pub zero_point_locked: bool, + /// View › Grids & Guides › Lock Column Guides (IDML `ColumnGuideLocked`): column guides can't + /// be dragged. On in new documents, as in InDesign. + #[serde(skip_serializing_if = "is_true")] + pub column_guides_locked: bool, /// The fill and stroke new shapes are drawn with: what the Tools panel's proxy shows and sets /// with nothing selected (InDesign's document defaults). pub new_object: NewObjectColors, } +fn is_true(b: &bool) -> bool { + *b +} + fn is_origin(p: &[f64; 2]) -> bool { p[0] == 0.0 && p[1] == 0.0 } @@ -461,6 +469,7 @@ impl Default for DocSettings { ruler_origin: RulerOrigin::Spread, zero_point: [0.0, 0.0], zero_point_locked: false, + column_guides_locked: true, new_object: NewObjectColors::default(), } } diff --git a/crates/engine/src/cmd/guides.rs b/crates/engine/src/cmd/guides.rs index 97bf4e9cc..18826fb18 100644 --- a/crates/engine/src/cmd/guides.rs +++ b/crates/engine/src/cmd/guides.rs @@ -67,6 +67,15 @@ pub fn specs() -> Vec { Ok(json!({"deleted": n})) }) }), + cmd!( + "view.lockColumnGuides", + "Lock Column Guides", + ["View", "Grids & Guides"], + None, + "{on?: bool (default: toggle)} → {locked} — locked column guides can't be dragged; saved with the document (IDML ColumnGuideLocked), on in new documents", + has_doc, + lock_column_guides + ), cmd!( query "guide.list", "Guides", @@ -125,6 +134,18 @@ pub fn specs() -> Vec { ] } +fn lock_column_guides(s: &mut Session, p: &Value) -> Result { + let cur = s.doc()?.doc.settings.column_guides_locked; + let on = p.get("on").and_then(Value::as_bool).unwrap_or(!cur); + if on == cur { + return Ok(json!({"locked": cur})); + } + s.edit(|d, _| { + d.settings.column_guides_locked = on; + Ok(json!({"locked": on})) + }) +} + fn checked_usize(value: &Value, key: &str, command: &str) -> Result { let n = value.as_u64().ok_or_else(|| bad(command, format!("`{key}` must be a non-negative integer")))?; usize::try_from(n).map_err(|_| bad(command, format!("`{key}` is too large for this platform"))) @@ -590,6 +611,39 @@ fn create_guides(s: &mut Session, p: &Value) -> Result { mod tests { use super::*; + #[test] + fn lock_column_guides_toggles_sets_and_undoes() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let locked = |s: &Session| s.doc().unwrap().doc.settings.column_guides_locked; + let undo_steps = |s: &Session| s.doc().unwrap().history.undo.len(); + assert!(locked(&s), "locked in new documents"); + let before = undo_steps(&s); + assert_eq!(s.execute("view.lockColumnGuides", &json!({})).unwrap()["locked"], false); + assert!(!locked(&s)); + assert_eq!(undo_steps(&s), before + 1, "one undo step per toggle"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(locked(&s), "undo restores the lock"); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(!locked(&s), "redo unlocks again"); + // Setting the current value changes nothing and adds no undo step. + let steps = undo_steps(&s); + assert_eq!(s.execute("view.lockColumnGuides", &json!({"on": false})).unwrap()["locked"], false); + assert_eq!(undo_steps(&s), steps); + assert_eq!(s.execute("view.lockColumnGuides", &json!({"on": true})).unwrap()["locked"], true); + assert!(locked(&s)); + assert_eq!(s.execute("view.lockColumnGuides", &json!({})).unwrap()["locked"], false); + // Saved with the document; files without the setting read as locked. + let json = serde_json::to_string(&*s.doc().unwrap().doc).unwrap(); + assert!(json.contains("\"columnGuidesLocked\":false"), "{json}"); + let back: Document = serde_json::from_str(&json).unwrap(); + assert!(!back.settings.column_guides_locked); + let old = json.replace("\"columnGuidesLocked\":false,", "").replace(",\"columnGuidesLocked\":false", ""); + assert!(!old.contains("columnGuidesLocked")); + let back: Document = serde_json::from_str(&old).unwrap(); + assert!(back.settings.column_guides_locked); + } + #[test] fn guides_add_move_delete_and_grid() { let mut s = Session::new(); diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs index bd1d117e0..99dcb383e 100644 --- a/crates/idml/src/export.rs +++ b/crates/idml/src/export.rs @@ -769,7 +769,7 @@ impl<'a> Ex<'a> { }, ) .attr("CreatePrimaryTextFrame", bool_s(s.primary_text_frame)) - .attr("ColumnGuideLocked", "true") + .attr("ColumnGuideLocked", bool_s(s.column_guides_locked)) .attr("MasterTextFrame", bool_s(s.primary_text_frame)) .attr("SnippetImportUsesOriginalLocation", "false"), ); diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs index 271eba146..ef504065e 100644 --- a/crates/idml/src/import.rs +++ b/crates/idml/src/import.rs @@ -850,6 +850,9 @@ impl<'r> Importer<'r> { if let Some(v) = e.boolean("CreatePrimaryTextFrame") { s.primary_text_frame = v; } + if let Some(v) = e.boolean("ColumnGuideLocked") { + s.column_guides_locked = v; + } } fn grid_prefs(&mut self, e: &El) { diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs index cf9ce28a4..37fb2af50 100644 --- a/crates/idml/src/tests.rs +++ b/crates/idml/src/tests.rs @@ -2773,6 +2773,18 @@ fn round_trips_the_zero_point_and_ruler_origin() { assert_eq!(fixture("NaN 4").settings.zero_point, [0.0, 0.0]); } +#[test] +fn round_trips_lock_column_guides() { + let mut d = Document::new(&NewDocument::default()); + assert!(zip_text(&export_idml(&d), "Resources/Preferences.xml").contains(r#"ColumnGuideLocked="true""#)); + assert!(import_idml(&export_idml(&d)).unwrap().settings.column_guides_locked); + d.settings.column_guides_locked = false; + let bytes = export_idml(&d); + let prefs = zip_text(&bytes, "Resources/Preferences.xml"); + assert!(prefs.contains(r#"ColumnGuideLocked="false""#), "{prefs}"); + assert!(!import_idml(&bytes).unwrap().settings.column_guides_locked); +} + #[test] fn kenten_shatai_and_grid_settings_import_and_round_trip() { use designcraft_doc::cjk::CharacterAlignment; diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 91c6db7de..acf70ff32 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -3164,6 +3164,10 @@ const TABLE: &[(&str, [&str; 5])] = &[ ("Last Spread", ["Last Spread", "Dernière planche", "Last Spread", "Last Spread", "最后一个跨页"]), ("Load DTD…", ["Load DTD…", "Charger la DTD…", "Load DTD…", "Load DTD…", "载入 DTD…"]), ("Location:", ["Location:", "Emplacement :", "Location:", "Location:", "位置:"]), + ( + "Lock Column Guides", + ["Spaltenhilfslinien sperren", "Verrouiller les repères de colonne", "Bloquear guías de columna", "列ガイドをロック", "锁定栏参考线"], + ), ("Lock Guides", ["Lock Guides", "Verrouiller les repères", "Lock Guides", "Lock Guides", "锁定参考线"]), ("Miter Limit:", ["Miter Limit:", "Limite de pointe :", "Miter Limit:", "Miter Limit:", "斜接限制:"]), ( diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 11a01c1cc..587ed775b 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -395,6 +395,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Adjust Layout", "ضبط التخطيط"), ("Smart Guides", "أدلة ذكية"), ("Lock Guides", "قفل الأدلة"), + ("Lock Column Guides", "قفل أدلة الأعمدة"), ("Show Document Grid", "إظهار شبكة المستند"), ("Show Baseline Grid", "إظهار شبكة خطوط الأساس"), ("Options", "خيارات"), diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index b295e5e5b..c052b8f33 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -1095,6 +1095,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Load DTD…", "Načíst DTD…"), ("Location:", "Umístění:"), ("Lock Guides", "Zamknout vodítka"), + ("Lock Column Guides", "Zamknout vodítka sloupců"), ("Miter Limit:", "Limit ostrého spoje:"), ("New Article from Selection", "Nový článek z výběru"), ("New Note at Cursor", "Nová poznámka u kurzoru"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 7a5c5d17e..7065c6f33 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1153,6 +1153,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Load DTD…", "DTD laden …"), ("Location:", "Position:"), ("Lock Guides", "Hilfslinien sperren"), + ("Lock Column Guides", "Spaltenhilfslinien sperren"), ("Miter Limit:", "Gehrungsgrenze:"), ("New Article from Selection", "Neuer Artikel aus Auswahl"), ("New Note at Cursor", "Neue Notiz an der Einfügemarke"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index e74d445fb..8199e2ebb 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1235,6 +1235,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Load DTD…", "Carica DTD…"), ("Location:", "Posizione:"), ("Lock Guides", "Blocca guide"), + ("Lock Column Guides", "Blocca guide colonne"), ("Miter Limit:", "Limite spigolo:"), ("New Article from Selection", "Nuovo articolo dalla selezione"), ("New Note at Cursor", "Nuova nota al cursore"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 072c188ff..e79f4ba06 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1351,6 +1351,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Load DTD…", "DTD を読み込み…"), ("Location:", "位置:"), ("Lock Guides", "ガイドをロック"), + ("Lock Column Guides", "列ガイドをロック"), ("Miter Limit:", "マイターの上限:"), ("New Article from Selection", "選択範囲から新規アーティクルを作成"), ("New Note at Cursor", "カーソル位置に新規注釈"), diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index df9fabc07..c8405c16e 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -1172,6 +1172,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Load DTD…", "DTD-ის ჩატვირთვა…"), ("Location:", "მდებარეობა:"), ("Lock Guides", "დამხმარე ხაზების ჩაკეტვა"), + ("Lock Column Guides", "სვეტების დამხმარე ხაზების ჩაკეტვა"), ("Miter Limit:", "მახვილის ზღვარი:"), ("New Article from Selection", "ახალი სტატია მონიშნულიდან"), ("New Note at Cursor", "ახალი შენიშვნა კურსორთან"), diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index fca29c211..51bb7fc5c 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -1105,6 +1105,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Load DTD…", "Wczytaj DTD…"), ("Location:", "Położenie:"), ("Lock Guides", "Zablokuj linie pomocnicze"), + ("Lock Column Guides", "Zablokuj linie pomocnicze łamów"), ("Miter Limit:", "Limit ostrych narożników:"), ("New Article from Selection", "Nowy artykuł z zaznaczenia"), ("New Note at Cursor", "Nowa notatka przy kursorze"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 6d3a05793..bb3d21831 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -403,6 +403,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Adjust Layout", "Ajustar layout"), ("Smart Guides", "Guias inteligentes"), ("Lock Guides", "Bloquear guias"), + ("Lock Column Guides", "Bloquear guias de colunas"), ("Show Document Grid", "Mostrar grade do documento"), ("Show Baseline Grid", "Mostrar grade de linha de base"), ("Options", "Opções"), diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index dc518b60c..27ce1fed3 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -1082,6 +1082,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Load DTD…", "Загрузить DTD…"), ("Location:", "Расположение:"), ("Lock Guides", "Заблокировать направляющие"), + ("Lock Column Guides", "Заблокировать направляющие колонок"), ("Miter Limit:", "Ограничение острого угла:"), ("New Article from Selection", "Новая статья из выделенного"), ("New Note at Cursor", "Новая заметка в позиции курсора"), diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 223dba543..d7ac7ce01 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -1232,6 +1232,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Load DTD…", "Завантажити DTD…"), ("Location:", "Розташування:"), ("Lock Guides", "Заблокувати напрямні"), + ("Lock Column Guides", "Заблокувати напрямні колонок"), ("Miter Limit:", "Межа гострого з’єднання:"), ("New Article from Selection", "Нова стаття з виділення"), ("New Note at Cursor", "Нова примітка в позиції курсора"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0844b95a4..3674b3e81 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -296,6 +296,7 @@ pub struct UiState { pub align_to: String, /// Properties > Text Style tab: 0 = Paragraph Styles, 1 = Character Styles. pub text_style_tab: u8, + /// View › Grids & Guides › Lock Guides: ruler guides can't be dragged. pub guides_locked: bool, pub smart_guides: bool, #[serde(default = "default_true")] diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index da5819e6f..fb43f8cb9 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -180,6 +180,7 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[ ("view.frameEdges", "Show/Hide Frame Edges", Some("Cmd+H"), "{}"), ("view.rulers", "Show/Hide Rulers", Some("Cmd+R"), "{}"), ("view.guides", "Show/Hide Guides", Some("Cmd+;"), "{}"), + ("view.lockGuides", "Lock Guides", Some("Cmd+Alt+;"), "{on?: bool} — ruler guides can't be dragged; toggles without `on`"), ("view.snapToGuides", "Snap to Guides", Some("Cmd+Shift+;"), "{}"), ("view.snapToDocumentGrid", "Snap to Document Grid", None, "{}"), ("view.smartGuides", "Smart Guides", None, "{}"), @@ -812,6 +813,8 @@ pub const MENUS: &[(&str, &[&str])] = &[ "<", ">Grids & Guides", "ui:view.guides", + "ui:view.lockGuides", + "cmd:view.lockColumnGuides", "ui:view.snapToGuides", "ui:view.snapToDocumentGrid", "ui:view.smartGuides", @@ -1505,6 +1508,10 @@ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option flag(&mut app.ui.rulers), "view.guides" => flag(&mut app.ui.guides), + "view.lockGuides" => { + app.ui.guides_locked = p.get("on").and_then(Value::as_bool).unwrap_or(!app.ui.guides_locked); + Ok(json!(app.ui.guides_locked)) + } "view.snapToGuides" => flag(&mut app.ui.snap_to_guides), "view.snapToDocumentGrid" => flag(&mut app.ui.snap_to_document_grid), "view.smartGuides" => flag(&mut app.ui.smart_guides), @@ -2364,6 +2371,8 @@ pub fn checked(app: &DesignApp, id: &str, params: &Value) -> Option { "view.typicalDisplay" => app.ui.display_quality == designcraft_render::DisplayQuality::Typical, "view.highQualityDisplay" => app.ui.display_quality == designcraft_render::DisplayQuality::High, "view.guides" => app.ui.guides, + "view.lockGuides" => app.ui.guides_locked, + "view.lockColumnGuides" => app.session.active().is_some_and(|d| d.doc.settings.column_guides_locked), "view.snapToGuides" => app.ui.snap_to_guides, "view.snapToDocumentGrid" => app.ui.snap_to_document_grid, "view.smartGuides" => app.ui.smart_guides, @@ -3969,6 +3978,26 @@ mod tests { assert!(run_ui(&mut app, "view.proofSetup", &json!({"target": "nope"})).unwrap().is_err()); } + #[test] + fn lock_guides_and_lock_column_guides_are_checked_in_grids_and_guides() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let view = menu_ids("View"); + assert!(view.contains(&"view.lockGuides") && view.contains(&"view.lockColumnGuides")); + assert_eq!(ui_label("view.lockGuides").and_then(|c| c.1), Some("Cmd+Alt+;")); + // Lock Guides: off at first, toggles, and `on` sets it. + assert_eq!(checked(&app, "view.lockGuides", &Value::Null), Some(false)); + assert_eq!(app.run("view.lockGuides", json!({})).unwrap(), json!(true)); + assert!(app.ui.guides_locked); + assert_eq!(app.run("view.lockGuides", json!({"on": true})).unwrap(), json!(true)); + assert_eq!(checked(&app, "view.lockGuides", &Value::Null), Some(true)); + assert_eq!(app.run("view.lockGuides", json!({"on": false})).unwrap(), json!(false)); + // Lock Column Guides: the document's setting, on in new documents. + assert_eq!(checked(&app, "view.lockColumnGuides", &Value::Null), Some(true)); + app.run("view.lockColumnGuides", json!({})).unwrap(); + assert_eq!(checked(&app, "view.lockColumnGuides", &Value::Null), Some(false)); + } + #[test] fn fitting_has_indesigns_shortcuts() { // LYH Studio episode 6 (7:00): "Fit Content to Frame (Ctrl + Shift + Alt + C)" fills the diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 399cc34e7..1cbd623a6 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -521,7 +521,9 @@ fn document_sections(app: &mut DesignApp, ui: &mut Ui) { if smart != app.ui.smart_guides { let _ = app.run("view.smartGuides", json!({})); } - app.ui.guides_locked = locked; + if locked != app.ui.guides_locked { + let _ = app.run("view.lockGuides", json!({"on": locked})); + } rule(ui); section(ui, crate::i18n::tr(&app.ui.language, "Quick Actions"), true); let (a, b) = button_pair(ui, crate::i18n::tr(&app.ui.language, "Import File"), crate::i18n::tr(&app.ui.language, "Insert Page")); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 89fe4d401..92b86f0f1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -268,7 +268,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Text engine: Knuth–Plass paragraph composer and single-line composer, dictionary hyphenation (public-domain Moby list + our own trained Liang patterns), justification with word/letter/glyph-scaling ranges, keep options (keep with next, keep lines together — at start/end of paragraph by default, as in InDesign — widows/orphans), balance ragged lines, optical margin alignment, hyphenation zone/limit, columns, threading across frames and spreads, tabs, bullets/numbering, rules, shading, baseline grid, first-baseline options, vertical justification, wrap exclusions, overset detection, caret/hit testing. - FID2: IDML underline/strikethrough Text Color resets survive style inheritance and roundtrip. Raster and PDF paint underlines behind glyphs, retain strikethrough above, and center rules on their offsets; synthetic overlap tests cover both backends. - Rendering: vello_cpu (SIMD, multithreaded) — pages, items, images with mip levels, gradients, composed text. -- UI (egui): application bar + menus, Control panel (object and text modes), Tools panel with flyouts and the Fill/Stroke proxy (D, X, Shift+X, / as `color.*` commands), document tabs, rulers, pasteboard, guides (margins, columns, bleed, baseline grid), document grid (View ▸ Grids & Guides, ⌘', on the snap positions, behind or in front of items), frame edges, selection handles, text ports and threads, Properties / Pages / Layers dock, Swatches (InDesign's header: Fill/Stroke proxy, Formatting Affects Container/Text, Tint; a swatch goes to the fill or stroke in front; New Color Group / New Swatch / Delete Swatch row), Styles, Character, Paragraph, Stroke, Text Wrap panels, New Document and Preferences dialogs, Quick Apply (⌘Return), 4 brightness themes. +- UI (egui): application bar + menus, Control panel (object and text modes), Tools panel with flyouts and the Fill/Stroke proxy (D, X, Shift+X, / as `color.*` commands), document tabs, rulers, pasteboard, guides (margins, columns, bleed, baseline grid), document grid (View ▸ Grids & Guides, ⌘', on the snap positions, behind or in front of items), Lock Guides (⌥⌘;) and Lock Column Guides (View ▸ Grids & Guides; Lock Column Guides is saved with the document and in IDML), frame edges, selection handles, text ports and threads, Properties / Pages / Layers dock, Swatches (InDesign's header: Fill/Stroke proxy, Formatting Affects Container/Text, Tint; a swatch goes to the fill or stroke in front; New Color Group / New Swatch / Delete Swatch row), Styles, Character, Paragraph, Stroke, Text Wrap panels, New Document and Preferences dialogs, Quick Apply (⌘Return), 4 brightness themes. - Pen tool, Direct Selection anchor/handle editing, rotate from corners, Rotate/Scale/Shear tools, Eyedropper, snapping & smart guides, Align/Distribute, Find/Change (text + GREP), Story Editor, Paragraph Style Options, Effects panel, hidden characters, native macOS menu bar, measured InDesign 2026 look (Medium Dark): Properties sections per selection state, 21 pt spinner fields with arithmetic, Contextual Task Bar, inverse (black) text selection, Pages panel with drag-and-drop reorder / parent apply, Layers panel with per-object rows, expandable groups and drag-and-drop reorder of layers and objects (the selection square moves the selection to another layer). - Tools: Selection (click, marquee, move, Alt-duplicate, resize handles), Direct Selection, Type (draw frame, click caret, select, type; Option/Alt+Left/Right kerns at the caret or tracks a selection by the Kerning/Tracking increment, ×5 with Cmd/Ctrl; words move with Cmd+Left/Right on macOS and Ctrl+Left/Right elsewhere), Rectangle/Ellipse/Polygon (+ frame variants), Line, Hand, Zoom. - PDF export (krilla): real selectable text with embedded font subsets, DeviceCMYK/RGB + spot Separations, bleed boxes, crop/bleed marks + page info, pages or spreads, PDF/A-2b (PDF/X-4 output intent pending) — `file.exportPdf`, File › Export PDF…, `designcraft-cli run --export out.pdf`. File › Export PDF… now opens an "Export PDF" options dialog (General / Compression / Marks and Bleeds / Advanced) and remembers the last-used settings across exports and sessions. From 1ba06027ac1ea5c5cc9cca04e31d199a66ea170c Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 22 Oct 2026 02:23:32 -0400 Subject: [PATCH 09/29] Layout: Margins and Columns keeps dragged columns, which scale with the margin box (#1096) (#1172) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * IDML: keep column guides that were dragged off centre (#1096) InDesign records dragged column guides in `MarginPreference ColumnsPositions`, as pairs of offsets from the margin box's left edge. The importer discarded them and divided the columns evenly, so a page whose gutter the designer had moved came back with it in the middle: on a 450 pt margin box, `0 150 170 450` was read as columns at 215 and 235. `Columns::positions` already existed, documented as "Custom column positions (after dragging column guides)", but nothing set it and nothing read it. Now `Page::column_rects` returns the custom rects when they are set — that one method is what the canvas guides, snapping, threading and the first frame of a placed story all go through, so they follow the dragged gutter — the importer fills it, and the exporter writes the page's real positions instead of recomputing an even split, so the round trip keeps them. `layout.marginsAndColumns` clears them when a count or gutter is set, which is what InDesign's Margins and Columns does. Without that the stale positions would outrank the new value and the dialog would look broken. Verified against InDesign-authored IDML rather than assumed, which settled two things. The attribute is written whether or not anything was dragged — a real page's values are exactly its even split — so an even set is dropped rather than marking every imported page custom and freezing its columns; the tolerance for that comparison only absorbs float noise, about 1e-14 pt on that page. And `` is a `` child, not a `` one, which is where this importer already looks: the reporter's missing ruler guide was 099fbd2, landed the day the ticket was filed, not a second bug. That commit left `lib.rs` still listing guides as ignored on import; corrected. * IDML: custom column positions are validated and round-trip (#1096) Columns::positions are used only when they are 2 x count finite edges, ascending from 0 to the margin box width (within 0.01 pt); anything else is the even split, in Page::column_rects, on IDML import (bounded parse, checked against the page's margin box) and on IDML export. Columns::with_gutter_moved moves one gutter's pair of guides between its neighbours for the coming column-guide command. ROADMAP: drop four progress-log lines the #1121 merge duplicated and move its line to the top. * Layout: Margins and Columns keeps dragged columns unless the count or gutter changes (#1096) * Layout: a new margin or page width resets dragged columns (#1096) * Layout: #1121's margin case follows the new-width rule (#1096) * Layout: dragged columns scale with a new margin or page width (#1096) * Layout: the page-width test drags a page whose columns are its own (#1096) * ROADMAP: the progress line lands in one commit after the guide PRs --------- Co-authored-by: Hamza --- crates/engine/src/cmd/layout.rs | 210 ++++++++++++++++++++++++++++++-- 1 file changed, 200 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 667bb927b..7df8aebf6 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -88,6 +88,7 @@ fn dist(r: designcraft_geom::Rect, x: f64) -> f64 { /// Apply the `margins`, `columns` and `gutter` params of `layout.marginsAndColumns` to one page. fn set_margins_columns(pg: &mut designcraft_doc::Page, p: &Value) { + let width_before = pg.margin_rect().width(); match p.get("margins") { Some(Value::Number(n)) => pg.margins = Margins::uniform(n.as_f64().unwrap_or(36.0)), Some(v @ Value::Object(_)) => { @@ -97,18 +98,62 @@ fn set_margins_columns(pg: &mut designcraft_doc::Page, p: &Value) { } _ => {} } - // Setting a count or a gutter re-divides the columns evenly, as InDesign's Margins and - // Columns does: dragged column positions are what the new value replaces. + scale_columns(pg, width_before); + // A new count or gutter re-divides the columns evenly: dragged column positions are what + // the new value replaces. The dialog always sends both, so an unchanged value keeps them. if let Some(c) = p.get("columns").and_then(Value::as_u64) { - pg.columns.count = (c as u32).clamp(1, 216); - pg.columns.positions = None; + let c = u32::try_from(c).unwrap_or(u32::MAX).clamp(1, 216); + if c != pg.columns.count { + pg.columns.count = c; + pg.columns.positions = None; + } } - if let Some(g) = p.get("gutter").and_then(Value::as_f64) { - pg.columns.gutter = g.max(0.0); + if let Some(g) = p.get("gutter").and_then(Value::as_f64).filter(|g| g.is_finite()) { + let g = g.max(0.0); + if (g - pg.columns.gutter).abs() > GUTTER_TOLERANCE { + pg.columns.gutter = g; + pg.columns.positions = None; + } + } +} + +/// Dragged column positions are measured across the margin box. When the box was +/// `width_before` wide and now has another width, they scale with it, as InDesign's do; a set +/// that doesn't scale into a valid one goes back to the even split rather than stay hidden. +fn scale_columns(pg: &mut designcraft_doc::Page, width_before: f64) { + let width = pg.margin_rect().width(); + if (width - width_before).abs() <= GUTTER_TOLERANCE { + return; + } + let Some(positions) = pg.columns.positions.as_mut() else { return }; + let factor = width / width_before; + if factor.is_finite() && factor > 0.0 { + positions.iter_mut().for_each(|p| *p *= factor); + // The ends sit exactly on the margins whatever the rounding. + if let Some(first) = positions.first_mut() { + *first = 0.0; + } + if let Some(last) = positions.last_mut() { + *last = width; + } + } + if pg.columns.valid_positions(width).is_none() { pg.columns.positions = None; } } +/// Gives `pg` the page width `width`, scaling its dragged columns with the margin box. +fn set_page_width(pg: &mut designcraft_doc::Page, width: f64) { + let before = pg.margin_rect().width(); + pg.width = width; + scale_columns(pg, before); +} + +/// How far a gutter may differ from the page's and still count as unchanged, in points. The +/// dialog shows the gutter in the ruler unit, rounded (inches to four decimals: up to 0.0036 pt +/// off), so an OK that leaves the field alone sends back a slightly different number. +const GUTTER_TOLERANCE: f64 = 0.01; + pub fn specs() -> Vec { vec![ cmd!( @@ -481,7 +526,7 @@ pub fn specs() -> Vec { for sp in d.spreads.iter_mut().chain(d.parents.iter_mut()) { let sp = std::sync::Arc::make_mut(sp); for pg in &mut sp.pages { - pg.width = d.settings.page_width; + set_page_width(pg, d.settings.page_width); pg.height = d.settings.page_height; } sp.relayout(); @@ -961,7 +1006,7 @@ pub(crate) fn resize_pages_from(d: &mut designcraft_doc::Document, pages: &[usiz let dw = w.map_or(0.0, |w| w.max(1.0) - pg.width); let dh = h.map_or(0.0, |h| h.max(1.0) - pg.height); if let Some(w) = w { - pg.width = w.max(1.0); + set_page_width(pg, w.max(1.0)); } if let Some(h) = h { pg.height = h.max(1.0); @@ -1689,10 +1734,155 @@ mod adjust_tests { assert_eq!(pg.columns.positions, None); assert!((pg.column_rects()[1].x0 - pg.column_rects()[0].x1 - 24.0).abs() < 1e-6); - // Margins alone leave them alone: the offsets are relative to the margin box. + // Margins that keep the margin box's width leave them alone; a new width scales them. drag(&mut s); - s.execute("layout.marginsAndColumns", &json!({"margins": 72})).unwrap(); + s.execute("layout.marginsAndColumns", &json!({"margins": {"top": 72, "bottom": 72, "inside": 36, "outside": 36}})).unwrap(); assert_eq!(s.doc().unwrap().doc.page(0).unwrap().columns.positions, Some(vec![0.0, 100.0, 130.0, 540.0])); + s.execute("layout.marginsAndColumns", &json!({"margins": 72})).unwrap(); + assert_scaled(s.doc().unwrap().doc.page(0).unwrap().columns.positions.clone(), 468.0); + } + + /// The params the Margins and Columns dialog sends on OK: every margin, the count and the + /// gutter, whether or not the user changed them. + fn dialog_params(margin: f64, columns: u32, gutter: f64) -> serde_json::Value { + json!({"margins": {"top": margin, "bottom": margin, "inside": margin, "outside": margin}, + "columns": columns, "gutter": gutter, "adjustLayout": false}) + } + + const DRAGGED: [f64; 4] = [0.0, 100.0, 130.0, 540.0]; + + fn dragged() -> designcraft_doc::Columns { + designcraft_doc::Columns { count: 2, gutter: 12.0, positions: Some(DRAGGED.to_vec()) } + } + + /// `positions` are [`DRAGGED`] scaled from its 540 pt margin box to one `width` wide. + #[track_caller] + fn assert_scaled(positions: Option>, width: f64) { + let want: Vec = DRAGGED.iter().map(|p| p * width / 540.0).collect(); + let got = positions.unwrap_or_default(); + assert!(got.len() == want.len() && got.iter().zip(&want).all(|(g, w)| (g - w).abs() < 1e-6), "{got:?} ≠ {want:?}"); + } + + /// An OK in the dialog keeps dragged columns unless the count or gutter it sends differs. + #[test] + fn the_dialog_keeps_dragged_columns_unless_the_count_or_gutter_changes() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 1, "facingPages": false})).unwrap(); + let drag = |s: &mut Session| { + s.edit(|d, _| { + std::sync::Arc::make_mut(&mut d.spreads[0]).pages[0].columns = dragged(); + Ok(()) + }) + .unwrap(); + }; + let positions = |s: &Session| s.doc().unwrap().doc.page(0).unwrap().columns.positions.clone(); + + // The same count and gutter (the gutter as an inch field rounds it) keep them in use. + drag(&mut s); + s.execute("layout.marginsAndColumns", &dialog_params(36.0, 2, 12.0)).unwrap(); + assert_eq!(positions(&s), Some(DRAGGED.to_vec())); + s.execute("layout.marginsAndColumns", &dialog_params(36.0, 2, 0.1667 * 72.0)).unwrap(); + assert_eq!(positions(&s), Some(DRAGGED.to_vec())); + let rects = s.doc().unwrap().doc.page(0).unwrap().column_rects(); + assert!((rects[0].x1 - rects[0].x0 - 100.0).abs() < 1e-6, "the dragged columns are in use: {rects:?}"); + + // Top and bottom margins leave the margin box's width alone, and the columns with it. + let mut taller = dialog_params(36.0, 2, 12.0); + taller["margins"]["top"] = json!(72.0); + taller["margins"]["bottom"] = json!(72.0); + s.execute("layout.marginsAndColumns", &taller).unwrap(); + assert_eq!(positions(&s), Some(DRAGGED.to_vec())); + + // A new width scales them with the margin box, and the old width scales them back. + s.execute("layout.marginsAndColumns", &dialog_params(72.0, 2, 12.0)).unwrap(); + assert_scaled(positions(&s), 468.0); + let rects = s.doc().unwrap().doc.page(0).unwrap().column_rects(); + assert!((rects[0].x1 - rects[0].x0 - 100.0 * 468.0 / 540.0).abs() < 1e-6, "the scaled columns are in use: {rects:?}"); + s.execute("layout.marginsAndColumns", &dialog_params(36.0, 2, 12.0)).unwrap(); + assert_scaled(positions(&s), 540.0); + + // A new count resets them. + drag(&mut s); + s.execute("layout.marginsAndColumns", &dialog_params(36.0, 3, 12.0)).unwrap(); + let pg = s.doc().unwrap().doc.page(0).unwrap().clone(); + assert_eq!((pg.columns.count, pg.columns.positions), (3, None)); + + // So does a new gutter. + drag(&mut s); + s.execute("layout.marginsAndColumns", &dialog_params(36.0, 2, 18.0)).unwrap(); + let pg = s.doc().unwrap().doc.page(0).unwrap().clone(); + assert_eq!((pg.columns.gutter, pg.columns.positions), (18.0, None)); + } + + /// A page of another width (Page Size, Document Setup) scales its dragged columns. + #[test] + fn a_new_page_width_scales_dragged_columns() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 1, "facingPages": false})).unwrap(); + let drag = |s: &mut Session| { + s.edit(|d, _| { + // A dragged page's columns are its own (`local_margins`), as the drag will make them. + let pg = &mut std::sync::Arc::make_mut(&mut d.spreads[0]).pages[0]; + pg.columns = dragged(); + pg.local_margins = true; + Ok(()) + }) + .unwrap(); + }; + let positions = |s: &Session| s.doc().unwrap().doc.page(0).unwrap().columns.positions.clone(); + + drag(&mut s); + s.execute("layout.pageSize", &json!({"pages": [1], "height": 900})).unwrap(); + assert_eq!(positions(&s), Some(DRAGGED.to_vec()), "a new height keeps them"); + s.execute("layout.pageSize", &json!({"pages": [1], "width": 700})).unwrap(); + assert_scaled(positions(&s), 628.0); + s.execute("layout.pageSize", &json!({"pages": [1], "width": 612})).unwrap(); + assert_scaled(positions(&s), 540.0); + + drag(&mut s); + s.execute("layout.documentSetup", &json!({"width": 700})).unwrap(); + assert_scaled(positions(&s), 628.0); + } + + /// Parent pages follow the same rule, and the document pages that follow them see it. + #[test] + fn the_dialog_keeps_a_parents_dragged_columns_unless_the_count_or_gutter_changes() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 1, "facingPages": false})).unwrap(); + let drag = |s: &mut Session| { + s.edit(|d, _| { + std::sync::Arc::make_mut(&mut d.parents[0]).pages[0].columns = dragged(); + d.sync_parent_margins(); + Ok(()) + }) + .unwrap(); + }; + let positions = |s: &Session| { + let d = &s.doc().unwrap().doc; + (d.parents[0].pages[0].columns.positions.clone(), d.page(0).unwrap().columns.positions.clone()) + }; + let on_parent = |m: f64, c: u32, g: f64| { + let mut p = dialog_params(m, c, g); + p["parent"] = json!(0); + p + }; + + drag(&mut s); + assert_eq!(positions(&s), (Some(DRAGGED.to_vec()), Some(DRAGGED.to_vec()))); + s.execute("layout.marginsAndColumns", &on_parent(36.0, 2, 12.0)).unwrap(); + assert_eq!(positions(&s), (Some(DRAGGED.to_vec()), Some(DRAGGED.to_vec()))); + s.execute("layout.marginsAndColumns", &on_parent(48.0, 2, 12.0)).unwrap(); + let (parent, follower) = positions(&s); + assert_scaled(parent, 516.0); + assert_scaled(follower, 516.0); + + drag(&mut s); + s.execute("layout.marginsAndColumns", &on_parent(36.0, 3, 12.0)).unwrap(); + assert_eq!(positions(&s), (None, None)); + + drag(&mut s); + s.execute("layout.marginsAndColumns", &on_parent(36.0, 2, 24.0)).unwrap(); + assert_eq!(positions(&s), (None, None)); } } From a912438ab868ad9de2bbe9005cef30d285dfbd32 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 22 Oct 2026 02:26:38 -0400 Subject: [PATCH 10/29] Layout: autoflow, inserted pages and new parents follow dragged columns, mirrored across sides (#1096) (#1173) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * IDML: keep column guides that were dragged off centre (#1096) InDesign records dragged column guides in `MarginPreference ColumnsPositions`, as pairs of offsets from the margin box's left edge. The importer discarded them and divided the columns evenly, so a page whose gutter the designer had moved came back with it in the middle: on a 450 pt margin box, `0 150 170 450` was read as columns at 215 and 235. `Columns::positions` already existed, documented as "Custom column positions (after dragging column guides)", but nothing set it and nothing read it. Now `Page::column_rects` returns the custom rects when they are set — that one method is what the canvas guides, snapping, threading and the first frame of a placed story all go through, so they follow the dragged gutter — the importer fills it, and the exporter writes the page's real positions instead of recomputing an even split, so the round trip keeps them. `layout.marginsAndColumns` clears them when a count or gutter is set, which is what InDesign's Margins and Columns does. Without that the stale positions would outrank the new value and the dialog would look broken. Verified against InDesign-authored IDML rather than assumed, which settled two things. The attribute is written whether or not anything was dragged — a real page's values are exactly its even split — so an even set is dropped rather than marking every imported page custom and freezing its columns; the tolerance for that comparison only absorbs float noise, about 1e-14 pt on that page. And `` is a `` child, not a `` one, which is where this importer already looks: the reporter's missing ruler guide was 099fbd2, landed the day the ticket was filed, not a second bug. That commit left `lib.rs` still listing guides as ignored on import; corrected. * IDML: custom column positions are validated and round-trip (#1096) Columns::positions are used only when they are 2 x count finite edges, ascending from 0 to the margin box width (within 0.01 pt); anything else is the even split, in Page::column_rects, on IDML import (bounded parse, checked against the page's margin box) and on IDML export. Columns::with_gutter_moved moves one gutter's pair of guides between its neighbours for the coming column-guide command. ROADMAP: drop four progress-log lines the #1121 merge duplicated and move its line to the top. * Layout: autoflow, inserted pages and new parents follow dragged columns (#1096) * IDML: a page without its own margins checks the default's column positions against its width (#1096) * Layout: dragged columns mirror when a page changes side (#1096) * Layout: pages that follow a one-page parent take its dragged columns mirrored (#1096) * ROADMAP: the progress line lands in one commit after the guide PRs --------- Co-authored-by: Hamza --- crates/doc/src/build.rs | 83 +++++++++++++++++++++++++- crates/doc/src/page.rs | 61 ++++++++++++++++++- crates/engine/src/cmd/datamerge/mod.rs | 2 +- crates/engine/src/cmd/inspect.rs | 4 +- crates/engine/src/cmd/layout.rs | 53 ++++++++++++++-- crates/engine/src/cmd/place_text.rs | 39 +++++++++++- 6 files changed, 231 insertions(+), 11 deletions(-) diff --git a/crates/doc/src/build.rs b/crates/doc/src/build.rs index f8ae0ec19..d4500f7ce 100644 --- a/crates/doc/src/build.rs +++ b/crates/doc/src/build.rs @@ -343,6 +343,8 @@ impl Document { let mut pages: Vec<(Page, Vec>)> = Vec::new(); let mut parity: Vec = Vec::new(); let mut kept: Vec<(usize, Arc)> = Vec::new(); + // Whether each shuffled page was a left page, to mirror its dragged columns if it moves. + let mut was_left: BTreeMap = BTreeMap::new(); let mut abs = 0; for sp in self.spreads.drain(..) { if !sp.allow_shuffle && sp.pages.len() > 1 { @@ -350,8 +352,9 @@ impl Document { kept.push((pages.len(), sp)); continue; } - for _ in &sp.pages { + for p in &sp.pages { parity.push(odd.get(abs).copied().unwrap_or(abs % 2 == 0)); + was_left.insert(p.id, p.side == PageSide::Left); abs += 1; } let mut sp = Arc::unwrap_or_clone(sp); @@ -445,6 +448,19 @@ impl Document { out.insert(at, sp); } self.spreads = out; + // A page that crosses the spine keeps its inside and outside margins, so its margin box + // mirrors; its dragged column guides mirror with it, as in InDesign. + let crossed = |p: &Page| was_left.get(&p.id).is_some_and(|&l| l != (p.side == PageSide::Left)) && p.columns.positions.is_some(); + for sp in &mut self.spreads { + if !sp.pages.iter().any(crossed) { + continue; + } + for p in &mut Arc::make_mut(sp).pages { + if crossed(&*p) { + p.columns = p.columns.mirrored(p.margin_rect().width()); + } + } + } // Pages can change sides, and so parent pages. self.sync_parent_margins(); } @@ -466,6 +482,10 @@ impl Document { if let Some(t) = &template { p.width = t.width; p.height = t.height; + // Dragged column guides too: the same width and margins keep them valid. + // They are taken as for this single page; repaginating mirrors them if the + // page lands on a left page. + p.columns.positions = p.columns_from(t).positions; } ids.push(p.id); p @@ -675,7 +695,7 @@ impl Document { if page.local_margins { continue; } - let Some(src) = self.parent_page(page).filter(|q| !q.same_margins(page)).map(|q| (q.margins, q.columns.clone())) else { + let Some(src) = self.parent_page(page).filter(|q| !q.same_margins(page)).map(|q| (q.margins, page.columns_from(q))) else { continue; }; if let Some(page) = Arc::make_mut(&mut self.spreads[si]).pages.get_mut(pi) { @@ -879,6 +899,65 @@ mod tests { assert!(d.delete_pages(&[0, 1]).is_err()); } + /// Pages inserted after a page with dragged column guides keep them, as they keep its column + /// count and gutter; pages that follow a parent take the parent's. + #[test] + fn inserted_pages_keep_dragged_columns() { + let dragged = Columns { count: 2, gutter: 12.0, positions: Some(vec![0.0, 100.0, 130.0, 540.0]) }; + let widths = |p: &Page| p.column_rects().iter().map(|r| r.width()).collect::>(); + let mut d = Document::new(&NewDocument { pages: 1, facing_pages: false, ..Default::default() }); + let pg = &mut Arc::make_mut(&mut d.spreads[0]).pages[0]; + (pg.columns, pg.local_margins) = (dragged.clone(), true); + d.insert_pages(Some(0), 2, None).unwrap(); + for i in 1..3 { + let p = d.page(i).unwrap(); + assert_eq!(p.columns, dragged, "page {i}"); + assert_eq!(widths(p), vec![100.0, 410.0], "page {i}"); + } + + let mut d = Document::new(&NewDocument { pages: 1, facing_pages: false, ..Default::default() }); + Arc::make_mut(&mut d.parents[0]).pages[0].columns = dragged.clone(); + d.sync_parent_margins(); + d.insert_pages(Some(0), 1, d.parents.first().map(|p| p.id)).unwrap(); + assert_eq!(d.page(1).map(widths), Some(vec![100.0, 410.0])); + } + + /// A right page whose gutter was dragged toward the spine keeps it there when inserting a + /// page before it makes it a left page: its dragged columns mirror across the margin box. + #[test] + fn dragged_columns_mirror_when_a_page_changes_side() { + let mut d = Document::new(&NewDocument { pages: 1, facing_pages: true, ..Default::default() }); + let pg = &mut Arc::make_mut(&mut d.spreads[0]).pages[0]; + assert_eq!(pg.side, PageSide::Right); + let w = pg.margin_rect().width(); + (pg.columns, pg.local_margins) = (Columns { count: 2, gutter: 12.0, positions: Some(vec![0.0, 100.0, 112.0, w]) }, true); + let id = pg.id; + // How far the gutter's spine-side edge is from the margin on the spine side. + let from_spine = |p: &Page| { + let (m, c) = (p.margin_rect(), p.column_rects()); + match p.side { + PageSide::Left => m.x1 - c[1].x0, + _ => c[0].x1 - m.x0, + } + }; + assert!((from_spine(d.page(0).unwrap()) - 100.0).abs() < 1e-9); + + d.insert_pages(None, 1, None).unwrap(); + let moved = d.page(1).unwrap(); + assert_eq!((moved.id, moved.side), (id, PageSide::Left)); + assert!((from_spine(moved) - 100.0).abs() < 1e-9, "{:?}", moved.column_rects()); + let widths: Vec = moved.column_rects().iter().map(|r| r.width()).collect(); + assert!((widths[0] - (w - 112.0)).abs() < 1e-9 && (widths[1] - 100.0).abs() < 1e-9, "{widths:?}"); + // The inserted page is a right page like the one it copies: no mirroring. + assert_eq!(d.page(0).unwrap().columns.positions, Some(vec![0.0, 100.0, 112.0, w])); + + // Moving it back to the right undoes the mirror. + d.delete_pages(&[0]).unwrap(); + let back = d.page(0).unwrap(); + assert_eq!(back.side, PageSide::Right); + assert!((from_spine(back) - 100.0).abs() < 1e-9, "{:?}", back.column_rects()); + } + #[test] fn items_travel_with_pages() { let mut d = Document::new(&NewDocument { pages: 3, ..Default::default() }); diff --git a/crates/doc/src/page.rs b/crates/doc/src/page.rs index d1a77d78e..7041f7ed8 100644 --- a/crates/doc/src/page.rs +++ b/crates/doc/src/page.rs @@ -106,6 +106,15 @@ impl Columns { *r = (at + width).min(hi); valid_column_positions(&pos, self.count, margin_width).then_some(pos) } + + /// These columns reflected across a margin box `margin_width` wide, as on the facing page + /// across the spine: each custom position `p` becomes `margin_width - p`, in reverse order so + /// they stay ascending. Count and gutter stay; positions that are not valid (see + /// [`Columns::valid_positions`]) become `None`, the even split, which mirrors onto itself. + pub fn mirrored(&self, margin_width: f64) -> Columns { + let positions = self.valid_positions(margin_width).map(|p| p.iter().rev().map(|&v| inside(margin_width - v, margin_width)).collect()); + Columns { count: self.count, gutter: self.gutter, positions } + } } /// `v` limited to `0..=w` without `clamp`, which panics when `w` is NaN. @@ -304,9 +313,10 @@ impl Page { pub fn bounds(&self) -> Rect { Rect::new(self.x, 0.0, self.x + self.width, self.height) } - /// Same margins and columns as `other`. + /// Same margins and columns as `other`, with `other`'s columns as it would take them from this + /// page: mirrored when one is a left page and the other isn't. pub fn same_margins(&self, other: &Page) -> bool { - self.margins == other.margins && self.columns == other.columns + self.margins == other.margins && other.columns_from(self) == other.columns } /// Left and right margins resolved for the page side (inside is at the spine). pub fn left_right_margins(&self) -> (f64, f64) { @@ -315,6 +325,16 @@ impl Page { _ => (self.margins.inside, self.margins.outside), } } + /// `src`'s columns as they fall on this page: the same when both pages put their inside + /// margin on the same physical side, mirrored across `src`'s margin box when one is a left + /// page and the other is not, as InDesign mirrors dragged column guides across the spine. + pub fn columns_from(&self, src: &Page) -> Columns { + if (self.side == PageSide::Left) == (src.side == PageSide::Left) { + src.columns.clone() + } else { + src.columns.mirrored(src.margin_rect().width()) + } + } /// The live area inside the margins. pub fn margin_rect(&self) -> Rect { let (l, r) = self.left_right_margins(); @@ -602,6 +622,43 @@ mod tests { assert_eq!(c.with_gutter_moved(f64::NAN, 0, 100.0), None); } + /// Mirroring reflects dragged columns across the margin box and keeps them ascending; an + /// invalid set becomes the even split. + #[test] + fn mirrored_columns_reflect_across_the_margin_box() { + let two = Columns { count: 2, gutter: 12.0, positions: Some(vec![0.0, 100.0, 130.0, 540.0]) }; + assert_eq!(two.mirrored(540.0), Columns { positions: Some(vec![0.0, 410.0, 440.0, 540.0]), ..two.clone() }); + assert_eq!(two.mirrored(540.0).mirrored(540.0), two); + + let three = Columns { count: 3, gutter: 10.0, positions: Some(vec![0.0, 50.0, 60.0, 200.0, 210.0, 300.0]) }; + let m = three.mirrored(300.0); + assert_eq!(m.positions, Some(vec![0.0, 90.0, 100.0, 240.0, 250.0, 300.0])); + assert!(m.valid_positions(300.0).is_some()); + + // Positions that do not fit the margin box, or none at all, mirror to the even split. + assert_eq!(two.mirrored(600.0).positions, None); + assert_eq!(two.mirrored(f64::NAN).positions, None); + let unsorted = Columns { positions: Some(vec![0.0, 130.0, 100.0, 540.0]), ..two.clone() }; + assert_eq!(unsorted.mirrored(540.0).positions, None); + let even = Columns { positions: None, ..two.clone() }; + assert_eq!(even.mirrored(540.0), even); + + // A left page takes a right page's columns mirrored, a page on the same side as they are. + let mut r = page(PageSide::Right, 612.0); + r.columns = Columns { count: 2, gutter: 12.0, positions: Some(vec![0.0, 100.0, 130.0, 522.0]) }; + let l = page(PageSide::Left, 0.0); + assert_eq!(l.columns_from(&r).positions, Some(vec![0.0, 392.0, 422.0, 522.0])); + assert_eq!(page(PageSide::Right, 0.0).columns_from(&r), r.columns); + + // A left page holding them mirrored has the same margins as that right page (a one-page + // parent in a facing document); holding them unmirrored, it doesn't. + let mut l = page(PageSide::Left, 0.0); + l.columns = l.columns_from(&r); + assert!(r.same_margins(&l)); + l.columns = r.columns.clone(); + assert!(!r.same_margins(&l)); + } + #[test] fn spread_spine_and_hit() { let s = Spread { diff --git a/crates/engine/src/cmd/datamerge/mod.rs b/crates/engine/src/cmd/datamerge/mod.rs index b29ae3b3c..38b543ff7 100644 --- a/crates/engine/src/cmd/datamerge/mod.rs +++ b/crates/engine/src/cmd/datamerge/mod.rs @@ -436,7 +436,7 @@ fn assign_page(dst: &mut Document, abs: usize, from: &Page) { p.guides = from.guides.clone(); p.parent = from.parent; p.margins = from.margins; - p.columns = from.columns.clone(); + p.columns = p.columns_from(from); p.local_margins = from.local_margins; p.width = from.width; p.height = from.height; diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs index f003fd30a..c1ddcf036 100644 --- a/crates/engine/src/cmd/inspect.rs +++ b/crates/engine/src/cmd/inspect.rs @@ -85,7 +85,9 @@ fn inspect(s: &mut Session, _p: &Value) -> Result { let abs = d.first_page_of_spread(si) + pi; json!({"index": abs, "name": d.page_name(abs), "bounds": [p.x, 0.0, p.x + p.width, p.height], "side": p.side, "parent": p.parent.and_then(|pid| d.parents.iter().find(|x| x.id == pid)).and_then(|x| x.parent.as_ref()).map(|i| i.label()), - "margins": p.margins, "columns": p.columns.count}) + "margins": p.margins, "columns": p.columns.count, "gutter": p.columns.gutter, + "customColumns": p.columns.valid_positions(p.margin_rect().width()).is_some(), + "columnRects": p.column_rects().iter().map(|r| [r.x0, r.y0, r.x1, r.y1]).collect::>()}) }).collect::>(), "items": sp.items.iter().map(|i| item_json(i)).collect::>(), }) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 7df8aebf6..9016c3848 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -246,8 +246,9 @@ pub fn specs() -> Vec { let nsp = std::sync::Arc::make_mut(&mut d.spreads[nsi]); let pg = &mut nsp.pages[npi]; let dx = pg.x - src.x; - (pg.width, pg.height, pg.margins, pg.columns, pg.liquid) = - (src.width, src.height, src.margins, src.columns.clone(), src.liquid); + // A copy on the other side of the spine has its dragged columns mirrored. + let columns = pg.columns_from(src); + (pg.width, pg.height, pg.margins, pg.columns, pg.liquid) = (src.width, src.height, src.margins, columns, src.liquid); pg.guides = src.guides.clone(); for g in pg.guides.iter_mut().filter(|g| g.orientation == designcraft_doc::Orientation::Vertical) { g.position += dx; @@ -301,8 +302,20 @@ pub fn specs() -> Vec { let name = str_param(p, "name").unwrap_or("Parent").to_string(); s.edit(|d, _| { let prefix = str_param(p, "prefix").map(str::to_string).unwrap_or_else(|| d.next_parent_prefix()); - let m = d.page(0).map(|p| (p.columns.count, p.columns.gutter, p.margins)).unwrap_or((1, 12.0, Margins::uniform(36.0))); - let id = d.add_parent(&prefix, &name, m.0, m.1, m.2); + let src = d.page(0).cloned(); + let (columns, margins) = + src.as_ref().map_or_else(|| (designcraft_doc::Columns::default(), Margins::uniform(36.0)), |p| (p.columns.clone(), p.margins)); + let id = d.add_parent(&prefix, &name, columns.count, columns.gutter, margins); + // Dragged column guides carry over to the parent pages they still fit, mirrored + // on the parent page across the spine from the first page. + if let (Some(src), Some(sp)) = (&src, d.parents.iter_mut().find(|x| x.id == id)) { + for pg in &mut std::sync::Arc::make_mut(sp).pages { + let columns = pg.columns_from(src); + if columns.valid_positions(pg.margin_rect().width()).is_some() { + pg.columns.positions = columns.positions; + } + } + } Ok(json!({"id": id.0, "prefix": prefix})) }) }), @@ -2182,6 +2195,38 @@ mod parent_tests { assert_eq!(r, json!({"on": false, "parent": null})); assert!(!s.doc().unwrap().editing_parents); } + + /// A new parent takes the first page's columns, dragged column guides included: the right + /// parent page as the first (right) page has them, the left one mirrored across the spine. + /// `document.inspect` reports where those columns are. + #[test] + fn a_new_parent_keeps_dragged_columns() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({"pages": 1})).unwrap(); + let dragged = designcraft_doc::Columns { count: 2, gutter: 12.0, positions: Some(vec![0.0, 100.0, 130.0, 540.0]) }; + // There is no command for dragging a column guide yet, so set what an import would leave. + s.edit(|d, _| { + let pg = &mut std::sync::Arc::make_mut(&mut d.spreads[0]).pages[0]; + (pg.columns, pg.local_margins) = (dragged.clone(), true); + Ok(()) + }) + .unwrap(); + let id = s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let parent = d.parents.iter().find(|p| p.id.0 == id).unwrap(); + assert_eq!(parent.pages.len(), 2); + let side = |s: designcraft_doc::PageSide| parent.pages.iter().find(|p| p.side == s).unwrap(); + let (left, right) = (side(designcraft_doc::PageSide::Left), side(designcraft_doc::PageSide::Right)); + assert_eq!(right.columns, dragged); + assert_eq!(right.column_rects().iter().map(|r| r.width()).collect::>(), vec![100.0, 410.0]); + assert_eq!(left.columns.positions, Some(vec![0.0, 410.0, 440.0, 540.0])); + assert_eq!(left.column_rects().iter().map(|r| r.width()).collect::>(), vec![410.0, 100.0]); + + let inspect = s.execute("document.inspect", &json!({})).unwrap(); + let page = &inspect["spreads"][0]["pages"][0]; + assert_eq!((page["columns"].clone(), page["customColumns"].clone()), (json!(2), json!(true)), "{page}"); + assert_eq!(page["columnRects"][0], json!([36.0, 36.0, 136.0, 756.0]), "{page}"); + } } #[cfg(test)] diff --git a/crates/engine/src/cmd/place_text.rs b/crates/engine/src/cmd/place_text.rs index fa93d4e40..c54b55084 100644 --- a/crates/engine/src/cmd/place_text.rs +++ b/crates/engine/src/cmd/place_text.rs @@ -277,7 +277,7 @@ pub(crate) fn autoflow(d: &mut Document, sid: StoryId, max_pages: usize, cmd: &s if added >= max_pages { return Err(bad(cmd, format!("autoflow stopped after {max_pages} pages"))); } - let per_page = if vertical { 1 } else { d.page(page).map_or(1, |p| p.columns.count.max(1) as usize) }; + let per_page = if vertical { 1 } else { d.page(page).map_or(1, |p| p.column_rects().len().max(1)) }; let pages = want.div_ceil(per_page).clamp(1, max_pages - added); let parent = d.page_loc(page).and_then(|(si, pi)| d.spreads[si].pages[pi].parent); new_pages.extend(d.insert_pages(Some(page), pages, parent)?); @@ -511,6 +511,43 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// Autoflow follows dragged column guides: one frame per dragged column, on the first page and + /// on every page it adds. + #[test] + fn autoflow_sets_frames_on_dragged_columns() { + let dir = std::env::temp_dir().join(format!("dc-place-dragged-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("long.txt"); + std::fs::write(&path, vec!["Lorem ipsum dolor sit amet, consectetur adipiscing elit. ".repeat(12); 40].join("\n")).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"preset": "Letter", "pages": 1, "columns": 2, "gutter": 18, "margins": 54})).unwrap(); + // The margin box is 504 pt wide; the gutter is dragged left. There is no command for + // dragging a column guide yet, so set what an import would leave, on the parent. + let dragged = designcraft_doc::Columns { count: 2, gutter: 18.0, positions: Some(vec![0.0, 150.0, 170.0, 504.0]) }; + s.edit(|d, _| { + for pg in &mut std::sync::Arc::make_mut(&mut d.parents[0]).pages { + pg.columns = dragged.clone(); + } + d.sync_parent_margins(); + Ok(()) + }) + .unwrap(); + let r = s.execute("file.place", &json!({"path": path.to_string_lossy(), "page": 1, "autoflow": true})).unwrap(); + assert_eq!(r["overset"], false, "{r}"); + let d = &s.doc().unwrap().doc; + assert!(d.page_count() >= 3, "{r}"); + let frames = &d.story(StoryId(r["story"].as_u64().unwrap())).unwrap().frames; + assert!(frames.len() > 2 * (d.page_count() - 1), "{} frames", frames.len()); + for (i, f) in frames.iter().enumerate() { + let page = d.page_of_item(*f).unwrap(); + assert_eq!(page, i / 2, "frame {i}"); + let m = d.page(page).unwrap().margin_rect(); + let (x0, x1) = [(0.0, 150.0), (170.0, 504.0)][i % 2]; + assert_eq!(d.item(*f).unwrap().bounds(), Rect::new(m.x0 + x0, m.y0, m.x0 + x1, m.y1), "frame {i}"); + } + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn autoflow_keeps_the_frame_the_user_drew() { let dir = std::env::temp_dir().join(format!("dc-place-drawn-{}", std::process::id())); From c3382b422c4ba6664a6ccf564ca9c50b49f55f4a Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 22 Oct 2026 02:26:52 -0400 Subject: [PATCH 11/29] Guides: a dragged ruler guide snaps to guides, margins, columns and objects (#1542) * Guides: a dragged guide shows where it is (#1282) While a guide is dragged out of a ruler or moved, a label beside the pointer reads X: or Y: and the guide's place, in the ruler units and measured the way the rulers measure (from the zero point, and from the page origin when rulers restart per page). * Guides: keep the drag readout inside the canvas Near the canvas's right or bottom edge the readout flips to the other side of the pointer, and it is kept inside the canvas in every case (readout_at). * Guides: the drag readout measures the spread under the pointer The readout measured from the spread in the middle of the view (where the rulers measure), but a guide is dropped on the spread under the pointer, so with spreads above one another the number shown could differ from the guide's place. It now measures that spread (ruler_pieces_of). * Guides: no readout for an existing guide over another spread An existing guide moves only on its own spread (guide_drag), so dropped over another it stays where it was: the readout no longer shows a place there it won't go. * #1282: guide selection commands (guide.select, guide.selectAll, guide.deselect, guide.moveBy) * #1282: select ruler guides on the canvas, X/Y in the Control bar and Properties * #1282: guides take clicks over objects, a new guide is selected, group drag preview * Guides: a dragged ruler guide snaps to guides, margins, columns and objects (#1221) --------- Co-authored-by: SBaksa --- crates/tools/src/frame.rs | 2 + crates/tools/src/lib.rs | 5 + crates/tools/src/select.rs | 4 + crates/tools/src/snap.rs | 58 +++++- crates/tools/src/xform.rs | 2 + crates/ui-egui/src/canvas.rs | 193 +++++++++++++++++--- crates/ui-egui/src/guide_selection_tests.rs | 78 +++++++- docs/target-app-parity.md | 2 +- 8 files changed, 307 insertions(+), 37 deletions(-) diff --git a/crates/tools/src/frame.rs b/crates/tools/src/frame.rs index 4b52e2ee5..ff65e7ce7 100644 --- a/crates/tools/src/frame.rs +++ b/crates/tools/src/frame.rs @@ -76,6 +76,7 @@ pub(crate) fn snapped_drag_rect(cx: &ToolContext, sr: SpreadRef, sa: Point, end: x_edges, y_edges, exclude: &[], + exclude_guides: &[], copying: false, lengths: [length_on(x_edges, r.width()), length_on(y_edges, r.height())], angle: None, @@ -160,6 +161,7 @@ fn line_hit(cx: &ToolContext, spread: SpreadRef, point: Point, len: Option) x_edges: [true, true, true], y_edges: [true, true, true], exclude: &[], + exclude_guides: &[], copying: false, lengths: [len, None], angle: None, diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index b5153e183..f0fd68019 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -191,6 +191,9 @@ pub enum Gesture { Create, Rotate, Point, + /// A ruler guide being dragged: one line on one axis, with no size or spacing to match and + /// no pull from the baseline grid. + Guide, } pub struct SnapRequest<'a> { @@ -202,6 +205,8 @@ pub struct SnapRequest<'a> { /// Top, center, bottom. pub y_edges: [bool; 3], pub exclude: &'a [ItemId], + /// Ruler guides that are not targets: the ones being dragged. + pub exclude_guides: &'a [designcraft_doc::GuideSel], pub copying: bool, /// Proposed width and height for the dimensions pass. None when that length is not being set. pub lengths: [Option; 2], diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index b3d3780f2..866003102 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -929,6 +929,7 @@ impl Tool for SelectionTool { x_edges, y_edges, exclude: &exclude, + exclude_guides: &[], copying: ev.mods.alt && !content, lengths: [None, None], angle: None, @@ -1002,6 +1003,7 @@ impl Tool for SelectionTool { x_edges, y_edges, exclude: &exclude, + exclude_guides: &[], copying: false, lengths: [axis_length(x_edges, proposed.width(), pad_x), axis_length(y_edges, proposed.height(), pad_y)], angle: None, @@ -1054,6 +1056,7 @@ impl Tool for SelectionTool { x_edges: [false, false, false], y_edges: [false, false, false], exclude: &exclude, + exclude_guides: &[], copying: false, lengths: [None, None], angle: Some(resulting), @@ -1092,6 +1095,7 @@ impl Tool for SelectionTool { x_edges: [true, true, true], y_edges: [true, true, true], exclude: &exclude, + exclude_guides: &[], copying: false, lengths: [None, None], angle: None, diff --git a/crates/tools/src/snap.rs b/crates/tools/src/snap.rs index 0cbc9aadd..11da46178 100644 --- a/crates/tools/src/snap.rs +++ b/crates/tools/src/snap.rs @@ -31,6 +31,7 @@ pub fn snap_point(cx: &ToolContext, sr: SpreadRef, p: Point) -> (Point, Vec, axis: Axis) -> Option= 0 while the line is inside the page /// (the bottom edge is not a line, matching the canvas). An increment of 0 or less skips the /// pass. `relative_to` and `view_threshold` are not read, and hiding the baseline grid does not -/// turn this off. Only a page the rect crosses on x contributes. +/// turn this off. Only a page the rect crosses on x contributes. A dragged ruler guide +/// ([`Gesture::Guide`]) doesn't snap to it. fn pass_baseline(cx: &ToolContext, req: &SnapRequest<'_>, axis: Axis, tol: f64) -> Option { - if !matches!(axis, Axis::Y) || !cx.snap.snap_to_guides { + if !matches!(axis, Axis::Y) || !cx.snap.snap_to_guides || matches!(req.gesture, Gesture::Guide) { return None; } let baseline = &cx.doc.settings.baseline_grid; @@ -1000,7 +1002,8 @@ fn push_parent_lengths(out: &mut Vec, cx: &ToolContext, req: &SnapRequest<' /// /// A page guide attracts when the moving rect overlaps that page on the other axis. A spread /// guide uses the spread bounds. Locked guides are included, and so are the guides a page shows -/// from its parent page. A guide is a target only when `Guide::visible_in` accepts it. +/// from its parent page. A guide is a target only when `Guide::visible_in` accepts it, and not +/// when the request excludes it (the guides being dragged). fn pass_guides(cx: &ToolContext, req: &SnapRequest<'_>, axis: Axis, tol: f64) -> Option { if !cx.snap.snap_to_guides || !cx.snap.show_guides { return None; @@ -1010,10 +1013,15 @@ fn pass_guides(cx: &ToolContext, req: &SnapRequest<'_>, axis: Axis, tol: f64) -> let flags = axis_flags(req, axis); let (moving_lo, moving_hi) = perp_ends(req.rect, axis); let mut best: Option = None; - for page in &sp.pages { + for (pi, page) in sp.pages.iter().enumerate() { let page_bounds = page.bounds(); - // The page's own guides, then those it shows from its parent page. - for guide in page.guides.iter().cloned().chain(cx.doc.parent_guides(page)) { + // The page's own guides, less the excluded ones, then those it shows from its parent page. + let own = page + .guides + .iter() + .enumerate() + .filter(|&(gi, _)| !req.exclude_guides.contains(&designcraft_doc::GuideSel { spread: req.spread, page: pi, index: gi })); + for guide in own.map(|(_, g)| g.clone()).chain(cx.doc.parent_guides(page)) { if !guide.visible_in(cx.doc) || !guide.position.is_finite() || guide.orientation != axis_orientation(axis) { continue; } @@ -1427,6 +1435,7 @@ mod tests { x_edges: [false, false, false], y_edges: [true, true, true], exclude: &[], + exclude_guides: &[], copying: false, lengths: [None, None], angle: None, @@ -1443,6 +1452,7 @@ mod tests { x_edges: [true, true, true], y_edges: [false, false, false], exclude, + exclude_guides: &[], copying: false, lengths: [None, None], angle: None, @@ -1475,6 +1485,7 @@ mod tests { x_edges: [false, false, false], y_edges: [true, true, true], exclude: &[moving], + exclude_guides: &[], copying: false, lengths: [None, None], angle: None, @@ -1504,6 +1515,7 @@ mod tests { x_edges: [true, true, true], y_edges: [false, false, false], exclude: &[moving], + exclude_guides: &[], copying: false, lengths: [None, None], angle: None, @@ -1515,6 +1527,28 @@ mod tests { assert!(hit.guides.is_empty()); } + /// A dragged guide is not its own target: excluded, the guide at 104 doesn't pull a line at 102. + /// Nor does the baseline grid pull it. + #[test] + fn excluded_guide_is_not_a_target() { + let far = Rect::new(400.0, 400.0, 420.0, 420.0); + let (doc, _, _) = doc_with_items(far, far, 104.0); + let cache = Cache::new(); + let layout = CanvasLayout::new(&doc, false); + let sel = Selection::default(); + let cx = ctx_on(&doc, &sel, &cache, &layout); + let line = Rect::new(102.0, 100.0, 102.0, 300.0); + let dragged = [designcraft_doc::GuideSel { spread: SpreadRef::Doc(0), page: 0, index: 0 }]; + let hit = snap(&cx, move_req(line, &[])); + assert!((hit.delta.x - 2.0).abs() < 1e-6, "{:?}", hit.delta); + let hit = snap(&cx, SnapRequest { exclude_guides: &dragged, ..move_req(line, &[]) }); + assert_eq!(hit.delta.x, 0.0); + // A dragged guide passes the baseline grid's lines (36 + 12n), which a moved object meets. + let flat = Rect::new(100.0, 86.0, 300.0, 86.0); + assert!((snap(&cx, y_req(flat)).delta.y - -2.0).abs() < 1e-6); + assert_eq!(snap(&cx, SnapRequest { gesture: Gesture::Guide, ..y_req(flat) }).delta.y, 0.0); + } + #[test] fn parent_centered_stroke_attracts_at_the_outer_edge() { let mut doc = Document::new(&NewDocument::default()); @@ -1542,6 +1576,7 @@ mod tests { x_edges: [true, false, false], y_edges: [false, false, false], exclude: &[], + exclude_guides: &[], copying: false, lengths: [None, None], angle: None, @@ -1569,6 +1604,7 @@ mod tests { x_edges: [true, true, true], y_edges: [false, false, false], exclude: &[moving], + exclude_guides: &[], copying: false, lengths: [None, None], angle: None, @@ -1599,6 +1635,7 @@ mod tests { x_edges: [false, false, true], y_edges: [false, false, false], exclude: &[moving], + exclude_guides: &[], copying: false, lengths: [None, None], angle: None, @@ -1630,6 +1667,7 @@ mod tests { x_edges: [true, false, false], y_edges: [false, false, false], exclude: &[id], + exclude_guides: &[], copying: true, lengths: [None, None], angle: None, @@ -1666,6 +1704,7 @@ mod tests { x_edges: [true, false, false], y_edges: [false, false, false], exclude: &[original], + exclude_guides: &[], copying: true, lengths: [None, None], angle: None, @@ -1793,6 +1832,7 @@ mod tests { x_edges: [false, false, true], y_edges: [false, false, false], exclude: &[], + exclude_guides: &[], copying: false, lengths: [Some(197.0), None], angle: None, @@ -1836,6 +1876,7 @@ mod tests { x_edges: [false, false, true], y_edges: [false, false, false], exclude: &[], + exclude_guides: &[], copying: false, lengths: [Some(82.0), None], angle: None, @@ -1871,6 +1912,7 @@ mod tests { x_edges: [true, true, true], y_edges: [false, false, false], exclude: &[moving], + exclude_guides: &[], copying: false, lengths: [None, None], angle: None, @@ -2009,6 +2051,7 @@ mod tests { x_edges: [true, true, true], y_edges: [false, false, false], exclude: &[], + exclude_guides: &[], copying: false, lengths: [Some(38.0), None], angle: None, @@ -2041,6 +2084,7 @@ mod tests { x_edges: [false, false, false], y_edges: [false, false, false], exclude: &[], + exclude_guides: &[], copying: false, lengths: [None, None], angle: Some(28.0), @@ -2085,6 +2129,7 @@ mod tests { x_edges: [false, false, false], y_edges: [false, false, false], exclude: &[], + exclude_guides: &[], copying: false, lengths: [None, None], angle: Some(28.0), @@ -2157,6 +2202,7 @@ mod tests { x_edges: [false, false, false], y_edges: [false, false, false], exclude: &[], + exclude_guides: &[], copying: false, lengths: [None, None], angle: Some(angle), diff --git a/crates/tools/src/xform.rs b/crates/tools/src/xform.rs index 258bcd62b..561ad0c86 100644 --- a/crates/tools/src/xform.rs +++ b/crates/tools/src/xform.rs @@ -100,6 +100,7 @@ impl Tool for XformTool { x_edges: [false, false, false], y_edges: [false, false, false], exclude: &exclude, + exclude_guides: &[], copying: false, lengths: [None, None], angle: Some(resulting), @@ -151,6 +152,7 @@ impl Tool for XformTool { x_edges, y_edges, exclude: &exclude, + exclude_guides: &[], copying: false, lengths: [length_on(x_edges, w, pad_x), length_on(y_edges, h, pad_y)], angle: None, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 322f75d80..f8ddc9487 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -539,10 +539,18 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { && let Some(p) = g.at { let col = Color32::from_rgb(74, 227, 255); + let spot = guide_spot(app, &xf, &g); + let line = spot.as_ref().map_or(p, |s| s.screen); let (a, b) = match g.orientation { - designcraft_doc::Orientation::Horizontal => (pos2(rect.min.x, p.y), pos2(rect.max.x, p.y)), - designcraft_doc::Orientation::Vertical => (pos2(p.x, rect.min.y), pos2(p.x, rect.max.y)), + designcraft_doc::Orientation::Horizontal => (pos2(rect.min.x, line.y), pos2(rect.max.x, line.y)), + designcraft_doc::Orientation::Vertical => (pos2(line.x, rect.min.y), pos2(line.x, rect.max.y)), }; + // What caught it, as for a moved object. + for mark in spot.iter().flat_map(|s| &s.marks) { + if let Overlay::Guide { a, b } = mark { + painter.line_segment([xf.to_screen(*a), xf.to_screen(*b)], Stroke::new(1.0, t.smart_guide)); + } + } // A new guide from the rulers with the Page tool is a liquid guide: dashed. if g.from.is_none() && app.session.tool_id() == "page" { dashed(&painter, a, b, Stroke::new(1.0, col), 6.0, 3.0); @@ -2881,6 +2889,9 @@ struct GuideDrag { from: Option<(designcraft_doc::SpreadRef, usize, usize)>, /// Pointer position (screen). at: Option, + /// Modifiers held at the pointer's last move: Shift snaps to the ruler's ticks, Command + /// suspends snapping. + mods: egui::Modifiers, } const GUIDE_PRESS: &str = "canvas_guide_press"; @@ -2921,10 +2932,12 @@ fn guide_measure(app: &DesignApp, xf: &Xf, g: &GuideDrag) -> Option<(&'static st let p = g.at?; let st = app.session.active()?; let layout = CanvasLayout::new(&st.doc, st.editing_parents); - let c = xf.to_canvas(p); - // Measured on the spread under the pointer, which the guide is dropped on (`guide_drag`), - // as the rulers measure that spread: not the one in the middle of the view. - let slot = layout.spread_at(c).and_then(|(r, _)| layout.slot(r)).or_else(|| current_slot(app, &layout).and_then(|i| layout.slots.get(i)))?; + // Measured where the guide is dropped (`guide_drag`): its snapped spot, on the spread under + // the pointer, as the rulers measure that spread, not the one in the middle of the view. + let (c, slot) = match guide_spot(app, xf, g) { + Some(spot) => (layout.to_canvas(spot.spread, spot.sp), layout.slot(spot.spread)?), + None => (xf.to_canvas(p), current_slot(app, &layout).and_then(|i| layout.slots.get(i))?), + }; // An existing guide moves only on its own spread (`guide_drag`): over another, dropping it // leaves it where it was, so there is no place to show. if g.from.is_some_and(|(r, _, _)| r != slot.spread) { @@ -2943,6 +2956,119 @@ fn guide_measure(app: &DesignApp, xf: &Xf, g: &GuideDrag) -> Option<(&'static st value.is_finite().then_some((label, value, unit)) } +/// Where a dragged ruler guide is (#1221). +struct GuideSpot { + /// The spread under the pointer. + spread: SpreadRef, + /// The pointer in that spread's coordinates. + pointer: Point, + /// [`Self::pointer`] with the guide's axis snapped. + sp: Point, + /// [`Self::sp`] on screen, where the preview line goes. + screen: Pos2, + /// Alignment marks (canvas coordinates) when an object or page edge or center caught it. + marks: Vec, +} + +/// Where the guide of drag `g` is: its axis (x for a vertical guide, y for a horizontal one) +/// snapped as a moved object's is, to ruler guides, margins, columns, bleed, the document grid and +/// smart-guide targets (not the baseline grid, which would catch a horizontal guide almost +/// anywhere). Shift snaps to the ruler's ticks instead and Command suspends snapping. The guides +/// being dragged are not targets. An existing guide over another spread, where it +/// can't be dropped, stays at the pointer. The preview, the readout and the drop all read it. +/// `None` with no spread under the pointer. +fn guide_spot(app: &DesignApp, xf: &Xf, g: &GuideDrag) -> Option { + let p = g.at?; + let st = app.session.active()?; + let layout = CanvasLayout::new(&st.doc, st.editing_parents); + let (r, pointer) = layout.spread_at(xf.to_canvas(p))?; + let spot = |sp: Point, marks: Vec| GuideSpot { spread: r, pointer, sp, screen: xf.to_screen(layout.to_canvas(r, sp)), marks }; + if g.mods.command || g.from.is_some_and(|(from, _, _)| from != r) { + return Some(GuideSpot { spread: r, pointer, sp: pointer, screen: p, marks: Vec::new() }); + } + let vertical = matches!(g.orientation, designcraft_doc::Orientation::Vertical); + let place = |v: f64| if vertical { Point::new(v, pointer.y) } else { Point::new(pointer.x, v) }; + if g.mods.shift { + let slot = layout.slot(r)?; + let at = ruler_tick_of(&st.doc, slot, g.orientation, xf.zoom, pointer).map_or(pointer, place); + return Some(spot(at, Vec::new())); + } + let spread = st.doc.spread(r)?; + // Not targets: the dragged guide, and the others of a selected group, which move with it. + let exclude: Vec = match g.from { + Some((sr, pi, gi)) if drags_group(app, GuideSel { spread: sr, page: pi, index: gi }) => st.selection.guides.to_vec(), + Some((sr, pi, gi)) => vec![GuideSel { spread: sr, page: pi, index: gi }], + None => Vec::new(), + }; + // How far the guide reaches across its axis: its page, or the whole spread. + let page = match g.from { + Some((_, pi, gi)) => spread.pages.get(pi).filter(|pg| pg.guides.get(gi).is_some_and(|guide| !guide.spread)), + None => spread.pages.iter().find(|pg| pg.bounds().contains(pointer)), + }; + let reach = page.map_or_else(|| spread.bounds(), |pg| pg.bounds()); + let (at, rect, x_edges, y_edges) = if vertical { + (pointer.x, DRect::new(pointer.x, reach.y0, pointer.x, reach.y1), [true; 3], [false; 3]) + } else { + (pointer.y, DRect::new(reach.x0, pointer.y, reach.x1, pointer.y), [false; 3], [true; 3]) + }; + let cx = designcraft_tools::ToolContext { + doc: &st.doc, + selection: &st.selection, + cache: &app.session.cache, + layout: &layout, + zoom: xf.zoom.max(1e-6), + layer: st.active_layer, + snap: app.ui.snap_view(), + unit: app.ui.units, + stroke_in_front: false, + }; + let s = designcraft_tools::snap::snap( + &cx, + designcraft_tools::SnapRequest { + spread: r, + gesture: designcraft_tools::Gesture::Guide, + rect, + x_edges, + y_edges, + exclude: &[], + exclude_guides: &exclude, + copying: false, + lengths: [None, None], + angle: None, + radius: 0.0, + pointer, + }, + ); + let snapped = at + if vertical { s.delta.x } else { s.delta.y }; + Some(if snapped.is_finite() { spot(place(snapped), s.guides) } else { spot(pointer, Vec::new()) }) +} + +/// The nearest ruler tick to spread point `sp` along a guide of `orientation`'s axis, in spread +/// coordinates: the horizontal ruler's (the piece under the point) where that axis runs across the +/// screen, else the vertical ruler's. `None` when the ruler has no ticks there. +fn ruler_tick_of(doc: &Document, slot: &SpreadSlot, orientation: designcraft_doc::Orientation, zoom: f64, sp: Point) -> Option { + let vertical = matches!(orientation, designcraft_doc::Orientation::Vertical); + // A quarter-turned spread runs its x axis down the screen. + let across = vertical == slot.rotation.is_multiple_of(2); + let c = slot.to_canvas(sp); + let pieces = ruler_pieces_of(doc, slot, doc.zero_point()); + let step = |unit: designcraft_geom::Unit| { + let (major, sub) = unit.ruler_ticks(zoom); + let step = major / f64::from(sub.max(1)); + (step.is_finite() && step > 0.0).then_some(step) + }; + let tick = |v: f64, o: f64, step: f64| o + ((v - o) / step).round() * step; + let c = if across { + let &(_, _, o) = pieces.iter().find(|(from, to, _)| *from <= c.x && c.x < *to).or(pieces.first())?; + Point::new(tick(c.x, o.x, step(doc.settings.horizontal_units)?), c.y) + } else { + let o = pieces.first()?.2; + Point::new(c.x, tick(c.y, o.y, step(doc.settings.vertical_units)?)) + }; + let s = slot.to_spread(c); + Some(if vertical { s.x } else { s.y }).filter(|v| v.is_finite()) +} + /// The guide under a screen point (within 3 px), as (spread, page, index, orientation). fn guide_at(app: &DesignApp, xf: &Xf, p: Pos2) -> Option<(designcraft_doc::SpreadRef, usize, usize, designcraft_doc::Orientation)> { let st = app.session.active()?; @@ -2994,7 +3120,7 @@ fn guide_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rec None }; if let Some(orientation) = orientation { - drag = Some(GuideDrag { orientation, from: None, at: Some(o) }); + drag = Some(GuideDrag { orientation, from: None, at: Some(o), mods: egui::Modifiers::NONE }); } } else if rect.contains(o) && matches!(app.session.tool_id(), "selection" | "directSelection") @@ -3007,13 +3133,14 @@ fn guide_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rec let _ = app.run("guide.select", json!({"spread": r, "page": pi, "index": gi})); } ui.data_mut(|d| d.insert_temp(egui::Id::new(GUIDE_PRESS), GuidePress { origin: o, shift })); - drag = Some(GuideDrag { orientation, from: Some((r, pi, gi)), at: Some(o) }); + drag = Some(GuideDrag { orientation, from: Some((r, pi, gi)), at: Some(o), mods: egui::Modifiers::NONE }); } } let Some(mut g) = drag else { return false }; if let Some(p) = latest { g.at = Some(p); } + g.mods = ui.input(|i| i.modifiers); if !released { ui.ctx().set_cursor_icon(match g.orientation { designcraft_doc::Orientation::Horizontal => egui::CursorIcon::ResizeVertical, @@ -3041,12 +3168,11 @@ fn guide_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rec // Dragging one of several selected guides moves (or deletes) them all. let group = g.from.is_some_and(|(spread, page, index)| drags_group(app, GuideSel { spread, page, index })); let on_canvas = rect.contains(p); - let target = app.session.active().and_then(|st| { - let layout = CanvasLayout::new(&st.doc, st.editing_parents); - let (r, sp) = layout.spread_at(xf.to_canvas(p))?; - let spread = st.doc.spread(r)?; - let on_page = spread.pages.iter().position(|pg| pg.bounds().contains(sp)); - Some((r, sp, on_page)) + // Placed where the preview showed it (snapped); the page under the pointer owns a new guide. + let target = guide_spot(app, xf, &g).and_then(|spot| { + let spread = app.session.active()?.doc.spread(spot.spread)?; + let on_page = spread.pages.iter().position(|pg| pg.bounds().contains(spot.pointer)); + Some((spot.spread, spot.sp, on_page)) }); let pos_of = |sp: Point| match g.orientation { designcraft_doc::Orientation::Horizontal => sp.y, @@ -3065,7 +3191,7 @@ fn guide_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rec let _ = app.run("guide.delete", json!({"spread": r, "page": pi, "index": gi})); } (Some((r, _, _)), true, Some((tr, _, _))) if tr == r && group => { - if let Some((dx, dy)) = press.and_then(|press| guide_drag_delta(app, xf, &g, press.origin, p)) { + if let Some((dx, dy)) = press.and_then(|press| guide_drag_delta(app, xf, &g, press.origin)) { let _ = app.run("guide.moveBy", json!({"dx": dx, "dy": dy})); } } @@ -3093,18 +3219,19 @@ fn drags_group(app: &DesignApp, from: GuideSel) -> bool { app.session.active().is_some_and(|st| st.selection.guides.len() > 1 && st.selection.guides.contains(&from)) } -/// How far a drag of the existing guide `g.from`, pressed at `origin` and now at `p` (screen), -/// moves guides, in spread coordinates: the dragged guide goes to the pointer, the other selected -/// guides as far along their own axis as the pointer moved. `None` while the pointer is not over -/// the guide's own spread, where a drop leaves it in place. -fn guide_drag_delta(app: &DesignApp, xf: &Xf, g: &GuideDrag, origin: Pos2, p: Pos2) -> Option<(f64, f64)> { +/// How far a drag of the existing guide `g.from`, pressed at `origin` (screen), moves guides, in +/// spread coordinates: the dragged guide goes to its [`guide_spot`], the other selected guides as +/// far along their own axis as it moved. `None` while the pointer is not over the guide's own +/// spread, where a drop leaves it in place. +fn guide_drag_delta(app: &DesignApp, xf: &Xf, g: &GuideDrag, origin: Pos2) -> Option<(f64, f64)> { let (r, pi, gi) = g.from?; - let st = app.session.active()?; - let layout = CanvasLayout::new(&st.doc, st.editing_parents); - let (tr, sp) = layout.spread_at(xf.to_canvas(p))?; - if tr != r { + let spot = guide_spot(app, xf, g)?; + if spot.spread != r { return None; } + let sp = spot.sp; + let st = app.session.active()?; + let layout = CanvasLayout::new(&st.doc, st.editing_parents); let start = layout.slot(r)?.to_spread(xf.to_canvas(origin)); let at = st.doc.spread(r)?.pages.get(pi)?.guides.get(gi)?.position; let (dx, dy) = match g.orientation { @@ -3130,7 +3257,7 @@ fn moving_guides(app: &DesignApp, xf: &Xf, rect: Rect, g: &GuideDrag, press: Gui if !rect.contains(p) || (p - press.origin).length() <= GUIDE_CLICK_SLOP { return None; } - let (dx, dy) = guide_drag_delta(app, xf, g, press.origin, p)?; + let (dx, dy) = guide_drag_delta(app, xf, g, press.origin)?; let from = GuideSel { spread, page, index }; let guides = if drags_group(app, from) { app.session.active()?.selection.guides.iter().copied().collect() } else { [from].into_iter().collect() }; Some(MovingGuides { guides, dx, dy }) @@ -4231,7 +4358,7 @@ mod tests { for (orientation, label, want) in [(designcraft_doc::Orientation::Vertical, "X", at.x - 100.0), (designcraft_doc::Orientation::Horizontal, "Y", at.y - 50.0)] { - let g = GuideDrag { orientation, from: None, at: Some(dest) }; + let g = GuideDrag { orientation, from: None, at: Some(dest), mods: egui::Modifiers::NONE }; let (l, v, _) = guide_measure(h.state(), &xf, &g).unwrap(); assert_eq!(l, label); assert!((v - want).abs() < 1e-6, "{label}: {v} vs {want}"); @@ -4270,7 +4397,12 @@ mod tests { let inside = Point::new(last.bounds.center().x, last.bounds.y0 + (last.bounds.y1 - last.bounds.y0) * 0.3); let (r, sp) = layout.spread_at(inside).unwrap(); assert_eq!(r, last.spread); - let g = GuideDrag { orientation: designcraft_doc::Orientation::Horizontal, from: None, at: Some(xf.to_screen(inside)) }; + let g = GuideDrag { + orientation: designcraft_doc::Orientation::Horizontal, + from: None, + at: Some(xf.to_screen(inside)), + mods: egui::Modifiers::NONE, + }; let (label, v, _) = guide_measure(h.state(), &xf, &g).unwrap(); assert_eq!(label, "Y"); // The guide would be stored at `sp.y` on that spread, which its ruler reads from the zero point. @@ -4279,7 +4411,12 @@ mod tests { // An existing guide of another spread can't be dropped there (it only moves on its own // spread): no readout over this one, a readout over its own. let first = layout.slots[current].spread; - let moving = GuideDrag { orientation: designcraft_doc::Orientation::Horizontal, from: Some((first, 0, 0)), at: Some(xf.to_screen(inside)) }; + let moving = GuideDrag { + orientation: designcraft_doc::Orientation::Horizontal, + from: Some((first, 0, 0)), + at: Some(xf.to_screen(inside)), + mods: egui::Modifiers::NONE, + }; assert!(guide_measure(h.state(), &xf, &moving).is_none(), "an existing guide over another spread"); let own = layout.slots[current].bounds; let over_own = Point::new(own.center().x, own.y0 + (own.y1 - own.y0) * 0.3); diff --git a/crates/ui-egui/src/guide_selection_tests.rs b/crates/ui-egui/src/guide_selection_tests.rs index 23ad14c91..6c41d0122 100644 --- a/crates/ui-egui/src/guide_selection_tests.rs +++ b/crates/ui-egui/src/guide_selection_tests.rs @@ -243,7 +243,8 @@ fn dragging_one_of_several_selected_guides_previews_them_all() { let mut h = with_guides(); h.state_mut().run("guide.select", json!({"guides": [{"page": 0, "index": 0}, {"page": 0, "index": 2}]})).unwrap(); let (a, b) = (screen_of(&h, 200.0, 600.0), screen_of(&h, 250.0, 620.0)); - let g = GuideDrag { orientation: designcraft_doc::Orientation::Vertical, from: Some((SpreadRef::Doc(0), 0, 0)), at: Some(b) }; + let g = + GuideDrag { orientation: designcraft_doc::Orientation::Vertical, from: Some((SpreadRef::Doc(0), 0, 0)), at: Some(b), mods: Modifiers::NONE }; let press = GuidePress { origin: a, shift: false }; let app = h.state(); let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); @@ -253,6 +254,79 @@ fn dragging_one_of_several_selected_guides_previews_them_all() { moved.sort_unstable(); assert_eq!(moved, [0, 2]); // The drop moves them by the same amounts. - let (dx, dy) = guide_drag_delta(app, &xf, &g, a, b).unwrap(); + let (dx, dy) = guide_drag_delta(app, &xf, &g, a).unwrap(); assert_eq!((dx, dy), (m.dx, m.dy)); } + +/// Spread points per screen pixel at the harness's view. +fn pt_per_px(h: &Harness<'_, DesignApp>) -> f64 { + let app = h.state(); + 1.0 / Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).zoom +} + +/// A letter page with two columns: the left column's right side. +fn with_columns() -> (Harness<'static, DesignApp>, f64) { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"preset": "Letter", "columns": 2, "gutter": 18, "margins": 54})).unwrap(); + app.run("guide.add", json!({"orientation": "vertical", "position": 200.0})).unwrap(); + let side = app.session.doc().unwrap().doc.spreads[0].pages[0].column_rects()[0].x1; + (harness(app), side) +} + +/// A dragged guide snaps to a column guide as a moved object does (#1221). +#[test] +fn a_dragged_guide_snaps_to_a_column_guide() { + let (mut h, side) = with_columns(); + let near = side + 1.5 * pt_per_px(&h); + let (a, b) = (screen_of(&h, 200.0, 600.0), screen_of(&h, near, 600.0)); + drag(&mut h, a, b); + assert_eq!(positions(&h), [side]); +} + +/// Snap to Guides and Smart Guides off: the guide goes where the pointer is. +#[test] +fn with_snapping_off_a_dragged_guide_stays_at_the_pointer() { + let (mut h, side) = with_columns(); + h.state_mut().ui.snap_to_guides = false; + h.state_mut().ui.smart_guides = false; + let near = side + 1.5 * pt_per_px(&h); + let (a, b) = (screen_of(&h, 200.0, 600.0), screen_of(&h, near, 600.0)); + drag(&mut h, a, b); + let p = positions(&h); + assert!((p[0] - near).abs() < 0.1 && p[0] != side, "{p:?} vs {near}"); +} + +/// A frame's edge catches a dragged guide, and the preview shows the alignment mark. +#[test] +fn a_dragged_guide_snaps_to_a_frame_edge_with_a_smart_guide() { + let mut h = with_guides(); + h.state_mut().run("frame.create", json!({"rect": [400, 100, 500, 200]})).unwrap(); + h.state_mut().run("edit.deselectAll", json!({})).unwrap(); + let near = 400.0 + 1.5 * pt_per_px(&h); + let (a, b) = (screen_of(&h, 200.0, 600.0), screen_of(&h, near, 600.0)); + let g = + GuideDrag { orientation: designcraft_doc::Orientation::Vertical, from: Some((SpreadRef::Doc(0), 0, 0)), at: Some(b), mods: Modifiers::NONE }; + { + let app = h.state(); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let spot = guide_spot(app, &xf, &g).unwrap(); + assert_eq!(spot.sp.x, 400.0); + assert!(spot.marks.iter().any(|m| matches!(m, Overlay::Guide { .. })), "{:?}", spot.marks); + // Command suspends snapping. + let spot = guide_spot(app, &xf, &GuideDrag { mods: Modifiers::COMMAND, ..g.clone() }).unwrap(); + assert!((spot.sp.x - near).abs() < 0.1 && spot.marks.is_empty()); + } + drag(&mut h, a, b); + assert_eq!(positions(&h), [400.0, 300.0, 400.0]); +} + +/// A new guide dragged out of a ruler snaps too: here to the horizontal guide at y 400. +#[test] +fn a_guide_dragged_out_of_a_ruler_snaps() { + let mut h = with_guides(); + let rect = h.state().canvas_rect.unwrap(); + let ruler = pos2(rect.min.x + 200.0, rect.min.y - RULER / 2.0); + let dest = screen_of(&h, 250.0, 400.0 + 1.5 * pt_per_px(&h)); + drag(&mut h, ruler, dest); + assert_eq!(positions(&h), [200.0, 300.0, 400.0, 400.0]); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 92b86f0f1..f61acacba 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -283,7 +283,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Index: page references (topic from the selection or up to 4 levels, sort keys; current page, to end of story, next n paragraphs, suppressed, See / See also), Generate / Update Index (section headings, nested or run-in, page ranges merged, Index Title / Section Head / Level 1–4 styles); IDML export/import as InDesign topics, page references and topic cross-references (verified in InDesign 2026); `index.*` commands. - 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; selected like objects with the Selection tools (click, Shift-click, a marquee that touches no object, Edit › Select All Guides ⌥⌘G), drawn highlighted, moved together by dragging or the arrow keys, deleted with Delete, and placed exactly with the X or Y field of the Control and Properties panels; Layout › Create Guides (rows/columns with gutters, fit to margins or page); Delete All Guides on Spread; `guide.*` 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; a dragged guide snaps along its axis to other guides, margins, columns, bleed, page and object edges and centers and the document grid (Shift: the ruler's ticks; Cmd suspends snapping); selected like objects with the Selection tools (click, Shift-click, a marquee that touches no object, Edit › Select All Guides ⌥⌘G), drawn highlighted, moved together by dragging or the arrow keys, deleted with Delete, and placed exactly with the X or Y field of the Control and Properties panels; 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. - Linked text files: `file.place {link: true}` or Preferences › File Handling › Create Links When Placing Text Files keeps a placed .docx/.rtf/.txt story linked to its file (path, size and hash, and the style map and conflict option used). The Links panel shows it OK / Modified / Missing; Update imports the file again into the same frames and thread with the saved style map, replacing edits made in the layout (the Links panel and menu ask first; the `links.update` command updates and returns a warning; undoable); Relink, Go To and Unlink. Saved in the native format; IDML exports the text unlinked. - Missing fonts: highlighted pink on screen (never in output), listed by Preflight; Type › Find/Replace Font (fonts in the document, missing first; replace in text, cells, footnotes and styles); `font.list` / `font.replace`. Type › Reload Fonts (`font.reload`) scans the font folders again and reads again the installed font files edited or removed since they were read, then recomposes the open documents: a font installed or edited while DesignCraft runs needs no restart (#328, #547). InDesign notices such changes by itself. From 333f2a04e31e0bff7eff4739640f0e765e6e14e9 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 22 Oct 2026 02:52:17 -0400 Subject: [PATCH 12/29] Selection: drag a column guide to move its gutter (#1096) (#1176) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * IDML: keep column guides that were dragged off centre (#1096) InDesign records dragged column guides in `MarginPreference ColumnsPositions`, as pairs of offsets from the margin box's left edge. The importer discarded them and divided the columns evenly, so a page whose gutter the designer had moved came back with it in the middle: on a 450 pt margin box, `0 150 170 450` was read as columns at 215 and 235. `Columns::positions` already existed, documented as "Custom column positions (after dragging column guides)", but nothing set it and nothing read it. Now `Page::column_rects` returns the custom rects when they are set — that one method is what the canvas guides, snapping, threading and the first frame of a placed story all go through, so they follow the dragged gutter — the importer fills it, and the exporter writes the page's real positions instead of recomputing an even split, so the round trip keeps them. `layout.marginsAndColumns` clears them when a count or gutter is set, which is what InDesign's Margins and Columns does. Without that the stale positions would outrank the new value and the dialog would look broken. Verified against InDesign-authored IDML rather than assumed, which settled two things. The attribute is written whether or not anything was dragged — a real page's values are exactly its even split — so an even set is dropped rather than marking every imported page custom and freezing its columns; the tolerance for that comparison only absorbs float noise, about 1e-14 pt on that page. And `` is a `` child, not a `` one, which is where this importer already looks: the reporter's missing ruler guide was 099fbd2, landed the day the ticket was filed, not a second bug. That commit left `lib.rs` still listing guides as ignored on import; corrected. * IDML: test a ruler guide in a column gutter without facing pages (#1096) * View: Lock Guides and Lock Column Guides are commands (#1096) view.lockGuides {on?} (Cmd+Alt+;) sets the Lock Guides UI state the Properties panel and ruler-guide drags use. view.lockColumnGuides {on?} is a document setting, on by default, saved with the document, not an undo step, and read from and written to IDML ColumnGuideLocked. Both are in View > Grids & Guides with checkmarks. * IDML: custom column positions are validated and round-trip (#1096) Columns::positions are used only when they are 2 x count finite edges, ascending from 0 to the margin box width (within 0.01 pt); anything else is the even split, in Page::column_rects, on IDML import (bounded parse, checked against the page's margin box) and on IDML export. Columns::with_gutter_moved moves one gutter's pair of guides between its neighbours for the coming column-guide command. ROADMAP: drop four progress-log lines the #1121 merge duplicated and move its line to the top. * Layout: Margins and Columns keeps dragged columns unless the count or gutter changes (#1096) * Layout: autoflow, inserted pages and new parents follow dragged columns (#1096) * Integration: close #1121's round-trip test beside the ruler-guide test * View: Lock Column Guides is translated wherever Lock Guides is (#1096) * View: Lock Column Guides is translated wherever Lock Guides is (#1096) * Layout: a new margin or page width resets dragged columns (#1096) * IDML: a page without its own margins checks the default's column positions against its width (#1096) * Layout: #1121's margin case follows the new-width rule (#1096) * View: Lock Column Guides is undoable (#1096) * Layout: dragged columns scale with a new margin or page width (#1096) * Layout: dragged columns mirror when a page changes side (#1096) * Layout: the page-width test drags a page whose columns are its own (#1096) * Selection: drag a column guide to move its gutter (#1096) * Layout: pages that follow a one-page parent take its dragged columns mirrored (#1096) * Selection: column-guide drag review fixes (#1096) * ROADMAP: the progress line lands in one commit after the guide PRs --------- Co-authored-by: Hamza --- ROADMAP.md | 8 + crates/engine/src/cmd/layout.rs | 163 ++++++++++++++ crates/engine/src/tooling.rs | 14 ++ crates/ui-egui/src/canvas.rs | 369 +++++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/cs.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ka.rs | 1 + crates/ui-egui/src/i18n/pl.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/ru.rs | 1 + crates/ui-egui/src/i18n/uk.rs | 1 + docs/target-app-parity.md | 1 + 15 files changed, 565 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index 9c4cb465c..f9be21cc9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -358,6 +358,14 @@ Newest first. - **2026-10-17** · Object strokes reject malformed types and unknown type fields before changing the document; command help lists every stroke kind and its required fields. No readiness percentage change. - **2026-10-17** · Docs: documented a persistent source CLI install with Cargo, MCP-client PATH setup and bare-name server registration in `docs/mcp.md`. No readiness percentage change. +- **2026-10-16** · Selection: drag a column guide to move its gutter, as in InDesign (#1096). Both guides of the gutter move together and keep its width, stop at the neighbouring guides and the margins, and snap to the document grid, guides and objects, or with Shift to the ruler's tick marks; Escape cancels and the drag is one undo step. Locked column guides (the default) are not picked. A document page takes the result as its own columns; on a parent page it passes to the pages that follow it. `layout.moveColumnGuide` does the same over the control channel and MCP. No readiness percentage change. +- **2026-10-16** · Layout: Margins and Columns keeps dragged column guides unless the column count or gutter changes (#1096). The dialog sends every field on OK, so a margin-only change re-divided the columns evenly. Margin changes keep the positions; the columns follow them only while they fit the margin box. No readiness percentage change. +- **2026-10-16** · Layout: autoflow, inserted pages and new parents follow dragged column guides (#1096). Autoflow sets one frame per dragged column and counts the pages it adds from them; Insert Pages and New Parent keep the custom positions with the column count and gutter; `document.inspect` reports each page's gutter, column rects and whether its columns are custom. No readiness percentage change. +- **2026-10-16** · Layout: autoflow, inserted pages and new parents follow dragged column guides (#1096). Autoflow sets one frame per dragged column and counts the pages it adds from them; Insert Pages and New Parent keep the custom positions with the column count and gutter; a page that moves to the other side of the spine (inserted, deleted or moved pages, Duplicate Spread, a new parent's other page) has them mirrored across its margin box, as InDesign does; `document.inspect` reports each page's gutter, column rects and whether its columns are custom. No readiness percentage change. +- **2026-10-16** · IDML: custom column positions are checked before they are used (#1096). A set must give two edges per column, ascending from the left margin to the right one; any other (a wrong count, unsorted or non-numeric values, a list longer than 216 columns allow, or positions left behind by a margin or page-size change) is the even split, in the canvas, on import and on export, instead of columns drawn outside the margins. No readiness percentage change. +- **2026-10-16** · IDML: a page keeps column guides that were dragged off centre (InDesign's Custom columns). They were divided evenly on import, so the gutter sprang back to the middle; the imported positions now place the columns, with the canvas guides, snapping and text placement following them, and they are written back on export. Layout › Margins and Columns re-divides them evenly when the count or gutter changes, as InDesign's does. No readiness percentage change. +- **2026-10-16** · Lock Guides and Lock Column Guides are commands in View ▸ Grids & Guides (`view.lockGuides`, ⌥⌘;, and `view.lockColumnGuides`), so the control channel and MCP reach them. Lock Column Guides is saved with the document, on in new ones, and read from and written to IDML's `ColumnGuideLocked`, which export always wrote as locked (#1096). No readiness percentage change. +- **2026-10-16** · Lock Guides and Lock Column Guides are commands in View ▸ Grids & Guides (`view.lockGuides`, ⌥⌘;, and `view.lockColumnGuides`), so the control channel and MCP reach them. Lock Column Guides is an undo step, is saved with the document, on in new ones, and read from and written to IDML's `ColumnGuideLocked`, which export always wrote as locked (#1096). 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/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 9016c3848..047bd90ba 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -430,6 +430,15 @@ pub fn specs() -> Vec { }) } ), + cmd!( + "layout.moveColumnGuide", + "Move Column Guide", + [], + None, + "{spread?, parent? (a parent's prefix, label or index: its spread instead of `spread`), page (index in the spread), gutter (0 = between the first two columns), position (the gutter's new left edge, spread x)} → {positions (each column's left and right edge from the margin box's left edge), left (where the gutter's left edge went, spread x)} — both guides of the gutter move, keeping its width, and stop at the neighbouring guides and the margins; a document page takes the result as its own columns, a parent page passes it to the pages that follow it; refused while column guides are locked", + column_guides_unlocked, + move_column_guide + ), cmd!( "layout.documentSetup", "Document Setup…", @@ -870,6 +879,52 @@ pub fn specs() -> Vec { ] } +/// Column guides can be dragged: a document is open and View › Grids & Guides › Lock Column +/// Guides is off. +fn column_guides_unlocked(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + match s.active() { + Some(st) if st.doc.settings.column_guides_locked => Err("column guides are locked (View › Grids & Guides › Lock Column Guides)".into()), + _ => Ok(()), + } +} + +/// A column guide dragged with the Selection tool: gutter `gutter` of a page moves to `position`. +fn move_column_guide(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "layout.moveColumnGuide"; + let index = |key: &str| -> Result { + let v = p.get(key).ok_or_else(|| bad(CMD, format!("missing `{key}`")))?; + v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad(CMD, format!("`{key}` must be a non-negative integer"))) + }; + let (page, gutter) = (index("page")?, index("gutter")?); + let position = + p.get("position").and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad(CMD, "`position` must be a finite number"))?; + let r = match p.get("parent") { + None | Some(Value::Null) => super::spread_param(p, CMD)?, + Some(v) => designcraft_doc::SpreadRef::Parent(parent_spread_index(&s.doc()?.doc, v).ok_or_else(|| bad(CMD, "no such parent"))?), + }; + s.edit(|d, _| { + if d.settings.column_guides_locked { + return Err(bad(CMD, "column guides are locked")); + } + let pg = d.spread_mut(r).ok_or_else(|| bad(CMD, "no such spread"))?.pages.get_mut(page).ok_or_else(|| bad(CMD, "no such page"))?; + let m = pg.margin_rect(); + let count = pg.columns.count; + if gutter.checked_add(1).is_none_or(|g| g >= count as usize) { + return Err(bad(CMD, format!("the page has {} gutters", count.saturating_sub(1)))); + } + let positions = + pg.columns.with_gutter_moved(m.width(), gutter, position - m.x0).ok_or_else(|| bad(CMD, "the columns cannot take that position"))?; + let left = positions.get(gutter * 2 + 1).map_or(position, |v| m.x0 + v); + pg.columns.positions = Some(positions.clone()); + match r { + designcraft_doc::SpreadRef::Doc(_) => pg.local_margins = true, + designcraft_doc::SpreadRef::Parent(_) => d.sync_parent_margins(), + } + Ok(json!({"positions": positions, "left": left})) + }) +} + /// A parent spread named by prefix, label (`A-Parent`) or index. fn parent_spread_index(d: &designcraft_doc::Document, v: &Value) -> Option { match v { @@ -2227,6 +2282,114 @@ mod parent_tests { assert_eq!((page["columns"].clone(), page["customColumns"].clone()), (json!(2), json!(true)), "{page}"); assert_eq!(page["columnRects"][0], json!([36.0, 36.0, 136.0, 756.0]), "{page}"); } + + fn columns_of(s: &crate::Session, abs: usize) -> (Option>, bool) { + let pg = s.doc().unwrap().doc.page(abs).unwrap().clone(); + (pg.columns.positions, pg.local_margins) + } + + /// Three columns across a 540 pt margin box (36 pt margins), column guides unlocked. + fn three_columns(pages: u64) -> crate::Session { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({"pages": pages})).unwrap(); + s.execute("layout.marginsAndColumns", &json!({"parent": "A", "columns": 3, "gutter": 12})).unwrap(); + s.execute("view.lockColumnGuides", &json!({"on": false})).unwrap(); + s + } + + /// Dragging a column guide moves its gutter's two guides together, stops at the neighbouring + /// gutter and the margin, makes a following page's columns its own, and undoes in one step. + #[test] + fn move_column_guide_moves_the_gutter_pair_within_its_neighbours() { + let mut s = three_columns(1); + assert_eq!(columns_of(&s, 0), (None, false), "the page follows A"); + let mv = + |s: &mut crate::Session, gutter: u64, x: f64| s.execute("layout.moveColumnGuide", &json!({"page": 0, "gutter": gutter, "position": x})); + let r = mv(&mut s, 0, 236.0).unwrap(); + assert_eq!(r, json!({"positions": [0.0, 200.0, 212.0, 356.0, 368.0, 540.0], "left": 236.0})); + assert_eq!(columns_of(&s, 0), (Some(vec![0.0, 200.0, 212.0, 356.0, 368.0, 540.0]), true)); + let inspect = s.execute("document.inspect", &json!({})).unwrap(); + assert_eq!(inspect["spreads"][0]["pages"][0]["columnRects"][0], json!([36.0, 36.0, 236.0, 756.0])); + // Past the next gutter: it stops there, and the middle column has no width. + assert_eq!(mv(&mut s, 0, 1000.0).unwrap()["left"], json!(36.0 + 344.0)); + // Past the right margin: the last gutter stops 12 pt (its width) inside it. + assert_eq!(mv(&mut s, 1, 1e12).unwrap()["positions"], json!([0.0, 344.0, 356.0, 528.0, 540.0, 540.0])); + // Past the left margin. + assert_eq!(mv(&mut s, 0, -1e12).unwrap()["positions"], json!([0.0, 0.0, 12.0, 528.0, 540.0, 540.0])); + for _ in 0..3 { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(columns_of(&s, 0), (Some(vec![0.0, 200.0, 212.0, 356.0, 368.0, 540.0]), true)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(columns_of(&s, 0), (None, false), "one undo step per drag"); + } + + /// On a parent page the drag changes the parent, and the document pages that follow it get + /// the new columns; a page with columns of its own keeps them. + #[test] + fn move_column_guide_on_a_parent_reaches_the_pages_that_follow_it() { + let mut s = three_columns(3); + // Page 1, the left page of spread 1, gets columns of its own. + let x = s.doc().unwrap().doc.spreads[1].pages[0].margin_rect().x0 + 300.0; + s.execute("layout.moveColumnGuide", &json!({"spread": 1, "page": 0, "gutter": 1, "position": x})).unwrap(); + let own = columns_of(&s, 1); + assert!(own.1 && own.0.is_some()); + let d = &s.doc().unwrap().doc; + // A's right page: the one page 0 (a right page) and page 2 follow. + let x0 = d.parents[0].pages[1].margin_rect().x0; + s.execute("layout.moveColumnGuide", &json!({"parent": "A", "page": 1, "gutter": 0, "position": x0 + 100.0})).unwrap(); + let moved = vec![0.0, 100.0, 112.0, 356.0, 368.0, 540.0]; + assert_eq!(s.doc().unwrap().doc.parents[0].pages[1].columns.positions, Some(moved.clone())); + assert_eq!(columns_of(&s, 0), (Some(moved.clone()), false)); + assert_eq!(columns_of(&s, 2), (Some(moved), false)); + assert_eq!(columns_of(&s, 1), own, "page 1's columns are its own"); + // The same parent page by spread reference. + let spread = json!({"kind": "parent", "index": 0}); + s.execute("layout.moveColumnGuide", &json!({"spread": spread, "page": 1, "gutter": 0, "position": x0 + 50.0})).unwrap(); + assert_eq!(columns_of(&s, 0).0.unwrap()[1], 50.0); + } + + /// A drag's preview in one document is put back there when another document became active. + #[test] + fn a_column_guide_preview_is_cancelled_in_its_own_document() { + let mut s = three_columns(1); + let uid = s.doc().unwrap().uid; + s.begin_interaction("Move Column Guide").unwrap(); + s.preview("layout.moveColumnGuide", json!({"page": 0, "gutter": 0, "position": 236})).unwrap(); + s.execute("file.new", &json!({})).unwrap(); + s.cancel_interaction_of(uid); + s.set_active(0); + assert!(s.doc().unwrap().interaction.is_none()); + assert_eq!(columns_of(&s, 0), (None, false)); + } + + #[test] + fn move_column_guide_refuses_while_locked_and_hostile_params() { + let mut s = three_columns(1); + s.execute("view.lockColumnGuides", &json!({"on": true})).unwrap(); + assert!(s.execute("layout.moveColumnGuide", &json!({"page": 0, "gutter": 0, "position": 200})).is_err()); + assert_eq!(columns_of(&s, 0), (None, false)); + s.execute("view.lockColumnGuides", &json!({"on": false})).unwrap(); + for p in [ + json!({"page": 0, "gutter": 0}), + json!({"page": 0, "gutter": 0, "position": f64::NAN}), + json!({"page": 0, "gutter": 0, "position": "200"}), + json!({"page": 0, "gutter": 2, "position": 200}), + json!({"page": 0, "gutter": u64::MAX, "position": 200}), + json!({"page": 0, "gutter": -1, "position": 200}), + json!({"page": 0, "gutter": 0.5, "position": 200}), + json!({"page": 9, "gutter": 0, "position": 200}), + json!({"page": u64::MAX, "gutter": 0, "position": 200}), + json!({"gutter": 0, "position": 200}), + json!({"spread": 99, "page": 0, "gutter": 0, "position": 200}), + json!({"parent": "Z", "page": 0, "gutter": 0, "position": 200}), + json!({"page": 0, "gutter": 0, "position": f64::MAX}), + ] { + let r = s.execute("layout.moveColumnGuide", &p); + // A huge but finite position is clamped to the margin; everything else is refused. + assert!(r.is_err() || p["position"] == json!(f64::MAX), "{p}: {r:?}"); + } + } } #[cfg(test)] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index c58236090..65d069bac 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -331,4 +331,18 @@ impl Session { } } } + + /// Cancel the interaction of the document with `uid`, active or not: a gesture that began in + /// one document and lost it to another tab ends there, leaving the document as it began. + pub fn cancel_interaction_of(&mut self, uid: u64) { + if self.active().is_some_and(|st| st.uid == uid) { + self.cancel_interaction(); + } else if let Some(st) = self.docs.iter_mut().find(|st| st.uid == uid) + && let Some(it) = st.interaction.take() + { + st.doc = it.doc; + st.selection = it.selection; + st.revision = it.revision; + } + } } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index f8ddc9487..9868d4d8b 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -623,6 +623,19 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { } else { app.session.cursor(xf.to_canvas(p), ui.input(|i| mods(i, false)), app.view_info()) }; + // A column guide that a press would drag, or one being dragged: a resize cursor across it. + let dragging = ui.data(|d| d.get_temp::(egui::Id::new((COLUMN_DRAG, app.pane)))).map(|g| g.spread); + let column = dragging.or_else(|| { + let menu_open = context_menu_open(ui.ctx()); + (!space && !zoom && !middle && !alt_hand && !tool_drag && !menu_open && xf.rot == 0) + .then(|| column_guide_at(app, &xf, p).map(|h| h.0)) + .flatten() + }); + let c = match column { + Some(r) if spread_x_across(app, r) => Cursor::ResizeH, + Some(_) => Cursor::ResizeV, + None => c, + }; let icon = crate::cursors::show(ui.ctx(), &mut app.cursors, c, p); ui.ctx().set_cursor_icon(icon); draw_cursor_badge(&painter, p, c, &t); @@ -2393,6 +2406,11 @@ fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, r // Space-drag = hand (unless a tool drag is under way: then Space is a modifier, e.g. Live // Distribute while resizing). Middle-drag pans too, with any tool; tools only // see the primary button. + // A column guide drag keeps the pointer until the button is up, whatever Space or a menu does + // meanwhile. + if ui.data(|d| d.get_temp::(egui::Id::new((COLUMN_DRAG, app.pane)))).is_some() && column_guide_drag(app, ui, resp, rect, &xf) { + return; + } let tool_drag: bool = ui.data(|d| d.get_temp(egui::Id::new(("canvas_pointer_down", app.pane)))).unwrap_or(false); let hand = space && !ui.input(|i| i.modifiers.command); if !tool_drag && ((hand && resp.dragged()) || resp.dragged_by(egui::PointerButton::Middle)) { @@ -2428,6 +2446,9 @@ fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, r if !space && !menu_open && xf.rot == 0 && guide_drag(app, ui, resp, rect, &xf) { return; } + if !space && !menu_open && xf.rot == 0 && column_guide_drag(app, ui, resp, rect, &xf) { + return; + } let m = ui.input(|i| mods(i, space)); let vi = app.view_info(); let pos = |p: Pos2| xf.to_canvas(p); @@ -3263,6 +3284,222 @@ fn moving_guides(app: &DesignApp, xf: &Xf, rect: Rect, g: &GuideDrag, press: Gui Some(MovingGuides { guides, dx, dy }) } +/// An object is under screen point `p` where the Selection tool would pick it (a document +/// spread's, or a parent spread's while editing parents): it takes the press before the guides +/// behind it. +fn over_item(app: &DesignApp, xf: &Xf, p: Pos2) -> bool { + let Some(st) = app.session.active() else { return false }; + let layout = CanvasLayout::new(&st.doc, st.editing_parents); + let cx = designcraft_tools::ToolContext { + doc: &st.doc, + selection: &st.selection, + cache: &app.session.cache, + layout: &layout, + zoom: xf.zoom.max(1e-6), + layer: st.active_layer, + snap: app.ui.snap_view(), + unit: app.ui.units, + stroke_in_front: false, + }; + cx.hit(xf.to_canvas(p)).is_some() +} + +const COLUMN_DRAG: &str = "canvas_column_drag"; + +/// A column guide being dragged with a Selection tool: its gutter follows the pointer. +#[derive(Clone, Debug)] +struct ColumnDrag { + /// The document the drag's interaction belongs to. + doc: u64, + spread: SpreadRef, + page: usize, + gutter: usize, + /// The pointer's spread x minus the gutter's left edge at the press: the gutter keeps that + /// distance from the pointer. + grab: f64, + /// The left edge last previewed. + last: Option, +} + +/// The interior column guide under screen point `p` (within 3 px) that a press there would drag, +/// as (spread, page, gutter, the gutter's left edge in spread x): a Selection tool, guides shown +/// (not in Preview or Presentation), column guides unlocked, and no object or ruler guide that +/// takes the press there. +fn column_guide_at(app: &DesignApp, xf: &Xf, p: Pos2) -> Option<(SpreadRef, usize, usize, f64)> { + let preview = matches!(app.ui.screen_mode, ScreenMode::Preview | ScreenMode::Presentation); + if !app.ui.guides || preview || !matches!(app.session.tool_id(), "selection" | "directSelection") { + return None; + } + let st = app.session.active()?; + if st.doc.settings.column_guides_locked { + return None; + } + let layout = CanvasLayout::new(&st.doc, st.editing_parents); + let (r, sp) = layout.spread_at(xf.to_canvas(p))?; + let tol = 3.0 / xf.zoom.max(1e-9); + let hit = st.doc.spread(r)?.pages.iter().enumerate().find_map(|(pi, pg)| { + let m = pg.margin_rect(); + if sp.y < m.y0 - tol || sp.y > m.y1 + tol { + return None; + } + pg.column_rects().windows(2).enumerate().find_map(|(gi, w)| match w { + // Columns that cannot move (gutters wider than the margin box) offer no guide. + [a, b] + if ((sp.x - a.x1).abs() <= tol || (sp.x - b.x0).abs() <= tol) + && pg.columns.with_gutter_moved(m.width(), gi, a.x1 - m.x0).is_some() => + { + Some((r, pi, gi, a.x1)) + } + _ => None, + }) + })?; + // A ruler guide there takes the press first (see `guide_drag`). + let ruler_guide = !app.ui.guides_locked && guide_at(app, xf, p).is_some(); + (!ruler_guide && !over_item(app, xf, p)).then_some(hit) +} + +/// Whether spread `r`'s x axis runs across the screen (the spread view is not turned a quarter). +fn spread_x_across(app: &DesignApp, r: SpreadRef) -> bool { + app.session.active().is_none_or(|st| { + let [a, b, ..] = CanvasLayout::new(&st.doc, st.editing_parents).xf(r).as_coeffs(); + a.abs() >= b.abs() + }) +} + +/// Canvas x `x` moved to the nearest tick mark of the horizontal ruler (its finest increment). +fn ruler_tick_x(app: &DesignApp, doc: &Document, layout: &CanvasLayout, zoom: f64, x: f64) -> Option { + let pieces = ruler_pieces(app, doc, layout, doc.zero_point()); + let &(_, _, o) = pieces.iter().find(|(from, to, _)| *from <= x && x < *to).or(pieces.first())?; + let (major, sub) = doc.settings.horizontal_units.ruler_ticks(zoom); + let step = major / f64::from(sub.max(1)); + (step.is_finite() && step > 0.0).then(|| o.x + ((x - o.x) / step).round() * step).filter(|v| v.is_finite()) +} + +/// Where a dragged gutter's left edge goes for spread x `want`: Shift snaps it to the ruler's tick +/// marks; otherwise its edges snap to the document grid, guides and objects as those snaps are +/// set. Measured against the document as it was when the drag began. +fn snap_gutter(app: &DesignApp, g: &ColumnDrag, want: f64, shift: bool, zoom: f64) -> f64 { + let Some(st) = app.session.active() else { return want }; + let doc = st.interaction.as_ref().map_or_else(|| st.doc.clone(), |i| i.doc.clone()); + let layout = CanvasLayout::new(&doc, st.editing_parents); + let Some(slot) = layout.slots.iter().find(|s| s.spread == g.spread) else { return want }; + let Some(pg) = doc.spread(g.spread).and_then(|sp| sp.pages.get(g.page)) else { return want }; + let m = pg.margin_rect(); + if shift { + if !spread_x_across(app, g.spread) { + return want; + } + let c = slot.to_canvas(Point::new(want, m.y0)); + return ruler_tick_x(app, &doc, &layout, zoom, c.x).map_or(want, |x| slot.to_spread(Point::new(x, c.y)).x); + } + let cols = pg.column_rects(); + let width = match (cols.get(g.gutter), cols.get(g.gutter + 1)) { + (Some(a), Some(b)) => (b.x0 - a.x1).max(0.0), + _ => 0.0, + }; + let cx = designcraft_tools::ToolContext { + doc: &doc, + selection: &st.selection, + cache: &app.session.cache, + layout: &layout, + zoom: zoom.max(1e-6), + layer: st.active_layer, + // A line has no size or spacing to match. + snap: designcraft_tools::SnapView { smart_dimensions: false, smart_spacing: false, ..app.ui.snap_view() }, + unit: app.ui.units, + stroke_in_front: false, + }; + let rect = DRect::new(want, m.y0, want + width, m.y1); + let s = designcraft_tools::snap::snap( + &cx, + designcraft_tools::SnapRequest { + spread: g.spread, + gesture: designcraft_tools::Gesture::Move, + rect, + x_edges: [true, false, true], + y_edges: [false; 3], + exclude: &[], + exclude_guides: &[], + copying: false, + lengths: [None, None], + angle: None, + radius: 0.0, + pointer: Point::new(want, m.center().y), + }, + ); + let x = want + s.delta.x; + if x.is_finite() { x } else { want } +} + +/// Column guides: with a Selection tool, drag an interior column guide (not over an object) to +/// move its gutter, both guides together; Escape puts it back. One undo step per drag. Returns +/// true while it owns the pointer. +fn column_guide_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rect: Rect, xf: &Xf) -> bool { + let id = egui::Id::new((COLUMN_DRAG, app.pane)); + let (pressed, released, origin, latest, shift, escape) = ui.input(|i| { + ( + i.pointer.primary_pressed(), + // A release this frame, or one missed while something else had the pointer. + i.pointer.primary_released() || !i.pointer.primary_down(), + i.pointer.press_origin(), + i.pointer.latest_pos(), + i.modifiers.shift, + i.key_pressed(egui::Key::Escape), + ) + }); + let mut drag: Option = ui.data(|d| d.get_temp(id)); + if drag.is_none() + && pressed + && resp.hovered() + && let Some(o) = origin.filter(|o| rect.contains(*o)) + && let Some((spread, page, gutter, left)) = column_guide_at(app, xf, o) + // Another gesture or a dialog's preview owns the document until it ends. + && let Some((doc, slot_x)) = app + .session + .active() + .filter(|st| st.interaction.is_none()) + .map(|st| (st.uid, CanvasLayout::new(&st.doc, st.editing_parents).to_spread(spread, xf.to_canvas(o)).x)) + && app.session.begin_interaction("Move Column Guide").is_ok() + { + drag = Some(ColumnDrag { doc, spread, page, gutter, grab: slot_x - left, last: None }); + } + let Some(mut g) = drag else { return false }; + // Another document became active: the drag ends in its own, as it began. + if app.session.active().is_none_or(|st| st.uid != g.doc) { + app.session.cancel_interaction_of(g.doc); + ui.data_mut(|d| d.remove::(id)); + return false; + } + if escape { + app.session.cancel_interaction(); + ui.data_mut(|d| d.remove::(id)); + return true; + } + if let Some(p) = latest + && let Some(x) = app.session.active().map(|st| CanvasLayout::new(&st.doc, st.editing_parents).to_spread(g.spread, xf.to_canvas(p)).x) + && x.is_finite() + { + let want = snap_gutter(app, &g, x - g.grab, shift, xf.zoom); + if g.last != Some(want) && (g.last.is_some() || (p - origin.unwrap_or(p)).length() > 0.0) { + let params = json!({"spread": g.spread, "page": g.page, "gutter": g.gutter, "position": want}); + if let Err(e) = app.session.preview("layout.moveColumnGuide", params) { + app.status(e.to_string()); + } + g.last = Some(want); + } + } + if released { + ui.data_mut(|d| d.remove::(id)); + if let Err(e) = app.session.commit_interaction() { + app.status(e.to_string()); + } + app.after_engine(); + return true; + } + ui.data_mut(|d| d.insert_temp(id, g)); + true +} + /// Presses in a row on the canvas: the last press's count, and where and when it was released /// (`at` is −∞ while the button is down). #[derive(Clone, Copy, Debug)] @@ -3498,6 +3735,138 @@ mod tests { assert!(!g[1].liquid); } + /// Dragging a column guide with the Selection tool moves its gutter (one undo step); with + /// column guides locked the same drag leaves the columns alone. + #[test] + fn the_selection_tool_drags_a_column_guide() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + // Two columns across the 540 pt margin box: the gutter's left edge is at x = 300. + app.run("layout.marginsAndColumns", json!({"parent": "A", "columns": 2, "gutter": 12})).unwrap(); + let mut h = harness(app); + let page = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.spreads[0].pages[0].clone(); + let screen = |h: &Harness<'_, DesignApp>, x: f64| { + let app = h.state(); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let layout = CanvasLayout::new(&app.session.active().unwrap().doc, false); + let slot = layout.slots.iter().find(|s| s.spread == SpreadRef::Doc(0)).unwrap(); + (xf.to_screen(slot.xf * Point::new(x, 400.0)), xf.zoom as f32) + }; + let (at, zoom) = screen(&h, 300.0); + drag(&mut h, at, at + vec2(72.0 * zoom, 0.0)); + assert_eq!(page(&h).columns.positions, None, "column guides are locked in a new document"); + h.hover_at(at); + h.run_steps(2); + assert_ne!(h.output().platform_output.cursor_icon, egui::CursorIcon::ResizeHorizontal); + + h.state_mut().run("view.lockColumnGuides", json!({"on": false})).unwrap(); + h.run_steps(2); + let (at, zoom) = screen(&h, 300.0); + drag(&mut h, at, at + vec2(72.0 * zoom, 0.0)); + let pg = page(&h); + let cols = pg.column_rects(); + assert!((cols[0].x1 - 372.0).abs() < 1.0 && (cols[1].x0 - cols[0].x1 - 12.0).abs() < 1e-9, "{cols:?}"); + assert!(pg.local_margins, "the dragged page's columns are its own"); + // Over the moved guide: a resize cursor. + h.hover_at(screen(&h, 372.0).0); + h.run_steps(2); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::ResizeHorizontal); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(page(&h).columns.positions, None, "one undo step"); + + // Escape during the drag puts the gutter back. + h.hover_at(at); + h.step(); + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.step(); + h.hover_at(at + vec2(40.0, 0.0)); + h.step(); + assert!(page(&h).columns.positions.is_some(), "the drag previews"); + h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }); + h.step(); + h.event(egui::Event::PointerButton { + pos: at + vec2(40.0, 0.0), + button: egui::PointerButton::Primary, + pressed: false, + modifiers: Default::default(), + }); + h.run_steps(3); + assert_eq!(page(&h).columns.positions, None); + assert!(!page(&h).local_margins); + + // Space pressed during the drag and the button released under it: the drag ends with the + // release and the gutter stops following the pointer. + let key = |pressed| egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + h.hover_at(at); + h.step(); + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.step(); + h.hover_at(at + vec2(40.0, 0.0)); + h.step(); + h.event(key(true)); + h.step(); + h.event(egui::Event::PointerButton { + pos: at + vec2(40.0, 0.0), + button: egui::PointerButton::Primary, + pressed: false, + modifiers: Default::default(), + }); + h.step(); + h.event(key(false)); + h.run_steps(2); + let moved = page(&h).columns.positions; + assert!(moved.is_some()); + h.hover_at(at + vec2(120.0, 0.0)); + h.run_steps(3); + assert_eq!(page(&h).columns.positions, moved, "the gutter stays where the drag ended"); + assert!(h.state().session.active().unwrap().interaction.is_none()); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(page(&h).columns.positions, None, "the drag was one undo step"); + } + + /// A column guide is not picked where the screen mode hides guides, where an object on the + /// parent being edited lies over it, or where its columns cannot move. + #[test] + fn column_guides_are_picked_only_where_a_drag_can_move_them() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 1})).unwrap(); + app.run("layout.marginsAndColumns", json!({"parent": "A", "columns": 2, "gutter": 12})).unwrap(); + app.run("view.lockColumnGuides", json!({"on": false})).unwrap(); + let mut h = harness(app); + let hit = |h: &Harness<'_, DesignApp>, r: SpreadRef, x: f64| { + let app = h.state(); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let st = app.session.active().unwrap(); + let layout = CanvasLayout::new(&st.doc, st.editing_parents); + let slot = layout.slots.iter().find(|s| s.spread == r).unwrap(); + column_guide_at(app, &xf, xf.to_screen(slot.xf * Point::new(x, 400.0))) + }; + assert!(hit(&h, SpreadRef::Doc(0), 300.0).is_some()); + h.state_mut().ui.screen_mode = ScreenMode::Preview; + assert!(hit(&h, SpreadRef::Doc(0), 300.0).is_none(), "Preview hides the guides"); + h.state_mut().ui.screen_mode = ScreenMode::Normal; + + // Editing parent A: its right page (the one page 0 follows) and a frame over its gutter. + h.state_mut().run("layout.parents.edit", json!({"on": true, "parent": "A-Parent"})).unwrap(); + h.run_steps(2); + let parent = SpreadRef::Parent(0); + let x = h.state().session.active().unwrap().doc.parents[0].pages[1].column_rects()[0].x1; + assert!(hit(&h, parent, x).is_some()); + h.state_mut() + .run("frame.create", json!({"spread": {"kind": "parent", "index": 0}, "rect": [x - 20.0, 300.0, x + 20.0, 500.0], "content": "text"})) + .unwrap(); + h.run_steps(2); + assert!(hit(&h, parent, x).is_none(), "the parent's frame takes the press"); + h.state_mut().run("layout.parents.edit", json!({"on": false})).unwrap(); + h.run_steps(2); + + // Gutters wider than the margin box: the even split cannot be moved. + h.state_mut().run("layout.marginsAndColumns", json!({"pages": [0], "columns": 2, "gutter": 1000})).unwrap(); + h.run_steps(2); + let x = h.state().session.active().unwrap().doc.spreads[0].pages[0].column_rects()[0].x1; + assert!(hit(&h, SpreadRef::Doc(0), x).is_none()); + } + fn right_click(h: &mut Harness<'_, DesignApp>, p: Pos2) { h.hover_at(p); h.step(); diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 587ed775b..31f7fb70d 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1606,6 +1606,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Move Anchors", "تحريك نقاط الارتساء"), ("Move Column", "نقل عمود"), ("Move Guide", "تحريك دليل"), + ("Move Column Guide", "تحريك دليل العمود"), ("Move Layer", "نقل طبقة"), ("Move Pages…", "نقل صفحات…"), ("Move to Layer", "نقل إلى طبقة"), diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index c052b8f33..4d41c30dc 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -775,6 +775,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Move Anchors", "Přesunout kotvy"), ("Move Column", "Přesunout sloupec"), ("Move Guide", "Přesunout vodítko"), + ("Move Column Guide", "Přesunout vodítko sloupce"), ("Move Layer", "Přesunout vrstvu"), ("Move Pages…", "Přesunout stránky…"), ("Move to Layer", "Přesunout do vrstvy"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 7065c6f33..d47657b09 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -832,6 +832,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Move Anchors", "Anker verschieben"), ("Move Column", "Spalte verschieben"), ("Move Guide", "Hilfslinie verschieben"), + ("Move Column Guide", "Spaltenhilfslinie verschieben"), ("Move Layer", "Ebene verschieben"), ("Move Pages…", "Seiten verschieben …"), ("Move to Layer", "Auf Ebene verschieben"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 8199e2ebb..755272fe5 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -905,6 +905,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Move Anchors", "Sposta ancoraggi"), ("Move Column", "Sposta colonna"), ("Move Guide", "Sposta guida"), + ("Move Column Guide", "Sposta guida colonna"), ("Move Layer", "Sposta livello"), ("Move Pages…", "Sposta pagine…"), ("Move to Layer", "Sposta su livello"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index e79f4ba06..e23ef15c7 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1020,6 +1020,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Move Anchors", "アンカーポイントを移動"), ("Move Column", "列を移動"), ("Move Guide", "ガイドを移動"), + ("Move Column Guide", "列ガイドを移動"), ("Move Layer", "レイヤーを移動"), ("Move Pages…", "ページを移動…"), ("Move to Layer", "レイヤーへ移動"), diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index c8405c16e..0300b62d7 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -837,6 +837,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Move Anchors", "საყრდენი წერტილების გადაადგილება"), ("Move Column", "სვეტის გადატანა"), ("Move Guide", "დამხმარე ხაზის გადაადგილება"), + ("Move Column Guide", "სვეტის დამხმარე ხაზის გადაადგილება"), ("Move Layer", "შრის გადაადგილება"), ("Move Pages…", "გვერდების გადატანა…"), ("Move to Layer", "შრეზე გადატანა"), diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index 51bb7fc5c..7d1d12c67 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -788,6 +788,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Move Anchors", "Przesuń kotwice"), ("Move Column", "Przesuń kolumnę"), ("Move Guide", "Przesuń linię pomocniczą"), + ("Move Column Guide", "Przesuń linię pomocniczą łamu"), ("Move Layer", "Przesuń warstwę"), ("Move Pages…", "Przesuń strony…"), ("Move to Layer", "Przenieś na warstwę"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index bb3d21831..f552e9a63 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1733,6 +1733,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Move Anchors", "Mover âncoras"), ("Move Column", "Mover coluna"), ("Move Guide", "Mover guia"), + ("Move Column Guide", "Mover guia de coluna"), ("Move Layer", "Mover camada"), ("Move to Layer", "Mover para a camada"), ("New Article", "Novo artigo"), diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 27ce1fed3..3f6ef1be0 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -762,6 +762,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Move Anchors", "Переместить опорные точки"), ("Move Column", "Переместить столбец"), ("Move Guide", "Переместить направляющую"), + ("Move Column Guide", "Переместить направляющую колонки"), ("Move Layer", "Переместить слой"), ("Move Pages…", "Переместить страницы…"), ("Move to Layer", "Переместить на слой"), diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index d7ac7ce01..9c7cc855a 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -908,6 +908,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Move Anchors", "Перемістити опорні точки"), ("Move Column", "Перемістити стовпець"), ("Move Guide", "Перемістити напрямну"), + ("Move Column Guide", "Перемістити напрямну колонки"), ("Move Layer", "Перемістити шар"), ("Move Pages…", "Перемістити сторінки…"), ("Move to Layer", "Перемістити до шару"), diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f61acacba..c7e0678d7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -284,6 +284,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - 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; a dragged guide snaps along its axis to other guides, margins, columns, bleed, page and object edges and centers and the document grid (Shift: the ruler's ticks; Cmd suspends snapping); selected like objects with the Selection tools (click, Shift-click, a marquee that touches no object, Edit › Select All Guides ⌥⌘G), drawn highlighted, moved together by dragging or the arrow keys, deleted with Delete, and placed exactly with the X or Y field of the Control and Properties panels; Layout › Create Guides (rows/columns with gutters, fit to margins or page); Delete All Guides on Spread; `guide.*` commands. +- Column guides: with the Selection tool, drag an interior column guide to move its gutter (both guides together, keeping its width, stopped by the neighbouring guides and the margins), snapping to the document grid, guides and objects, or with Shift to the ruler's tick marks; Escape cancels; one undo step. Refused while Lock Column Guides is on (the default). A document page takes the result as its own columns; on a parent page it reaches the pages that follow it. Objects stay where they are (there is no persistent Layout Adjustment setting yet). `layout.moveColumnGuide`. - 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. - Linked text files: `file.place {link: true}` or Preferences › File Handling › Create Links When Placing Text Files keeps a placed .docx/.rtf/.txt story linked to its file (path, size and hash, and the style map and conflict option used). The Links panel shows it OK / Modified / Missing; Update imports the file again into the same frames and thread with the saved style map, replacing edits made in the layout (the Links panel and menu ask first; the `links.update` command updates and returns a warning; undoable); Relink, Go To and Unlink. Saved in the native format; IDML exports the text unlinked. - Missing fonts: highlighted pink on screen (never in output), listed by Preflight; Type › Find/Replace Font (fonts in the document, missing first; replace in text, cells, footnotes and styles); `font.list` / `font.replace`. Type › Reload Fonts (`font.reload`) scans the font folders again and reads again the installed font files edited or removed since they were read, then recomposes the open documents: a font installed or edited while DesignCraft runs needs no restart (#328, #547). InDesign notices such changes by itself. From f3b7c3ee34e402b1e5c1854e7e8a86e876bd286e Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 22 Oct 2026 03:06:48 -0400 Subject: [PATCH 13/29] ROADMAP: progress lines for guide selection, guide snapping and dragged column guides (#1543) --- ROADMAP.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index f9be21cc9..8a2352e86 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -33,7 +33,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope - Index: page references (topic from the selection or up to 4 levels, sort keys; current page, to end of story, next n paragraphs, suppressed, See / See also), Generate / Update Index (section headings, nested or run-in, page ranges merged, Index Title / Section Head / Level 1–4 styles); IDML export/import as InDesign topics, page references and topic cross-references (verified in InDesign 2026); `index.*` commands. - 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. +- Ruler guides: drag out of the rulers (page guides, or spread guides on the pasteboard), drag to move, drop on a ruler to delete; a dragged guide snaps along its axis to other guides, margins, columns, bleed, page and object edges and centers and the document grid (Shift: the ruler's ticks; Cmd suspends snapping); selected like objects (click, Shift-click, a marquee that touches no object, Edit › Select All Guides ⌥⌘G), moved together, nudged, deleted, and placed exactly with the X or Y field; 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. - Missing fonts: highlighted pink on screen (never in output), listed by Preflight; Type › Find/Replace Font (fonts in the document, missing first; replace in text, cells, footnotes and styles); `font.list` / `font.replace`. - Missing glyphs, as in InDesign: a character the applied font lacks is drawn as that font's missing-glyph box (its .notdef; a drawn box when the font's is empty), on screen and in PDF (as a path, so PDF/A and PDF/UA exports take it), and Preflight lists the characters by font. Preferences › Composition › Draw Missing Glyphs from Fallback Fonts (`document.preferences {glyphFallback}`, stored with the document) draws them from other fonts instead; it is off in new documents and IDML imports, on in documents saved before it existed. A missing font's substitute always uses fallback fonts. @@ -348,9 +348,17 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-22** · A ruler guide dragged with the Selection tools, out of a ruler, on its own or with other selected guides, snaps along its axis as objects do (#1221): to other ruler guides, margins, columns, bleed, page and object edges and centers (with the smart-guide mark) and the document grid, within the snap zone and following Snap to Guides and Smart Guides. Shift snaps to the ruler's ticks and Cmd suspends snapping. The preview line, the position readout and the drop use the same snapped position. No readiness percentage change. - **2026-10-22** · macOS: the app menu has a Language submenu after Settings… with each interface language in its own name and the current one checked, as in the suite's other apps; Preferences › General › Interface Language stays. No readiness percentage change. - **2026-10-22** · macOS menu bar: the menus keep working after the interface language or Show CJK Features changes (a rebuilt menu bar lost every click, Quit included), and its key equivalents are the shortcuts in effect, so a shortcut moved in the Keyboard Shortcuts editor leaves its old menu item. No readiness percentage change. - **2026-10-22** · Paragraph rules: Rule Above's offset is measured from the first line's baseline to the rule's bottom edge, as in InDesign. Rules sat one ascent too high and crossed the previous paragraph's text (reported from an imported INDD document). No readiness percentage change. +- **2026-10-21** · Ruler guides are selected like objects (#1282): a click with the Selection tools selects a guide (also where it crosses an object), Shift-click adds or removes one, a new guide from the rulers is selected, a marquee that touches no object selects the guides it crosses, and Edit › Select All Guides (⌥⌘G, `guide.selectAll`) selects every unlocked guide on the spread. Selected guides draw thicker in their layer's color, drag together (all of them shown moving), nudge with the arrow keys and go with Delete, each as one undo step (`guide.select`, `guide.deselect`, `guide.moveBy`, `guide.delete {}`). With one guide selected the Control bar's X (vertical guide) or Y (horizontal guide) field and Properties › Transform show where it is, as the rulers measure, and typing a value moves it there. No readiness percentage change. +- **2026-10-16** · Selection: drag a column guide to move its gutter, as in InDesign (#1096). Both guides of the gutter move together and keep its width, stop at the neighbouring guides and the margins, and snap to the document grid, guides and objects, or with Shift to the ruler's tick marks; Escape cancels and the drag is one undo step. Locked column guides (the default) are not picked. A document page takes the result as its own columns; on a parent page it passes to the pages that follow it. `layout.moveColumnGuide` does the same over the control channel and MCP. No readiness percentage change. +- **2026-10-16** · Layout: autoflow, inserted pages and new parents follow dragged column guides (#1096). Autoflow sets one frame per dragged column and counts the pages it adds from them; Insert Pages and New Parent keep the custom positions with the column count and gutter; a page that moves to the other side of the spine (inserted, deleted or moved pages, Duplicate Spread, a new parent's other page) has them mirrored across its margin box, as InDesign does; `document.inspect` reports each page's gutter, column rects and whether its columns are custom. No readiness percentage change. +- **2026-10-16** · Layout: Margins and Columns keeps dragged column guides unless the column count or gutter changes (#1096). The dialog sends every field on OK, so a margin-only change re-divided the columns evenly. Margin changes keep the positions; the columns follow them only while they fit the margin box. No readiness percentage change. +- **2026-10-16** · Lock Guides and Lock Column Guides are commands in View ▸ Grids & Guides (`view.lockGuides`, ⌥⌘;, and `view.lockColumnGuides`), so the control channel and MCP reach them. Lock Column Guides is an undo step, is saved with the document, on in new ones, and read from and written to IDML's `ColumnGuideLocked`, which export always wrote as locked (#1096). No readiness percentage change. +- **2026-10-16** · IDML: a page keeps column guides that were dragged off centre (InDesign's Custom columns). They were divided evenly on import, so the gutter sprang back to the middle; the imported positions now place the columns, with the canvas guides, snapping and text placement following them, and they are written back on export. Layout › Margins and Columns re-divides them evenly when the count or gutter changes, as InDesign's does. No readiness percentage change. +- **2026-10-16** · IDML: custom column positions are checked before they are used (#1096). A set must give two edges per column, ascending from the left margin to the right one; any other (a wrong count, unsorted or non-numeric values, a list longer than 216 columns allow, or positions left behind by a margin or page-size change) is the even split, in the canvas, on import and on export, instead of columns drawn outside the margins. 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. From 3bdd70a9758d0b47341f310f298b0181226933ba Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 22 Oct 2026 17:57:35 +0700 Subject: [PATCH 14/29] README: the app icon above the title --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 4ca03d4dc..cd0f56479 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,10 @@

+

+ DesignCraft icon: an engraved cat in a polka-dot scarf on a green tile +

+

DesignCraft

From d2bdb0866fb73cf9aac012dc4c08a8854ae2b92e Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 22 Oct 2026 09:26:43 -0400 Subject: [PATCH 15/29] Paste: other apps' text goes into a text caret after copying objects (#1344) * Paste: other apps' text goes into a text caret even after copying objects (#212) * Paste: text that matches a copied frame still pastes; groups with text frames aren't anchored (#212) --- crates/engine/src/cmd/anchored.rs | 2 +- crates/engine/src/cmd/edit.rs | 109 ++++++++++++++++++++++++++++-- crates/engine/src/cmd/mod.rs | 1 + crates/engine/src/cmd/object.rs | 3 +- crates/ui-egui/src/lib.rs | 31 +-------- 5 files changed, 108 insertions(+), 38 deletions(-) diff --git a/crates/engine/src/cmd/anchored.rs b/crates/engine/src/cmd/anchored.rs index dc7127459..6d09f89dd 100644 --- a/crates/engine/src/cmd/anchored.rs +++ b/crates/engine/src/cmd/anchored.rs @@ -109,7 +109,7 @@ fn position_param(p: &Value, base: &AnchorPosition) -> Result { } /// Text frames can't be anchored yet (their stories need frames on a spread). -fn check_item(it: &Item) -> Result<()> { +pub(crate) fn check_item(it: &Item) -> Result<()> { let mut ok = true; it.walk(&mut |i| ok &= !matches!(i.content, Content::Text(_))); if ok { Ok(()) } else { Err(bad("anchored.insert", "text frames can't be anchored yet")) } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index e5a2d2296..fb8848a90 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -43,24 +43,64 @@ fn copy_text(s: &mut Session) -> Result> { Ok(Some(text)) } +/// Plain text for the system clipboard after copying objects: the copied text frames' stories, +/// or U+FFFC (object replacement character) when none has text. Paste reads it back as "the +/// copied objects", not as text. +pub fn copied_objects_text(s: &Session) -> String { + let Some(clip) = &s.clipboard else { return '\u{FFFC}'.to_string() }; + let mut stories = Vec::new(); + for it in clip.spreads.first().map(|sp| sp.items.as_slice()).unwrap_or_default() { + it.walk(&mut |i| { + if let Some(tf) = i.text_frame() + && !stories.contains(&tf.story) + { + stories.push(tf.story); + } + }); + } + let text = stories.iter().filter_map(|id| clip.story(*id)).map(plain).filter(|t| !t.is_empty()).collect::>().join("\n"); + if text.is_empty() { '\u{FFFC}'.to_string() } else { text } +} + +/// `text` (the system clipboard's) is what the last copy put there: objects were copied last and +/// it is their placeholder, so Paste stands for the copied objects. +fn is_objects_placeholder(s: &Session, text: &str) -> bool { + s.text_clipboard.is_none() && s.clipboard.is_some() && text.replace("\r\n", "\n") == copied_objects_text(s).replace("\r\n", "\n") +} + /// Paste text at the insertion point: the formatted copy when the system clipboard still holds /// what was copied here (or `formatted` is forced), else plain text in the insertion format. +/// With `formatted`, objects copied last paste as anchored objects when `text` is absent or their +/// placeholder; other text was copied in another app since. Objects that can't be anchored (text +/// frames, into a table cell) paste as their placeholder text. fn paste_text(s: &mut Session, text: Option, formatted: bool) -> Result { let t = s.doc()?.selection.text.ok_or_else(|| super::bad("edit.paste", "no insertion point"))?; let clip = s.text_clipboard.clone(); - // Items copied last (no text copied since) paste into the text as anchored objects. - if formatted - && clip.is_none() + let own = formatted && clip.is_none() && s.clipboard.is_some() && text.as_deref().is_none_or(|x| is_objects_placeholder(s, x)); + if own && t.cell.is_none() && let Some(items) = s.clipboard.clone() { let list: Vec = items.spreads.first().map(|sp| sp.items.iter().map(|i| (**i).clone()).collect()).unwrap_or_default(); - if !list.is_empty() && list.iter().all(|i| !i.is_text_frame()) { + if !list.is_empty() && list.iter().all(|i| super::anchored::check_item(i).is_ok()) { return s.edit(|d, sel| { let st = d.story_mut(t.story).ok_or(designcraft_doc::DocError::NoStory(t.story))?; let r = t.range(); st.delete(r.start.min(st.len())..r.end.min(st.len())); - let end = super::anchored::anchor_items(d, t.story, r.start, list.clone(), &Default::default())?; + // Fresh ids, story and asset copies for every paste, as on the page. + let mut stories = std::collections::HashMap::new(); + let fresh: Vec = list + .iter() + .map(|i| { + let mut i = i.clone(); + super::object::renumber(d, &items, &mut i, &mut stories); + if d.layer(i.layer).is_none() { + i.layer = d.default_layer(); + } + i + }) + .collect(); + let end = super::anchored::anchor_items(d, t.story, r.start, fresh, &Default::default())?; sel.text = Some(designcraft_doc::TextSel { anchor: end, focus: end, ..t }); Ok(json!({"pos": end, "anchored": list.len()})) }); @@ -80,6 +120,8 @@ fn paste_text(s: &mut Session, text: Option, formatted: bool) -> Result< Ok(json!({"pos": end, "formatted": true})) }); } + // U+FFFC stands for objects with no text. + let text = if own { Some(copied_objects_text(s)).filter(|m| m != "\u{FFFC}") } else { text }; let text = text.or_else(|| clip.map(|(_, p)| p)).ok_or_else(|| super::bad("edit.paste", "clipboard is empty"))?; let text = outside_text(&text)?; s.execute("text.insert", &json!({"text": text, "raw": true})) @@ -327,7 +369,8 @@ pub fn specs() -> Vec { if s.doc()?.selection.text.is_some() { return paste_text(s, text.map(str::to_string), true); } - if let Some(text) = text { + // The placeholder of an object copy pastes the copied objects. + if let Some(text) = text.filter(|t| !is_objects_placeholder(s, t)) { // What our own text copy put on the clipboard keeps its formatting. let slice = s.text_clipboard.clone().filter(|(_, plain)| text.replace("\r\n", "\n") == *plain).map(|(slice, _)| slice); return paste_text_frame(s, p, text, slice.as_deref()); @@ -538,6 +581,60 @@ mod text_clipboard_tests { s.doc().unwrap().doc.check().unwrap(); } + /// Copying a rectangle, then text in another app, pasted the rectangle into the text (#212). + #[test] + fn paste_at_a_caret_prefers_other_apps_text_to_copied_objects() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let story = frame(&mut s, "ab"); + let rect = s.execute("frame.create", &json!({"rect": [72, 400, 200, 480]})).unwrap()["id"].clone(); + s.execute("selection.set", &json!({"ids": [rect]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + let marker = copied_objects_text(&s); + s.execute("text.select", &json!({"story": story.0, "anchor": 2, "focus": 2})).unwrap(); + let r = s.execute("edit.paste", &json!({"text": "From elsewhere"})).unwrap(); + assert!(r.get("anchored").is_none(), "{r}"); + assert_eq!(s.doc().unwrap().doc.story(story).unwrap().text, "abFrom elsewhere"); + // What the object copy put on the system clipboard still pastes the objects. + assert_eq!(s.execute("edit.paste", &json!({"text": marker})).unwrap()["anchored"], 1); + // With no insertion point too: the rectangle, not a text frame holding the marker. + s.execute("edit.deselectAll", &json!({})).unwrap(); + let r = s.execute("edit.paste", &json!({"text": marker})).unwrap(); + let id = ItemId(r["ids"][0].as_u64().unwrap()); + assert!(s.doc().unwrap().doc.item(id).unwrap().text_frame().is_none()); + s.doc().unwrap().doc.check().unwrap(); + // Paste without Formatting inserts the text given; empty text is no text. + s.execute("text.select", &json!({"story": story.0, "anchor": 0, "focus": 0})).unwrap(); + assert!(s.execute("edit.pasteWithoutFormatting", &json!({"text": ""})).is_err()); + } + + /// Text frames, and groups holding one, can't be anchored: at a caret their copy pastes as text. + #[test] + fn copied_text_frames_paste_at_a_caret_as_their_text() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let target = frame(&mut s, "ab"); + let copy_and_paste = |s: &mut Session, ids: Value, text: Value| { + s.execute("selection.set", &json!({"ids": ids})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("text.select", &json!({"story": target.0, "anchor": 0, "focus": 0})).unwrap(); + s.execute("edit.paste", &json!({"text": text})).unwrap() + }; + let chapter = s.execute("frame.create", &json!({"rect": [72, 400, 300, 480], "content": "text", "text": "Chapter 1"})).unwrap()["id"].clone(); + // The same text copied in another app, and the system clipboard read back as absent. + let r = copy_and_paste(&mut s, json!([chapter]), json!("Chapter 1")); + assert!(r.get("anchored").is_none(), "{r}"); + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.story(target).unwrap().text, "Chapter 1Chapter 1ab"); + // A group with a text frame inside, its own placeholder on the system clipboard. + let rect = s.execute("frame.create", &json!({"rect": [72, 500, 200, 560]})).unwrap()["id"].clone(); + let group = s.execute("object.group", &json!({"ids": [chapter, rect]})).unwrap()["id"].clone(); + let r = copy_and_paste(&mut s, json!([group]), Value::Null); + assert!(r.get("anchored").is_none(), "{r}"); + assert_eq!(s.doc().unwrap().doc.story(target).unwrap().text, "Chapter 1Chapter 1Chapter 1ab"); + s.doc().unwrap().doc.check().unwrap(); + } + #[test] fn outside_text_never_pastes_markers() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index a4d5413bb..1d6294ea6 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -17,6 +17,7 @@ mod endnotes; mod export; mod file; pub(crate) mod find; +pub use edit::copied_objects_text; pub use find::same_find_domain; pub(crate) mod flex; mod fonts; diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 82f33a6d8..4ccb5c823 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -1074,7 +1074,8 @@ fn adopt_or_dangle(dst: &mut Document, src: &Document, id: AssetId) -> AssetId { dst.adopt_asset(src, id).unwrap_or_else(|| AssetId(dst.alloc())) } -fn renumber(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut HashMap) { +/// Give `it` (an item of `src`) fresh ids from `dst`, with copies of its stories and the assets it uses. +pub(crate) fn renumber(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut HashMap) { it.id = ItemId(dst.alloc()); let my_id = it.id; if let Some(m) = it.media.as_mut() diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3674b3e81..0c155851f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -810,7 +810,7 @@ impl DesignApp { Some(t.to_string()) } None if !self.native_menu => { - self.object_clip_text = Some(self.copied_objects_text()); + self.object_clip_text = Some(designcraft_engine::cmd::copied_objects_text(&self.session)); self.object_clip_text.clone() } None => { @@ -910,35 +910,6 @@ impl DesignApp { params } - /// Plain text for the system clipboard after copying objects: the copied text frames' stories, - /// or U+FFFC (object replacement character) when none has text. - fn copied_objects_text(&self) -> String { - let mut stories = Vec::new(); - if let Some(clip) = &self.session.clipboard - && let Some(sp) = clip.spreads.first() - { - for it in &sp.items { - it.walk(&mut |i| { - if let Some(tf) = i.text_frame() - && !stories.contains(&tf.story) - { - stories.push(tf.story); - } - }); - } - } - let text = stories - .iter() - .filter_map(|id| self.session.clipboard.as_ref()?.story(*id)) - .map(|st| { - st.text.chars().filter(|c| !('\u{E000}'..='\u{E1FF}').contains(c)).map(|c| if c == '\u{2028}' { '\n' } else { c }).collect::() - }) - .filter(|t| !t.is_empty()) - .collect::>() - .join("\n"); - if text.is_empty() { '\u{FFFC}'.to_string() } else { text } - } - /// Handle requests produced by tools/commands (dialogs, view changes, file pickers). pub fn after_engine(&mut self) { let reqs = std::mem::take(&mut self.session.ui_requests); From 1500b444b57a20d7d3fa7194faab94f853788bee Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 22 Oct 2026 09:26:51 -0400 Subject: [PATCH 16/29] Hidden characters: trailing spaces show their dots before the paragraph mark (#1345) * Hidden characters: trailing spaces show their dots before the paragraph mark (#594) * Hidden characters: skip glyphs whose offset isn't a character boundary --- crates/ui-egui/src/canvas.rs | 77 ++++++++++++++++++++++++++---------- 1 file changed, 57 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 9868d4d8b..ae6394bbd 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -2716,33 +2716,47 @@ fn draw_hidden_characters(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc for l in &ft.lines { let size = (l.ascent * 0.75 * xf.zoom).clamp(6.0, 40.0) as f32; let font = egui::FontId::proportional(size); - for g in &l.glyphs { - if g.len == 0 { - continue; - } - let ch = story.text[g.byte.min(story.text.len())..].chars().next().unwrap_or(' '); - let mark = match ch { - ' ' => "·", - '\t' => "»", - '\u{2028}' => "¬", - '\u{A0}' => "°", - _ => continue, - }; - let p = xf.to_screen(m * Point::new(g.x + if ch == ' ' { g.adv / 2.0 } else { 0.0 }, l.baseline)); - let align = if ch == ' ' { egui::Align2::CENTER_BOTTOM } else { egui::Align2::LEFT_BOTTOM }; + for (x, mark, centered) in hidden_marks(&story.text, l) { + let p = xf.to_screen(m * Point::new(x, l.baseline)); + let align = if centered { egui::Align2::CENTER_BOTTOM } else { egui::Align2::LEFT_BOTTOM }; painter.text(p, align, mark, font.clone(), col); } - if l.last_in_para { - let end = l.range.end; - let mark = if end >= story.text.len() { "#" } else { "¶" }; - let p = xf.to_screen(m * Point::new(l.end_x + 1.0, l.baseline)); - painter.text(p, egui::Align2::LEFT_BOTTOM, mark, font.clone(), col); - } } } } } +/// The hidden-character marks on line `l` of a story with text `text`: frame-space x, mark, and +/// whether the mark is centered on x (spaces) or starts at it. +fn hidden_marks(text: &str, l: &compose::Line) -> Vec<(f64, &'static str, bool)> { + let mut out = Vec::new(); + for g in &l.glyphs { + if g.len == 0 { + continue; + } + let Some(ch) = text.get(g.byte..).and_then(|t| t.chars().next()) else { continue }; + let mark = match ch { + ' ' => "·", + '\t' => "»", + '\u{2028}' => "¬", + '\u{A0}' => "°", + _ => continue, + }; + if ch == ' ' { + out.push((g.x + g.adv / 2.0, mark, true)); + } else { + out.push((g.x, mark, false)); + } + } + if l.last_in_para { + // The spaces trimmed off the line's end sit past `end_x`; the paragraph mark follows them. + let end = l.glyphs.iter().filter(|g| g.len > 0 && !g.visible && g.x >= l.end_x - 1e-9).map(|g| g.x + g.adv).fold(l.end_x, f64::max); + let mark = if l.range.end >= text.len() { "#" } else { "¶" }; + out.push((end + 1.0, mark, false)); + } + out +} + /// View › Flattener Preview: red over every object that involves transparency (opacity, blend /// modes, effects, knockout) — what flattening or export rasterising affects. fn draw_flattener_preview(painter: &egui::Painter, xf: &Xf, doc: &Document, layout: &CanvasLayout) { @@ -5560,6 +5574,29 @@ mod tests { assert_eq!(size, 18.0, "{key:?} applies the typed size"); } } + + #[test] + fn trailing_spaces_show_dots_before_the_paragraph_mark() { + let text = "ab \ncd "; + let mut d = Document::new(&designcraft_doc::build::NewDocument::default()); + let lid = d.default_layer(); + let rect = DRect::new(0.0, 0.0, 300.0, 100.0); + let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), rect, lid, text, Default::default()).unwrap(); + let cs = compose::compose_story(&d, sid, &compose::ComposeOptions::default()); + let lines: Vec<_> = cs.frames.iter().flat_map(|f| &f.lines).collect(); + assert_eq!(lines.len(), 2); + for (l, end_mark) in lines.iter().zip(["¶", "#"]) { + let marks = hidden_marks(text, l); + let dots: Vec = marks.iter().filter(|m| m.1 == "·").map(|m| m.0).collect(); + assert_eq!(dots.len(), 2, "a dot for each trailing space: {marks:?}"); + let &(para_x, mark, _) = marks.last().unwrap(); + assert_eq!(mark, end_mark); + // The dots sit past the last letter, and the mark comes after both spaces. + let space = l.glyphs.iter().rev().find(|g| g.len > 0).unwrap(); + assert!(dots.iter().all(|&x| x > l.end_x && x < para_x), "{dots:?} then {mark} at {para_x}"); + assert!(para_x >= space.x + space.adv, "{mark} at {para_x} overlaps the last space"); + } + } } #[cfg(test)] From 291b39a1f30ee7b2df53dab6c18cc78e141468ac Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 22 Oct 2026 09:27:00 -0400 Subject: [PATCH 17/29] Edit: the Paste in Place shortcut pastes in place (#1346) * Edit: the Paste in Place shortcut pastes in place * Edit: the Paste in Place chord handling is native-only (web gets the key press) --- crates/ui-egui/src/canvas.rs | 71 ++++++++++++++++++++++++++++++++++++ crates/ui-egui/src/menus.rs | 14 +++++++ 2 files changed, 85 insertions(+) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ae6394bbd..318f82388 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1583,6 +1583,21 @@ fn field_focused_id(ctx: &egui::Context) -> egui::Id { pub fn begin_frame(ctx: &egui::Context) { let (id, focused) = (field_focused_id(ctx), ctx.text_edit_focused()); ctx.data_mut(|d| d.insert_temp(id, focused)); + #[cfg(not(target_arch = "wasm32"))] + { + let now = ctx.input(|i| i.modifiers); + // The modifiers last frame ended with are the ones this frame's events began with. + ctx.data_mut(|d| { + let (_, end) = d.get_temp::<(egui::Modifiers, egui::Modifiers)>(modifiers_id()).unwrap_or((now, now)); + d.insert_temp(modifiers_id(), (end, now)); + }); + } +} + +/// (held when this frame's events began, held after them). +#[cfg(not(target_arch = "wasm32"))] +fn modifiers_id() -> egui::Id { + egui::Id::new("canvas-frame-modifiers") } /// Caret / text highlight inside a table cell (the cell's lines are offset by the cell origin). @@ -2546,7 +2561,21 @@ fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, r // text must not delete the character before it). let composing_at_start = app.session.tool_composing(); let evs = ui.input(|i| i.events.clone()); + // Native only: egui-winit sends a ⌘+V chord as a paste without its key press, so the modifiers + // held at the paste tell Paste in Place from Paste. The web also gets the key press, and the + // shortcut table has already run the command. A chord's modifiers may be released in the same + // frame, hence the modifiers held at each event. + #[cfg(not(target_arch = "wasm32"))] + let mut held = + ui.data(|d| d.get_temp::<(egui::Modifiers, egui::Modifiers)>(modifiers_id())).map_or_else(|| ui.input(|i| i.modifiers), |(start, _)| start); for e in evs { + #[cfg(not(target_arch = "wasm32"))] + let chord = { + if let egui::Event::ModifiersChanged(m) = &e { + held = *m; + } + if matches!(e, egui::Event::Paste(_)) { crate::menus::paste_chord_command(app, held) } else { None } + }; let composing = composing_at_start || app.session.tool_composing(); match e { egui::Event::Ime(ime) if wants_text => ime_event(app, ime, vi), @@ -2568,6 +2597,15 @@ fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, r let id = if matches!(e, egui::Event::Cut) { "edit.cut" } else { "edit.copy" }; let _ = app.run(id, json!({})); } + // Paste in Place's chord (⌘⌥⇧V unless rebound) arrives as a paste too. + #[cfg(not(target_arch = "wasm32"))] + egui::Event::Paste(_) if chord.is_some() => { + if let Some(id) = chord + && crate::menus::enabled(app, id) + { + crate::menus::activate(app, id, &serde_json::Value::Null); + } + } // Without a native menu bar the copy and paste keys arrive only as these events. egui::Event::Copy | egui::Event::Cut | egui::Event::Paste(_) if !app.native_menu => { let (id, params) = match e { @@ -4278,6 +4316,39 @@ mod tests { assert!((it.bounds().center() - centre).hypot() < 0.01, "{:?} vs {centre:?}", it.bounds()); } + #[test] + fn the_paste_in_place_shortcut_pastes_in_place_and_plain_paste_offsets() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [100, 100, 200, 200]})).unwrap()["id"].as_u64().unwrap(); + let original = app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().bounds(); + app.run("edit.copy", json!({})).unwrap(); + let clip = app.object_clip_text.clone().expect("the copy's placeholder text"); + let mut h = harness(app); + let paste = |h: &mut Harness<'static, DesignApp>, modifiers: egui::Modifiers| { + // As egui-winit delivers ⌃⌥⇧V: the chord's paste and the V release, no V press; here the + // modifiers are released within the same frame. + let release = egui::Event::Key { key: egui::Key::V, physical_key: None, pressed: false, repeat: false, modifiers }; + let none = egui::Event::ModifiersChanged(egui::Modifiers::NONE); + h.input_mut().events.extend([egui::Event::ModifiersChanged(modifiers), egui::Event::Paste(clip.clone()), release, none]); + h.run_steps(2); + let st = h.state().session.doc().unwrap(); + let pasted = *st.selection.items.first().expect("the copy is selected"); + assert_ne!(pasted.0, id); + st.doc.item(pasted).unwrap().bounds() + }; + let linux = egui::Modifiers { alt: true, ctrl: true, shift: true, mac_cmd: false, command: true }; + assert_eq!(paste(&mut h, linux), original, "Paste in Place"); + let moved = paste(&mut h, egui::Modifiers::COMMAND); + assert!((moved.x0 - original.x0 - 12.0).abs() < 1e-9 && (moved.y0 - original.y0 - 12.0).abs() < 1e-9, "{moved:?}"); + // The modifiers went down in an earlier frame than the paste. + h.event_modifiers(egui::Event::Paste(clip.clone()), linux); + h.run_steps(2); + let st = h.state().session.doc().unwrap(); + let pasted = *st.selection.items.first().expect("the copy is selected"); + assert_eq!(st.doc.item(pasted).unwrap().bounds(), original); + } + #[test] fn edit_paste_from_the_menu_pastes_svg_on_the_system_clipboard_as_paths() { let services = crate::Services { clipboard_text: Some(Box::new(|| Some(ART.to_string()))), ..Default::default() }; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index fb43f8cb9..af2a91fc3 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -3050,6 +3050,20 @@ fn key_matches(m: egui::Modifiers, k: egui::Key, key: egui::Key, modifiers: egui matches.then_some(k == key && m.shift == modifiers.shift) } +/// The command a paste event stands for besides plain Paste. egui-winit turns every ⌘+V chord into +/// `Event::Paste` with the clipboard's text and drops the key press, so the shortcut table never +/// sees Paste in Place's chord; the modifiers held when it went down tell them apart. `None` when +/// the chord is another one, or the native menu's accelerator takes it. +#[cfg(not(target_arch = "wasm32"))] +pub fn paste_chord_command(app: &DesignApp, modifiers: egui::Modifiers) -> Option<&'static str> { + let id = "edit.pasteInPlace"; + if app.native_menu && !app.ui.shortcuts.contains_key(id) { + return None; + } + let (m, k) = shortcut_of(app, id).as_deref().and_then(parse_shortcut)?; + (k == egui::Key::V && key_matches(m, k, egui::Key::V, modifiers) == Some(true)).then_some(id) +} + /// Global keyboard shortcuts: menu commands and single-key tool shortcuts. pub fn shortcuts(app: &mut DesignApp, ctx: &egui::Context) { // Only a focused text field takes the keys: the canvas (or a button) having focus after a click From 8f98f3dc8bfac09d69f949c39bf97f0861621b6c Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 22 Oct 2026 09:28:11 -0400 Subject: [PATCH 18/29] Keyboard Shortcuts: import an InDesign shortcut set (#1296) * #1180: import an InDesign keyboard shortcut set Edit > Keyboard Shortcuts gets Import InDesign Set..., which reads the .txt that InDesign's Show Set writes (window.importShortcuts {path|text}). Matched commands take the set's Default shortcut, or lose theirs when every occurrence says [none defined]; other commands give up keys the set takes. The report lists changes, cleared conflicts, and the items that could not be matched or read. Tool keys stay fixed. * #1180: read the set file through the checked reader * #1180: when two items want the same keys, the later one takes them --- ROADMAP.md | 1 + apps/designcraft-web/src/web.rs | 2 + apps/designcraft/src/main.rs | 1 + crates/ui-egui/src/dialogs.rs | 13 +- crates/ui-egui/src/lib.rs | 5 + crates/ui-egui/src/menus.rs | 19 +- crates/ui-egui/src/shortcut_import.rs | 611 ++++++++++++++++++++++++++ docs/file-format-parity.md | 2 +- docs/target-app-parity.md | 2 +- docs/ui-parity.md | 2 +- 10 files changed, 651 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/shortcut_import.rs diff --git a/ROADMAP.md b/ROADMAP.md index 8a2352e86..d3ef17e47 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-16** · Edit › Keyboard Shortcuts imports a set saved by InDesign's Show Set (.txt, Windows or Mac key names, UTF-8 or UTF-16): matched commands take its Default shortcuts or lose theirs, other commands give up keys it takes, and a report lists what it changed and the items it could not match (`window.importShortcuts`, #1180). Tool keys stay fixed. No readiness percentage change. - **2026-10-22** · A ruler guide dragged with the Selection tools, out of a ruler, on its own or with other selected guides, snaps along its axis as objects do (#1221): to other ruler guides, margins, columns, bleed, page and object edges and centers (with the smart-guide mark) and the document grid, within the snap zone and following Snap to Guides and Smart Guides. Shift snaps to the ruler's ticks and Cmd suspends snapping. The preview line, the position readout and the drop use the same snapped position. No readiness percentage change. - **2026-10-22** · macOS: the app menu has a Language submenu after Settings… with each interface language in its own name and the current one checked, as in the suite's other apps; Preferences › General › Interface Language stays. No readiness percentage change. - **2026-10-22** · macOS menu bar: the menus keep working after the interface language or Show CJK Features changes (a rebuilt menu bar lost every click, Quit included), and its key equivalents are the shortcuts in effect, so a shortcut moved in the Keyboard Shortcuts editor leaves its old menu item. No readiness percentage change. diff --git a/apps/designcraft-web/src/web.rs b/apps/designcraft-web/src/web.rs index fe0f4a7fa..27d236a2f 100644 --- a/apps/designcraft-web/src/web.rs +++ b/apps/designcraft-web/src/web.rs @@ -395,6 +395,8 @@ 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 == "shortcuts" { + rfd::AsyncFileDialog::new().add_filter("Shortcut set (text)", &["txt"]) } else if request.purpose == "place" { rfd::AsyncFileDialog::new().add_filter("Graphics", IMAGE_EXTS) } else { diff --git a/apps/designcraft/src/main.rs b/apps/designcraft/src/main.rs index b56878176..13416e4e0 100644 --- a/apps/designcraft/src/main.rs +++ b/apps/designcraft/src/main.rs @@ -187,6 +187,7 @@ fn open_filters(purpose: &str) -> &'static [OpenFilter] { match purpose { "swatches" => &[OpenFilter { name: "Swatch Exchange (ASE)", extensions: &["ase"] }], "script" => &[OpenFilter { name: "Script", extensions: &["dcscript", "txt", "json"] }], + "shortcuts" => &[OpenFilter { name: "Shortcut set (text)", extensions: &["txt"] }], "icc" => &[OpenFilter { name: "ICC profile", extensions: &["icc", "icm"] }], "book" => &[OpenFilter { name: "Book", extensions: &["dcbook"] }], "xml" => &[OpenFilter { name: "XML", extensions: &["xml"] }], diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 8b4043787..6b60b1296 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -315,9 +315,16 @@ fn keyboard_shortcuts(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { if !msg.is_empty() { ui.label(egui::RichText::new(msg).color(egui::Color32::from_rgb(240, 180, 60))); } - if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Reset All to Defaults"))).clicked() { - let _ = app.run("window.resetShortcuts", json!({})); - } + ui.horizontal(|ui| { + if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Reset All to Defaults"))).clicked() { + let _ = app.run("window.resetShortcuts", json!({})); + } + if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Import InDesign Set…"))).clicked() + && let Some(msg) = crate::shortcut_import::pick_and_import(app) + { + d.fields.insert("message".into(), json!(msg)); + } + }); } /// File › Print, with the printers the system knows. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0c155851f..18fa402a5 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -27,6 +27,7 @@ mod prefs; pub mod render_worker; mod rtl; mod section_options; +mod shortcut_import; pub mod story_editor; pub mod taskbar; pub mod theme; @@ -1033,6 +1034,10 @@ 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())); for file in files { + if file.request.purpose == "shortcuts" { + shortcut_import::import_delivered(self, &file.bytes); + continue; + } if self.ui.dialog.is_some() { self.status( crate::i18n::tr(&self.ui.language, "{name}: import cancelled while a dialog is open; choose the file again") diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index af2a91fc3..2a271324a 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -85,6 +85,12 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[ ("window.richBlack", "Appearance of Black", None, "{on: bool} — show 100% black as rich black on screen (off: accurately)"), ("window.setShortcut", "Set Shortcut", None, "{id, shortcut: \"Cmd+Alt+J\" | \"\" (none) | null (default)} → {shortcut, conflicts: [ids]}"), ("window.resetShortcuts", "Reset Shortcuts", None, "{} — every command back to its default shortcut"), + ( + "window.importShortcuts", + "Import InDesign Shortcut Set", + None, + "{path | text} — a set saved by InDesign's Show Set (.txt): matched commands take its Default shortcuts (or none), other commands lose keys it takes → {set, imported, changed, conflictsCleared, skipped (an earlier item whose keys a later one took), unmatched, unmatchedWithoutShortcut, unreadable}", + ), ("app.findChange", "Find/Change…", Some("Cmd+F"), "{}"), ("app.insertTableDialog", "Create Table…", None, "{} — Insert Table dialog (body/header/footer rows, columns)"), ( @@ -1705,6 +1711,17 @@ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option { + let text = match (p.get("text").and_then(Value::as_str), p.get("path").and_then(Value::as_str)) { + (Some(text), _) => text.to_string(), + (None, Some(path)) => match crate::shortcut_import::read_file(path) { + Ok(text) => text, + Err(e) => return Some(Err(e)), + }, + (None, None) => return Some(Err("give the set's path or text".into())), + }; + crate::shortcut_import::import(app, &text) + } "view.snapPreferences" => { let b = |k: &str| p.get(k).and_then(Value::as_bool); let ui = &mut app.ui; @@ -3009,7 +3026,7 @@ pub fn all_menu_items() -> Vec<(String, String)> { out } -fn parse_shortcut(sc: &str) -> Option<(egui::Modifiers, egui::Key)> { +pub(crate) fn parse_shortcut(sc: &str) -> Option<(egui::Modifiers, egui::Key)> { let mut m = egui::Modifiers::NONE; let mut key = None; for part in sc.split('+').filter(|s| !s.is_empty()) { diff --git a/crates/ui-egui/src/shortcut_import.rs b/crates/ui-egui/src/shortcut_import.rs new file mode 100644 index 000000000..9ccbef1b9 --- /dev/null +++ b/crates/ui-egui/src/shortcut_import.rs @@ -0,0 +1,611 @@ +//! Importing a keyboard shortcut set that InDesign's Keyboard Shortcuts dialog saved as text +//! (Show Set): `window.importShortcuts`. +//! +//! The file lists items under `Product area : ` headers, one per line: +//! ` --- [none defined]` or ` --- : , : `. Item names +//! use `: ` between submenu levels. Only the Default context applies (DesignCraft has no +//! shortcut contexts); a type command with no Default entry takes its Text entry. + +use std::collections::{BTreeSet, HashMap}; + +use serde_json::{Value, json}; + +use crate::DesignApp; +use crate::menus::{self, Item}; + +/// Largest set file read. InDesign's full set is a few hundred kilobytes (twice that as UTF-16). +pub const MAX_BYTES: usize = 8 << 20; +/// Entries read per item: a real item has one or two per context. +const MAX_ENTRIES: usize = 64; + +/// One `: ` entry of an item. +struct Entry { + context: String, + keys: String, +} + +struct SetItem { + area: String, + name: String, + entries: Vec, +} + +struct ParsedSet { + name: String, + items: Vec, +} + +/// Text from the bytes of a set file: UTF-8 (with or without a BOM) or UTF-16 (by its BOM, or +/// by the zero bytes of ASCII text without one). +pub fn decode(bytes: &[u8]) -> Result { + if bytes.len() > MAX_BYTES { + return Err(format!("the file is larger than {} MB", MAX_BYTES >> 20)); + } + let utf16 = |rest: &[u8], le: bool| -> String { + let units = rest.as_chunks::<2>().0.iter().map(|&c| if le { u16::from_le_bytes(c) } else { u16::from_be_bytes(c) }); + char::decode_utf16(units).map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER)).collect() + }; + Ok(match bytes { + [0xFF, 0xFE, rest @ ..] => utf16(rest, true), + [0xFE, 0xFF, rest @ ..] => utf16(rest, false), + [0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(), + [a, 0, ..] if *a != 0 => utf16(bytes, true), + [0, b, ..] if *b != 0 => utf16(bytes, false), + _ => String::from_utf8_lossy(bytes).into_owned(), + }) +} + +/// Reads and decodes a set file, refusing one over [`MAX_BYTES`]. +pub fn read_file(path: &str) -> Result { + let cap = u64::try_from(MAX_BYTES).unwrap_or(u64::MAX); + let bytes = designcraft_engine::io::read_capped(path, cap).map_err(|e| format!("can't read {path}: {e}"))?; + decode(&bytes) +} + +/// `Label : value` with any spacing around the colon, when the line starts with `label`. +fn header<'a>(line: &'a str, label: &str) -> Option<&'a str> { + let rest = line.get(..label.len()).filter(|h| h.eq_ignore_ascii_case(label)).and_then(|_| line.get(label.len()..))?; + rest.trim_start().strip_prefix(':').map(str::trim) +} + +fn parse(text: &str) -> Result { + let text = text.strip_prefix('\u{feff}').unwrap_or(text); + let mut set = ParsedSet { name: String::new(), items: Vec::new() }; + let mut area = String::new(); + let mut header_seen = false; + for line in text.lines() { + let line = line.trim_end_matches('\r'); + let trimmed = line.trim(); + if let Some(name) = header(trimmed, "Shortcut Set") { + set.name = name.to_string(); + header_seen = true; + } else if let Some(a) = header(trimmed, "Product area") { + area = a.to_string(); + header_seen = true; + } else if let Some((name, keys)) = trimmed.split_once(" --- ") { + let name = name.trim(); + if name.is_empty() { + continue; + } + set.items.push(SetItem { area: area.clone(), name: name.to_string(), entries: entries(keys) }); + } + } + if set.items.is_empty() && !header_seen { + return Err("not a shortcut set: no `Product area` or ` --- ` lines".into()); + } + Ok(set) +} + +/// The entries after ` --- `: none for `[none defined]`. A comma is also a key (`Ctrl+,`), so a +/// piece without `: ` belongs to the entry before it. +fn entries(keys: &str) -> Vec { + let keys = keys.trim(); + if keys.eq_ignore_ascii_case("[none defined]") || keys.is_empty() { + return Vec::new(); + } + let mut pieces: Vec = Vec::new(); + for piece in keys.split(", ") { + match pieces.last_mut() { + Some(last) if !piece.contains(": ") => { + last.push_str(", "); + last.push_str(piece); + } + _ => pieces.push(piece.to_string()), + } + } + pieces + .into_iter() + .take(MAX_ENTRIES) + .filter_map(|p| { + let (context, keys) = p.split_once(": ")?; + Some(Entry { context: context.trim().to_string(), keys: keys.trim().to_string() }) + }) + .collect() +} + +/// Whether the keys use Mac modifier names, where Ctrl is the Control key rather than the +/// command modifier. +fn is_mac_set(set: &ParsedSet) -> bool { + set.items.iter().flat_map(|i| &i.entries).any(|e| { + let k = e.keys.to_lowercase(); + k.contains("cmd") || k.contains("command") || k.contains('⌘') || k.contains("opt") || k.contains('⌥') + }) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Mod { + Command, + Alt, + Shift, + Control, +} + +/// Keys as InDesign writes them (`Shift+Ctrl+S`, `Ctrl+Num 5`, `Page Down`, `⇧⌘S`) as a +/// DesignCraft shortcut string (`Cmd+Shift+S`). Ctrl is the command modifier in a Windows set. +fn read_keys(keys: &str, mac: bool) -> Result { + const SYMBOLS: &[(&str, Mod)] = &[("⌘", Mod::Command), ("⌥", Mod::Alt), ("⇧", Mod::Shift), ("⌃", Mod::Control)]; + const WORDS: &[(&str, Mod)] = &[ + ("command", Mod::Command), + ("cmd", Mod::Command), + ("option", Mod::Alt), + ("opt", Mod::Alt), + ("alt", Mod::Alt), + ("shift", Mod::Shift), + ("control", Mod::Control), + ("ctrl", Mod::Control), + ]; + let mut m = egui::Modifiers::NONE; + let mut set = |md: Mod| match md { + Mod::Command => m.command = true, + Mod::Alt => m.alt = true, + Mod::Shift => m.shift = true, + Mod::Control if mac => m.ctrl = true, + Mod::Control => m.command = true, + }; + let mut rest = keys.trim(); + 'strip: loop { + for (sym, md) in SYMBOLS { + if let Some(r) = rest.strip_prefix(sym) { + set(*md); + rest = r.strip_prefix('+').unwrap_or(r).trim_start(); + continue 'strip; + } + } + for (word, md) in WORDS { + let Some(head) = rest.get(..word.len()) else { continue }; + let Some(after) = rest.get(word.len()..) else { continue }; + // The word must be followed by a separator and a key: "Alt" alone, or "Altx", is a key name. + let mut chars = after.chars(); + if head.eq_ignore_ascii_case(word) && matches!(chars.next(), Some('+' | ' ' | '-')) && !chars.as_str().is_empty() { + set(*md); + rest = chars.as_str().trim_start(); + continue 'strip; + } + } + break; + } + if m.ctrl { + return Err("Control-key shortcuts are not supported"); + } + let key = key_named(rest.trim()).ok_or("unknown key")?; + let sc = menus::shortcut_string(m, key); + // Only a string the shortcut dispatcher reads back as these keys is imported. + match menus::parse_shortcut(&sc) { + Some((pm, pk)) if pk == key && same_mods(pm, m) => Ok(sc), + _ => Err("unknown key"), + } +} + +fn same_mods(a: egui::Modifiers, b: egui::Modifiers) -> bool { + a.command == b.command && a.alt == b.alt && a.shift == b.shift && a.ctrl == b.ctrl +} + +/// A key by the name InDesign gives it (Windows words, Mac symbols), case- and space-insensitive. +fn key_named(name: &str) -> Option { + use egui::Key; + if name.is_empty() { + return None; + } + let squashed: String = name.chars().filter(|c| !c.is_whitespace()).collect::().to_lowercase(); + // The numeric keypad: egui doesn't tell its keys apart from the main ones. + let n = squashed.strip_prefix("numpad").or_else(|| squashed.strip_prefix("num").filter(|r| !r.is_empty() && *r != "lock")).unwrap_or(&squashed); + let key = match n { + "up" | "uparrow" | "arrowup" | "↑" => Key::ArrowUp, + "down" | "downarrow" | "arrowdown" | "↓" => Key::ArrowDown, + "left" | "leftarrow" | "arrowleft" | "←" => Key::ArrowLeft, + "right" | "rightarrow" | "arrowright" | "→" => Key::ArrowRight, + "pageup" | "pgup" | "⇞" => Key::PageUp, + "pagedown" | "pgdn" | "⇟" => Key::PageDown, + "home" | "↖" => Key::Home, + "end" | "↘" => Key::End, + "esc" | "escape" | "⎋" => Key::Escape, + "tab" | "⇥" => Key::Tab, + "space" | "spacebar" => Key::Space, + "enter" | "return" | "↩" | "⏎" | "⌤" => Key::Enter, + "backspace" | "⌫" => Key::Backspace, + "delete" | "del" | "forwarddelete" | "⌦" => Key::Delete, + "insert" | "ins" | "help" => Key::Insert, + _ => return Key::from_name(n).or_else(|| Key::from_name(&n.to_uppercase())).or_else(|| Key::from_name(name)), + }; + Some(key) +} + +/// Matching form of a label or menu name: no ellipsis, no `&`, single spaces, lower case, and +/// no Show/Hide in front (InDesign names a toggle by what choosing it does now). +fn norm(s: &str) -> String { + let s = s.replace('…', "").replace("...", "").replace('&', ""); + let s = s.split_whitespace().collect::>().join(" ").to_lowercase(); + ["show/hide ", "show ", "hide "].iter().find_map(|p| s.strip_prefix(p).filter(|r| !r.is_empty())).map_or(s.clone(), str::to_string) +} + +/// DesignCraft's commands by menu path and label. +#[derive(Default)] +struct Index { + /// `menu\nsubmenu\nlabel` → ids, in the menu bar. + path: HashMap>, + /// The same from the engine commands' own menu placement, which a UI command (the one with + /// the dialog) may stand in for in the menu bar. + engine_path: HashMap>, + /// (menu, label) → ids, at any depth of that menu. + in_menu: HashMap<(String, String), BTreeSet>, + /// label → ids, anywhere. + label: HashMap>, +} + +impl Index { + fn build() -> Self { + fn walk(ix: &mut Index, items: &[Item], path: &mut Vec) { + for it in items { + match it { + Item::Sub(name, children) => { + path.push(norm(name)); + walk(ix, children, path); + path.pop(); + } + // A shortcut runs the command without parameters; a fixed-parameter variant can't hold one. + Item::Cmd { label, id, params, .. } if params.is_null() => { + let label = norm(label); + let top = path.first().cloned().unwrap_or_default(); + add_path(&mut ix.path, path, &label, id); + ix.in_menu.entry((top, label.clone())).or_default().insert(id.clone()); + ix.label.entry(label).or_default().insert(id.clone()); + } + _ => {} + } + } + } + let mut ix = Index::default(); + for (menu, entries) in menus::menu_tree() { + walk(&mut ix, &entries, &mut vec![norm(menu)]); + } + for c in designcraft_engine::command_specs() { + let label = norm(c.label); + if !c.menu.is_empty() { + let path: Vec = c.menu.iter().map(|m| norm(m)).collect(); + add_path(&mut ix.engine_path, &path, &label, c.id); + } + ix.label.entry(label).or_default().insert(c.id.to_string()); + } + for (id, label, _, _) in menus::UI_COMMANDS { + ix.label.entry(norm(label)).or_default().insert((*id).to_string()); + } + ix + } + + /// The command an item names, trying the most specific match first. Matches by label alone + /// only count when exactly one command has that label. + fn find(&self, area: &str, name: &str) -> Option { + let one = |s: Option<&BTreeSet>| s.filter(|s| s.len() == 1).and_then(|s| s.first().cloned()); + let segments: Vec = name.split(": ").map(norm).collect(); + let last = segments.last().cloned().unwrap_or_default(); + let area = norm(area); + if let Some(menu) = area.strip_suffix(" menu").filter(|m| !m.contains(':')) { + let mut key = menu.to_string(); + for s in &segments { + key.push('\n'); + key.push_str(s); + } + if let Some(id) = one(self.path.get(&key)) { + return Some(id); + } + if segments.len() > 1 + && let Some(id) = one(self.in_menu.get(&(menu.to_string(), segments.join(" ")))) + { + return Some(id); + } + if let Some(id) = one(self.engine_path.get(&key)) { + return Some(id); + } + if let Some(id) = one(self.in_menu.get(&(menu.to_string(), last.clone()))) { + return Some(id); + } + // Menus are arranged differently: the item's own label, if no other command has it. + return one(self.label.get(&last)); + } + if segments.len() == 1 { one(self.label.get(&last)) } else { None } + } +} + +fn add_path(map: &mut HashMap>, path: &[String], label: &str, id: &str) { + let mut key = path.join("\n"); + key.push('\n'); + key.push_str(label); + map.entry(key).or_default().insert(id.to_string()); +} + +/// What the set says about one DesignCraft command, over every item matched to it. +struct Decision { + id: String, + item: String, + /// The first readable shortcut. + shortcut: Option, + /// Every matched item said `[none defined]`. + all_none: bool, +} + +fn command_label(id: &str) -> String { + menus::ui_label(id) + .map(|(l, _)| l.to_string()) + .or_else(|| designcraft_engine::find_command(id).map(|c| c.label.to_string())) + .unwrap_or_else(|| id.to_string()) +} + +fn keys_of(sc: &str) -> Option<(bool, bool, bool, bool, egui::Key)> { + menus::parse_shortcut(sc).map(|(m, k)| (m.command, m.alt, m.shift, m.ctrl, k)) +} + +/// Imports a set: every matched command takes the set's shortcut (or none), another command +/// holding an imported shortcut loses it, and the rest keep theirs. Returns the report. +pub fn import(app: &mut DesignApp, text: &str) -> Result { + if text.len() > MAX_BYTES { + return Err(format!("the set is larger than {} MB", MAX_BYTES >> 20)); + } + let set = parse(text)?; + let mac = is_mac_set(&set); + let ix = Index::build(); + let mut decisions: Vec = Vec::new(); + let mut unmatched = Vec::new(); + let mut unmatched_without_shortcut = 0usize; + let mut unreadable = Vec::new(); + for item in &set.items { + let shown = if item.area.is_empty() { item.name.clone() } else { format!("{} › {}", item.area, item.name) }; + let all_keys = item.entries.iter().map(|e| format!("{}: {}", e.context, e.keys)).collect::>().join(", "); + let Some(id) = ix.find(&item.area, &item.name) else { + if item.entries.is_empty() { + unmatched_without_shortcut += 1; + } else { + let tool = norm(&item.area) == "tools" + && designcraft_tools::TOOL_GROUPS.iter().flat_map(|g| g.iter()).any(|t| norm(t.label) == norm(&item.name)); + let mut row = json!({"item": shown, "keys": all_keys}); + if tool { + row["reason"] = json!("tool keys are fixed"); + } + unmatched.push(row); + } + continue; + }; + let in_context = |ctx: &'static str| item.entries.iter().filter(move |e| e.context.eq_ignore_ascii_case(ctx)).collect::>(); + let text_command = id.starts_with("type.") || id.starts_with("text."); + let mut considered = in_context("Default"); + if considered.is_empty() && text_command { + considered = in_context("Text"); + } + let mut read = None; + let mut why = ""; + for e in &considered { + match read_keys(&e.keys, mac) { + Ok(sc) => { + read = Some(sc); + break; + } + Err(w) => why = w, + } + } + if read.is_none() && !considered.is_empty() { + unreadable.push(json!({"item": shown, "keys": all_keys, "reason": why})); + } + let pos = match decisions.iter().position(|d| d.id == id) { + Some(p) => p, + None => { + decisions.push(Decision { id: id.clone(), item: shown.clone(), shortcut: None, all_none: true }); + decisions.len() - 1 + } + }; + let Some(d) = decisions.get_mut(pos) else { continue }; + d.all_none &= item.entries.is_empty(); + if d.shortcut.is_none() + && let Some(sc) = read + { + d.shortcut = Some(sc); + d.item = shown; + } + } + + let before: HashMap> = menus::effective_shortcuts(app).into_iter().map(|(id, sc)| (id, Some(sc))).collect(); + let mut imported = 0usize; + let mut taken: Vec<((bool, bool, bool, bool, egui::Key), String)> = Vec::new(); + let mut skipped = Vec::new(); + let mut decided: BTreeSet = BTreeSet::new(); + // When two items in the set want the same keys, the later one takes them (the rule shared by + // the Craft apps' importers). + let mut winner: HashMap<(bool, bool, bool, bool, egui::Key), usize> = HashMap::new(); + for (i, d) in decisions.iter().enumerate() { + if let Some(keys) = d.shortcut.as_deref().and_then(keys_of) { + winner.insert(keys, i); + } + } + for (i, d) in decisions.iter().enumerate() { + match &d.shortcut { + Some(sc) => { + let Some(keys) = keys_of(sc) else { continue }; + if let Some(w) = winner.get(&keys).filter(|&&w| w != i).and_then(|&w| decisions.get(w)) { + skipped.push(json!({"id": d.id, "item": d.item, "shortcut": sc, "takenBy": w.id})); + continue; + } + taken.push((keys, d.id.clone())); + if menus::default_shortcut(&d.id).and_then(keys_of) == Some(keys) { + app.ui.shortcuts.remove(&d.id); + } else { + app.ui.shortcuts.insert(d.id.clone(), sc.clone()); + } + } + None if d.all_none => { + if menus::default_shortcut(&d.id).is_none() { + app.ui.shortcuts.remove(&d.id); + } else { + app.ui.shortcuts.insert(d.id.clone(), String::new()); + } + } + None => continue, + } + imported += 1; + decided.insert(d.id.clone()); + } + let mut conflicts = Vec::new(); + for (id, sc) in menus::effective_shortcuts(app) { + if decided.contains(&id) { + continue; + } + // A command sharing its default keys with the one taking them (file.new and the New + // Document dialog) keeps them: the dispatcher already prefers the other. + let twin = |by: &str| { + let default = |id: &str| menus::default_shortcut(id).and_then(keys_of); + default(&id).is_some() && default(&id) == default(by) + }; + if let Some(keys) = keys_of(&sc) + && taken.iter().any(|(k, by)| *k == keys && !twin(by)) + { + app.ui.shortcuts.insert(id.clone(), String::new()); + conflicts.push(json!({"id": id, "label": command_label(&id), "shortcut": sc})); + } + } + let changed: Vec = decisions + .iter() + .filter(|d| decided.contains(&d.id)) + .filter_map(|d| { + let from = before.get(&d.id).cloned().flatten(); + let to = menus::shortcut_of(app, &d.id); + (from != to).then(|| json!({"id": d.id, "label": command_label(&d.id), "item": d.item, "from": from, "to": to})) + }) + .collect(); + Ok(json!({ + "set": set.name, + "imported": imported, + "changed": changed, + "conflictsCleared": conflicts, + "skipped": skipped, + "unmatched": unmatched, + "unmatchedWithoutShortcut": unmatched_without_shortcut, + "unreadable": unreadable, + })) +} + +/// One line for the Keyboard Shortcuts dialog about an import's report. +pub fn summary(lang: &str, report: &Value) -> String { + let n = |k: &str| report[k].as_u64().unwrap_or_default().to_string(); + let len = |k: &str| report[k].as_array().map_or(0, Vec::len).to_string(); + crate::i18n::tr(lang, "Imported {count} shortcuts from “{set}”; {unmatched} items not matched, {unreadable} unreadable.") + .replace("{count}", &n("imported")) + .replace("{set}", report["set"].as_str().unwrap_or_default()) + .replace("{unmatched}", &len("unmatched")) + .replace("{unreadable}", &len("unreadable")) +} + +/// The Keyboard Shortcuts dialog's Import button: a native file picker imports at once and +/// returns the summary; in a browser the chosen file arrives later through the import inbox. +pub fn pick_and_import(app: &mut DesignApp) -> Option { + if let Some(pick) = app.services.pick_open.as_mut() { + let path = pick("shortcuts")?; + return Some(match app.run("window.importShortcuts", json!({"path": path})) { + Ok(report) => summary(&app.ui.language, &report), + Err(e) => e, + }); + } + let request = app.import_request("shortcuts"); + if let Some(open) = app.services.open_async.as_mut() { + open(request); + } + None +} + +/// A set file chosen in the browser: import it and say how it went in the open Keyboard +/// Shortcuts dialog, or the status bar. +pub fn import_delivered(app: &mut DesignApp, bytes: &[u8]) { + let msg = match decode(bytes).and_then(|text| app.run("window.importShortcuts", json!({"text": text}))) { + Ok(report) => summary(&app.ui.language, &report), + Err(e) => e, + }; + match app.ui.dialog.as_mut().filter(|d| d.id == "keyboardShortcuts") { + Some(d) => { + d.fields.insert("message".into(), json!(msg)); + } + None => app.status(msg), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn app() -> DesignApp { + DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()) + } + + #[test] + fn imports_a_windows_set_and_reports_what_it_could_not_use() { + let mut app = app(); + // Something else holds Ctrl+Alt+K before the import; the set gives it to Check Spelling. + menus::run_ui(&mut app, "window.setShortcut", &json!({"id": "app.palette", "shortcut": "Cmd+Alt+K"})).unwrap().unwrap(); + let set = "\u{feff}Shortcut Set : My Set\r\n\r\n\ + Product area : Edit Menu\r\n\ + \tSpelling: Check Spelling... --- Default: Ctrl+Alt+K, Text: F7\r\n\ + \tDuplicate --- [none defined]\r\n\ + \tDuplicate --- [none defined]\r\n\ + \tFrobnicate Everything --- Default: Ctrl+F12\r\n\ + \tNever Heard Of It --- [none defined]\r\n\ + Product area : File Menu\r\n\ + \tClose --- Default: Shift+Ctrl+Num 5, Default: Ctrl+F4\r\n\ + \tSave --- Default: Ctrl+Hyperspace\r\n\ + \tRevert --- Default: Shift+Ctrl+F9\r\n\ + \tSave As... --- Default: Shift+Ctrl+F9\r\n\ + garbage line without a separator\r\n"; + let r = menus::run_ui(&mut app, "window.importShortcuts", &json!({"text": set})).unwrap().unwrap(); + assert_eq!(r["set"], "My Set"); + // A submenu item, with Ctrl as the command modifier. + assert_eq!(menus::shortcut_of(&app, "spelling.check").as_deref(), Some("Cmd+Alt+K")); + assert_eq!(menus::shortcut_of(&app, "file.close").as_deref(), Some("Cmd+Shift+5")); + // `[none defined]` in every occurrence clears a matched command. + assert_eq!(menus::shortcut_of(&app, "edit.duplicate"), None); + // The command that held the imported keys loses them. + assert_eq!(menus::shortcut_of(&app, "app.palette"), None); + assert!(r["conflictsCleared"].as_array().unwrap().iter().any(|c| c["id"] == "app.palette"), "{r}"); + // Unknown items with shortcuts and unreadable keys are reported; Save keeps its shortcut. + assert_eq!(r["unmatched"], json!([{"item": "Edit Menu › Frobnicate Everything", "keys": "Default: Ctrl+F12"}])); + assert_eq!(r["unmatchedWithoutShortcut"], 1); + assert_eq!(r["unreadable"][0]["item"], "File Menu › Save"); + assert_eq!(menus::shortcut_of(&app, "app.save").as_deref(), Some("Cmd+S")); + // Two items want the same keys: the later one takes them. + assert_eq!(menus::shortcut_of(&app, "app.saveDialog").as_deref(), Some("Cmd+Shift+F9")); + assert_eq!(r["skipped"][0]["takenBy"], "app.saveDialog", "{r}"); + assert_eq!(r["imported"], 4); + // Reset Shortcuts is the way back. + menus::run_ui(&mut app, "window.resetShortcuts", &json!({})).unwrap().unwrap(); + assert_eq!(menus::shortcut_of(&app, "app.palette").as_deref(), Some("Cmd+Return")); + } + + #[test] + fn hostile_input_returns_a_report_or_an_error() { + let mut app = app(); + for text in ["", "\0\0\0", "--- ---", " --- Default: Ctrl+", "Product area : \n\t: --- Default: +, Default: ,,,", "x --- Default: ⌘⇧"] { + let _ = menus::run_ui(&mut app, "window.importShortcuts", &json!({"text": text})).unwrap(); + } + assert!(menus::run_ui(&mut app, "window.importShortcuts", &json!({})).unwrap().is_err()); + assert!(menus::run_ui(&mut app, "window.importShortcuts", &json!({"path": "/nonexistent/set.txt"})).unwrap().is_err()); + // UTF-16 with a BOM, and Mac modifier spellings. + let mut bytes = vec![0xFF, 0xFE]; + bytes.extend("Shortcut Set : Mac\nProduct area : File Menu\n\tClose --- Default: ⇧⌘W\n".encode_utf16().flat_map(u16::to_le_bytes)); + let r = menus::run_ui(&mut app, "window.importShortcuts", &json!({"text": decode(&bytes).unwrap()})).unwrap().unwrap(); + assert_eq!(r["set"], "Mac"); + assert_eq!(menus::shortcut_of(&app, "file.close").as_deref(), Some("Cmd+Shift+W")); + } +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 507358dec..381498fb6 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -85,7 +85,7 @@ layer survive interchange; literal XML and round-trip tests are in | PDF presets | `.joboptions`, `.pdfs` | read/write | ✗ | | Print / flattener / document presets | `.prst`, `.flst`, `.dcst` | read/write | ✗ | | Preflight profiles | `.idpp` | read/write | ✗ (own profiles in the document) | -| Keyboard shortcut sets | `.indk` | read/write | ✗ (own JSON) | +| Keyboard shortcut sets | `.indk`; Show Set `.txt` | read/write; write | ~ (imports a Show Set `.txt`; own JSON) | | User dictionary | `.udc` | read/write | ✗ (own, in the document and prefs) | | Fonts | OTF, TTF, TTC, variable | ✓ | ✓ (Type 1 retired by both) | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c7e0678d7..bb7c5eb80 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -417,7 +417,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Spring-loaded Zoom: hold Cmd+Space (Ctrl+Space on Windows/Linux) for the Zoom cursor and click/scrubby zoom; Alt-click zooms out. Release returns to the previous tool without changing the document or undo history. Text-frame and text-field typing suppress the shortcut; Space remains Hand. - Guides belong to the active layer: hidden with it (or with its Show Guides off) and locked with it. - Pencil tool (N): freehand strokes, shown as you draw in the layer's colour, simplified to smooth paths (Alt closes); Smooth and Erase tools re-fit or remove the stretch you drag along (`path.smooth`, `path.erase`). -- Edit › Keyboard Shortcuts: every command, click and press the new keys, conflicts shown, per-command and global reset; `window.setShortcut`. +- Edit › Keyboard Shortcuts: every command, click and press the new keys, conflicts shown, per-command and global reset; `window.setShortcut`. Import InDesign Set… reads a set saved by InDesign's Show Set (.txt) and reports what it changed and what it could not match; `window.importShortcuts`. - Primary Text Frame (New Document) and Smart Text Reflow: pages are added while the primary story oversets and empty ones at the end removed, in the same undo step (Preferences › Type). - Glyphs panel: every character of any font (rendered by our renderer), search by character or U+code, click to insert, recently used. - UI scaling (Preferences › Interface, 50–200%; `window.uiScale`); the window title steps aside when the bar is crowded. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 2dcf4687a..b66fb585c 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -43,7 +43,7 @@ basics of editing fail for too many users on Windows and Linux. | Context menus (canvas, panels, rulers) | ✓ everywhere | 9 context-menu sites, ruler units by right-click | ~ | **not opening for several users** (#238, #187, #160) | | IME text input on the canvas | ✓ | ✓ | ~ | not checked by hand with a system IME (#322) | | Font menu: search, preview, favourites, type-ahead, filters (class, recently added), styles per family, sample text and size, recently used, similar fonts | ✓ | ✓ | ~ | search field focus on macOS (#335, #86); Adobe Fonts (Find More, activated) out of scope | -| Keyboard shortcuts: InDesign defaults, editor, sets | ✓ | ✓ editor; defaults from 09-shortcuts.md | ✓ | | +| Keyboard shortcuts: InDesign defaults, editor, sets | ✓ | ✓ editor; defaults from 09-shortcuts.md; imports an InDesign Show Set `.txt` | ✓ | tool keys are fixed, so a set's Tools items are reported, not applied | | Quick Apply | ✓ | ✓ | ✓ | | | Numeric fields: units, arithmetic, scrubbing | ✓ | 21 pt spinner fields with arithmetic | ✓ | | | Colour fields: hex, picker from any swatch field | ✓ | ✓ | ~ | hex entry and picker issues (#323, #190) | From 9bd85a14b2857113259da4950f30736a1166791a Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 22 Oct 2026 09:30:03 -0400 Subject: [PATCH 19/29] i18n: complete the French interface (#1347) * i18n: complete the French interface (#644) * i18n: French uses gabarit for parent pages; fixes * i18n: French for the guide commands and the shortcut-set import --- crates/ui-egui/src/i18n.rs | 174 +++++++++++++++++++++++---- crates/ui-egui/src/i18n/fr.rs | 220 ++++++++++++++++++++++++++++++++++ 2 files changed, 371 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index acf70ff32..fec123a33 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -139,7 +139,7 @@ const TABLE: &[(&str, [&str; 5])] = &[ ("Pages on Top", ["Seiten oben", "Pages en haut", "Páginas en la parte superior", "ページを上に表示", "页面在上"]), ( "Parents on Top", - ["Übergeordnete Seiten oben", "Parents en haut", "Páginas principales en la parte superior", "親ページを上に表示", "父页面在上"], + ["Übergeordnete Seiten oben", "Gabarits en haut", "Páginas principales en la parte superior", "親ページを上に表示", "父页面在上"], ), ("Resize:", ["Größe ändern:", "Redimensionner :", "Cambiar tamaño:", "サイズ変更:", "调整大小:"]), ("Extra Small", ["Sehr klein", "Très petite", "Extra pequeño", "極小", "特小"]), @@ -150,8 +150,8 @@ const TABLE: &[(&str, [&str; 5])] = &[ ("Jumbo", ["Riesig", "Géante", "Gigante", "最大", "巨大"]), ("Proportional", ["Proportional", "Proportionnel", "Proporcional", "比例", "按比例"]), ("Pages Fixed", ["Seiten fixiert", "Pages fixes", "Páginas fijas", "ページを固定", "页面固定"]), - ("Parents Fixed", ["Übergeordnete fixiert", "Parents fixes", "Páginas principales fijas", "親ページを固定", "父页面固定"]), - ("Parents", ["Übergeordnete Seiten", "Parents", "Páginas principales", "親ページ", "父页面"]), + ("Parents Fixed", ["Übergeordnete fixiert", "Gabarits fixes", "Páginas principales fijas", "親ページを固定", "父页面固定"]), + ("Parents", ["Übergeordnete Seiten", "Gabarits", "Páginas principales", "親ページ", "父页面"]), ( "Bulleted & Numbered Lists", [ @@ -497,7 +497,7 @@ const TABLE: &[(&str, [&str; 5])] = &[ ), ("ICF Top", ["ICF oben", "Haut ICF", "Parte superior ICF", "平均字面の上", "平均字面上"]), ("ICF Bottom", ["ICF unten", "Bas ICF", "Parte inferior ICF", "平均字面の下", "平均字面下"]), - ("Gyoudori:", ["Gyoudori:", "Gyoudori:", "Gyoudori:", "行取り:", "行取:"]), + ("Gyoudori:", ["Gyoudori:", "Gyoudori :", "Gyoudori:", "行取り:", "行取:"]), ( "Use Paragraph Gyoudori", ["Absatz-Gyoudori verwenden", "Utiliser le gyoudori de paragraphe", "Usar gyoudori de párrafo", "段落行取りを使用", "使用段落行取"], @@ -734,7 +734,7 @@ const TABLE: &[(&str, [&str; 5])] = &[ ("Editorial", ["Redaktion", "Éditorial", "Editorial", "エディトリアル", "编辑"]), ("Object & Layout", ["Objekt und Layout", "Objet et mise en page", "Objeto y diseño", "オブジェクト&レイアウト", "对象和版面"]), ("Styles", ["Formate", "Styles", "Estilos", "スタイル", "样式"]), - ("Essentials Classic", ["Essentials Classic", "Essentials Classic", "Essentials Classic", "Essentials Classic", "基本功能(经典)"]), + ("Essentials Classic", ["Essentials Classic", "Les indispensables (classique)", "Essentials Classic", "Essentials Classic", "基本功能(经典)"]), ("Split Window", ["Fenster teilen", "Fractionner la fenêtre", "Dividir ventana", "ウィンドウを分割", "拆分窗口"]), ("New Window", ["Neues Fenster", "Nouvelle fenêtre", "Nueva ventana", "新規ウィンドウ", "新建窗口"]), ( @@ -873,7 +873,7 @@ const TABLE: &[(&str, [&str; 5])] = &[ ], ), ("Delete Spread", ["Druckbogen löschen", "Supprimer la planche", "Eliminar pliego", "スプレッドを削除", "删除跨页"]), - ("Parent Pages", ["Übergeordnete Seiten", "Pages parents", "Páginas principales", "親ページ", "父页面"]), + ("Parent Pages", ["Übergeordnete Seiten", "Gabarits", "Páginas principales", "親ページ", "父页面"]), ( "Apply Parent to Pages", [ @@ -1388,12 +1388,12 @@ const TABLE: &[(&str, [&str; 5])] = &[ ("Apply None (/)", ["Apply None (/)", "Appliquer Aucun (/)", "Apply None (/)", "Apply None (/)", "应用无 (/)"]), ( "Default Fill and Stroke", - ["Default Fill and Stroke", "Default Fill and Stroke", "Default Fill and Stroke", "Default Fill and Stroke", "默认填色和描边"], + ["Default Fill and Stroke", "Fond et contour par défaut", "Default Fill and Stroke", "Default Fill and Stroke", "默认填色和描边"], ), - ("Swap Fill and Stroke", ["Swap Fill and Stroke", "Swap Fill and Stroke", "Swap Fill and Stroke", "Swap Fill and Stroke", "交换填色和描边"]), + ("Swap Fill and Stroke", ["Swap Fill and Stroke", "Permuter fond et contour", "Swap Fill and Stroke", "Swap Fill and Stroke", "交换填色和描边"]), ( "Toggle Fill and Stroke", - ["Toggle Fill and Stroke", "Toggle Fill and Stroke", "Toggle Fill and Stroke", "Toggle Fill and Stroke", "切换填色和描边"], + ["Toggle Fill and Stroke", "Basculer fond/contour", "Toggle Fill and Stroke", "Toggle Fill and Stroke", "切换填色和描边"], ), ("Reverse the gradient", ["Reverse the gradient", "Inverser le dégradé", "Reverse the gradient", "Reverse the gradient", "反转渐变"]), ("Style source", ["Style source", "Source du style", "Style source", "Style source", "样式源"]), @@ -2061,7 +2061,13 @@ const TABLE: &[(&str, [&str; 5])] = &[ ), ( "Show/Hide Document Grid", - ["Show/Hide Document Grid", "Show/Hide Document Grid", "Show/Hide Document Grid", "Show/Hide Document Grid", "显示/隐藏文档网格"], + [ + "Show/Hide Document Grid", + "Afficher/Masquer la grille du document", + "Show/Hide Document Grid", + "Show/Hide Document Grid", + "显示/隐藏文档网格", + ], ), ( "Show/Hide Frame Edges", @@ -2713,7 +2719,7 @@ const TABLE: &[(&str, [&str; 5])] = &[ "Select an object or text to color its fill or stroke.", [ "Select an object or text to color its fill or stroke.", - "Select an object or text to color its fill or stroke.", + "Sélectionnez un objet ou du texte pour colorer son fond ou son contour.", "Select an object or text to color its fill or stroke.", "Select an object or text to color its fill or stroke.", "选择一个对象或文本以设置其填色或描边颜色。", @@ -2922,7 +2928,7 @@ const TABLE: &[(&str, [&str; 5])] = &[ ("Cap Height", ["Cap Height", "Hauteur de capitale", "Cap Height", "Cap Height", "大写字母高度"]), ("Leading", ["Leading", "Interligne", "Leading", "Leading", "行距"]), ("x Height", ["x Height", "Hauteur d'x", "x Height", "x Height", "x 字高"]), - ("Em Box Height", ["Em Box Height", "Em Box Height", "Em Box Height", "Em Box Height", "全角字框高度"]), + ("Em Box Height", ["Em Box Height", "Hauteur du cadratin", "Em Box Height", "Em Box Height", "全角字框高度"]), ("Fixed", ["Fixed", "Fixe", "Fixed", "Fixed", "固定"]), ("Never (continuous)", ["Never (continuous)", "Jamais (continu)", "Never (continuous)", "Never (continuous)", "从不(连续编号)"]), ("Page", ["Page", "Page", "Page", "Page", "页面"]), @@ -3505,8 +3511,8 @@ const TABLE: &[(&str, [&str; 5])] = &[ ("Ukrainian", ["Ukrainian", "Ukrainien", "Ukrainian", "Ukrainian", "乌克兰语"]), ("Cell Style", ["Cell Style", "Style de cellule", "Cell Style", "Cell Style", "单元格样式"]), ("Table Style", ["Table Style", "Style de tableau", "Table Style", "Table Style", "表样式"]), - ("Col ←", ["Col ←", "Col ←", "Col ←", "Col ←", "左侧插入列"]), - ("Col →", ["Col →", "Col →", "Col →", "Col →", "右侧插入列"]), + ("Col ←", ["Col ←", "Col. ←", "Col ←", "Col ←", "左侧插入列"]), + ("Col →", ["Col →", "Col. →", "Col →", "Col →", "右侧插入列"]), ("Row ↑", ["Row ↑", "Ligne ↑", "Row ↑", "Row ↑", "上方插入行"]), ("Row ↓", ["Row ↓", "Ligne ↓", "Row ↓", "Row ↓", "下方插入行"]), ("Hide Others", ["Hide Others", "Masquer les autres", "Hide Others", "Hide Others", "隐藏其他图层"]), @@ -3536,7 +3542,7 @@ const TABLE: &[(&str, [&str; 5])] = &[ "Show Parent Page Overlay", [ "Überlagerung der übergeordneten Seite anzeigen", - "Afficher la superposition de la page parent", + "Afficher la superposition du gabarit", "Mostrar superposición de página principal", "親ページオーバーレイを表示", "显示父页面叠加", @@ -3544,7 +3550,7 @@ const TABLE: &[(&str, [&str; 5])] = &[ ), ( "Controlled by Parent", - ["Durch übergeordnete Seite gesteuert", "Contrôlé par le parent", "Controlado por principal", "親ページで制御", "由父页面控制"], + ["Durch übergeordnete Seite gesteuert", "Contrôlé par le gabarit", "Controlado por principal", "親ページで制御", "由父页面控制"], ), ("US Business Card", ["US-Visitenkarte", "Carte de visite US", "Tarjeta de visita EE. UU.", "US 名刺", "美国名片"]), ( @@ -4229,8 +4235,8 @@ const TABLE: &[(&str, [&str; 5])] = &[ "Bullets and Numbering…", ["Aufzählungszeichen und Nummerierung…", "Puces et numérotation…", "Viñetas y numeración…", "箇条書き記号と番号付け…", "项目符号和编号…"], ), - ("List:", ["Liste:", "Liste:", "Lista:", "リスト:", "列表:"]), - ("Mode:", ["Modus:", "Mode:", "Modo:", "モード:", "模式:"]), + ("List:", ["Liste:", "Liste :", "Lista:", "リスト:", "列表:"]), + ("Mode:", ["Modus:", "Mode :", "Modo:", "モード:", "模式:"]), ( "Continue from Previous Number", [ @@ -4717,7 +4723,7 @@ mod tests { // `fr::TABLE` is looked up first: a key there would hide the shared table's French column. let both: Vec<_> = catalog.keys().filter(|k| shared.contains(*k)).collect(); assert!(both.is_empty(), "French keys also in the shared table: {both:?}"); - let mut keys = std::collections::HashSet::new(); + let mut keys = interface_strings(); for table in [ar::TABLE, de::TABLE, it::TABLE, ja::TABLE, pt_br::TABLE, uk::TABLE, ru::TABLE, cs::TABLE] { keys.extend(table.iter().map(|(key, _)| *key)); } @@ -4738,6 +4744,121 @@ mod tests { assert_eq!(tr("fr", "Group"), "Associer"); } + /// Interface strings that read the same in French: names, abbreviations, numbering samples, key + /// symbols and words French shares with English. + const SAME_IN_FRENCH: &[&str] = &[ + " OK ", + " (auto)", + "+Bin", + "+LOC", + "A, B, C, D...", + "Angle", + "Articles", + "Bunri-Kinshi", + "Commits", + "Composition", + "Compression", + "Conditions", + "Cyan", + "DesignCraft", + "Direction", + "Distance", + "Document", + "Document…", + "Ellipse", + "Extras", + "Fractions", + "GREP", + "Hindi", + "Horizontal", + "I, II, III, IV...", + "Image", + "Index", + "Interface", + "Justification", + "Justification…", + "Kanji", + "Kenten", + "Lab", + "Ligatures", + "Magenta", + "Maximum", + "Menus", + "Menus…", + "Minimum", + "Mobile", + "Normal", + "Normal (W)", + "Notes", + "OK", + "OpenType", + "Options", + "Orange", + "Orientation", + "PDF/A-2b", + "PDF/X-4", + "Page", + "Pages", + "Pathfinder", + "Picas", + "Portrait", + "Position", + "Radial", + "Rectangle", + "Rensuuji", + "Rotation", + "Ruby", + "Ruby…", + "Satin", + "Saturation", + "Script", + "Scripts", + "Section", + "Serif", + "Shatai", + "Signature", + "Simple", + "Structure", + "Style", + "Styles", + "Tate-Chu-Yoko", + "Triangle", + "Version", + "Vertical", + "Violet", + "Warichu", + "Web", + "a, b, c, d...", + "document", + "i, ii, iii, iv...", + "pages", + "ΔLOC", + "⇧", + "−Bin", + "−LOC", + "⌃", + "⌘", + "⌥", + ]; + + #[test] + fn french_translates_every_interface_string() { + let keys = interface_strings(); + // A new English string needs a French entry (or a place on `SAME_IN_FRENCH`) before it ships. + let mut untranslated: Vec<_> = keys.iter().filter(|key| tr("fr", key) == **key && !SAME_IN_FRENCH.contains(key)).collect(); + untranslated.sort(); + assert!(untranslated.is_empty(), "French falls back to English for: {untranslated:?}"); + for key in SAME_IN_FRENCH { + assert!(keys.contains(key), "SAME_IN_FRENCH lists a string the interface no longer has: {key}"); + assert_eq!(tr("fr", key), *key, "SAME_IN_FRENCH lists a string French translates: {key}"); + } + for tool in designcraft_tools::TOOL_GROUPS.iter().flat_map(|group| group.iter()) { + assert!(tr("fr", tool.label).starts_with("Outil "), "{}", tool.id); + } + assert_eq!(tr("fr", "Selection Tool"), "Outil Sélection"); + assert_eq!(tr("fr", "Don't Save"), "Ne pas enregistrer"); + } + #[test] fn ukrainian_catalog_covers_existing_keys_and_preserves_placeholders() { let catalog: std::collections::HashMap<_, _> = uk::TABLE.iter().copied().collect(); @@ -4937,10 +5058,9 @@ mod tests { assert_eq!(tr("pl", "{pages} Pages in {spreads} Spreads"), "Strony: {pages}, rozkładówki: {spreads}"); } - #[test] - fn czech_catalog_has_no_stale_keys_and_keeps_placeholders_and_markers() { - let catalog: HashMap<_, _> = cs::TABLE.iter().copied().collect(); - assert_eq!(catalog.len(), cs::TABLE.len(), "duplicate Czech keys"); + /// Every English string the interface passes to `tr`, as far as the catalogs, command and tool + /// tables and the list of UI-only labels know them. + fn interface_strings() -> std::collections::HashSet<&'static str> { let mut keys = std::collections::HashSet::new(); keys.extend(TABLE.iter().map(|(key, _)| *key)); for table in [ar::TABLE, it::TABLE, ja::TABLE, pt_br::TABLE, uk::TABLE] { @@ -5033,6 +5153,14 @@ mod tests { "{name}: import cancelled while a dialog is open; choose the file again", "{name}: {count} step(s) done", ]); + keys + } + + #[test] + fn czech_catalog_has_no_stale_keys_and_keeps_placeholders_and_markers() { + let catalog: HashMap<_, _> = cs::TABLE.iter().copied().collect(); + assert_eq!(catalog.len(), cs::TABLE.len(), "duplicate Czech keys"); + let keys = interface_strings(); // A new English string falls back to English until it is translated, so only stale // entries (keys nothing passes to `tr` any more) fail. let stale: Vec<_> = catalog.keys().filter(|k| !keys.contains(*k)).collect(); diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 78c5d5948..681230d84 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1,57 +1,118 @@ //! French translations of the strings the shared table in `i18n.rs` has no row for, //! written from the English source using ordinary French desktop-publishing vocabulary. pub(super) const TABLE: &[(&str, &str)] = &[ + ("% of all commits", "% de tous les commits"), + ("(any)", "(quelconque)"), + ("(unchanged)", "(inchangé)"), ("90° CCW", "90° sens antihoraire"), ("90° CW", "90° sens horaire"), + ("About", "À propos"), + ("Activate Panel", "Activer le panneau"), + ("Add Anchor Point Tool", "Outil Ajout de point d'ancrage"), + ("Add Tab", "Ajouter une tabulation"), + ("Align To", "Aligner sur"), ("Alignment", "Alignement"), ("All Documents", "Tous les documents"), ("Alpha Channel", "Couche alpha"), + ("Alternate layout", "Variante de mise en page"), ("Anchored Object Options", "Options d'objet ancré"), + ("Apply Numbering & Section Options", "Appliquer les options de numérotation et de section"), + ("Apply Text Attributes (Eyedropper)", "Appliquer les attributs de texte (Pipette)"), ("ArtCraft App Page", "Page de l'application ArtCraft"), ("ArtCraft Website", "Site web d'ArtCraft"), ("Auto Size", "Taille automatique"), + ("Auto Tate-Chu-Yoko", "Tate-Chu-Yoko automatique"), + ("Binary assets added", "Fichiers binaires ajoutés"), + ("Binary assets removed", "Fichiers binaires supprimés"), ("Binding", "Reliure"), + ("Break Thread", "Rompre le chaînage"), ("Bullet Character", "Caractère de puce"), ("CMYK:", "CMJN :"), + ("Cancel Preview", "Annuler l'aperçu"), + ("Cell Number:", "Numéro de mobile :"), + ("Change Panel Layout", "Modifier la disposition des panneaux"), + ("Change Tab", "Modifier la tabulation"), ("Change To", "Remplacer par"), + ("Change fill to:", "Remplacer le fond par :"), + ("Character Style", "Style de caractère"), ("Check Spelling", "Vérifier l'orthographe"), + ("Chinese: Simplified", "Chinois : simplifié"), + ("Chinese: Traditional", "Chinois : traditionnel"), + ("Clear All Tabs", "Effacer toutes les tabulations"), + ("Clear Object Style Overrides", "Effacer les remplacements du style d'objet"), ("Clear Rotation", "Effacer la rotation"), + ("Clipping Path Options…", "Options de masque…"), + ("Close Panel", "Fermer le panneau"), + ("Close Window", "Fermer la fenêtre"), ("Closed Path", "Tracé fermé"), ("Color Blindness – Deuteranopia", "Daltonisme – Deutéranopie"), ("Color Blindness – Protanopia", "Daltonisme – Protanopie"), + ("Color Theme Tool", "Outil Thème de couleur"), + ("Color Theme…", "Thème de couleur…"), ("Colour", "Couleur"), ("Colour Picker", "Sélecteur de couleurs"), ("Column Break", "Saut de colonne"), + ("Commit Preview", "Valider l'aperçu"), ("Community", "Communauté"), + ("Company", "Entreprise"), ("Conditional Text", "Texte conditionnel"), + ("Content Collector Tool", "Outil Collecteur de contenu"), + ("Content Placer Tool", "Outil Placeur de contenu"), + ("Contributors", "Contributeurs"), + ("Convert Direction Point Tool", "Outil Conversion de point directeur"), + ("Convert Point", "Convertir le point"), + ("Convert Rows", "Convertir les lignes"), ("Copyright Symbol", "Symbole du copyright"), ("Corner Options", "Options d'arrondi"), + ("Couldn't write recovery data: {error}", "Impossible d'écrire les données de récupération : {error}"), ("Create Guides", "Créer des repères"), ("Dark", "Foncé"), + ("Data Fields", "Champs de données"), + ("Data Merge Options", "Options de fusion des données"), ("Define Cross-Reference Format", "Définir un format de référence croisée"), ("Define Lists", "Définir des listes"), ("Define Text Variable", "Définir une variable de texte"), + ("Delete Anchor Point Tool", "Outil Suppression de point d'ancrage"), + ("Delete Character Style", "Supprimer le style de caractère"), + ("Delete Document Preset", "Supprimer le paramètre prédéfini de document"), + ("Delete Parent", "Supprimer le gabarit"), ("Delete Type from Path", "Supprimer le texte curviligne"), + ("Deselect Guides", "Désélectionner les repères"), ("DesignCraft Website", "Site web de DesignCraft"), ("DesignCraft on GitHub", "DesignCraft sur GitHub"), + ("DesignCraft page", "Page DesignCraft"), ("Detect Edges", "Détecter les contours"), + ("Direct Selection Tool", "Outil Sélection directe"), ("Discretionary Hyphen", "Trait d'union conditionnel"), + ("Display name", "Nom affiché"), + ("Distribute Rows Evenly", "Répartir les lignes uniformément"), ("Document CMYK", "CMJN du document"), ("Document Endnote Options", "Options de notes de fin de document"), ("Document Footnote Options", "Options de notes de bas de page du document"), ("Document RGB", "RVB du document"), + ("Don't Save", "Ne pas enregistrer"), ("Done", "Terminé"), ("Double Left Quotation Marks", "Guillemets doubles ouvrants"), ("Double Right Quotation Marks", "Guillemets doubles fermants"), + ("Drag Rows or Columns", "Faire glisser des lignes ou des colonnes"), ("Edit/Interface Language", "Édition/Langue de l'interface"), ("Edit/Spelling", "Édition/Orthographe"), ("Edit/Transparency Blend Space", "Édition/Espace de fusion de la transparence"), ("Edit/Transparency Flattener Presets", "Édition/Préréglages d'aplatissement de la transparence"), + ("Ellipse Frame Tool", "Outil Bloc elliptique"), + ("Ellipse Tool", "Outil Ellipse"), ("Ellipsis", "Points de suspension"), ("Em Dash", "Tiret cadratin"), ("Em Space", "Espace cadratin"), + ("Email Address:", "Adresse e-mail :"), + ("Email:", "E-mail :"), ("En Dash", "Tiret demi-cadratin"), ("En Space", "Espace demi-cadratin"), + ( + "Equal fixed heights for the selected rows; cell text may become overset.", + "Hauteurs fixes identiques pour les lignes sélectionnées ; le texte des cellules peut déborder.", + ), + ("Erase Tool", "Outil Gomme"), ("Export EPUB", "Exporter en EPUB"), ("Export EPUB (Fixed Layout)", "Exporter en EPUB (mise en page fixe)"), ("Export EPUB (Reflowable)", "Exporter en EPUB (redistribuable)"), @@ -59,50 +120,99 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Export IDML", "Exporter en IDML"), ("Export PDF (Interactive)", "Exporter en PDF (interactif)"), ("Export Page as PNG", "Exporter la page en PNG"), + ("Export PowerPoint…", "Exporter en PowerPoint…"), ("Export Text", "Exporter le texte"), ("Export XML", "Exporter en XML"), + ( + "Export a PDF, IDML or package to share — no cloud account needed.", + "Exportez un PDF, un fichier IDML ou un assemblage à partager — aucun compte cloud requis.", + ), + ("Extract Color Theme", "Extraire le thème de couleur"), + ("Eyedropper Tool", "Outil Pipette"), ("Figure Space", "Espace chiffre"), ("File/Export", "Fichier/Exporter"), ("Find What", "Rechercher"), + ("Find fill:", "Rechercher le fond :"), + ("First commit", "Premier commit"), ("Flush Space", "Espace sans alinéa"), ("Forced Line Break", "Saut de ligne forcé"), + ("Formatting Affects Text", "La mise en forme agit sur le texte"), + ("Found", "Trouvé"), ("Frame Break", "Saut de bloc"), + ("Free Transform Tool", "Outil Transformation manuelle"), ("GREP", "GREP"), + ("Gap Tool", "Outil Espace"), ("Generate Index", "Générer l'index"), ("Generate Live Caption", "Générer une légende dynamique"), + ("Get Cell Stroke", "Obtenir le contour de cellule"), + ("Get Tabs", "Obtenir les tabulations"), ("Global Light", "Lumière globale"), + ("Grab bag", "Liste"), + ("Gradient Feather Tool", "Outil Contour progressif dégradé"), + ("Gradient Swatch Tool", "Outil Dégradé de nuance"), ("Graphic", "Graphique"), + ("Group with", "Grouper avec"), ("Hair Space", "Espace ultrafine"), + ("Hand Tool", "Outil Main"), ("Hide Guides", "Masquer les repères"), ("High Contrast", "Contraste élevé"), ("High Resolution", "Haute résolution"), ("I, II, III, IV...", "I, II, III, IV..."), + ("Import InDesign Shortcut Set", "Importer un jeu de raccourcis InDesign"), ("Import XML", "Importer XML"), + ("Import cancelled: the originating document has closed", "Importation annulée : le document d'origine a été fermé"), ("Indent", "Retrait"), ("Indent to Here", "Retrait jusqu'à ce point"), ("Ink Limit 300%", "Limite d'encre 300 %"), ("Insert Anchored Object", "Insérer un objet ancré"), ("Insert Cross-Reference", "Insérer une référence croisée"), + ("Insert Field", "Insérer un champ"), ("Insert Math Expression", "Insérer une expression mathématique"), ("Insert Pages", "Insérer des pages"), ("Internet Standard RGB (sRGB)", "RVB standard Internet (sRGB)"), + ("Invalid panel layout; restored the default dock", "Disposition des panneaux non valide ; disposition par défaut restaurée"), + ("Join", "Joindre"), ("Join the ArtCraft Discord", "Rejoindre le Discord d'ArtCraft"), ("Join the community", "Rejoindre la communauté"), ("Kerning", "Crénage"), + ("Kerning/Tracking Step", "Pas de crénage/d'approche"), + ("Key Object", "Objet clé"), + ("Last commit", "Dernier commit"), ("Layout/Index", "Page/Index"), ("Layout/Pages", "Page/Pages"), ("Legacy Macintosh RGB", "RVB Macintosh hérité"), ("Light", "Clair"), + ("Line Tool", "Outil Trait"), + ("Line delta", "Différence de lignes"), + ("Lines +/−", "Lignes +/−"), + ("Lines added", "Lignes ajoutées"), + ("Lines deleted", "Lignes supprimées"), + ("List Composite Fonts", "Lister les polices composites"), + ("List Styles in File", "Lister les styles du fichier"), ("Load DTD", "Charger la DTD"), + ("Load Styles…", "Charger les styles…"), ("Load Swatches", "Charger des nuances"), ("Low Resolution", "Basse résolution"), ("Margins:", "Marges :"), + ("Maximize/Restore Window", "Agrandir/Restaurer la fenêtre"), + ("Measure Tool", "Outil Mesure"), ("Medium Dark", "Moyennement foncé"), ("Medium Light", "Moyennement clair"), ("Medium Resolution", "Résolution moyenne"), ("Menus", "Menus"), + ("Merged PRs", "PR fusionnées"), + ("Message:", "Message :"), + ("Minimize Window", "Réduire la fenêtre"), + ("Models", "Modèles"), ("Monitor RGB", "RVB du moniteur"), + ("Move Column Guide", "Déplacer le repère de colonne"), + ("Move Guides", "Déplacer les repères"), ("Move Pages", "Déplacer des pages"), + ("Move Panel", "Déplacer le panneau"), + ("Move Tab", "Déplacer la tabulation"), + ("Move Window", "Déplacer la fenêtre"), + ("Name (A–Z)", "Nom (A–Z)"), + ("New Cell Style", "Nouveau style de cellule"), ("New Condition", "Nouvelle condition"), ("New Hyperlink", "Nouvel hyperlien"), ("New Hyperlink Destination", "Nouvelle destination d'hyperlien"), @@ -110,13 +220,20 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("New Page Reference", "Nouvelle référence de page"), ("New Parent", "Nouveau gabarit"), ("New Stroke Style", "Nouveau style de contour"), + ("New Table Style", "Nouveau style de tableau"), ("Next Page Number", "Numéro de la page suivante"), + ("No contributor data was built into this copy.", "Aucune donnée sur les contributeurs n'est intégrée à cette copie."), + ("No matches", "Aucune correspondance"), + ("No model credits were built into this copy.", "Aucun crédit de modèle n'est intégré à cette copie."), ("Nonbreaking Hyphen", "Trait d'union insécable"), ("Nonbreaking Space", "Espace insécable"), ("None (keep transparency)", "Aucun (conserver la transparence)"), + ("Note Tool", "Outil Note"), ("Number of Pages", "Nombre de pages"), ("Numbering & Section Options", "Options de numérotation et de section"), ("OK", "OK"), + ("Object Style", "Style d'objet"), + ("Object Style Options…", "Options de style d'objet…"), ("Object Styles", "Styles d'objet"), ("Object/Anchored Object", "Objet/Objet ancré"), ("Object/Arrange", "Objet/Disposition"), @@ -132,64 +249,130 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Object/Transform", "Objet/Transformation"), ("Object/Transform Again", "Objet/Répéter la transformation"), ("On", "Activé"), + ("Organization:", "Organisation :"), ("Orientation", "Orientation"), + ("PDF import cancelled: the originating document has closed", "Importation PDF annulée : le document d'origine a été fermé"), + ("PRs", "PR"), ("Package", "Assemblage"), + ("Packaged {count} files into {dir}", "{count} fichiers assemblés dans {dir}"), ("Page Break", "Saut de page"), + ("Page Options", "Options de page"), + ("Page Tool", "Outil Page"), ("Panels", "Panneaux"), ("Paragraph Return", "Retour de paragraphe"), + ("Paragraph Style", "Style de paragraphe"), ("Paragraph Symbol", "Symbole de paragraphe"), + ("Parent Options…", "Options de gabarit…"), + ("Pen Tool", "Outil Plume"), + ("Pencil Tool", "Outil Crayon"), + ("Phone:", "Téléphone :"), ("Picas", "Picas"), + ("Pin Bar Position", "Épingler la position de la barre"), ("Place with Import Options", "Importer avec les options d'importation"), + ("Polygon Frame Tool", "Outil Bloc polygonal"), + ("Polygon Tool", "Outil Polygone"), ("Preflight", "Contrôle en amont"), ("Preflight Panel…", "Panneau Contrôle en amont…"), + ("Press keys…", "Appuyez sur des touches…"), + ("Preview Change", "Prévisualiser la modification"), + ("Preview Record", "Aperçu de l'enregistrement"), ("Previous Page Number", "Numéro de la page précédente"), ("Print Booklet", "Imprimer le cahier"), ("Punctuation Space", "Espace de ponctuation"), ("Quarter Space", "Quart d'espace"), ("Quick Apply", "Application rapide"), ("RGB:", "RVB :"), + ("Range:", "Plage :"), + ("Real name", "Nom réel"), + ("Recent Files", "Fichiers récents"), + ("Rectangle Frame Tool", "Outil Bloc rectangulaire"), + ("Rectangle Tool", "Outil Rectangle"), + ("Redefine Character Style", "Redéfinir le style de caractère"), + ("Redefine Paragraph Style", "Redéfinir le style de paragraphe"), ("Registered Trademark Symbol", "Symbole de marque déposée"), ("Relink", "Rééditer le lien"), ("Relink to Folder", "Rééditer le lien au dossier"), + ("Relinked {count}", "Liens rétablis : {count}"), + ("Reload Fonts", "Recharger les polices"), + ("Remove Data Source", "Supprimer la source de données"), + ("Remove Field", "Supprimer le champ"), + ("Remove Frame from Thread", "Retirer le bloc du chaînage"), + ("Reorder Objects", "Réorganiser les objets"), ("Report an Issue", "Signaler un problème"), + ("Report an issue", "Signaler un problème"), + ("Reset Bar Position", "Réinitialiser la position de la barre"), + ("Resize Row or Column", "Redimensionner la ligne ou la colonne"), + ("Resize Window", "Redimensionner la fenêtre"), + ("Resize panel window", "Redimensionner la fenêtre du panneau"), + ("Resize panels", "Redimensionner les panneaux"), + ("Reverse the order", "Inverser l'ordre"), ("Right Indent Tab", "Tabulation de retrait à droite"), + ("Rotate Tool", "Outil Rotation"), ("Rotation", "Rotation"), + ("Ruler Zero Point", "Point zéro des règles"), ("Save As", "Enregistrer sous"), ("Save Swatches for Exchange", "Enregistrer les nuances pour échange"), ("Save a Copy", "Enregistrer une copie"), + ("Scale Tool", "Outil Mise à l'échelle"), + ("Scissors Tool", "Outil Ciseaux"), ("Scripts", "Scripts"), ("Section Marker", "Marque de section"), ("Section Symbol", "Symbole de section"), + ("Select Guide", "Sélectionner le repère"), + ("Select Page", "Sélectionner la page"), + ("Select Paragraph", "Sélectionner le paragraphe"), + ("Select Sentence", "Sélectionner la phrase"), + ("Select Story", "Sélectionner l'article"), + ("Select Text Unit", "Sélectionner une unité de texte"), ("Selection", "Sélection"), + ("Selection Tool", "Outil Sélection"), + ("Sent {count} page(s) to {printer}", "{count} page(s) envoyée(s) à {printer}"), ("Sentence case", "Majuscule en début de phrase"), + ("Set Composite Font", "Définir la police composite"), + ("Set OpenType Features", "Définir les fonctions OpenType"), + ("Shear Tool", "Outil Déformation"), ("Simulate Paper Color", "Simuler la couleur du papier"), ("Single Left Quotation Mark", "Guillemet simple ouvrant"), ("Single Right Quotation Mark", "Guillemet simple fermant"), ("Sixth Space", "Sixième d'espace"), ("Smart Guide Options", "Options des repères commentés"), + ("Smooth Tool", "Outil Lissage"), ("Space After", "Espace après"), ("Space Before", "Espace avant"), ("Start Page #", "N° de la première page"), ("Step and Repeat", "Exécuter et répéter"), + ("Stop Preview", "Arrêter l'aperçu"), ("Story Column Direction", "Sens des colonnes de l'article"), + ("Story Editor — {count} words", "Mode éditeur — {count} mots"), + ("Story {story} ← story {parent}", "Article {story} ← article {parent}"), ("Straight Double Quotation Marks", "Guillemets droits doubles"), ("Straight Single Quotation Mark (Apostrophe)", "Guillemet droit simple (apostrophe)"), + ("Subject:", "Objet :"), ("Subscript:", "Indice :"), ("Superscript:", "Exposant :"), + ("Swap Text Fill and Stroke", "Permuter le fond et le contour du texte"), ("Tab", "Tabulation"), ("Table of Contents", "Table des matières"), ("Table/Convert Cell Type", "Tableau/Convertir le type de cellule"), ("Table/Delete", "Tableau/Supprimer"), ("Table/Insert", "Tableau/Insérer"), ("Table/Select", "Tableau/Sélectionner"), + ("Text Anchor", "Ancre de texte"), + ("Text:", "Texte :"), ("Thin Space", "Espace fine"), ("Third Space", "Tiers d'espace"), + ("Thread Text Frames", "Chaîner les blocs de texte"), ("Title Case", "Majuscule à chaque mot"), + ("To Body", "En lignes de corps"), + ("To Footer", "En lignes de pied"), + ("To Header", "En lignes d'en-tête"), ("Trademark Symbol", "Symbole de marque"), ("Transform Again Individually", "Répéter la transformation individuellement"), ("Transform Sequence Again", "Répéter la séquence de transformations"), ("Transform Sequence Again Individually", "Répéter la séquence de transformations individuellement"), + ("Type Tool", "Outil Texte"), ("Type on a Path Options", "Options de texte curviligne"), + ("Type on a Path Tool", "Outil Texte curviligne"), ("Type/Bulleted and Numbered Lists", "Texte/Listes à puces et numérotées"), ("Type/Change Case", "Texte/Modifier la casse"), ("Type/Hyperlinks & Cross-References", "Texte/Hyperliens et références croisées"), @@ -210,8 +393,20 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("URL:", "URL :"), ("Unassigned", "Non attribué"), ("Units", "Unités"), + ("Unsaved Changes", "Modifications non enregistrées"), + ("Update Data Source", "Mettre à jour la source de données"), + ("Username", "Nom d'utilisateur"), + ("Validate from Root Element", "Valider à partir de l'élément racine"), + ("Vertical Type Tool", "Outil Texte vertical"), + ("Vertical Type on a Path Tool", "Outil Texte curviligne vertical"), ("View/Display Performance", "Affichage/Performances d'affichage"), + ("View/Extras", "Affichage/Extras"), ("View/Grids & Guides", "Affichage/Grilles et repères"), + ("View/Proof Setup", "Affichage/Format d'épreuve"), + ("View/Rotate Spread", "Affichage/Faire pivoter la planche"), + ("View/Screen Mode", "Affichage/Mode de l'écran"), + ("View/Separations Preview", "Affichage/Aperçu des séparations"), + ("View/Structure", "Affichage/Structure"), ("Window/Arrange", "Fenêtre/Disposition"), ("Window/Interactive", "Fenêtre/Interactif"), ("Window/Interface Color Theme", "Fenêtre/Thème de couleur de l'interface"), @@ -220,6 +415,31 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Window/Type & Tables", "Fenêtre/Texte et tableaux"), ("Window/Utilities", "Fenêtre/Utilitaires"), ("Working CMYK", "CMJN de travail"), + ("Zoom Tool", "Outil Zoom"), + ("[No Language]", "[Aucune langue]"), ("i, ii, iii, iv...", "i, ii, iii, iv..."), + ("image editing", "retouche d'images"), + ("layer", "calque"), + ("layers", "calques"), ("lowercase", "minuscules"), + ("motion graphics and visual effects", "animation graphique et effets visuels"), + ("photo library and raw development", "photothèque et développement raw"), + ("reading, organizing and protecting PDFs", "lecture, organisation et protection de PDF"), + ("the default printer", "l'imprimante par défaut"), + ("vector illustration", "illustration vectorielle"), + ("video editing, color and sound", "montage vidéo, couleur et son"), + ("{contributors} contributors · {commits} commits", "{contributors} contributeurs · {commits} commits"), + ("{count} conflict(s): {names}", "{count} conflit(s) : {names}"), + ("{count} match(es)", "{count} correspondance(s)"), + ("{count} replacement(s) made", "{count} remplacement(s) effectué(s)"), + ("{label}: {name} (double-click: Color Picker)", "{label} : {name} (double-clic : Sélecteur de couleurs)"), + ( + "{name}: import cancelled while a dialog is open; choose the file again", + "{name} : importation annulée car une boîte de dialogue était ouverte ; choisissez à nouveau le fichier", + ), + ("{name}: {count} step(s) done", "{name} : {count} étape(s) effectuée(s)"), + ( + "“{}” has changes that are not saved. Save them before closing?", + "« {} » contient des modifications non enregistrées. Les enregistrer avant de fermer ?", + ), ]; From e44662305f2367189e0fd11bac9d010e37e3f73b Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 22 Oct 2026 10:25:46 -0400 Subject: [PATCH 20/29] i18n tests: the same checks for every language, none fail on a missing translation (#1576) * i18n: missing French strings don't fail tests * i18n: drop the Czech tool-name translation check * i18n tests: one catalog check for every language, no translated literals One test checks every catalog (each language's table and context table, and the shared tables' columns) for duplicate and stale keys, empty translations, placeholders, padding, ellipses and label colons. One test selects, persists and checks document data for every interface language. Context lookup, fallback, built-in names and RTL are checked over every language against the catalogs. Asserts on particular translated text, and checks that particular strings are translated, are gone. * i18n: drop a stale German entry --- crates/ui-egui/src/chrome.rs | 16 +- crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/guide_selection_tests.rs | 5 - crates/ui-egui/src/i18n.rs | 652 +++++--------------- crates/ui-egui/src/i18n/de.rs | 1 - crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/src/menus.rs | 167 +---- crates/ui-egui/src/panels/properties.rs | 15 +- 8 files changed, 205 insertions(+), 655 deletions(-) diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 0df5361f9..e853e6793 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -1155,7 +1155,7 @@ mod tests { /// The application bar's search field (German interface). fn search_node<'h>(h: &'h egui_kittest::Harness<'static, test_window::Window>) -> egui_kittest::Node<'h> { - h.get_by(|n| n.role() == egui::accesskit::Role::TextInput && n.placeholder() == Some("Suchen")) + h.get_by(|n| n.role() == egui::accesskit::Role::TextInput && n.placeholder() == Some(crate::i18n::tr("de", "Search"))) } /// A document with two frames, the Selection tool, German menus, and the search field clicked. @@ -1187,12 +1187,12 @@ mod tests { #[test] fn the_search_field_finds_and_runs_menu_commands() { let mut h = searching(); - h.event(egui::Event::Text("gruppier".into())); + let group = crate::i18n::tr("de", "Group"); + h.event(egui::Event::Text(group.to_lowercase())); h.run_steps(4); - assert!(row(&h, "Gruppieren").is_some(), "the German label is listed"); - assert!(row(&h, "Gruppierung aufheben").is_some()); + assert!(row(&h, group).is_some(), "the German label is listed"); // Nothing is selected, so Group is off and Return doesn't run it. - assert!(row(&h, "Gruppieren").is_some_and(|n| n.accesskit_node().is_disabled())); + assert!(row(&h, group).is_some_and(|n| n.accesskit_node().is_disabled())); h.key_press(egui::Key::Enter); h.run_steps(4); assert_eq!(items(&h), (2, 0), "a disabled command doesn't run"); @@ -1205,7 +1205,7 @@ mod tests { h.key_press(egui::Key::Enter); h.run_steps(4); assert_eq!(items(&h).0, 1, "the two frames are grouped"); - assert!(row(&h, "Gruppieren").is_none(), "the matches closed"); + assert!(row(&h, group).is_none(), "the matches closed"); assert!(!h.ctx.memory(|m| m.has_focus(super::search_id())), "the field gave the keyboard back"); } @@ -1227,11 +1227,11 @@ mod tests { assert_eq!(items(&h), (2, 2), "nothing was deleted or deselected"); h.event(egui::Event::Text("zz-no-such-command".into())); h.run_steps(4); - assert!(h.query_by_label("Keine passenden Befehle").is_some()); + assert!(h.query_by_label(crate::i18n::tr("de", "No matching commands")).is_some()); // Escape closes the matches and clears the field without touching the document. h.key_press(egui::Key::Escape); h.run_steps(4); - assert!(h.query_by_label("Keine passenden Befehle").is_none()); + assert!(h.query_by_label(crate::i18n::tr("de", "No matching commands")).is_none()); assert!(!h.ctx.text_edit_focused()); assert_eq!(h.state().app.session.tool_id(), "rectangleFrame"); assert_eq!(items(&h), (2, 2)); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6b60b1296..40787954f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -8963,7 +8963,7 @@ mod tests { assert_eq!(app.ui.language, "de"); assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("preferences")); let labels = dialog_frame(&mut app, &ctx, screen, vec![]); - let heading = visible_label(&labels, screen, "Sprache der Oberfläche"); + let heading = visible_label(&labels, screen, crate::i18n::tr("de", "Interface Language")); let combo = visible_label(&labels, screen, "Deutsch"); // The names stay endonyms in the German interface. diff --git a/crates/ui-egui/src/guide_selection_tests.rs b/crates/ui-egui/src/guide_selection_tests.rs index 6c41d0122..d69026712 100644 --- a/crates/ui-egui/src/guide_selection_tests.rs +++ b/crates/ui-egui/src/guide_selection_tests.rs @@ -190,11 +190,6 @@ fn select_all_guides_is_in_the_edit_menu_on_the_spread_in_view() { assert_eq!(crate::menus::default_shortcut("guide.selectAll"), Some("Cmd+Alt+G")); crate::menus::activate(h.state_mut(), "guide.selectAll", &serde_json::Value::Null); assert_eq!(selected(&h), [0, 1, 2]); - assert_eq!(crate::i18n::tr("de", "Select All Guides"), "Alle Hilfslinien auswählen"); - for (code, _) in crate::i18n::LANGUAGES.iter().filter(|(c, _)| !c.is_empty()) { - assert_ne!(crate::i18n::tr(code, "Select All Guides"), "Select All Guides", "{code}"); - assert_ne!(crate::i18n::tr(code, "Ruler Guide"), "Ruler Guide", "{code}"); - } h.state_mut().ui.guides = false; assert!(!crate::menus::menu_enabled(h.state(), "guide.selectAll")); } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index fec123a33..6057abc97 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -4598,332 +4598,198 @@ pub fn workspace_name<'a>(lang: &str, name: &'a str) -> &'a str { #[cfg(test)] mod tests { use super::*; + use std::collections::HashSet; + + /// Every per-language table `tr` looks up, by interface language. + const LANGUAGE_TABLES: &[(&str, &[(&str, &str)])] = &[ + ("ar", ar::TABLE), + ("cs", cs::TABLE), + ("de", de::TABLE), + ("fr", fr::TABLE), + ("it", it::TABLE), + ("ja", ja::TABLE), + ("ka", ka::TABLE), + ("pl", pl::TABLE), + ("pt-br", pt_br::TABLE), + ("ru", ru::TABLE), + ("uk", uk::TABLE), + ]; + + /// Every per-language table `tr_context` looks up. + const CONTEXT_TABLES: &[(&str, &[(&str, &str, &str)])] = + &[("ar", ar::CONTEXT), ("cs", cs::CONTEXT), ("ja", ja::CONTEXT), ("pl", pl::CONTEXT), ("ru", ru::CONTEXT), ("uk", uk::CONTEXT)]; + + /// The languages of the shared tables' columns, in column order. + const SHARED_COLUMNS: [&str; 5] = ["de", "fr", "es", "ja", "zh"]; + + /// The German and Japanese tables translate the whole interface and win over the shared columns. + const WHOLE_INTERFACE: [&str; 2] = ["de", "ja"]; + + #[test] + fn every_interface_language_has_a_catalog() { + for (lang, i) in SHARED_COLUMNS.iter().zip(0..) { + assert_eq!(column(lang), Some(i), "{lang}"); + } + for (code, name) in LANGUAGES.iter().filter(|(code, _)| !code.is_empty()) { + assert!(!name.is_empty(), "{code}"); + assert!(LANGUAGE_TABLES.iter().any(|(lang, _)| lang == code) || column(code).is_some(), "{code} has no catalog in LANGUAGE_TABLES"); + } + } #[test] fn cached_lookup_preserves_every_translation_across_language_switches() { + let own = |lang: &str, key: &str| { + LANGUAGE_TABLES.iter().find(|(code, _)| *code == lang).and_then(|(_, table)| table.iter().find(|(k, _)| *k == key)).map(|(_, text)| *text) + }; for (key, translations) in TABLE { - for (lang, expected) in ["de", "fr", "es", "ja", "zh"].into_iter().zip(translations) { - // `de::TABLE` and `ja::TABLE` translate the whole interface and win over the shared columns. - if lang != "de" && lang != "ja" { - assert_eq!(tr(lang, key), *expected, "{lang}: {key}"); - } + for (lang, shared) in SHARED_COLUMNS.into_iter().zip(translations) { + // A language's own table is looked up before the shared column. + assert_eq!(tr(lang, key), own(lang, key).unwrap_or(*shared), "{lang}: {key}"); } assert_eq!(tr("", key), *key); } - for (key, expected) in de::TABLE { - assert_eq!(tr("de", key), *expected, "de: {key}"); - } - for (key, expected) in ar::TABLE { - assert_eq!(tr("ar", key), *expected, "ar: {key}"); - } - for (key, expected) in pt_br::TABLE { - assert_eq!(tr("pt-br", key), *expected, "pt-br: {key}"); - } - for (key, expected) in it::TABLE { - assert_eq!(tr("it", key), *expected, "it: {key}"); - } - for (key, expected) in uk::TABLE { - assert_eq!(tr("uk", key), *expected, "uk: {key}"); - } - for (key, expected) in ru::TABLE { - assert_eq!(tr("ru", key), *expected, "ru: {key}"); - } - for (key, expected) in cs::TABLE { - assert_eq!(tr("cs", key), *expected, "cs: {key}"); - } - for (key, expected) in fr::TABLE { - assert_eq!(tr("fr", key), *expected, "fr: {key}"); - } - for (key, expected) in pl::TABLE { - assert_eq!(tr("pl", key), *expected, "pl: {key}"); - } - for (key, expected) in ka::TABLE { - assert_eq!(tr("ka", key), *expected, "ka: {key}"); + for (lang, table) in LANGUAGE_TABLES { + for (key, expected) in *table { + assert_eq!(tr(lang, key), *expected, "{lang}: {key}"); + assert_eq!(tr("", key), *key); + } } + // Strings no catalog has stay as they are, in every language. let unknown = String::from("A user-defined untranslated label"); - for lang in ["pl", "cs", "uk", "ru", "ar", "pt-br", "it", "ka", "zh", "ja", "de", "fr", "es", "", "unknown"] { - assert!(std::ptr::eq(tr(lang, &unknown), unknown.as_str())); + for lang in LANGUAGES.iter().map(|(code, _)| *code).chain(["en", "unknown"]) { + assert!(std::ptr::eq(tr(lang, &unknown), unknown.as_str()), "{lang}"); + // Fixed standard names stay identical. + assert_eq!(tr(lang, "PDF/X-4"), "PDF/X-4", "{lang}"); } } #[test] - fn translates_known_strings_and_keeps_the_rest() { - assert_eq!(tr("de", "File"), "Datei"); - assert_eq!(tr("ja", "Swatches"), "スウォッチ"); - assert_eq!(tr("fr", "Something new"), "Something new"); - assert_eq!(tr("", "File"), "File"); - assert_eq!(tr("ar", "File"), "ملف"); - assert_eq!(tr("ar", "Unknown label"), "Unknown label"); - assert_eq!(tr("pt-br", "File"), "Arquivo"); - assert_eq!(tr("pt-br", "New Document…"), "Novo documento…"); - assert_eq!(tr("pt-br", "Unknown label"), "Unknown label"); - assert_eq!(tr("it", "Edit"), "Modifica"); - assert_eq!(tr("it", "New Document…"), "Nuovo documento…"); - assert_eq!(tr("it", "Unknown label"), "Unknown label"); - assert!(is_rtl("ar")); - for (i, (en, translation)) in ar::TABLE.iter().enumerate() { - assert!(ar::TABLE[..i].iter().all(|(key, _)| key != en), "duplicate {en}"); - assert!(!translation.is_empty(), "{en}"); + fn context_captions_come_from_their_context_or_the_plain_translation() { + for (lang, table) in CONTEXT_TABLES { + for (key, scope, text) in *table { + assert_eq!(tr_context(lang, key, scope), *text, "{lang}: {key} ({scope})"); + } } - for (i, (en, translation)) in pt_br::TABLE.iter().enumerate() { - assert!(pt_br::TABLE[..i].iter().all(|(key, _)| key != en), "duplicate {en}"); - assert!(!translation.is_empty(), "{en}"); + for (key, scope, row) in CONTEXT { + for (lang, shared) in SHARED_COLUMNS.into_iter().zip(row) { + // A language's own context table is looked up before the shared one. + let own = CONTEXT_TABLES + .iter() + .filter(|(code, _)| *code == lang) + .flat_map(|(_, table)| table.iter()) + .find(|(k, s, _)| k == key && s == scope) + .map(|(_, _, text)| *text); + assert_eq!(tr_context(lang, key, scope), own.unwrap_or(*shared), "{lang}: {key} ({scope})"); + } } - for (i, (en, translation)) in it::TABLE.iter().enumerate() { - assert!(it::TABLE[..i].iter().all(|(key, _)| key != en), "duplicate {en}"); - assert!(!translation.is_empty(), "{en}"); - } - // Italian entries are for keys the shared or Arabic table knows. A new English string - // falls back to English until it is translated, so it doesn't fail here. - for (en, _) in it::TABLE { - assert!(TABLE.iter().any(|(key, _)| key == en) || ar::TABLE.iter().any(|(key, _)| key == en), "it: unknown key {en}"); - } - // Every row is unique and complete. - for (i, (en, t)) in TABLE.iter().enumerate() { - assert!(TABLE[..i].iter().all(|(e, _)| e != en), "duplicate {en}"); - assert!(t.iter().all(|x| !x.is_empty()), "{en}"); + // An unknown context, or a language without one, keeps the plain translation. + let keys = CONTEXT.iter().map(|(key, _, _)| *key).chain(CONTEXT_TABLES.iter().flat_map(|(_, table)| table.iter().map(|(key, _, _)| *key))); + for key in keys { + for lang in LANGUAGES.iter().map(|(code, _)| *code).chain(["en"]) { + assert_eq!(tr_context(lang, key, "no such context"), tr(lang, key), "{lang}: {key}"); + } + assert_eq!(tr_context("", key, "count"), key); } } + /// Every catalog: no duplicate or stale keys, no empty translations, and placeholders, padding, + /// ellipses and label colons as in English. A string a catalog doesn't translate yet falls back + /// to English, so missing translations don't fail here. #[test] - fn a_column_count_and_a_list_number_read_differently() { - for (lang, count, numeral) in [ - ("de", "Anzahl:", "Zahl:"), - ("ja", "数:", "番号:"), - ("uk", "Кількість:", "Номер:"), - ("ar", "العدد:", "الرقم:"), - ("fr", "Nombre :", "Numéro:"), - ("zh", "数量:", "编号:"), - ] { - assert_eq!((tr_context(lang, "Number:", "count"), tr(lang, "Number:")), (count, numeral), "{lang}"); + fn every_catalog_is_unique_current_and_keeps_placeholders_and_markers() { + // (language, key, translation) of every catalog, and every catalog's keys by name. + let mut entries: Vec<(&str, &str, &str)> = Vec::new(); + let mut catalogs: Vec<(&str, HashSet<&str>)> = Vec::new(); + for (lang, table) in LANGUAGE_TABLES { + let keys: HashSet<_> = table.iter().map(|(key, _)| *key).collect(); + assert_eq!(keys.len(), table.len(), "{lang}: duplicate keys"); + catalogs.push((*lang, keys)); + entries.extend(table.iter().map(|(key, text)| (*lang, *key, *text))); } - assert_eq!(tr_context("en", "Number:", "count"), "Number:"); - assert_eq!(tr("de", "Gutter:"), "Spaltenabstand:"); - // The Pages panel menu. - for key in [ - "Insert Pages…", - "Move Pages…", - "New Parent…", - "Override All Parent Page Items", - "Remove All Local Overrides", - "Detach All Objects from Parent", - "Create Alternate Layout…", - "Allow Selected Spread to Shuffle", - ] { - assert_ne!(tr("pt-br", key), key); + let shared: HashSet<_> = TABLE.iter().map(|(key, _)| *key).collect(); + assert_eq!(shared.len(), TABLE.len(), "duplicate keys in the shared table"); + catalogs.push(("shared", shared.clone())); + for (lang, i) in SHARED_COLUMNS.into_iter().zip(0..) { + entries.extend(TABLE.iter().filter_map(|(key, row)| row.get(i).map(|text| (lang, *key, *text)))); + entries.extend(CONTEXT.iter().filter_map(|(key, _, row)| row.get(i).map(|text| (lang, *key, *text)))); + } + let mut contexts = vec![("shared", CONTEXT.iter().map(|(key, scope, _)| (*key, *scope)).collect::>())]; + for (lang, table) in CONTEXT_TABLES { + contexts.push((*lang, table.iter().map(|(key, scope, _)| (*key, *scope)).collect())); + entries.extend(table.iter().map(|(key, _, text)| (*lang, *key, *text))); } - assert_ne!(tr("ar", "Apply Parent to Pages"), "Apply Parent to Pages"); - } - #[test] - fn french_catalog_has_no_duplicate_or_stale_keys_and_keeps_placeholders() { - let catalog: HashMap<_, _> = fr::TABLE.iter().copied().collect(); - assert_eq!(catalog.len(), fr::TABLE.len(), "duplicate French keys"); - let shared: std::collections::HashSet<_> = TABLE.iter().map(|(key, _)| *key).collect(); - // `fr::TABLE` is looked up first: a key there would hide the shared table's French column. - let both: Vec<_> = catalog.keys().filter(|k| shared.contains(*k)).collect(); - assert!(both.is_empty(), "French keys also in the shared table: {both:?}"); - let mut keys = interface_strings(); - for table in [ar::TABLE, de::TABLE, it::TABLE, ja::TABLE, pt_br::TABLE, uk::TABLE, ru::TABLE, cs::TABLE] { - keys.extend(table.iter().map(|(key, _)| *key)); + // A per-language table is looked up before the shared table, so a key in both hides the + // shared column, except in the tables that translate the whole interface. + for (lang, table) in LANGUAGE_TABLES.iter().filter(|(lang, _)| column(lang).is_some() && !WHOLE_INTERFACE.contains(lang)) { + let both: Vec<_> = table.iter().map(|(key, _)| *key).filter(|key| shared.contains(key)).collect(); + assert!(both.is_empty(), "{lang} keys also in the shared table: {both:?}"); } - let stale: Vec<_> = catalog.keys().filter(|k| !keys.contains(*k)).collect(); - assert!(stale.is_empty(), "French entries for unknown keys: {stale:?}"); - let placeholders = |s: &str| { - let mut names = s.split('{').skip(1).filter_map(|part| part.split_once('}').map(|(name, _)| name.to_owned())).collect::>(); - names.sort(); + + // A key is current while the interface or another catalog has it. + let interface = interface_strings(); + let current = |key: &str, own: &str| interface.contains(key) || catalogs.iter().any(|(name, keys)| *name != own && keys.contains(key)); + for (name, keys) in &catalogs { + let mut stale: Vec<_> = keys.iter().filter(|key| !current(key, name)).collect(); + stale.sort(); + assert!(stale.is_empty(), "{name}: entries for unknown keys: {stale:?}"); + } + for (name, keys) in &contexts { + let unique: HashSet<_> = keys.iter().collect(); + assert_eq!(unique.len(), keys.len(), "{name}: duplicate context keys"); + let stale: Vec<_> = keys.iter().filter(|(key, _)| !current(key, "")).collect(); + assert!(stale.is_empty(), "{name}: contexts for unknown keys: {stale:?}"); + } + + let placeholders = |s: &'static str| { + let mut names: Vec<_> = s.split('{').skip(1).filter_map(|part| part.split_once('}').map(|(name, _)| name)).collect(); + names.sort_unstable(); names }; - let shared_french = TABLE.iter().filter_map(|(key, row)| row.get(1).map(|text| (*key, *text))); - for (key, translation) in fr::TABLE.iter().copied().chain(shared_french) { - assert!(!translation.trim().is_empty(), "empty {key}"); - assert_eq!(key.starts_with(' '), translation.starts_with(' '), "leading space: {key}"); - assert_eq!(key.ends_with(' '), translation.ends_with(' '), "trailing space: {key}"); - assert_eq!(placeholders(key), placeholders(translation), "placeholders: {key}"); + let ellipsis = |s: &str| s.ends_with('…') || s.ends_with("..."); + let colon = |s: &str| s.ends_with(':') || s.ends_with(':'); + // Full-width punctuation carries its own spacing. + let full_width = |c: char| ('\u{3000}'..='\u{303F}').contains(&c) || ('\u{FF00}'..='\u{FFEF}').contains(&c); + for (lang, key, text) in entries { + assert!(!text.trim().is_empty(), "{lang}: empty translation of {key:?}"); + assert_eq!(placeholders(key), placeholders(text), "{lang}: placeholders of {key:?}"); + // Dialog ellipses, label colons and padded captions stay as in English. + assert_eq!(ellipsis(key), ellipsis(text), "{lang}: ellipsis of {key:?}"); + assert_eq!(colon(key), colon(text), "{lang}: colon of {key:?}"); + if !text.starts_with(full_width) { + assert_eq!(key.starts_with(' '), text.starts_with(' '), "{lang}: leading space of {key:?}"); + } + if !text.ends_with(full_width) { + assert_eq!(key.ends_with(' '), text.ends_with(' '), "{lang}: trailing space of {key:?}"); + } } - assert_eq!(tr("fr", "Group"), "Associer"); - } - - /// Interface strings that read the same in French: names, abbreviations, numbering samples, key - /// symbols and words French shares with English. - const SAME_IN_FRENCH: &[&str] = &[ - " OK ", - " (auto)", - "+Bin", - "+LOC", - "A, B, C, D...", - "Angle", - "Articles", - "Bunri-Kinshi", - "Commits", - "Composition", - "Compression", - "Conditions", - "Cyan", - "DesignCraft", - "Direction", - "Distance", - "Document", - "Document…", - "Ellipse", - "Extras", - "Fractions", - "GREP", - "Hindi", - "Horizontal", - "I, II, III, IV...", - "Image", - "Index", - "Interface", - "Justification", - "Justification…", - "Kanji", - "Kenten", - "Lab", - "Ligatures", - "Magenta", - "Maximum", - "Menus", - "Menus…", - "Minimum", - "Mobile", - "Normal", - "Normal (W)", - "Notes", - "OK", - "OpenType", - "Options", - "Orange", - "Orientation", - "PDF/A-2b", - "PDF/X-4", - "Page", - "Pages", - "Pathfinder", - "Picas", - "Portrait", - "Position", - "Radial", - "Rectangle", - "Rensuuji", - "Rotation", - "Ruby", - "Ruby…", - "Satin", - "Saturation", - "Script", - "Scripts", - "Section", - "Serif", - "Shatai", - "Signature", - "Simple", - "Structure", - "Style", - "Styles", - "Tate-Chu-Yoko", - "Triangle", - "Version", - "Vertical", - "Violet", - "Warichu", - "Web", - "a, b, c, d...", - "document", - "i, ii, iii, iv...", - "pages", - "ΔLOC", - "⇧", - "−Bin", - "−LOC", - "⌃", - "⌘", - "⌥", - ]; - - #[test] - fn french_translates_every_interface_string() { - let keys = interface_strings(); - // A new English string needs a French entry (or a place on `SAME_IN_FRENCH`) before it ships. - let mut untranslated: Vec<_> = keys.iter().filter(|key| tr("fr", key) == **key && !SAME_IN_FRENCH.contains(key)).collect(); - untranslated.sort(); - assert!(untranslated.is_empty(), "French falls back to English for: {untranslated:?}"); - for key in SAME_IN_FRENCH { - assert!(keys.contains(key), "SAME_IN_FRENCH lists a string the interface no longer has: {key}"); - assert_eq!(tr("fr", key), *key, "SAME_IN_FRENCH lists a string French translates: {key}"); - } - for tool in designcraft_tools::TOOL_GROUPS.iter().flat_map(|group| group.iter()) { - assert!(tr("fr", tool.label).starts_with("Outil "), "{}", tool.id); - } - assert_eq!(tr("fr", "Selection Tool"), "Outil Sélection"); - assert_eq!(tr("fr", "Don't Save"), "Ne pas enregistrer"); } #[test] - fn ukrainian_catalog_covers_existing_keys_and_preserves_placeholders() { - let catalog: std::collections::HashMap<_, _> = uk::TABLE.iter().copied().collect(); - assert_eq!(catalog.len(), uk::TABLE.len(), "duplicate Ukrainian keys"); - let mut keys = std::collections::HashSet::new(); - keys.extend(TABLE.iter().map(|(key, _)| *key)); - keys.extend(ar::TABLE.iter().map(|(key, _)| *key)); - keys.extend(pt_br::TABLE.iter().map(|(key, _)| *key)); - // A new English string falls back to English until it is translated, so only stale - // entries (keys no catalog knows any more) fail. - let stale: Vec<_> = catalog.keys().filter(|k| !keys.contains(*k)).collect(); - assert!(stale.is_empty(), "Ukrainian entries for unknown keys: {stale:?}"); - let placeholders = - |s: &str| s.split('{').skip(1).filter_map(|part| part.split_once('}').map(|(name, _)| name.to_owned())).collect::>(); - for (key, translation) in uk::TABLE { - assert!(!translation.trim().is_empty(), "empty {key}"); - let mut source = placeholders(key); - let mut translated = placeholders(translation); - source.sort(); - translated.sort(); - assert_eq!(source, translated, "placeholders: {key}"); + fn only_arabic_lays_out_right_to_left() { + for (code, _) in LANGUAGES { + assert_eq!(is_rtl(code), *code == "ar", "{code}"); + } + } + + /// Built-in style and workspace names follow the interface language; names people give their + /// own styles and workspaces are document data and stay as typed. + #[test] + fn only_built_in_style_and_workspace_names_are_translated() { + for (code, _) in LANGUAGES { + for name in [designcraft_doc::NO_PARA_STYLE, designcraft_doc::BASIC_PARAGRAPH, designcraft_doc::NO_CHAR_STYLE] { + assert_eq!(style_name(code, name), tr(code, name), "{code}"); + } + assert_eq!(workspace_name(code, "Essentials"), tr(code, "Essentials"), "{code}"); + for custom in ["Group", "Columns", "My layout style"] { + assert_eq!(style_name(code, custom), custom, "{code}"); + assert_eq!(workspace_name(code, custom), custom, "{code}"); + } } - assert_eq!(tr_context("uk", "Columns", "table"), "Стовпці"); - assert_eq!(tr("uk", "Columns"), "Колонки"); - assert_eq!(tr_context("uk", "Group", "selection"), "Група"); - // Step and Repeat's grid columns are not a text frame's. - assert_eq!(tr_context("uk", "Columns:", "grid"), "Стовпці:"); - assert_eq!(tr_context("ja", "Columns:", "grid"), "列:"); - assert_eq!(tr("ja", "Columns:"), "段:"); - assert_eq!(tr("uk", "Group"), "Згрупувати"); - assert_eq!(tr_context("", "Columns", "table"), "Columns"); - assert_eq!(tr_context("ja", "Span Columns", "paragraphLayout"), "段抜き"); - assert_eq!(tr("ja", "Span Columns"), "段抜きと段分割"); - assert_eq!(tr_context("uk", "Custom caption", "custom"), "Custom caption"); - assert_eq!(tr("uk", "through"), "включно"); - assert_eq!(tr("uk", "up to"), "не включно"); - assert!(!is_rtl("uk")); - assert_eq!(tr("uk", "Type"), "Текст"); - assert_eq!(tr("uk", "Spread"), "Розворот"); - assert_eq!(tr("uk", "Story"), "Текстовий матеріал"); - assert_eq!(tr("uk", "Footer Rows"), "Рядки нижнього колонтитула"); - assert_eq!(style_name("uk", "[Basic Paragraph]"), "[Основний абзац]"); - assert_eq!(style_name("uk", "My layout style"), "My layout style"); - assert_eq!(workspace_name("uk", "Essentials"), "Основне"); - assert_eq!(workspace_name("uk", "My workspace"), "My workspace"); } #[test] - fn georgian_catalog_preserves_placeholders_and_counts() { - let catalog: HashMap<_, _> = ka::TABLE.iter().copied().collect(); - assert_eq!(catalog.len(), ka::TABLE.len(), "duplicate Georgian keys"); - let placeholders = |s: &str| { - s.split('{').skip(1).filter_map(|part| part.split_once('}').map(|(name, _)| name.to_owned())).collect::>() - }; - for (key, translation) in ka::TABLE { - assert!(!translation.trim().is_empty(), "empty {key}"); - assert_eq!(placeholders(key), placeholders(translation), "placeholders: {key}"); - assert_eq!(key.ends_with('…'), translation.ends_with('…'), "ellipsis: {key}"); - // Georgian has no capitals in running text: Mtavruli never appears in the interface. - assert!(!translation.chars().any(|c| ('\u{1C90}'..='\u{1CBF}').contains(&c)), "Mtavruli: {key}"); - } - assert_eq!(tr("ka", "File"), "ფაილი"); - assert_eq!(tr("ka", "Save As…"), "შენახვა როგორც…"); - assert_eq!(tr("ka", "Unknown label"), "Unknown label"); - assert!(!is_rtl("ka")); + fn georgian_counts_use_category_captions_for_every_number() { for n in [1, 2, 5, 21] { assert_eq!(count_label("ka", "pages", n), format!("გვერდი: {n}")); } @@ -4941,62 +4807,6 @@ mod tests { assert_eq!(count_label("", "objects", 2), "2 objects"); } - #[test] - fn russian_catalog_covers_existing_keys_and_preserves_placeholders() { - let catalog: std::collections::HashMap<_, _> = ru::TABLE.iter().copied().collect(); - assert_eq!(catalog.len(), ru::TABLE.len(), "duplicate Russian keys"); - let mut keys = std::collections::HashSet::new(); - keys.extend(TABLE.iter().map(|(key, _)| *key)); - keys.extend(ar::TABLE.iter().map(|(key, _)| *key)); - keys.extend(pt_br::TABLE.iter().map(|(key, _)| *key)); - keys.extend(it::TABLE.iter().map(|(key, _)| *key)); - keys.extend(ja::TABLE.iter().map(|(key, _)| *key)); - keys.extend(uk::TABLE.iter().map(|(key, _)| *key)); - // A new English string falls back to English until it is translated, so only stale - // entries (keys no catalog knows any more) fail. - let stale: Vec<_> = catalog.keys().filter(|k| !keys.contains(*k)).collect(); - assert!(stale.is_empty(), "Russian entries for unknown keys: {stale:?}"); - let placeholders = - |s: &str| s.split('{').skip(1).filter_map(|part| part.split_once('}').map(|(name, _)| name.to_owned())).collect::>(); - for (key, translation) in ru::TABLE { - assert!(!translation.trim().is_empty(), "empty {key}"); - assert_eq!(key.starts_with(' '), translation.starts_with(' '), "leading space: {key}"); - assert_eq!(key.ends_with(' '), translation.ends_with(' '), "trailing space: {key}"); - assert!(!translation.contains(['ґ', 'є', 'і', 'ї', 'Ґ', 'Є', 'І', 'Ї']), "Ukrainian letter in {key}"); - let mut source = placeholders(key); - let mut translated = placeholders(translation); - source.sort(); - translated.sort(); - assert_eq!(source, translated, "placeholders: {key}"); - } - } - - #[test] - fn russian_is_selectable_ltr_and_resolves_contexts_styles_and_menu_paths() { - assert!(LANGUAGES.contains(&("ru", "Русский"))); - assert!(!is_rtl("ru")); - assert_eq!(tr("ru", "File"), "Файл"); - assert_eq!(tr("ru", "Type"), "Текст"); - assert_eq!(tr("ru", "Spread"), "Разворот"); - assert_eq!(tr("ru", "Story"), "Материал"); - assert_eq!(tr("ru", "Unknown label"), "Unknown label"); - assert_eq!(tr_context("ru", "Columns", "table"), "Столбцы"); - assert_eq!(tr("ru", "Columns"), "Колонки"); - assert_eq!(tr_context("ru", "Group", "selection"), "Группа"); - assert_eq!(tr("ru", "Group"), "Сгруппировать"); - assert_eq!(tr_context("ru", "Custom caption", "custom"), "Custom caption"); - assert_eq!(tr("ru", "through"), "включительно"); - assert_eq!(tr("ru", "up to"), "не включая"); - assert_eq!(tr("ru", "Edit/Spelling"), "Редактирование/Орфография"); - assert_eq!(tr("ru", "Type/Insert Special Character/Quotation Marks"), "Текст/Вставить специальный символ/Кавычки"); - assert_eq!(style_name("ru", "[Basic Paragraph]"), "[Основной абзац]"); - assert_eq!(style_name("ru", "My layout style"), "My layout style"); - assert_eq!(workspace_name("ru", "Essentials"), "Основное"); - assert_eq!(workspace_name("ru", "My workspace"), "My workspace"); - // Fixed standard names stay identical. - assert_eq!(tr("ru", "PDF/X-4"), "PDF/X-4"); - } - #[test] fn russian_counts_use_category_captions_for_every_number() { assert!(category_first("ru") && category_first("uk") && !category_first("de") && !category_first("")); @@ -5009,45 +4819,6 @@ mod tests { } } - #[test] - fn polish_catalog_covers_existing_keys_and_preserves_placeholders() { - let catalog: HashMap<_, _> = pl::TABLE.iter().copied().collect(); - assert_eq!(catalog.len(), pl::TABLE.len(), "duplicate Polish keys"); - let mut keys = std::collections::HashSet::new(); - keys.extend(TABLE.iter().map(|(key, _)| *key)); - for table in [ar::TABLE, pt_br::TABLE, ja::TABLE, it::TABLE, uk::TABLE, de::TABLE, fr::TABLE, ru::TABLE, cs::TABLE] { - keys.extend(table.iter().map(|(key, _)| *key)); - } - // A new English string falls back to English until it is translated; only stale entries fail. - let stale: Vec<_> = catalog.keys().filter(|k| !keys.contains(*k)).collect(); - assert!(stale.is_empty(), "Polish entries for unknown keys: {stale:?}"); - let placeholders = - |s: &str| s.split('{').skip(1).filter_map(|part| part.split_once('}').map(|(name, _)| name.to_owned())).collect::>(); - for (key, translation) in pl::TABLE { - assert!(!translation.trim().is_empty(), "empty {key}"); - let mut source = placeholders(key); - let mut translated = placeholders(translation); - source.sort(); - translated.sort(); - assert_eq!(source, translated, "placeholders: {key}"); - assert_eq!(key.ends_with('…'), translation.ends_with('…'), "ellipsis: {key}"); - } - assert!(LANGUAGES.contains(&("pl", "Polski"))); - assert!(!is_rtl("pl")); - assert_eq!(tr("pl", "File"), "Plik"); - assert_eq!(tr("pl", "New Document…"), "Nowy dokument…"); - assert_eq!(tr("pl", "Spread"), "Rozkładówka"); - assert_eq!(tr("pl", "Unknown label"), "Unknown label"); - assert_eq!(style_name("pl", "[Basic Paragraph]"), "[Podstawowy akapit]"); - assert_eq!(workspace_name("pl", "Essentials"), "Podstawowe"); - // A table's columns and grid columns aren't a text frame's; a selection's group isn't the action. - assert_eq!(tr("pl", "Columns"), "Łamy"); - assert_eq!(tr_context("pl", "Columns", "table"), "Kolumny"); - assert_eq!(tr_context("pl", "Columns:", "grid"), "Łamy:"); - assert_eq!(tr("pl", "Group"), "Grupuj"); - assert_eq!(tr_context("pl", "Group", "selection"), "Grupa"); - } - #[test] fn polish_counts_use_category_captions_for_every_number() { for n in [0, 1, 2, 5, 12, 22, 25] { @@ -5058,14 +4829,10 @@ mod tests { assert_eq!(tr("pl", "{pages} Pages in {spreads} Spreads"), "Strony: {pages}, rozkładówki: {spreads}"); } - /// Every English string the interface passes to `tr`, as far as the catalogs, command and tool - /// tables and the list of UI-only labels know them. - fn interface_strings() -> std::collections::HashSet<&'static str> { - let mut keys = std::collections::HashSet::new(); - keys.extend(TABLE.iter().map(|(key, _)| *key)); - for table in [ar::TABLE, it::TABLE, ja::TABLE, pt_br::TABLE, uk::TABLE] { - keys.extend(table.iter().map(|(key, _)| *key)); - } + /// Every English string the interface passes to `tr`, as far as the command and tool tables and + /// the list of UI-only labels know them. + fn interface_strings() -> HashSet<&'static str> { + let mut keys = HashSet::new(); // Command labels and menu names reach `tr` from the engine and the UI command table. for spec in designcraft_engine::command_specs() { keys.insert(spec.label); @@ -5085,6 +4852,8 @@ mod tests { "(unchanged)", "[No Language]", "Cell Number:", + "Differs from this document", + "Digits:", "Change fill to:", "Chinese: Simplified", "Chinese: Traditional", @@ -5120,6 +4889,7 @@ mod tests { "Found", "Grab bag", "Key Object", + "Load Styles", "layer", "layers", "Lines +/−", @@ -5135,6 +4905,7 @@ mod tests { "Redefine Document Style", "Report an issue", "Reverse the order", + "Sort Entries in Alphabetical Order", "Story {story} ← story {parent}", "Story Editor — {count} words", "Text Anchor", @@ -5156,48 +4927,6 @@ mod tests { keys } - #[test] - fn czech_catalog_has_no_stale_keys_and_keeps_placeholders_and_markers() { - let catalog: HashMap<_, _> = cs::TABLE.iter().copied().collect(); - assert_eq!(catalog.len(), cs::TABLE.len(), "duplicate Czech keys"); - let keys = interface_strings(); - // A new English string falls back to English until it is translated, so only stale - // entries (keys nothing passes to `tr` any more) fail. - let stale: Vec<_> = catalog.keys().filter(|k| !keys.contains(*k)).collect(); - assert!(stale.is_empty(), "Czech entries for unknown keys: {stale:?}"); - let placeholders = - |s: &str| s.split('{').skip(1).filter_map(|part| part.split_once('}').map(|(name, _)| name.to_owned())).collect::>(); - for (key, translation) in cs::TABLE { - assert!(!translation.trim().is_empty(), "empty {key}"); - let mut source = placeholders(key); - let mut translated = placeholders(translation); - source.sort(); - translated.sort(); - assert_eq!(source, translated, "placeholders: {key}"); - // Dialog ellipses, label colons and padded button captions stay as in English. - assert_eq!(key.ends_with('…'), translation.ends_with('…'), "ellipsis: {key}"); - assert_eq!(key.ends_with(':'), translation.ends_with(':'), "colon: {key}"); - assert_eq!(key.starts_with(' '), translation.starts_with(' '), "leading space: {key}"); - assert_eq!(key.ends_with(' '), translation.ends_with(' '), "trailing space: {key}"); - } - assert!(!is_rtl("cs")); - assert_eq!(tr("cs", "File"), "Soubor"); - assert_eq!(tr("cs", "New Document…"), "Nový dokument…"); - assert_eq!(tr("cs", "Spread"), "Dvoustrana"); - assert_eq!(tr("cs", "Bleed"), "Spadávka"); - assert_eq!(tr("cs", "Leading"), "Proklad"); - assert_eq!(tr("cs", "Unknown label"), "Unknown label"); - assert_eq!(tr_context("cs", "Group", "selection"), "Skupina"); - assert_eq!(tr_context("cs", "Name", "contributors"), "Jméno"); - assert_eq!(tr_context("cs", "Name", "unknown"), "Název"); - assert_eq!(tr("cs", "Group"), "Seskupit"); - assert_eq!(tr_context("cs", "Columns", "table"), tr("cs", "Columns")); - assert_eq!(style_name("cs", "[Basic Paragraph]"), "[Základní odstavec]"); - assert_eq!(style_name("cs", "My layout style"), "My layout style"); - assert_eq!(workspace_name("cs", "Essentials"), "Základní"); - assert_eq!(workspace_name("cs", "My workspace"), "My workspace"); - } - #[test] fn czech_counts_use_the_plural_form_for_the_number() { for (n, form) in [(0, "chyb"), (1, "chyba"), (2, "chyby"), (4, "chyby"), (5, "chyb"), (11, "chyb"), (22, "chyb")] { @@ -5222,51 +4951,4 @@ mod tests { assert!(forms.contains(&tr("cs", noun)), "{noun}: the catalog row is one of the plural forms"); } } - - #[test] - fn czech_translates_every_tool_name() { - for tool in designcraft_tools::TOOL_GROUPS.iter().flat_map(|group| group.iter()) { - assert_ne!(tr("cs", tool.label), tool.label, "{}", tool.id); - assert_eq!(tr("", tool.label), tool.label); - } - } - - #[test] - fn japanese_vertical_type_commands_are_translated() { - for (en, ja) in [ - ("Story Direction", "組み方向"), - ("Horizontal", "横書き"), - ("Vertical", "縦書き"), - ("Tate-Chu-Yoko", "縦中横"), - ("Ruby…", "ルビ…"), - ("Kenten", "圏点"), - ("Warichu", "割り注"), - ] { - assert_eq!(tr("ja", en), ja); - } - } - - #[test] - fn pdf_export_dialog_strings_are_translated() { - // Translated labels in every supported language. - assert_ne!(tr("zh", "Crop Marks"), "Crop Marks"); - assert_ne!(tr("de", "Tagged PDF"), "Tagged PDF"); - assert_ne!(tr("ar", "Include document bleed"), "Include document bleed"); - assert_ne!(tr("pt-br", "Compress images"), "Compress images"); - // English returns the key unchanged. - assert_eq!(tr("", "Export PDF"), "Export PDF"); - // An unknown string still falls through unchanged. - assert_eq!(tr("de", "Low Quality Print"), "Low Quality Print"); - // Fixed standard names stay identical in every language. - assert_eq!(tr("ja", "PDF/X-4"), "PDF/X-4"); - } - - #[test] - fn style_row_menu_strings_are_translated_in_every_language() { - for (code, _) in LANGUAGES.iter().filter(|(c, _)| !c.is_empty()) { - for key in ["Redefine Style", "Alt-click clears overrides", "Apply \"{name}\", Clear Overrides"] { - assert_ne!(tr(code, key), key, "{code}: {key}"); - } - } - } } diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index d47657b09..4f4177cbd 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -2037,7 +2037,6 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Print Layer", "Ebene drucken"), ("Suppress Text Wrap When Layer is Hidden", "Textumfluss bei ausgeblendeter Ebene unterdrücken"), // Remaining interface strings. - ("A custom name", "Ein eigener Name"), ("Close Panel", "Bedienfeld schließen"), ("Default Fill and Stroke", "Standardfläche und -kontur"), ("Distribute Rows Evenly", "Zeilen gleichmäßig verteilen"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 18fa402a5..535c87629 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2460,7 +2460,7 @@ mod tests { assert_eq!(app.ui.status, "Table: No table selected"); app.ui.language = "cs".into(); app.status_error("Table", "No table selected"); - assert_eq!(app.ui.status, "Tabulka: No table selected"); + assert_eq!(app.ui.status, format!("{}: No table selected", crate::i18n::tr("cs", "Table"))); } #[test] diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 2a271324a..87537abd7 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -3367,16 +3367,12 @@ mod tests { } #[test] - fn screen_mode_shows_the_current_mode_and_view_submenus_are_translated() { + fn screen_mode_shows_the_current_mode() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); let mode = |app: &DesignApp, m: &str| checked(app, "view.screenMode", &json!({ "mode": m })); assert_eq!((mode(&app, "normal"), mode(&app, "preview")), (Some(true), Some(false))); app.ui.screen_mode = crate::ScreenMode::Preview; assert_eq!((mode(&app, "normal"), mode(&app, "preview")), (Some(false), Some(true))); - // Every View submenu has its Japanese path (Edit › Menus shows them). - for path in submenu_paths("View") { - assert_ne!(crate::i18n::tr("ja", &path), path, "{path} has no Japanese row"); - } } fn walk(items: &[Item], out: &mut Vec<(String, String, Value)>) { @@ -3793,8 +3789,8 @@ mod tests { run_ui(&mut app, "app.language", &json!({"lang": "de"})).unwrap().unwrap(); assert_eq!(app.ui.language, "de"); assert_eq!(checked(&app, "app.language", &json!({"lang": "de"})), Some(true)); - assert_eq!(crate::i18n::tr(&app.ui.language, "Window"), "Fenster"); assert!(run_ui(&mut app, "app.language", &json!({"lang": "xx"})).unwrap().is_err()); + assert_eq!(app.ui.language, "de"); // The language is set in Preferences, not from a menu; without `lang` the command opens it. let mut items = Vec::new(); for (_, entries) in menu_tree() { @@ -3804,153 +3800,23 @@ mod tests { run_ui(&mut app, "app.language", &json!({})).unwrap().unwrap(); assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("preferences")); assert_eq!(app.ui.language, "de"); - app.ui.dialog = None; - - run_ui(&mut app, "app.language", &json!({"lang": "zh"})).unwrap().unwrap(); - assert_eq!(app.ui.language, "zh"); - assert_eq!(crate::i18n::tr(&app.ui.language, "File"), "文件"); - - app.run("file.new", json!({"pages": 4, "facingPages": true})).unwrap(); - let before = serde_json::to_value(&app.session.doc().unwrap().doc).unwrap(); - run_ui(&mut app, "app.language", &json!({"lang": "ar"})).unwrap().unwrap(); - assert_eq!(app.ui.language, "ar"); - assert_eq!(checked(&app, "app.language", &json!({"lang": "ar"})), Some(true)); - assert_eq!(before, serde_json::to_value(&app.session.doc().unwrap().doc).unwrap()); - for (title, _) in menu_tree() { - assert_ne!(crate::i18n::tr("ar", title), title, "{title}"); - } - // Every menu title has a translation (Japanese never matches the English). - for (title, _) in menu_tree() { - assert_ne!(crate::i18n::tr("ja", title), title, "{title}"); - } - - run_ui(&mut app, "app.language", &json!({"lang": "pt-br"})).unwrap().unwrap(); - assert_eq!(app.ui.language, "pt-br"); - assert_eq!(checked(&app, "app.language", &json!({"lang": "pt-br"})), Some(true)); - for (title, _) in menu_tree() { - // "Layout" is the natural Brazilian Portuguese word, so it stays identical - // to English; every other title must be translated. - if title != "Layout" { - assert_ne!(crate::i18n::tr("pt-br", title), title, "{title}"); - } - } - - run_ui(&mut app, "app.language", &json!({"lang": "it"})).unwrap().unwrap(); - assert_eq!(app.ui.language, "it"); - assert_eq!(checked(&app, "app.language", &json!({"lang": "it"})), Some(true)); - for (title, _) in menu_tree() { - // "File" and "Layout" are the usual Italian menu names, so they stay identical - // to English; every other title must be translated. - if title != "File" && title != "Layout" { - assert_ne!(crate::i18n::tr("it", title), title, "{title}"); - } - } - - run_ui(&mut app, "app.language", &json!({"lang": "ka"})).unwrap().unwrap(); - assert_eq!(app.ui.language, "ka"); - assert_eq!(checked(&app, "app.language", &json!({"lang": "ka"})), Some(true)); - // Every menu title, item and submenu is translated into Georgian. - let mut untranslated = Vec::new(); - for (title, entries) in menu_tree() { - let mut labels = vec![title.to_string()]; - let mut stack: Vec<&Item> = entries.iter().collect(); - while let Some(entry) = stack.pop() { - match entry { - Item::Sub(label, children) => { - labels.push(label.clone()); - stack.extend(children.iter()); - } - Item::Cmd { label, id, .. } if id != "app.language" => labels.push(label.clone()), - _ => {} - } - } - // Labels without letters ("180°") or point sizes ("72 pt") read the same in every language. - let size = |l: &str| l.strip_suffix(" pt").is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit())); - untranslated - .extend(labels.into_iter().filter(|l| l.chars().any(char::is_alphabetic) && !size(l) && crate::i18n::tr("ka", l) == l.as_str())); - } - assert!(untranslated.is_empty(), "untranslated Georgian menu labels: {untranslated:?}"); } #[test] - fn ukrainian_language_is_selectable_persisted_and_keeps_document_data() { + fn every_interface_language_is_selectable_persisted_and_keeps_document_data() { let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"pages": 4, "facingPages": true})).unwrap(); - app.run("frame.create", json!({"rect": [36, 36, 200, 200], "content": "text", "text": "My words · Мої слова"})).unwrap(); + app.run("frame.create", json!({"rect": [36, 36, 200, 200], "content": "text", "text": "My words · Мої слова · Zażółć gęślą jaźń"})).unwrap(); let before = serde_json::to_value(&app.session.doc().unwrap().doc).unwrap(); - run_ui(&mut app, "app.language", &json!({"lang": "uk"})).unwrap().unwrap(); - assert_eq!(checked(&app, "app.language", &json!({"lang": "uk"})), Some(true)); - assert_eq!(before, serde_json::to_value(&app.session.doc().unwrap().doc).unwrap()); - for (title, _) in menu_tree() { - assert_ne!(crate::i18n::tr("uk", title), title, "{title}"); + for (code, _) in crate::i18n::LANGUAGES { + run_ui(&mut app, "app.language", &json!({"lang": code})).unwrap().unwrap(); + assert_eq!(app.ui.language, *code); + assert_eq!(checked(&app, "app.language", &json!({"lang": code})), Some(true), "{code}"); + assert_eq!(before, serde_json::to_value(&app.session.doc().unwrap().doc).unwrap(), "{code}"); + let bytes = serde_json::to_vec(&app.ui).unwrap(); + let restored: crate::UiState = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(restored.language, *code); } - let bytes = serde_json::to_vec(&app.ui).unwrap(); - let restored: crate::UiState = serde_json::from_slice(&bytes).unwrap(); - assert_eq!(restored.language, "uk"); - assert_eq!(crate::i18n::tr(&restored.language, "File"), "Файл"); - assert_eq!(crate::i18n::tr(&restored.language, "A custom name"), "A custom name"); - assert!(crate::i18n::LANGUAGES.contains(&("uk", "Українська")), "Preferences lists Ukrainian by its own name"); - } - - #[test] - fn russian_language_is_selectable_persisted_and_keeps_document_data() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"pages": 4, "facingPages": true})).unwrap(); - app.run("frame.create", json!({"rect": [36, 36, 200, 200], "content": "text", "text": "My words · Мои слова"})).unwrap(); - let before = serde_json::to_value(&app.session.doc().unwrap().doc).unwrap(); - run_ui(&mut app, "app.language", &json!({"lang": "ru"})).unwrap().unwrap(); - assert_eq!(checked(&app, "app.language", &json!({"lang": "ru"})), Some(true)); - assert_eq!(before, serde_json::to_value(&app.session.doc().unwrap().doc).unwrap()); - for (title, _) in menu_tree() { - assert_ne!(crate::i18n::tr("ru", title), title, "{title}"); - } - let bytes = serde_json::to_vec(&app.ui).unwrap(); - let restored: crate::UiState = serde_json::from_slice(&bytes).unwrap(); - assert_eq!(restored.language, "ru"); - assert_eq!(crate::i18n::tr(&restored.language, "File"), "Файл"); - assert_eq!(crate::i18n::tr(&restored.language, "A custom name"), "A custom name"); - assert!(crate::i18n::LANGUAGES.contains(&("ru", "Русский")), "Preferences lists Russian by its own name"); - } - - #[test] - fn czech_language_is_selectable_persisted_and_keeps_document_data() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"pages": 4, "facingPages": true})).unwrap(); - app.run("frame.create", json!({"rect": [36, 36, 200, 200], "content": "text", "text": "My words · Příliš žluťoučký kůň"})).unwrap(); - let before = serde_json::to_value(&app.session.doc().unwrap().doc).unwrap(); - run_ui(&mut app, "app.language", &json!({"lang": "cs"})).unwrap().unwrap(); - assert_eq!(app.ui.language, "cs"); - assert_eq!(checked(&app, "app.language", &json!({"lang": "cs"})), Some(true)); - assert_eq!(before, serde_json::to_value(&app.session.doc().unwrap().doc).unwrap()); - for (title, _) in menu_tree() { - assert_ne!(crate::i18n::tr("cs", title), title, "{title}"); - } - let bytes = serde_json::to_vec(&app.ui).unwrap(); - let restored: crate::UiState = serde_json::from_slice(&bytes).unwrap(); - assert_eq!(restored.language, "cs"); - assert_eq!(crate::i18n::tr(&restored.language, "File"), "Soubor"); - assert_eq!(crate::i18n::tr(&restored.language, "A custom name"), "A custom name"); - assert!(crate::i18n::LANGUAGES.contains(&("cs", "Čeština")), "Preferences lists Czech by its own name"); - } - - #[test] - fn polish_language_is_selectable_persisted_and_keeps_document_data() { - let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"pages": 2, "facingPages": true})).unwrap(); - app.run("frame.create", json!({"rect": [36, 36, 200, 200], "content": "text", "text": "Zażółć gęślą jaźń"})).unwrap(); - let before = serde_json::to_value(&app.session.doc().unwrap().doc).unwrap(); - run_ui(&mut app, "app.language", &json!({"lang": "pl"})).unwrap().unwrap(); - assert_eq!(app.ui.language, "pl"); - assert_eq!(checked(&app, "app.language", &json!({"lang": "pl"})), Some(true)); - assert_eq!(before, serde_json::to_value(&app.session.doc().unwrap().doc).unwrap()); - for (title, _) in menu_tree() { - assert_ne!(crate::i18n::tr("pl", title), title, "{title}"); - } - let bytes = serde_json::to_vec(&app.ui).unwrap(); - let restored: crate::UiState = serde_json::from_slice(&bytes).unwrap(); - assert_eq!(restored.language, "pl"); - assert_eq!(crate::i18n::tr(&restored.language, "File"), "Plik"); - assert!(crate::i18n::LANGUAGES.contains(&("pl", "Polski")), "Preferences lists Polish by its own name"); } #[test] @@ -4993,9 +4859,10 @@ mod tests { fn command_search_matches_labels_in_the_interface_language() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); app.ui.language = "de".into(); - let items = command_search(&app, "gruppieren"); + let label = crate::i18n::tr("de", "Group"); + let items = command_search(&app, &label.to_lowercase()); let group = items.iter().find(|i| i.id == "object.group").unwrap(); - assert_eq!(group.label, "Gruppieren"); + assert_eq!(group.label, label); assert_eq!(group.shortcut.as_deref(), Some("Cmd+G")); assert!(command_search(&app, "group").iter().any(|i| i.id == "object.group"), "English labels match too"); assert!(command_search(&app, " ").is_empty()); @@ -5652,9 +5519,6 @@ mod tests { // Language follows Settings, as in the suite's other apps, titled in the interface language. assert_eq!(MAC_APP_MENU.get(settings + 1), Some(&AppMenuItem::Language)); assert_eq!(MAC_APP_MENU.get(settings + 2), Some(&AppMenuItem::Sep)); - for (code, _) in crate::i18n::LANGUAGES.iter().filter(|(c, _)| !c.is_empty()) { - assert_ne!(crate::i18n::tr(code, "Language"), "Language", "{code}"); - } let label = |command: &str| { MAC_APP_MENU.iter().find_map(|m| match m { AppMenuItem::Cmd { label, command: c, .. } if *c == command => Some(*label), @@ -5662,7 +5526,6 @@ mod tests { }) }; assert_eq!(label("app.preferences"), Some("Settings…")); - assert_ne!(crate::i18n::tr("de", "Settings…"), "Settings…"); let ids = MAC_APP_MENU.iter().filter_map(|m| if let AppMenuItem::Cmd { id, .. } = m { Some(*id) } else { None }).collect::>(); assert!(ids.iter().enumerate().all(|(i, id)| !ids[..i].contains(id)), "native ids are unique: {ids:?}"); diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 1cbd623a6..fd0094f9b 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -3148,8 +3148,19 @@ mod tests { /// are translated, with a sample of each script's figures. #[test] fn digits_choices_use_the_reference_names() { - let shown: Vec = DIGIT_OPTIONS.iter().map(|o| digit_label("fr", *o)).collect(); - assert_eq!(shown, ["Par défaut", "Arabe 0123", "Hindi ٠١٢٣", "Persan ۰۱۲۳", "Natif"].map(String::from)); + assert_eq!(DIGIT_OPTIONS.map(|o| o.1), ["Default", "Arabic", "Hindi", "Farsi", "Native"]); + for (lang, _) in crate::i18n::LANGUAGES { + let tr = |s| crate::i18n::tr(lang, s); + let shown: Vec = DIGIT_OPTIONS.iter().map(|o| digit_label(lang, *o)).collect(); + let expected = [ + tr("Default").to_string(), + format!("{} 0123", tr("Arabic")), + format!("{} ٠١٢٣", tr("Hindi")), + format!("{} ۰۱۲۳", tr("Farsi")), + tr("Native").to_string(), + ]; + assert_eq!(shown, expected, "{lang}"); + } } #[test] From 5e8ef678321cfdd2d18927e2af94d58e5f9d8836 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Thu, 22 Oct 2026 15:38:12 -0400 Subject: [PATCH 21/29] Release 0.12.0 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 42 +++++++++++++++++++++--------------------- Cargo.toml | 2 +- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0b022ecfe..e75e8d5a5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -942,7 +942,7 @@ dependencies = [ [[package]] name = "designcraft" -version = "0.11.0" +version = "0.12.0" dependencies = [ "arboard", "designcraft-engine", @@ -964,7 +964,7 @@ dependencies = [ [[package]] name = "designcraft-cli" -version = "0.11.0" +version = "0.12.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -980,7 +980,7 @@ dependencies = [ [[package]] name = "designcraft-color" -version = "0.11.0" +version = "0.12.0" dependencies = [ "craft-cms", "kurbo", @@ -992,7 +992,7 @@ dependencies = [ [[package]] name = "designcraft-compose" -version = "0.11.0" +version = "0.12.0" dependencies = [ "designcraft-color", "designcraft-doc", @@ -1012,7 +1012,7 @@ dependencies = [ [[package]] name = "designcraft-doc" -version = "0.11.0" +version = "0.12.0" dependencies = [ "chrono", "designcraft-color", @@ -1025,7 +1025,7 @@ dependencies = [ [[package]] name = "designcraft-engine" -version = "0.11.0" +version = "0.12.0" dependencies = [ "caseless", "craft-atomic", @@ -1064,7 +1064,7 @@ dependencies = [ [[package]] name = "designcraft-epub" -version = "0.11.0" +version = "0.12.0" dependencies = [ "chrono", "designcraft-color", @@ -1074,7 +1074,7 @@ dependencies = [ [[package]] name = "designcraft-fonts" -version = "0.11.0" +version = "0.12.0" dependencies = [ "core-text", "harfrust 0.13.3", @@ -1087,7 +1087,7 @@ dependencies = [ [[package]] name = "designcraft-format" -version = "0.11.0" +version = "0.12.0" dependencies = [ "designcraft-doc", "designcraft-images", @@ -1099,7 +1099,7 @@ dependencies = [ [[package]] name = "designcraft-geom" -version = "0.11.0" +version = "0.12.0" dependencies = [ "flo_curves", "kurbo", @@ -1112,7 +1112,7 @@ dependencies = [ [[package]] name = "designcraft-idml" -version = "0.11.0" +version = "0.12.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1127,7 +1127,7 @@ dependencies = [ [[package]] name = "designcraft-images" -version = "0.11.0" +version = "0.12.0" dependencies = [ "craft-cms", "designcraft-color", @@ -1142,7 +1142,7 @@ dependencies = [ [[package]] name = "designcraft-mcp" -version = "0.11.0" +version = "0.12.0" dependencies = [ "designcraft-engine", "designcraft-geom", @@ -1155,7 +1155,7 @@ dependencies = [ [[package]] name = "designcraft-pdf" -version = "0.11.0" +version = "0.12.0" dependencies = [ "chrono", "craft-pdf", @@ -1178,7 +1178,7 @@ dependencies = [ [[package]] name = "designcraft-pptx" -version = "0.11.0" +version = "0.12.0" dependencies = [ "chrono", "designcraft-color", @@ -1196,7 +1196,7 @@ dependencies = [ [[package]] name = "designcraft-render" -version = "0.11.0" +version = "0.12.0" dependencies = [ "craft-pdf", "designcraft-color", @@ -1215,7 +1215,7 @@ dependencies = [ [[package]] name = "designcraft-textimport" -version = "0.11.0" +version = "0.12.0" dependencies = [ "designcraft-doc", "quick-xml", @@ -1224,7 +1224,7 @@ dependencies = [ [[package]] name = "designcraft-tools" -version = "0.11.0" +version = "0.12.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1236,7 +1236,7 @@ dependencies = [ [[package]] name = "designcraft-ui-egui" -version = "0.11.0" +version = "0.12.0" dependencies = [ "craft-ui", "designcraft-color", @@ -1263,7 +1263,7 @@ dependencies = [ [[package]] name = "designcraft-web" -version = "0.11.0" +version = "0.12.0" dependencies = [ "designcraft-engine", "designcraft-format", @@ -5814,7 +5814,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.11.0" +version = "0.12.0" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index 0e728e87f..bc5982898 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/designcraft", "apps/designcraft-cli", "xtask"] [workspace.package] -version = "0.11.0" +version = "0.12.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 079b5bea820291d6f219fb5db2cf3f967481ff69 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 22 Oct 2026 23:31:37 +0000 Subject: [PATCH 22/29] CI: dev profile keeps line tables only --- Cargo.toml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index bc5982898..8a83e0463 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -103,11 +103,16 @@ todo = "warn" too_many_arguments = "allow" type_complexity = "allow" +# Line tables keep file and line in panics and backtraces; full debug info +# for every test binary and dependency would multiply the target dir size. +# The test profile inherits both settings. [profile.dev.package."*"] opt-level = 2 +debug = false [profile.dev] opt-level = 1 +debug = "line-tables-only" [profile.release] opt-level = 3 From 40e86d48a521d15d80f370705e13f9362c8bfb00 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 22 Oct 2026 23:35:30 +0000 Subject: [PATCH 23/29] CI: xtask runs tests with nextest, doctests apart, wasm in one check --- xtask/src/main.rs | 71 ++++++++++++++++++++++++++++++++--------------- 1 file changed, 49 insertions(+), 22 deletions(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index e730feb51..5000860cc 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -12,7 +12,7 @@ mod stats; mod version; use std::path::{Path, PathBuf}; -use std::process::{Command, ExitCode}; +use std::process::{Command, ExitCode, Stdio}; const USAGE: &str = "\ usage: cargo xtask @@ -21,8 +21,10 @@ commands: assets check that every icon/image/font/asset is attributed in ASSETS.md layers enforce the crate dependency layering (plan/architecture.md §3) pdf-deps verify the pinned PDF backend, including Krilla dependencies - wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates - ci fmt --check, clippy -D warnings, test, assets, layers, wasm (stops at first failure) + wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates (one call) + test workspace tests (cargo nextest when installed, else cargo test), then doctests + ci fmt --check, pdf-deps, clippy -D warnings, test, doctest, assets, layers, wasm + (stops at first failure) corpus [--download] show where test corpora live; --download fetches PngSuite into corpus/pngsuite stats [--exact] count tests and lines per crate (--exact: ask the test harness via `-- --list`) @@ -39,6 +41,7 @@ fn main() -> ExitCode { Some("layers") => cmd_layers(), Some("pdf-deps") => pdf_deps::run(&root()), Some("wasm") => cmd_wasm(), + Some("test") => cmd_test().and_then(|()| cmd_doctest()), Some("ci") => cmd_ci(), Some("corpus") => cmd_corpus(rest.contains(&"--download")), Some("stats") => stats::run(&root(), rest.contains(&"--exact")), @@ -134,21 +137,51 @@ fn wasm_set() -> Result, String> { .collect()) } +/// One `cargo check` for the whole set: each crate is checked once, and +/// `--keep-going` still reports every failing crate. Features unify across the +/// set, so each crate is checked with the union of the features the set enables. fn cmd_wasm() -> Result<(), String> { let set = wasm_set()?; - let mut results = Vec::new(); + if set.is_empty() { + return Err("no wasm-safe crates found in the workspace metadata".into()); + } + let mut c = cargo(); + c.args(["check", "--target", "wasm32-unknown-unknown", "--keep-going"]); for pkg in &set { - let mut c = cargo(); - c.args(["check", "--target", "wasm32-unknown-unknown", "-p", pkg]); - let ok = run(c, &format!("cargo check --target wasm32-unknown-unknown -p {pkg}")).is_ok(); - results.push((pkg.clone(), ok)); + c.args(["-p", pkg]); } - println!("\nwasm32-unknown-unknown check:"); - for (p, ok) in &results { - println!(" {:<6} {p}", if *ok { "ok" } else { "FAIL" }); - } - let failed = results.iter().filter(|r| !r.1).count(); - if failed == 0 { Ok(()) } else { Err(format!("{failed} crate(s) failed the wasm check")) } + run(c, &format!("cargo check --target wasm32-unknown-unknown --keep-going -p {}", set.join(" -p ")))?; + println!("\nwasm32-unknown-unknown check: ok ({} crates: {})", set.len(), set.join(", ")); + Ok(()) +} + +/// Test targets for the test build. Examples are left out so they aren't +/// linked; clippy `--all-targets` still compiles them. +const TEST_TARGETS: [&str; 4] = ["--workspace", "--lib", "--bins", "--tests"]; + +fn nextest_available() -> bool { + cargo().args(["nextest", "--version"]).stdout(Stdio::null()).stderr(Stdio::null()).status().is_ok_and(|s| s.success()) +} + +fn cmd_test() -> Result<(), String> { + let mut c = cargo(); + let tool = if nextest_available() { + c.args(["nextest", "run"]); + "nextest run" + } else { + eprintln!("note: cargo-nextest is not installed, running cargo test (cargo install cargo-nextest --locked)"); + c.arg("test"); + "test" + }; + c.args(TEST_TARGETS); + run(c, &format!("cargo {tool} {}", TEST_TARGETS.join(" "))) +} + +/// nextest does not run doctests. +fn cmd_doctest() -> Result<(), String> { + let mut c = cargo(); + c.args(["test", "--workspace", "--doc"]); + run(c, "cargo test --workspace --doc") } fn cmd_ci() -> Result<(), String> { @@ -171,14 +204,8 @@ fn cmd_ci() -> Result<(), String> { run(c, "cargo clippy --workspace --all-targets -- -D warnings") }), ), - ( - "test", - Box::new(|| { - let mut c = cargo(); - c.args(["test", "--workspace"]); - run(c, "cargo test --workspace") - }), - ), + ("test", Box::new(cmd_test)), + ("doctest", Box::new(cmd_doctest)), ("assets", Box::new(|| assets::run(&root()))), ("layers", Box::new(cmd_layers)), ("wasm", Box::new(cmd_wasm)), From 3ee11391aec7434d318654369a7b7b276882f668 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 22 Oct 2026 23:39:10 +0000 Subject: [PATCH 24/29] CI: one integration-test binary per crate --- ASSETS.md | 12 +++++----- apps/designcraft-cli/tests/{ => it}/cli.rs | 0 apps/designcraft-cli/tests/it/main.rs | 1 + crates/engine/tests/{ => it}/book_safety.rs | 2 -- crates/engine/tests/{ => it}/browser_print.rs | 1 - .../character_style_from_selection.rs | 0 .../engine/tests/{ => it}/close_retention.rs | 0 .../{ => it}/collection_state_atomicity.rs | 2 -- .../tests/{ => it}/combined_close_glyph.rs | 0 .../engine/tests/{ => it}/distribute_locks.rs | 0 .../tests/{ => it}/export_page_input.rs | 0 .../tests/{ => it}/insert_pages_bounds.rs | 0 crates/engine/tests/it/main.rs | 23 +++++++++++++++++++ crates/engine/tests/{ => it}/param_keys.rs | 0 crates/engine/tests/{ => it}/pdf_backend.rs | 0 .../tests/{ => it}/preflight_resolution.rs | 0 .../tests/{ => it}/primary_frame_columns.rs | 0 .../tests/{ => it}/save_state_atomicity.rs | 2 -- .../tests/{ => it}/stroke_tint_range.rs | 0 .../engine/tests/{ => it}/text_decorations.rs | 0 .../tests/{ => it}/text_insert_memory.rs | 0 .../tests/{ => it}/text_thread_regressions.rs | 0 .../tests/{ => it}/thread_color_safety.rs | 0 .../epub/tests/{ => it}/export_tag_styles.rs | 0 .../tests/{ => it}/grouped_reading_order.rs | 0 crates/epub/tests/it/main.rs | 2 ++ crates/fonts/tests/it/main.rs | 4 ++++ crates/fonts/tests/{ => it}/system_fonts.rs | 2 -- crates/images/tests/it/main.rs | 1 + .../{ => it}/rgba_conversion_contract.rs | 0 crates/mcp/tests/{ => it}/automation_roots.rs | 2 -- crates/mcp/tests/it/main.rs | 4 ++++ crates/pdf/tests/image_content_cache.rs | 5 ---- .../tests/{ => it}/gradient_color_spaces.rs | 2 +- crates/pdf/tests/it/image_content_cache.rs | 3 +++ crates/pdf/tests/it/main.rs | 6 +++++ .../{ => it}/page_entry_search_contract.rs | 0 .../render/tests/{ => it}/blend_over_paper.rs | 0 crates/render/tests/{ => it}/colorize.rs | 0 crates/render/tests/{ => it}/effects.rs | 2 +- .../render/tests/{ => it}/glyph_retention.rs | 0 crates/render/tests/{ => it}/gradient_inks.rs | 0 crates/render/tests/{ => it}/gradients.rs | 0 crates/render/tests/it/main.rs | 12 ++++++++++ crates/render/tests/{ => it}/pdf_geometry.rs | 0 crates/render/tests/{ => it}/perf.rs | 2 +- crates/render/tests/{ => it}/placed_pdf.rs | 0 .../render/tests/{ => it}/stroke_alignment.rs | 0 .../tests/{ => it}/text_frame_bottom.rs | 0 .../tests/{ => it}/text_stroke_behind.rs | 0 crates/ui-egui/tests/it/main.rs | 2 ++ .../{ => it}/native_job_lifetime_control.rs | 1 - 52 files changed, 67 insertions(+), 26 deletions(-) rename apps/designcraft-cli/tests/{ => it}/cli.rs (100%) create mode 100644 apps/designcraft-cli/tests/it/main.rs rename crates/engine/tests/{ => it}/book_safety.rs (99%) rename crates/engine/tests/{ => it}/browser_print.rs (97%) rename crates/engine/tests/{ => it}/character_style_from_selection.rs (100%) rename crates/engine/tests/{ => it}/close_retention.rs (100%) rename crates/engine/tests/{ => it}/collection_state_atomicity.rs (98%) rename crates/engine/tests/{ => it}/combined_close_glyph.rs (100%) rename crates/engine/tests/{ => it}/distribute_locks.rs (100%) rename crates/engine/tests/{ => it}/export_page_input.rs (100%) rename crates/engine/tests/{ => it}/insert_pages_bounds.rs (100%) create mode 100644 crates/engine/tests/it/main.rs rename crates/engine/tests/{ => it}/param_keys.rs (100%) rename crates/engine/tests/{ => it}/pdf_backend.rs (100%) rename crates/engine/tests/{ => it}/preflight_resolution.rs (100%) rename crates/engine/tests/{ => it}/primary_frame_columns.rs (100%) rename crates/engine/tests/{ => it}/save_state_atomicity.rs (98%) rename crates/engine/tests/{ => it}/stroke_tint_range.rs (100%) rename crates/engine/tests/{ => it}/text_decorations.rs (100%) rename crates/engine/tests/{ => it}/text_insert_memory.rs (100%) rename crates/engine/tests/{ => it}/text_thread_regressions.rs (100%) rename crates/engine/tests/{ => it}/thread_color_safety.rs (100%) rename crates/epub/tests/{ => it}/export_tag_styles.rs (100%) rename crates/epub/tests/{ => it}/grouped_reading_order.rs (100%) create mode 100644 crates/epub/tests/it/main.rs create mode 100644 crates/fonts/tests/it/main.rs rename crates/fonts/tests/{ => it}/system_fonts.rs (86%) create mode 100644 crates/images/tests/it/main.rs rename crates/images/tests/{ => it}/rgba_conversion_contract.rs (100%) rename crates/mcp/tests/{ => it}/automation_roots.rs (99%) create mode 100644 crates/mcp/tests/it/main.rs delete mode 100644 crates/pdf/tests/image_content_cache.rs rename crates/pdf/tests/{ => it}/gradient_color_spaces.rs (98%) create mode 100644 crates/pdf/tests/it/image_content_cache.rs create mode 100644 crates/pdf/tests/it/main.rs rename crates/pdf/tests/{ => it}/page_entry_search_contract.rs (100%) rename crates/render/tests/{ => it}/blend_over_paper.rs (100%) rename crates/render/tests/{ => it}/colorize.rs (100%) rename crates/render/tests/{ => it}/effects.rs (99%) rename crates/render/tests/{ => it}/glyph_retention.rs (100%) rename crates/render/tests/{ => it}/gradient_inks.rs (100%) rename crates/render/tests/{ => it}/gradients.rs (100%) create mode 100644 crates/render/tests/it/main.rs rename crates/render/tests/{ => it}/pdf_geometry.rs (100%) rename crates/render/tests/{ => it}/perf.rs (98%) rename crates/render/tests/{ => it}/placed_pdf.rs (100%) rename crates/render/tests/{ => it}/stroke_alignment.rs (100%) rename crates/render/tests/{ => it}/text_frame_bottom.rs (100%) rename crates/render/tests/{ => it}/text_stroke_behind.rs (100%) create mode 100644 crates/ui-egui/tests/it/main.rs rename crates/ui-egui/tests/{ => it}/native_job_lifetime_control.rs (98%) diff --git a/ASSETS.md b/ASSETS.md index 40e8a97b4..407a26c92 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -40,12 +40,12 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra | `docs/images/page-4.png` | DesignCraft contributors | screenshot/render of DesignCraft itself (sample document generated in code) | MIT OR Apache-2.0 | Original; no Adobe UI | | `docs/images/page-cover.png` | DesignCraft contributors | screenshot/render of DesignCraft itself (sample document generated in code) | MIT OR Apache-2.0 | Original; no Adobe UI | | `docs/images/ui-spread.png` | DesignCraft contributors | screenshot/render of DesignCraft itself (sample document generated in code) | MIT OR Apache-2.0 | Original; no Adobe UI | -| `crates/render/tests/golden/drop-shadow-spread.png` | DesignCraft contributors (generated) | rendered by DesignCraft's own renderer (`crates/render/tests/effects.rs`, synthetic shapes and bundled fonts) | MIT OR Apache-2.0 | Golden test image for soft effects | -| `crates/render/tests/golden/drop-shadow-text.png` | DesignCraft contributors (generated) | rendered by DesignCraft's own renderer (`crates/render/tests/effects.rs`, synthetic shapes and bundled fonts) | MIT OR Apache-2.0 | Golden test image for soft effects | -| `crates/render/tests/golden/drop-shadow.png` | DesignCraft contributors (generated) | rendered by DesignCraft's own renderer (`crates/render/tests/effects.rs`, synthetic shapes and bundled fonts) | MIT OR Apache-2.0 | Golden test image for soft effects | -| `crates/render/tests/golden/feather.png` | DesignCraft contributors (generated) | rendered by DesignCraft's own renderer (`crates/render/tests/effects.rs`, synthetic shapes and bundled fonts) | MIT OR Apache-2.0 | Golden test image for soft effects | -| `crates/render/tests/golden/inner-shadow.png` | DesignCraft contributors (generated) | rendered by DesignCraft's own renderer (`crates/render/tests/effects.rs`, synthetic shapes and bundled fonts) | MIT OR Apache-2.0 | Golden test image for soft effects | -| `crates/render/tests/golden/outer-glow.png` | DesignCraft contributors (generated) | rendered by DesignCraft's own renderer (`crates/render/tests/effects.rs`, synthetic shapes and bundled fonts) | MIT OR Apache-2.0 | Golden test image for soft effects | +| `crates/render/tests/golden/drop-shadow-spread.png` | DesignCraft contributors (generated) | rendered by DesignCraft's own renderer (`crates/render/tests/it/effects.rs`, synthetic shapes and bundled fonts) | MIT OR Apache-2.0 | Golden test image for soft effects | +| `crates/render/tests/golden/drop-shadow-text.png` | DesignCraft contributors (generated) | rendered by DesignCraft's own renderer (`crates/render/tests/it/effects.rs`, synthetic shapes and bundled fonts) | MIT OR Apache-2.0 | Golden test image for soft effects | +| `crates/render/tests/golden/drop-shadow.png` | DesignCraft contributors (generated) | rendered by DesignCraft's own renderer (`crates/render/tests/it/effects.rs`, synthetic shapes and bundled fonts) | MIT OR Apache-2.0 | Golden test image for soft effects | +| `crates/render/tests/golden/feather.png` | DesignCraft contributors (generated) | rendered by DesignCraft's own renderer (`crates/render/tests/it/effects.rs`, synthetic shapes and bundled fonts) | MIT OR Apache-2.0 | Golden test image for soft effects | +| `crates/render/tests/golden/inner-shadow.png` | DesignCraft contributors (generated) | rendered by DesignCraft's own renderer (`crates/render/tests/it/effects.rs`, synthetic shapes and bundled fonts) | MIT OR Apache-2.0 | Golden test image for soft effects | +| `crates/render/tests/golden/outer-glow.png` | DesignCraft contributors (generated) | rendered by DesignCraft's own renderer (`crates/render/tests/it/effects.rs`, synthetic shapes and bundled fonts) | MIT OR Apache-2.0 | Golden test image for soft effects | | `assets/app-icon/LICENSE.txt` | (licence text) | this project | — | Licence for the app icon | | `assets/app-icon/designcraft-1024.png` | DesignCraft project owner (drawn in ArtCraft) | rendered from `assets/app-icon/designcraft.svg` by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon: calico cat in a polka-dot scarf (see `assets/app-icon/README.md`) | | `assets/app-icon/designcraft-macos-512.png` | DesignCraft project owner (drawn in ArtCraft) | rendered from `assets/app-icon/designcraft.svg` by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon: calico cat in a polka-dot scarf (see `assets/app-icon/README.md`) | diff --git a/apps/designcraft-cli/tests/cli.rs b/apps/designcraft-cli/tests/it/cli.rs similarity index 100% rename from apps/designcraft-cli/tests/cli.rs rename to apps/designcraft-cli/tests/it/cli.rs diff --git a/apps/designcraft-cli/tests/it/main.rs b/apps/designcraft-cli/tests/it/main.rs new file mode 100644 index 000000000..26710c101 --- /dev/null +++ b/apps/designcraft-cli/tests/it/main.rs @@ -0,0 +1 @@ +mod cli; diff --git a/crates/engine/tests/book_safety.rs b/crates/engine/tests/it/book_safety.rs similarity index 99% rename from crates/engine/tests/book_safety.rs rename to crates/engine/tests/it/book_safety.rs index 74c96815a..01c527be5 100644 --- a/crates/engine/tests/book_safety.rs +++ b/crates/engine/tests/it/book_safety.rs @@ -1,5 +1,3 @@ -#![cfg(not(target_arch = "wasm32"))] - use designcraft_engine::Session; use serde_json::json; use std::path::Path; diff --git a/crates/engine/tests/browser_print.rs b/crates/engine/tests/it/browser_print.rs similarity index 97% rename from crates/engine/tests/browser_print.rs rename to crates/engine/tests/it/browser_print.rs index fda224b90..208a6cde8 100644 --- a/crates/engine/tests/browser_print.rs +++ b/crates/engine/tests/it/browser_print.rs @@ -1,5 +1,4 @@ //! Browser Print must reject native spooler operations without trapping the editor. -#![cfg(target_arch = "wasm32")] use designcraft_engine::Session; use serde_json::json; diff --git a/crates/engine/tests/character_style_from_selection.rs b/crates/engine/tests/it/character_style_from_selection.rs similarity index 100% rename from crates/engine/tests/character_style_from_selection.rs rename to crates/engine/tests/it/character_style_from_selection.rs diff --git a/crates/engine/tests/close_retention.rs b/crates/engine/tests/it/close_retention.rs similarity index 100% rename from crates/engine/tests/close_retention.rs rename to crates/engine/tests/it/close_retention.rs diff --git a/crates/engine/tests/collection_state_atomicity.rs b/crates/engine/tests/it/collection_state_atomicity.rs similarity index 98% rename from crates/engine/tests/collection_state_atomicity.rs rename to crates/engine/tests/it/collection_state_atomicity.rs index b73eefa7e..cb6a0db94 100644 --- a/crates/engine/tests/collection_state_atomicity.rs +++ b/crates/engine/tests/it/collection_state_atomicity.rs @@ -1,5 +1,3 @@ -#![cfg(not(target_arch = "wasm32"))] - use designcraft_engine::Session; use serde_json::json; diff --git a/crates/engine/tests/combined_close_glyph.rs b/crates/engine/tests/it/combined_close_glyph.rs similarity index 100% rename from crates/engine/tests/combined_close_glyph.rs rename to crates/engine/tests/it/combined_close_glyph.rs diff --git a/crates/engine/tests/distribute_locks.rs b/crates/engine/tests/it/distribute_locks.rs similarity index 100% rename from crates/engine/tests/distribute_locks.rs rename to crates/engine/tests/it/distribute_locks.rs diff --git a/crates/engine/tests/export_page_input.rs b/crates/engine/tests/it/export_page_input.rs similarity index 100% rename from crates/engine/tests/export_page_input.rs rename to crates/engine/tests/it/export_page_input.rs diff --git a/crates/engine/tests/insert_pages_bounds.rs b/crates/engine/tests/it/insert_pages_bounds.rs similarity index 100% rename from crates/engine/tests/insert_pages_bounds.rs rename to crates/engine/tests/it/insert_pages_bounds.rs diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs new file mode 100644 index 000000000..14555d3ee --- /dev/null +++ b/crates/engine/tests/it/main.rs @@ -0,0 +1,23 @@ +#[cfg(not(target_arch = "wasm32"))] +mod book_safety; +#[cfg(target_arch = "wasm32")] +mod browser_print; +mod character_style_from_selection; +mod close_retention; +#[cfg(not(target_arch = "wasm32"))] +mod collection_state_atomicity; +mod combined_close_glyph; +mod distribute_locks; +mod export_page_input; +mod insert_pages_bounds; +mod param_keys; +mod pdf_backend; +mod preflight_resolution; +mod primary_frame_columns; +#[cfg(not(target_arch = "wasm32"))] +mod save_state_atomicity; +mod stroke_tint_range; +mod text_decorations; +mod text_insert_memory; +mod text_thread_regressions; +mod thread_color_safety; diff --git a/crates/engine/tests/param_keys.rs b/crates/engine/tests/it/param_keys.rs similarity index 100% rename from crates/engine/tests/param_keys.rs rename to crates/engine/tests/it/param_keys.rs diff --git a/crates/engine/tests/pdf_backend.rs b/crates/engine/tests/it/pdf_backend.rs similarity index 100% rename from crates/engine/tests/pdf_backend.rs rename to crates/engine/tests/it/pdf_backend.rs diff --git a/crates/engine/tests/preflight_resolution.rs b/crates/engine/tests/it/preflight_resolution.rs similarity index 100% rename from crates/engine/tests/preflight_resolution.rs rename to crates/engine/tests/it/preflight_resolution.rs diff --git a/crates/engine/tests/primary_frame_columns.rs b/crates/engine/tests/it/primary_frame_columns.rs similarity index 100% rename from crates/engine/tests/primary_frame_columns.rs rename to crates/engine/tests/it/primary_frame_columns.rs diff --git a/crates/engine/tests/save_state_atomicity.rs b/crates/engine/tests/it/save_state_atomicity.rs similarity index 98% rename from crates/engine/tests/save_state_atomicity.rs rename to crates/engine/tests/it/save_state_atomicity.rs index ac0f30f58..2ced20ef0 100644 --- a/crates/engine/tests/save_state_atomicity.rs +++ b/crates/engine/tests/it/save_state_atomicity.rs @@ -1,5 +1,3 @@ -#![cfg(not(target_arch = "wasm32"))] - use std::path::Path; use std::sync::Arc; diff --git a/crates/engine/tests/stroke_tint_range.rs b/crates/engine/tests/it/stroke_tint_range.rs similarity index 100% rename from crates/engine/tests/stroke_tint_range.rs rename to crates/engine/tests/it/stroke_tint_range.rs diff --git a/crates/engine/tests/text_decorations.rs b/crates/engine/tests/it/text_decorations.rs similarity index 100% rename from crates/engine/tests/text_decorations.rs rename to crates/engine/tests/it/text_decorations.rs diff --git a/crates/engine/tests/text_insert_memory.rs b/crates/engine/tests/it/text_insert_memory.rs similarity index 100% rename from crates/engine/tests/text_insert_memory.rs rename to crates/engine/tests/it/text_insert_memory.rs diff --git a/crates/engine/tests/text_thread_regressions.rs b/crates/engine/tests/it/text_thread_regressions.rs similarity index 100% rename from crates/engine/tests/text_thread_regressions.rs rename to crates/engine/tests/it/text_thread_regressions.rs diff --git a/crates/engine/tests/thread_color_safety.rs b/crates/engine/tests/it/thread_color_safety.rs similarity index 100% rename from crates/engine/tests/thread_color_safety.rs rename to crates/engine/tests/it/thread_color_safety.rs diff --git a/crates/epub/tests/export_tag_styles.rs b/crates/epub/tests/it/export_tag_styles.rs similarity index 100% rename from crates/epub/tests/export_tag_styles.rs rename to crates/epub/tests/it/export_tag_styles.rs diff --git a/crates/epub/tests/grouped_reading_order.rs b/crates/epub/tests/it/grouped_reading_order.rs similarity index 100% rename from crates/epub/tests/grouped_reading_order.rs rename to crates/epub/tests/it/grouped_reading_order.rs diff --git a/crates/epub/tests/it/main.rs b/crates/epub/tests/it/main.rs new file mode 100644 index 000000000..69af15eaa --- /dev/null +++ b/crates/epub/tests/it/main.rs @@ -0,0 +1,2 @@ +mod export_tag_styles; +mod grouped_reading_order; diff --git a/crates/fonts/tests/it/main.rs b/crates/fonts/tests/it/main.rs new file mode 100644 index 000000000..1737c00b9 --- /dev/null +++ b/crates/fonts/tests/it/main.rs @@ -0,0 +1,4 @@ +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod system_fonts; diff --git a/crates/fonts/tests/system_fonts.rs b/crates/fonts/tests/it/system_fonts.rs similarity index 86% rename from crates/fonts/tests/system_fonts.rs rename to crates/fonts/tests/it/system_fonts.rs index 62310c34b..66db0f5b1 100644 --- a/crates/fonts/tests/system_fonts.rs +++ b/crates/fonts/tests/it/system_fonts.rs @@ -1,7 +1,5 @@ //! A new session finds the installed system fonts by family name (#22). One test in its own //! process, so the process-wide database starts fresh, as it does when the app starts. -// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use designcraft_fonts::{FontDb, system_font_dirs}; diff --git a/crates/images/tests/it/main.rs b/crates/images/tests/it/main.rs new file mode 100644 index 000000000..d2f76fb71 --- /dev/null +++ b/crates/images/tests/it/main.rs @@ -0,0 +1 @@ +mod rgba_conversion_contract; diff --git a/crates/images/tests/rgba_conversion_contract.rs b/crates/images/tests/it/rgba_conversion_contract.rs similarity index 100% rename from crates/images/tests/rgba_conversion_contract.rs rename to crates/images/tests/it/rgba_conversion_contract.rs diff --git a/crates/mcp/tests/automation_roots.rs b/crates/mcp/tests/it/automation_roots.rs similarity index 99% rename from crates/mcp/tests/automation_roots.rs rename to crates/mcp/tests/it/automation_roots.rs index 9380b1987..871945920 100644 --- a/crates/mcp/tests/automation_roots.rs +++ b/crates/mcp/tests/it/automation_roots.rs @@ -3,8 +3,6 @@ //! goes inside the write root. Paths that leave a root (`..`, another folder, a sibling with the //! same prefix, a link) are refused, nothing from a refused file reaches the document, and nothing //! is written outside. -// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md). -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use std::path::{Path, PathBuf}; diff --git a/crates/mcp/tests/it/main.rs b/crates/mcp/tests/it/main.rs new file mode 100644 index 000000000..be744719e --- /dev/null +++ b/crates/mcp/tests/it/main.rs @@ -0,0 +1,4 @@ +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod automation_roots; diff --git a/crates/pdf/tests/image_content_cache.rs b/crates/pdf/tests/image_content_cache.rs deleted file mode 100644 index dd3d413d0..000000000 --- a/crates/pdf/tests/image_content_cache.rs +++ /dev/null @@ -1,5 +0,0 @@ -//! Run public contracts with the production content-cache hasher. -#[path = "support/image_content_cache_contract.rs"] -mod contracts; -#[path = "support/image_fixtures.rs"] -mod image_fixtures; diff --git a/crates/pdf/tests/gradient_color_spaces.rs b/crates/pdf/tests/it/gradient_color_spaces.rs similarity index 98% rename from crates/pdf/tests/gradient_color_spaces.rs rename to crates/pdf/tests/it/gradient_color_spaces.rs index 05806a120..d906413e1 100644 --- a/crates/pdf/tests/gradient_color_spaces.rs +++ b/crates/pdf/tests/it/gradient_color_spaces.rs @@ -42,7 +42,7 @@ fn mixed_gradient_export_survives_in_subprocess() { const CHILD: &str = "DESIGNCRAFT_TEST_MIXED_GRADIENT_CHILD"; if std::env::var_os(CHILD).is_none() { let out = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "mixed_gradient_export_survives_in_subprocess", "--nocapture"]) + .args(["--exact", "gradient_color_spaces::mixed_gradient_export_survives_in_subprocess", "--nocapture"]) .env(CHILD, "1") .output() .unwrap(); diff --git a/crates/pdf/tests/it/image_content_cache.rs b/crates/pdf/tests/it/image_content_cache.rs new file mode 100644 index 000000000..ec0f666c0 --- /dev/null +++ b/crates/pdf/tests/it/image_content_cache.rs @@ -0,0 +1,3 @@ +//! Run public contracts with the production content-cache hasher. +#[path = "../support/image_content_cache_contract.rs"] +mod contracts; diff --git a/crates/pdf/tests/it/main.rs b/crates/pdf/tests/it/main.rs new file mode 100644 index 000000000..e2e092e2f --- /dev/null +++ b/crates/pdf/tests/it/main.rs @@ -0,0 +1,6 @@ +#[path = "../support/image_fixtures.rs"] +mod image_fixtures; + +mod gradient_color_spaces; +mod image_content_cache; +mod page_entry_search_contract; diff --git a/crates/pdf/tests/page_entry_search_contract.rs b/crates/pdf/tests/it/page_entry_search_contract.rs similarity index 100% rename from crates/pdf/tests/page_entry_search_contract.rs rename to crates/pdf/tests/it/page_entry_search_contract.rs diff --git a/crates/render/tests/blend_over_paper.rs b/crates/render/tests/it/blend_over_paper.rs similarity index 100% rename from crates/render/tests/blend_over_paper.rs rename to crates/render/tests/it/blend_over_paper.rs diff --git a/crates/render/tests/colorize.rs b/crates/render/tests/it/colorize.rs similarity index 100% rename from crates/render/tests/colorize.rs rename to crates/render/tests/it/colorize.rs diff --git a/crates/render/tests/effects.rs b/crates/render/tests/it/effects.rs similarity index 99% rename from crates/render/tests/effects.rs rename to crates/render/tests/it/effects.rs index a9420fbcb..230913173 100644 --- a/crates/render/tests/effects.rs +++ b/crates/render/tests/it/effects.rs @@ -3,7 +3,7 @@ //! //! Goldens live in `tests/golden/*.png` and are compared with a tolerance (antialiasing and blur //! rounding may differ by a few levels between SIMD levels). Regenerate them after an intended -//! change with `DESIGNCRAFT_BLESS=1 cargo test -p designcraft-render --test effects`. +//! change with `DESIGNCRAFT_BLESS=1 cargo test -p designcraft-render --test it effects::`. use designcraft_compose::Cache; use designcraft_doc::build::NewDocument; diff --git a/crates/render/tests/glyph_retention.rs b/crates/render/tests/it/glyph_retention.rs similarity index 100% rename from crates/render/tests/glyph_retention.rs rename to crates/render/tests/it/glyph_retention.rs diff --git a/crates/render/tests/gradient_inks.rs b/crates/render/tests/it/gradient_inks.rs similarity index 100% rename from crates/render/tests/gradient_inks.rs rename to crates/render/tests/it/gradient_inks.rs diff --git a/crates/render/tests/gradients.rs b/crates/render/tests/it/gradients.rs similarity index 100% rename from crates/render/tests/gradients.rs rename to crates/render/tests/it/gradients.rs diff --git a/crates/render/tests/it/main.rs b/crates/render/tests/it/main.rs new file mode 100644 index 000000000..52000ae2d --- /dev/null +++ b/crates/render/tests/it/main.rs @@ -0,0 +1,12 @@ +mod blend_over_paper; +mod colorize; +mod effects; +mod glyph_retention; +mod gradient_inks; +mod gradients; +mod pdf_geometry; +mod perf; +mod placed_pdf; +mod stroke_alignment; +mod text_frame_bottom; +mod text_stroke_behind; diff --git a/crates/render/tests/pdf_geometry.rs b/crates/render/tests/it/pdf_geometry.rs similarity index 100% rename from crates/render/tests/pdf_geometry.rs rename to crates/render/tests/it/pdf_geometry.rs diff --git a/crates/render/tests/perf.rs b/crates/render/tests/it/perf.rs similarity index 98% rename from crates/render/tests/perf.rs rename to crates/render/tests/it/perf.rs index 1f23f88f4..46f33ab62 100644 --- a/crates/render/tests/perf.rs +++ b/crates/render/tests/it/perf.rs @@ -1,6 +1,6 @@ //! Renderer caching/culling behaviour, and a render-time regression test (`#[ignore]`: wall-clock //! timings are only meaningful on an idle machine — run with -//! `cargo test --release -p designcraft-render --test perf -- --ignored`). +//! `cargo test --release -p designcraft-render --test it perf:: -- --ignored`). use std::time::Instant; diff --git a/crates/render/tests/placed_pdf.rs b/crates/render/tests/it/placed_pdf.rs similarity index 100% rename from crates/render/tests/placed_pdf.rs rename to crates/render/tests/it/placed_pdf.rs diff --git a/crates/render/tests/stroke_alignment.rs b/crates/render/tests/it/stroke_alignment.rs similarity index 100% rename from crates/render/tests/stroke_alignment.rs rename to crates/render/tests/it/stroke_alignment.rs diff --git a/crates/render/tests/text_frame_bottom.rs b/crates/render/tests/it/text_frame_bottom.rs similarity index 100% rename from crates/render/tests/text_frame_bottom.rs rename to crates/render/tests/it/text_frame_bottom.rs diff --git a/crates/render/tests/text_stroke_behind.rs b/crates/render/tests/it/text_stroke_behind.rs similarity index 100% rename from crates/render/tests/text_stroke_behind.rs rename to crates/render/tests/it/text_stroke_behind.rs diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs new file mode 100644 index 000000000..2d07c9629 --- /dev/null +++ b/crates/ui-egui/tests/it/main.rs @@ -0,0 +1,2 @@ +#[cfg(not(target_arch = "wasm32"))] +mod native_job_lifetime_control; diff --git a/crates/ui-egui/tests/native_job_lifetime_control.rs b/crates/ui-egui/tests/it/native_job_lifetime_control.rs similarity index 98% rename from crates/ui-egui/tests/native_job_lifetime_control.rs rename to crates/ui-egui/tests/it/native_job_lifetime_control.rs index 2cf82e5bd..b7fa87214 100644 --- a/crates/ui-egui/tests/native_job_lifetime_control.rs +++ b/crates/ui-egui/tests/it/native_job_lifetime_control.rs @@ -1,5 +1,4 @@ //! Own a real native Job across last close. This does not run the asynchronous worker. -#![cfg(not(target_arch = "wasm32"))] use std::sync::Arc; From 0fd6e06ad6a7921c0d5df08b3d45434910827d52 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 23 Oct 2026 01:17:55 +0000 Subject: [PATCH 25/29] CI: install nextest for the test step --- .github/workflows/ci.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 72bac7ef7..c27fdfe10 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -57,6 +57,10 @@ jobs: --target wasm32-unknown-unknown rustup default stable + - uses: taiki-e/install-action@f7e5d7c961414b23f5b25b2da9294395d08513ad # v2.87.26 + with: + tool: cargo-nextest@0.9.145 + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: save-if: ${{ github.ref == 'refs/heads/main' }} From 62148670bd6ee3522c116cc1b78e2d6be0f16765 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 23 Oct 2026 02:54:21 +0000 Subject: [PATCH 26/29] CI: apt packages through craft-common-actions' cached install --- .github/workflows/ci.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c27fdfe10..d5b820d24 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -45,10 +45,10 @@ jobs: persist-credentials: false - name: Install Linux build dependencies - run: | - sudo apt-get update - sudo apt-get install -y --no-install-recommends \ - pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev \ + uses: storytold/craft-common-actions/actions/install-apt-packages@main + with: + packages: >- + pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers - name: Install Rust (stable + clippy, rustfmt, wasm32) From bd7fb76d4c6fdda501651df1674bc34dbffc6ec4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 23 Oct 2026 09:29:39 -0400 Subject: [PATCH 27/29] fix: annotate package output permissions (SonarCloud rust:S2612) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New packages are created with the ordinary 0666 request; the process umask decides the effective mode. Annotated with that reason so the analyzer's world-writable warning does not change the intended sharing behaviour. 🤖 Generated with Codebuff Co-Authored-By: Codebuff --- crates/engine/src/cmd/package.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index f2d33ccfa..d0ed58b03 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -135,8 +135,9 @@ impl OutputRoot { { use std::os::unix::fs::PermissionsExt; - // Match fs::write for a new output: 0666 restricted by the caller's umask. - builder.permissions(std::fs::Permissions::from_mode(0o666)); + // Like fs::write for a new output: request 0666 and let the process umask decide the + // effective mode (0644 with the usual 022, 0664 with 002). + builder.permissions(std::fs::Permissions::from_mode(0o666)); // NOSONAR } let file = builder.tempfile_in(parent).map_err(|e| path_error(path, e))?; #[cfg(unix)] From df1db1646b05f4e3f12ca88f3e0f1ed7c2df0164 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 23 Oct 2026 11:16:49 -0400 Subject: [PATCH 28/29] web: let the browser zoom the page (SonarCloud Web:S7926) (#1641) The viewport no longer sets user-scalable=no, so people who need to zoom the page can (WCAG 1.4.4). The canvas takes touch-action: none, so pinch and pan gestures on it still go to the app's own zoom, as eframe's touch handlers expect, instead of zooming the page. --- apps/designcraft-web/index.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/designcraft-web/index.html b/apps/designcraft-web/index.html index b05be3936..da7ccc5da 100644 --- a/apps/designcraft-web/index.html +++ b/apps/designcraft-web/index.html @@ -2,12 +2,12 @@ - + DesignCraft From 2e36dcf909627c8f0e5662fe6b4825b1c1c24420 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 23 Oct 2026 11:16:54 -0400 Subject: [PATCH 29/29] packaging: harden shell scripts (SonarCloud S7688/S7679/S7682/S131) (#1640) - Use bash's [[ ]] instead of [ ] for conditional tests (S7688). - Copy positional parameters into named locals in render(), has() and sha256() (S7679). - End the env.sh helper functions with an explicit return, which keeps the last command's status (S7682). - Give the appimagetool checksum case a default branch for architectures without a pinned download (S131). No behaviour change; shellcheck -x is clean. --- packaging/env.sh | 19 ++++++++++++------- packaging/freebsd/package.sh | 14 +++++++------- packaging/icons.sh | 5 ++++- packaging/linux/flatpak-bundle.sh | 8 ++++---- packaging/linux/package.sh | 23 ++++++++++++++--------- packaging/macos/import-cert.sh | 6 +++--- packaging/macos/package.sh | 24 ++++++++++++------------ packaging/web/package.sh | 4 ++-- 8 files changed, 58 insertions(+), 45 deletions(-) diff --git a/packaging/env.sh b/packaging/env.sh index 0eb58029b..55ff3943c 100644 --- a/packaging/env.sh +++ b/packaging/env.sh @@ -19,10 +19,11 @@ workspace_version() { /^\[/ { in_pkg = ($0 == "[workspace.package]") ; next } in_pkg && $1 == "version" { gsub(/[" ]/, "", $3); print $3; exit } ' "$ROOT/Cargo.toml" + return } VERSION="${DESIGNCRAFT_VERSION:-$(workspace_version)}" -if [ -z "$VERSION" ]; then +if [[ -z "$VERSION" ]]; then echo "error: could not read [workspace.package] version from $ROOT/Cargo.toml" >&2 exit 1 fi @@ -32,7 +33,7 @@ DIST="${DIST:-$ROOT/dist/release}" mkdir -p "$DIST" export DIST -if [ -z "${DESIGNCRAFT_BUILD_SHA:-}" ]; then +if [[ -z "${DESIGNCRAFT_BUILD_SHA:-}" ]]; then DESIGNCRAFT_BUILD_SHA="$(git -C "$ROOT" rev-parse HEAD 2>/dev/null || true)" fi export DESIGNCRAFT_BUILD_SHA @@ -41,29 +42,33 @@ export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$ROOT/target}" # Emit a GitHub Actions warning (plain stderr outside Actions). warn() { - if [ -n "${GITHUB_ACTIONS:-}" ]; then echo "::warning::$*"; else echo "warning: $*" >&2; fi + if [[ -n "${GITHUB_ACTIONS:-}" ]]; then echo "::warning::$*"; else echo "warning: $*" >&2; fi + return } # Copy licence and readme files that exist into a package directory. copy_docs() { local dest="$1" f for f in README.md LICENSE LICENSE-MIT LICENSE-APACHE COPYRIGHT; do - if [ -f "$ROOT/$f" ]; then cp "$ROOT/$f" "$dest/"; fi + if [[ -f "$ROOT/$f" ]]; then cp "$ROOT/$f" "$dest/"; fi done copy_font_licences "$dest" + return } # Builds made with craft-fonts (CRAFT_FONTS_DIR, set by the release workflow) embed its fonts, so # the package carries their licences as OFL-.txt. Nothing without CRAFT_FONTS_DIR. copy_font_licences() { local dest="$1" f - [ -n "${CRAFT_FONTS_DIR:-}" ] || return 0 + [[ -n "${CRAFT_FONTS_DIR:-}" ]] || return 0 for f in "$CRAFT_FONTS_DIR"/fonts/*/OFL.txt; do - if [ -f "$f" ]; then cp "$f" "$dest/OFL-$(basename "$(dirname "$f")").txt"; fi + if [[ -f "$f" ]]; then cp "$f" "$dest/OFL-$(basename "$(dirname "$f")").txt"; fi done } # Portable SHA-256 of a file (prints just the hash). sha256() { - if command -v sha256sum >/dev/null; then sha256sum "$1" | cut -d' ' -f1; else shasum -a 256 "$1" | cut -d' ' -f1; fi + local file="$1" + if command -v sha256sum >/dev/null; then sha256sum "$file" | cut -d' ' -f1; else shasum -a 256 "$file" | cut -d' ' -f1; fi + return } diff --git a/packaging/freebsd/package.sh b/packaging/freebsd/package.sh index 1854c284a..d11434be0 100755 --- a/packaging/freebsd/package.sh +++ b/packaging/freebsd/package.sh @@ -20,7 +20,7 @@ APP_ID=ai.storyteller.designcraft SKIP_BUILD=0 DRY_RUN=0 -while [ $# -gt 0 ]; do +while [[ $# -gt 0 ]]; do case "$1" in --skip-build) SKIP_BUILD=1; shift ;; --dry-run) DRY_RUN=1; SKIP_BUILD=1; shift ;; @@ -36,7 +36,7 @@ case "$MACHINE" in arm64 | aarch64) ARCH=aarch64 ;; *) echo "unsupported architecture $MACHINE" >&2; exit 2 ;; esac -if [ "$DRY_RUN" = 0 ] && [ "$(uname -s)" != FreeBSD ]; then +if [[ "$DRY_RUN" = 0 ]] && [[ "$(uname -s)" != FreeBSD ]]; then echo "error: build on FreeBSD (or pass --dry-run to check the tree layout)" >&2 exit 2 fi @@ -46,7 +46,7 @@ echo "==> DesignCraft $VERSION for FreeBSD $ARCH" # The release VM has 12 GB; full parallelism on the biggest crates runs it out of memory. export CARGO_BUILD_JOBS="${CARGO_BUILD_JOBS:-4}" -if [ "$SKIP_BUILD" = 0 ]; then +if [[ "$SKIP_BUILD" = 0 ]]; then (cd "$ROOT" && cargo build --release --locked -p designcraft -p designcraft-cli) fi WORK="$CARGO_TARGET_DIR/freebsd-package" @@ -56,7 +56,7 @@ mkdir -p "$WORK" BIN="$CARGO_TARGET_DIR/release" OUT_DIR="$DIST" -if [ "$DRY_RUN" = 1 ]; then +if [[ "$DRY_RUN" = 1 ]]; then # Stub binaries, and the tarball stays in the work dir so dist/ only ever holds real builds. BIN="$WORK/stub-bin" OUT_DIR="$WORK" @@ -81,13 +81,13 @@ sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$DESIGNCRAFT_BUILD_DATE/g" \ cp -R "$ROOT/assets/app-icon/hicolor" "$STAGE/share/icons/" copy_docs "$STAGE/share/doc/designcraft" for f in NOTICE ATTRIBUTION.md; do - if [ -f "$ROOT/$f" ]; then install -m 644 "$ROOT/$f" "$STAGE/share/doc/designcraft/"; fi + if [[ -f "$ROOT/$f" ]]; then install -m 644 "$ROOT/$f" "$STAGE/share/doc/designcraft/"; fi done for f in bin/designcraft bin/designcraft-cli "share/applications/$APP_ID.desktop" \ "share/icons/hicolor/256x256/apps/$APP_ID.png" "share/icons/hicolor/scalable/apps/$APP_ID.svg" \ share/doc/designcraft/LICENSE-MIT share/doc/designcraft/LICENSE-APACHE; do - if [ ! -e "$STAGE/$f" ]; then echo "error: $f is missing from the package" >&2; exit 1; fi + if [[ ! -e "$STAGE/$f" ]]; then echo "error: $f is missing from the package" >&2; exit 1; fi done # ---- .tar.gz ------------------------------------------------------------------------------------ @@ -96,7 +96,7 @@ tar -C "$WORK" -czf "$OUT_DIR/$BASENAME.tar.gz" "$BASENAME" echo "wrote $OUT_DIR/$BASENAME.tar.gz" "$STAGE/bin/designcraft-cli" --version -if [ "$DRY_RUN" = 1 ]; then +if [[ "$DRY_RUN" = 1 ]]; then echo "==> dry run: tarball contents" tar -tzvf "$OUT_DIR/$BASENAME.tar.gz" fi diff --git a/packaging/icons.sh b/packaging/icons.sh index 6e06fb9ad..7ac9e2954 100755 --- a/packaging/icons.sh +++ b/packaging/icons.sh @@ -21,7 +21,10 @@ MAC="$TMP/mac.svg" sed 's/viewBox="0 0 512 512"/viewBox="-62.136 -62.136 636.272 636.272"/' "$SVG" >"$MAC" grep -q 'viewBox="-62.136' "$MAC" || { echo "error: expected viewBox=\"0 0 512 512\" in $SVG" >&2; exit 1; } -render() { resvg -w "$2" -h "$2" "$1" "$3" &2; exit 1; } +[[ -f "$TARBALL" ]] || { echo "error: $TARBALL not found (run packaging/linux/package.sh --formats tar first)" >&2; exit 1; } for tool in flatpak flatpak-builder; do command -v "$tool" >/dev/null || { echo "error: $tool not found (apt install flatpak flatpak-builder librsvg2-common)" >&2; exit 1; } done @@ -49,7 +49,7 @@ WORK="$CARGO_TARGET_DIR/flatpak-bundle" rm -rf "$WORK" mkdir -p "$WORK/stage" tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1 -[ -x "$WORK/stage/bin/designcraft" ] || { echo "error: $TARBALL has no bin/designcraft" >&2; exit 1; } +[[ -x "$WORK/stage/bin/designcraft" ]] || { echo "error: $TARBALL has no bin/designcraft" >&2; exit 1; } cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$APP_ID.yml" flatpak remote-add --user --if-not-exists flathub "$FLATHUB" @@ -62,7 +62,7 @@ OUT="$DIST/$BASENAME.flatpak" flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$APP_ID" stable echo "wrote $OUT" -if [ "$TEST" = 1 ]; then +if [[ "$TEST" = 1 ]]; then flatpak install --user -y --noninteractive --reinstall "$OUT" flatpak info --user "$APP_ID" flatpak run --command=designcraft-cli "$APP_ID" --version diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index 12ad8e0f2..c4d843eca 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -22,7 +22,7 @@ APP_ID=ai.storyteller.designcraft SKIP_BUILD=0 FORMATS="appimage deb rpm arch tar" -while [ $# -gt 0 ]; do +while [[ $# -gt 0 ]]; do case "$1" in --skip-build) SKIP_BUILD=1; shift ;; --formats) FORMATS="$2"; shift 2 ;; @@ -43,8 +43,8 @@ BASENAME="designcraft-$VERSION-linux-$ARCH" echo "==> DesignCraft $VERSION for Linux $ARCH ($FORMATS)" -if [ "$SKIP_BUILD" = 0 ]; then - if [ -n "${CROSS_TARGET:-}" ]; then +if [[ "$SKIP_BUILD" = 0 ]]; then + if [[ -n "${CROSS_TARGET:-}" ]]; then (cd "$ROOT" && cargo build --release --locked -p designcraft -p designcraft-cli --target "$CROSS_TARGET") else (cd "$ROOT" && cargo build --release --locked -p designcraft -p designcraft-cli) @@ -76,7 +76,10 @@ if command -v appstreamcli >/dev/null; then appstreamcli validate --no-net --explain "$STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" fi -has() { case " $FORMATS " in *" $1 "*) return 0 ;; *) return 1 ;; esac; } +has() { + local fmt="$1" + case " $FORMATS " in *" $fmt "*) return 0 ;; *) return 1 ;; esac +} # ---- .tar.gz ------------------------------------------------------------------------------------ if has tar; then @@ -134,6 +137,8 @@ if has appimage; then case "$ARCH" in x86_64) APPIMAGETOOL_SHA256=ed4ce84f0d9caff66f50bcca6ff6f35aae54ce8135408b3fa33abfc3cb384eb0 ;; aarch64) APPIMAGETOOL_SHA256=f0837e7448a0c1e4e650a93bb3e85802546e60654ef287576f46c71c126a9158 ;; + # No pinned download (e.g. riscv64): set APPIMAGETOOL or put appimagetool on PATH. + *) APPIMAGETOOL_SHA256="" ;; esac APPDIR="$WORK/DesignCraft.AppDir" cp -R "$STAGE" "$APPDIR" @@ -144,9 +149,9 @@ if has appimage; then ln -s "$APP_ID.png" "$APPDIR/.DirIcon" TOOL="${APPIMAGETOOL:-$(command -v appimagetool || true)}" - if [ -z "$TOOL" ]; then + if [[ -z "$TOOL" ]]; then TOOL="$CARGO_TARGET_DIR/appimagetool-$APPIMAGETOOL_VERSION-$ARCH.AppImage" - if [ ! -x "$TOOL" ]; then + if [[ ! -x "$TOOL" ]]; then download="$TOOL.download" curl --proto '=https' -fsSL -o "$download" \ "https://github.com/AppImage/appimagetool/releases/download/$APPIMAGETOOL_VERSION/appimagetool-$ARCH.AppImage" @@ -174,16 +179,16 @@ if has appimage; then # package) appimagetool also writes the .zsync, into its working directory, hence the cd. (cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream -u "$UPDATE_INFO" "$APPDIR" "$OUT") echo "wrote $OUT" - if [ -s "$OUT.zsync" ]; then + if [[ -s "$OUT.zsync" ]]; then echo "wrote $OUT.zsync" else warn "zsyncmake not found, so $OUT.zsync was not written; AppImage delta updates need it" fi fi -if [ -z "${CROSS_TARGET:-}" ]; then +if [[ -z "${CROSS_TARGET:-}" ]]; then "$STAGE/usr/bin/designcraft-cli" --version -elif [ -n "${EMULATOR:-}" ]; then +elif [[ -n "${EMULATOR:-}" ]]; then "$EMULATOR" "$STAGE/usr/bin/designcraft-cli" --version fi echo "==> done" diff --git a/packaging/macos/import-cert.sh b/packaging/macos/import-cert.sh index 9e549610f..8669d8675 100755 --- a/packaging/macos/import-cert.sh +++ b/packaging/macos/import-cert.sh @@ -12,7 +12,7 @@ umask 077 # shellcheck source=../env.sh . "$(dirname "${BASH_SOURCE[0]}")/../env.sh" -if [ -z "${APPLE_CERTIFICATE:-}" ]; then +if [[ -z "${APPLE_CERTIFICATE:-}" ]]; then warn "APPLE_CERTIFICATE is not set: macOS builds will be ad-hoc signed and not notarized" exit 0 fi @@ -36,13 +36,13 @@ security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KC_PASS" security list-keychains -d user -s "$KEYCHAIN" $(security list-keychains -d user | tr -d '"') IDENTITY="$(security find-identity -v -p codesigning "$KEYCHAIN" | awk '/Developer ID Application/ { print $2; exit }')" -if [ -z "$IDENTITY" ]; then +if [[ -z "$IDENTITY" ]]; then security find-identity -v -p codesigning "$KEYCHAIN" >&2 echo "error: no 'Developer ID Application' identity in APPLE_CERTIFICATE" >&2 exit 1 fi echo "Imported signing identity $IDENTITY" -if [ -n "${GITHUB_ENV:-}" ]; then +if [[ -n "${GITHUB_ENV:-}" ]]; then { echo "MACOS_SIGN_IDENTITY=$IDENTITY"; echo "MACOS_KEYCHAIN=$KEYCHAIN"; } >>"$GITHUB_ENV" else echo "MACOS_SIGN_IDENTITY=$IDENTITY" diff --git a/packaging/macos/package.sh b/packaging/macos/package.sh index c818ae6db..21edfa574 100755 --- a/packaging/macos/package.sh +++ b/packaging/macos/package.sh @@ -19,7 +19,7 @@ HERE="$ROOT/packaging/macos" ARCH=universal SKIP_BUILD=0 -while [ $# -gt 0 ]; do +while [[ $# -gt 0 ]]; do case "$1" in --arch) ARCH="$2"; shift 2 ;; --skip-build) SKIP_BUILD=1; shift ;; @@ -44,9 +44,9 @@ DMG="$DIST/designcraft-$VERSION-macos-$ARCH.dmg" CLI_ZIP="$DIST/designcraft-cli-$VERSION-macos-$ARCH.zip" NOTARIZE=0 -if [ "$IDENTITY" = "-" ]; then +if [[ "$IDENTITY" = "-" ]]; then warn "macOS: ad-hoc signing (no MACOS_SIGN_IDENTITY); artifacts are not notarized" -elif [ -n "${APPLE_ID:-}" ] && [ -n "${APPLE_PASSWORD:-}" ] && [ -n "${APPLE_TEAM_ID:-}" ]; then +elif [[ -n "${APPLE_ID:-}" ]] && [[ -n "${APPLE_PASSWORD:-}" ]] && [[ -n "${APPLE_TEAM_ID:-}" ]]; then NOTARIZE=1 else warn "macOS: APPLE_ID / APPLE_PASSWORD / APPLE_TEAM_ID incomplete; signed but not notarized" @@ -55,7 +55,7 @@ fi echo "==> DesignCraft $VERSION for macOS ($ARCH), identity: $IDENTITY, notarize: $NOTARIZE" # ---- build ------------------------------------------------------------------------------------- -if [ "$SKIP_BUILD" = 0 ]; then +if [[ "$SKIP_BUILD" = 0 ]]; then args=() for t in "${TARGETS[@]}"; do args+=(--target "$t"); done (cd "$ROOT" && cargo build --release --locked -p designcraft -p designcraft-cli "${args[@]}") @@ -74,9 +74,9 @@ done sign() { # Hardened runtime + secure timestamp for a real identity; ad-hoc can't be timestamped. local ts=(--timestamp) - [ "$IDENTITY" = "-" ] && ts=(--timestamp=none) + [[ "$IDENTITY" = "-" ]] && ts=(--timestamp=none) local kc=() - [ -n "${MACOS_KEYCHAIN:-}" ] && kc=(--keychain "$MACOS_KEYCHAIN") + [[ -n "${MACOS_KEYCHAIN:-}" ]] && kc=(--keychain "$MACOS_KEYCHAIN") codesign --force --sign "$IDENTITY" ${kc[@]+"${kc[@]}"} "${ts[@]}" "$@" } @@ -88,8 +88,8 @@ notarize() { echo "$out" id="$(printf '%s' "$out" | plutil -extract id raw -o - - 2>/dev/null || true)" status="$(printf '%s' "$out" | plutil -extract status raw -o - - 2>/dev/null || true)" - if [ "$status" != "Accepted" ]; then - if [ -n "$id" ]; then + if [[ "$status" != "Accepted" ]]; then + if [[ -n "$id" ]]; then xcrun notarytool log "$id" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" --team-id "$APPLE_TEAM_ID" || true fi echo "error: notarization of $(basename "$file") failed (status: ${status:-unknown})" >&2 @@ -117,7 +117,7 @@ sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/ sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP" codesign --verify --strict --deep --verbose=2 "$APP" -if [ "$NOTARIZE" = 1 ]; then +if [[ "$NOTARIZE" = 1 ]]; then ditto -c -k --keepParent "$APP" "$WORK/DesignCraft-notarize.zip" notarize "$WORK/DesignCraft-notarize.zip" xcrun stapler staple "$APP" @@ -151,7 +151,7 @@ hdiutil_retry() { if hdiutil "$@"; then return 0 fi - [ "$attempt" = 5 ] && { echo "hdiutil $what failed 5 times" >&2; return 1; } + [[ "$attempt" = 5 ]] && { echo "hdiutil $what failed 5 times" >&2; return 1; } echo "hdiutil $what failed (attempt $attempt of 5); retrying in $((attempt * 10))s" >&2 sleep $((attempt * 10)) done @@ -169,7 +169,7 @@ if ! codesign --verify --strict --deep --verbose=2 "$MOUNT/DesignCraft.app"; the exit 1 fi hdiutil_retry detach detach "$MOUNT" >/dev/null -if [ "$NOTARIZE" = 1 ]; then +if [[ "$NOTARIZE" = 1 ]]; then notarize "$DMG" xcrun stapler staple "$DMG" xcrun stapler validate "$DMG" @@ -187,7 +187,7 @@ codesign --verify --strict --verbose=2 "$CLI_DIR/designcraft-cli" rm -f "$CLI_ZIP" ditto -c -k --keepParent "$CLI_DIR" "$CLI_ZIP" # A bare Mach-O can't carry a stapled ticket; Gatekeeper looks the notarization up online. -if [ "$NOTARIZE" = 1 ]; then notarize "$CLI_ZIP"; fi +if [[ "$NOTARIZE" = 1 ]]; then notarize "$CLI_ZIP"; fi "$WORK/bin/designcraft-cli" --version echo "==> done" diff --git a/packaging/web/package.sh b/packaging/web/package.sh index 4aafc3e80..62c220f0c 100755 --- a/packaging/web/package.sh +++ b/packaging/web/package.sh @@ -11,13 +11,13 @@ set -euo pipefail . "$(dirname "${BASH_SOURCE[0]}")/../env.sh" HERE="$ROOT/packaging/web" -if [ "${1:-}" != "--skip-build" ]; then +if [[ "${1:-}" != "--skip-build" ]]; then command -v trunk >/dev/null || { echo "error: trunk not found (cargo install trunk --locked)" >&2; exit 1; } (cd "$ROOT/apps/designcraft-web" && trunk build --release) fi SITE="$ROOT/dist/web" -[ -f "$SITE/index.html" ] || { echo "error: $SITE/index.html missing; run without --skip-build" >&2; exit 1; } +[[ -f "$SITE/index.html" ]] || { echo "error: $SITE/index.html missing; run without --skip-build" >&2; exit 1; } # Paths must be relative so the site works under any prefix (public_url = "./" in Trunk.toml). if grep -Eq '(src|href)="/[^/]' "$SITE/index.html"; then echo "error: $SITE/index.html has root-absolute URLs; it would break when served from a sub-path" >&2