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/wordmodel/src/props.rs b/crates/wordmodel/src/props.rs index 8833656e37..0165d6dc43 100644 --- a/crates/wordmodel/src/props.rs +++ b/crates/wordmodel/src/props.rs @@ -23,8 +23,8 @@ mod para_props; mod table_props; pub use char_props::{ - CharProps, CombineBrackets, DEFAULT_FONT_SIZE, EastAsianLayout, EmphasisMark, Highlight, Ligatures, NumChange, PropChange, ThemeFont, Underline, - VertAlign, + CharProps, CombineBrackets, DEFAULT_FONT_SIZE, EastAsianLayout, EmphasisMark, Highlight, Ligatures, LinkHistory, NumChange, PropChange, + ThemeFont, Underline, VertAlign, }; pub use color::{Rgb, TextColor}; pub use para_props::{ diff --git a/crates/wordmodel/src/props/char_props.rs b/crates/wordmodel/src/props/char_props.rs index 556d035406..f5e6a93a76 100644 --- a/crates/wordmodel/src/props/char_props.rs +++ b/crates/wordmodel/src/props/char_props.rs @@ -165,6 +165,18 @@ impl ThemeFont { } } +/// A hyperlink's `w:history` when a .docx file didn't have it on. Only the .docx reader sets one. +/// A link with none, whether made in the app, read from another format or read with history on, +/// is written with history on, so it reads back the same. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum LinkHistory { + /// `w:history` was off. + Off, + /// The hyperlink had no `w:history`, so none is written back. + Omitted, +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)] #[serde(rename_all = "camelCase")] pub enum VertAlign { @@ -435,6 +447,10 @@ pub struct CharProps { /// Optional ScreenTip for the hyperlink. Runs from one link can share its text. #[serde(skip_serializing_if = "Option::is_none")] pub link_tooltip: Option>, + /// The hyperlink's `w:history` when a .docx file had it off or left it out. `None` writes it + /// on, as Word does for a new link. + #[serde(skip_serializing_if = "Option::is_none")] + pub link_history: Option, /// Tracked insertion: index into `Document::revisions`. #[serde(skip_serializing_if = "Option::is_none")] pub ins: Option, @@ -572,6 +588,7 @@ impl CharProps { c.style = None; } c.link_tooltip = None; + c.link_history = None; c } @@ -632,9 +649,10 @@ impl CharProps { } fn minus_document_marks(&mut self, base: &CharProps) { - if self.link == base.link && self.link_tooltip == base.link_tooltip { + if self.link == base.link && self.link_tooltip == base.link_tooltip && self.link_history == base.link_history { self.link = None; self.link_tooltip = None; + self.link_history = None; } drop_same_fields!(self, base; ins, del, ligatures); } @@ -689,6 +707,7 @@ impl CharProps { if let Some(link) = &patch.link { self.link = Some(link.clone()); self.link_tooltip = patch.link_tooltip.clone(); + self.link_history = patch.link_history; } overlay_fields!(self, patch; ins, del, fmt_change, ligatures); } @@ -716,6 +735,7 @@ impl CharProps { CharProps { link: self.link.clone(), link_tooltip: self.link_tooltip.clone(), + link_history: self.link_history, ins: self.ins, del: self.del, fmt_change: self.fmt_change.clone(), @@ -726,6 +746,6 @@ impl CharProps { } /// Just the formatting: without the link, revision marks and tracked formatting change. pub fn formatting(&self) -> CharProps { - CharProps { link: None, link_tooltip: None, ins: None, del: None, fmt_change: None, ..self.clone() } + CharProps { link: None, link_tooltip: None, link_history: None, ins: None, del: None, fmt_change: None, ..self.clone() } } } diff --git a/crates/wordmodel/src/settings.rs b/crates/wordmodel/src/settings.rs index d7689fa66d..d4447312f5 100644 --- a/crates/wordmodel/src/settings.rs +++ b/crates/wordmodel/src/settings.rs @@ -124,8 +124,9 @@ pub struct Settings { pub protect_hash: Vec<(String, String)>, /// Word compatibility mode the document is laid out in (`compatibilityMode`): 15 for Word /// 2013 and later, which places a table's border at the margin rather than its text and lets - /// justified lines shrink their spaces to fit more text. - pub compat_mode: u32, + /// justified lines shrink their spaces to fit more text. `None` when omitted from the file. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compat_mode: Option, /// Fonts the document's font table classes as roman (serif, `w:family w:val="roman"`): Word /// draws one that isn't installed in a serif face. #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -326,7 +327,7 @@ impl Default for Settings { protection: None, protect_formatting: false, protect_hash: Vec::new(), - compat_mode: COMPAT_MODE_CURRENT, + compat_mode: Some(COMPAT_MODE_CURRENT), roman_fonts: Vec::new(), sum_paragraph_spacing: false, do_not_expand_shift_return: false, @@ -346,3 +347,11 @@ impl Default for Settings { } } } + +impl Settings { + /// The effective compatibility mode: the authored mode, or Word 2007 (`LEGACY_COMPAT_MODE` = 12) + /// when omitted from the file. + pub fn effective_compat_mode(&self) -> u32 { + self.compat_mode.unwrap_or(LEGACY_COMPAT_MODE) + } +} diff --git a/crates/wordmodel/src/tests.rs b/crates/wordmodel/src/tests.rs index b4d1b17dd4..f5ab928c7f 100644 --- a/crates/wordmodel/src/tests.rs +++ b/crates/wordmodel/src/tests.rs @@ -309,6 +309,27 @@ fn json_round_trip() { assert_eq!(back.para(StoryRef::Body, &Path::top(0)).unwrap().runs[0].props.bold, Some(true)); } +#[test] +fn settings_compat_mode_serde_round_trip() { + let mut s = Settings::default(); + assert_eq!(s.compat_mode, Some(COMPAT_MODE_CURRENT)); + s.compat_mode = None; + let json = serde_json::to_string(&s).unwrap(); + assert!(!json.contains("compatMode"), "expected compatMode omitted: {json}"); + let back: Settings = serde_json::from_str(&json).unwrap(); + assert_eq!(back.compat_mode, None); + assert_eq!(back.effective_compat_mode(), LEGACY_COMPAT_MODE); + + let from_empty: Settings = serde_json::from_str("{}").unwrap(); + assert_eq!(from_empty.compat_mode, None); + + s.compat_mode = Some(14); + let json14 = serde_json::to_string(&s).unwrap(); + assert!(json14.contains(r#""compatMode":14"#), "{json14}"); + let back14: Settings = serde_json::from_str(&json14).unwrap(); + assert_eq!(back14.compat_mode, Some(14)); +} + #[test] fn ensure_nonempty_repairs() { let mut d = Document::new();