DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #316 update: GREP styles with a pattern that can't compile are rejected, and imports warn
aiongg037771057e15
diff --cc crates/engine/src/cmd/file.rsindex add22efa4,4d2761e59..c319538eb--- a/crates/engine/src/cmd/file.rs+++ b/crates/engine/src/cmd/file.rs@@@ -13,40 -13,18 +13,40 @@@ use crate::{DocState, EngineError, Resupub fn specs() -> Vec<CommandSpec> {vec![cmd!(noundo "file.new", "Document…", ["File", "New"], Some("Cmd+N"),- "{preset?: \"Letter\"|\"A4\"|…, width?, height?, pages?, facingPages?, columns?, gutter?, margins?: number|{top,bottom,inside,outside}, bleed?, title?}",+ "{preset?: \"Letter\"|\"A4\"|… or a saved preset (file.savePreset), intent?: print|web|mobile, units?: points|picas|millimeters|…, width?, height?, pages?, startPage?, facingPages?, columns?, gutter?, margins?: number|{top,bottom,inside,outside}, bleed?, slug?: n | [top, bottom, inside, outside], title?}",always, file_new),cmd!(noundo "file.newSample", "Sample Document", ["Help"], None, "{} — a multi-page magazine sample", always, file_sample),- cmd!(query "file.presets", "Document Presets", [], None, "{}", always, |_, _| Ok(serde_json::to_value(PRESETS).unwrap_or_default())),+ cmd!(query "file.presets", "Document Presets", [], None, "{} → the built-in presets [{name, intent, width, height, units}], then the saved ones (with `saved: true`)", always, |s, _| {+ let mut presets: Vec<Value> = PRESETS.iter().map(|p| serde_json::to_value(p).unwrap_or_default()).collect();+ presets.extend(+ s.prefs+ .document_presets+ .iter()+ .map(|p| json!({"name": p.title, "intent": p.intent, "width": p.width, "height": p.height, "units": p.units, "saved": true})),+ );+ Ok(Value::Array(presets))+ }),+ cmd!(noundo "file.savePreset", "Save Document Preset", [], None,+ "{name, …the settings file.new takes} — kept with the preferences; `file.new {preset: name}` uses it. A saved preset of that name is replaced; built-in names are refused",+ always, save_preset),+ cmd!(noundo "file.deletePreset", "Delete Document Preset", [], None, "{name} — a saved document preset", always, |s, p| {+ let name = str_param(p, "name").unwrap_or_default().trim().to_string();+ let before = s.prefs.document_presets.len();+ s.prefs.document_presets.retain(|x| !x.title.eq_ignore_ascii_case(&name));+ if s.prefs.document_presets.len() == before {+ return Err(bad("file.deletePreset", format!("no saved preset `{name}`")));+ }+ ok()+ }),cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"),- "{path} — a DesignCraft or IDML file (recognised by its content, so the extension may be missing), or an InDesign .indd/.indt (recognised by its signature or extension, converted to IDML; its conversion warnings join `warnings`); the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped and, for IDML and InDesign files, package parts missing}",- "{path} — .designcraft or .idml; the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped, GREP styles whose pattern can't compile}",++ "{path} — a DesignCraft or IDML file (recognised by its content, so the extension may be missing), or an InDesign .indd/.indt (recognised by its signature or extension, converted to IDML; its conversion warnings join `warnings`); the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped, GREP styles whose pattern can't compile and, for IDML and InDesign files, package parts missing}",always, file_open),- cmd!(noundo "file.openBytes", "Open Bytes", [], None, "{name, base64} — DesignCraft JSON or an IDML package", always, file_open_bytes),- cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?}", has_doc, file_save),- cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path}", has_doc, file_save),- cmd!(noundo "file.saveACopy", "Save a Copy…", ["File"], None, "{path} — writes the document without changing which file it is or its unsaved state", has_doc, |s, p| {- let path = str_param(p, "path").ok_or_else(|| bad("file.saveACopy", "missing `path`"))?.to_string();+ cmd!(noundo "file.openBytes", "Open Bytes", [], None, "{name, base64} — DesignCraft JSON, an IDML package or an InDesign .indd/.indt", always, file_open_bytes),+ cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?} — a `path` without the .designcraft extension gets it → {path: the file written, bytes}", has_doc, file_save),+ cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path} — a path without the .designcraft extension gets it → {path: the file written, bytes}", has_doc, file_save),+ cmd!(noundo "file.saveACopy", "Save a Copy…", ["File"], None, "{path} — writes the document without changing which file it is or its unsaved state; a path without the .designcraft extension gets it → {path: the file written, bytes}", has_doc, |s, p| {+ let path = str_param(p, "path").ok_or_else(|| bad("file.saveACopy", "missing `path`"))?;+ let path = with_document_extension(path);let bytes = to_bytes(&s.doc()?.doc);#[cfg(not(target_arch = "wasm32"))]std::fs::write(&path, &bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;diff --cc crates/engine/src/cmd/interchange.rsindex 898e78891,0ece4037f..a3c379156--- a/crates/engine/src/cmd/interchange.rs+++ b/crates/engine/src/cmd/interchange.rs@@@ -14,7 -13,7 +14,7 @@@ pub fn specs() -> Vec<CommandSpec>"{path?, embedImages?: true} — writes an IDML package to `path`, or returns {base64} without a path",has_doc, export_idml),cmd!(noundo "file.openIdml", "Open IDML", [], None,- "{path | base64, name?} — opens an IDML package, or an InDesign document or template (.indd, .indt: converted to IDML first; its conversion warnings join `warnings`), as a new document (linked images are read next to the file or from its Links/ folder; the fonts in a `Document Fonts` folder beside it load first) → {index, documentFonts, warnings: conversion warnings, package parts missing, font files skipped}",- "{path | base64, name?} — opens an IDML package as a new document (linked images are read next to the file or from its Links/ folder; the fonts in a `Document Fonts` folder beside it load first) → {index, documentFonts, warnings: font files skipped, GREP styles whose pattern can't compile}",++ "{path | base64, name?} — opens an IDML package, or an InDesign document or template (.indd, .indt: converted to IDML first; its conversion warnings join `warnings`), as a new document (linked images are read next to the file or from its Links/ folder; the fonts in a `Document Fonts` folder beside it load first) → {index, documentFonts, warnings: conversion warnings, package parts missing, font files skipped, GREP styles whose pattern can't compile}",always, open_idml),]}@@@ -215,8 -150,8 +215,9 @@@ pub(crate) fn open_idml(s: &mut SessionSome(path) => super::file::load_document_fonts(&mut d, path),None => (None, 0, Vec::new()),};+ warnings.extend(font_warnings);+ warnings.extend(super::style::grep_style_warnings(&d));- // Never save over the .idml with the native format: the document starts unsaved.+ // Never save over the .idml or .indd with the native format: the document starts unsaved.let mut st = DocState::new(d, None);st.fonts = fonts;let i = s.add_document(st);diff --cc crates/engine/src/cmd/style.rsindex 5f5165304,1944be2d8..cbedd42a9--- a/crates/engine/src/cmd/style.rs+++ b/crates/engine/src/cmd/style.rs@@@ -86,7 -86,7 +86,7 @@@ pub fn specs() -> Vec<CommandSpec>"New Paragraph Style…",[],None,- "{name, basedOn?, nextStyle?, para?: {… startAt?: null = continue numbering}, chars?: {…}, fromSelection?: bool}",- "{name, basedOn?, nextStyle?, para?: {… grepStyles?: [{style, pattern}]: a pattern that can't compile is an error}, chars?: {…}, fromSelection?: bool}",++ "{name, basedOn?, nextStyle?, para?: {… startAt?: null = continue numbering; grepStyles?: [{style, pattern}]: a pattern that can't compile is an error}, chars?: {…}, fromSelection?: bool}",has_doc,create_para),@@@ -95,7 -95,7 +95,7 @@@"Paragraph Style Options…",[],None,- "{name, rename?, basedOn?, nextStyle?, para?: {… ruleAbove?/ruleBelow?: only the named rule fields change; startAt?: null = continue numbering; kinsoku?: set | null (default rules)}, chars?: {…}}",- "{name, rename?, basedOn?, nextStyle?, para?: {… ruleAbove?/ruleBelow?: only the named rule fields change; a grepStyles pattern that can't compile is an error}, chars?: {…}}",++ "{name, rename?, basedOn?, nextStyle?, para?: {… ruleAbove?/ruleBelow?: only the named rule fields change; startAt?: null = continue numbering; kinsoku?: set | null (default rules); a grepStyles pattern that can't compile is an error}, chars?: {…}}",has_doc,edit_para),@@@ -435,21 -425,10 +435,22 @@@ fn apply_char(s: &mut Session, p: &Valu})}+/// In a style, `startAt: null` is Continue from Previous Number: it is stored as an explicit+/// "continue" so it also overrides a Start At the style would inherit.+fn continue_numbering(p: Option<&Value>, para: &mut ParaAttrs) {+ let explicit =+ p.and_then(Value::as_object).is_some_and(|o| o.iter().any(|(k, v)| v.is_null() && k.replace('_', "").eq_ignore_ascii_case("startAt")));+ if explicit {+ para.start_at = Some(None);+ }+}+fn create_para(s: &mut Session, p: &Value) -> Result<Value> {let base = str_param(p, "name").unwrap_or("Paragraph Style 1").to_string();- let mut para: ParaAttrs = attrs(p.get("para"), |a: &mut ParaAttrs, k, v| a.set_json(k, v))?;+ let mut para: ParaAttrs = attrs(p.get("para"), |a: &mut ParaAttrs, k, v| a.set_json_over(k, v, &designcraft_doc::ParaProps::default()))?;+ continue_numbering(p.get("para"), &mut para);+ explicit_default_kinsoku(&mut para, p.get("para"));+ check_grep_styles("style.paragraph.create", ¶)?;let mut chars: CharAttrs = attrs(p.get("chars"), |a: &mut CharAttrs, k, v| a.set_json(k, v))?;if p.get("fromSelection").and_then(Value::as_bool).unwrap_or(false)&& let Ok(cur) = s.execute("type.selectionAttrs", &json!({}))@@@ -480,14 -459,39 +481,47 @@@})}+/// `kinsoku: null` sets the composer's default kinsoku rules, also over a Based On style's set.+/// For the other attributes `null` leaves the style's value as it is.+fn explicit_default_kinsoku(para: &mut ParaAttrs, given: Option<&Value>) {+ if given.and_then(|o| o.get("kinsoku")).is_some_and(Value::is_null) {+ para.kinsoku = Some(None);+ }+}++ /// The compile error of the first GREP style in `a` whose pattern can't compile.+ pub(crate) fn grep_style_error(a: &ParaAttrs) -> Option<String> {+ a.grep_styles+ .iter()+ .flatten()+ .filter(|g| !g.pattern.is_empty())+ .find_map(|g| designcraft_compose::grep::Grep::new(&g.pattern, Default::default()).err().map(|e| format!("{e} (pattern {:?})", g.pattern)))+ }++ /// Rejects GREP styles a command would set with a pattern that can't compile.+ pub(crate) fn check_grep_styles(cmd: &str, a: &ParaAttrs) -> Result<()> {+ grep_style_error(a).map_or(Ok(()), |e| Err(bad(cmd, e)))+ }++ /// One warning for each paragraph style or paragraph whose GREP style pattern can't compile.+ /// Such a GREP style stays in the document and composition skips it.+ pub(crate) fn grep_style_warnings(d: &designcraft_doc::Document) -> Vec<String> {+ let mut out: Vec<String> = d+ .styles+ .paragraph+ .iter()+ .filter_map(|st| grep_style_error(&st.para).map(|e| format!("paragraph style {:?}: GREP style not applied: {e}", st.name)))+ .collect();+ for st in d.stories.values() {+ for (i, pf) in st.paras.iter().enumerate() {+ if let Some(e) = grep_style_error(&pf.para) {+ out.push(format!("story {} paragraph {}: GREP style not applied: {e}", st.id.0, i + 1));+ }+ }+ }+ out+ }+#[allow(non_snake_case)]fn ParaProps_to_attrs(p: &designcraft_doc::ParaProps) -> ParaAttrs {designcraft_doc::ParaProps::common([p])@@@ -510,9 -514,8 +544,10 @@@ fn edit_para(s: &mut Session, p: &Value}// A rule object changes only the rule fields it names, over the style's resolved rule.let (current, _) = d.styles.resolve_para_style(&name);- let para: ParaAttrs = attrs(p.get("para"), |a: &mut ParaAttrs, k, v| a.set_json_over(k, v, ¤t))?;+ let mut para: ParaAttrs = attrs(p.get("para"), |a: &mut ParaAttrs, k, v| a.set_json_over(k, v, ¤t))?;+ continue_numbering(p.get("para"), &mut para);+ explicit_default_kinsoku(&mut para, p.get("para"));+ check_grep_styles("style.paragraph.edit", ¶)?;let st = d.styles_mut().para_mut(&name).ok_or_else(|| bad("style.paragraph.edit", format!("no style `{name}`")))?;st.para.merge(¶);st.chars.merge(&chars);@@@ -1515,273 -1354,57 +1550,328 @@@ mod cjk_tests}}+#[cfg(test)]+mod delete_tests {+ use designcraft_doc::{CellStyle, ObjectStyle, StoryId, Toc, TocEntry};+ use serde_json::json;++ use crate::Session;++ /// Is `name` still named anywhere in the document?+ fn named(s: &Session, name: &str) -> bool {+ serde_json::to_string(&*s.doc().unwrap().doc).unwrap().contains(&format!("\"{name}\""))+ }++ fn char_doc() -> (Session, u64) {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("style.character.create", &json!({"name": "Base", "chars": {"fontStyle": "Bold"}})).unwrap();+ s.execute("style.character.create", &json!({"name": "Emphasis", "basedOn": "Base", "chars": {"tracking": 20}})).unwrap();+ s.execute("style.character.create", &json!({"name": "Child", "basedOn": "Emphasis"})).unwrap();+ s.execute("style.character.create", &json!({"name": "Strong", "chars": {"size": 14}})).unwrap();+ let refs = json!({+ "nestedStyles": [{"style": "Emphasis", "through": true, "count": 1, "until": {"kind": "words"}}],+ "grepStyles": [{"style": "Emphasis", "pattern": "\\d+"}],+ "nestedLineStyles": [{"style": "Emphasis", "lines": 1}],+ "dropCapLines": 2, "dropCapChars": 1, "dropCapStyle": "Emphasis"});+ s.execute("style.paragraph.create", &json!({"name": "Lead", "para": refs})).unwrap();+ s.execute("footnote.options", &json!({"refCharStyle": "Emphasis"})).unwrap();+ let sid = s.execute("frame.create", &json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Hi there"})).unwrap()["story"]+ .as_u64()+ .unwrap();+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 2})).unwrap();+ s.execute("style.character.apply", &json!({"name": "Emphasis"})).unwrap();+ // Local paragraph overrides name it too.+ s.execute("type.para", &json!({"attrs": refs})).unwrap();+ s.edit(|d, _| {+ d.styles_mut().default_character = "Emphasis".into();+ Ok(())+ })+ .unwrap();+ assert!(named(&s, "Emphasis"));+ (s, sid)+ }++ #[test]+ fn deleting_a_character_style_points_every_use_at_the_replacement() {+ let (mut s, sid) = char_doc();+ let undo = s.doc().unwrap().history.undo.len();+ s.execute("style.character.delete", &json!({"name": "Emphasis", "replaceWith": "Strong"})).unwrap();+ assert!(!named(&s, "Emphasis"), "no dangling reference");+ let d = s.doc().unwrap().doc.clone();+ assert_eq!(d.styles.char_style("Child").unwrap().based_on.as_deref(), Some("Strong"));+ assert_eq!(d.story(StoryId(sid)).unwrap().chars[0].format.style, "Strong");+ let lead = &d.styles.para("Lead").unwrap().para;+ assert_eq!(lead.nested_styles.as_ref().unwrap()[0].style, "Strong");+ assert_eq!(lead.grep_styles.as_ref().unwrap()[0].style, "Strong");+ assert_eq!(lead.nested_line_styles.as_ref().unwrap()[0].style, "Strong");+ assert_eq!(lead.drop_cap_style.as_deref(), Some("Strong"));+ assert_eq!(d.footnote_options.ref_char_style, "Strong");+ assert_eq!(d.styles.default_character, "Strong");+ // One undo step brings the style and every use back.+ assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);+ s.execute("edit.undo", &json!({})).unwrap();+ assert!(s.doc().unwrap().doc.styles.char_style("Emphasis").is_some());+ assert_eq!(s.doc().unwrap().doc.story(StoryId(sid)).unwrap().chars[0].format.style, "Emphasis");+ }++ #[test]+ fn deleting_a_character_style_for_none_unsets_based_on() {+ let (mut s, _) = char_doc();+ s.execute("style.character.delete", &json!({"name": "Emphasis"})).unwrap();+ assert!(!named(&s, "Emphasis"), "no dangling reference");+ let d = s.doc().unwrap().doc.clone();+ assert_eq!(d.styles.char_style("Child").unwrap().based_on, None);+ assert_eq!(d.footnote_options.ref_char_style, designcraft_doc::NO_CHAR_STYLE);+ }++ /// Replacing a style with its own descendant rebases the deleted style's children on its+ /// parent, so no based-on chain becomes a cycle.+ #[test]+ fn replacing_a_style_with_its_child_makes_no_cycle() {+ let (mut s, _) = char_doc();+ s.execute("style.character.create", &json!({"name": "Grandchild", "basedOn": "Child"})).unwrap();+ s.execute("style.character.delete", &json!({"name": "Emphasis", "replaceWith": "Grandchild"})).unwrap();+ let d = s.doc().unwrap().doc.clone();+ assert_eq!(d.styles.char_style("Child").unwrap().based_on.as_deref(), Some("Base"));+ assert_eq!(d.styles.char_style("Grandchild").unwrap().based_on.as_deref(), Some("Child"));+ assert!(!named(&s, "Emphasis"));+ }++ #[test]+ fn bad_style_deletes_are_errors_and_change_nothing() {+ let (mut s, _) = char_doc();+ s.execute("style.paragraph.create", &json!({"name": "Head"})).unwrap();+ let before = s.doc().unwrap().doc.clone();+ let undo = s.doc().unwrap().history.undo.len();+ for (id, p) in [+ ("style.character.delete", json!({})),+ ("style.character.delete", json!({"name": ""})),+ ("style.character.delete", json!({"name": "Nope"})),+ ("style.character.delete", json!({"name": "[None]"})),+ ("style.character.delete", json!({"name": "Emphasis", "replaceWith": "Nope"})),+ ("style.character.delete", json!({"name": "Emphasis", "replaceWith": "Emphasis"})),+ ("style.paragraph.delete", json!({})),+ ("style.paragraph.delete", json!({"name": ""})),+ ("style.paragraph.delete", json!({"name": "Nope"})),+ ("style.paragraph.delete", json!({"name": "[Basic Paragraph]"})),+ ("style.paragraph.delete", json!({"name": "Head", "replaceWith": "Nope"})),+ ("style.paragraph.delete", json!({"name": "Head", "replaceWith": "Head"})),+ ] {+ assert!(s.execute(id, &p).is_err(), "{id} {p}");+ }+ assert_eq!(*s.doc().unwrap().doc, *before);+ assert_eq!(s.doc().unwrap().history.undo.len(), undo);+ }++ #[test]+ fn deleting_a_paragraph_style_points_every_use_at_the_replacement() {+ let mut s = Session::new();+ s.execute("file.newSample", &json!({})).unwrap();+ s.execute("style.paragraph.create", &json!({"name": "Sub", "basedOn": "Table Body", "nextStyle": "Table Body"})).unwrap();+ s.edit(|d, _| {+ let story = *d.stories.keys().next().ok_or(crate::EngineError::NoDocument)?;+ let st = d.styles_mut();+ st.default_paragraph = "Table Body".into();+ st.object.push(ObjectStyle { name: "Boxed".into(), paragraph_style: Some("Table Body".into()), ..Default::default() });+ st.cell.push(CellStyle { name: "Body Cell".into(), paragraph_style: Some("Table Body".into()), ..Default::default() });+ d.footnote_options.para_style = "Table Body".into();+ d.endnote_options.para_style = "Table Body".into();+ d.endnote_options.heading_style = "Table Body".into();+ d.toc =+ Some(Toc { story, title: "Contents".into(), entries: vec![TocEntry { style: "Table Body".into(), level: 1 }], page_numbers: false });+ Ok(())+ })+ .unwrap();+ assert!(named(&s, "Table Body"));+ s.execute("style.paragraph.delete", &json!({"name": "Table Body", "replaceWith": "Body"})).unwrap();+ assert!(!named(&s, "Table Body"), "no dangling reference");+ let d = s.doc().unwrap().doc.clone();+ let sub = d.styles.para("Sub").unwrap();+ assert_eq!((sub.based_on.as_deref(), sub.next_style.as_deref()), (Some("Body"), Some("Body")));+ assert_eq!(d.styles.default_paragraph, "Body");+ assert_eq!(d.endnote_options.heading_style, "Body");+ let after = s.execute("preflight.run", &json!({})).unwrap();+ assert!(!after.to_string().contains("Table Body"), "{after}");+ }+}++#[cfg(test)]+mod swatch_options_tests {+ use designcraft_color::SwatchValue;+ use designcraft_doc::{ItemId, StoryId};+ use serde_json::json;++ use crate::Session;++ /// A document whose frame, text, styles, tint swatch and colour group all use "Brand".+ fn brand_doc() -> (Session, u64, u64) {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("swatch.create", &json!({"name": "Brand", "color": {"c": 0, "m": 80, "y": 100, "k": 0}})).unwrap();+ s.execute("swatch.create", &json!({"name": "Other", "color": "#108080"})).unwrap();+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Hello"})).unwrap();+ let (id, sid) = (r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap());+ s.execute("object.fill", &json!({"swatch": "Brand", "ids": [id]})).unwrap();+ s.execute("object.stroke", &json!({"swatch": "Brand", "ids": [id]})).unwrap();+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 3})).unwrap();+ s.execute("type.char", &json!({"attrs": {"fill": "Brand"}})).unwrap();+ s.execute("text.select", &json!({"story": sid, "anchor": 5, "focus": 5})).unwrap();+ s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap();+ s.execute("table.select", &json!({"what": "table"})).unwrap();+ s.execute("table.setCell", &json!({"stroke": {"weight": 2, "type": "dashed", "gapColor": "Brand", "edges": ["all"]}})).unwrap();+ s.execute("swatch.newColorGroup", &json!({"name": "Brand Colors", "swatches": ["Brand"]})).unwrap();+ s.execute("style.character.create", &json!({"name": "Accent"})).unwrap();+ s.edit(|d, _| {+ d.swatches.push(designcraft_color::Swatch {+ name: "Brand 50%".into(),+ value: SwatchValue::Tint { base: "Brand".into(), tint: 0.5 },+ locked: false,+ named: true,+ hidden: false,+ });+ let st = d.styles_mut();+ if let Some(p) = st.para_mut(designcraft_doc::BASIC_PARAGRAPH) {+ p.chars.underline_color = Some("Brand".into());+ p.para.shading_color = Some("Brand".into());+ p.para.border_gap_color = Some("Brand".into());+ p.chars.ruby_stroke = Some("Brand".into());+ }+ if let Some(c) = st.char_style_mut("Accent") {+ c.chars.fill = Some("Brand".into());+ c.chars.kenten_fill = Some("Brand".into());+ }+ Ok(())+ })+ .unwrap();+ (s, id, sid)+ }++ fn uses(s: &Session, id: u64, sid: u64, name: &str) -> Vec<bool> {+ let d = &s.doc().unwrap().doc;+ let it = d.item(ItemId(id)).unwrap();+ let story = d.story(StoryId(sid)).unwrap();+ let basic = d.styles.para(designcraft_doc::BASIC_PARAGRAPH).unwrap();+ vec![+ it.fill.swatch == name,+ it.stroke.swatch == name,+ story.chars.iter().any(|r| r.format.over.fill.as_deref() == Some(name)),+ basic.chars.underline_color.as_deref() == Some(name),+ basic.para.shading_color.as_deref() == Some(name),+ d.styles.char_style("Accent").unwrap().chars.fill.as_deref() == Some(name),+ matches!(&d.swatch("Brand 50%").unwrap().value, SwatchValue::Tint { base, .. } if base == name),+ d.color_groups[0].swatches == [name],+ basic.para.border_gap_color.as_deref() == Some(name),+ basic.chars.ruby_stroke.as_deref() == Some(name),+ d.styles.char_style("Accent").unwrap().chars.kenten_fill.as_deref() == Some(name),+ story.tables.values().any(|t| t.cells.iter().all(|c| c.strokes.iter().all(|e| e.gap_color == name))),+ ]+ }++ #[test]+ fn renaming_a_swatch_renames_every_use_in_one_undo_step() {+ let (mut s, id, sid) = brand_doc();+ assert!(uses(&s, id, sid, "Brand").iter().all(|u| *u));+ let r = s.execute("swatch.options", &json!({"name": "Brand", "to": "Signal Orange", "spot": true})).unwrap();+ assert_eq!(r["name"], "Signal Orange");+ let d = &s.doc().unwrap().doc;+ assert!(d.swatch("Brand").is_none());+ assert!(matches!(d.swatch("Signal Orange").unwrap().value, SwatchValue::Color { color_type: designcraft_color::ColorType::Spot, .. }));+ assert_eq!(uses(&s, id, sid, "Signal Orange"), vec![true; 12]);+ s.execute("edit.undo", &json!({})).unwrap();+ assert!(s.doc().unwrap().doc.swatch("Brand").is_some());+ assert_eq!(uses(&s, id, sid, "Brand"), vec![true; 12]);+ }++ #[test]+ fn bad_swatch_renames_change_nothing() {+ let (mut s, id, sid) = brand_doc();+ let before = s.doc().unwrap().doc.clone();+ for p in [+ json!({"name": "Brand", "to": "Other"}),+ json!({"name": "Brand", "to": " "}),+ json!({"name": "Brand", "to": "[Paper]"}),+ json!({"name": "[Black]", "to": "Ink"}),+ json!({"name": "[Registration]", "to": "Reg"}),+ json!({"name": "[None]", "to": "Nothing"}),+ json!({"name": "[Black]", "color": "#ff0000"}),+ json!({"name": "Brand 50%", "color": "#ff0000"}),+ json!({"name": "Missing", "to": "X"}),+ ] {+ assert!(s.execute("swatch.options", &p).is_err(), "{p}");+ }+ assert_eq!(s.doc().unwrap().doc.swatches, before.swatches);+ assert_eq!(uses(&s, id, sid, "Brand"), vec![true; 12]);+ // [Paper]'s colour can change; its name can't.+ s.execute("swatch.options", &json!({"name": "[Paper]", "to": "[Paper]", "color": "#fff8e0"})).unwrap();+ }++ #[test]+ fn name_with_color_value_tracks_the_colour() {+ let (mut s, id, sid) = brand_doc();+ let r = s.execute("swatch.options", &json!({"name": "Brand", "nameWithValue": true, "color": {"c": 10, "m": 20, "y": 30, "k": 40}})).unwrap();+ assert_eq!(r["name"], "C=10 M=20 Y=30 K=40");+ assert_eq!(uses(&s, id, sid, "C=10 M=20 Y=30 K=40"), vec![true; 12]);+ // Later colour edits keep the name in step until the swatch is named by hand.+ let r = s.execute("swatch.options", &json!({"name": "C=10 M=20 Y=30 K=40", "color": {"c": 0, "m": 0, "y": 0, "k": 50}})).unwrap();+ assert_eq!(r["name"], "C=0 M=0 Y=0 K=50");+ let r = s.execute("swatch.options", &json!({"name": "C=0 M=0 Y=0 K=50", "to": "Warm Gray"})).unwrap();+ assert_eq!(r["name"], "Warm Gray");+ assert!(s.doc().unwrap().doc.swatch("Warm Gray").unwrap().named);+ }+}+++ #[cfg(test)]+ mod grep_style_tests {+ use serde_json::json;++ use crate::Session;++ #[test]+ fn grep_style_pattern_that_cannot_compile_is_rejected() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("style.character.create", &json!({"name": "Keep"})).unwrap();+ let bad = json!([{"style": "Keep", "pattern": "(\\d+"}]);+ let e = s.execute("style.paragraph.create", &json!({"name": "Broken", "para": {"grepStyles": bad}})).unwrap_err().to_string();+ assert!(e.contains("bad GREP") && e.contains("(\\\\d+"), "{e}");+ assert!(s.doc().unwrap().doc.styles.para("Broken").is_none());++ // The lookbehind dialect compiles.+ let good = json!([{"style": "Keep", "pattern": "(?<=\\s)[aiouwzAIOUWZ]\\s"}]);+ s.execute("style.paragraph.create", &json!({"name": "Polish", "para": {"grepStyles": good}})).unwrap();+ let e = s.execute("style.paragraph.edit", &json!({"name": "Polish", "para": {"grepStyles": bad, "spaceAfter": 6}})).unwrap_err().to_string();+ assert!(e.contains("bad GREP"), "{e}");+ let st = s.doc().unwrap().doc.styles.para("Polish").unwrap().clone();+ assert_eq!(st.para.grep_styles.unwrap()[0].pattern, "(?<=\\s)[aiouwzAIOUWZ]\\s");+ assert_eq!(st.para.space_after, None, "nothing changes");++ // A paragraph override too.+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Ala i kot"})).unwrap();+ s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();+ let e = s.execute("type.para", &json!({"grepStyles": bad})).unwrap_err().to_string();+ assert!(e.contains("bad GREP"), "{e}");+ }++ #[test]+ fn idml_import_keeps_a_broken_grep_style_and_warns() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("style.character.create", &json!({"name": "Keep"})).unwrap();+ s.execute("style.paragraph.create", &json!({"name": "Broken"})).unwrap();+ // Written past the command, as another application could.+ s.edit(|d, _| {+ if let Some(st) = d.styles_mut().para_mut("Broken") {+ st.para.grep_styles = Some(vec![designcraft_doc::GrepStyle { style: "Keep".into(), pattern: "[a-".into() }]);+ }+ Ok(())+ })+ .unwrap();+ let b64 = s.execute("file.exportIdml", &json!({})).unwrap()["base64"].as_str().unwrap().to_string();+ let r = s.execute("file.openIdml", &json!({"base64": b64})).unwrap();+ let warnings = r["warnings"].to_string();+ assert!(warnings.contains("Broken") && warnings.contains("[a-") && warnings.contains("bad GREP"), "{warnings}");+ let st = s.doc().unwrap().doc.styles.para("Broken").unwrap().clone();+ assert_eq!(st.para.grep_styles.unwrap()[0].pattern, "[a-", "the style opens with its pattern");+ }+ }diff --cc crates/ui-egui/src/dialogs.rsindex f2ea39122,10ec0f7f8..d02470009--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@@ -1946,69 -1807,18 +1946,33 @@@ pub fn confirm(app: &mut DesignApp) ->)}"paragraphStyleOptions" => {- let name = d.s("name");- let mut para = serde_json::Map::new();- let mut chars = serde_json::Map::new();- for (k, v) in &d.fields {- if let Some(a) = k.strip_prefix("p.") {- // `p.ruleAbove.weight`: one field of a rule (the command keeps the others).- match a.split_once('.') {- Some((attr, field)) => {- if let Value::Object(m) = para.entry(attr).or_insert_with(|| json!({})) {- m.insert(field.into(), v.clone());- }- }- None => {- para.insert(a.into(), v.clone());- }- }- } else if let Some(a) = k.strip_prefix("c.") {- chars.insert(a.into(), v.clone());- }- }- let based = d.s("basedOn");- let rename = d.s("rename");- let (r, style) = if d.b("new") {- let mut params = json!({"name": if rename.trim().is_empty() { "Paragraph Style 1" } else { rename.trim() }, "para": para, "chars": chars});- if !based.is_empty() && based != designcraft_doc::NO_PARA_STYLE {- params["basedOn"] = json!(based);- }- let r = app.run("style.paragraph.create", params)?;- let style = r["name"].as_str().unwrap_or_default().to_string();- (r, style)- } else {- let mut params = json!({"name": name, "para": para, "chars": chars});- if !based.is_empty() {- params["basedOn"] = if based == designcraft_doc::NO_PARA_STYLE { Value::Null } else { json!(based) };- }- if !rename.is_empty() && rename != name {- params["rename"] = json!(rename);+ let mut d = d;+ let r = confirm_paragraph_style_options(app, &mut d);+ if let Err(e) = &r {+ // Keep the dialog open with the reason, on the section it concerns.+ if e.contains("bad GREP") {+ d.fields.insert("section".into(), json!("grep"));}- let style = if !rename.is_empty() && rename != name { rename } else { name };- (app.run("style.paragraph.edit", params)?, style)- };- if d.fields.contains_key("x.tag") {- let tag = d.s("x.tag");- let tag = if tag == "[Automatic]" { String::new() } else { tag };- app.run("style.exportTag", json!({"style": style, "tag": tag, "class": d.s("x.class")}))?;+ d.fields.insert("status".into(), json!(e));+ app.ui.dialog = Some(d);}- Ok(r)+ r}+ "deleteParagraphStyle" => {+ let name = d.s("name");+ let replace = d.s("replaceWith");+ app.run(+ "style.paragraph.delete",+ json!({"name": name, "replaceWith": if replace.is_empty() { json!(designcraft_doc::BASIC_PARAGRAPH) } else { json!(replace) }}),+ )+ }+ "paragraphLocal" => {+ let attrs: Map<String, Value> = d.fields.iter().filter_map(|(k, v)| k.strip_prefix("p.").map(|a| (a.to_string(), v.clone()))).collect();+ if attrs.is_empty() {+ return Ok(Value::Null);+ }+ app.run("type.para", json!({"attrs": attrs}))+ }"paragraphRules" => {let attrs = rule_edits(&d, "");if attrs.is_empty() {@@@ -2909,890 -2670,76 +2931,895 @@@ fn paragraph_style_options(app: &mut De}});});+ // Why OK didn't apply (a pattern that can't compile, a taken name).+ let status = d.s("status");+ if !status.is_empty() {+ crate::rtl::label(ui, egui::RichText::new(status).color(crate::theme::Tokens::get(ui.ctx()).text_strong));+ }}-/// The section list on the left of the style options dialogs.-fn section_list(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, sections: &[(&str, &str)]) {- ui.vertical(|ui| {- ui.set_width(170.0);- for (id, label) in sections {- if ui.selectable_label(d.s("section") == *id, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {- d.fields.insert("section".into(), json!(id));+fn delete_paragraph_style(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {+ let name = d.s("name");+ ui.set_min_width(380.0);+ crate::rtl::label(+ ui,+ egui::RichText::new(+ crate::i18n::tr(&app.ui.language, "Delete the paragraph style \"{name}\"?")+ .replace("{name}", crate::i18n::style_name(&app.ui.language, &name)),+ )+ .size(12.5),+ );+ ui.add_space(8.0);+ let Some(st) = app.session.active() else { return };+ let in_use = st.doc.stories.values().any(|s| s.paras.iter().any(|f| f.style == name));+ let names: Vec<String> = st.doc.styles.paragraph.iter().map(|p| p.name.clone()).filter(|n| *n != name).collect();+ if in_use {+ crate::rtl::label(+ ui,+ egui::RichText::new(crate::i18n::tr(&app.ui.language, "This style is in use. Text using it will be reassigned to:"))+ .size(11.0)+ .color(crate::theme::Tokens::get(ui.ctx()).text_dim),+ );+ } else {+ crate::rtl::label(+ ui,+ egui::RichText::new(crate::i18n::tr(&app.ui.language, "Replace with:")).size(11.0).color(crate::theme::Tokens::get(ui.ctx()).text_dim),+ );+ }+ ui.add_space(4.0);+ if !d.fields.contains_key("replaceWith") {+ d.fields.insert("replaceWith".into(), json!(designcraft_doc::BASIC_PARAGRAPH));+ }+ let replace = d.s("replaceWith");+ egui::ComboBox::from_id_salt("del_para_replace")+ .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, &replace)))+ .width(260.0)+ .show_ui(ui, |ui| {+ for n in &names {+ if ui.selectable_label(*n == replace, crate::rtl::widget(ui, crate::i18n::style_name(&app.ui.language, n))).clicked() {+ d.fields.insert("replaceWith".into(), json!(n));+ }+ }+ });+}++/// Paragraph Style Options › Tabs: the style's stops on a ruler as wide as the first page's+/// column, edited in `p.tabs` (and the indents in `p.leftIndent`…) until OK.+fn style_tabs(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, doc: &designcraft_doc::Document) {+ use crate::panels::tabs::{Ruler, RulerEdit, align_buttons, ruler, text_commit};+ use designcraft_engine::cmd::tabs;+ let cur = |d: &Dialog, k: &str| d.fields.get(k).cloned().unwrap_or_else(|| pv[k.trim_start_matches("p.")].clone());+ let mut list: Vec<designcraft_doc::TabStop> = serde_json::from_value(cur(d, "p.tabs")).unwrap_or_default();+ tabs::sort(&mut list);+ let num = |d: &Dialog, k: &str| cur(d, k).as_f64().filter(|v| v.is_finite()).unwrap_or(0.0);+ let (left, first, right) = (num(d, "p.leftIndent"), num(d, "p.firstLineIndent"), num(d, "p.rightIndent"));+ let width = doc.page(0).and_then(|p| p.column_rects().first().map(|r| r.width())).filter(|w| *w > 1.0).unwrap_or(468.0);+ let unit = doc.settings.horizontal_units;+ let mut sel = d.fields.get("tabsSelected").and_then(Value::as_u64).map(|i| i as usize).filter(|i| *i < list.len());+ let mut align = d.fields.get("tabsAlign").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default();+ let stop = sel.and_then(|i| list.get(i)).cloned();+ // Each control's edit, applied to the list below.+ let mut result: Option<Result<Option<usize>, String>> = None;+ let mut indent: Option<(&str, f64)> = None;+ ui.horizontal(|ui| {+ ui.spacing_mut().item_spacing.x = 4.0;+ if let Some(a) = align_buttons(ui, lang, stop.as_ref().map_or(align, |s| s.align)) {+ align = a;+ if let Some(i) = sel {+ result = Some(tabs::change(&mut list, i, Some(a), None, None));}}+ ui.add_space(6.0);+ crate::rtl::label(ui, crate::i18n::tr(lang, "X:"));+ if let Some(x) = crate::widgets::measure(ui, "pstabx", stop.as_ref().map(|s| s.position), unit, 72.0) {+ result = Some(match sel {+ Some(i) => tabs::move_to(&mut list, i, x),+ None => tabs::add(&mut list, designcraft_doc::TabStop { position: x, align, leader: String::new(), align_on: String::new() }),+ });+ }+ crate::rtl::label(ui, crate::i18n::tr(lang, "Leader:"));+ if let (Some(l), Some(i)) = (text_commit(ui, "psleader", stop.as_ref().map_or("", |s| s.leader.as_str()), 36.0, stop.is_some()), sel) {+ result = Some(tabs::leader_value(&l, "tabs").map_err(|e| e.to_string()).and_then(|l| tabs::change(&mut list, i, None, Some(l), None)));+ }+ crate::rtl::label(ui, crate::i18n::tr(lang, "Align On:"));+ let on_char = stop.as_ref().is_some_and(|s| s.align == designcraft_doc::TabAlign::Char);+ if let (Some(c), Some(i)) = (text_commit(ui, "psalignon", stop.as_ref().map_or("", |s| s.align_on.as_str()), 18.0, on_char), sel) {+ result = Some(tabs::align_on_value(&c, "tabs").map_err(|e| e.to_string()).and_then(|c| tabs::change(&mut list, i, None, None, Some(c))));+ }+ ui.add_space(6.0);+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(lang, "Clear All"))).clicked() {+ list.clear();+ result = Some(Ok(None));+ }});+ ui.add_space(6.0);+ let r = Ruler { tabs: &list, left, first, right, width, unit, selected: sel, scale: None };+ match ruler(ui, "style", &r) {+ Some(RulerEdit::Select(i)) => sel = Some(i),+ Some(RulerEdit::Add(x)) => {+ result = Some(tabs::add(&mut list, designcraft_doc::TabStop { position: x, align, leader: String::new(), align_on: String::new() }))+ }+ Some(RulerEdit::Move(i, x)) => result = Some(tabs::move_to(&mut list, i, x)),+ Some(RulerEdit::Remove(i)) => result = Some(tabs::remove(&mut list, i)),+ Some(RulerEdit::Indent(k, x)) => indent = Some((k, x)),+ None => {}+ }+ match result {+ Some(Ok(i)) => {+ sel = i;+ d.fields.insert("p.tabs".into(), serde_json::to_value(&list).unwrap_or_default());+ d.fields.remove("status");+ }+ Some(Err(e)) => {+ d.fields.insert("status".into(), json!(e));+ }+ None => {}+ }+ if let Some((k, x)) = indent {+ d.fields.insert(format!("p.{k}"), json!(x));+ }+ d.fields.insert("tabsSelected".into(), sel.map_or(Value::Null, |i| json!(i)));+ d.fields.insert("tabsAlign".into(), serde_json::to_value(align).unwrap_or_default());}-/// "Paragraph Style n" / "Character Style n": the first name no style has.-fn next_style_name(styles: &designcraft_doc::Styles, para: bool) -> String {- let (base, count) = if para { ("Paragraph Style", styles.paragraph.len()) } else { ("Character Style", styles.character.len()) };- let taken = |n: &str| if para { styles.para(n).is_some() } else { styles.char_style(n).is_some() };- // Among count + 1 numbers at least one is free.- (1..=count + 1).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_else(|| format!("{base} {}", count + 1))+/// A paragraph attribute as Paragraph Style Options shows it: the dialog's edit (`p.<key>`), else+/// the style's resolved value in `pv`.+fn para_value(d: &Dialog, pv: &Value, key: &str) -> Value {+ d.fields.get(&format!("p.{key}")).cloned().unwrap_or_else(|| pv.get(key).cloned().unwrap_or(Value::Null))}-/// Paragraph or Character Style Options for an existing style (a double-click on it in the styles-/// panel, or Edit in its menu). [None] and [No Paragraph Style] have no options.-pub fn open_style_options(app: &mut DesignApp, para: bool, name: &str) {- if name == if para { designcraft_doc::NO_PARA_STYLE } else { designcraft_doc::NO_CHAR_STYLE } {- return;+/// Edit paragraph attribute `key`. The value is the whole attribute: `confirm` reads a dotted key+/// as one field of a rule.+fn para_set(d: &mut Dialog, key: &str, v: Value) {+ d.fields.insert(format!("p.{key}"), v);+}++/// A count attribute (lines, columns), rounded and kept in `range`.+fn para_count(ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, range: (u32, u32)) {+ let v = para_value(d, pv, key).as_f64();+ if let Some(n) = crate::widgets::number(ui, &format!("ps{key}"), v, "", 50.0, 0) {+ let n = if n.is_finite() { n.round().clamp(f64::from(range.0), f64::from(range.1)) as u32 } else { range.0 };+ para_set(d, key, json!(n));}- let id = if para { "paragraphStyleOptions" } else { "characterStyleOptions" };- app.ui.dialog = Some(Dialog::new(id, json!({"name": name})));}-/// New Paragraph Style… / New Character Style…: the style options for a style made on OK, named-/// with the next free "Paragraph Style n" / "Character Style n".-pub fn open_new_style(app: &mut DesignApp, para: bool) {- let Some(st) = app.session.active() else { return };- let name = next_style_name(&st.doc.styles, para);- let id = if para { "paragraphStyleOptions" } else { "characterStyleOptions" };- app.ui.dialog = Some(Dialog::new(id, json!({"new": true, "rename": name})));+fn para_check(ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, label: &str) {+ let mut on = para_value(d, pv, key).as_bool().unwrap_or(false);+ if ui.checkbox(&mut on, crate::rtl::widget(ui, label)).changed() {+ para_set(d, key, json!(on));+ }}-/// Character Style Options: General, then the character sections it shares with Paragraph Style-/// Options. A character style sets only some attributes: the fields show those it and its Based-/// On set and leave the rest blank. Edits are `c.<attr>` fields (`null` = no longer set), applied-/// on OK; `new` makes the style instead of editing `name`.-fn character_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {- let name = d.s("name");- let new = d.b("new");- let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return };- let styles = &doc.styles;- let style = match styles.char_style(&name) {- _ if new => designcraft_doc::CharacterStyle { name: String::new(), based_on: None, chars: Default::default(), shortcut: String::new() },- Some(s) if name != designcraft_doc::NO_CHAR_STYLE => s.clone(),- _ => {- crate::rtl::label(ui, format!("No style named {name}"));- return;+fn para_measure(ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, unit: Unit) {+ let v = para_value(d, pv, key).as_f64();+ if let Some(n) = crate::widgets::measure(ui, &format!("ps{key}"), v, unit, 80.0) {+ para_set(d, key, json!(n));+ }+}++/// A paragraph attribute chosen from `opts` (serialized value, label).+fn para_choice(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, opts: &[(&str, &str)]) {+ let cur = para_value(d, pv, key);+ let shown = opts.iter().find(|o| cur == o.0).map_or("", |o| crate::i18n::tr(lang, o.1));+ egui::ComboBox::from_id_salt(("pschoice", key)).selected_text(crate::rtl::widget(ui, shown)).width(200.0).show_ui(ui, |ui| {+ for (v, label) in opts {+ if ui.selectable_label(cur == *v, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {+ para_set(d, key, json!(v));+ }}- };- if !d.fields.contains_key("rename") {- d.fields.insert("rename".into(), json!(if new { next_style_name(styles, false) } else { name.clone() }));+ });+}++/// Four per-side values in the order the attribute holds them: top, left, bottom, right. An+/// edited side stores the whole array.+fn para_sides(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, field: &dyn Fn(&mut egui::Ui, &str, Option<f64>) -> Option<f64>) {+ let mut sides: [f64; 4] = serde_json::from_value(para_value(d, pv, key)).unwrap_or_default();+ let mut changed = false;+ egui::Grid::new(("pssides", key)).num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {+ for (i, label) in ["Top:", "Left:", "Bottom:", "Right:"].into_iter().enumerate() {+ crate::rtl::label(ui, crate::i18n::tr(lang, label));+ if let Some(side) = sides.get_mut(i)+ && let Some(v) = field(ui, &format!("ps{key}{i}"), Some(*side))+ {+ *side = v;+ changed = true;+ }+ if i % 2 == 1 {+ ui.end_row();+ }+ }+ });+ if changed {+ para_set(d, key, json!(sides));}- let based = d- .fields- .get("basedOn")- .and_then(Value::as_str)+}++/// A swatch menu with a colour chip per swatch (hidden swatches left out); returns the swatch+/// picked.+fn swatch_menu(ui: &mut egui::Ui, doc: &designcraft_doc::Document, id: impl egui::AsIdSalt, current: &str, width: f32) -> Option<String> {+ let mut picked = None;+ egui::ComboBox::from_id_salt(id).selected_text(current).width(width).show_ui(ui, |ui| {+ for w in doc.swatches.iter().filter(|w| !w.hidden) {+ let (c, g) = crate::widgets::swatch_colors(doc, &w.name, 1.0);+ ui.horizontal(|ui| {+ let (r, _) = ui.allocate_exact_size(egui::vec2(12.0, 12.0), egui::Sense::hover());+ crate::widgets::paint_chip(ui.painter(), r, c, g);+ if ui.selectable_label(w.name == current, &w.name).clicked() {+ picked = Some(w.name.clone());+ }+ });+ }+ });+ picked+}++/// Built-in stroke types of the paragraph border's Type menu (serialized `StrokeType`s).+const BORDER_TYPES: [&str; 11] =+ ["solid", "dashed", "dotted", "thickThin", "thinThick", "thinThin", "thickThick", "thinThickThin", "thickThinThick", "wavy", "hashed"];++/// The border's stroke type: a built-in type or one of the document's stroke styles.+fn border_type_menu(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, doc: &designcraft_doc::Document) {+ use designcraft_doc::StrokeType;+ let cur: StrokeType = serde_json::from_value(para_value(d, pv, "borderType")).unwrap_or_default();+ let shown = match &cur {+ StrokeType::Style { name } => name.clone(),+ k => crate::i18n::tr(lang, k.label()).to_string(),+ };+ egui::ComboBox::from_id_salt("psbordertype").selected_text(crate::rtl::widget(ui, shown)).width(160.0).show_ui(ui, |ui| {+ for k in BORDER_TYPES {+ let ty = if k == "dashed" { json!({"kind": k, "pattern": []}) } else { json!({"kind": k}) };+ let Ok(t) = serde_json::from_value::<StrokeType>(ty.clone()) else { continue };+ let on = std::mem::discriminant(&t) == std::mem::discriminant(&cur);+ if ui.selectable_label(on, crate::rtl::widget(ui, crate::i18n::tr(lang, t.label()))).clicked() && !on {+ para_set(d, "borderType", ty);+ }+ }+ for st in &doc.stroke_styles {+ let on = matches!(&cur, StrokeType::Style { name } if *name == st.name);+ if ui.selectable_label(on, &st.name).clicked() {+ para_set(d, "borderType", json!({"kind": "style", "name": st.name}));+ }+ }+ });+}++/// Corner size and shape of a border or shading (`key` holds top left, top right, bottom right,+/// bottom left); an edited corner stores all four.+fn para_corners(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, units: Unit) {+ use designcraft_geom::corners::{Corner, CornerShape};+ let mut corners: [Corner; 4] = serde_json::from_value(para_value(d, pv, key)).unwrap_or_default();+ let mut changed = false;+ egui::Grid::new(("pscorners", key)).num_columns(3).spacing([8.0, 6.0]).show(ui, |ui| {+ for (i, label) in ["Top Left:", "Top Right:", "Bottom Right:", "Bottom Left:"].into_iter().enumerate() {+ let Some(c) = corners.get_mut(i) else { continue };+ crate::rtl::label(ui, crate::i18n::tr(lang, label));+ if let Some(v) = crate::widgets::measure(ui, &format!("ps{key}{i}"), Some(c.size), units, 70.0) {+ c.size = if v.is_finite() { v.clamp(0.0, 10_000.0) } else { 0.0 };+ changed = true;+ }+ egui::ComboBox::from_id_salt(("pscornershape", key, i))+ .selected_text(crate::rtl::widget(ui, crate::i18n::tr(lang, c.shape.label())))+ .width(130.0)+ .show_ui(ui, |ui| {+ for shape in CornerShape::ALL {+ if ui.selectable_label(c.shape == shape, crate::rtl::widget(ui, crate::i18n::tr(lang, shape.label()))).clicked() {+ c.shape = shape;+ changed = true;+ }+ }+ });+ ui.end_row();+ }+ });+ if changed {+ para_set(d, key, serde_json::to_value(corners).unwrap_or_default());+ }+}++/// The colour and tint rows of a border, its gap or shading (`keys`: colour, tint), in a grid.+fn para_color_tint(+ ui: &mut egui::Ui,+ d: &mut Dialog,+ pv: &Value,+ doc: &designcraft_doc::Document,+ keys: (&str, &str),+ labels: (&str, &str),+ enabled: bool,+) {+ let (color_key, tint_key) = keys;+ crate::rtl::label(ui, labels.0);+ let color = para_value(d, pv, color_key).as_str().unwrap_or("").to_string();+ if let Some(w) = ui.add_enabled_ui(enabled, |ui| swatch_menu(ui, doc, ("pscolor", color_key), &color, 160.0)).inner {+ para_set(d, color_key, json!(w));+ }+ ui.end_row();+ crate::rtl::label(ui, labels.1);+ let tint = para_value(d, pv, tint_key).as_f64().map(|t| t * 100.0);+ if let Some(v) = ui.add_enabled_ui(enabled, |ui| crate::widgets::number(ui, &format!("ps{tint_key}"), tint, "%", 60.0, 0)).inner {+ para_set(d, tint_key, json!(if v.is_finite() { (v / 100.0).clamp(0.0, 1.0) } else { 1.0 }));+ }+ ui.end_row();+}++/// Paragraph Style Options › Paragraph Border / Paragraph Shading (and the Paragraph Borders and+/// Shading dialog): on or off, the stroke (border) or colour (shading), corners, offsets, the+/// edges and width the box follows, and the options for split and consecutive paragraphs.+fn border_shading(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, doc: &designcraft_doc::Document, border: bool) {+ let key = |field: &str| format!("{}{field}", if border { "border" } else { "shading" });+ let on_key = key("On");+ para_check(ui, d, pv, &on_key, crate::i18n::tr(lang, if border { "Border" } else { "Shading" }));+ let on = para_value(d, pv, &on_key).as_bool().unwrap_or(false);+ let units = doc.settings.horizontal_units;+ let head = |ui: &mut egui::Ui, t: &str| {+ ui.add_space(4.0);+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(lang, t)).font(semibold(12.0)));+ };+ ui.add_space(4.0);+ egui::ScrollArea::vertical().id_salt(("psbsscroll", border)).max_height(330.0).show(ui, |ui| {+ ui.add_enabled_ui(on, |ui| {+ if border {+ head(ui, "Stroke");+ para_sides(lang, ui, d, pv, &key("Weights"), &|ui: &mut egui::Ui, id: &str, v: Option<f64>| {+ crate::widgets::number(ui, id, v, " pt", 60.0, 2).map(|w| if w.is_finite() { w.clamp(0.0, 1000.0) } else { 0.0 })+ });+ ui.add_space(4.0);+ } else {+ head(ui, "Color");+ }+ egui::Grid::new(("psbs", border)).num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ if border {+ crate::rtl::label(ui, crate::i18n::tr(lang, "Type:"));+ border_type_menu(lang, ui, d, pv, doc);+ ui.end_row();+ }+ let (color, tint) = (crate::i18n::tr(lang, "Color:"), crate::i18n::tr(lang, "Tint:"));+ para_color_tint(ui, d, pv, doc, (&key("Color"), &key("Tint")), (color, tint), true);+ if border {+ // The gap colour shows between the dashes, dots or stripes.+ let solid = para_value(d, pv, "borderType").get("kind").and_then(Value::as_str).is_none_or(|k| k == "solid");+ let (gap, gap_tint) = (crate::i18n::tr(lang, "Gap Color:"), crate::i18n::tr(lang, "Gap Tint:"));+ para_color_tint(ui, d, pv, doc, ("borderGapColor", "borderGapTint"), (gap, gap_tint), !solid);+ crate::rtl::label(ui, crate::i18n::tr(lang, "Cap:"));+ para_choice(lang, ui, d, pv, "borderCap", &[("butt", "Butt"), ("round", "Round"), ("projecting", "Projecting")]);+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Join:"));+ para_choice(lang, ui, d, pv, "borderJoin", &[("miter", "Miter"), ("round", "Round"), ("bevel", "Bevel")]);+ ui.end_row();+ }+ });+ head(ui, "Corner Size and Shape");+ para_corners(lang, ui, d, pv, &key("Corners"), units);+ head(ui, "Offsets");+ para_sides(lang, ui, d, pv, &key("Offsets"), &|ui: &mut egui::Ui, id: &str, v: Option<f64>| {+ crate::widgets::measure(ui, id, v, units, 60.0)+ });+ ui.add_space(4.0);+ egui::Grid::new(("psbsedges", border)).num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(lang, "Top Edge:"));+ para_choice(+ lang,+ ui,+ d,+ pv,+ &key("Top"),+ &[("ascent", "Ascent"), ("baseline", "Baseline"), ("emBox", "Em Box Top"), ("leading", "Leading")],+ );+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Bottom Edge:"));+ para_choice(lang, ui, d, pv, &key("Bottom"), &[("descent", "Descent"), ("baseline", "Baseline"), ("emBox", "Em Box Bottom")]);+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Width:"));+ para_choice(lang, ui, d, pv, &key("Width"), &[("column", "Column"), ("text", "Text")]);+ ui.end_row();+ });+ ui.add_space(4.0);+ if border {+ para_check(ui, d, pv, "borderDisplayIfSplits", crate::i18n::tr(lang, "Display Border if Paragraph Splits Across Frames/Columns"));+ para_check(ui, d, pv, "borderMerge", crate::i18n::tr(lang, "Merge Consecutive Borders and Shading"));+ } else {+ para_check(ui, d, pv, "shadingClip", crate::i18n::tr(lang, "Clip to Frame"));+ para_check(ui, d, pv, "shadingNonprinting", crate::i18n::tr(lang, "Do not Print or Export"));+ }+ });+ });+}++/// Paragraph Style Options › Keep Options: lines kept with the next paragraph, the paragraph's+/// lines kept together (all of them, or its first and last lines), and where it starts.+fn keep_options(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value) {+ ui.horizontal(|ui| {+ crate::rtl::label(ui, crate::i18n::tr(lang, "Keep with Next:"));+ para_count(ui, d, pv, "keepWithNext", (0, 5));+ crate::rtl::label(ui, crate::i18n::tr(lang, "lines"));+ });+ ui.add_space(4.0);+ para_check(ui, d, pv, "keepLinesTogether", crate::i18n::tr(lang, "Keep Lines Together"));+ let together = para_value(d, pv, "keepLinesTogether").as_bool().unwrap_or(false);+ ui.add_enabled_ui(together, |ui| {+ ui.indent("pskeepall", |ui| {+ let all = para_value(d, pv, "keepAllLines").as_bool().unwrap_or(true);+ if ui.radio(all, crate::rtl::widget(ui, crate::i18n::tr(lang, "All Lines in Paragraph"))).clicked() {+ para_set(d, "keepAllLines", json!(true));+ }+ if ui.radio(!all, crate::rtl::widget(ui, crate::i18n::tr(lang, "At Start/End of Paragraph"))).clicked() {+ para_set(d, "keepAllLines", json!(false));+ }+ ui.add_enabled_ui(!all, |ui| {+ egui::Grid::new("pskeepends").num_columns(3).spacing([8.0, 6.0]).show(ui, |ui| {+ for (label, key) in [("Start:", "keepFirst"), ("End:", "keepLast")] {+ crate::rtl::label(ui, crate::i18n::tr(lang, label));+ para_count(ui, d, pv, key, (1, 50));+ crate::rtl::label(ui, crate::i18n::tr(lang, "lines"));+ ui.end_row();+ }+ });+ });+ });+ });+ ui.add_space(6.0);+ ui.horizontal(|ui| {+ crate::rtl::label(ui, crate::i18n::tr(lang, "Start Paragraph:"));+ para_choice(+ lang,+ ui,+ d,+ pv,+ "startParagraph",+ &[+ ("anywhere", "Anywhere"),+ ("nextColumn", "In Next Column"),+ ("nextFrame", "In Next Frame"),+ ("nextPage", "On Next Page"),+ ("nextOddPage", "On Next Odd Page"),+ ("nextEvenPage", "On Next Even Page"),+ ],+ );+ });+}++/// Paragraph Style Options › Span Columns (and the Span Columns dialog): one column, spanning+/// columns (0 = all), or split into sub-columns with inside and outside gutters; the least space+/// before and after a spanning or split paragraph.+fn span_columns(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, doc: &designcraft_doc::Document) {+ use designcraft_doc::SpanColumns;+ let cur: SpanColumns = serde_json::from_value(para_value(d, pv, "spanColumns")).unwrap_or_default();+ let same = |a: &SpanColumns, b: &SpanColumns| std::mem::discriminant(a) == std::mem::discriminant(b);+ let units = doc.settings.horizontal_units;+ let mut next = None;+ egui::Grid::new("psspan").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(lang, "Paragraph Layout:"));+ let kinds = [("Single Column", SpanColumns::Single), ("Span Columns", SpanColumns::Span(0)), ("Split Column", SpanColumns::Split(2))];+ // "Span Columns" names both the section and this option, which some languages word differently.+ let kind_label = |k: &'static str| -> &'static str { crate::i18n::tr_context(lang, k, "paragraphLayout") };+ let shown = kinds.iter().find(|k| same(&k.1, &cur)).map_or("", |k| kind_label(k.0));+ egui::ComboBox::from_id_salt("psspankind").selected_text(crate::rtl::widget(ui, shown)).width(200.0).show_ui(ui, |ui| {+ for (label, v) in kinds {+ if ui.selectable_label(same(&v, &cur), crate::rtl::widget(ui, kind_label(label))).clicked() && !same(&v, &cur) {+ next = Some(v);+ }+ }+ });+ ui.end_row();+ match cur {+ SpanColumns::Single => {}+ SpanColumns::Span(n) => {+ crate::rtl::label(ui, crate::i18n::tr(lang, "Columns:"));+ let shown = if n == 0 { crate::i18n::tr(lang, "All").to_string() } else { n.to_string() };+ egui::ComboBox::from_id_salt("psspann").selected_text(crate::rtl::widget(ui, shown)).width(80.0).show_ui(ui, |ui| {+ if ui.selectable_label(n == 0, crate::rtl::widget(ui, crate::i18n::tr(lang, "All"))).clicked() {+ next = Some(SpanColumns::Span(0));+ }+ for c in 2..=20u32 {+ if ui.selectable_label(n == c, c.to_string()).clicked() {+ next = Some(SpanColumns::Span(c));+ }+ }+ });+ ui.end_row();+ }+ SpanColumns::Split(n) => {+ crate::rtl::label(ui, crate::i18n::tr(lang, "Columns:"));+ if let Some(c) = crate::widgets::number(ui, "pssplitn", Some(f64::from(n)), "", 50.0, 0) {+ next = Some(SpanColumns::Split(if c.is_finite() { c.round().clamp(2.0, 20.0) as u32 } else { 2 }));+ }+ ui.end_row();+ }+ }+ let v_units = doc.settings.vertical_units;+ let spaces = match cur {+ SpanColumns::Single => None,+ SpanColumns::Span(_) => Some(("Space Before Span:", "Space After Span:")),+ SpanColumns::Split(_) => Some(("Space Before Split:", "Space After Split:")),+ };+ if let Some((before, after)) = spaces {+ for (label, key) in [(before, "spanSpaceBefore"), (after, "spanSpaceAfter")] {+ crate::rtl::label(ui, crate::i18n::tr(lang, label));+ para_measure(ui, d, pv, key, v_units);+ ui.end_row();+ }+ }+ if matches!(cur, SpanColumns::Split(_)) {+ for (label, key) in [("Inside Gutter:", "splitInsideGutter"), ("Outside Gutter:", "splitOutsideGutter")] {+ crate::rtl::label(ui, crate::i18n::tr(lang, label));+ para_measure(ui, d, pv, key, units);+ ui.end_row();+ }+ }+ });+ if let Some(v) = next {+ para_set(d, "spanColumns", serde_json::to_value(v).unwrap_or_default());+ }+}++/// Number styles as the list's Format menu shows them (`NumberStyle` values).+const NUMBER_STYLES: [(&str, &str); 9] = [+ ("arabic", "1, 2, 3, 4..."),+ ("upperRoman", "I, II, III, IV..."),+ ("lowerRoman", "i, ii, iii, iv..."),+ ("upperLetters", "A, B, C, D..."),+ ("lowerLetters", "a, b, c, d..."),+ ("arabicLeadingZero", "01, 02, 03..."),+ ("arabicThreeDigits", "001, 002, 003..."),+ ("arabicFourDigits", "0001, 0002, 0003..."),+ ("symbols", "*, †, ‡, §..."),+];++/// A list label text (Text After, Number), shown with its tab as `^t`; labels expand+/// metacharacters, so the typed text is stored as it is.+fn list_text(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, label: &str, key: &str) {+ crate::rtl::label(ui, crate::i18n::tr(lang, label));+ let mut s = para_value(d, pv, key).as_str().unwrap_or("").replace('\t', "^t");+ if ui.add(egui::TextEdit::singleline(&mut s).desired_width(160.0)).changed() {+ para_set(d, key, json!(s));+ }+ ui.end_row();+}++/// What the Bullets and Numbering section offers besides the paragraph's attributes: the+/// document's character styles, the font families for the bullet, the fonts, and the paragraph's+/// font (the bullet's when it has none of its own).+struct ListUi<'a> {+ char_styles: &'a [String],+ families: &'a [String],+ fonts: &'a designcraft_fonts::ScopedFonts<'static>,+ scope: u32,+ family: &'a str,+ style: &'a str,+}++impl ListUi<'_> {+ fn new_parts(app: &DesignApp) -> (Vec<String>, Vec<String>, designcraft_fonts::ScopedFonts<'static>, u32) {+ let styles = app.session.active().map(|s| s.doc.styles.character.iter().map(|c| c.name.clone()).collect()).unwrap_or_default();+ let families = crate::panels::font_menu(app).into_iter().map(|f| f.family).collect();+ (styles, families, crate::panels::fonts(app), crate::panels::font_scope(app))+ }+}++/// A character style for a bullet or number (`key`), [None] first.+fn list_char_style(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, styles: &[String]) {+ let cur = para_value(d, pv, key).as_str().unwrap_or(designcraft_doc::NO_CHAR_STYLE).to_string();+ egui::ComboBox::from_id_salt(("pslistcs", key)).selected_text(crate::rtl::widget(ui, crate::i18n::style_name(lang, &cur))).width(200.0).show_ui(+ ui,+ |ui| {+ for n in std::iter::once(designcraft_doc::NO_CHAR_STYLE)+ .chain(styles.iter().map(String::as_str).filter(|n| *n != designcraft_doc::NO_CHAR_STYLE))+ {+ if ui.selectable_label(n == cur, crate::rtl::widget(ui, crate::i18n::style_name(lang, n))).clicked() {+ para_set(d, key, json!(n));+ }+ }+ },+ );+}++/// The bullet character: common bullets, a field, and the font's glyphs in a grid to pick from.+fn bullet_char(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, lu: &ListUi<'_>) {+ crate::rtl::label(ui, crate::i18n::tr(lang, "Bullet Character:"));+ ui.horizontal(|ui| {+ let cur = para_value(d, pv, "bulletChar").as_str().unwrap_or("").to_string();+ for b in ["\u{2022}", "\u{2013}", "\u{2014}", "\u{00BB}", "*"] {+ if ui.add_sized([24.0, 20.0], egui::Button::selectable(cur == b, b)).clicked() {+ para_set(d, "bulletChar", json!(b));+ }+ }+ let mut s = cur;+ if ui.add(egui::TextEdit::singleline(&mut s).desired_width(36.0)).changed() {+ para_set(d, "bulletChar", json!(s));+ }+ let open = d.b("bulletGlyphs");+ if ui.selectable_label(open, crate::rtl::widget(ui, crate::i18n::tr(lang, "Glyphs…"))).clicked() {+ d.fields.insert("bulletGlyphs".into(), json!(!open));+ }+ });+ ui.end_row();+ if d.b("bulletGlyphs") {+ ui.label("");+ ui.vertical(|ui| {+ ui.set_width(300.0);+ let font = para_value(d, pv, "bulletFont").as_str().unwrap_or("").to_string();+ let (family, style) = if font.is_empty() {+ (lu.family.to_string(), lu.style.to_string())+ } else {+ let st = para_value(d, pv, "bulletFontStyle").as_str().unwrap_or("").to_string();+ let st = if st.is_empty() { lu.fonts.styles(&font).into_iter().next().unwrap_or_else(|| "Regular".into()) } else { st };+ (font, st)+ };+ let mut q = d.s("bulletGlyphQuery");+ if ui+ .add(+ egui::TextEdit::singleline(&mut q)+ .hint_text(crate::rtl::widget(ui, crate::i18n::tr(lang, "Search: character or U+code")))+ .desired_width(300.0),+ )+ .changed()+ {+ d.fields.insert("bulletGlyphQuery".into(), json!(q));+ }+ if let (Some(c), _) = crate::panels::glyphs::grid(ui, lu.fonts, lu.scope, &family, &style, &q, 160.0) {+ para_set(d, "bulletChar", json!(c.to_string()));+ }+ });+ ui.end_row();+ }+}++/// The bullet's font family and style ("" = the paragraph's).+fn bullet_font(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, lu: &ListUi<'_>) {+ let font = para_value(d, pv, "bulletFont").as_str().unwrap_or("").to_string();+ let inherit = crate::i18n::tr(lang, "(Paragraph Font)");+ crate::rtl::label(ui, crate::i18n::tr(lang, "Font Family:"));+ egui::ComboBox::from_id_salt("psbulletfont").selected_text(if font.is_empty() { inherit } else { font.as_str() }).width(200.0).show_ui(+ ui,+ |ui| {+ if ui.selectable_label(font.is_empty(), inherit).clicked() {+ para_set(d, "bulletFont", json!(""));+ para_set(d, "bulletFontStyle", json!(""));+ }+ for f in lu.families {+ if ui.selectable_label(*f == font, f).clicked() {+ para_set(d, "bulletFont", json!(f));+ para_set(d, "bulletFontStyle", json!(lu.fonts.styles(f).into_iter().next().unwrap_or_default()));+ }+ }+ },+ );+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Font Style:"));+ let style = para_value(d, pv, "bulletFontStyle").as_str().unwrap_or("").to_string();+ ui.add_enabled_ui(!font.is_empty(), |ui| {+ egui::ComboBox::from_id_salt("psbulletstyle").selected_text(style.as_str()).width(200.0).show_ui(ui, |ui| {+ for st in lu.fonts.styles(&font) {+ if ui.selectable_label(st == style, &st).clicked() {+ para_set(d, "bulletFontStyle", json!(st));+ }+ }+ });+ });+ ui.end_row();+}++/// Paragraph Style Options › Bullets and Numbering (and the Bullets and Numbering dialog): the+/// list type and level; the bullet, its font and the text after it, or the list, number style,+/// number text and where numbering starts and restarts; the label's character style; then where+/// the label goes (alignment, indents and the tab position of the text after it).+fn bullets_and_numbering(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, doc: &designcraft_doc::Document, lu: &ListUi<'_>) {+ let units = doc.settings.horizontal_units;+ let kind = para_value(d, pv, "listType").as_str().unwrap_or("none").to_string();+ let level = para_value(d, pv, "listLevel").as_u64().unwrap_or(1).clamp(1, designcraft_doc::LIST_LEVELS as u64) as u32;+ egui::ScrollArea::vertical().id_salt("psbnscroll").max_height(340.0).show(ui, |ui| {+ egui::Grid::new("psbn").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(lang, "List Type:"));+ para_choice(lang, ui, d, pv, "listType", &[("none", "None"), ("bullets", "Bullets"), ("numbers", "Numbers")]);+ ui.end_row();+ if kind != "none" {+ crate::rtl::label(ui, crate::i18n::tr(lang, "Level:"));+ para_count(ui, d, pv, "listLevel", (1, designcraft_doc::LIST_LEVELS as u32));+ ui.end_row();+ }+ match kind.as_str() {+ "bullets" => {+ bullet_char(lang, ui, d, pv, lu);+ bullet_font(lang, ui, d, pv, lu);+ list_text(lang, ui, d, pv, "Text After:", "listSeparator");+ crate::rtl::label(ui, crate::i18n::tr(lang, "Character Style:"));+ list_char_style(lang, ui, d, pv, "bulletCharStyle", lu.char_styles);+ ui.end_row();+ }+ "numbers" => {+ crate::rtl::label(ui, crate::i18n::tr(lang, "List:"));+ let list = para_value(d, pv, "listName").as_str().unwrap_or("").to_string();+ // "" is the story's own list.+ let name = |n: &str| if n.is_empty() { crate::i18n::tr(lang, "[Default]").to_string() } else { n.to_string() };+ egui::ComboBox::from_id_salt("pslist").selected_text(name(&list)).width(200.0).show_ui(ui, |ui| {+ for n in std::iter::once("").chain(doc.settings.lists.iter().map(|l| l.name.as_str())) {+ if ui.selectable_label(n == list, name(n)).clicked() {+ para_set(d, "listName", json!(n));+ }+ }+ });+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Format:"));+ para_choice(lang, ui, d, pv, "numberStyle", &NUMBER_STYLES);+ ui.end_row();+ list_text(lang, ui, d, pv, "Number:", "numberExpression");+ crate::rtl::label(ui, crate::i18n::tr(lang, "Character Style:"));+ list_char_style(lang, ui, d, pv, "numberCharStyle", lu.char_styles);+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(lang, "Mode:"));+ let start = para_value(d, pv, "startAt").as_u64();+ ui.horizontal(|ui| {+ let shown = crate::i18n::tr(lang, if start.is_some() { "Start At" } else { "Continue from Previous Number" });+ egui::ComboBox::from_id_salt("psmode").selected_text(crate::rtl::widget(ui, shown)).width(200.0).show_ui(ui, |ui| {+ if ui+ .selectable_label(start.is_none(), crate::rtl::widget(ui, crate::i18n::tr(lang, "Continue from Previous Number")))+ .clicked()+ {+ para_set(d, "startAt", Value::Null);+ }+ if ui.selectable_label(start.is_some(), crate::rtl::widget(ui, crate::i18n::tr(lang, "Start At"))).clicked()+ && start.is_none()+ {+ para_set(d, "startAt", json!(1));+ }+ });+ if let Some(n) = start+ && let Some(v) = crate::widgets::number(ui, "psstartat", Some(n as f64), "", 60.0, 0)+ {+ para_set(d, "startAt", json!(if v.is_finite() { v.round().clamp(0.0, 1_000_000.0) as u32 } else { 1 }));+ }+ });+ ui.end_row();+ // Restart Numbers at This Level After: a higher level (any, or one of them).+ ui.label("");+ ui.add_enabled_ui(level > 1, |ui| {+ ui.horizontal(|ui| {+ para_check(ui, d, pv, "restartNumbers", crate::i18n::tr(lang, "Restart Numbers at This Level After:"));+ let after = para_value(d, pv, "restartAfterLevel").as_u64().unwrap_or(0) as u32;+ let label = |n: u32| if n == 0 { crate::i18n::tr(lang, "Any Previous Level").to_string() } else { n.to_string() };+ egui::ComboBox::from_id_salt("psrestartafter").selected_text(crate::rtl::widget(ui, label(after))).width(140.0).show_ui(+ ui,+ |ui| {+ for n in 0..level {+ if ui.selectable_label(n == after, crate::rtl::widget(ui, label(n))).clicked() {+ para_set(d, "restartAfterLevel", json!(n));+ }+ }+ },+ );+ });+ });+ ui.end_row();+ }+ _ => {}+ }+ if kind != "none" {+ crate::rtl::label(ui, crate::i18n::tr(lang, "Alignment:"));+ let key = if kind == "bullets" { "bulletAlign" } else { "numberAlign" };+ para_choice(lang, ui, d, pv, key, &[("left", "Left"), ("center", "Center"), ("right", "Right")]);+ ui.end_row();+ for (label, key) in [("Left Indent:", "leftIndent"), ("First Line Indent:", "firstLineIndent")] {+ crate::rtl::label(ui, crate::i18n::tr(lang, label));+ para_measure(ui, d, pv, key, units);+ ui.end_row();+ }+ // Tab Position: none, or a stop for the text after the label.+ crate::rtl::label(ui, crate::i18n::tr(lang, "Tab Position:"));+ ui.horizontal(|ui| {+ let tab = para_value(d, pv, "listTab").as_f64();+ let mut on = tab.is_some();+ if ui.checkbox(&mut on, "").changed() {+ let left = para_value(d, pv, "leftIndent").as_f64().filter(|v| v.is_finite() && *v > 0.0).unwrap_or(18.0);+ para_set(d, "listTab", if on { json!(left) } else { Value::Null });+ }+ if let Some(t) = tab+ && let Some(v) = crate::widgets::measure(ui, "pslisttab", Some(t), units, 80.0)+ {+ para_set(d, "listTab", json!(if v.is_finite() { v.max(0.0) } else { 0.0 }));+ }+ });+ ui.end_row();+ }+ });+ });+}++/// Paragraph Borders and Shading, Span Columns, and Bullets and Numbering for the selected+/// paragraphs: the Paragraph Style Options sections over the paragraphs' attributes (`current`);+/// OK applies the edits (`p.<key>`) as local formatting.+fn paragraph_local(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {+ let Some(doc) = app.session.active().map(|s| s.doc.clone()) else { return };+ let pv = d.fields.get("current").cloned().unwrap_or_default();+ let lang = app.ui.language.clone();+ ui.set_min_width(480.0);+ match d.s("section").as_str() {+ "span" => span_columns(&lang, ui, d, &pv, &doc),+ "bullets" => {+ let (char_styles, families, fonts, scope) = ListUi::new_parts(app);+ let (family, style) = (d.s("family"), d.s("style"));+ let lu = ListUi { char_styles: &char_styles, families: &families, fonts: &fonts, scope, family: &family, style: &style };+ bullets_and_numbering(&lang, ui, d, &pv, &doc, &lu);+ }+ section => {+ let border = section != "shading";+ ui.horizontal(|ui| {+ for (tab, label) in [("border", "Border"), ("shading", "Shading")] {+ if ui.selectable_label(section == tab, crate::rtl::widget(ui, crate::i18n::tr(&lang, label))).clicked() {+ d.fields.insert("section".into(), json!(tab));+ }+ }+ });+ ui.separator();+ border_shading(&lang, ui, d, &pv, &doc, border);+ }+ }+}++fn section_list(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cjk: bool, sections: &[(&str, &str)]) {+ let sections = style_cjk::sections(cjk, d.id == "paragraphStyleOptions", sections);+ ui.vertical(|ui| {+ ui.set_width(170.0);+ // The dialog has a fixed height; a long list scrolls.+ egui::ScrollArea::vertical().id_salt("style_sections").auto_shrink([false, true]).show(ui, |ui| {+ for (id, label) in §ions {+ if ui.selectable_label(d.s("section") == *id, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {+ d.fields.insert("section".into(), json!(id));+ }+ }+ });+ });+}++/// "Paragraph Style n" / "Character Style n": the first name no style has.+fn next_style_name(styles: &designcraft_doc::Styles, para: bool) -> String {+ let (base, count) = if para { ("Paragraph Style", styles.paragraph.len()) } else { ("Character Style", styles.character.len()) };+ let taken = |n: &str| if para { styles.para(n).is_some() } else { styles.char_style(n).is_some() };+ // Among count + 1 numbers at least one is free.+ (1..=count + 1).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_else(|| format!("{base} {}", count + 1))+}++/// Paragraph or Character Style Options for an existing style (a double-click on it in the styles+/// panel, or Edit in its menu). [None] and [No Paragraph Style] have no options.+pub fn open_style_options(app: &mut DesignApp, para: bool, name: &str) {+ if name == if para { designcraft_doc::NO_PARA_STYLE } else { designcraft_doc::NO_CHAR_STYLE } {+ return;+ }+ let id = if para { "paragraphStyleOptions" } else { "characterStyleOptions" };+ app.ui.dialog = Some(Dialog::new(id, json!({"name": name})));+}++/// New Paragraph Style… / New Character Style…: the style options for a style made on OK, named+/// with the next free "Paragraph Style n" / "Character Style n".+pub fn open_new_style(app: &mut DesignApp, para: bool) {+ let Some(st) = app.session.active() else { return };+ let name = next_style_name(&st.doc.styles, para);+ let id = if para { "paragraphStyleOptions" } else { "characterStyleOptions" };+ app.ui.dialog = Some(Dialog::new(id, json!({"new": true, "rename": name})));+}++/// Character Style Options: General, then the character sections it shares with Paragraph Style+/// Options. A character style sets only some attributes: the fields show those it and its Based+/// On set and leave the rest blank. Edits are `c.<attr>` fields (`null` = no longer set), applied+/// on OK; `new` makes the style instead of editing `name`.+fn character_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {+ let name = d.s("name");+ let new = d.b("new");+ let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return };+ let styles = &doc.styles;+ let style = match styles.char_style(&name) {+ _ if new => designcraft_doc::CharacterStyle { name: String::new(), based_on: None, chars: Default::default(), shortcut: String::new() },+ Some(s) if name != designcraft_doc::NO_CHAR_STYLE => s.clone(),+ _ => {+ crate::rtl::label(ui, format!("No style named {name}"));+ return;+ }+ };+ if !d.fields.contains_key("rename") {+ d.fields.insert("rename".into(), json!(if new { next_style_name(styles, false) } else { name.clone() }));+ }+ let based = d+ .fields+ .get("basedOn")+ .and_then(Value::as_str).map(str::to_string).or(style.based_on.clone()).unwrap_or_else(|| designcraft_doc::NO_CHAR_STYLE.into());@@@ -4913,345 -3768,6 +4940,360 @@@ fn find_font(app: &mut DesignApp, ui: &mod tests {use super::*;+ #[test]+ fn cell_options_dialog_draws_and_applies_only_changed_values_to_the_chosen_edges() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();+ let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();+ app.run("table.select", json!({"what": "table"})).unwrap();+ app.run("app.cellOptionsDialog", json!({})).unwrap();+ let ctx = dialog_context("");+ dialog_frame(&mut app, &ctx, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0)), vec![]);+ let d = app.ui.dialog.as_mut().unwrap();+ assert_eq!(d.id, "cellOptions");+ assert_eq!(d.fields["weight"], json!(1.0));+ d.fields.insert("edges".into(), json!(["top", "bottom", "left", "right"]));+ d.fields.insert("gapColor".into(), json!("[Paper]"));+ d.fields.insert("fill".into(), json!("[Black]"));+ d.fields.insert("fillTint".into(), json!(0.2));+ confirm(&mut app).unwrap();+ let st = app.session.active().unwrap();+ let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();+ let gap = |r: usize, c: usize, side: usize| t.cell(r, c).unwrap().strokes[side].gap_color.clone();+ assert_eq!([gap(0, 0, 0), gap(0, 0, 1), gap(1, 1, 2), gap(1, 1, 3)], ["[Paper]"; 4].map(String::from), "outer edges");+ assert_eq!([gap(0, 0, 2), gap(0, 0, 3)], ["[None]"; 2].map(String::from), "inner edges keep theirs");+ assert!(t.cells.iter().all(|c| c.fill == "[Black]" && (c.fill_tint - 0.2).abs() < 1e-6));+ assert!(t.cells.iter().all(|c| c.strokes.iter().all(|e| e.weight == 1.0)), "unchanged values are not applied");+ }++ #[test]+ fn cell_options_edge_changes_reseed_every_stroke_field_and_survive_a_bad_seed() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();+ let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();+ app.run("table.select", json!({"what": "table"})).unwrap();+ app.run("table.setCell", json!({"stroke": {"weight": 3, "edges": "innerHorizontal"}})).unwrap();+ app.run("app.cellOptionsDialog", json!({})).unwrap();+ let mut d = app.ui.dialog.take().unwrap();+ d.fields.insert("seed".into(), json!(5));+ let outer = [true, true, true, true, false, false];+ cell_options_edges_changed(&mut app, &mut d, &outer);+ assert_eq!((&d.fields["weight"], &d.fields["seed"]["weight"]), (&json!(1.0), &json!(1.0)));+ // A weight typed for the outer edges, then the inner horizontal edges (3 pt) chosen+ // and 1 pt typed: 1 pt differs from what those edges show, so OK applies it.+ d.fields.insert("weight".into(), json!(5.0));+ cell_options_edges_changed(&mut app, &mut d, &[false, false, false, false, true, false]);+ assert_eq!((&d.fields["weight"], &d.fields["seed"]["weight"]), (&json!(5.0), &json!(3.0)));+ d.fields.insert("weight".into(), json!(1.0));+ app.ui.dialog = Some(d);+ confirm(&mut app).unwrap();+ let st = app.session.active().unwrap();+ let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();+ assert_eq!([t.cell(0, 0).unwrap().strokes[2].weight, t.cell(1, 1).unwrap().strokes[0].weight], [1.0; 2]);+ }++ #[test]+ fn numbering_and_section_options_keep_their_actions_in_view() {+ for language in ["en", "ar"] {+ for size in [egui::vec2(1178.0, 814.0), egui::vec2(392.0, 271.0)] {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.ui.language = language.into();+ app.run("file.new", json!({"pages": 2})).unwrap();+ crate::menus::activate(&mut app, "layout.section", &Value::Null);+ 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![]);+ }+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ let tr = |s| crate::i18n::tr(language, s);+ for expected in [tr("Numbering & Section Options…").trim_end_matches('…'), tr("OK"), tr("Cancel"), tr("Start Section")] {+ visible_label(&labels, screen, expected);+ }+ if size.x > 1000.0 {+ // Every option fits without scrolling, and choosing one then OK applies it.+ visible_label(&labels, screen, &format!("{} {}", tr("Book Name:"), tr("N/A")));+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, tr("Automatic Page Numbering")).center());+ let labels = dialog_frame(&mut app, &ctx, screen, vec![]);+ click_dialog(&mut app, &ctx, screen, visible_label(&labels, screen, tr("OK")).center());+ assert!(app.ui.dialog.is_none(), "{language}: OK closes the dialog");+ let doc = &app.session.active().unwrap().doc;+ assert!(doc.sections.iter().all(|s| s.start != 0 || s.start_number.is_none()), "{language}: page 1 numbers automatically");+ }+ }+ }+ }++ fn draw(app: &mut DesignApp, ctx: &egui::Context) {+ let input =+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ }++ /// A paragraph styled "Ruled Child", whose Rule Below comes from its parent "Ruled".+ fn ruled_paragraph() -> (DesignApp, Value) {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let rule = json!({"on": true, "weight": 3.0, "color": "[Black]", "tint": 0.5, "columnWidth": false, "offset": 4.0, "leftIndent": 6.0, "rightIndent": 2.0});+ app.run("style.paragraph.create", json!({"name": "Ruled", "para": {"ruleBelow": rule}})).unwrap();+ app.run("style.paragraph.create", json!({"name": "Ruled Child", "basedOn": "Ruled"})).unwrap();+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 400], "content": "text", "text": "One"})).unwrap();+ app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();+ app.run("style.paragraph.apply", json!({"name": "Ruled Child"})).unwrap();+ (app, rule)+ }++ fn undo_steps(app: &DesignApp) -> usize {+ app.session.doc().map_or(0, |st| st.history.undo.len())+ }++ #[test]+ fn paragraph_rules_dialog_shows_the_rule_and_applies_one_field() {+ let (mut app, rule) = ruled_paragraph();+ let ctx = egui::Context::default();+ app.run("app.paragraphRulesDialog", json!({"rule": "ruleBelow"})).unwrap();+ draw(&mut app, &ctx);+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!(d.id, "paragraphRules");+ let current = d.fields["current"].clone();+ assert_eq!(shown_rule(&d, "", "ruleBelow", ¤t), rule, "the inherited rule");+ assert_eq!(shown_rule(&d, "", "ruleAbove", ¤t)["on"], false);+ // Pick a colour, as the Color menu does.+ app.ui.dialog.as_mut().unwrap().fields.insert("ruleBelow.color".into(), json!("[Registration]"));+ 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["color"] = json!("[Registration]");+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], want);+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["ruleBelow"], rule);+ }++ #[test]+ 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);+ }++ /// Opens Paragraph Style Options on "Ruled Child" at each of `sections`, sets `fields` and+ /// clicks OK; returns the resolved attributes of the paragraph styled with it.+ fn style_section_edit(sections: &[&str], fields: Value) -> Value {+ let (mut app, _) = ruled_paragraph();+ let ctx = egui::Context::default();+ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child"})));+ for section in sections {+ app.ui.dialog.as_mut().unwrap().fields.insert("section".into(), json!(section));+ draw(&mut app, &ctx);+ }+ for (k, v) in fields.as_object().unwrap() {+ app.ui.dialog.as_mut().unwrap().fields.insert(k.clone(), v.clone());+ }+ draw(&mut app, &ctx);+ let before = undo_steps(&app);+ confirm(&mut app).unwrap();+ assert_eq!(undo_steps(&app), before + 1, "one undo step");+ let style = app.session.doc().unwrap().doc.styles.para("Ruled Child").cloned().unwrap();+ let own = serde_json::to_value(&style.para).unwrap();+ for (k, v) in fields.as_object().unwrap() {+ assert_eq!(own[k.trim_start_matches("p.")], *v, "the style sets {k}");+ }+ app.run("type.selectionAttrs", json!({})).unwrap()["para"].clone()+ }++ #[test]+ fn paragraph_style_options_keep_and_border_sections_reach_the_styled_paragraph() {+ let para = style_section_edit(+ &["keep", "border"],+ json!({"p.keepWithNext": 2, "p.keepLinesTogether": true, "p.keepAllLines": false, "p.keepFirst": 3,+ "p.startParagraph": "nextPage", "p.borderOn": true, "p.borderWeights": [2.0, 0.0, 2.0, 0.0]}),+ );+ assert_eq!(para["keepWithNext"], 2);+ assert_eq!(para["keepLinesTogether"], true);+ assert_eq!(para["keepAllLines"], false);+ assert_eq!(para["keepFirst"], 3);+ assert_eq!(para["startParagraph"], "nextPage");+ assert_eq!(para["borderOn"], true);+ assert_eq!(para["borderWeights"], json!([2.0, 0.0, 2.0, 0.0]));+ // Fields not edited keep the resolved value.+ assert_eq!(para["keepLast"], 2);+ assert_eq!(para["ruleBelow"]["weight"], 3.0);+ }++ #[test]+ fn paragraph_style_options_bullets_and_span_sections_reach_the_styled_paragraph() {+ let para = style_section_edit(+ &["bullets", "span"],+ json!({"p.listType": "numbers", "p.numberStyle": "upperRoman", "p.numberExpression": "^#)^t", "p.startAt": 3,+ "p.spanColumns": {"kind": "split", "columns": 3}}),+ );+ assert_eq!(para["listType"], "numbers");+ assert_eq!(para["numberStyle"], "upperRoman");+ assert_eq!(para["numberExpression"], "^#)^t");+ assert_eq!(para["startAt"], 3);+ assert_eq!(para["spanColumns"], json!({"kind": "split", "columns": 3}));+ let props: designcraft_doc::ParaProps = serde_json::from_value(para).unwrap();+ assert_eq!(props.number_label(3), "III)\t");+ }+++ #[test]++ fn paragraph_style_options_keep_a_bad_grep_pattern_open_with_the_error() {++ let (mut app, _) = ruled_paragraph();++ let ctx = egui::Context::default();++ app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled", "section": "general"})));++ draw(&mut app, &ctx);++ app.ui.dialog.as_mut().unwrap().fields.insert("p.grepStyles".into(), json!([{"style": "[None]", "pattern": "(?<=x"}]));++ let e = confirm(&mut app).unwrap_err();++ assert!(e.contains("bad GREP"), "{e}");++ let d = app.ui.dialog.clone().expect("the dialog stays open");++ assert_eq!((d.s("section").as_str(), d.s("status").contains("bad GREP")), ("grep", true));++ assert!(app.session.doc().unwrap().doc.styles.para("Ruled").unwrap().para.grep_styles.is_none(), "nothing saved");++ draw(&mut app, &ctx);++ }+++ 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);