From ed8c7c2621378c0922ce9bca187b9f7f37b165b8 Mon Sep 17 00:00:00 2001 From: alehel Date: Sun, 15 Nov 2026 21:57:18 +0100 Subject: [PATCH 1/8] ODT: a style or list change keeps the file's other definitions Any style or list change threw away every definition in the file's office:styles and wrote them all from the model, which does not hold everything: gradients, fill pictures, styles the model doesn't have and the default style's settings were lost. The import now records, per office:styles child, a hash of what the writer would write for it (KeptXml::style_prints, replacing the single styles_fp fingerprint) and which of the file's style names it read into which style id (KeptXml::style_ids). A save rewrites only the definitions whose hash changed, under the file's own names, escaped, with parent and next style named as the file named them; a deleted style stays deleted; everything else is written as read. Ported from storytold/wordcraft#5702 (the ODT reader and writer now live here). Co-Authored-By: Claude Opus 5.5 --- crates/odf/src/text/import.rs | 9 +- crates/odf/src/text/kept.rs | 137 ++++++++- crates/odf/src/text/package.rs | 29 +- crates/odf/src/text/tests_more/kept.rs | 333 ++++++++++++++++++++- crates/odf/src/text/tests_more/lossless.rs | 25 ++ crates/wordmodel/src/kept.rs | 24 +- 6 files changed, 527 insertions(+), 30 deletions(-) diff --git a/crates/odf/src/text/import.rs b/crates/odf/src/text/import.rs index 486e67a260..45a89bd9c4 100644 --- a/crates/odf/src/text/import.rs +++ b/crates/odf/src/text/import.rs @@ -1143,11 +1143,16 @@ pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result k.keep_file(path, bytes); } k.section_masters = section_masters; + // Which of the file's styles became which of the document's (by kept key): a save names + // an edited style's definition, parent and next style by the file's names for them. + let paras = named_odt.iter().map(|n| (format!("common:{n}"), super::styles::style_id(n))); + let texts = char_styles.iter().map(|(n, id)| (format!("common:{n}|text"), id.clone())); + k.style_ids = paras.chain(texts).collect(); } doc.seal_kept(); - let (fp, pages) = (craft_wordmodel::kept::styles_fingerprint(&doc), craft_wordmodel::kept::pages_fingerprint(&doc)); + let (prints, pages) = (super::package::style_prints(&doc), craft_wordmodel::kept::pages_fingerprint(&doc)); if let Some(k) = doc.kept.get_mut() { - (k.styles_fp, k.pages_fp) = (Some(fp), Some(pages)); + (k.style_prints, k.pages_fp) = (prints, Some(pages)); } Ok(doc) } diff --git a/crates/odf/src/text/kept.rs b/crates/odf/src/text/kept.rs index e9efebdec3..953b672cc3 100644 --- a/crates/odf/src/text/kept.rs +++ b/crates/odf/src/text/kept.rs @@ -313,16 +313,143 @@ fn drawing_def(xml: &str) -> bool { /// `styles` (a `styles.xml` WordCraft wrote) with its `office:styles` as read: every kept /// child of the file's, then WordCraft's own children the file had no such of. A drawing's -/// definition both have stays WordCraft's (see [`drawing_def`]). For a document whose style -/// definitions are as read. -pub(super) fn with_common_as_read(styles: &str, defs: &BTreeMap>, order: &[String]) -> String { - with_as_read(styles, "office:styles", "common", defs, order, &|_, d, ours| match ours { - Some(o) if drawing_def(o) => Some(o.to_string()), +/// definition both have stays WordCraft's (see [`drawing_def`]), as does one in `changed`, which +/// the document has changed since it was read. One in `changed` that WordCraft no longer writes +/// (a deleted style) goes. +pub(super) fn with_common_as_read( + styles: &str, + defs: &BTreeMap>, + order: &[String], + changed: &BTreeSet, + rewritten: &BTreeMap>, +) -> String { + with_as_read(styles, "office:styles", "common", defs, order, &|k, d, ours| match ours { + _ if rewritten.contains_key(k) => rewritten.get(k).cloned().flatten(), + Some(o) if drawing_def(o) || changed.contains(k) => Some(o.to_string()), + None if changed.contains(k) => None, // (The default graphic style is the file's: WordCraft's drawings say what they need.) _ => Some(d.to_string()), }) } +/// What becomes of the file's styles (`defs`) that `changed` touches but `styles` (the part being +/// written) doesn't have under the file's key, by those keys: WordCraft's definition from `now` +/// (all it would write) under the file's names, or `None` for a style it no longer has. `ids` +/// gives the style id the import read a file's style into ([`KeptXml::style_ids`]), `ours` the +/// name WordCraft writes an id under: paragraphs written as read name the file's. A style the +/// import didn't read is WordCraft's only under its own name, so another of the file's styles +/// WordCraft would have under the same id (`Base_20_Style` beside `BaseStyle`) is left alone. +/// +/// [`KeptXml::style_ids`]: craft_wordmodel::kept::KeptXml::style_ids +pub(super) fn rewritten_defs( + styles: &str, + now: &str, + defs: &BTreeMap>, + changed: &BTreeSet, + ids: &BTreeMap, + ours: &dyn Fn(&str) -> String, +) -> BTreeMap> { + use std::collections::{HashMap, HashSet}; + // A common style's name and its family's key suffix: a text style's name isn't a paragraph + // style's. + let style_of = |key: &str| { + let rest = key.strip_prefix("common:")?; + match rest.strip_suffix("|text") { + Some(name) => Some((name.to_string(), "|text")), + None => (!rest.contains('|')).then(|| (rest.to_string(), "")), + } + }; + // Each of the file's styles, its family and the name WordCraft writes it under; and by that + // name and family, the file's name (the first the import read into it). + let mut styles_of: Vec<(&String, String, &str, String)> = Vec::new(); + let mut theirs: HashMap<(&str, String), String> = HashMap::new(); + for key in defs.keys() { + let Some((name, family)) = style_of(key) else { continue }; + let mine = match ids.get(key) { + Some(id) => { + let mine = ours(id); + if mine != name { + theirs.entry((family, mine.clone())).or_insert_with(|| name.clone()); + } + mine + } + None => name.clone(), + }; + styles_of.push((key, name, family, mine)); + } + let (kids, _) = children(now, "office:styles", "common"); + let kids: HashMap = kids.into_iter().collect(); + let (written, _) = children(styles, "office:styles", "common"); + let written: HashSet = written.into_iter().map(|(k, _)| k).collect(); + let mut out = BTreeMap::new(); + for (key, name, family, mine) in styles_of { + let mine = format!("common:{mine}{family}"); + if !changed.contains(&mine) || (mine == *key && written.contains(key)) { + continue; + } + let def = kids.get(&mine).and_then(|(a, b)| now.get(*a..*b)).map(|d| { + renamed(d, &|attr, v| match attr { + // Two of the file's names can be one of WordCraft's: a style keeps its own. + "style:name" => Some(name.clone()), + _ => theirs.get(&(family, v.to_string())).cloned(), + }) + }); + out.insert(key.clone(), def); + } + out +} + +/// `def` (markup WordCraft wrote) with the values of its `style:name`, `style:parent-style-name` +/// and `style:next-style-name` attributes that `to` gives another name for (by attribute and +/// value) renamed to that, escaped. One pass: WordCraft writes these names unescaped (they are +/// letters, digits and `_xNN_`). +fn renamed(def: &str, to: &dyn Fn(&str, &str) -> Option) -> String { + const ATTRS: [&str; 3] = ["style:name", "style:parent-style-name", "style:next-style-name"]; + let mut out = String::with_capacity(def.len()); + let mut rest = def; + while let Some(at) = rest.find("=\"") { + let (head, tail) = rest.split_at(at + 2); + let attr = head.get(..at).and_then(|h| h.rsplit(|c: char| c.is_whitespace()).next()).unwrap_or(""); + let Some(end) = tail.find('"') else { break }; + let (value, tail) = tail.split_at(end); + out.push_str(head); + match ATTRS.contains(&attr).then(|| to(attr, value)).flatten() { + Some(name) => out.push_str(&super::writer::x(&name)), + None => out.push_str(value), + } + rest = tail; + } + out.push_str(rest); + out +} + +/// Each child of `office:styles` in `styles` (a `styles.xml` WordCraft wrote), as a hash by its +/// key: what to compare to tell which definitions a document has changed since it was read. +pub(super) fn prints(styles: &str) -> BTreeMap { + use std::hash::{Hash, Hasher}; + let (kids, _) = children(styles, "office:styles", "common"); + kids.into_iter() + .filter_map(|(key, (a, b))| { + let mut h = std::collections::hash_map::DefaultHasher::new(); + styles.get(a..b)?.hash(&mut h); + Some((key, h.finish())) + }) + .collect() +} + +/// The keys whose definition differs between `then` and `now` ([`prints`]), and those no longer +/// in `now` (a deleted style). Standard goes with +/// the default paragraph style: WordCraft writes Normal in the default style, and Standard empty +/// over it, so the file's own Standard would hide a change to Normal. +pub(super) fn changed(then: &BTreeMap, now: &BTreeMap) -> BTreeSet { + let mut out: BTreeSet = now.iter().filter(|(k, v)| then.get(*k) != Some(*v)).map(|(k, _)| k.clone()).collect(); + out.extend(then.keys().filter(|k| !now.contains_key(*k)).cloned()); + if out.contains("common~style:default-style~paragraph") { + out.insert("common:Standard".to_string()); + } + out +} + /// `styles` (a `styles.xml` WordCraft wrote) with its page layouts, master pages and their /// automatic styles as read, WordCraft's own added where the file had none by that name. For a /// document whose page setup is as read. diff --git a/crates/odf/src/text/package.rs b/crates/odf/src/text/package.rs index 97520027c9..3b91a02b52 100644 --- a/crates/odf/src/text/package.rs +++ b/crates/odf/src/text/package.rs @@ -815,17 +815,40 @@ fn conn_kinds(blocks: &[FBlock]) -> super::HashMap std::collections::BTreeMap { + super::kept::prints(&model_styles(doc)) +} + +/// What WordCraft would write of `doc`'s style definitions: all of them, used or not. +fn model_styles(doc: &Document) -> String { + let ids = |custom: fn(&Document, &str) -> bool| doc.styles.styles.iter().filter(|s| custom(doc, &s.id)).map(|s| s.id.clone()).collect(); + // The first section, as a save writes the document-wide line numbering from it. + let first = doc.sections().first().map_or_else(|| doc.last_section.clone(), |(_, s)| (*s).clone()); + let page = [(String::new(), first)]; + let xml = styles_xml(doc, &page, &[], "", &ids(model::is_custom_style)); + let text = char_styles(doc, &ids(model::is_custom_char_style)); + xml.replacen("", &format!("{text}"), 1) +} + +/// `styles` with the file's own style definitions except those `doc` has since changed (see /// `super::kept`), and the font faces they name added to those kept paragraphs need (`used`). +/// Changing one style or list leaves the rest of what the file defines alone: its gradients and +/// fill pictures, the styles WordCraft doesn't model, its default style's settings. fn styles_as_read(doc: &Document, kept: Option<&craft_wordmodel::kept::KeptXml>, styles: String, used: &mut super::kept::Needed) -> String { - let Some(k) = kept.filter(|k| k.styles_as_read(doc)) else { return styles }; + let Some(k) = kept else { return styles }; // With the font faces they name (any of the file's, by its names). for (key, d) in &k.defs { if let Some(name) = key.strip_prefix("font:") { used.2.entry(name.to_string()).or_insert_with(|| d.clone()); } } - super::kept::with_common_as_read(&styles, &k.defs, &k.order) + let now = model_styles(doc); + let changed = super::kept::changed(&k.style_prints, &super::kept::prints(&now)); + // The name WordCraft writes a style id under (`My_20_Custom` was read as `MyCustom`). + let ours = |id: &str| super::writer::odf_name(id); + let rewritten = super::kept::rewritten_defs(&styles, &now, &k.defs, &changed, &k.style_ids, &ours); + super::kept::with_common_as_read(&styles, &k.defs, &k.order, &changed, &rewritten) } /// The package files the file's own definitions refer to, and those the markup written as read diff --git a/crates/odf/src/text/tests_more/kept.rs b/crates/odf/src/text/tests_more/kept.rs index 88d271142a..d47ea57389 100644 --- a/crates/odf/src/text/tests_more/kept.rs +++ b/crates/odf/src/text/tests_more/kept.rs @@ -128,12 +128,18 @@ fn unedited_style_definitions_are_written_as_read() { assert!(s.contains(r#"x:odd="1""#) && s.contains(r#"xmlns:x="urn:example:x""#), "{s}"); assert_eq!(s.matches("").next().is_some_and(|q| q.contains(r#"fo:font-weight="bold""#))), + "{s}" + ); assert_eq!(s.matches(r#" Vec { + let ns = crate::text::tests::NS_T; + let draw = + r#"xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0""#; + let styles = format!( + r##""## + ); + let content = format!( + r#"TextInOwn"# + ); + crate::text::tests::package(&content, Some(&styles)) +} + +#[test] +fn changing_one_style_leaves_the_files_other_definitions_alone() { + use std::sync::Arc; + let bytes = file_with_definitions(); + let as_read = |saved: &[u8]| { + let s = crate::text::tests::entry(saved, "styles.xml"); + assert!(s.contains(r#"draw:gradient draw:name="Sunset""#), "its gradient: {s}"); + assert!(s.contains(r#"fo:margin-bottom="7pt""#), "a style WordCraft doesn't model: {s}"); + assert!(s.contains(r#"style:wrap="dynamic""#), "what its frames derive from: {s}"); + assert!(s.contains(r#"style:writing-mode="page""#) && s.contains(r#"fo:language="de""#), "its default style: {s}"); + s + }; + // A style no text uses. + let mut d = crate::text::import(&bytes).unwrap(); + Arc::make_mut(&mut d.styles).get_mut("Quote").unwrap().chr.size = Some(13.0); + let saved = crate::text::export(&d).unwrap(); + let s = as_read(&saved); + assert!(s.contains(r#"fo:font-size="13pt""#), "the change: {s}"); + assert_eq!(crate::text::import(&saved).unwrap().styles.get("Quote").unwrap().chr.size, Some(13.0)); + // A style the file defined: that one is WordCraft's now, the others still the file's. + let mut d = crate::text::import(&bytes).unwrap(); + Arc::make_mut(&mut d.styles).get_mut("Eigen").unwrap().chr.size = Some(21.0); + let saved = crate::text::export(&d).unwrap(); + let s = as_read(&saved); + assert!(s.contains(r#"fo:font-size="21pt""#) && !s.contains(r#"fo:font-size="9pt""#), "{s}"); + // A new list (`para.numbering`): the styles as read, and the list there. + let mut d = crate::text::import(&bytes).unwrap(); + Arc::make_mut(&mut d.numbering).add_list(craft_wordmodel::numbering::ListKind::Bullet); + as_read(&crate::text::export(&d).unwrap()); + // Normal changed: the default style and Standard are WordCraft's. + let mut d = crate::text::import(&bytes).unwrap(); + Arc::make_mut(&mut d.styles).default_chr.size = Some(15.0); + let s = crate::text::tests::entry(&crate::text::export(&d).unwrap(), "styles.xml"); + assert!(s.contains(r#"fo:font-size="15pt""#), "{s}"); + assert!(s.contains(r#"draw:gradient draw:name="Sunset""#) && s.contains(r#"fo:margin-bottom="7pt""#), "the rest stays: {s}"); + // Nothing changed: the file's own, and none of WordCraft's over them. + let d = crate::text::import(&bytes).unwrap(); + as_read(&crate::text::export(&d).unwrap()); +} + +/// A style deleted in WordCraft stays deleted: the file's own definition doesn't come back with +/// the definitions that stay as read. +#[test] +fn a_deleted_style_stays_deleted() { + use std::sync::Arc; + let mut d = crate::text::import(&file_with_definitions()).unwrap(); + assert!(d.styles.get("Eigen").is_some()); + Arc::make_mut(&mut d.styles).remove("Eigen"); + d.restyle("Eigen", None); + let saved = crate::text::export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(!s.contains(r#"style:name="Eigen""#), "{s}"); + assert!(s.contains(r#"draw:gradient draw:name="Sunset""#) && s.contains(r#"fo:margin-bottom="7pt""#), "the rest stays: {s}"); + assert!(!crate::text::tests::entry(&saved, "content.xml").contains("Eigen")); + assert!(crate::text::import(&saved).unwrap().styles.get("Eigen").is_none()); +} + +/// A file's style whose name has a space (`My_20_Custom`, WordCraft's `MyCustom`) is one style. An +/// edit reaches its definition under the file's name, a deletion removes it, and left alone it +/// stays as read with no second definition. A style nothing uses any more keeps its edit. +#[test] +fn a_style_named_with_a_space_is_the_files_style() { + use std::sync::Arc; + let s = r#""#; + let styles = format!(r#"{s}"#); + let content = format!( + r#"OneTwoThree"# + ); + let bytes = package(&content, Some(&styles)); + let open = || import(&bytes).unwrap(); + let def = |xml: &str, name: &str| xml.split(""#; + let styles = format!(r#"{s}"#); + let content = format!( + r#"OneTwo"# + ); + let mut d = import(&package(&content, Some(&styles))).unwrap(); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.size = Some(21.0); + let saved = styles_of(&export(&d).unwrap()); + for name in ["My_20_Custom", "My_Custom"] { + assert_eq!(saved.matches(&format!(r#"style:name="{name}""#)).count(), 1, "{name}: {saved}"); + let def = saved.split(&format!(r#"style:name="{name}""#)).nth(1).and_then(|d| d.split("").next()).unwrap(); + assert!(def.contains(r#"fo:font-size="21pt""#), "{name}: {def}"); + } +} + +/// A parent's name goes by its family: a text style's other name isn't a paragraph style's. +#[test] +fn a_rewritten_styles_parent_keeps_its_own_familys_name() { + use std::sync::Arc; + let s = r#""#; + let styles = format!(r#"{s}"#); + let content = format!( + r#"OneTwo three"# + ); + let mut d = import(&package(&content, Some(&styles))).unwrap(); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.italic = Some(true); + let bytes = export(&d).unwrap(); + let saved = styles_of(&bytes); + let mine = saved.split("').next()).unwrap(); + assert!(mine.contains(r#"style:parent-style-name="BaseStyle""#), "{mine}"); + let back = import(&bytes).unwrap(); + let p = back.body[0].as_para().unwrap(); + assert_eq!(back.styles.resolve_char(p.props.style.as_deref(), &Default::default()).size, 30.0, "inherited"); +} + +/// Whether `xml` reads as XML: tags close in order and every attribute value unescapes. +fn reads_as_xml(xml: &str) -> bool { + // craft-xml's strict read refuses unbalanced tags, malformed attributes and unknown + // references, but takes a bare `&` as itself: each `&` must start a reference too. + let refs = xml.split('&').skip(1).all(|r| { + let name = r.split(';').next().unwrap_or(""); + r.contains(';') && !name.is_empty() && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'#') + }); + let mut events = craft_xml::Options::default().strict().events(xml.as_bytes()); + loop { + match events.next() { + Ok(Some(_)) => {} + Ok(None) => return refs, + Err(_) => return false, + } + } +} + +/// A file's paragraph style `styles` (markup inside `office:styles`) and paragraphs naming +/// `used`, opened. +fn opened(styles: &str, used: &[&str]) -> craft_wordmodel::Document { + let styles = format!(r#"{styles}"#); + let body: String = used.iter().map(|n| format!(r#"Text"#)).collect(); + let content = + format!(r#"{body}"#); + import(&package(&content, Some(&styles))).unwrap() +} + +/// The definition of the style named `name` (as written, escaped) in `xml`, up to its end. +fn def_named(xml: &str, name: &str) -> Option { + xml.split("").next()) + .map(String::from) +} + +/// A file's style whose name has `&`, `"` or `<` in it, edited, is written under its name escaped. +#[test] +fn an_edited_styles_name_is_written_escaped() { + use std::sync::Arc; + for name in ["R&D", "Say"Hi", "A<B"] { + let s = format!( + r#""# + ); + let mut d = opened(&s, &[name]); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.size = Some(21.0); + let bytes = export(&d).unwrap(); + let saved = styles_of(&bytes); + assert!(reads_as_xml(&saved), "{name}: {saved}"); + assert!(def_named(&saved, name).is_some_and(|d| d.contains(r#"fo:font-size="21pt""#)), "{name}: {saved}"); + let back = import(&bytes).unwrap(); + assert_eq!(back.styles.resolve_char(back.body[0].as_para().unwrap().props.style.as_deref(), &Default::default()).size, 21.0, "{name}"); + } +} + +/// An edited style's parent is the file's style the import read it from, not another of the +/// file's styles WordCraft would have under the same id (`BaseStyle`, `Base_20_Style`). +#[test] +fn a_rewritten_styles_parent_is_the_one_it_was_read_from() { + use std::sync::Arc; + let s = r#""#; + let mut d = opened(s, &["My_20_Custom"]); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.italic = Some(true); + let bytes = export(&d).unwrap(); + let saved = styles_of(&bytes); + let mine = def_named(&saved, "My_20_Custom").unwrap_or_else(|| panic!("{saved}")); + assert!(mine.contains(r#"style:parent-style-name="BaseStyle""#), "{mine}"); + assert!(def_named(&saved, "Base_20_Style").is_some_and(|d| d.contains(r#"fo:font-size="9pt""#)), "as read: {saved}"); + let back = import(&bytes).unwrap(); + assert_eq!(back.styles.resolve_char(back.body[0].as_para().unwrap().props.style.as_deref(), &Default::default()).size, 30.0, "inherited"); +} + +/// A style nothing in the file uses keeps its own definition when a used one WordCraft has +/// under the same id (`My_20_Custom`, `My_Custom`) is edited. +#[test] +fn an_unused_style_sharing_an_edited_ones_id_keeps_its_definition() { + use std::sync::Arc; + let s = r##""##; + let mut d = opened(s, &["My_20_Custom"]); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.size = Some(21.0); + let saved = styles_of(&export(&d).unwrap()); + assert!(def_named(&saved, "My_20_Custom").is_some_and(|d| d.contains(r#"fo:font-size="21pt""#)), "{saved}"); + let theirs = def_named(&saved, "My_Custom").unwrap_or_else(|| panic!("{saved}")); + assert!(theirs.contains(r#"fo:font-size="30pt""#) && theirs.contains("#ff0000"), "as read: {theirs}"); +} + +/// A character style WordCraft read under another id (`AccentChar`, as a paragraph style has +/// `Accent`), edited, is written under the file's name: the text written as read names that. +#[test] +fn an_edited_character_style_read_under_another_id_keeps_the_files_name() { + use std::sync::Arc; + let s = r#""#; + let styles = format!(r#"{s}"#); + let content = format!( + r#"One two"# + ); + let mut d = import(&package(&content, Some(&styles))).unwrap(); + let id = + d.styles.styles.iter().find(|s| s.kind == craft_wordmodel::styles::StyleKind::Character && s.name == "Accent").map(|s| s.id.clone()).unwrap(); + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.size = Some(21.0); + let saved = styles_of(&export(&d).unwrap()); + let text = saved + .split("').next().is_some_and(|h| h.contains(r#"style:family="text""#))) + .and_then(|d| d.split("").next()) + .unwrap_or_else(|| panic!("{saved}")); + assert!(text.contains(r#"fo:font-size="21pt""#), "{text}"); +} + +/// Many of the file's styles WordCraft has under one id (`My-Custom`, `My.Custom`…), one edited: +/// the save looks each name up once, not every name for every style. +#[test] +fn many_styles_sharing_an_id_save_quickly() { + use std::sync::Arc; + let names: Vec = + (0..6_000u32).map(|i| format!("My{}Custom", (0..13).map(|b| if i >> b & 1 == 1 { '-' } else { '.' }).collect::())).collect(); + let mut s = String::from(r#""#); + for n in &names { + s.push_str(&format!(r#""#)); + } + let used: Vec<&str> = names.iter().take(500).map(String::as_str).collect(); + let mut d = opened(&s, &used); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.size = Some(21.0); + let t = std::time::Instant::now(); + let saved = styles_of(&export(&d).unwrap()); + assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed()); + assert_eq!(saved.matches(r#"fo:font-size="21pt""#).count(), 500, "the ones read into it"); + assert_eq!(saved.matches(r#"fo:font-size="9pt""#).count(), 5_500, "the others as read"); +} + #[test] fn the_files_font_declarations_are_kept() { // A reader without a font picks its substitute by how the file declares it. WordCraft's own @@ -316,3 +620,26 @@ fn a_name_space_on_the_font_declarations_goes_with_them() { assert!(part.contains(r#"xmlns:x="urn:example:x""#), "{part}"); } } + +/// Line numbering changed in the first of two sections is saved: the file's own definition stays +/// only while the section the save writes it from is as read (#5702 review). +#[test] +fn line_numbering_changed_in_the_first_section_is_saved() { + let styles = format!( + r#""# + ); + let content = format!( + r#"One.Two."# + ); + let bytes = package(&content, Some(&styles)); + let mut d = import(&bytes).unwrap(); + assert_eq!(d.sections().len(), 2, "two sections"); + let first = d.body.iter_mut().find_map(|b| match std::sync::Arc::make_mut(b) { + craft_wordmodel::Block::Para(p) => p.section.as_deref_mut(), + _ => None, + }); + let first = first.expect("the first section"); + first.line_numbers.as_mut().expect("line numbering as read").count_by = 3; + let s = styles_of(&export(&d).unwrap()); + assert!(s.contains(r#"text:increment="3""#) && !s.contains(r#"text:increment="5""#), "the change: {s}"); +} diff --git a/crates/odf/src/text/tests_more/lossless.rs b/crates/odf/src/text/tests_more/lossless.rs index 7d05e34910..6dc6506be5 100644 --- a/crates/odf/src/text/tests_more/lossless.rs +++ b/crates/odf/src/text/tests_more/lossless.rs @@ -169,6 +169,31 @@ fn a_save_without_edits_loses_nothing() { } } +/// The same gate after an edit: a save must lose nothing the edit didn't touch. Our loss checks +/// once only saved without edits, and missed that one style change rewrote every definition. +#[test] +fn a_style_or_list_change_loses_nothing_else() { + let edits: [(&str, fn(&mut craft_wordmodel::Document)); 2] = [ + ("an unused style", |d| { + if let Some(st) = std::sync::Arc::make_mut(&mut d.styles).get_mut("Quote") { + st.chr.size = Some(13.0); + } + }), + ("a new list", |d| { + std::sync::Arc::make_mut(&mut d.numbering).add_list(craft_wordmodel::numbering::ListKind::Bullet); + }), + ]; + for s in SAMPLES { + for (what, edit) in &edits { + let orig = package(&s); + let mut d = import(&orig).unwrap(); + edit(&mut d); + let lost = losses(&orig, &export(&d).unwrap()); + assert!(lost.is_empty(), "{}: lost after changing {what}:\n {}", s.name, lost.join("\n ")); + } + } +} + #[test] fn the_gate_sees_a_loss() { let with = Sample { diff --git a/crates/wordmodel/src/kept.rs b/crates/wordmodel/src/kept.rs index fcf52b60bc..e7b537439a 100644 --- a/crates/wordmodel/src/kept.rs +++ b/crates/wordmodel/src/kept.rs @@ -74,9 +74,13 @@ pub struct KeptXml { pub order: Vec, /// Files of the package kept definitions refer to (a style's fill picture), by path. pub files: BTreeMap>>, - /// The document's style definitions' [`styles_fingerprint`] when read: while it is the - /// same, the file's own style definitions can be written as they were. - pub styles_fp: Option, + /// What the format would write for each style definition when read, by [`KeptXml::defs`]' + /// key, as a hash: while a definition's is the same, the file's own is written as it was. + pub style_prints: BTreeMap, + /// The style id the reader read each of the file's styles into, by [`KeptXml::defs`]' key: + /// only those it read (its text's styles and what they derive from), not every style the + /// file defines. + pub style_ids: BTreeMap, /// The document's page setup's [`pages_fingerprint`] when read: while it is the same, the /// file's own page layouts and master pages can be written as they were. pub pages_fp: Option, @@ -267,20 +271,6 @@ impl KeptXml { let now = in_scope(doc, |sc| *sc.pages.get_or_insert_with(|| pages_fingerprint(doc))).unwrap_or_else(|| pages_fingerprint(doc)); fp == now } - /// Whether `doc`'s style definitions are still as they were read. - pub fn styles_as_read(&self, doc: &crate::Document) -> bool { - self.styles_fp.is_some_and(|fp| fp == styles_fingerprint(doc)) - } -} - -/// What `doc`'s style definitions are: its styles, lists and default tab interval. -pub fn styles_fingerprint(doc: &crate::Document) -> u64 { - let mut h = std::collections::hash_map::DefaultHasher::new(); - match serde_json::to_vec(&(&doc.styles, &doc.numbering, doc.settings.default_tab)) { - Ok(v) => v.hash(&mut h), - Err(_) => u64::MAX.hash(&mut h), - } - h.finish() } /// What a block is, as the kept markup knows it: its paragraphs' fingerprints and From 96320ea14610bb0eb28cf88ea2e11f02d78bdd4c Mon Sep 17 00:00:00 2001 From: alehel Date: Mon, 16 Nov 2026 15:21:24 +0100 Subject: [PATCH 2/8] ODT: an edited style keeps its parent's and an unread namesake's file definitions An edited style the file names as WordCraft does (`Eigen`) was skipped by the rewrite, so its parent kept WordCraft's name (`BaseStyle`) instead of the file's (`Base_20_Style`). It is now rewritten like any other. A style the import didn't read whose name is the one WordCraft writes a read style under (`MyCustom` beside `My_20_Custom`) took that style's edit or deletion. It now keeps its own definition. Co-Authored-By: Claude Opus 5.5 --- crates/odf/src/text/kept.rs | 33 ++++++++++++------- crates/odf/src/text/package.rs | 2 +- crates/odf/src/text/tests_more/kept.rs | 45 ++++++++++++++++++++++++++ 3 files changed, 67 insertions(+), 13 deletions(-) diff --git a/crates/odf/src/text/kept.rs b/crates/odf/src/text/kept.rs index 953b672cc3..3e507e5b67 100644 --- a/crates/odf/src/text/kept.rs +++ b/crates/odf/src/text/kept.rs @@ -332,17 +332,17 @@ pub(super) fn with_common_as_read( }) } -/// What becomes of the file's styles (`defs`) that `changed` touches but `styles` (the part being -/// written) doesn't have under the file's key, by those keys: WordCraft's definition from `now` -/// (all it would write) under the file's names, or `None` for a style it no longer has. `ids` -/// gives the style id the import read a file's style into ([`KeptXml::style_ids`]), `ours` the -/// name WordCraft writes an id under: paragraphs written as read name the file's. A style the -/// import didn't read is WordCraft's only under its own name, so another of the file's styles -/// WordCraft would have under the same id (`Base_20_Style` beside `BaseStyle`) is left alone. +/// What becomes of the file's styles (`defs`) that `changed` touches, by their keys: WordCraft's +/// definition from `now` (all it would write) under the file's names, its parent and next style +/// included, or `None` for a style it no longer has. `ids` gives the style id the import read a +/// file's style into ([`KeptXml::style_ids`]), `ours` the name WordCraft writes an id under: +/// paragraphs written as read name the file's. A style the import didn't read is WordCraft's only +/// under its own name, so another of the file's styles WordCraft would have under the same id +/// (`Base_20_Style` beside `BaseStyle`) is left alone, as is one the import didn't read named as +/// WordCraft names one it did (`MyCustom` beside `My_20_Custom`). /// /// [`KeptXml::style_ids`]: craft_wordmodel::kept::KeptXml::style_ids pub(super) fn rewritten_defs( - styles: &str, now: &str, defs: &BTreeMap>, changed: &BTreeSet, @@ -377,16 +377,25 @@ pub(super) fn rewritten_defs( }; styles_of.push((key, name, family, mine)); } + // The names WordCraft writes the styles the import read under, by family: one of the file's + // styles the import didn't read but named so (`MyCustom` beside `My_20_Custom`) isn't theirs. + let read: HashSet<(&str, &str)> = + styles_of.iter().filter(|(key, ..)| ids.contains_key(*key)).map(|(_, _, family, mine)| (*family, mine.as_str())).collect(); let (kids, _) = children(now, "office:styles", "common"); let kids: HashMap = kids.into_iter().collect(); - let (written, _) = children(styles, "office:styles", "common"); - let written: HashSet = written.into_iter().map(|(k, _)| k).collect(); let mut out = BTreeMap::new(); - for (key, name, family, mine) in styles_of { + for (key, name, family, mine) in &styles_of { + let (key, name, family) = (*key, name, *family); + let read_so = !ids.contains_key(key) && read.contains(&(family, mine.as_str())); let mine = format!("common:{mine}{family}"); - if !changed.contains(&mine) || (mine == *key && written.contains(key)) { + if !changed.contains(&mine) { continue; } + if read_so { + out.insert(key.clone(), defs.get(key).map(|d| d.to_string())); + continue; + } + // Rewritten even under its own name: its parent or next style may have another. let def = kids.get(&mine).and_then(|(a, b)| now.get(*a..*b)).map(|d| { renamed(d, &|attr, v| match attr { // Two of the file's names can be one of WordCraft's: a style keeps its own. diff --git a/crates/odf/src/text/package.rs b/crates/odf/src/text/package.rs index 3b91a02b52..6e1b73a3a8 100644 --- a/crates/odf/src/text/package.rs +++ b/crates/odf/src/text/package.rs @@ -847,7 +847,7 @@ fn styles_as_read(doc: &Document, kept: Option<&craft_wordmodel::kept::KeptXml>, let changed = super::kept::changed(&k.style_prints, &super::kept::prints(&now)); // The name WordCraft writes a style id under (`My_20_Custom` was read as `MyCustom`). let ours = |id: &str| super::writer::odf_name(id); - let rewritten = super::kept::rewritten_defs(&styles, &now, &k.defs, &changed, &k.style_ids, &ours); + let rewritten = super::kept::rewritten_defs(&now, &k.defs, &changed, &k.style_ids, &ours); super::kept::with_common_as_read(&styles, &k.defs, &k.order, &changed, &rewritten) } diff --git a/crates/odf/src/text/tests_more/kept.rs b/crates/odf/src/text/tests_more/kept.rs index d47ea57389..a87e38655e 100644 --- a/crates/odf/src/text/tests_more/kept.rs +++ b/crates/odf/src/text/tests_more/kept.rs @@ -418,6 +418,51 @@ fn an_unused_style_sharing_an_edited_ones_id_keeps_its_definition() { assert!(theirs.contains(r#"fo:font-size="30pt""#) && theirs.contains("#ff0000"), "as read: {theirs}"); } +/// A style nothing in the file uses, named as WordCraft names a used one (`MyCustom` beside +/// `My_20_Custom`, which WordCraft has as `MyCustom`), keeps its definition when the used one is +/// edited or deleted. +#[test] +fn an_unused_style_named_as_wordcraft_names_an_edited_one_keeps_its_definition() { + use std::sync::Arc; + let s = r##""##; + let as_read = |saved: &str| { + let theirs = def_named(saved, "MyCustom").unwrap_or_else(|| panic!("{saved}")); + assert!(theirs.contains(r#"fo:font-size="30pt""#) && theirs.contains("#ff0000"), "as read: {theirs}"); + }; + + let mut d = opened(s, &["My_20_Custom"]); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.size = Some(21.0); + let saved = styles_of(&export(&d).unwrap()); + assert!(def_named(&saved, "My_20_Custom").is_some_and(|d| d.contains(r#"fo:font-size="21pt""#)), "{saved}"); + as_read(&saved); + + let mut d = opened(s, &["My_20_Custom"]); + Arc::make_mut(&mut d.styles).remove(&id); + d.restyle(&id, None); + let saved = styles_of(&export(&d).unwrap()); + assert!(def_named(&saved, "My_20_Custom").is_none(), "{saved}"); + as_read(&saved); +} + +/// An edited style the file names as WordCraft does (`Eigen`), whose parent WordCraft names +/// otherwise (`Base_20_Style`, WordCraft's `BaseStyle`), still derives from the file's parent. +#[test] +fn an_edited_style_under_its_own_name_keeps_its_parents_file_name() { + use std::sync::Arc; + let s = r#""#; + let mut d = opened(s, &["Eigen"]); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.italic = Some(true); + let bytes = export(&d).unwrap(); + let saved = styles_of(&bytes); + let mine = def_named(&saved, "Eigen").unwrap_or_else(|| panic!("{saved}")); + assert!(mine.contains(r#"style:parent-style-name="Base_20_Style""#), "{mine}"); + assert!(def_named(&saved, "Base_20_Style").is_some_and(|d| d.contains(r#"style:writing-mode="tb-rl""#)), "as read: {saved}"); + let back = import(&bytes).unwrap(); + assert_eq!(back.styles.resolve_char(back.body[0].as_para().unwrap().props.style.as_deref(), &Default::default()).size, 30.0, "inherited"); +} + /// A character style WordCraft read under another id (`AccentChar`, as a paragraph style has /// `Accent`), edited, is written under the file's name: the text written as read names that. #[test] From 116914c8f2233f0ba05b39ab75d0136ba84e534e Mon Sep 17 00:00:00 2001 From: alehel Date: Mon, 16 Nov 2026 18:13:20 +0100 Subject: [PATCH 3/8] ODT: text written from the model names the file's style beside an unread namesake A file style the import read (My_20_Custom) whose WordCraft name (MyCustom) is another of the file's styles the import didn't read keeps that namesake's own definition. A paragraph or text span written from the model now names the file's style it was read with, directly or as its automatic style's parent, instead of resolving to the namesake. Co-Authored-By: Claude Opus 5.5 --- crates/odf/src/text/kept.rs | 23 +++++++++++++++ crates/odf/src/text/package.rs | 3 ++ crates/odf/src/text/tests_more/kept.rs | 39 ++++++++++++++++++++++++++ crates/odf/src/text/writer.rs | 9 ++++-- 4 files changed, 72 insertions(+), 2 deletions(-) diff --git a/crates/odf/src/text/kept.rs b/crates/odf/src/text/kept.rs index 3e507e5b67..4f1e7654a5 100644 --- a/crates/odf/src/text/kept.rs +++ b/crates/odf/src/text/kept.rs @@ -408,6 +408,29 @@ pub(super) fn rewritten_defs( out } +/// The file's names for the styles the import read whose name as WordCraft writes them (`ours`) +/// is a style of the file's the import didn't read (`MyCustom` beside `My_20_Custom`): by that +/// name with its family's key suffix (`MyCustom`, `MyCustom|text`), escaped. That namesake keeps +/// its own definition ([`rewritten_defs`]), so markup written from the model names the file's +/// style the text was read with instead. +pub(super) fn read_names( + defs: &BTreeMap>, + ids: &BTreeMap, + ours: &dyn Fn(&str) -> String, +) -> std::collections::HashMap { + let mut out = std::collections::HashMap::new(); + for (key, id) in ids { + let Some(rest) = key.strip_prefix("common:") else { continue }; + let (name, family) = rest.strip_suffix("|text").map_or((rest, ""), |n| (n, "|text")); + let mine = format!("{}{family}", ours(id)); + let namesake = format!("common:{mine}"); + if mine != rest && defs.contains_key(&namesake) && !ids.contains_key(&namesake) { + out.entry(mine).or_insert_with(|| super::writer::x(name)); + } + } + out +} + /// `def` (markup WordCraft wrote) with the values of its `style:name`, `style:parent-style-name` /// and `style:next-style-name` attributes that `to` gives another name for (by attribute and /// value) renamed to that, escaped. One pass: WordCraft writes these names unescaped (they are diff --git a/crates/odf/src/text/package.rs b/crates/odf/src/text/package.rs index 6e1b73a3a8..8ce5726df0 100644 --- a/crates/odf/src/text/package.rs +++ b/crates/odf/src/text/package.rs @@ -1067,6 +1067,8 @@ fn export_as(doc: &Document, mime: &str) -> Result, String> { })); w.kept_defs = std::sync::Arc::new(kept.map(|k| k.defs.clone()).unwrap_or_default()); w.reserved = std::sync::Arc::new(kept.map(|k| k.files.keys().cloned().collect()).unwrap_or_default()); + let ours = |id: &str| super::writer::odf_name(id); + w.read_names = std::sync::Arc::new(kept.map(|k| super::kept::read_names(&k.defs, &k.style_ids, &ours)).unwrap_or_default()); w.groups_whole = whole_groups(&flow.blocks); // The file's master pages are written as read: what was kept may start them. w.kept_pages = kept.is_some_and(|k| k.pages_as_read(doc)); @@ -1189,6 +1191,7 @@ fn export_as(doc: &Document, mime: &str) -> Result, String> { let mut hw = Writer::with_prefix(if kept.is_some() { "wcM" } else { "M" }); // Headers' and footers' new pictures and objects skip the kept files' names too. hw.reserved = std::sync::Arc::clone(&w.reserved); + hw.read_names = std::sync::Arc::clone(&w.read_names); hw.accents = accents; hw.variables.clone_from(&w.variables); let parts: Vec = pages.iter().map(|(_, sec)| page_parts(doc, sec, &mut hw)).collect(); diff --git a/crates/odf/src/text/tests_more/kept.rs b/crates/odf/src/text/tests_more/kept.rs index a87e38655e..8fd56b5537 100644 --- a/crates/odf/src/text/tests_more/kept.rs +++ b/crates/odf/src/text/tests_more/kept.rs @@ -445,6 +445,45 @@ fn an_unused_style_named_as_wordcraft_names_an_edited_one_keeps_its_definition() as_read(&saved); } +/// A paragraph written from the model names the file's style it was read with (`My_20_Custom`), +/// not a style of the file's that WordCraft's name for it would land on (`MyCustom`, unused). +#[test] +fn an_edited_paragraph_keeps_its_styles_file_name_beside_an_unused_namesake() { + use std::sync::Arc; + let s = r##""##; + for (edit_style, size) in [(false, 9.0), (true, 21.0)] { + let mut d = opened(s, &["My_20_Custom"]); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + if edit_style { + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.size = Some(21.0); + } + d.insert_text(&Pos::body(0, 0), "New ", &Default::default()).unwrap(); + let bytes = export(&d).unwrap(); + let c = content_of(&bytes); + assert!(c.contains("New Text"), "{c}"); + assert!(!c.contains(r#"style-name="MyCustom""#), "{c}"); + let back = import(&bytes).unwrap(); + let got = back.styles.resolve_char(back.body[0].as_para().unwrap().props.style.as_deref(), &Default::default()).size; + assert_eq!(got, size, "edited style {edit_style}: {c}\n{}", styles_of(&bytes)); + } +} + +/// The same for a character style: edited text's automatic style derives from the file's +/// character style it was read with (`My_20_Accent`), not an unused namesake (`MyAccent`). +#[test] +fn edited_text_keeps_its_character_styles_file_name_beside_an_unused_namesake() { + let s = r##""##; + let styles = format!(r#"{s}"#); + let content = format!( + r#"One two"# + ); + let mut d = import(&package(&content, Some(&styles))).unwrap(); + d.insert_text(&Pos::body(0, 0), "New ", &Default::default()).unwrap(); + let c = content_of(&export(&d).unwrap()); + assert!(c.contains("New One"), "{c}"); + assert!(c.contains(r#"style:parent-style-name="My_20_Accent""#) && !c.contains(r#"="MyAccent""#), "{c}"); +} + /// An edited style the file names as WordCraft does (`Eigen`), whose parent WordCraft names /// otherwise (`Base_20_Style`, WordCraft's `BaseStyle`), still derives from the file's parent. #[test] diff --git a/crates/odf/src/text/writer.rs b/crates/odf/src/text/writer.rs index 2ad475739c..0f23a63ce4 100644 --- a/crates/odf/src/text/writer.rs +++ b/crates/odf/src/text/writer.rs @@ -237,6 +237,9 @@ pub(super) struct Writer { refs_open: std::collections::BTreeSet, /// The file's own package paths, kept as read: names WordCraft's own pictures don't take. pub(super) reserved: std::sync::Arc>, + /// The file's names for styles WordCraft would otherwise name as one of the file's other + /// styles (see `kept::read_names`), by WordCraft's name and family key suffix. + pub(super) read_names: std::sync::Arc>, pub(super) kept_used: super::kept::Needed, /// The file's own master pages are written (its page setup is as read): kept markup may /// start one. @@ -302,7 +305,8 @@ impl Writer { if let Some(id) = f.extra.as_ref().and_then(|x| x.style.as_deref()) { self.named_text.insert(id.to_string()); props.push('\u{1}'); - props.push_str(&odf_name(id)); + let name = odf_name(id); + props.push_str(self.read_names.get(&format!("{name}|text")).unwrap_or(&name)); } if props.is_empty() { return None; @@ -327,7 +331,8 @@ impl Writer { // A custom style: written as a common style of the same name (see `custom_styles`). (_, _, Some(id)) => { self.named.insert(id.to_string()); - odf_name(id) + let name = odf_name(id); + self.read_names.get(&name).cloned().unwrap_or(name) } (Kind::Normal, Some(n), None) => n.to_string(), _ => parent_style(p.kind).to_string(), From 9087ce027e734e6fde662d9761ca749f756ecccf Mon Sep 17 00:00:00 2001 From: alehel Date: Mon, 16 Nov 2026 18:21:28 +0100 Subject: [PATCH 4/8] ODT: a new style derives from the file's style beside an unread namesake A style WordCraft writes that the file didn't have (one made after reading) is added as written, so one based on a read style whose WordCraft name is an unread style of the file's (`MyCustom` beside `My_20_Custom`) derived from that namesake. Its parent and next style now take the file's name, as text written from the model does. `kept::read_names` gives the names unescaped; the writer escapes them. Co-Authored-By: Claude Opus 5.5 --- crates/odf/src/text/kept.rs | 26 ++++++++++++++++++-------- crates/odf/src/text/package.rs | 3 ++- crates/odf/src/text/tests_more/kept.rs | 25 +++++++++++++++++++++++++ crates/odf/src/text/writer.rs | 4 ++-- 4 files changed, 47 insertions(+), 11 deletions(-) diff --git a/crates/odf/src/text/kept.rs b/crates/odf/src/text/kept.rs index 4f1e7654a5..6372ce55a3 100644 --- a/crates/odf/src/text/kept.rs +++ b/crates/odf/src/text/kept.rs @@ -270,7 +270,7 @@ pub(super) fn children(xml: &str, container: &str, group: &str) -> (Vec<(String, /// `xml` (a part WordCraft wrote) with `container`'s children as read: the file's (those of /// `group` in `defs`, in `order`; `pick` may choose WordCraft's instead, or neither), then -/// WordCraft's own the file had none of by that key. +/// WordCraft's own the file had none of by that key (as `fresh` gives them, by key and markup). fn with_as_read( xml: &str, container: &str, @@ -278,6 +278,7 @@ fn with_as_read( defs: &BTreeMap>, order: &[String], pick: &dyn Fn(&str, &str, Option<&str>) -> Option, + fresh: &dyn Fn(&str, &str) -> String, ) -> String { let (kids, content) = children(xml, container, group); let Some((from, to)) = content else { return xml.to_string() }; @@ -295,7 +296,7 @@ fn with_as_read( if !defs.contains_key(k) && let Some(x) = xml.get(*a..*b) { - body.push_str(x); + body.push_str(&fresh(k, x)); } } let (Some(head), Some(tail)) = (xml.get(..from), xml.get(to..)) else { return xml.to_string() }; @@ -322,14 +323,22 @@ pub(super) fn with_common_as_read( order: &[String], changed: &BTreeSet, rewritten: &BTreeMap>, + read: &std::collections::HashMap, ) -> String { - with_as_read(styles, "office:styles", "common", defs, order, &|k, d, ours| match ours { + let pick = |k: &str, d: &str, ours: Option<&str>| match ours { _ if rewritten.contains_key(k) => rewritten.get(k).cloned().flatten(), Some(o) if drawing_def(o) || changed.contains(k) => Some(o.to_string()), None if changed.contains(k) => None, // (The default graphic style is the file's: WordCraft's drawings say what they need.) _ => Some(d.to_string()), - }) + }; + // A style of WordCraft's own derives from (or is followed by) the file's style a style was + // read from, not an unread namesake of it ([`read_names`]). + let fresh = |k: &str, d: &str| { + let family = if k.ends_with("|text") { "|text" } else { "" }; + renamed(d, &|attr, v| (attr != "style:name").then(|| read.get(&format!("{v}{family}")).cloned()).flatten()) + }; + with_as_read(styles, "office:styles", "common", defs, order, &pick, &fresh) } /// What becomes of the file's styles (`defs`) that `changed` touches, by their keys: WordCraft's @@ -410,7 +419,7 @@ pub(super) fn rewritten_defs( /// The file's names for the styles the import read whose name as WordCraft writes them (`ours`) /// is a style of the file's the import didn't read (`MyCustom` beside `My_20_Custom`): by that -/// name with its family's key suffix (`MyCustom`, `MyCustom|text`), escaped. That namesake keeps +/// name with its family's key suffix (`MyCustom`, `MyCustom|text`), unescaped. That namesake keeps /// its own definition ([`rewritten_defs`]), so markup written from the model names the file's /// style the text was read with instead. pub(super) fn read_names( @@ -425,7 +434,7 @@ pub(super) fn read_names( let mine = format!("{}{family}", ours(id)); let namesake = format!("common:{mine}"); if mine != rest && defs.contains_key(&namesake) && !ids.contains_key(&namesake) { - out.entry(mine).or_insert_with(|| super::writer::x(name)); + out.entry(mine).or_insert_with(|| name.to_string()); } } out @@ -487,8 +496,9 @@ pub(super) fn changed(then: &BTreeMap, now: &BTreeMap) /// document whose page setup is as read. pub(super) fn with_pages_as_read(styles: &str, defs: &BTreeMap>, order: &[String]) -> String { let keep_file = |_: &str, d: &str, _: Option<&str>| Some(d.to_string()); - let s = with_as_read(styles, "office:automatic-styles", "sauto", defs, order, &keep_file); - with_as_read(&s, "office:master-styles", "master", defs, order, &keep_file) + let as_is = |_: &str, d: &str| d.to_string(); + let s = with_as_read(styles, "office:automatic-styles", "sauto", defs, order, &keep_file, &as_is); + with_as_read(&s, "office:master-styles", "master", defs, order, &keep_file, &as_is) } /// Attribute names whose values name a definition kept markup may refer to. diff --git a/crates/odf/src/text/package.rs b/crates/odf/src/text/package.rs index 8ce5726df0..87ee24c553 100644 --- a/crates/odf/src/text/package.rs +++ b/crates/odf/src/text/package.rs @@ -848,7 +848,8 @@ fn styles_as_read(doc: &Document, kept: Option<&craft_wordmodel::kept::KeptXml>, // The name WordCraft writes a style id under (`My_20_Custom` was read as `MyCustom`). let ours = |id: &str| super::writer::odf_name(id); let rewritten = super::kept::rewritten_defs(&now, &k.defs, &changed, &k.style_ids, &ours); - super::kept::with_common_as_read(&styles, &k.defs, &k.order, &changed, &rewritten) + let read = super::kept::read_names(&k.defs, &k.style_ids, &ours); + super::kept::with_common_as_read(&styles, &k.defs, &k.order, &changed, &rewritten, &read) } /// The package files the file's own definitions refer to, and those the markup written as read diff --git a/crates/odf/src/text/tests_more/kept.rs b/crates/odf/src/text/tests_more/kept.rs index 8fd56b5537..c3b778896a 100644 --- a/crates/odf/src/text/tests_more/kept.rs +++ b/crates/odf/src/text/tests_more/kept.rs @@ -468,6 +468,31 @@ fn an_edited_paragraph_keeps_its_styles_file_name_beside_an_unused_namesake() { } } +/// A style made after reading (`NewChild`), based on a file's style beside an unused namesake +/// (`My_20_Custom`, WordCraft's `MyCustom`, beside `MyCustom`), derives from the file's style it +/// was based on. +#[test] +fn a_new_style_based_on_one_beside_an_unused_namesake_derives_from_it() { + use std::sync::Arc; + let s = r##""##; + let mut d = opened(s, &["My_20_Custom"]); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + let mut child = d.styles.get(&id).unwrap().clone(); + (child.id, child.name, child.based_on, child.next) = ("NewChild".into(), "NewChild".into(), Some(id.clone()), None); + (child.para, child.chr) = Default::default(); + Arc::make_mut(&mut d.styles).upsert(child); + d.restyle(&id, Some("NewChild".to_string())); + let bytes = export(&d).unwrap(); + let saved = styles_of(&bytes); + let new = saved.split("').next()); + assert!(new.is_some_and(|n| n.contains(r#"style:parent-style-name="My_20_Custom""#)), "{saved}"); + let theirs = def_named(&saved, "MyCustom").unwrap_or_else(|| panic!("{saved}")); + assert!(theirs.contains(r#"fo:font-size="30pt""#), "as read: {theirs}"); + let back = import(&bytes).unwrap(); + let got = back.styles.resolve_char(back.body[0].as_para().unwrap().props.style.as_deref(), &Default::default()).size; + assert_eq!(got, 9.0, "{saved}\n{}", content_of(&bytes)); +} + /// The same for a character style: edited text's automatic style derives from the file's /// character style it was read with (`My_20_Accent`), not an unused namesake (`MyAccent`). #[test] diff --git a/crates/odf/src/text/writer.rs b/crates/odf/src/text/writer.rs index 0f23a63ce4..13a2dbbce3 100644 --- a/crates/odf/src/text/writer.rs +++ b/crates/odf/src/text/writer.rs @@ -306,7 +306,7 @@ impl Writer { self.named_text.insert(id.to_string()); props.push('\u{1}'); let name = odf_name(id); - props.push_str(self.read_names.get(&format!("{name}|text")).unwrap_or(&name)); + props.push_str(&self.read_names.get(&format!("{name}|text")).map_or(name, |n| x(n))); } if props.is_empty() { return None; @@ -332,7 +332,7 @@ impl Writer { (_, _, Some(id)) => { self.named.insert(id.to_string()); let name = odf_name(id); - self.read_names.get(&name).cloned().unwrap_or(name) + self.read_names.get(&name).map_or(name, |n| x(n)) } (Kind::Normal, Some(n), None) => n.to_string(), _ => parent_style(p.kind).to_string(), From 2ceddfd4aeaeb1b142a433a0b36aefb49b5ab1ba Mon Sep 17 00:00:00 2001 From: alehel Date: Mon, 16 Nov 2026 21:46:56 +0100 Subject: [PATCH 5/8] ODT: a new style derives from the file's style under the file's name A style WordCraft writes that the file didn't have, based on a style the import read under another name (`Base_20_Style`, WordCraft's `BaseStyle`), named WordCraft's name as its parent. That resolved to WordCraft's own copy of the style, without what WordCraft doesn't model of the file's. Its parent and next style now take the file's name for every style read under another name (`kept::file_names`), not only where an unread namesake collides. Co-Authored-By: Claude Opus 5.5 --- crates/odf/src/text/kept.rs | 19 ++++++++++++++++++- crates/odf/src/text/package.rs | 2 +- crates/odf/src/text/tests_more/kept.rs | 24 ++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/crates/odf/src/text/kept.rs b/crates/odf/src/text/kept.rs index 6372ce55a3..f3c68c47ec 100644 --- a/crates/odf/src/text/kept.rs +++ b/crates/odf/src/text/kept.rs @@ -333,7 +333,8 @@ pub(super) fn with_common_as_read( _ => Some(d.to_string()), }; // A style of WordCraft's own derives from (or is followed by) the file's style a style was - // read from, not an unread namesake of it ([`read_names`]). + // read from, under the file's name ([`file_names`]): not WordCraft's copy of it, nor an + // unread namesake. let fresh = |k: &str, d: &str| { let family = if k.ends_with("|text") { "|text" } else { "" }; renamed(d, &|attr, v| (attr != "style:name").then(|| read.get(&format!("{v}{family}")).cloned()).flatten()) @@ -417,6 +418,22 @@ pub(super) fn rewritten_defs( out } +/// The file's names for the styles the import read under another name than WordCraft writes them +/// under (`ours`): by that name with its family's key suffix (`BaseStyle`, `BaseStyle|text`), +/// unescaped, the first the import read into it where several were. +pub(super) fn file_names(ids: &BTreeMap, ours: &dyn Fn(&str) -> String) -> std::collections::HashMap { + let mut out = std::collections::HashMap::new(); + for (key, id) in ids { + let Some(rest) = key.strip_prefix("common:") else { continue }; + let (name, family) = rest.strip_suffix("|text").map_or((rest, ""), |n| (n, "|text")); + let mine = format!("{}{family}", ours(id)); + if mine != rest { + out.entry(mine).or_insert_with(|| name.to_string()); + } + } + out +} + /// The file's names for the styles the import read whose name as WordCraft writes them (`ours`) /// is a style of the file's the import didn't read (`MyCustom` beside `My_20_Custom`): by that /// name with its family's key suffix (`MyCustom`, `MyCustom|text`), unescaped. That namesake keeps diff --git a/crates/odf/src/text/package.rs b/crates/odf/src/text/package.rs index 87ee24c553..cc4023fa4c 100644 --- a/crates/odf/src/text/package.rs +++ b/crates/odf/src/text/package.rs @@ -848,7 +848,7 @@ fn styles_as_read(doc: &Document, kept: Option<&craft_wordmodel::kept::KeptXml>, // The name WordCraft writes a style id under (`My_20_Custom` was read as `MyCustom`). let ours = |id: &str| super::writer::odf_name(id); let rewritten = super::kept::rewritten_defs(&now, &k.defs, &changed, &k.style_ids, &ours); - let read = super::kept::read_names(&k.defs, &k.style_ids, &ours); + let read = super::kept::file_names(&k.style_ids, &ours); super::kept::with_common_as_read(&styles, &k.defs, &k.order, &changed, &rewritten, &read) } diff --git a/crates/odf/src/text/tests_more/kept.rs b/crates/odf/src/text/tests_more/kept.rs index c3b778896a..fd75609542 100644 --- a/crates/odf/src/text/tests_more/kept.rs +++ b/crates/odf/src/text/tests_more/kept.rs @@ -493,6 +493,30 @@ fn a_new_style_based_on_one_beside_an_unused_namesake_derives_from_it() { assert_eq!(got, 9.0, "{saved}\n{}", content_of(&bytes)); } +/// A style made after reading (`NewChild`), based on a file's style WordCraft names otherwise +/// (`Base_20_Style`, WordCraft's `BaseStyle`), derives from the file's style, with what WordCraft +/// doesn't model of it. +#[test] +fn a_new_style_based_on_a_renamed_one_derives_from_the_files() { + use std::sync::Arc; + let s = r#""#; + let mut d = opened(s, &["Base_20_Style"]); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + let mut child = d.styles.get(&id).unwrap().clone(); + (child.id, child.name, child.based_on, child.next) = ("NewChild".into(), "NewChild".into(), Some(id.clone()), None); + (child.para, child.chr) = Default::default(); + Arc::make_mut(&mut d.styles).upsert(child); + d.restyle(&id, Some("NewChild".to_string())); + let bytes = export(&d).unwrap(); + let saved = styles_of(&bytes); + let new = saved.split("').next()); + assert!(new.is_some_and(|n| n.contains(r#"style:parent-style-name="Base_20_Style""#)), "{saved}"); + assert!(def_named(&saved, "Base_20_Style").is_some_and(|d| d.contains(r#"style:writing-mode="tb-rl""#)), "as read: {saved}"); + let back = import(&bytes).unwrap(); + let got = back.styles.resolve_char(back.body[0].as_para().unwrap().props.style.as_deref(), &Default::default()).size; + assert_eq!(got, 30.0, "{saved}"); +} + /// The same for a character style: edited text's automatic style derives from the file's /// character style it was read with (`My_20_Accent`), not an unused namesake (`MyAccent`). #[test] From 937d0a9d681916c35ab0ae971803541d72651d3e Mon Sep 17 00:00:00 2001 From: alehel Date: Tue, 17 Nov 2026 02:38:22 +0100 Subject: [PATCH 6/8] ODT: package files of a style definition follow it per definition main's page background change (#1809) asked `KeptXml::styles_as_read`, which this branch replaces with per-definition fingerprints, to tell whether the file's style definitions are written as read. `with_kept_files` now asks per definition instead: one the document changed or that is written from the model doesn't keep its package files, as a drawing definition WordCraft writes its own of doesn't. `common_changes` gives both it and `styles_as_read` the same answer. Co-Authored-By: Claude Opus 5.5 --- crates/odf/src/text/package.rs | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/crates/odf/src/text/package.rs b/crates/odf/src/text/package.rs index 63abcb20a1..e9c7fd720d 100644 --- a/crates/odf/src/text/package.rs +++ b/crates/odf/src/text/package.rs @@ -843,13 +843,25 @@ fn styles_as_read(doc: &Document, kept: Option<&craft_wordmodel::kept::KeptXml>, used.2.entry(name.to_string()).or_insert_with(|| d.clone()); } } + let (changed, rewritten) = common_changes(doc, k); + let ours = |id: &str| super::writer::odf_name(id); + let read = super::kept::file_names(&k.style_ids, &ours); + super::kept::with_common_as_read(&styles, &k.defs, &k.order, &changed, &rewritten, &read) +} + +/// The keys of the file's style definitions `doc` has changed since they were read, and what +/// becomes of those written from the model under the file's names ([`super::kept::rewritten_defs`]). +/// The others are written as read. +fn common_changes( + doc: &Document, + k: &craft_wordmodel::kept::KeptXml, +) -> (std::collections::BTreeSet, std::collections::BTreeMap>) { let now = model_styles(doc); let changed = super::kept::changed(&k.style_prints, &super::kept::prints(&now)); // The name WordCraft writes a style id under (`My_20_Custom` was read as `MyCustom`). let ours = |id: &str| super::writer::odf_name(id); let rewritten = super::kept::rewritten_defs(&now, &k.defs, &changed, &k.style_ids, &ours); - let read = super::kept::file_names(&k.style_ids, &ours); - super::kept::with_common_as_read(&styles, &k.defs, &k.order, &changed, &rewritten, &read) + (changed, rewritten) } /// The package files the file's own definitions refer to, and those the markup written as read @@ -867,20 +879,16 @@ fn with_kept_files( let Some(k) = kept else { return }; let mut wanted = w.kept_files_used.clone(); let pages_kept = k.pages_as_read(doc); - let styles_kept = k.styles_as_read(doc); + let (changed, rewritten) = common_changes(doc, k); for (key, d) in &k.defs { if !pages_kept && (key.starts_with("sauto:") || key.starts_with("master:")) { continue; } if key.starts_with("common:") { - // The file's definition is written back whole (`styles_as_read`, non-`draw:` - // definitions win), or this one is restored for markup naming it. WordCraft's own - // definition takes a drawing definition's place: its href is no longer used. - let written = if styles_kept { - !(super::kept::drawing_def(d) && super::kept::defined(styles, d)) - } else { - key.strip_prefix("common:").is_some_and(|n| w.kept_used.1.contains_key(n)) && !super::kept::defined(styles, d) - }; + // The file's definition is written back as read unless the document changed it + // (`styles_as_read`): then WordCraft's takes its place, or none does. WordCraft's own + // definition takes a drawing definition's place too. Its href is then no longer used. + let written = !changed.contains(key) && !rewritten.contains_key(key) && !(super::kept::drawing_def(d) && super::kept::defined(styles, d)); if !written { continue; } From 41c7c80e8ae8f0d5a4f05ea4055841a185486069 Mon Sep 17 00:00:00 2001 From: alehel Date: Tue, 17 Nov 2026 03:14:30 +0100 Subject: [PATCH 7/8] ODT: a rewritten style definition keeps the package files it names A file style that `rewritten_defs` writes back as read (an unread namesake, `MyCustom` beside an edited `My_20_Custom`) was left out of the package files to keep, so a picture only it named was dropped while its href stayed in styles.xml. The files kept now follow the markup the rewrite writes for each key. Co-Authored-By: Claude Opus 5.5 --- crates/odf/src/text/package.rs | 16 ++++++++++++---- crates/odf/src/text/tests_more/kept.rs | 25 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/crates/odf/src/text/package.rs b/crates/odf/src/text/package.rs index e9c7fd720d..17b6d6cdfc 100644 --- a/crates/odf/src/text/package.rs +++ b/crates/odf/src/text/package.rs @@ -885,10 +885,18 @@ fn with_kept_files( continue; } if key.starts_with("common:") { - // The file's definition is written back as read unless the document changed it - // (`styles_as_read`): then WordCraft's takes its place, or none does. WordCraft's own - // definition takes a drawing definition's place too. Its href is then no longer used. - let written = !changed.contains(key) && !rewritten.contains_key(key) && !(super::kept::drawing_def(d) && super::kept::defined(styles, d)); + // What `styles_as_read` writes in its place, when it rewrites it: what that names (an + // unread namesake's own definition, as read) is what is written. + if let Some(def) = rewritten.get(key) { + if let Some(def) = def { + super::kept::hrefs(def, &mut wanted); + } + continue; + } + // The file's definition is written back as read unless the document changed it: then + // WordCraft's takes its place, or none does. WordCraft's own definition takes a + // drawing definition's place too. Its href is then no longer used. + let written = !changed.contains(key) && !(super::kept::drawing_def(d) && super::kept::defined(styles, d)); if !written { continue; } diff --git a/crates/odf/src/text/tests_more/kept.rs b/crates/odf/src/text/tests_more/kept.rs index fd75609542..dc423669f2 100644 --- a/crates/odf/src/text/tests_more/kept.rs +++ b/crates/odf/src/text/tests_more/kept.rs @@ -165,6 +165,31 @@ fn a_file_a_kept_definition_names_is_written_with_it() { assert!(m.contains(r#"manifest:full-path="Pictures/paper.png""#), "{m}"); } +/// An unused namesake's definition written back as read (`MyCustom` beside an edited +/// `My_20_Custom`) keeps the picture it names in the package. +#[test] +fn an_unused_namesakes_picture_stays_when_the_used_style_is_edited() { + use std::sync::Arc; + let png = [b"\x89PNG\r\n\x1a\n".as_slice(), &[5u8; 64]].concat(); + let styles = format!( + r##""## + ); + let content = format!( + r#"Text"# + ); + let pkg = crate::text::tests::zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes()), ("Pictures/only.png", &png)]); + let mut d = import(&pkg).unwrap(); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.size = Some(21.0); + let saved = export(&d).unwrap(); + let s = styles_of(&saved); + assert!(def_named(&s, "MyCustom").is_some_and(|d| d.contains(r#"xlink:href="Pictures/only.png""#)), "{s}"); + let mut z = crate::Package::open(&saved, &crate::Limits::DEFAULT).unwrap(); + assert_eq!(z.read("Pictures/only.png").unwrap(), Some(png)); + let m = crate::text::tests::entry(&saved, "META-INF/manifest.xml"); + assert!(m.contains(r#"manifest:full-path="Pictures/only.png""#), "{m}"); +} + /// A file defining what WordCraft doesn't model: a gradient, a paragraph style no text of its /// own uses, a default style's writing mode, and a frame style naming them. fn file_with_definitions() -> Vec { From 2ca5586810ff7e480961810d1267958339ffef0d Mon Sep 17 00:00:00 2001 From: alehel Date: Mon, 23 Nov 2026 09:32:29 +0100 Subject: [PATCH 8/8] test(odf): replace style export deadline with lookup work bound --- crates/odf/src/text/tests_more/kept.rs | 38 +++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/crates/odf/src/text/tests_more/kept.rs b/crates/odf/src/text/tests_more/kept.rs index 9bc9d6af6c..1bcf22b0ed 100644 --- a/crates/odf/src/text/tests_more/kept.rs +++ b/crates/odf/src/text/tests_more/kept.rs @@ -764,9 +764,9 @@ fn an_edited_character_style_read_under_another_id_keeps_the_files_name() { } /// Many of the file's styles WordCraft has under one id (`My-Custom`, `My.Custom`…), one edited: -/// the save looks each name up once, not every name for every style. +/// editing the shared id rewrites only the definitions that were read into it. #[test] -fn many_styles_sharing_an_id_save_quickly() { +fn many_styles_sharing_an_id_keep_unedited_definitions() { use std::sync::Arc; let names: Vec = (0..6_000u32).map(|i| format!("My{}Custom", (0..13).map(|b| if i >> b & 1 == 1 { '-' } else { '.' }).collect::())).collect(); @@ -778,9 +778,7 @@ fn many_styles_sharing_an_id_save_quickly() { let mut d = opened(&s, &used); let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.size = Some(21.0); - let t = std::time::Instant::now(); let saved = styles_of(&export(&d).unwrap()); - assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed()); assert_eq!(saved.matches(r#"fo:font-size="21pt""#).count(), 500, "the ones read into it"); assert_eq!(saved.matches(r#"fo:font-size="9pt""#).count(), 5_500, "the others as read"); } @@ -965,3 +963,35 @@ fn line_numbering_changed_in_the_first_section_is_saved() { let s = styles_of(&export(&d).unwrap()); assert!(s.contains(r#"text:increment="3""#) && !s.contains(r#"text:increment="5""#), "the change: {s}"); } + +#[test] +fn rewriting_shared_style_names_scales_linearly_in_name_lookups() { + use std::{ + cell::Cell, + collections::{BTreeMap, BTreeSet}, + sync::Arc, + }; + let lookups = |n: usize| { + let defs: BTreeMap> = (0..n).map(|i| (format!("common:Name{i}"), Arc::from(""))).collect(); + let ids = defs.keys().map(|key| (key.clone(), "Shared".to_string())).collect(); + let changed = BTreeSet::from(["common:Shared".to_string()]); + let calls = Cell::new(0usize); + let ours = |id: &str| { + calls.set(calls.get() + 1); + id.to_string() + }; + let rewritten = super::super::kept::rewritten_defs( + r#""#, + &defs, + &changed, + &ids, + &ours, + ); + assert_eq!(rewritten.len(), n); + calls.get() + }; + let small = lookups(16); + let large = lookups(128); + assert!(small > 0); + assert!(large <= 8 * small, "name lookups grew faster than the input: {small} -> {large}"); +}