diff --git a/crates/doc-binary/src/lib.rs b/crates/doc-binary/src/lib.rs index d8e3ce31a5..bab7c612da 100644 --- a/crates/doc-binary/src/lib.rs +++ b/crates/doc-binary/src/lib.rs @@ -283,7 +283,7 @@ fn read_limited(bytes: &[u8], password: Option<&str>, max_paragraphs: usize) -> let mut doc = Document::new(); // Word opens Word 97-2003 files in compatibility mode 11 (Word 2003); the model's default // 15 would apply Word 2013+ justification and line-breaking rules to them. - doc.settings.compat_mode = 11; + doc.settings.compat_mode = Some(11); if let Some(core) = metadata::read(&comp) { doc.core = core; } @@ -455,7 +455,7 @@ fn read_word6(comp: &craft_cfb::CompoundFile<'_>, word: &[u8], max_paragraphs: u let content = word6::content(word, &fib)?; let mut doc = Document::new(); // Word opens these files in compatibility mode 11 too. - doc.settings.compat_mode = 11; + doc.settings.compat_mode = Some(11); if let Some(core) = metadata::read(comp) { doc.core = core; } diff --git a/crates/doc-binary/src/tests.rs b/crates/doc-binary/src/tests.rs index 8c1025eb27..2f380ca84a 100644 --- a/crates/doc-binary/src/tests.rs +++ b/crates/doc-binary/src/tests.rs @@ -347,7 +347,7 @@ fn a_doc_opens_in_word_97_2003_compatibility_mode() { let doc = read(&f).expect("opens"); // Word 97-2003 files are mode 11 in Word 2013+; mode 15 would change justification and // line breaking. - assert_eq!(doc.settings.compat_mode, 11); + assert_eq!(doc.settings.compat_mode, Some(11)); } #[test] diff --git a/crates/docx/src/read.rs b/crates/docx/src/read.rs index 518f3e6b47..53c04675bf 100644 --- a/crates/docx/src/read.rs +++ b/crates/docx/src/read.rs @@ -254,7 +254,8 @@ fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize, lenient("numbering", r.read_numbering(&p)); } // Without a stated mode (or settings at all) Word lays a document out as Word 2007 did. - r.doc.settings.compat_mode = craft_wordmodel::LEGACY_COMPAT_MODE; + // Retain `compat_mode` as `None` when omitted from the source file to preserve XML fidelity on save (#3308). + r.doc.settings.compat_mode = None; if let Some(p) = part(rt::SETTINGS) { lenient("settings", r.read_settings(&p)); } diff --git a/crates/docx/src/read/meta.rs b/crates/docx/src/read/meta.rs index 851ecae67f..5a4330bdca 100644 --- a/crates/docx/src/read/meta.rs +++ b/crates/docx/src/read/meta.rs @@ -47,7 +47,7 @@ impl Reader<'_> { }) .and_then(|c| c.attr("w:val")); if let Some(m) = mode.and_then(u32_of) { - s.compat_mode = m.clamp(11, 99); + s.compat_mode = Some(m.clamp(11, 99)); } s.sum_paragraph_spacing = k.children("w:doNotUseHTMLParagraphAutoSpacing").any(on_off); s.do_not_expand_shift_return = k.children("w:doNotExpandShiftReturn").any(on_off); diff --git a/crates/docx/src/read/story.rs b/crates/docx/src/read/story.rs index 9b5b04300a..8d97db6afb 100644 --- a/crates/docx/src/read/story.rs +++ b/crates/docx/src/read/story.rs @@ -49,6 +49,7 @@ const MAX_FORM: usize = 64 * 1024; pub struct RunCtx { link: Option, link_tooltip: Option>, + link_history: Option, ins: Option, del: Option, } @@ -212,5 +213,5 @@ fn placeholder_of(s: &str) -> String { } fn on_off_attr(e: &El, name: &str) -> bool { - e.attr(name).is_some_and(|v| !matches!(v, "0" | "false" | "off")) + e.attr(name).is_some_and(|v| !crate::units::is_off_val(v)) } diff --git a/crates/docx/src/read/story/runs.rs b/crates/docx/src/read/story/runs.rs index 0c8b699949..f28745bac1 100644 --- a/crates/docx/src/read/story/runs.rs +++ b/crates/docx/src/read/story/runs.rs @@ -32,6 +32,12 @@ impl Reader<'_> { if let Some(link) = link { c.link = Some(link); c.link_tooltip = k.attr("w:tooltip").and_then(crate::bounded_link_tooltip).map(std::sync::Arc::from); + // History on stays `None`: it is what the writer writes for a link with none. + c.link_history = match k.attr("w:history") { + Some(v) if crate::units::is_off_val(v) => Some(craft_wordmodel::props::LinkHistory::Off), + Some(_) => None, + None => Some(craft_wordmodel::props::LinkHistory::Omitted), + }; } self.read_inline_children(sc, pb, k, rels, &c, depth + 1); } @@ -138,6 +144,7 @@ impl Reader<'_> { let mut p = self.pc.rpr(rpr); p.link = ctx.link.clone(); p.link_tooltip = ctx.link_tooltip.clone(); + p.link_history = ctx.link_history; p.ins = ctx.ins; p.del = ctx.del; p.fmt_change = self.rpr_change(rpr); @@ -145,7 +152,14 @@ impl Reader<'_> { } fn run_props_none(&self, ctx: &RunCtx) -> CharProps { - CharProps { link: ctx.link.clone(), link_tooltip: ctx.link_tooltip.clone(), ins: ctx.ins, del: ctx.del, ..Default::default() } + CharProps { + link: ctx.link.clone(), + link_tooltip: ctx.link_tooltip.clone(), + link_history: ctx.link_history, + ins: ctx.ins, + del: ctx.del, + ..Default::default() + } } fn read_run(&mut self, sc: &mut StoryCtx, pb: &mut PB, r: &El, rels: &Rels, ctx: &RunCtx, depth: usize) { @@ -354,7 +368,7 @@ impl Reader<'_> { let (base, base_props) = part("w:rubyBase"); let (ruby, ruby_props) = part("w:rt"); let mut bp = base_props.unwrap_or_default(); - (bp.link, bp.ins, bp.del) = (props.link.clone(), props.ins, props.del); + (bp.link, bp.link_history, bp.ins, bp.del) = (props.link.clone(), props.link_history, props.ins, props.del); if base.is_empty() { return; } diff --git a/crates/docx/src/units.rs b/crates/docx/src/units.rs index 295fe76215..cefd1977c7 100644 --- a/crates/docx/src/units.rs +++ b/crates/docx/src/units.rs @@ -141,11 +141,16 @@ pub fn tw_u16(e: &El, attr: &str) -> Option { } } +/// Return whether an XML attribute value for an `ST_OnOff` represents "off" / false. +pub fn is_off_val(v: &str) -> bool { + matches!(v.trim(), "0" | "false" | "off" | "False" | "FALSE") +} + /// ST_OnOff: absent `w:val` = on; `0`, `false`, `off` = off. pub fn on_off(e: &El) -> bool { match e.attr("w:val") { None => true, - Some(v) => !matches!(v.trim(), "0" | "false" | "off" | "False" | "FALSE"), + Some(v) => !is_off_val(v), } } diff --git a/crates/docx/src/write/settings.rs b/crates/docx/src/write/settings.rs index a76ded663a..9080ce32af 100644 --- a/crates/docx/src/write/settings.rs +++ b/crates/docx/src/write/settings.rs @@ -151,6 +151,13 @@ fn write_note_settings( } fn write_compatibility_settings(w: &mut W, doc: &Document) { + let has_compat = doc.settings.do_not_expand_shift_return + || doc.settings.sum_paragraph_spacing + || doc.settings.allow_space_of_same_style_in_table + || doc.settings.compat_mode.is_some(); + if !has_compat { + return; + } w.open("w:compat", &[]); // CT_Compat: the older switches come before the `w:compatSetting`s. if doc.settings.do_not_expand_shift_return { @@ -162,8 +169,10 @@ fn write_compatibility_settings(w: &mut W, doc: &Document) { if doc.settings.allow_space_of_same_style_in_table { w.empty("w:allowSpaceOfSameStyleInTable", &[]); } - let mode = doc.settings.compat_mode.clamp(11, 15).to_string(); - w.empty("w:compatSetting", &[("w:name", "compatibilityMode"), ("w:uri", "http://schemas.microsoft.com/office/word"), ("w:val", &mode)]); + if let Some(mode) = doc.settings.compat_mode { + let mode = mode.clamp(11, 15).to_string(); + w.empty("w:compatSetting", &[("w:name", "compatibilityMode"), ("w:uri", "http://schemas.microsoft.com/office/word"), ("w:val", &mode)]); + } w.close("w:compat"); } diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index ac673c63ad..323e9b7cfa 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -8,7 +8,8 @@ //! tag (namespace declarations, `mc:Ignorable`) and every child the model doesn't own are kept //! byte for byte; owned children come from the generated part (or go, when the model turned //! them off); owned children the original lacks are inserted at their CT_Settings position; in -//! `w:compat` only the `compatibilityMode` setting is replaced. Kept children that refer to a +//! `w:compat` only the switches the model writes and the `compatibilityMode` setting come from the +//! generated part, and a block left empty goes. Kept children that refer to a //! relationship are dropped unless owned: mail merge is regenerated with remapped external //! sources by `mail_merge`. Anything unexpected returns `None`, and the generated part is written as before. @@ -232,29 +233,125 @@ fn children(xml: &str, root: &str) -> Option<(usize, usize, Vec)> { Some((open_end, close, out)) } -/// The original `w:compat` with its `compatibilityMode` taken from the generated one. +/// The `w:compat` switches the model writes (`super::settings`). +const OWNED_COMPAT_SWITCHES: &[&str] = &["w:doNotExpandShiftReturn", "w:doNotUseHTMLParagraphAutoSpacing", "w:allowSpaceOfSameStyleInTable"]; + +/// CT_Compat's sequence (ECMA-376 §17.15.3.9), for placing inserted switches. +const CT_COMPAT_ORDER: &[&str] = &[ + "useSingleBorderforContiguousCells", + "wpJustification", + "noTabHangInd", + "noLeading", + "spaceForUL", + "noColumnBalance", + "balanceSingleByteDoubleByteWidth", + "noExtraLineSpacing", + "doNotLeaveBackslashAlone", + "ulTrailSpace", + "doNotExpandShiftReturn", + "spacingInWholePoints", + "lineWrapLikeWord6", + "printBodyTextBeforeHeader", + "printColBlack", + "wpSpaceWidth", + "showBreaksInFrames", + "subFontBySize", + "suppressBottomSpacing", + "suppressTopSpacing", + "suppressSpacingAtTopOfPage", + "suppressTopSpacingWP", + "suppressSpBfAfterPgBrk", + "swapBordersFacingPages", + "convMailMergeEsc", + "truncateFontHeightsLikeWP6", + "mwSmallCaps", + "usePrinterMetrics", + "doNotSuppressParagraphBorders", + "wrapTrailSpaces", + "footnoteLayoutLikeWW8", + "shapeLayoutLikeWW8", + "alignTablesRowByRow", + "forgetLastTabAlignment", + "adjustLineHeightInTable", + "autoSpaceLikeWord95", + "noSpaceRaiseLower", + "doNotUseHTMLParagraphAutoSpacing", + "layoutRawTableWidth", + "layoutTableRowsApart", + "useWord97LineBreakRules", + "doNotBreakWrappedTables", + "doNotSnapToGridInCell", + "selectFldWithFirstOrLastChar", + "applyBreakingRules", + "doNotWrapTextWithPunct", + "doNotUseEastAsianBreakRules", + "useWord2002TableStyleRules", + "growAutofit", + "useFELayout", + "useNormalStyleForList", + "doNotUseIndentAsNumberingTabStop", + "useAltKinsokuLineBreakRules", + "allowSpaceOfSameStyleInTable", + "doNotSuppressIndentation", + "doNotAutofitConstrainedTables", + "autofitToFirstFixedWidthCell", + "underlineTabInNumList", + "displayHangulFixedWidth", + "splitPgBreakAndParaMark", + "doNotVertAlignCellWithSp", + "doNotBreakConstrainedForcedTable", + "doNotVertAlignInTxbx", + "useAnsiKerningPairs", + "cachedColBalance", + "compatSetting", +]; + +/// Position of a `w:`-prefixed `w:compat` child in [`CT_COMPAT_ORDER`]; `None` for anything else. +fn compat_rank(name: &str) -> Option { + let local = name.strip_prefix("w:")?; + CT_COMPAT_ORDER.iter().position(|n| *n == local) +} + +/// Is this `w:compat` child Word's `compatibilityMode` setting? +fn is_compat_mode(child: &str) -> bool { + let mut reader = quick_xml::Reader::from_str(child); + let Ok(quick_xml::events::Event::Start(e) | quick_xml::events::Event::Empty(e)) = reader.read_event() else { return false }; + e.name().as_ref() == b"w:compatSetting" + && e.attributes().with_checks(false).flatten().any(|a| a.key.as_ref() == b"w:name" && a.value.as_ref() == b"compatibilityMode") +} + +/// The original `w:compat` with what the model owns in it taken from the generated one (`""` +/// when the model writes none): its switches, and the `compatibilityMode` setting. A block left +/// without children goes (`""`). fn merge_compat(orig: &str, generated: &str) -> Option { - let mode = |s: &str| -> Option<(usize, usize)> { - let at = s.find("w:name=\"compatibilityMode\"")?; - let tag_start = s.get(..at)?.rfind('<')?; - let tag_end = tag_start + s.get(tag_start..)?.find('>')? + 1; - Some((tag_start, tag_end)) + let g_kids = children(generated, "w:compat").map(|(_, _, kids)| kids).unwrap_or_default(); + let g_child = |pred: &dyn Fn(&Child, &str) -> bool| g_kids.iter().find_map(|k| generated.get(k.start..k.end).filter(|text| pred(k, text))); + let mut out = match orig.strip_suffix("/>") { + Some(open) => format!("{}>", open.trim_end()), + None => orig.to_string(), }; - match (mode(orig), mode(generated)) { - (Some((a, b)), Some((c, d))) => Some(format!("{}{}{}", orig.get(..a)?, generated.get(c..d)?, orig.get(b..)?)), - (None, Some((c, d))) => { - // No mode in the original: add the generated one before ``, or expand a self-closing ``. - if let Some(close) = orig.rfind("") { - Some(format!("{}{}{}", orig.get(..close)?, generated.get(c..d)?, orig.get(close..)?)) - } else if let Some(slash) = orig.rfind("/>") { - let open = orig.get(..slash)?.trim_end(); - Some(format!("{open}>{}", generated.get(c..d)?)) - } else { - None - } + for sw in OWNED_COMPAT_SWITCHES { + let (_, _, kids) = children(&out, "w:compat")?; + for k in kids.iter().rev().filter(|k| k.name == *sw) { + out.replace_range(k.start..k.end, ""); + } + if let Some(g) = g_child(&|k, _| k.name == *sw) { + let (_, close, kids) = children(&out, "w:compat")?; + let rank = compat_rank(sw); + let at = kids.iter().find(|k| compat_rank(&k.name) > rank).map_or(close, |k| k.start); + out.insert_str(at, g); } - _ => Some(orig.to_string()), } + let (_, close, kids) = children(&out, "w:compat")?; + let o_mode = kids.iter().find(|k| out.get(k.start..k.end).is_some_and(is_compat_mode)).map(|k| k.start..k.end); + match (o_mode, g_child(&|_, text| is_compat_mode(text))) { + (Some(span), Some(g)) => out.replace_range(span, g), + (Some(span), None) => out.replace_range(span, ""), + (None, Some(g)) => out.insert_str(close, g), + (None, None) => {} + } + let (_, _, kids) = children(&out, "w:compat")?; + Some(if kids.is_empty() { String::new() } else { out }) } /// Does `original` (a settings part) hold anything the model doesn't write? Then the reader keeps @@ -358,11 +455,11 @@ pub fn merge(original: &[u8], generated: &[u8]) -> Option> { out.push((k.name.clone(), g_text(g_kids.get(gi)?)?)); } } else if k.name == "w:compat" { - let merged = match mark("w:compat", &mut used) { - Some(gi) => merge_compat(text, &g_text(g_kids.get(gi)?)?)?, - None => text.to_string(), - }; - out.push((k.name.clone(), merged)); + let g_compat = mark("w:compat", &mut used).and_then(|gi| g_text(g_kids.get(gi)?)); + let merged = merge_compat(text, g_compat.as_deref().unwrap_or(""))?; + if !merged.is_empty() { + out.push((k.name.clone(), merged)); + } } else if !text.contains("r:id=") { out.push((k.name.clone(), text.to_string())); } @@ -475,4 +572,95 @@ mod tests { // A file whose only extra setting is this one has nothing foreign to keep. assert!(!has_unowned(br#""#)); } + + #[test] + fn compatibility_mode_removal_handles_paired_tags_quotes_and_whitespace() { + let gen_no_mode = r#""#; + + // Paired tag with closing + let orig_paired = r#""#; + assert!(has_unowned(orig_paired.as_bytes())); + let out_paired = String::from_utf8(merge(orig_paired.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); + assert!(!out_paired.contains("compatibilityMode"), "{out_paired}"); + assert!(!out_paired.contains(""), "{out_paired}"); + assert!(out_paired.contains("overrideTableStyleFontSizeAndJustification"), "{out_paired}"); + + // Single quotes + let orig_single_quotes = r#""#; + let out_sq = String::from_utf8(merge(orig_single_quotes.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); + assert!(!out_sq.contains("compatibilityMode"), "{out_sq}"); + assert!(out_sq.contains("overrideTableStyleFontSizeAndJustification"), "{out_sq}"); + + // Whitespace around equals + let orig_spaces = r#""#; + let out_sp = String::from_utf8(merge(orig_spaces.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap(); + assert!(!out_sp.contains("compatibilityMode"), "{out_sp}"); + assert!(out_sp.contains("overrideTableStyleFontSizeAndJustification"), "{out_sp}"); + + // Foreign vendor compatSetting element is preserved + let orig_foreign = r#""#; + let gen_foreign = + r#""#; + let out_foreign = String::from_utf8(merge(orig_foreign.as_bytes(), gen_foreign.as_bytes()).unwrap()).unwrap(); + assert!(out_foreign.contains("x:compatSetting"), "{out_foreign}"); + assert!(!out_foreign.contains(r#"w:name="compatibilityMode""#), "{out_foreign}"); + } + + #[test] + fn repeated_compat_switches_are_all_removed_when_disabled_and_deduplicated_when_enabled() { + let orig_two = r#""#; + // Disabled in generated: both must be removed + let gen_disabled = + r#""#; + let out_disabled = String::from_utf8(merge(orig_two.as_bytes(), gen_disabled.as_bytes()).unwrap()).unwrap(); + assert!(!out_disabled.contains("doNotExpandShiftReturn"), "{out_disabled}"); + assert!(out_disabled.contains(""), "{out_disabled}"); + + // Enabled in generated: exactly one occurrence emitted + let gen_enabled = r#""#; + let out_enabled = String::from_utf8(merge(orig_two.as_bytes(), gen_enabled.as_bytes()).unwrap()).unwrap(); + assert_eq!(out_enabled.matches("doNotExpandShiftReturn").count(), 1, "{out_enabled}"); + assert!(out_enabled.contains(""), "{out_enabled}"); + } + + #[test] + fn new_compat_switches_are_inserted_in_schema_order() { + // spacingInWholePoints is ranked after doNotExpandShiftReturn in CT_Compat + let orig = r#""#; + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + let idx_shift = merged.find("").unwrap(); + let idx_spacing = merged.find("").unwrap(); + assert!(idx_shift < idx_spacing, "doNotExpandShiftReturn must precede spacingInWholePoints: {merged}"); + } + + #[test] + fn foreign_child_is_ignored_when_finding_switch_insertion_point() { + // x:spacingInWholePoints precedes w:ulTrailSpace + let orig = r#""#; + let gen_xml = r#""#; + let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap(); + let idx_custom = merged.find("").unwrap(); + let idx_trail = merged.find("").unwrap(); + let idx_shift = merged.find("").unwrap(); + let idx_spacing = merged.find("").unwrap(); + assert!(idx_custom < idx_trail, "custom before trail: {merged}"); + assert!(idx_trail < idx_shift, "trail before shift: {merged}"); + assert!(idx_shift < idx_spacing, "shift before spacing: {merged}"); + } + + #[test] + fn a_bare_self_closing_compat_block_goes_like_an_empty_paired_one() { + let gen_xml = r#""#; + let merged_with = |compat: &str| { + let orig = format!( + r#"{compat}"# + ); + String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap() + }; + let self_closing = merged_with(""); + assert!(!self_closing.contains("compat"), "{self_closing}"); + assert!(self_closing.contains(r#""#), "{self_closing}"); + assert_eq!(self_closing, merged_with("")); + } } diff --git a/crates/docx/src/write/story/para.rs b/crates/docx/src/write/story/para.rs index 624ce32381..15c23ee9f9 100644 --- a/crates/docx/src/write/story/para.rs +++ b/crates/docx/src/write/story/para.rs @@ -210,17 +210,24 @@ impl Writer<'_> { i += 1; continue; } - // Hyperlinks with different ScreenTips stay separate even if their target is shared. - let link = props - .link - .as_deref() - .filter(|target| !target.is_empty()) - .map(|target| (target, props.link_tooltip.as_deref().and_then(crate::bounded_link_tooltip))); + // Hyperlinks with different ScreenTips or history settings stay separate even if their target is shared. + let base = link_target_and_tip; + // Text with no history of its own (typed into a link) takes the history of the link it + // is in: the open one, or else the first of the following text in the same link that has one. + let link = base(props).map(|(target, tip)| { + let history = match open_link { + Some((open_target, open_tip, open_history)) if (open_target, open_tip) == (target, tip) => props.link_history.or(open_history), + _ => props.link_history.or_else(|| { + pieces.iter().skip(i + 1).map(|(_, p)| *p).take_while(|p| base(p) == Some((target, tip))).find_map(|p| p.link_history) + }), + }; + (target, tip, history) + }); if link != open_link { if open_link.is_some() { w.close("w:hyperlink"); } - if let Some((link, tip)) = link { + if let Some((link, tip, hist)) = link { let id; let target = if let Some(anchor) = link.strip_prefix('#') { ("w:anchor", anchor) @@ -228,11 +235,19 @@ impl Writer<'_> { id = rels.add(rt::HYPERLINK, link, true); ("r:id", id.as_str()) }; - if let Some(tip) = tip { - w.open("w:hyperlink", &[target, ("w:history", "1"), ("w:tooltip", tip)]); - } else { - w.open("w:hyperlink", &[target, ("w:history", "1")]); + let mut attrs = [("", ""); 3]; + let mut n = 0; + attrs[n] = target; + n += 1; + if let Some(h) = link_history_val(hist) { + attrs[n] = ("w:history", h); + n += 1; } + if let Some(tip) = tip { + attrs[n] = ("w:tooltip", tip); + n += 1; + } + w.open("w:hyperlink", &attrs[..n]); } open_link = link; } @@ -355,3 +370,19 @@ impl Writer<'_> { } } } + +/// A run's hyperlink target and the ScreenTip it is written with, or `None` outside a link. +fn link_target_and_tip(p: &CharProps) -> Option<(&str, Option<&str>)> { + p.link.as_deref().filter(|target| !target.is_empty()).map(|target| (target, p.link_tooltip.as_deref().and_then(crate::bounded_link_tooltip))) +} + +/// The `w:history` value a hyperlink is written with: off or none when a .docx file gave that, +/// otherwise on, as Word writes it for a new link. +fn link_history_val(history: Option) -> Option<&'static str> { + use craft_wordmodel::props::LinkHistory; + match history { + None => Some("1"), + Some(LinkHistory::Off) => Some("0"), + Some(LinkHistory::Omitted) => None, + } +} diff --git a/crates/docx/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index e58fb3e0a7..6f9f191a22 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -1280,17 +1280,17 @@ fn compatibility_mode_is_read_and_defaults_to_word_2007() { let compat = |v: &str| { format!(r#""#) }; - assert_eq!(with_settings(Some(&compat("15"))).settings.compat_mode, 15); - assert_eq!(with_settings(Some(&compat("14"))).settings.compat_mode, 14); + assert_eq!(with_settings(Some(&compat("15"))).settings.compat_mode, Some(15)); + assert_eq!(with_settings(Some(&compat("14"))).settings.compat_mode, Some(14)); // Unnamed, out of range or junk values. - assert_eq!(with_settings(Some("")).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE); - assert_eq!(with_settings(None).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE); - assert_eq!(with_settings(Some(&compat("-3"))).settings.compat_mode, 11); - assert_eq!(with_settings(Some(&compat("99999"))).settings.compat_mode, 99); - assert_eq!(with_settings(Some(&compat("abc"))).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE); + assert_eq!(with_settings(Some("")).settings.compat_mode, None); + assert_eq!(with_settings(None).settings.compat_mode, None); + assert_eq!(with_settings(Some(&compat("-3"))).settings.compat_mode, Some(11)); + assert_eq!(with_settings(Some(&compat("99999"))).settings.compat_mode, Some(99)); + assert_eq!(with_settings(Some(&compat("abc"))).settings.compat_mode, None); // Another vendor's setting of the same name is ignored. let other = r#""#; - assert_eq!(with_settings(Some(other)).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE); + assert_eq!(with_settings(Some(other)).settings.compat_mode, None); } #[test] @@ -1458,7 +1458,9 @@ fn anchor_stacking_order_is_read_and_kept() { #[test] fn documents_without_a_compatibility_mode_are_laid_out_as_word_2007() { - assert_eq!(read_body("").settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE); + let d = read_body(""); + assert_eq!(d.settings.compat_mode, None); + assert_eq!(d.settings.effective_compat_mode(), craft_wordmodel::LEGACY_COMPAT_MODE); } #[test] diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index f826bdf57e..07a7b79888 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -143,6 +143,7 @@ fn every_char_prop_round_trips() { }), link: None, link_tooltip: None, + link_history: None, ins: None, del: None, fmt_change: None, @@ -1564,11 +1565,11 @@ fn table_contextual_spacing_compatibility_flag_round_trips() { for mode in [11, 12, 14, 15] { for allow in [false, true] { let mut d = Document::new(); - d.settings.compat_mode = mode; + d.settings.compat_mode = Some(mode); d.settings.allow_space_of_same_style_in_table = allow; let r = rt(&d); assert_eq!(r.settings.allow_space_of_same_style_in_table, allow); - assert_eq!(r.settings.compat_mode, mode); + assert_eq!(r.settings.compat_mode, Some(mode)); if allow { let bytes = craft_docx::write(&d).unwrap(); let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); @@ -1585,14 +1586,165 @@ fn table_contextual_spacing_compatibility_flag_round_trips() { fn compatibility_mode_round_trips() { // New documents are Word 2013+ documents; an older file keeps its mode, so saving it doesn't // change how Word lays it out. - assert_eq!(rt(&Document::new()).settings.compat_mode, craft_wordmodel::COMPAT_MODE_CURRENT); + assert_eq!(rt(&Document::new()).settings.compat_mode, Some(craft_wordmodel::COMPAT_MODE_CURRENT)); for mode in [11, 12, 14, 15] { let mut d = Document::new(); - d.settings.compat_mode = mode; - assert_eq!(rt(&d).settings.compat_mode, mode); + d.settings.compat_mode = Some(mode); + assert_eq!(rt(&d).settings.compat_mode, Some(mode)); } } +/// #3308: A document without `` or without `` +/// round-trips without synthesizing the tag on save. +#[test] +fn compatibility_mode_omitted_round_trips_without_synthesizing() { + let settings_xml_of = |bytes: &[u8]| { + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut xml = String::new(); + match zip.by_name("word/settings.xml") { + Ok(mut file) => { + std::io::Read::read_to_string(&mut file, &mut xml).unwrap(); + Some(xml) + } + Err(zip::result::ZipError::FileNotFound) => None, + Err(e) => panic!("zip error: {e:?}"), + } + }; + + // Case 1: settings.xml without `` at all. + let base_docx = craft_docx::write(&Document::new()).unwrap(); + let original_settings = settings_xml_of(&base_docx).unwrap(); + let without_compat = original_settings.replace( + "", + "", + ); + assert_ne!(original_settings, without_compat); + let docx_without_compat = replace_part(&base_docx, "word/settings.xml", without_compat.as_bytes()); + + let doc = craft_docx::read(&docx_without_compat).unwrap(); + assert_eq!(doc.settings.compat_mode, None); + assert_eq!(doc.settings.effective_compat_mode(), craft_wordmodel::LEGACY_COMPAT_MODE); + + let saved_bytes = craft_docx::write(&doc).unwrap(); + let saved_settings = settings_xml_of(&saved_bytes).unwrap(); + assert!(!saved_settings.contains(", got: {saved_settings}"); + assert!(!saved_settings.contains("compatibilityMode"), "expected no compatibilityMode, got: {saved_settings}"); + + let read_back = craft_docx::read(&saved_bytes).unwrap(); + assert_eq!(read_back.settings.compat_mode, None); + + // Case 2: settings.xml with `` but without `` + // (e.g. only legacy compatibility flags like ``). + let with_other_compat = original_settings.replace( + "", + "", + ); + assert_ne!(original_settings, with_other_compat); + let docx_with_other = replace_part(&base_docx, "word/settings.xml", with_other_compat.as_bytes()); + + let doc2 = craft_docx::read(&docx_with_other).unwrap(); + assert_eq!(doc2.settings.compat_mode, None); + assert!(doc2.settings.do_not_expand_shift_return); + + let saved_bytes2 = craft_docx::write(&doc2).unwrap(); + let saved_settings2 = settings_xml_of(&saved_bytes2).unwrap(); + assert!(saved_settings2.contains(""), "expected , got: {saved_settings2}"); + assert!(saved_settings2.contains(""), "expected doNotExpandShiftReturn, got: {saved_settings2}"); + assert!(!saved_settings2.contains("compatibilityMode"), "expected no compatibilityMode, got: {saved_settings2}"); + + let read_back2 = craft_docx::read(&saved_bytes2).unwrap(); + assert_eq!(read_back2.settings.compat_mode, None); + assert!(read_back2.settings.do_not_expand_shift_return); +} + +/// #3305: a hyperlink keeps the `w:history` a .docx file gave it (on, off or none), and a link +/// with no value, as one made in the app has, is written with history on and reads back the same. +#[test] +fn hyperlink_history_attribute_preservation_round_trips() { + use craft_wordmodel::props::LinkHistory; + let doc_xml_of = |bytes: &[u8]| { + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut xml = String::new(); + std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap(); + xml + }; + + // 1. Each model value is written as the matching attribute and read back as it. + for (history, written) in [(None, Some("1")), (Some(LinkHistory::Off), Some("0")), (Some(LinkHistory::Omitted), None)] { + let mut p = Paragraph::new(); + p.insert_text(0, "link", &CharProps { link: Some("https://example.com/".into()), link_history: history, ..Default::default() }).unwrap(); + let bytes = craft_docx::write(&doc_with(vec![p])).unwrap(); + let xml = doc_xml_of(&bytes); + assert!(xml.contains(" assert!(xml.contains(&format!(r#"w:history="{v}""#)), "{history:?}: {xml}"), + None => assert!(!xml.contains("w:history"), "{history:?}: {xml}"), + } + let read = craft_docx::read(&bytes).unwrap(); + assert_eq!(paras(&read)[0].props_of_char(0).link_history, history); + } + let mut p_one = Paragraph::new(); + p_one + .insert_text( + 0, + "link with history 1", + &CharProps { link: Some("https://example.com/hist-one".into()), link_history: None, ..Default::default() }, + ) + .unwrap(); + let d_one = doc_with(vec![p_one]); + + // 2. Original XML fixture round-trip: + // Verify that reading raw XML with omitted w:history and w:history="0" saves back identically. + let base = craft_docx::write(&d_one).unwrap(); + // Replace the hyperlink in document.xml to have NO w:history attribute + let orig_doc_xml = doc_xml_of(&base); + let xml_omitted_hist = orig_doc_xml.replace(r#" w:history="1""#, ""); + assert_ne!(orig_doc_xml, xml_omitted_hist); + let file_omitted = replace_part(&base, "word/document.xml", xml_omitted_hist.as_bytes()); + + let read_omitted = craft_docx::read(&file_omitted).unwrap(); + assert_eq!(paras(&read_omitted)[0].props_of_char(0).link_history, Some(LinkHistory::Omitted)); + let saved_omitted = craft_docx::write(&read_omitted).unwrap(); + let resaved_xml = doc_xml_of(&saved_omitted); + assert!(!resaved_xml.contains("w:history"), "expected no w:history on save, got: {resaved_xml}"); + + // Replace the hyperlink in document.xml to have w:history="0" + let xml_zero_hist = orig_doc_xml.replace(r#"w:history="1""#, r#"w:history="0""#); + assert_ne!(orig_doc_xml, xml_zero_hist); + let file_zero = replace_part(&base, "word/document.xml", xml_zero_hist.as_bytes()); + + let read_zero = craft_docx::read(&file_zero).unwrap(); + assert_eq!(paras(&read_zero)[0].props_of_char(0).link_history, Some(LinkHistory::Off)); + let saved_zero = craft_docx::write(&read_zero).unwrap(); + let resaved_zero_xml = doc_xml_of(&saved_zero); + assert!(resaved_zero_xml.contains(r#"w:history="0""#), "expected w:history=\"0\" on save, got: {resaved_zero_xml}"); + + // Replace the hyperlink in document.xml to have w:history=" 0 " (whitespace-padded false) + let xml_padded_zero = orig_doc_xml.replace(r#"w:history="1""#, r#"w:history=" 0 ""#); + assert_ne!(orig_doc_xml, xml_padded_zero); + let file_padded = replace_part(&base, "word/document.xml", xml_padded_zero.as_bytes()); + + let read_padded = craft_docx::read(&file_padded).unwrap(); + assert_eq!(paras(&read_padded)[0].props_of_char(0).link_history, Some(LinkHistory::Off)); + let saved_padded = craft_docx::write(&read_padded).unwrap(); + let resaved_padded_xml = doc_xml_of(&saved_padded); + assert!(resaved_padded_xml.contains(r#"w:history="0""#), "expected w:history=\"0\" on save, got: {resaved_padded_xml}"); +} + +/// #3305: a link the app makes, by laying a `CharProps` patch with a target over text, saves with +/// history on, as it did before `w:history` was kept from .docx files. +#[test] +fn a_link_made_with_a_char_props_patch_saves_with_history_on() { + let mut p = Paragraph::with_text("see the site", CharProps::default()); + let patch = CharProps { link: Some("https://example.com/".into()), ..Default::default() }; + p.format(4, 12, &|c| c.overlay(&patch)).unwrap(); + let bytes = craft_docx::write(&doc_with(vec![p])).unwrap(); + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut xml = String::new(); + std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap(); + assert!(xml.contains(""), "expected w:compat preserved for unowned settings: {s}"); + assert!(s.contains("overrideTableStyleFontSizeAndJustification"), "{s}"); + assert!(s.contains("enableOpenTypeFeatures"), "{s}"); + + let reopened = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); + assert_eq!(reopened.settings.compat_mode, None); + + // Case 2: compat_mode is set to None, but another switch is enabled. + doc.settings.do_not_expand_shift_return = true; + let files2 = save(&doc); + let s2 = text(&files2, "word/settings.xml"); + assert!(!s2.contains("compatibilityMode"), "expected mode removed: {s2}"); + assert!(s2.contains(""), "{s2}"); + assert!(s2.contains(""), "expected switch preserved: {s2}"); + assert!(s2.contains("overrideTableStyleFontSizeAndJustification"), "{s2}"); + assert!(s2.contains("enableOpenTypeFeatures"), "{s2}"); + + let reopened2 = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); + assert_eq!(reopened2.settings.compat_mode, None); + assert!(reopened2.settings.do_not_expand_shift_return); +} + /// Hide spelling errors and Hide grammar errors in this document only (`w:hideSpellingErrors`, /// `w:hideGrammaticalErrors`) are read, written once each (before `w:proofState` in a merged /// part), written in a generated part, and left out when they are turned off. diff --git a/crates/font-manager/src/glyphs.rs b/crates/font-manager/src/glyphs.rs index 25aca72fa5..ccdab018dd 100644 --- a/crates/font-manager/src/glyphs.rs +++ b/crates/font-manager/src/glyphs.rs @@ -1,6 +1,8 @@ //! [`GlyphsPanel`]: Photoshop's Glyphs panel. A family and style picker, a category list (Entire Font, Punctuation, //! Currency, ...), a grid of glyph cells drawn by the app's text engine, a zoom slider, and the recently used //! glyphs in a row at the top. Double-click or Enter inserts the glyph where the app can insert. +//! A secondary click on a grid cell reports that cell ([`GlyphsPanelOutput::menu`]); the app opens +//! the menu from the grid response. #[cfg(feature = "suite")] pub(crate) mod stories; @@ -209,6 +211,19 @@ pub struct GlyphsPanelOutput { pub alternate: Option, /// The family or style changed in the panel's own pickers. pub font_changed: bool, + /// The grid cell a context menu was asked for, with the grid response the menu hangs from. + /// Reported on the secondary click and on every later pass while that menu stays open. + pub menu: Option, +} + +/// A grid cell's context menu: the cell, and the grid response the app hangs the menu from. +#[derive(Debug)] +#[non_exhaustive] +pub struct GlyphCellMenu { + /// The cell. + pub cell: GlyphCell, + /// The grid the menu hangs from. + pub opener: Response, } /// The cell whose popup was used and the picked glyph. @@ -313,6 +328,30 @@ struct Marked { host: Option<(GlyphCell, usize)>, } +/// The glyph a context menu was opened on, and the face it was opened in. Later passes keep this glyph: the grid +/// remembers the row, and another glyph of a same-length list must not take the menu over. A glyph id names a glyph +/// only in its own face, so the menu holds the cell only while that face is shown: the same family and style, and +/// for a glyph id the same source revision, since the source can replace a face under the same names. +#[derive(Clone, Default)] +struct HeldMenu(Option); + +/// A held menu's cell, the family and style it was clicked in, and the source revision then. +#[derive(Clone)] +struct MenuCell { + cell: GlyphCell, + family: String, + style: String, + revision: u64, +} + +impl MenuCell { + /// Whether the cell still names the glyph it was clicked on in `face` at `revision`. A character names the same + /// glyph after the source reads its faces again; a glyph id may not. + fn holds_in(&self, face: (&str, &str), revision: u64) -> bool { + (self.family.as_str(), self.style.as_str()) == face && (matches!(self.cell, GlyphCell::Char(_)) || self.revision == revision) + } +} + /// The alternates popup: whether it is open, the cell it was opened for and that cell's alternates, read once when /// it opened. #[derive(Clone, Default)] @@ -337,10 +376,12 @@ fn recent_cells(recent: &[String]) -> Vec { seen.into_iter().map(GlyphCell::Char).collect() } -/// The cells of the shown set: the recents, or the source's cells of the category. +/// The cells of the shown set: the recents, or the source's cells of the category, read again when the source's +/// `revision` (read once for the pass) is not the one they were read at. fn category_cells( cache: &mut CellsCache, source: &dyn GlyphSource, + revision: u64, family: &str, style: &str, category: &str, @@ -350,7 +391,6 @@ fn category_cells( return Arc::new(recent_cells(recent)); } let key = (family.to_owned(), style.to_owned(), category.to_owned()); - let revision = source.revision(); if cache.key != key || cache.revision != revision { *cache = CellsCache { key, revision, cells: Arc::new(source.cells(family, style, category)) }; } @@ -486,12 +526,13 @@ impl<'a> GlyphsPanel<'a> { }); }); craft_ui::runtime::frame::request_repaint_after(ui.ctx(), SCAN_POLL_SECONDS); - return GlyphsPanelOutput { response: shown.output, activated: None, alternate: None, font_changed: false }; + return GlyphsPanelOutput { response: shown.output, activated: None, alternate: None, font_changed: false, menu: None }; } let ctx = ui.ctx().clone(); let mut activated_out: Option = None; let mut picked: Option = None; let mut font_changed = false; + let mut menu: Option = None; let shown = Stack::new().label(label).command_scope(GlyphsCommand::SCOPE).show(ui, |ui, cx| { cx.publish(GlyphsCommand::Alternates, CommandState::new()); let mut state = read_bind(&mut settings, cx).unwrap_or_default(); @@ -592,8 +633,10 @@ impl<'a> GlyphsPanel<'a> { } } - // The grid. - let cells = category_cells(cx.memory::(), source, face.0, face.1, &state.category, &state.recent); + // The grid. One revision read serves the pass: a menu cell is stamped with the revision its list was read + // at, so a source that moves on mid-pass cannot give an old glyph id the new revision. + let revision = source.revision(); + let cells = category_cells(cx.memory::(), source, revision, face.0, face.1, &state.category, &state.recent); let index_of = |cell: GlyphCell| cells.iter().position(|c| *c == cell); let mut marked = cx.memory::().clone(); let host = marked_cell.and_then(|cell| index_of(cell).map(|at| (cell, at))); @@ -633,6 +676,25 @@ impl<'a> GlyphsPanel<'a> { None => tile, } }); + // The click names the glyph. Later passes keep that glyph: the grid remembers the row, so a + // same-length list must not move the open menu onto whatever glyph is there now. + let clicked = shown_grid.response.events.iter().find_map(|event| match event { + CollectionEvent::ContextMenu(request) => cells.get(request.key).copied(), + _ => None, + }); + let mut held = std::mem::take(cx.memory::()); + if let Some(cell) = clicked { + held = HeldMenu(Some(MenuCell { cell, family: face.0.to_owned(), style: face.1.to_owned(), revision })); + } + // A closed menu lets go of its cell, and so does another face, or a glyph id after the source + // replaced its faces: the same id there is another glyph. + let other_face = held.0.as_ref().is_some_and(|held| !held.holds_in(face, revision)); + if shown_grid.response.menu.is_none() || other_face { + held = HeldMenu(None); + } + let opener = shown_grid.response.response.clone(); + menu = held.0.as_ref().map(|held| GlyphCellMenu { cell: held.cell, opener }); + *cx.memory::() = held; for event in shown_grid.response.events { match event { CollectionEvent::Activate(key) => activated = cells.get(key).copied().or(activated), @@ -718,6 +780,6 @@ impl<'a> GlyphsPanel<'a> { write_bind(&mut settings, cx, state, "Glyphs panel"); } }); - GlyphsPanelOutput { response: shown.output, activated: activated_out, alternate: picked, font_changed } + GlyphsPanelOutput { response: shown.output, activated: activated_out, alternate: picked, font_changed, menu } } } diff --git a/crates/font-manager/tests/it/glyphs.rs b/crates/font-manager/tests/it/glyphs.rs index c30ee8cdf9..0ce58b6479 100644 --- a/crates/font-manager/tests/it/glyphs.rs +++ b/crates/font-manager/tests/it/glyphs.rs @@ -3,9 +3,13 @@ use std::cell::RefCell; use std::rc::Rc; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use craft_font_manager::glyphs::{CellInfo, GlyphCell, GlyphSource, GlyphsPanel, GlyphsPanelSettings}; -use craft_ui::contract::Bind; +use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; +use craft_ui::menu::{Menu, MenuItem}; +use craft_ui::testing::pointer; use craft_ui::testing::{Fixture, Room, trial}; use egui::{ColorImage, Event}; @@ -43,6 +47,8 @@ struct Seen { marked: Option, reveal: Option, picks: Vec<(GlyphCell, GlyphCell)>, + /// Cells a secondary click asked for a menu on, in order. + menu: Vec, } fn rig() -> (Fixture, Rc>) { @@ -62,9 +68,13 @@ fn rig() -> (Fixture, Rc>) { if let Some(cell) = reveal { panel = panel.reveal(cell); } - if let Some(pick) = panel.show(ui).alternate { + let out = panel.show(ui); + if let Some(pick) = out.alternate { shown.borrow_mut().picks.push((pick.cell, pick.glyph)); } + if let Some(menu) = out.menu { + shown.borrow_mut().menu.push(menu.cell); + } }); fx.in_room(Room::Window); fx.settle(); @@ -158,6 +168,159 @@ fn a_corner_pick_reports_the_cell_and_the_glyph() { assert!(!visible(&fx, 'Ⓑ'), "a pick closes the popup"); } +#[trial] +fn a_secondary_click_reports_the_cell_the_menu_is_for() { + let (mut fx, seen) = rig(); + let cell = fx.by_label(&name(FIRST)).expect("the first cell"); + let at = cell.center(); + fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]); + fx.frame(vec![pointer::secondary(at, false)]); + fx.settle(); + let menu = seen.borrow().menu.clone(); + assert!(!menu.is_empty(), "the secondary click names the cell"); + assert!(menu.iter().all(|cell| *cell == GlyphCell::Char(FIRST)), "the menu is for the clicked cell: {menu:?}"); +} + +/// A list whose first cell changes, at the same length, when `swapped` is set. The revision changes with it, so the +/// panel reads the list again. +struct Swap(Arc); + +impl GlyphSource for Swap { + fn cells(&self, _: &str, _: &str, _: &str) -> Vec { + let first = if self.0.load(Ordering::Relaxed) { '\u{0102}' } else { FIRST }; + std::iter::once(GlyphCell::Char(first)).chain((1..300).filter_map(|i| char::from_u32(0x100 + i).map(GlyphCell::Char))).collect() + } + + fn glyph(&self, _: &str, _: &str, _: GlyphCell, _: u32) -> Option { + None + } + + fn revision(&self) -> u64 { + u64::from(self.0.load(Ordering::Relaxed)) + } +} + +#[trial] +fn an_open_menu_keeps_the_clicked_cell_when_that_row_changes() { + let swapped = Arc::new(AtomicBool::new(false)); + let source = Swap(Arc::clone(&swapped)); + let seen = Rc::new(RefCell::new(Vec::::new())); + let shown = Rc::clone(&seen); + let (mut family, mut style, mut settings) = ("Plain".to_owned(), "Regular".to_owned(), GlyphsPanelSettings::default()); + let mut fx = Fixture::new(move |ui| { + let out = GlyphsPanel::new("Glyphs", &source, Bind::bound(&mut family), Bind::bound(&mut style), Bind::bound(&mut settings)) + .can_insert(true) + .show(ui); + if let Some(menu) = out.menu { + shown.borrow_mut().push(menu.cell); + Menu::context("Glyph", &menu.opener).show(ui, |ui, _| { + MenuItem::new("Insert Glyph").show(ui); + }); + } + }); + fx.in_room(Room::Window); + fx.settle(); + let cell = fx.by_label(&name(FIRST)).expect("the first cell"); + let at = cell.center(); + fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]); + fx.frame(vec![pointer::secondary(at, false)]); + fx.settle(); + assert!(seen.borrow().contains(&GlyphCell::Char(FIRST)), "the click names the cell"); + + seen.borrow_mut().clear(); + swapped.store(true, Ordering::Relaxed); + fx.frame(Vec::new()); + fx.settle(); + let menu = seen.borrow().clone(); + assert!(!menu.is_empty(), "the menu stays open"); + assert!(menu.iter().all(|cell| *cell == GlyphCell::Char(FIRST)), "the row's new glyph does not take the menu: {menu:?}"); +} + +/// Unencoded glyphs 1 to 300 in every face and at every revision: the same id names another glyph in another face, +/// or in a face the source replaced under the same names. +struct Unencoded(Arc); + +impl GlyphSource for Unencoded { + fn cells(&self, _: &str, _: &str, _: &str) -> Vec { + (1..=300).map(GlyphCell::Glyph).collect() + } + + fn glyph(&self, _: &str, _: &str, _: GlyphCell, _: u32) -> Option { + None + } + + fn revision(&self) -> u64 { + self.0.load(Ordering::Relaxed) + } +} + +/// A host menu open on glyph 1 of an [`Unencoded`] source, with the family and the revision the test can change. +struct GlyphMenu { + fx: Fixture, + family: Rc>, + revision: Arc, + seen: Rc>>, +} + +impl GlyphMenu { + fn open() -> Self { + let revision = Arc::new(AtomicU64::new(0)); + let source = Unencoded(Arc::clone(&revision)); + let family = Rc::new(RefCell::new("Plain".to_owned())); + let host_family = Rc::clone(&family); + let seen = Rc::new(RefCell::new(Vec::::new())); + let shown = Rc::clone(&seen); + let (mut style, mut settings) = ("Regular".to_owned(), GlyphsPanelSettings::default()); + let mut fx = Fixture::new(move |ui| { + let out = { + let mut family = host_family.borrow_mut(); + GlyphsPanel::new("Glyphs", &source, Bind::bound(&mut *family), Bind::bound(&mut style), Bind::bound(&mut settings)) + .can_insert(true) + .show(ui) + }; + if let Some(menu) = out.menu { + shown.borrow_mut().push(menu.cell); + Menu::context("Glyph", &menu.opener).show(ui, |ui, _| { + MenuItem::new("Insert Glyph").show(ui); + }); + } + }); + fx.in_room(Room::Window); + fx.settle(); + let cell = fx.by_label("1, glyph 1").expect("the first glyph"); + let at = cell.center(); + fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]); + fx.frame(vec![pointer::secondary(at, false)]); + fx.settle(); + assert!(seen.borrow().contains(&GlyphCell::Glyph(1)), "the click names the glyph"); + seen.borrow_mut().clear(); + GlyphMenu { fx, family, revision, seen } + } + + /// The cells the menu reported over the next passes. + fn reported(&mut self) -> Vec { + self.fx.frame(Vec::new()); + self.fx.settle(); + self.seen.borrow().clone() + } +} + +#[trial] +fn an_open_menu_does_not_report_a_glyph_id_from_another_face() { + let mut open = GlyphMenu::open(); + *open.family.borrow_mut() = "Other".to_owned(); + let menu = open.reported(); + assert!(menu.is_empty(), "the clicked id names another glyph in the new face, so the menu reports none: {menu:?}"); +} + +#[trial] +fn an_open_menu_does_not_report_a_glyph_id_after_the_source_replaces_the_face() { + let mut open = GlyphMenu::open(); + open.revision.store(1, Ordering::Relaxed); + let menu = open.reported(); + assert!(menu.is_empty(), "the face behind the same names changed, so the clicked id names another glyph: {menu:?}"); +} + #[trial] fn glyphs_panel_alternates() { let (mut fx, _seen) = rig(); diff --git a/crates/proof/README.md b/crates/proof/README.md index bbf39f7be8..84d811f811 100644 --- a/crates/proof/README.md +++ b/crates/proof/README.md @@ -19,6 +19,7 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = " | French (fr-FR, fr-CA and other French pack locales) | the installed Language pack or Hunspell dictionary; dictionary-driven elisions and accent-oriented suggestions | conservative typography and basic checks, with Quebec punctuation spacing in fr-CA | the Language pack (generic fr fallback) | | German | — | — | TeX patterns (embedded, or a Language pack) | | Bulgarian | — | — | syllable rules | +| Gujarati, Hindi | the installed Hunspell dictionary (Hindi: nukta letters spelled either way) | generic checks | akshara rules (or a Language pack) | Grammar rules, suggestion tuning and the rule-based hyphenation are code: they work in every build. diff --git a/crates/proof/src/devanagari.rs b/crates/proof/src/devanagari.rs new file mode 100644 index 0000000000..aa48d7d5f7 --- /dev/null +++ b/crates/proof/src/devanagari.rs @@ -0,0 +1,88 @@ +//! What the proofing of a language written in Devanagari (Hindi now) needs to know about the +//! script, for the shared checks ([`crate::script_checks`]): its letters (as the akshara rules +//! classify them, [`crate::indic::Script::Devanagari`]), its digits and the two spellings of its +//! nukta letters. + +use crate::indic; +use crate::script_checks::Script; + +/// Devanagari for the shared checks. +pub(crate) const SCRIPT: Script = + Script { in_words: is_letter, is_letter, is_digit: is_devanagari_digit, variant: Some(nukta_variant as fn(&str) -> Option) }; + +fn is_letter(c: char) -> bool { + indic::Script::Devanagari.is_letter(c) +} + +/// Is `c` a Devanagari digit (`०`..=`९`, U+0966..=U+096F)? +fn is_devanagari_digit(c: char) -> bool { + ('\u{0966}'..='\u{096F}').contains(&c) +} + +/// The consonants with a precomposed nukta letter (U+0958..=U+095F): the base consonant, then +/// the precomposed letter. +const NUKTA_LETTERS: [(char, char); 8] = [ + ('\u{0915}', '\u{0958}'), + ('\u{0916}', '\u{0959}'), + ('\u{0917}', '\u{095A}'), + ('\u{091C}', '\u{095B}'), + ('\u{0921}', '\u{095C}'), + ('\u{0922}', '\u{095D}'), + ('\u{092B}', '\u{095E}'), + ('\u{092F}', '\u{095F}'), +]; + +/// The nukta sign (U+093C). +const NUKTA: char = '\u{093C}'; + +/// `w` with its nukta letters spelled the other way, if it has any: precomposed ones (`क़`, +/// U+0958) as consonant and nukta (`क` + `़`), else consonant-and-nukta pairs precomposed. +/// Composition (NFC) always gives the pair, since the precomposed letters are excluded from it, +/// but a dictionary may list either spelling. +pub(crate) fn nukta_variant(w: &str) -> Option { + let precomposed = |c: char| NUKTA_LETTERS.iter().find(|&&(_, p)| p == c).map(|&(base, _)| base); + if w.chars().any(|c| precomposed(c).is_some()) { + let mut out = String::with_capacity(w.len() + 4); + for c in w.chars() { + match precomposed(c) { + Some(base) => { + out.push(base); + out.push(NUKTA); + } + None => out.push(c), + } + } + return Some(out); + } + let mut out = String::with_capacity(w.len()); + let mut changed = false; + let mut chars = w.chars().peekable(); + while let Some(c) = chars.next() { + if let Some(&(_, p)) = NUKTA_LETTERS.iter().find(|&&(base, _)| base == c) + && chars.peek() == Some(&NUKTA) + { + chars.next(); + out.push(p); + changed = true; + } else { + out.push(c); + } + } + changed.then_some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nukta_letters_have_two_spellings() { + // ज़मीन precomposed and as ज + nukta; सड़क the same. + assert_eq!(nukta_variant("\u{095B}मीन").as_deref(), Some("ज\u{093C}मीन")); + assert_eq!(nukta_variant("ज\u{093C}मीन").as_deref(), Some("\u{095B}मीन")); + assert_eq!(nukta_variant("सड\u{093C}क").as_deref(), Some("स\u{095C}क")); + // A nukta on a consonant with no precomposed letter, and no nukta at all: one spelling. + assert_eq!(nukta_variant("स\u{093C}"), None); + assert_eq!(nukta_variant("किताब"), None); + } +} diff --git a/crates/proof/src/gu/grammar.rs b/crates/proof/src/gu/grammar.rs index 80a102f57a..1cc0f0891f 100644 --- a/crates/proof/src/gu/grammar.rs +++ b/crates/proof/src/gu/grammar.rs @@ -1,77 +1,30 @@ -//! Generic repeated-word and spacing checks with Gujarati messages. -//! No Gujarati-specific grammar or case rules are inferred. +//! Generic repeated-word and spacing checks, shared with the other languages proofed by their +//! script, with Gujarati messages. No Gujarati-specific grammar or case rules are inferred. -use crate::{Issue, IssueKind, ProofLang, words}; - -fn issue(start: usize, end: usize, message: String, suggestions: Vec) -> Issue { - Issue { start, end, kind: IssueKind::Grammar, message, suggestions, lang: ProofLang::Gu } -} +use crate::script_checks::Rules; +use crate::{Issue, ProofLang}; /// Checks `text` for repeated words and spacing problems, with Gujarati messages. pub fn check(text: &str) -> Vec { - let mut issues = Vec::new(); - repeated_words(text, &words(text), &mut issues); - spaces(text, &mut issues); - issues.sort_by_key(|i| (i.start, i.end)); - issues + crate::script_checks::check(text, &RULES) } +const RULES: Rules = Rules { + lang: ProofLang::Gu, + script: &super::SCRIPT, + repeated_word: "પુનરાવર્તિત શબ્દ", + space_before_punctuation: "વિરામચિહ્ન પહેલાં જગ્યા", + double_space: "બેવડી જગ્યા", + flag_repeat: |w| !ALLOWED_REPEATS.contains(&w), +}; + /// Words Gujarati repeats on purpose (`હા હા`, `ના ના`, `ધીમે ધીમે`, `સાચે સાચે`). const ALLOWED_REPEATS: &[&str] = &["હા", "ના", "ધીમે", "જલ્દી", "વારંવાર", "સાચે", "રોજે", "ખરેખર", "જરા", "થોડું", "સાથે", "પાસે"]; -fn is_digit(c: char) -> bool { - c.is_ascii_digit() || ('\u{0AE6}'..='\u{0AEF}').contains(&c) -} - -fn repeated_words(text: &str, ws: &[(usize, usize)], v: &mut Vec) { - for pair in ws.windows(2) { - let [(a0, b0), (a1, b1)] = pair else { continue }; - let (Some(w0), Some(w1), Some(gap)) = (text.get(*a0..*b0), text.get(*a1..*b1), text.get(*b0..*a1)) else { continue }; - if !gap.is_empty() - && gap.chars().all(char::is_whitespace) - && w0.chars().all(|c| c.is_alphabetic() || (super::is_gujarati_char(c) && !c.is_numeric())) - && w0 == w1 - && !ALLOWED_REPEATS.contains(&w0) - { - v.push(issue(*a0, *b1, format!("પુનરાવર્તિત શબ્દ: “{w1}”"), vec![w0.to_string()])); - } - } -} - -fn spaces(text: &str, v: &mut Vec) { - for (i, c) in text.char_indices() { - if c != ' ' { - continue; - } - let rest = text.get(i + 1..).unwrap_or(""); - let mut it = rest.chars(); - let Some(p) = it.next() else { continue }; - let after = it.next(); - // A ratio/score keeps the spaces in digit-space-colon-space-digit (ASCII or Gujarati digits). - let ratio = p == ':' - && text.get(..i).and_then(|before| before.chars().next_back()).is_some_and(is_digit) - && after == Some(' ') - && it.next().is_some_and(is_digit); - let flag = !ratio - && match p { - ',' => true, - ';' => !matches!(after, Some(')' | '(' | '-' | 'P' | 'D')), - '.' => !matches!(after, Some('.')) && !after.is_some_and(|a| a.is_ascii_digit()), - ':' | '!' | '?' => after.is_none_or(|a| a.is_whitespace() || matches!(a, '"' | '”' | '’' | '!' | '?')), - _ => false, - }; - if flag { - v.push(issue(i, i + 1 + p.len_utf8(), "વિરામચિહ્ન પહેલાં જગ્યા".into(), vec![p.to_string()])); - } - } - for run in crate::space_runs(text) { - v.push(issue(run.start, run.end, "બેવડી જગ્યા".into(), vec![" ".into()])); - } -} - #[cfg(test)] mod tests { use super::*; + use crate::IssueKind; #[test] fn intentional_repeats_are_fine() { diff --git a/crates/proof/src/gu/mod.rs b/crates/proof/src/gu/mod.rs index e72089a4ca..d511c4ecd3 100644 --- a/crates/proof/src/gu/mod.rs +++ b/crates/proof/src/gu/mod.rs @@ -1,6 +1,6 @@ //! Gujarati proofing using the installed Hunspell `gu_IN` dictionary (never bundled). //! Suggestions use its runtime MAP/REP/TRY/KEY tables. Generic grammar checks have Gujarati -//! messages; hyphenation keeps the existing fallback. +//! messages. Hyphenation is by akshara ([`crate::indic`]). pub mod grammar; pub(crate) mod suggest; @@ -10,6 +10,7 @@ pub(crate) mod test_dict; use std::sync::Arc; use crate::affix::AffixDict; +use crate::script_checks::Script; use crate::slot::DictSlot; pub use suggest::suggest; @@ -61,29 +62,20 @@ pub fn is_correct_with(d: &AffixDict, word: &str) -> bool { /// [`is_correct_with_options`] against a given dictionary. fn check(d: &AffixDict, word: &str, opts: &crate::Options) -> bool { - if d.is_empty() { - return true; - } - let w = word.trim_matches(|c: char| !c.is_alphanumeric() && !is_gujarati_char(c) && !matches!(c, '\'' | '’' | '-')); - let w = w.trim_matches(['\'', '’', '-']); - let letter_count = w.chars().filter(|&c| (is_gujarati_char(c) && !c.is_numeric()) || c.is_alphabetic()).count(); - if letter_count <= 1 || (opts.ignore_numbers && w.chars().any(char::is_numeric)) { - return true; - } - // A word in another script (or with no Gujarati characters) is not marked by this dictionary. - if !w.chars().any(is_gujarati_char) { - return true; - } - if w.contains('-') { - // The whole word first, as Hunspell does: a hyphenated entry or user word. - return known(d, w) || w.split('-').all(|p| p.chars().count() <= 1 || !p.chars().any(is_gujarati_char) || known(d, p)); - } - known(d, w) + crate::script_checks::is_correct(&SCRIPT, d, word, opts) } -/// Is one word (no hyphens) in the dictionary or the user dictionary? -fn known(d: &AffixDict, w: &str) -> bool { - d.check(w) || crate::in_user_dictionary(&w.to_lowercase()) +/// Gujarati for the shared checks: the whole block is kept in words, its letters are everything +/// in it but the digits. +pub(crate) const SCRIPT: Script = Script { in_words: is_gujarati_char, is_letter, is_digit: is_gujarati_digit, variant: None }; + +fn is_letter(c: char) -> bool { + is_gujarati_char(c) && !c.is_numeric() +} + +/// Is `c` a Gujarati digit (U+0AE6..=U+0AEF)? +fn is_gujarati_digit(c: char) -> bool { + ('\u{0AE6}'..='\u{0AEF}').contains(&c) } #[cfg(test)] diff --git a/crates/proof/src/hi/grammar.rs b/crates/proof/src/hi/grammar.rs new file mode 100644 index 0000000000..cc417f1b98 --- /dev/null +++ b/crates/proof/src/hi/grammar.rs @@ -0,0 +1,116 @@ +//! Generic repeated-word and spacing checks, shared with the other languages proofed by their +//! script, with Hindi messages. No Hindi-specific grammar or agreement rules are inferred. + +use crate::script_checks::Rules; +use crate::{Issue, ProofLang}; + +/// Checks `text` for repeated words and spacing problems, with Hindi messages. +pub fn check(text: &str) -> Vec { + crate::script_checks::check(text, &RULES) +} + +const RULES: Rules = Rules { + lang: ProofLang::Hi, + script: &crate::devanagari::SCRIPT, + repeated_word: "दोहराया गया शब्द", + space_before_punctuation: "विराम चिह्न से पहले रिक्त स्थान", + double_space: "दोहरा रिक्त स्थान", + flag_repeat, +}; + +/// Hindi doubles words on purpose all the time (`धीरे धीरे`, `बार बार`, `घर घर`, `छोटे छोटे`), +/// so a doubled Hindi word is flagged only when it is one of these postpositions, auxiliaries +/// and conjunctions, which are never doubled on purpose (`के के`, `है है`). A doubled word in +/// another script is flagged as in the other languages. +const NEVER_DOUBLED: &[&str] = &[ + "का", + "की", + "के", + "को", + "में", + "से", + "ने", + "पर", + "तक", + "है", + "हैं", + "था", + "थी", + "थे", + "हूँ", + "हूं", + "और", + "या", + "कि", + "एवं", + "तथा", + "लेकिन", + "परंतु", + "किंतु", + "क्योंकि", + "भी", +]; + +fn flag_repeat(w: &str) -> bool { + !w.chars().any(|c| ('\u{0900}'..='\u{097F}').contains(&c)) || NEVER_DOUBLED.contains(&w) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::IssueKind; + + #[test] + fn intentional_repeats_are_fine() { + for text in ["धीरे धीरे चलो।", "बार बार कहा।", "घर घर में दीये जले।", "कभी कभी", "अपने अपने घर जाओ।", "छोटे छोटे बच्चे"] + { + assert!(check(text).is_empty(), "{text}: {:?}", check(text)); + } + assert_eq!(check("मैं घर के के पास हूँ।").len(), 1); + assert_eq!(check("यह सच है है।").len(), 1); + assert!(check("1 1").is_empty()); + assert!(check("१ १").is_empty()); + } + + #[test] + fn repeated_words_and_spaces_have_hindi_messages() { + let text = "राम ने ने कहा , ठीक है।"; + let issues = check(text); + assert_eq!(issues.len(), 3, "{issues:?}"); + assert_eq!(issues[0].message, "दोहराया गया शब्द: “ने”"); + assert_eq!(issues[0].suggestions, ["ने"]); + assert_eq!(&text[issues[0].start..issues[0].end], "ने ने"); + assert!(issues.iter().any(|i| i.message == "विराम चिह्न से पहले रिक्त स्थान" && &text[i.start..i.end] == " ,")); + assert!(issues.iter().any(|i| i.message == "दोहरा रिक्त स्थान")); + assert!(issues.iter().all(|i| i.lang == ProofLang::Hi && i.kind == IssueKind::Grammar)); + // Latin words doubled inside Hindi text are still flagged. + assert_eq!(check("यह the the है").len(), 1); + } + + #[test] + fn a_space_before_the_danda_is_left_alone() { + for text in ["वह घर गया।", "वह घर गया ।", "श्लोक ॥"] { + assert!(check(text).is_empty(), "{text}: {:?}", check(text)); + } + } + + #[test] + fn ratios_and_scores_keep_their_spaces() { + for text in ["3 : 1", "स्कोर 12 : 10।", "३ : १", "१ : २", "स्कोर १२ : १०।"] { + assert!(check(text).is_empty(), "{text}: {:?}", check(text)); + } + for text in ["शब्द : दूसरा", "3 : शब्द", "3 :", "३ : शब्द", "३ :"] { + assert!(check(text).iter().any(|i| i.message == "विराम चिह्न से पहले रिक्त स्थान"), "{text}"); + } + } + + proptest::proptest! { + #[test] + fn never_panics_and_ranges_are_valid(s in "\\PC{0,80}") { + for issue in check(&s) { + proptest::prop_assert!(issue.start <= issue.end && issue.end <= s.len()); + proptest::prop_assert!(s.is_char_boundary(issue.start) && s.is_char_boundary(issue.end)); + } + } + } +} diff --git a/crates/proof/src/hi/mod.rs b/crates/proof/src/hi/mod.rs new file mode 100644 index 0000000000..047f78607a --- /dev/null +++ b/crates/proof/src/hi/mod.rs @@ -0,0 +1,171 @@ +//! Hindi proofing using the installed Hunspell `hi_IN` dictionary (never bundled). +//! Suggestions use its runtime MAP/REP/TRY/KEY tables. Spelling and the generic checks are the +//! ones Gujarati shares, with Devanagari's letters and digits and Hindi messages. Hyphenation is +//! by akshara ([`crate::indic`]). + +pub mod grammar; +pub(crate) mod suggest; +#[cfg(test)] +pub(crate) mod test_dict; + +use std::sync::Arc; + +use crate::affix::AffixDict; +use crate::slot::DictSlot; + +pub use suggest::suggest; + +/// File names of a Hindi Hunspell dictionary. +const NAMES: &[&str] = &["hi_IN", "hi-IN", "hi"]; + +/// The Hindi dictionary, found on first use (see [`DictSlot`]). +pub(crate) static DICT: DictSlot = DictSlot::new(NAMES, "Hindi"); + +/// The Hindi dictionary: the installed Hunspell `hi_IN` (read on first use), one given with +/// [`install_dictionary`], or an empty one when none is available (Hindi spelling is off then; +/// see [`has_dictionary`]). +pub fn dictionary() -> Arc { + DICT.get() +} + +/// Use this Hindi dictionary from now on (Hunspell `.aff` and `.dic` text, decoded to UTF-8), +/// for example one the user picked. On error the current dictionary stays. +pub fn install_dictionary(aff: &str, dic: &str) -> Result<(), String> { + DICT.install(aff, dic) +} + +/// Is a Hindi dictionary available (spelling is checked)? +pub fn has_dictionary() -> bool { + DICT.has_dictionary() +} + +/// Is `word` spelled correctly in Hindi? Numbers (ASCII or Devanagari digits), single letters, +/// short words with digits and words in other scripts are accepted, and so is every word when no +/// Hindi dictionary is installed. A nukta letter matches the dictionary however either spells it +/// (`ज़`, U+095B, or `ज` and the nukta). +pub fn is_correct(word: &str) -> bool { + is_correct_with(&dictionary(), word) +} + +/// [`is_correct`] with the File › Options › Proofing choices: with Ignore words that contain +/// numbers off, words with digits are checked. +pub fn is_correct_with_options(word: &str, opts: &crate::Options) -> bool { + check(&dictionary(), word, opts) +} + +/// [`is_correct`] against a given dictionary (an empty one accepts everything). +pub fn is_correct_with(d: &AffixDict, word: &str) -> bool { + check(d, word, &crate::Options::default()) +} + +/// [`is_correct_with_options`] against a given dictionary. +fn check(d: &AffixDict, word: &str, opts: &crate::Options) -> bool { + crate::script_checks::is_correct(&crate::devanagari::SCRIPT, d, word, opts) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dictionary_lookup_accepts_hindi_file_names() { + let dir = std::env::temp_dir().join(format!("wordcraft-hi-aliases-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + for name in ["hi_IN", "hi-IN", "hi"] { + std::fs::write(dir.join(format!("{name}.aff")), test_dict::AFF).unwrap(); + std::fs::write(dir.join(format!("{name}.dic")), test_dict::DIC).unwrap(); + let (aff, dic) = crate::hunspell::find_in(&dir, NAMES).unwrap(); + let d = crate::hunspell::load(&aff, &dic).unwrap(); + assert!(is_correct_with(&d, "किताबें")); + std::fs::remove_file(aff).unwrap(); + std::fs::remove_file(dic).unwrap(); + } + std::fs::remove_dir(dir).unwrap(); + } + + #[test] + fn hindi_words_affixes_and_misspellings() { + test_dict::install(); + assert!(has_dictionary()); + for w in [ + "घर", + "घरों", + "किताब", + "किताबें", + "किताबों", + "कमरा", + "कमरे", + "कमरों", + "बच्चे", + "बच्चों", + "गाँव", + "गाँवों", + "सफल", + "असफल", + "परीक्षण", + "घर-शहर", + "“किताब”", + ] { + assert!(is_correct(w), "{w}"); + } + for w in ["घरर", "किताबब", "पानीई", "कमरो", "zqप्रतिबंधित"] { + assert!(!is_correct(w), "{w}"); + } + } + + #[test] + fn missing_dictionary_and_ignored_inputs_are_quiet() { + let empty = AffixDict::default(); + assert!(is_correct_with(&empty, "किताबब")); + assert!(install_dictionary("FLAG bogus\n", "1\nघर\n").is_err()); + let d = AffixDict::from_hunspell(test_dict::AFF, test_dict::DIC, &[]).unwrap(); + for w in ["", "2026", "१२", "२०२६", "क", "।", "English", "日本語", "ગુજરાતી"] { + assert!(is_correct_with(&d, w), "{w}"); + } + let no_ignore = crate::Options { ignore_numbers: false, ..Default::default() }; + assert!(check(&d, "१२", &no_ignore)); + assert!(check(&d, "2026", &no_ignore)); + assert!(!check(&d, "घरर१२", &no_ignore)); + assert!(check(&d, "घरर१२", &crate::Options::default())); + } + + /// Composing a word (as every check does) splits a precomposed nukta letter into consonant + /// and nukta, so a dictionary that lists either spelling still knows the word. + #[test] + fn nukta_letters_match_either_spelling() { + crate::hold_dictionary_tests(); + // ज़मीन listed precomposed (U+095B), सड़क as ड and the nukta. + install_dictionary("SET UTF-8\n", "2\n\u{095B}मीन\nसड\u{093C}क\n").unwrap(); + for w in ["\u{095B}मीन", "ज\u{093C}मीन", "स\u{095C}क", "सड\u{093C}क"] { + assert!(crate::is_correct_in(w, crate::ProofLang::Hi), "{w:?}"); + } + assert!(!crate::is_correct_in("ज\u{093C}मीनन", crate::ProofLang::Hi)); + test_dict::install(); + } + + #[test] + fn user_dictionary_applies() { + test_dict::install(); + assert!(!is_correct("नयाशब्दहिंदी")); + crate::add_word("नयाशब्दहिंदी"); + assert!(is_correct("नयाशब्दहिंदी")); + } + + #[test] + fn hindi_dispatch_messages_options_and_mixed_spans() { + crate::hold_dictionary_tests(); + test_dict::install(); + assert!(crate::has_dictionary(Some("hi-IN"))); + assert!(crate::is_correct_for("किताबें", Some("hin"))); + // The danda ends the sentence and is no part of the word before it. + let text = "बच्चे किताबब घर।"; + let issues = crate::check_text(text, &[(0..text.len(), crate::ProofLang::Hi)]); + assert_eq!(issues.len(), 1, "{issues:?}"); + assert_eq!(&text[issues[0].start..issues[0].end], "किताबब"); + assert_eq!(issues[0].message, "संभावित वर्तनी त्रुटि"); + assert_eq!(issues[0].lang, crate::ProofLang::Hi); + let text = "घर this is is wrong"; + let issues = crate::check_text(text, &[(0..6, crate::ProofLang::Hi), (7..text.len(), crate::ProofLang::En)]); + assert!(issues.iter().any(|i| i.lang == crate::ProofLang::En && i.message.starts_with("Repeated word"))); + } +} diff --git a/crates/proof/src/hi/suggest.rs b/crates/proof/src/hi/suggest.rs new file mode 100644 index 0000000000..30bd707916 --- /dev/null +++ b/crates/proof/src/hi/suggest.rs @@ -0,0 +1,69 @@ +//! Hindi suggestions: the shared ranking ([`crate::affix_suggest`]) with the installed +//! dictionary's own MAP/REP/TRY/KEY tables and nothing Hindi hard-coded. + +use crate::affix::AffixDict; +use crate::affix_suggest::Tuning; + +/// Spelling suggestions for a Hindi word, best first, at most `max`. +pub fn suggest(word: &str, max: usize) -> Vec { + suggest_in(&super::dictionary(), word, max) +} + +/// [`suggest`] against a given dictionary. +pub fn suggest_in(d: &AffixDict, word: &str, max: usize) -> Vec { + crate::affix_suggest::suggest_in(d, word, max, &Tuning::DEFAULT) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hindi_suggestions_use_runtime_tables() { + crate::hi::test_dict::install(); + // MAP (ि/ी, ं/ँ), REP (कश → क्ष) and a doubled letter. + for (word, want) in [("पानि", "पानी"), ("गांव", "गाँव"), ("परीकशण", "परीक्षण"), ("प्रेमम", "प्रेम"), ("किताबो", "किताबों")] + { + let s = suggest(word, 8); + assert!(s.contains(&want.into()), "{word}: {s:?}"); + } + } + + #[test] + fn suggestions_stay_bounded_and_skip_forbidden_words() { + crate::hi::test_dict::install(); + for w in ["", "दो शब्द", &"क".repeat(41)] { + assert!(suggest(w, 4).is_empty()); + } + assert!(suggest("घर", 0).is_empty()); + assert!(suggest_in(&AffixDict::default(), "घर", 4).is_empty()); + for word in ["zqबहुतलंबाहिंदीशब्द", "किताबब", "परीक्षणण"] { + let res = suggest(word, 6); + assert!(res.len() <= 6, "{word}: got {} suggestions", res.len()); + assert!(!res.contains(&"zqप्रतिबंधित".to_string()), "{word}: {res:?}"); + assert!(res.iter().all(|s| !s.is_empty() && crate::hi::is_correct(s)), "{word}: {res:?}"); + } + } + + /// A NOSUGGEST stem stays correct spelling, but the Hindi collector never offers it or any + /// prefixed, suffixed or REP-reached form of it; ordinary stems are still offered. + #[test] + fn nosuggest_stems_and_forms_are_never_offered() { + let aff = "SET UTF-8\nNOSUGGEST N\nTRY गुप्तसामान्यअताएँ\nREP 2\nREP गुपत गुप्त\nREP सामानय सामान्य\nPFX X Y 1\nPFX X 0 अ .\nSFX A Y 1\nSFX A 0 ता/B .\nSFX B Y 1\nSFX B 0 एँ .\n"; + let d = AffixDict::from_hunspell(aff, "2\nगुप्त/NXA\nसामान्य/XA\n", &[]).unwrap(); + let hidden = d.forms("गुप्त"); + assert!(hidden.contains(&"अगुप्त".into()) && hidden.contains(&"गुप्तताएँ".into()), "{hidden:?}"); + for word in hidden.iter().chain(&["अगुप्तताएँ".to_string()]) { + assert!(d.check(word), "NOSUGGEST is still correct: {word}"); + assert!(!d.can_suggest(word), "NOSUGGEST form: {word}"); + } + for input in ["गुपत", "अगुपत", "गुपतता", "अगुपतताएँ", "गुप्तत", "अगुप्तताए"] + { + let got = suggest_in(&d, input, 32); + assert!(got.iter().all(|w| w.split(' ').all(|part| d.can_suggest(part))), "{input}: {got:?}"); + assert!(got.iter().all(|w| !w.contains("गुप्त")), "{input}: {got:?}"); + } + assert!(suggest_in(&d, "सामानय", 8).contains(&"सामान्य".into())); + assert!(suggest_in(&d, "असामानयता", 8).contains(&"असामान्यता".into())); + } +} diff --git a/crates/proof/src/hi/test_dict.rs b/crates/proof/src/hi/test_dict.rs new file mode 100644 index 0000000000..bf0b128ea1 --- /dev/null +++ b/crates/proof/src/hi/test_dict.rs @@ -0,0 +1,47 @@ +//! Hand-written synthetic Hindi test data. No words, rules or suggestion tables were copied +//! from a system dictionary. This is a small fixture, not a redistributable Hindi dictionary. + +pub const AFF: &str = "SET UTF-8 +FLAG UTF-8 +FORBIDDENWORD F +TRY अआइईउऊऋएऐओऔकखगघङचछजझञटठडढणतथदधनपफबभमयरलवशषसहािीुूृेैोौ्ंःँ +KEY सश|तद +MAP 4 +MAP इईिी +MAP उऊुू +MAP सशष +MAP ंँ +REP 1 +REP कश क्ष +SFX P Y 2 +SFX P ा े ा +SFX P ा ों ा +SFX O Y 1 +SFX O 0 ों . +SFX E Y 1 +SFX E 0 ें . +PFX X Y 1 +PFX X 0 अ . +"; + +pub const DIC: &str = "14 +घर/O +शहर/O +गाँव/O +मित्र/O +किताब/OE +कमरा/P +बच्चा/P +भाषा +पानी +परीक्षण +प्रेम +सूर्य +सफल/X +zqप्रतिबंधित/F +"; + +pub fn install() { + crate::hold_dictionary_tests(); + super::install_dictionary(AFF, DIC).unwrap(); +} diff --git a/crates/proof/src/hyphen.rs b/crates/proof/src/hyphen.rs index 862526bb58..45f8118051 100644 --- a/crates/proof/src/hyphen.rs +++ b/crates/proof/src/hyphen.rs @@ -15,6 +15,10 @@ //! //! **Bulgarian**: the Bulgarian syllable rules ([`crate::bg`]); no pattern file or word list. //! +//! **Gujarati and Hindi**: breaks between aksharas, never inside a conjunct or between a +//! consonant and its vowel sign ([`crate::indic`], rules from the script's Unicode encoding); no +//! pattern file. +//! //! **German**: the TeX German patterns for the reformed spelling ([`Patterns::de`]), also for //! Swiss text, whose `ss` the patterns split like any double consonant (`Stras-se`). //! @@ -116,7 +120,7 @@ pub enum Source { Patterns, /// A heuristic for a language without a dictionary or patterns. Heuristic, - /// A language's syllable rules (Bulgarian, [`crate::bg`]). + /// A language's syllable rules (Bulgarian [`crate::bg`], Turkish, Gujarati and Hindi [`crate::indic`]). Rules, /// No break points: the word is too short or no source applies. None, @@ -131,6 +135,13 @@ fn is_word_char(c: char) -> bool { c.is_alphabetic() || is_apostrophe(c) || unicode_normalization::char::is_combining_mark(c) } +/// [`is_word_char`] in `lang`. In a language with Indic rules a zero-width joiner or non-joiner +/// is part of the word too: it shapes a conjunct inside an akshara ([`crate::indic`]). In any +/// other language it still ends a letter run (Persian's ZWNJ between a word's parts). +fn is_word_char_in(c: char, lang: ProofLang) -> bool { + is_word_char(c) || (crate::indic::is_joiner(c) && crate::indic::Script::of(lang.built_in()).is_some()) +} + /// Unrestricted break points of one lowercase core (letters and `'` only, no leading/trailing `'`). fn core_breaks(core: &[char], lang: ProofLang) -> (Vec, Source) { let n = core.len(); @@ -156,6 +167,13 @@ fn core_breaks(core: &[char], lang: ProofLang) -> (Vec, Source) { if lang == ProofLang::Bg && core.iter().all(|&c| crate::bg::is_letter(c)) { return (crate::bg::points(core), Source::Rules); } + // Gujarati and Hindi words break between aksharas ([`crate::indic`]); other words in their runs + // (`WordCraft`) are hyphenated as English. + if let Some(script) = crate::indic::Script::of(lang) + && core.iter().all(|&c| script.is_letter(c)) + { + return (crate::indic::points(script, core), Source::Rules); + } // A suffix written after an apostrophe (`Ankara'dan`, `Türkiye'nin`) is hyphenated part by // part; no break goes next to the apostrophe ([`word_breaks_in`] drops those). if lang == ProofLang::Tr && core.iter().all(|&c| c == '\'' || crate::tr::hyphen::is_letter(c)) { @@ -224,9 +242,10 @@ fn composed_chars(core: &[char]) -> (Vec, Vec>) { (nfc, starts) } -/// Does a pack's `pats` hyphenate `core` in `lang`? Russian, Bulgarian, Turkish and Gujarati: a -/// word in their script (the guard their rules use) whose letters the patterns know, so a word with a -/// letter the pack never mentions goes on to the fallback rules. Polish, Portuguese, Italian +/// Does a pack's `pats` hyphenate `core` in `lang`? Russian, Bulgarian, Turkish, Gujarati and +/// Hindi: a word in their script (the guard their rules use; for Gujarati and Hindi, the script's +/// letters and marks and the joiners inside a conjunct, [`crate::indic`]) whose letters the +/// patterns know, so a word with a letter the pack never mentions goes on to the fallback rules. Polish, Portuguese, Italian /// and German: every word, as their embedded patterns do. Any other language: a word whose letters /// the patterns know. fn pack_patterns_fit(lang: ProofLang, pats: &Patterns, core: &[char]) -> bool { @@ -235,7 +254,9 @@ fn pack_patterns_fit(lang: ProofLang, pats: &Patterns, core: &[char]) -> bool { ProofLang::Bg => core.iter().all(|&c| crate::bg::is_letter(c)) && pack_knows(pats, core), ProofLang::Tr => core.iter().all(|&c| crate::tr::hyphen::is_letter(c)) && pack_knows(pats, core), ProofLang::Pl | ProofLang::Pt | ProofLang::It | ProofLang::De => true, - ProofLang::Gu => core.iter().all(|&c| crate::gu::is_gujarati_char(c)) && pack_knows(pats, core), + ProofLang::Gu | ProofLang::Hi => { + crate::indic::Script::of(lang).is_some_and(|s| core.iter().all(|&c| s.is_letter(c))) && pack_knows(pats, core) + } _ => pats.values(core).is_some(), } } @@ -311,12 +332,12 @@ pub fn word_breaks_in(word: &str, lang: ProofLang) -> (Vec, Source) { let mut src = Source::None; let mut i = 0; while i < chars.len() { - if !is_word_char(chars[i]) { + if !is_word_char_in(chars[i], lang) { i += 1; continue; } let mut j = i; - while j < chars.len() && is_word_char(chars[j]) { + while j < chars.len() && is_word_char_in(chars[j], lang) { j += 1; } let (mut a, mut b) = (i, j); @@ -370,7 +391,7 @@ pub fn hyphen_points_in(word: &str, lim: &Limits, lang: ProofLang) -> Vec let mut i = 0; while i < chars.len() { let mut j = i; - while chars.get(j).is_some_and(|c| is_word_char(*c)) { + while chars.get(j).is_some_and(|c| is_word_char_in(*c, lang)) { j += 1; } let (mut a, mut b) = (i, j); diff --git a/crates/proof/src/hyphen/tests.rs b/crates/proof/src/hyphen/tests.rs index d8f8cf4318..26705716e7 100644 --- a/crates/proof/src/hyphen/tests.rs +++ b/crates/proof/src/hyphen/tests.rs @@ -194,3 +194,44 @@ fn gujarati_pack_patterns_fit_checks_script_and_exceptions() { let en_word: Vec = "hyphenation".chars().collect(); assert!(!pack_patterns_fit(ProofLang::Gu, &pats, &en_word)); } + +/// CodeRabbit on craft-libs#3905: a word with a joiner in a conjunct still reaches its pack's +/// exception word (here: no break at all), in Gujarati and Hindi. +#[test] +fn indic_pack_exceptions_reach_words_with_joiners() { + for (lang, word) in [(ProofLang::Gu, "પુસ્\u{200D}તક"), (ProofLang::Hi, "पुस्\u{200D}तक")] { + let pats = Patterns::parse(&format!("1ક 1क \\hyphenation{{{word}}}")); + let core: Vec = word.chars().collect(); + assert!(pack_patterns_fit(lang, &pats, &core), "{lang:?}"); + assert_eq!(core_breaks_patterns(&pats, &core), (vec![], Source::Dictionary), "{lang:?}"); + } +} + +/// storytold/vectorcraft#4947: Gujarati text breaks between aksharas, within the paragraph's +/// limits, where it used to fall to the English rules and get no break at all; a Latin word in +/// a Gujarati run is still hyphenated as English. +#[test] +fn gujarati_breaks_between_aksharas_within_the_limits() { + let lim = Limits::default(); + let gu = |w: &str| hyphenate_word_in(w, &lim, ProofLang::Gu); + assert_eq!(gu("વિદ્યાર્થી"), "વિ-દ્યા-ર્થી", "a conjunct is never split"); + assert_eq!(word_breaks_in("વિદ્યાર્થી", ProofLang::Gu).1, Source::Rules); + // A lone consonant at either end is fewer letters than `after_first`/`before_last` allow. + assert_eq!(gu("અમદાવાદ"), "અમ-દા-વાદ"); + assert_eq!(gu("«ગુજરાતી»"), "«ગુ-જ-રા-તી»", "punctuation around the word"); + assert_eq!(gu("Typography"), hyphenate_word_in("Typography", &lim, ProofLang::En)); + // A joiner in a conjunct doesn't cut the word in two (each part then too short to break). + assert_eq!(gu("પુસ્\u{200D}તક"), "પુ-સ્\u{200D}તક"); +} + +/// Hindi text breaks between Devanagari aksharas by the same rules, where it used to get no +/// break; a Latin word in a Hindi run is still hyphenated as English. +#[test] +fn hindi_breaks_between_aksharas_within_the_limits() { + let lim = Limits::default(); + let hi = |w: &str| hyphenate_word_in(w, &lim, ProofLang::Hi); + assert_eq!(hi("विद्यार्थी"), "वि-द्या-र्थी", "a conjunct is never split"); + assert_eq!(word_breaks_in("विद्यार्थी", ProofLang::Hi).1, Source::Rules); + assert_eq!(hi("«विद्यार्थी»"), "«वि-द्या-र्थी»", "punctuation around the word"); + assert_eq!(hi("Typography"), hyphenate_word_in("Typography", &lim, ProofLang::En)); +} diff --git a/crates/proof/src/indic.rs b/crates/proof/src/indic.rs new file mode 100644 index 0000000000..9da779458b --- /dev/null +++ b/crates/proof/src/indic.rs @@ -0,0 +1,254 @@ +//! Hyphenation of Indic scripts by rule: a word breaks only between its orthographic syllables +//! (aksharas), never inside one. +//! +//! An akshara is a consonant with what is written on it — its vowel sign, nukta, anusvara, +//! candrabindu or visarga — and the consonants joined to it by a virama (a conjunct: `દ્ય`, `ર્થ`, +//! `न्द`), or an independent vowel with its marks. So a break goes only before a consonant or an +//! independent vowel that does not follow a virama: `ગુ-જ-રા-તી`, `વિ-દ્યા-ર્થી`, `સં-સ્કૃત`, +//! `हि-न्दी`. A vowel sign, a mark or the second consonant of a conjunct never starts a line. +//! Nor does a dead consonant — one ending in a virama with no consonant after it (`વાક્`) — since +//! it has no vowel of its own and is the end of the syllable before. A zero-width joiner or +//! non-joiner after a virama (`સ્` U+200D `ત`) only chooses how the conjunct is drawn: it stays +//! inside the akshara, and no break goes next to a joiner. +//! +//! The rules come from the scripts' Unicode encoding alone; no pattern file or word list is +//! read (and none is borrowed). The Brahmic blocks share one layout (the ISCII order), so a +//! script is its block's start and a few script-specific code points (`Script::kind`). +//! Gujarati ([`ProofLang::Gu`]) and Hindi ([`ProofLang::Hi`], [`Script::Devanagari`]) use them; +//! another language written in one of these scripts is one more line in [`Script::of`]. +//! +//! A single akshara left at the end or start of a line is ruled out by the paragraph's +//! [`Limits`](crate::hyphen::Limits), which count letters (vowel signs and anusvara count, +//! viramas and nuktas don't), so a bare consonant (`…-ત`) is not carried over with the default +//! limits but a consonant with its vowel sign (`…-તી`) is. + +use crate::ProofLang; + +/// An Indic script hyphenated by [`points`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Script { + /// Devanagari (U+0900..=U+097F): Hindi, Marathi, Nepali… + Devanagari, + /// Gujarati (U+0A80..=U+0AFF). + Gujarati, +} + +/// What a code point is in an akshara. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + /// An independent vowel: starts an akshara. + Vowel, + /// A consonant: starts an akshara, unless a virama joins it to the consonant before. + Consonant, + /// The virama: joins the consonant before it to the next one, or kills its vowel. + Virama, + /// A vowel sign, nukta, anusvara, candrabindu, visarga or other mark (and the avagraha): + /// belongs to the akshara before it. + Mark, + /// A zero-width joiner or non-joiner: shapes the conjunct around it, in the same akshara. + Joiner, +} + +/// Is `c` a zero-width joiner or non-joiner (U+200D, U+200C)? Inside an Indic word it shapes a +/// conjunct, so it is part of the word (as in Unicode's word boundaries, UAX #29). +pub fn is_joiner(c: char) -> bool { + matches!(c, '\u{200C}' | '\u{200D}') +} + +impl Script { + /// The script whose rules hyphenate `lang`'s words, if any. + pub fn of(lang: ProofLang) -> Option