From 2e5e69091a1d41217f93f9f18678351c3ff8653f Mon Sep 17 00:00:00 2001 From: batistalucasv Date: Mon, 16 Nov 2026 00:41:54 -0300 Subject: [PATCH] craft-odf: preserve page background bitmap fill and legacy fallback (#1784) - Preserves page background images and bitmap fills (`draw:fill="bitmap"`) alongside legacy `` fallbacks on ODT export, preventing orphaned duplicate backgrounds and resolving naming collisions with header pictures. - Reuses kept picture files or fill images with identical bytes on export instead of duplicating background files and definitions on every save. - Allocates distinct fill names for replaced page pictures and maps colliding names in linear time. - Falls back to legacy `` when modern bitmap fill is missing or contains non-image bytes. - Adds comprehensive round-trip tests in `crates/odf/src/text/tests_more/page_setup.rs`. --- crates/odf/src/text/import.rs | 101 ++- crates/odf/src/text/kept.rs | 2 +- crates/odf/src/text/package.rs | 138 +++- crates/odf/src/text/tests_more/page_setup.rs | 659 +++++++++++++++++++ 4 files changed, 859 insertions(+), 41 deletions(-) diff --git a/crates/odf/src/text/import.rs b/crates/odf/src/text/import.rs index 486e67a26..fcd98b164 100644 --- a/crates/odf/src/text/import.rs +++ b/crates/odf/src/text/import.rs @@ -823,8 +823,8 @@ struct Parsed { kept: super::parts::Kept, /// Hidden form controls, kept for the next save. hidden_controls: Vec, - /// The page background picture's bytes and fill. - page_image: Option<(Vec, &'static str)>, + /// The page background picture's bytes, fill, and optional fill image name. + page_image: Option<(Vec, &'static str, Option)>, } /// Hyphenation is a paragraph's in ODF (`fo:hyphenate`) and the document's in WordCraft (as in @@ -911,8 +911,19 @@ fn parse_tracked(bytes: &[u8], paper: (f32, f32)) -> Result { // A frame may point at any entry, as often as it likes: `Pictures` keeps that bounded. pictures.get(&mut z, path) }; - // The page background picture's bytes. - let page_image = pages.doc.page_image.clone().and_then(|(href, fill)| fetch(&href).map(|b| (b, fill))); + // The page background picture's bytes: modern draw:fill="bitmap" preferred when valid, + // falling back to legacy style:background-image if modern is missing or not an image. + let page_image = { + let modern = pages.doc.page_image.clone().and_then(|(href, fill, name)| { + let bytes = fetch(&href)?; + if model::sniff_image(&bytes).is_some() { Some((bytes, fill, name)) } else { None } + }); + modern.or_else(|| { + let (href, fill) = pages.doc.legacy_image.clone()?; + let bytes = fetch(&href)?; + if model::sniff_image(&bytes).is_some() { Some((bytes, fill, None)) } else { None } + }) + }; let objects = (entries.as_slice(), &manifest); // One `text:s` budget for the headers and footers and then the body. let mut spaces_left = MAX_EXTRA_SPACES; @@ -1096,11 +1107,15 @@ pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result doc.settings.odf = Some(craft_wordmodel::OdfLayout { tabs_from_indent }); doc.settings.sum_paragraph_spacing = sum_spacing; // The page background picture (Design › Page Color › Fill Effects › Picture). - if let Some((bytes, fill)) = page_image + if let Some((bytes, fill, name)) = page_image && let Some(ext) = model::sniff_image(&bytes) { let media = doc.add_media(bytes, ext); - doc.settings.page_picture = Some(craft_wordmodel::PagePicture { media, fill_type: fill.to_string(), title: String::new() }); + doc.settings.page_picture = Some(craft_wordmodel::PagePicture { + media, + fill_type: fill.to_string(), + title: name.map(|n| n.chars().take(255).collect()).unwrap_or_default(), + }); } if let Some((fmt, props)) = page_doc.notes[0] { (doc.settings.footnote_format, doc.settings.footnote_pr) = (fmt, props); @@ -1172,9 +1187,11 @@ pub(super) struct Pages { #[derive(Clone, Default)] pub(super) struct PageDoc { pub(super) page_color: Option, - /// The first page style's background picture (§17.3 `style:background-image`): its package - /// path and WordCraft's fill for its repeat (tiled, stretched, or centred at its size). - pub(super) page_image: Option<(String, &'static str)>, + /// The first page style's background picture (§17.3 `style:background-image` or §16.42 + /// `draw:fill-image` with `draw:fill="bitmap"`): package path, fill, and optional fill name. + pub(super) page_image: Option<(String, &'static str, Option)>, + /// Legacy fallback background picture from §17.3 `style:background-image`. + pub(super) legacy_image: Option<(String, &'static str)>, /// Footnotes', then endnotes', number format and options. pub(super) notes: [Option<(craft_wordmodel::section::NumFormat, craft_wordmodel::section::NoteProps)>; 2], } @@ -1248,12 +1265,43 @@ struct Layout { attrs: Attrs, /// Its background picture: package path and fill (see [`PageDoc::page_image`]). image: Option<(String, &'static str)>, + /// Its bitmap fill image name (`draw:fill-image-name`). + image_name: Option, + /// Its legacy background picture: package path and fill (§17.3 `style:background-image`). + legacy_image: Option<(String, &'static str)>, columns: Option, column_specs: Vec, header: Band, footer: Band, } +/// The background fill picture and its fill-image name from `page-layout-properties` +/// attributes `a` when modern `draw:fill="bitmap"` is declared (§16.42). +fn page_layout_fill(a: &super::xml::Attrs, fill_images: &HashMap) -> Option<((String, &'static str), String)> { + if get(a, "draw:fill") != Some("bitmap") { + return None; + } + let name = get(a, "draw:fill-image-name")?; + let href = fill_images.get(name)?; + let fill = match get(a, "style:repeat").map(str::trim) { + Some("no-repeat") => "center", + Some("stretch") => "frame", + _ => "tile", + }; + Some(((href.clone(), fill), name.to_string())) +} + +/// The page background picture and fill from legacy `background-image` attributes `a` (§17.3). +fn legacy_background_fill(a: &super::xml::Attrs) -> Option<(String, &'static str)> { + let href = get(a, "xlink:href").map(str::trim).filter(|h| !h.is_empty() && h.len() <= 1024)?; + let fill = match get(a, "style:repeat").map(str::trim) { + Some("no-repeat") => "center", + Some("stretch") => "frame", + _ => "tile", + }; + Some((href.trim_start_matches("./").to_string(), fill)) +} + /// A page stating nothing, `paper` (width, height) in size: no margins (§20.206–20.209 refer to /// XSL's margins, whose initial value is 0; whether it comes with the reference the standard /// doesn't say). @@ -1271,6 +1319,7 @@ fn unstated_page(paper: (f32, f32)) -> SectionProps { fn read_pages(xml: &[u8], paper: (f32, f32)) -> Pages { let mut layouts: HashMap = HashMap::new(); + let mut fill_images: HashMap = HashMap::new(); let mut cur: Option = None; // Inside a layout's footer style (else its header style). let mut in_footer = false; @@ -1289,6 +1338,12 @@ fn read_pages(xml: &[u8], paper: (f32, f32)) -> Pages { } } "linenumbering-configuration" if q.starts_with("text:") => lines = line_numbering(&a), + // Modern ODF 1.2/1.3 fill image definitions (§16.42 `draw:fill-image` in `office:styles`). + "fill-image" if q.starts_with("draw:") => { + if let (Some(name), Some(href)) = (get(&a, "draw:name"), get(&a, "xlink:href")) { + fill_images.insert(name.to_string(), href.trim_start_matches("./").to_string()); + } + } "page-layout" if q.starts_with("style:") => { cur = get(&a, "style:name").map(String::from); // A layout stating nothing is still one: the defaults' page. @@ -1300,16 +1355,14 @@ fn read_pages(xml: &[u8], paper: (f32, f32)) -> Pages { } // A page background picture (§17.3, in `style:page-layout-properties`): §20.249 // `style:repeat` (repeat is the default) as WordCraft's tile, stretch, or centre. + // Preserved as a fallback when modern `draw:fill="bitmap"` is missing or non-image. "background-image" if q.starts_with("style:") => { - if let (Some(l), Some(href)) = - (cur.as_ref().and_then(|n| layouts.get_mut(n)), get(&a, "xlink:href").map(str::trim).filter(|h| !h.is_empty() && h.len() <= 1024)) - { - let fill = match get(&a, "style:repeat").map(str::trim) { - Some("no-repeat") => "center", - Some("stretch") => "frame", - _ => "tile", - }; - l.image = Some((href.trim_start_matches("./").to_string(), fill)); + if let Some(l) = cur.as_ref().and_then(|n| layouts.get_mut(n)) { + let leg = legacy_background_fill(&a); + if l.image.is_none() { + l.image = leg.clone(); + } + l.legacy_image = leg; } } // A band whose height isn't stated is LibreOffice's default, 0.5 cm (measured; see @@ -1327,6 +1380,10 @@ fn read_pages(xml: &[u8], paper: (f32, f32)) -> Pages { } "page-layout-properties" => { if let Some(l) = cur.as_ref().and_then(|n| layouts.get_mut(n)) { + if let Some((img, name)) = page_layout_fill(&a, &fill_images) { + l.image = Some(img); + l.image_name = Some(name); + } l.attrs = a; } } @@ -1380,14 +1437,18 @@ fn read_pages(xml: &[u8], paper: (f32, f32)) -> Pages { }); let mut pages = Pages { doc, next: nexts, ..Default::default() }; for (name, layout, header, footer) in masters { - let Some(Layout { attrs: a, columns: cols, column_specs, header: hb, footer: fb, image }) = layouts.get(&layout) else { continue }; + let Some(Layout { attrs: a, columns: cols, column_specs, header: hb, footer: fb, image, image_name, legacy_image }) = layouts.get(&layout) + else { + continue; + }; // What a layout leaves unsaid: the default paper, and no margins. let mut sec = unstated_page(paper); apply_layout(a, &mut sec); sec.line_numbers.clone_from(&lines); if pages.first.is_none() { pages.doc.page_color = get(a, "fo:background-color").and_then(model::parse_color); - pages.doc.page_image.clone_from(image); + pages.doc.page_image = image.as_ref().map(|(href, fill)| (href.clone(), *fill, image_name.clone())); + pages.doc.legacy_image.clone_from(legacy_image); } // ODF starts a header at the page margin and the text after the header's band; Word // measures the header's distance and the text's margin from the edge. How the band's diff --git a/crates/odf/src/text/kept.rs b/crates/odf/src/text/kept.rs index e9efebdec..da49b3054 100644 --- a/crates/odf/src/text/kept.rs +++ b/crates/odf/src/text/kept.rs @@ -307,7 +307,7 @@ fn with_as_read( /// graphic style (the `Graphics` and `Frame` styles drawings derive from) is the file's: its /// drawings written as read derive from it, and those written from the model derived from it /// when read (what WordCraft models of it is in theirs). -fn drawing_def(xml: &str) -> bool { +pub(super) fn drawing_def(xml: &str) -> bool { xml.split('>').next().unwrap_or("").starts_with(", } /// The package files the file's own definitions refer to, and those the markup written as read -/// links to (`used`), written as read with them (added to `files` and `manifest` where no file -/// `taken` has the path). A picture only an edited paragraph showed isn't written. +/// links to (`w.kept_files_used`, `w.kept_used`), written as read with them (added to `files` and +/// `manifest` where no file `taken` has the path). A picture only an edited paragraph showed isn't written. fn with_kept_files( + doc: &Document, kept: Option<&craft_wordmodel::kept::KeptXml>, - used: &std::collections::BTreeSet, + styles: &str, + w: &Writer, taken: &dyn Fn(&str) -> bool, files: &mut Vec<(String, std::sync::Arc>)>, manifest: &mut String, ) { let Some(k) = kept else { return }; - let mut wanted = used.clone(); - for d in k.defs.values() { + let mut wanted = w.kept_files_used.clone(); + let pages_kept = k.pages_as_read(doc); + let styles_kept = k.styles_as_read(doc); + 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) + }; + if !written { + continue; + } + } super::kept::hrefs(d, &mut wanted); } // A file linked, or one in a folder linked (an object's). @@ -1234,7 +1254,7 @@ fn export_as(doc: &Document, mime: &str) -> Result, String> { w.objects.iter().map(|(d, _, _)| d).chain(w.object_dirs.iter().map(|(d, _)| d)).map(|d| format!("{}/", d.trim_end_matches('/'))).collect(); let taken = |p: &str| w.pictures.iter().any(|(n, _, _)| n == p) || dirs.iter().any(|d| p.starts_with(d.as_str())); let mut kept_files: Vec<_> = kept_files.into_iter().filter(|(p, _)| !taken(p)).collect(); - with_kept_files(kept, &w.kept_files_used, &taken, &mut kept_files, &mut manifest); + with_kept_files(doc, kept, &styles, &w, &taken, &mut kept_files, &mut manifest); for (path, mime) in &kept_entries { if (path.ends_with('/') && kept_files.iter().any(|(p, _)| p.starts_with(path.as_str()))) || kept_files.iter().any(|(p, _)| p == path) { manifest.push_str(&format!("\n", x(path), x(mime))); @@ -1384,43 +1404,121 @@ fn variables(doc: &Document) -> std::collections::BTreeSet { out } +/// A `draw:fill-image` definition's name and picture path, when `xml` starts with one. +fn fill_image_of(xml: &str) -> Option<(String, String)> { + let tag = xml.split('>').next()?; + if !tag.trim_start_matches('<').starts_with("draw:fill-image") { + return None; + } + let name = super::kept::raw_attr(tag, "draw:name").map(super::kept::attr_text)?; + let href = super::kept::raw_attr(tag, "xlink:href").map(super::kept::attr_text)?; + Some((name.into_owned(), href.into_owned())) +} + +/// `name` as a `draw:name` (§16.42) may read: an NCName — letters, digits, `-`, `_` and `.`, not +/// starting with `-`, `.` or a digit. Characters outside those are turned into `_`. +fn fill_image_name(name: &str) -> String { + let mut out = String::with_capacity(name.len().min(255)); + for c in name.chars().take(255) { + let ok = c.is_alphanumeric() || c == '-' || c == '_' || c == '.'; + let start_ok = c.is_alphabetic() || c == '_'; + if out.is_empty() { + out.push(if start_ok { c } else { '_' }); + } else { + out.push(if ok { c } else { '_' }); + } + } + if out.is_empty() { "PageBackground".to_string() } else { out } +} + /// `styles` with the page background picture (Design › Page Color › Fill Effects › Picture) in -/// each page layout (§17.3 `style:background-image`, first in `style:page-layout-properties`), -/// the picture written into the package by `w`: tiled, stretched, or centred at its own size -/// (§20.249 `style:repeat`). -fn page_background(doc: &Document, w: &mut Writer, styles: String) -> String { +/// each page layout (§17.3 `style:background-image`, first in `style:page-layout-properties`, and +/// modern ODF 1.2/1.3 §16.42 `draw:fill="bitmap"` with `draw:fill-image`), the picture written +/// into the package by `w`: tiled, stretched, or centred at its own size (§20.249 `style:repeat`). +fn page_background(doc: &Document, w: &mut Writer, mut styles: String) -> String { let Some(pic) = doc.settings.page_picture.as_ref() else { return styles }; let Some(data) = doc.media.get(&pic.media) else { return styles }; let Some(ext) = model::sniff_image(data) else { return styles }; - let name = format!("Pictures/page-background.{ext}"); - if !w.pictures.iter().any(|(n, _, _)| *n == name) { - w.pictures.push((name.clone(), data.clone(), model::mime_of(ext).to_string())); + let kept = doc.kept.of("odt"); + // A kept package file holding these bytes is this picture already: its path is reused, so + // saving what was opened doesn't add a copy on every save. + let same_kept = |path: &str| kept.is_some_and(|k| k.files.get(path).is_some_and(|b| b.as_slice() == data.as_slice())); + let mut name = format!("Pictures/page-background.{ext}"); + let mut pic_n = 1; + while (w.reserved.contains(&name) && !same_kept(&name)) || w.pictures.iter().any(|(n, d, _)| n == &name && d.as_slice() != data.as_slice()) { + name = format!("Pictures/page-background-{pic_n}.{ext}"); + pic_n += 1; } let repeat = match pic.fill_type.to_ascii_lowercase().as_str() { "tile" => "repeat", "center" => "no-repeat", _ => "stretch", }; - let el = format!( + // The fill-image definitions already written, by name, once: renaming looks each up rather + // than scanning every definition for it (a hostile file names thousands alike). + let mut fill_images: std::collections::HashMap = std::collections::HashMap::new(); + for d in w.kept_defs.values() { + if let Some((n, h)) = fill_image_of(d) { + fill_images.insert(n, h); + } + } + for (i, _) in styles.match_indices("", x(&fill_name), x(&name)); + if !super::kept::defined(&styles, &fill_image_def) { + styles = styles.replacen("", &format!("{fill_image_def}"), 1); + } + let bg_el = format!( "", x(&name) ); + let fill_attrs = format!(" draw:fill=\"bitmap\" draw:fill-image-name=\"{}\" style:repeat=\"{repeat}\"", x(&fill_name)); + // After each layout's properties' opening tag. - let mut out = String::with_capacity(styles.len() + el.len() * 4); + let mut out = String::with_capacity(styles.len() + bg_el.len() * 4); let mut rest = styles.as_str(); while let Some(at) = rest.find("')).map(|e| at + e) else { break }; let self_closing = rest.get(end.saturating_sub(1)..end) == Some("/"); if self_closing { - out.push_str(rest.get(..end.saturating_sub(1)).unwrap_or_default()); + let before_slash = end.saturating_sub(1); + out.push_str(rest.get(..tag_start).unwrap_or_default()); + out.push_str(&fill_attrs); + out.push_str(rest.get(tag_start..before_slash).unwrap_or_default()); out.push('>'); - out.push_str(&el); + out.push_str(&bg_el); out.push_str(""); } else { - out.push_str(rest.get(..=end).unwrap_or_default()); - out.push_str(&el); + out.push_str(rest.get(..tag_start).unwrap_or_default()); + out.push_str(&fill_attrs); + out.push_str(rest.get(tag_start..=end).unwrap_or_default()); + out.push_str(&bg_el); } - rest = rest.get(end + 1..).unwrap_or_default(); + rest = rest.get(end.saturating_add(1)..).unwrap_or_default(); } out.push_str(rest); out diff --git a/crates/odf/src/text/tests_more/page_setup.rs b/crates/odf/src/text/tests_more/page_setup.rs index af687bd45..79b74f248 100644 --- a/crates/odf/src/text/tests_more/page_setup.rs +++ b/crates/odf/src/text/tests_more/page_setup.rs @@ -233,3 +233,662 @@ fn a_page_borders_padding_keeps_the_text_where_it_was() { } assert_eq!(s.page_borders.and_then(|b| b.left).map(|b| (b.width, b.space)), Some((3.0, 24.0))); } + +/// An ODT document with a page background and an active header containing a logo +/// preserves the page background (both modern draw:fill and legacy fallback) and the header logo (#5803). +#[test] +fn background_plus_small_header_logo_keeps_background() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let logo_png = { + let img = image::RgbImage::from_pixel(4, 4, image::Rgb([30, 200, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let bg_media = d.add_media(png, "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media: bg_media, fill_type: "frame".into(), title: "PageBackground".into() }); + let logo_media = d.add_media(logo_png, "png"); + let mut hp = craft_wordmodel::Paragraph::new(); + hp.text = format!("Company {}", craft_wordmodel::para::OBJ); + hp.objects.push(craft_wordmodel::InlineObject::Image { + media: logo_media, + w: 50.0, + h: 20.0, + alt: "Logo".into(), + float: Default::default(), + crop: [0.0; 4], + fx: Default::default(), + ole: None, + }); + hp.runs = vec![ + craft_wordmodel::para::Run { len: 8, props: Default::default() }, + craft_wordmodel::para::Run { len: craft_wordmodel::para::OBJ.len_utf8(), props: Default::default() }, + ]; + d.parts.insert( + 1, + craft_wordmodel::Part { kind: craft_wordmodel::PartKind::Header, blocks: vec![craft_wordmodel::para_block(hp)], body: Default::default() }, + ); + d.last_section.headers.default = Some(1); + + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + // Verify both draw:fill="bitmap" and style:background-image are emitted consistently + assert!(s.contains("draw:fill=\"bitmap\""), "page layout must declare draw:fill=\"bitmap\": {s}"); + assert!(s.contains("style:background-image"), "legacy background-image fallback must be present: {s}"); + assert!(s.contains(""# + ); + let content = format!( + r#"Cell test"# + ); + let pkg = crate::text::tests::zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes()), ("Pictures/cell-bg.png", &png)]); + let d = import(&pkg).unwrap(); + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains("style:background-image"), "cell style background-image must survive on kept path: {s}"); + assert!(s.contains("Pictures/cell-bg.png"), "cell background picture path must survive: {s}"); +} + +/// An ODT document with a text-only header retains its legacy page background image +/// and writes the image into the package archive. +#[test] +fn text_header_keeps_page_background_picture() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let bg_media = d.add_media(png, "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media: bg_media, fill_type: "frame".into(), title: String::new() }); + let mut hp = craft_wordmodel::Paragraph::new(); + hp.text = "Header text".into(); + hp.runs = vec![craft_wordmodel::para::Run { len: hp.text.len(), props: Default::default() }]; + d.parts.insert( + 1, + craft_wordmodel::Part { kind: craft_wordmodel::PartKind::Header, blocks: vec![craft_wordmodel::para_block(hp)], body: Default::default() }, + ); + d.last_section.headers.default = Some(1); + + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains("style:background-image"), "page background must be written when header has no picture: {s}"); + assert!(s.contains("Pictures/page-background.png")); +} + +/// Every picture written into the ODT zip archive must be referenced by styles.xml or content.xml (#5803). +#[test] +fn no_unreferenced_images_left_in_package() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let ns = crate::text::tests::NS_T; + let nsd = r#"xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:xlink="http://www.w3.org/1999/xlink""#; + // An imported ODT with modern draw:fill="bitmap" and draw:fill-image + let styles = format!( + r#""# + ); + let content = format!( + r#"Body text."# + ); + let pkg = crate::text::tests::zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes()), ("Pictures/original.png", &png)]); + let mut d = import(&pkg).unwrap(); + + // Now insert a header picture into the document, changing page setup + let header_media = d.add_media(png.clone(), "png"); + let mut hp = craft_wordmodel::Paragraph::new(); + hp.text = format!("{}", craft_wordmodel::para::OBJ); + hp.objects.push(craft_wordmodel::InlineObject::Image { + media: header_media, + w: 100.0, + h: 50.0, + alt: "Header logo".into(), + float: Default::default(), + crop: [0.0; 4], + fx: Default::default(), + ole: None, + }); + hp.runs = vec![craft_wordmodel::para::Run { len: hp.text.len(), props: Default::default() }]; + d.parts.insert( + 1, + craft_wordmodel::Part { kind: craft_wordmodel::PartKind::Header, blocks: vec![craft_wordmodel::para_block(hp)], body: Default::default() }, + ); + d.last_section.headers.default = Some(1); + + let saved = export(&d).unwrap(); + let styles_xml = crate::text::tests::entry(&saved, "styles.xml"); + let content_xml = crate::text::tests::entry(&saved, "content.xml"); + + // Verify modern draw:fill bitmap and legacy style:background-image resolve to the same image target + let fill_name = + styles_xml.split("draw:fill-image-name=\"").nth(1).and_then(|s| s.split('"').next()).expect("styles.xml must contain draw:fill-image-name"); + let draw_fill_pattern = format!(" = (0..archive.len()).map(|i| archive.by_index(i).unwrap().name().unwrap().to_string()).collect(); + + let pic_files: Vec<&String> = file_names.iter().filter(|n| n.starts_with("Pictures/")).collect(); + assert!(!pic_files.is_empty(), "package should contain picture files"); + + for pic in pic_files { + let is_referenced = styles_xml.contains(pic.as_str()) || content_xml.contains(pic.as_str()); + assert!(is_referenced, "package image {pic} must be referenced in styles.xml or content.xml: styles={styles_xml}"); + } +} + +/// An inactive header (e.g. `first` when `title_page` is false, or `even` when `even_odd_headers` +/// is false) containing an image does NOT suppress the page background picture (#5803). +#[test] +fn inactive_header_picture_does_not_suppress_page_background() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let bg_media = d.add_media(png.clone(), "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media: bg_media, fill_type: "frame".into(), title: String::new() }); + + let header_media = d.add_media(png, "png"); + let mut hp = craft_wordmodel::Paragraph::new(); + hp.text = format!("{}", craft_wordmodel::para::OBJ); + hp.objects.push(craft_wordmodel::InlineObject::Image { + media: header_media, + w: 100.0, + h: 100.0, + alt: "Inactive header picture".into(), + float: Default::default(), + crop: [0.0; 4], + fx: Default::default(), + ole: None, + }); + hp.runs = vec![craft_wordmodel::para::Run { len: hp.text.len(), props: Default::default() }]; + d.parts.insert( + 100, + craft_wordmodel::Part { kind: craft_wordmodel::PartKind::Header, blocks: vec![craft_wordmodel::para_block(hp)], body: Default::default() }, + ); + + // Point headers.first to the header with picture, but title_page is FALSE. + d.last_section.headers.first = Some(100); + d.last_section.title_page = false; + + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains("style:background-image"), "background-image must be preserved when header picture is in an inactive header: {s}"); + assert!(s.contains("Pictures/page-background.png")); +} + +/// A noninitial continuous section header containing a picture does NOT produce a master page +/// and does not suppress the page background (#5803). +#[test] +fn continuous_section_header_picture_does_not_suppress_page_background() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let bg_media = d.add_media(png.clone(), "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media: bg_media, fill_type: "frame".into(), title: String::new() }); + + // Body with a first section ending paragraph + let mut p1 = craft_wordmodel::Paragraph::new(); + p1.text = "First paragraph in section 1".into(); + p1.runs = vec![craft_wordmodel::para::Run { len: p1.text.len(), props: Default::default() }]; + p1.section = Some(Box::new(craft_wordmodel::SectionProps::default())); + d.body.push(craft_wordmodel::para_block(p1)); + + // Second section (last_section) is continuous + let header_media = d.add_media(png, "png"); + let mut hp = craft_wordmodel::Paragraph::new(); + hp.text = format!("{}", craft_wordmodel::para::OBJ); + hp.objects.push(craft_wordmodel::InlineObject::Image { + media: header_media, + w: 100.0, + h: 100.0, + alt: "Continuous section header picture".into(), + float: Default::default(), + crop: [0.0; 4], + fx: Default::default(), + ole: None, + }); + hp.runs = vec![craft_wordmodel::para::Run { len: hp.text.len(), props: Default::default() }]; + d.parts.insert( + 200, + craft_wordmodel::Part { kind: craft_wordmodel::PartKind::Header, blocks: vec![craft_wordmodel::para_block(hp)], body: Default::default() }, + ); + + d.last_section.start = craft_wordmodel::section::SectionStart::Continuous; + d.last_section.headers.default = Some(200); + + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!( + s.contains("style:background-image"), + "page background must not be suppressed by continuous section header that emits no master page: {s}" + ); + assert!(s.contains("Pictures/page-background.png")); +} + +/// A non-continuous `last_section` without any body blocks following the section break +/// does not produce an exported page and does not suppress the page background (#5803). +#[test] +fn trailing_empty_last_section_header_picture_does_not_suppress_page_background() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let bg_media = d.add_media(png.clone(), "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media: bg_media, fill_type: "frame".into(), title: String::new() }); + + // Body with a single paragraph ending section 1 (nothing follows it) + let mut p1 = craft_wordmodel::Paragraph::new(); + p1.text = "Sole paragraph ending section 1".into(); + p1.runs = vec![craft_wordmodel::para::Run { len: p1.text.len(), props: Default::default() }]; + p1.section = Some(Box::new(craft_wordmodel::SectionProps::default())); + d.body.push(craft_wordmodel::para_block(p1)); + + // last_section is NextPage and has a header with a picture, but has no blocks following + let header_media = d.add_media(png, "png"); + let mut hp = craft_wordmodel::Paragraph::new(); + hp.text = format!("{}", craft_wordmodel::para::OBJ); + hp.objects.push(craft_wordmodel::InlineObject::Image { + media: header_media, + w: 100.0, + h: 100.0, + alt: "Unused trailing section header picture".into(), + float: Default::default(), + crop: [0.0; 4], + fx: Default::default(), + ole: None, + }); + hp.runs = vec![craft_wordmodel::para::Run { len: hp.text.len(), props: Default::default() }]; + d.parts.insert( + 300, + craft_wordmodel::Part { kind: craft_wordmodel::PartKind::Header, blocks: vec![craft_wordmodel::para_block(hp)], body: Default::default() }, + ); + + d.last_section.start = craft_wordmodel::section::SectionStart::NextPage; + d.last_section.headers.default = Some(300); + + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains("style:background-image"), "page background must not be suppressed by an unexported trailing last_section header: {s}"); + assert!(s.contains("Pictures/page-background.png")); +} + +/// When a page background picture is replaced with a new image while retaining an existing +/// fill-image name that belongs to a graphic style, export allocates a distinct fill name, +/// references it in page layouts, and preserves the retained definition and image (#5803). +#[test] +fn replaced_page_picture_allocates_distinct_fill_name_and_keeps_retained_def() { + let orig_png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([100, 200, 100])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let new_png = { + let img = image::RgbImage::from_pixel(4, 8, image::Rgb([200, 100, 200])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let ns = crate::text::tests::NS_T; + let nsd = "xmlns:draw=\"urn:oasis:names:tc:opendocument:xmlns:drawing:1.0\""; + let styles = format!( + r#""# + ); + let content = format!( + r#"Body text"# + ); + let pkg = + crate::text::tests::zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes()), ("Pictures/original.png", &orig_png)]); + let mut d = import(&pkg).unwrap(); + let new_media = d.add_media(new_png.clone(), "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media: new_media, fill_type: "stretch".into(), title: "SharedBg".into() }); + + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains(r#" Vec { + let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut out: Vec = + (0..archive.len()).map(|i| archive.by_index(i).unwrap().name().unwrap().to_string()).filter(|n| n.starts_with("Pictures/")).collect(); + out.sort(); + out +} + +/// Saving a page background picture and opening it again keeps one picture and one fill-image +/// definition: the kept file is reused while its bytes are the document's, not renamed (#5856). +#[test] +fn page_background_round_trips_do_not_grow_the_package() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let media = d.add_media(png, "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media, fill_type: "frame".into(), title: "PageBackground".into() }); + let mut current = d; + for generation in 1..=4 { + let saved = export(¤t).unwrap(); + let styles = crate::text::tests::entry(&saved, "styles.xml"); + assert_eq!(styles.matches(""# + ); + let content = format!( + r#"Body text."# + ); + let pkg = crate::text::tests::zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes()), ("Pictures/original.png", &png)]); + let d = import(&pkg).unwrap(); + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert_eq!(s.matches(""# + ); + let content = format!( + r#"Body text."# + ); + let pkg = crate::text::tests::zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes()), ("Pictures/para.png", &png)]); + let d = import(&pkg).unwrap(); + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains("Pictures/para.png"), "the style's background reference must stay: {s}"); + assert_eq!(picture_paths(&saved), ["Pictures/para.png"], "the referenced picture must be written"); +} + +/// A DOCX texture name (`o:title`, "Blue tissue paper") is not an XML NCName: the fill image it +/// names is written with one (#5856). +#[test] +fn a_texture_name_is_written_as_an_ncname() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let media = d.add_media(png, "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media, fill_type: "frame".into(), title: "Blue tissue paper".into() }); + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains(r#""#)); + } + let styles = format!( + r#"{defs}"# + ); + let content = format!( + r#"Body text."# + ); + let pkg = crate::text::tests::zip_of(&[ + ("content.xml", content.as_bytes()), + ("styles.xml", styles.as_bytes()), + ("Pictures/bg.png", &bg), + ("Pictures/other.png", &other), + ]); + let mut d = import(&pkg).unwrap(); + // The user replaces the picture: its fill-image name now meets every kept name. + let media = d.add_media(replacement, "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media, fill_type: "stretch".into(), title: "X".into() }); + let start = std::time::Instant::now(); + let saved = export(&d).unwrap(); + assert!(start.elapsed() < std::time::Duration::from_secs(5), "export took {:?}", start.elapsed()); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains(r#"` if present and valid (#1784). +#[test] +fn legacy_background_fallback_when_modern_bitmap_missing() { + let legacy_png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([10, 150, 20])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let ns = crate::text::tests::NS_T; + let nsd = r#"xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:xlink="http://www.w3.org/1999/xlink""#; + let styles = format!( + r#""# + ); + let content = format!( + r#"Body text."# + ); + let pkg = + crate::text::tests::zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes()), ("Pictures/legacy.png", &legacy_png)]); + let d = import(&pkg).unwrap(); + let pic = d.settings.page_picture.as_ref().expect("legacy fallback background picture must be imported"); + assert_eq!(d.media.get(&pic.media).map(|b| b.as_slice()), Some(legacy_png.as_slice())); + assert_eq!(pic.fill_type, "frame"); +} + +/// When modern `draw:fill="bitmap"` references a file with non-image bytes, +/// import falls back to legacy `` if present and valid (#1784). +#[test] +fn legacy_background_fallback_when_modern_bitmap_non_image() { + let legacy_png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([10, 150, 20])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let corrupt_data = b"This is plain text and definitely not a valid image format."; + let ns = crate::text::tests::NS_T; + let nsd = r#"xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:xlink="http://www.w3.org/1999/xlink""#; + let styles = format!( + r#""# + ); + let content = format!( + r#"Body text."# + ); + let pkg = crate::text::tests::zip_of(&[ + ("content.xml", content.as_bytes()), + ("styles.xml", styles.as_bytes()), + ("Pictures/corrupt.bin", corrupt_data), + ("Pictures/legacy.png", &legacy_png), + ]); + let d = import(&pkg).unwrap(); + let pic = d.settings.page_picture.as_ref().expect("legacy fallback background picture must be imported when modern is non-image"); + assert_eq!(d.media.get(&pic.media).map(|b| b.as_slice()), Some(legacy_png.as_slice())); + assert_eq!(pic.fill_type, "frame"); +}