DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
GREP: styles with a pattern that can't compile are rejected, and imports warn
aionggae50689e278e
diff --git a/crates/compose/src/overlay.rs b/crates/compose/src/overlay.rsindex 9b1fd453a..d58734983 100644--- a/crates/compose/src/overlay.rs+++ b/crates/compose/src/overlay.rs@@ -109,4 +109,13 @@ mod tests {let got: Vec<&str> = o.iter().map(|(r, _)| &text[r.clone()]).collect();assert_eq!(got, ["и ", "он ", "в "]);}++ #[test]+ fn grep_style_with_lookbehind() {+ // Polish one-letter words kept with the next one; the space before is not styled.+ let text = "Ala i kot w domu.\n".to_string();+ let o = overlays(&text, 0..text.len(), &[], &[GrepStyle { style: "nobreak".into(), pattern: r"(?<=\s)[aiouwzAIOUWZ]\s".into() }]);+ let got: Vec<&str> = o.iter().map(|(r, _)| &text[r.clone()]).collect();+ assert_eq!(got, ["i ", "w "]);+ }}diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rsindex f871a43e8..4d2761e59 100644--- a/crates/engine/src/cmd/file.rs+++ b/crates/engine/src/cmd/file.rs@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {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!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"),- "{path} — .designcraft or .idml; the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped}",+ "{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}",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),@@ -166,7 +166,8 @@ fn file_open(s: &mut Session, p: &Value) -> Result<Value> {let mut d = from_bytes(&bytes)?;super::interchange::resolve_packaged_links(&mut d, std::path::Path::new(path).parent());super::datamerge::resolve_sources_on_open(&mut d, Some(std::path::Path::new(path)));- let (fonts, faces, warnings) = load_document_fonts(&mut d, path);+ let (fonts, faces, mut warnings) = load_document_fonts(&mut d, path);+ warnings.extend(super::style::grep_style_warnings(&d));let mut st = DocState::new(d, Some(path.to_string()));st.fonts = fonts;let i = s.add_document(st);diff --git a/crates/engine/src/cmd/interchange.rs b/crates/engine/src/cmd/interchange.rsindex 8a65ec913..0ece4037f 100644--- a/crates/engine/src/cmd/interchange.rs+++ b/crates/engine/src/cmd/interchange.rs@@ -13,7 +13,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 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}",+ "{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}",always, open_idml),]}@@ -146,10 +146,11 @@ pub(crate) fn open_idml(s: &mut Session, p: &Value) -> Result<Value> {if let Some(n) = name {d.title = n;}- let (fonts, faces, warnings) = match str_param(p, "path").filter(|_| str_param(p, "base64").is_none()) {+ let (fonts, faces, mut warnings) = match str_param(p, "path").filter(|_| str_param(p, "base64").is_none()) {Some(path) => super::file::load_document_fonts(&mut d, path),None => (None, 0, Vec::new()),};+ warnings.extend(super::style::grep_style_warnings(&d));// Never save over the .idml with the native format: the document starts unsaved.let mut st = DocState::new(d, None);st.fonts = fonts;diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rsindex 94bd92c6d..1944be2d8 100644--- a/crates/engine/src/cmd/style.rs+++ b/crates/engine/src/cmd/style.rs@@ -86,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {"New Paragraph Style…",[],None,- "{name, basedOn?, nextStyle?, para?: {…}, chars?: {…}, fromSelection?: bool}",+ "{name, basedOn?, nextStyle?, para?: {… grepStyles?: [{style, pattern}]: a pattern that can't compile is an error}, chars?: {…}, fromSelection?: bool}",has_doc,create_para),@@ -95,7 +95,7 @@ pub fn specs() -> Vec<CommandSpec> {"Paragraph Style Options…",[],None,- "{name, rename?, basedOn?, nextStyle?, para?: {… ruleAbove?/ruleBelow?: only the named rule fields change}, 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?: {…}}",has_doc,edit_para),@@ -428,6 +428,7 @@ fn apply_char(s: &mut Session, p: &Value) -> Result<Value> {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))?;+ 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!({}))@@ -458,6 +459,39 @@ fn create_para(s: &mut Session, p: &Value) -> Result<Value> {})}+/// 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])@@ -481,6 +515,7 @@ fn edit_para(s: &mut Session, p: &Value) -> Result<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))?;+ 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);@@ -1318,3 +1353,58 @@ mod cjk_tests {assert!(s.execute("style.compositeFont.set", &definition(-1.0)).is_err());}}++#[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 --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rsindex 4950d82b9..0b08f4a07 100644--- a/crates/engine/src/cmd/text.rs+++ b/crates/engine/src/cmd/text.rs@@ -863,6 +863,7 @@ pub(crate) fn format_paras(s: &mut Session, attrs: &Value) -> Result<Value> {for (k, v) in obj {a.set_json_over(k, v, &designcraft_doc::ParaProps::default()).map_err(|e| bad("type.para", e))?;}+ super::style::check_grep_styles("type.para", &a)?;// `null` removes the override (back to the style's value).let cleared: Vec<String> = obj.iter().filter(|(_, v)| v.is_null()).map(|(k, _)| k.clone()).collect();let targets = format_targets(s);diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex d701b1d4c..accee9856 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -1807,53 +1807,17 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {)}"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 r = confirm_paragraph_style_options(app, &d);+ if let Err(e) = &r {+ // Keep the dialog open with the reason, on the section it concerns.+ let mut d = d;+ 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}"paragraphRules" => {let attrs = rule_edits(&d, "");@@ -2197,16 +2161,66 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {}}-/// Paragraph Style Options: sections in a left list (like InDesign), fields on the right.-/// Edited values are stored as `p.<attr>` / `c.<attr>` fields and applied on OK.-/// Is `p` a pattern the GREP styles can use? (Checked as the user types.)-fn regex_ok(p: &str) -> Result<(), ()> {+/// Why `p` is not a pattern the GREP styles can use, if it isn't. (Checked as the user types.)+fn grep_error(p: &str) -> Option<String> {if p.is_empty() {- return Ok(());+ return None;}- designcraft_compose::grep::Grep::new(p, Default::default()).map(|_| ()).map_err(|_| ())+ designcraft_compose::grep::Grep::new(p, Default::default()).err().map(|e| e.to_string())}+fn confirm_paragraph_style_options(app: &mut DesignApp, d: &Dialog) -> Result<Value, String> {+ 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 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")}))?;+ }+ Ok(r)+}++/// Paragraph Style Options: sections in a left list (like InDesign), fields on the right.+/// Edited values are stored as `p.<attr>` / `c.<attr>` fields and applied on OK.fn paragraph_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {let name = d.s("name");let new = d.b("new");@@ -2470,7 +2484,7 @@ fn paragraph_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo});crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "To Text:"));let mut pat = g["pattern"].as_str().unwrap_or("").to_string();- let bad = regex_ok(&pat).is_err();+ let bad = grep_error(&pat).is_some();let r = ui.add(egui::TextEdit::singleline(&mut pat).desired_width(150.0)@@ -2490,6 +2504,9 @@ fn paragraph_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialoremove = Some(i);}});+ if let Some(e) = grep_error(g["pattern"].as_str().unwrap_or("")) {+ crate::rtl::label(ui, egui::RichText::new(e).size(11.0).color(egui::Color32::from_rgb(240, 90, 90)));+ }}if let Some(i) = remove {list.remove(i);@@ -2648,6 +2665,11 @@ fn paragraph_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo}});});+ // 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.@@ -4070,6 +4092,21 @@ mod tests {assert_eq!(resolved(&app)["ruleBelow"], rule);}+ #[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));