craft-odf: preserve page background bitmap fill and legacy fallback (#1784)

- Preserves page background images and bitmap fills (`draw:fill="bitmap"`) alongside legacy `<style:background-image>` 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 `<style:background-image>` 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`.
This commit is contained in:
batistalucasv committed 2026-11-16 00:41:54 -03:00
1 parent 2f10c9389e
commit 2e5e69091a
4 files changed
+859 -41

No files matched your search

+81 -20
View File
@@ -823,8 +823,8 @@ struct Parsed {
kept: super::parts::Kept,
/// Hidden form controls, kept for the next save.
hidden_controls: Vec<String>,
/// The page background picture's bytes and fill.
page_image: Option<(Vec<u8>, &'static str)>,
/// The page background picture's bytes, fill, and optional fill image name.
page_image: Option<(Vec<u8>, &'static str, Option<String>)>,
}
/// 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<Parsed, String> {
// 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<Document, String>
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<craft_wordmodel::props::Rgb>,
/// 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<String>)>,
/// 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<String>,
/// Its legacy background picture: package path and fill (§17.3 `style:background-image`).
legacy_image: Option<(String, &'static str)>,
columns: Option<Columns>,
column_specs: Vec<super::styles::ColumnSpec>,
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<String, String>) -> 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<String, Layout> = HashMap::new();
let mut fill_images: HashMap<String, String> = HashMap::new();
let mut cur: Option<String> = 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
+1 -1
View File
@@ -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("<draw:")
}
+118 -20
View File
@@ -829,18 +829,38 @@ fn styles_as_read(doc: &Document, kept: Option<&craft_wordmodel::kept::KeptXml>,
}
/// 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<String>,
styles: &str,
w: &Writer,
taken: &dyn Fn(&str) -> bool,
files: &mut Vec<(String, std::sync::Arc<Vec<u8>>)>,
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<Vec<u8>, 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!("<manifest:file-entry manifest:full-path=\"{}\" manifest:media-type=\"{}\"/>\n", x(path), x(mime)));
@@ -1384,43 +1404,121 @@ fn variables(doc: &Document) -> std::collections::BTreeSet<String> {
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<String, String> = 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("<draw:fill-image ") {
if let Some((n, h)) = styles.get(i..).and_then(fill_image_of) {
fill_images.insert(n, h);
}
}
let mut fill_name = if !pic.title.is_empty() { fill_image_name(&pic.title) } else { "PageBackground".to_string() };
let base_fill_name = fill_name.clone();
// The definition under this name is this picture when its path is ours, or a kept file with
// the same bytes: then the file's name is reused instead of a copy being added.
let same_picture =
|href: &str, w: &Writer| href == name || same_kept(href) || w.pictures.iter().any(|(n, d, _)| n == href && d.as_slice() == data.as_slice());
let mut n = 1;
while let Some(href) = fill_images.get(&fill_name) {
let href = href.clone();
if same_picture(&href, w) {
name = href;
break;
}
fill_name = format!("{base_fill_name}-{n}");
n += 1;
}
if !w.pictures.iter().any(|(n, _, _)| *n == name) {
w.pictures.push((name.clone(), data.clone(), model::mime_of(ext).to_string()));
}
let fill_image_def =
format!("<draw:fill-image draw:name=\"{}\" xlink:href=\"{}\" xlink:type=\"simple\" xlink:actuate=\"onLoad\"/>", x(&fill_name), x(&name));
if !super::kept::defined(&styles, &fill_image_def) {
styles = styles.replacen("</office:styles>", &format!("{fill_image_def}</office:styles>"), 1);
}
let bg_el = format!(
"<style:background-image xlink:href=\"{}\" xlink:type=\"simple\" xlink:actuate=\"onLoad\" style:position=\"center center\" style:repeat=\"{repeat}\"/>",
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("<style:page-layout-properties") {
let tag_start = at + "<style:page-layout-properties".len();
let Some(end) = rest.get(at..).and_then(|r| r.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("</style:page-layout-properties>");
} 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
@@ -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("<draw:fill-image"), "draw:fill-image must be declared in office:styles: {s}");
// Reading the saved ODT back preserves page_picture
let back = import(&saved).unwrap();
assert!(back.settings.page_picture.is_some(), "saved ODT must preserve page background picture");
}
/// An ODT document with a page background and a full-page behind-text header picture
/// preserves both the header picture and the page background on export and re-import (#5803).
#[test]
fn full_page_header_picture_with_background_round_trips() {
let bg_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 header_png = {
let img = image::RgbImage::from_pixel(4, 8, image::Rgb([30, 30, 200]));
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(bg_png.clone(), "png");
d.settings.page_picture = Some(craft_wordmodel::PagePicture { media: bg_media, fill_type: "frame".into(), title: "PageBackground".into() });
let header_media = d.add_media(header_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: 595.0,
h: 842.0,
alt: "Full page header picture".into(),
float: craft_wordmodel::para::Float { wrap: craft_wordmodel::para::Wrap::BehindText, ..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 s = crate::text::tests::entry(&saved, "styles.xml");
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("<draw:fill-image"), "draw:fill-image must be declared in office:styles: {s}");
let fill_name =
s.split("draw:fill-image-name=\"").nth(1).and_then(|x| x.split('"').next()).expect("styles.xml must contain draw:fill-image-name");
let draw_fill_pattern = format!("<draw:fill-image draw:name=\"{fill_name}\" xlink:href=\"");
let draw_href = s.split(&draw_fill_pattern).nth(1).and_then(|x| x.split('"').next()).expect("draw:fill-image must define xlink:href");
let legacy_href = s
.split("<style:background-image xlink:href=\"")
.nth(1)
.and_then(|x| x.split('"').next())
.expect("legacy background-image must define xlink:href");
assert_eq!(draw_href, legacy_href, "modern and legacy background image references must match");
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(&saved)).unwrap();
let mut bg_entry = archive.by_name(draw_href).expect("packaged background picture must exist");
let mut bg_bytes = Vec::new();
std::io::Read::read_to_end(&mut bg_entry, &mut bg_bytes).unwrap();
assert_eq!(bg_bytes, bg_png, "packaged background image bytes must match");
let back = import(&saved).unwrap();
let bg = back.settings.page_picture.as_ref().expect("page background picture must survive round trip");
assert_eq!(back.media.get(&bg.media).map(|m| m.as_slice()), Some(bg_png.as_slice()), "imported background bytes must match");
let header_part = back.last_section.headers.default.and_then(|id| back.parts.get(&id)).expect("header part must survive round trip");
let header_img_media = header_part.blocks.iter().find_map(|b| {
b.as_para().and_then(|p| {
p.objects.iter().find_map(|o| if let craft_wordmodel::InlineObject::Image { media, .. } = o { Some(media.as_str()) } else { None })
})
});
assert!(header_img_media.is_some(), "header part must contain image object");
let header_img_media = header_img_media.unwrap();
assert_eq!(back.media.get(header_img_media).map(|m| m.as_slice()), Some(header_png.as_slice()), "imported header image bytes must match");
}
/// A table cell style with a background image survives the kept styles path (#5803).
#[test]
fn cell_style_picture_survives_kept_path() {
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 styles = format!(
r#"<office:document-styles {ns}><office:styles><style:style style:name="CellBg" style:family="table-cell"><style:table-cell-properties><style:background-image xlink:href="Pictures/cell-bg.png" xlink:type="simple" xlink:actuate="onLoad"/></style:table-cell-properties></style:style></office:styles></office:document-styles>"#
);
let content = format!(
r#"<office:document-content {ns}><office:body><office:text><text:p>Cell test</text:p></office:text></office:body></office:document-content>"#
);
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#"<office:document-styles {ns} {nsd}><office:styles><draw:fill-image draw:name="Bg1" xlink:href="Pictures/original.png" xlink:type="simple"/><style:style style:name="Standard" style:family="paragraph"/></office:styles><office:automatic-styles><style:page-layout style:name="pm1"><style:page-layout-properties fo:page-width="8.5in" fo:page-height="11in" draw:fill="bitmap" draw:fill-image-name="Bg1"><style:background-image xlink:href="Pictures/original.png" xlink:type="simple" xlink:actuate="onLoad" style:repeat="stretch"/></style:page-layout-properties></style:page-layout></office:automatic-styles><office:master-styles><style:master-page style:name="Standard" style:page-layout-name="pm1"/></office:master-styles></office:document-styles>"#
);
let content = format!(
r#"<office:document-content {ns}><office:body><office:text><text:p>Body text.</text:p></office:text></office:body></office:document-content>"#
);
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!("<draw:fill-image draw:name=\"{fill_name}\" xlink:href=\"");
let draw_href = styles_xml.split(&draw_fill_pattern).nth(1).and_then(|s| s.split('"').next()).expect("draw:fill-image must define xlink:href");
let legacy_href = styles_xml
.split("<style:background-image xlink:href=\"")
.nth(1)
.and_then(|s| s.split('"').next())
.expect("legacy background-image must define xlink:href");
assert_eq!(draw_href, legacy_href, "modern and legacy background image references must match");
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(&saved)).unwrap();
let file_names: Vec<String> = (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#"<office:document-styles {ns} {nsd}><office:styles><draw:fill-image draw:name="SharedBg" xlink:href="Pictures/original.png" xlink:type="simple"/><style:style style:name="Graphic1" style:family="graphic"><style:graphic-properties draw:fill="bitmap" draw:fill-image-name="SharedBg"/></style:style></office:styles><office:automatic-styles><style:page-layout style:name="pm1"><style:page-layout-properties fo:page-width="8.5in" fo:page-height="11in" draw:fill="bitmap" draw:fill-image-name="SharedBg"><style:background-image xlink:href="Pictures/original.png" xlink:type="simple" xlink:actuate="onLoad" style:repeat="stretch"/></style:page-layout-properties></style:page-layout></office:automatic-styles><office:master-styles><style:master-page style:name="Standard" style:page-layout-name="pm1"/></office:master-styles></office:document-styles>"#
);
let content = format!(
r#"<office:document-content {ns} {nsd}><office:body><office:text><text:p>Body text</text:p></office:text></office:body></office:document-content>"#
);
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#"<draw:fill-image draw:name="SharedBg" xlink:href="Pictures/original.png""#), "original fill-image must be preserved: {s}");
assert!(s.contains(r#"<draw:fill-image draw:name="SharedBg-1""#), "distinct fill-image definition must be allocated: {s}");
assert!(s.contains(r#"draw:fill-image-name="SharedBg-1""#), "page layout must reference distinct fill-image name: {s}");
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(&saved)).unwrap();
assert!(archive.by_name("Pictures/original.png").is_ok(), "Pictures/original.png must be in package");
assert!(archive.by_name("Pictures/page-background.png").is_ok(), "Pictures/page-background.png must be in package");
}
/// The pictures in package `bytes` under `Pictures/`, sorted.
fn picture_paths(bytes: &[u8]) -> Vec<String> {
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut out: Vec<String> =
(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(&current).unwrap();
let styles = crate::text::tests::entry(&saved, "styles.xml");
assert_eq!(styles.matches("<draw:fill-image ").count(), 1, "generation {generation} must keep one fill image: {styles}");
assert_eq!(picture_paths(&saved), ["Pictures/page-background.png"], "generation {generation} must keep one picture");
current = import(&saved).unwrap();
}
}
/// An untouched LibreOffice page background (fill image `Bg1` in `Pictures/original.png`) is
/// written back as it was: one definition, one file, no renamed copies (#5856).
#[test]
fn an_unchanged_libreoffice_page_background_is_written_back_once() {
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""#;
let styles = format!(
r#"<office:document-styles {ns} {nsd}><office:styles><draw:fill-image draw:name="Bg1" xlink:href="Pictures/original.png" xlink:type="simple"/><style:style style:name="Standard" style:family="paragraph"/></office:styles><office:automatic-styles><style:page-layout style:name="pm1"><style:page-layout-properties fo:page-width="8.5in" fo:page-height="11in" draw:fill="bitmap" draw:fill-image-name="Bg1"><style:background-image xlink:href="Pictures/original.png" xlink:type="simple" xlink:actuate="onLoad" style:repeat="stretch"/></style:page-layout-properties></style:page-layout></office:automatic-styles><office:master-styles><style:master-page style:name="Standard" style:page-layout-name="pm1"/></office:master-styles></office:document-styles>"#
);
let content = format!(
r#"<office:document-content {ns}><office:body><office:text><text:p>Body text.</text:p></office:text></office:body></office:document-content>"#
);
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("<draw:fill-image ").count(), 1, "one fill image, as read: {s}");
assert!(s.contains(r#"<draw:fill-image draw:name="Bg1" xlink:href="Pictures/original.png""#), "the file's fill image is reused: {s}");
assert!(!s.contains("page-background"), "no second picture is named for the background: {s}");
assert_eq!(picture_paths(&saved), ["Pictures/original.png"], "one picture, as read");
}
/// A kept paragraph style both sides name (`Standard`) keeps the picture its background refers
/// to: when styles are written as read, the file's definition wins and its file must stay
/// (#5856).
#[test]
fn common_style_background_picture_survives_styles_as_read() {
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 = "xmlns:xlink=\"http://www.w3.org/1999/xlink\"";
let styles = format!(
r#"<office:document-styles {ns} {nsd}><office:styles><style:style style:name="Standard" style:family="paragraph"><style:paragraph-properties><style:background-image xlink:href="Pictures/para.png" xlink:type="simple" xlink:actuate="onLoad"/></style:paragraph-properties></style:style></office:styles><office:automatic-styles><style:page-layout style:name="pm1"><style:page-layout-properties fo:page-width="8.5in" fo:page-height="11in"/></style:page-layout></office:automatic-styles><office:master-styles><style:master-page style:name="Standard" style:page-layout-name="pm1"/></office:master-styles></office:document-styles>"#
);
let content = format!(
r#"<office:document-content {ns}><office:body><office:text><text:p>Body text.</text:p></office:text></office:body></office:document-content>"#
);
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#"<draw:fill-image draw:name="Blue_tissue_paper""#), "the fill name is an NCName: {s}");
assert!(s.contains(r#"draw:fill-image-name="Blue_tissue_paper""#), "the page layout names it: {s}");
let back = import(&saved).unwrap();
assert_eq!(back.settings.page_picture.as_ref().map(|p| p.title.as_str()), Some("Blue_tissue_paper"));
}
/// Fill-image names a hostile file repeats with suffixes cost one lookup each, not a scan of
/// every definition per attempt (#5856).
#[test]
fn many_colliding_fill_image_names_export_in_linear_time() {
let bg = {
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 other = {
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 replacement = {
let img = image::RgbImage::from_pixel(2, 6, image::Rgb([30, 30, 200]));
let mut out = std::io::Cursor::new(Vec::new());
img.write_to(&mut out, image::ImageFormat::Png).unwrap();
out.into_inner()
};
const N: usize = 12_000;
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 mut defs = String::with_capacity(N * 90);
for i in 0..N {
let name = if i == 0 { "X".to_string() } else { format!("X-{i}") };
let href = if i == 0 { "Pictures/bg.png" } else { "Pictures/other.png" };
defs.push_str(&format!(r#"<draw:fill-image draw:name="{name}" xlink:href="{href}" xlink:type="simple"/>"#));
}
let styles = format!(
r#"<office:document-styles {ns} {nsd}><office:styles>{defs}</office:styles><office:automatic-styles><style:page-layout style:name="pm1"><style:page-layout-properties fo:page-width="8.5in" fo:page-height="11in" draw:fill="bitmap" draw:fill-image-name="X"><style:background-image xlink:href="Pictures/bg.png" xlink:type="simple" xlink:actuate="onLoad" style:repeat="stretch"/></style:page-layout-properties></style:page-layout></office:automatic-styles><office:master-styles><style:master-page style:name="Standard" style:page-layout-name="pm1"/></office:master-styles></office:document-styles>"#
);
let content = format!(
r#"<office:document-content {ns}><office:body><office:text><text:p>Body text.</text:p></office:text></office:body></office:document-content>"#
);
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#"<draw:fill-image draw:name="X-12000""#), "a free fill-image name is allocated: {s}");
}
/// When modern `draw:fill="bitmap"` references a picture missing from the package,
/// import falls back to legacy `<style:background-image>` 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#"<office:document-styles {ns} {nsd}><office:styles><draw:fill-image draw:name="MissingBg" xlink:href="Pictures/missing.png" xlink:type="simple"/><style:style style:name="Standard" style:family="paragraph"/></office:styles><office:automatic-styles><style:page-layout style:name="pm1"><style:page-layout-properties fo:page-width="8.5in" fo:page-height="11in" draw:fill="bitmap" draw:fill-image-name="MissingBg"><style:background-image xlink:href="Pictures/legacy.png" xlink:type="simple" xlink:actuate="onLoad" style:repeat="stretch"/></style:page-layout-properties></style:page-layout></office:automatic-styles><office:master-styles><style:master-page style:name="Standard" style:page-layout-name="pm1"/></office:master-styles></office:document-styles>"#
);
let content = format!(
r#"<office:document-content {ns}><office:body><office:text><text:p>Body text.</text:p></office:text></office:body></office:document-content>"#
);
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 `<style:background-image>` 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#"<office:document-styles {ns} {nsd}><office:styles><draw:fill-image draw:name="CorruptBg" xlink:href="Pictures/corrupt.bin" xlink:type="simple"/><style:style style:name="Standard" style:family="paragraph"/></office:styles><office:automatic-styles><style:page-layout style:name="pm1"><style:page-layout-properties fo:page-width="8.5in" fo:page-height="11in" draw:fill="bitmap" draw:fill-image-name="CorruptBg"><style:background-image xlink:href="Pictures/legacy.png" xlink:type="simple" xlink:actuate="onLoad" style:repeat="stretch"/></style:page-layout-properties></style:page-layout></office:automatic-styles><office:master-styles><style:master-page style:name="Standard" style:page-layout-name="pm1"/></office:master-styles></office:document-styles>"#
);
let content = format!(
r#"<office:document-content {ns}><office:body><office:text><text:p>Body text.</text:p></office:text></office:body></office:document-content>"#
);
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");
}