Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Merge #341: feat(engine): Document chapter numbering and section prefix rules

aiongg54504fa341d7
diff --cc ROADMAP.md
index 9d23dc4c4,75c61a9c2..323521ba3
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -199,7 -166,7 +199,8 @@@ DesignCraft aims at full Adobe InDesig
- OpenType menu (Character panel): discretionary ligatures, fractions, ordinal, swash, titling, contextual alternates, slashed zero, the four figure styles and stylistic sets 1–20; `type.openType`; mapped to IDML's OTF attributes.
- Add Anchor Point (=), Delete Anchor Point (-) and Convert Direction Point (⇧C) tools (click toggles smooth/corner, drag pulls out handles), with `path.addAnchor`, `path.deleteAnchor`, `path.convertAnchor`.
- Gradients: the Gradient Swatch tool (G) drags a gradient's start and end across objects (Shift: 45°); the Gradient panel sets type, angle, reverse and edits stops on a ramp (drag, add, drag off to remove, location, colour). Edited gradients are unnamed swatches; `object.gradient`; the vector round-trips through IDML.
+- New Document (⌘N) as in InDesign: Recent, Saved, Print, Web and Mobile tabs of page cards (double-click creates), and preset details beside them — document name, size with arrows, units, orientation, pages, start page #, facing pages, primary text frame, columns, margins, bleed and slug per edge (linked or not); Save Document Preset; `file.new` takes `intent`, `units`, `startPage` and per-edge `bleed`/`slug`.
+ - Document chapter numbering (`layout.chapterNumbering`): style (1, I, i, A, a, 01, 001, 0001), Automatic Chapter Numbering, Start Chapter Numbering at, Same as Previous Document in the Book; a book's Update Numbering resolves chapter numbers in order; Chapter Number variables and cross-references use the style.
- Document Setup (⌥⌘P): intent, number of pages, start page # (an even start begins with a left page), facing pages, size presets and orientation, bleed and slug per edge; `layout.documentSetup {}` reports the setup.
- Stroke panel: cap, join, miter limit, alignment, type, Start/End arrowheads (12 kinds, drawn on screen and in PDF; the path is shortened under pointed heads) and gap colour under dashes and dots.
- Preferences (⌘K: General, Type, Units & Increments, Grids, Guides & Pasteboard, Display Performance) backed by `prefs.set` (application) and `document.preferences` (units, increments, grids — undoable, saved with the document; right-click a ruler to pick its units, the horizontal and vertical rulers each have their own); scaling applies to content and scales stroke weights (Include Stroke Weight), and X/Y/W/H measure the stroke's outer edge (Dimensions Include Stroke Weight). Quick Apply (⌘Return) finds paragraph, character and object styles as well as commands.
diff --cc crates/engine/src/cmd/book.rs
index 60ace973b,ccee45517..5edde9d1a
--- a/crates/engine/src/cmd/book.rs
+++ b/crates/engine/src/cmd/book.rs
@@@ -154,10 -156,17 +156,17 @@@ pub fn specs() -> Vec<CommandSpec>
for p in &b.documents {
let mut d = load(p)?;
start_at(&mut d, next);
- next = next.saturating_add(d.page_count() as u32);
+ next = next.saturating_add(u32::try_from(d.page_count()).unwrap_or(u32::MAX));
+ chapter = match d.settings.chapter_source {
+ designcraft_doc::ChapterSource::Automatic => chapter.saturating_add(1),
+ designcraft_doc::ChapterSource::UserDefined => d.settings.chapter_number.max(1),
+ designcraft_doc::ChapterSource::SameAsPrevious => chapter.max(1),
+ };
+ d.settings.chapter_number = chapter;
+ chapters.push(d.chapter_label());
store(p, &d)?;
}
- Ok(json!({"pages": next.saturating_sub(1)}))
- Ok(json!({"pages": next - 1, "chapters": chapters}))
++ Ok(json!({"pages": next.saturating_sub(1), "chapters": chapters}))
}),
cmd!(noundo "book.syncStyles", "Synchronize Book", [], None, "{} — paragraph and character styles and swatches of the style source go into every document (by name)", has_book, |s, _| {
let b = s.book.clone().ok_or_else(no_book)?;
diff --cc crates/engine/src/cmd/layout.rs
index f195daf6d,56be6aa21..6c4137c01
--- a/crates/engine/src/cmd/layout.rs
+++ b/crates/engine/src/cmd/layout.rs
@@@ -4,16 -4,8 +4,16 @@@ use designcraft_doc::{LAYER_COLORS, Lay
use serde_json::{Value, json};
use super::{CommandSpec, bad, cmd, has_doc, ok, str_param};
- use crate::Result;
+ use crate::{Result, Session};
+/// A start page number parameter: a whole number in 1..=[`designcraft_doc::MAX_PAGE_NUMBER`].
+fn start_number(cmd: &str, key: &str, v: &Value) -> Result<u32> {
+ v.as_u64()
+ .and_then(|n| u32::try_from(n).ok())
+ .filter(|n| (1..=designcraft_doc::MAX_PAGE_NUMBER).contains(n))
+ .ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number from 1 to {}", designcraft_doc::MAX_PAGE_NUMBER)))
+}
+
/// Each page's margin box, by spread and page id.
fn margin_boxes(d: &designcraft_doc::Document) -> Vec<(designcraft_doc::SpreadRef, designcraft_doc::PageId, designcraft_geom::Rect)> {
d.spread_refs()
@@@ -910,19 -996,19 +1010,33 @@@ mod page_numbering_view_tests
assert_eq!(s.resolve_page("9"), None);
}
+ #[test]
+ fn section_start_numbers_are_bounded() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"pages": 2})).unwrap();
+ for n in [json!(0), json!(100_000), json!(u32::MAX), json!(u64::from(u32::MAX) + 2), json!(-1), json!(2.5), json!("7")] {
+ let e = s.execute("layout.section", &json!({"page": 1, "startNumber": n})).unwrap_err().to_string();
+ assert!(e.contains("startNumber"), "{n}: {e}");
+ assert!(s.execute("layout.documentSetup", &json!({"startPage": n})).is_err(), "{n}");
+ }
+ assert_eq!((0..2).map(|i| s.page_label(i)).collect::<Vec<_>>(), ["1", "2"]);
+ let r = s.execute("layout.section", &json!({"page": 1, "startNumber": 99_999})).unwrap();
+ assert_eq!(r["names"], json!(["99999", "100000"]));
+ }
++
+ #[test]
+ fn section_prefixes_are_short_and_avoid_plus_and_comma() {
+ let mut s = crate::Session::new();
+ s.execute("file.new", &json!({"pages": 2})).unwrap();
+ for prefix in ["A-", "Appendix", "§ 1"] {
+ s.execute("layout.section", &json!({"page": 2, "prefix": prefix})).unwrap();
+ }
+ for prefix in ["Appendix1", "A+", "1,2"] {
+ assert!(s.execute("layout.section", &json!({"page": 2, "prefix": prefix})).is_err(), "{prefix}");
+ }
+ assert!(s.execute("layout.section", &json!({"page": 2, "style": "symbols"})).is_err());
+ assert_eq!(s.doc().unwrap().doc.sections.iter().find(|x| x.start == 1).unwrap().prefix, "§ 1", "a refused prefix changes nothing");
+ }
}
#[cfg(test)]
diff --cc crates/ui-egui/src/dialogs.rs
index 559ec9e80,1b0e5e66d..0dd48a912
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@@ -4031,220 -3810,15 +4031,227 @@@ mod tests
}
#[test]
- fn dialog_title_and_actions_fit_scaled_viewports() {
- for language in ["en", "ar"] {
- for size in [egui::vec2(1178.0, 814.0), egui::vec2(589.0, 407.0), egui::vec2(392.0, 271.0), egui::vec2(450.0, 280.0)] {
- for (command, title) in [("app.preferences", "Preferences"), ("app.newDocumentDialog", "New Document")] {
- let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
- app.ui.language = language.into();
- app.run("file.new", json!({})).unwrap();
- app.run(command, json!({})).unwrap();
- let ctx = dialog_context(language);
+ fn paragraph_style_options_edit_one_rule_field() {
+ let (mut app, rule) = ruled_paragraph();
+ let ctx = egui::Context::default();
+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "rules", "rule": "ruleBelow"})));
+ draw(&mut app, &ctx);
+ let resolved = |app: &DesignApp| serde_json::to_value(app.session.doc().unwrap().doc.styles.resolve_para_style("Ruled Child").0).unwrap();
+ let d = app.ui.dialog.clone().unwrap();
+ assert_eq!(shown_rule(&d, "p.", "ruleBelow", &resolved(&app)), rule, "inherited from the parent style");
+ app.ui.dialog.as_mut().unwrap().fields.insert("p.ruleBelow.weight".into(), json!(1.5));
+ draw(&mut app, &ctx);
+ let before = undo_steps(&app);
+ confirm(&mut app).unwrap();
+ assert_eq!(undo_steps(&app), before + 1, "one undo step");
+ let mut want = rule.clone();
+ want["weight"] = json!(1.5);
+ assert_eq!(resolved(&app)["ruleBelow"], want);
+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], want, "the paragraph follows its style");
+ app.run("edit.undo", json!({})).unwrap();
+ assert_eq!(resolved(&app)["ruleBelow"], rule);
+ }
+
+ fn command_app(id: &str, fields: Value) -> DesignApp {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.ui.dialog = Some(Dialog::new(&format!("cmd:{id}"), fields));
+ app
+ }
+
+ #[test]
+ fn generic_new_document_preserves_typed_values_and_text_entry() {
+ for pages in [json!(2), json!(" 2 ")] {
+ let mut app = command_app(
+ "file.new",
+ json!({
+ "preset": "A4", "pages": pages, "facingPages": false, "gutter": 0,
+ "margins": {"top": 10, "bottom": 20, "inside": 30, "outside": 40},
+ "title": " ", "status": "internal", "primaryTextFrame": true
+ }),
+ );
+ confirm(&mut app).unwrap();
+ let doc = &app.session.active().unwrap().doc;
+ assert_eq!(doc.page_count(), 2);
+ assert!(!doc.settings.facing_pages);
+ assert!(doc.title.starts_with("Untitled-"));
+ for page in doc.spreads.iter().flat_map(|s| &s.pages) {
+ assert!((page.width - 595.2755905511812).abs() < 0.01);
+ assert!((page.height - 841.8897637795277).abs() < 0.01);
+ assert_eq!(page.columns.gutter, 0.0);
+ assert_eq!(page.margins.top, 10.0);
+ assert_eq!(page.margins.outside, 40.0);
+ }
+ assert!(doc.spreads.iter().all(|s| s.items.is_empty()), "undocumented fields stay excluded");
+ assert!(app.ui.dialog.is_none());
+ }
+ }
+
++ #[test]
++ fn numbering_commands_document_their_fields() {
++ let names = |id: &str| command_fields(designcraft_engine::find_command(id).unwrap().params).into_iter().map(|f| f.key).collect::<Vec<_>>();
++ assert_eq!(names("layout.section"), ["page", "startNumber", "style", "prefix", "includePrefix", "marker", "remove"]);
++ assert_eq!(names("layout.chapterNumbering"), ["style", "start", "source"]);
++ }
++
+ #[test]
+ fn generic_command_preserves_array_geometry() {
+ let mut app = command_app("file.new", json!({}));
+ confirm(&mut app).unwrap();
+ app.ui.dialog = Some(Dialog::new("cmd:frame.create", json!({"rect": [10, 20, 110, 220]})));
+ confirm(&mut app).unwrap();
+ let doc = &app.session.active().unwrap().doc;
+ let item = doc.spreads.iter().flat_map(|s| &s.items).next().unwrap();
+ assert_eq!(item.bounds(), designcraft_geom::Rect::new(10.0, 20.0, 110.0, 220.0));
+ }
+
+ #[test]
+ fn generic_explicit_null_uses_the_commands_existing_semantics() {
+ // file.new accepts null width by using the selected preset's width.
+ for width in [Value::Null, json!("null")] {
+ let mut app = command_app("file.new", json!({"preset": "A4", "width": width, "title": " Sample layout "}));
+ confirm(&mut app).unwrap();
+ let doc = &app.session.active().unwrap().doc;
+ assert_eq!(doc.title, "Sample layout");
+ assert!((doc.settings.page_width - 595.2755905511812).abs() < 0.01);
+ }
+ }
+
+ #[test]
+ fn generic_invalid_number_retains_dialog_without_creating_document() {
+ let mut app = command_app("file.new", json!({"width": 0}));
+ assert!(confirm(&mut app).is_err());
+ assert!(app.session.active().is_none());
+ let dialog = app.ui.dialog.as_ref().unwrap();
+ assert_eq!(dialog.fields["width"], 0);
+ assert!(dialog.fields["status"].as_str().unwrap().contains("page size out of range"));
+ }
+
+ #[test]
+ fn text_frame_options_change_only_what_was_edited() {
+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "content": "text", "text": "Hello"})).unwrap();
+ let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());
+ app.run("object.textFrameOptions", json!({"ids": [id.0], "columns": 2, "inset": [1, 2, 3, 4]})).unwrap();
+ let opts = |app: &DesignApp| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.clone();
+ let before = opts(&app);
+ let open = |app: &mut DesignApp, fields: &[(&str, Value)]| {
+ app.ui.dialog = Some(Dialog::new("textFrameOptions", json!({})));
+ let mut d = app.ui.dialog.take().unwrap();
+ seed_text_frame_options(app, &mut d);
+ for (k, v) in fields {
+ d.fields.insert((*k).into(), v.clone());
+ }
+ app.ui.dialog = Some(d);
+ confirm(app)
+ };
+ // OK without edits changes nothing (no undo step either).
+ assert_eq!(open(&mut app, &[]).unwrap(), Value::Null);
+ assert_eq!(opts(&app), before);
+ // The rule's weight is in points; unequal insets the user didn't touch stay.
+ open(&mut app, &[("columnRule", json!(true)), ("columnRuleWeight", json!("6"))]).unwrap();
+ let o = opts(&app);
+ assert!(o.column_rule && o.column_rule_weight == 6.0, "{o:?}");
+ assert_eq!((o.inset, o.columns, o.gutter), (before.inset, before.columns, before.gutter));
+ // One of the rule's insets edited: the other rule settings stay.
+ open(&mut app, &[("columnRuleBottomInset", json!("0p9")), ("columnRuleTint", json!("40"))]).unwrap();
+ let o = opts(&app);
+ assert_eq!((o.column_rule_bottom_inset, o.column_rule_top_inset, o.column_rule_offset, o.column_rule_weight), (9.0, 0.0, 0.0, 6.0));
+ assert!((o.column_rule_tint - 0.4).abs() < 1e-6 && o.column_rule);
+ // One inset side edited: the others keep their values.
+ open(&mut app, &[("insetLeft", json!("1p0"))]).unwrap();
+ assert_eq!(opts(&app).inset, [1.0, 12.0, 3.0, 4.0]);
+ // An unknown swatch is an error and the dialog stays open.
+ let e = open(&mut app, &[("columnRuleColor", json!("Mauve"))]).unwrap_err();
+ assert!(e.contains("Mauve") && app.ui.dialog.is_some(), "{e}");
+ assert_eq!(opts(&app).column_rule_color, designcraft_color::swatch::BLACK);
+ // Each OK is one undo step.
+ for _ in 0..3 {
+ app.run("edit.undo", json!({})).unwrap();
+ }
+ assert_eq!(opts(&app), before);
+ }
+
+ fn dialog_context(language: &str) -> egui::Context {
+ let ctx = egui::Context::default();
+ crate::theme::install_fonts(&ctx, language);
+ crate::theme::apply(&ctx, &crate::theme::Tokens::for_brightness(crate::theme::Brightness::default()));
+ ctx
+ }
+
+ fn dialog_frame(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, events: Vec<egui::Event>) -> Vec<(String, egui::Rect, egui::Rect)> {
+ let time = ctx.input(|i| i.time) + 1.0 / 60.0;
+ let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), events, ..Default::default() }, |ui| {
+ show(app, ui.ctx());
+ });
+ output.textures_delta.clear();
+ fn collect(shape: &egui::Shape, clip: egui::Rect, labels: &mut Vec<(String, egui::Rect, egui::Rect)>) {
+ match shape {
+ egui::Shape::Text(t) => labels.push((t.galley.job.text.clone(), t.visual_bounding_rect(), clip)),
+ egui::Shape::Vec(shapes) => {
+ for s in shapes {
+ collect(s, clip, labels);
+ }
+ }
+ _ => {}
+ }
+ }
+ let mut labels = Vec::new();
+ for shape in output.shapes {
+ collect(&shape.shape, shape.clip_rect, &mut labels);
+ }
+ labels
+ }
+
+ fn visible_label(labels: &[(String, egui::Rect, egui::Rect)], screen: egui::Rect, expected: &str) -> egui::Rect {
+ let (_, rect, clip) = labels.iter().find(|(text, _, _)| text.trim() == expected).unwrap_or_else(|| panic!("{expected} is painted"));
+ assert!(screen.contains_rect(*rect), "{expected} must stay on screen: {rect:?}");
+ assert!(clip.contains_rect(*rect), "{expected} must not be clipped: {rect:?}, {clip:?}");
+ *rect
+ }
+
+ fn click_dialog(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, pos: egui::Pos2) {
+ for pressed in [true, false] {
+ dialog_frame(
+ app,
+ ctx,
+ screen,
+ vec![
+ egui::Event::PointerMoved(pos),
+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE },
+ ],
+ );
+ }
+ }
+
+ fn scroll_dialog(app: &mut DesignApp, ctx: &egui::Context, screen: egui::Rect, pos: egui::Pos2, delta: egui::Vec2) {
+ dialog_frame(
+ app,
+ ctx,
+ screen,
+ vec![
+ egui::Event::PointerMoved(pos),
+ egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Point, delta, phase: egui::TouchPhase::Move, modifiers: egui::Modifiers::NONE },
+ ],
+ );
+ // Let smooth wheel scrolling and scrollbar visibility settle before clicking.
+ for _ in 0..30 {
+ dialog_frame(app, ctx, screen, vec![]);
+ }
+ }
+
+ #[test]
+ fn dialog_title_and_actions_fit_scaled_viewports() {
+ for language in ["en", "ar"] {
+ for size in [egui::vec2(1178.0, 814.0), egui::vec2(589.0, 407.0), egui::vec2(392.0, 271.0), egui::vec2(450.0, 280.0)] {
+ for (command, title, ok, cancel) in
+ [("app.preferences", "Preferences", "OK", "Cancel"), ("app.newDocumentDialog", "New Document", "Create", "Close")]
+ {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.ui.language = language.into();
+ app.run("file.new", json!({})).unwrap();
+ app.run(command, json!({})).unwrap();
+ let ctx = dialog_context(language);
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size);
for _ in 0..3 {
dialog_frame(&mut app, &ctx, screen, vec![]);