//! Tests of the warnings: their texts, and the warnings of a layout.
use f_office_fonts::{FamilyName, FontId, OutlineError, ShapeFailure};
use f_office_opc::Package;
use f_office_warnings::Name;
use super::{
ChartReason, Drawing, DrawingMlWarning, Limit, MetafileRecordType, MetafileWarning, ReadAs,
Reason, ValuePlace, Warning,
};
use crate::ns::{A, C, CX, DGM, M, MC, O, PIC, R, V, W, W14, WP, WPG, WPS};
use crate::testing::{self, Builder, DOCUMENT, WordParts as _};
use crate::{ChosenFace, FaceMetrics, Fonts, Options};
#[test]
fn says_the_font_that_draws_a_family_with_its_version_and_layout() {
let cases = [
(
Warning::FontSubstituted {
asked: Name::new("Calibri"),
used: Some(Name::new("Carlito")),
version: None,
layout: crate::SubstituteLayout::Widths,
},
"font Calibri is drawn with Carlito".to_owned(),
),
(
Warning::FontSubstituted {
asked: Name::new("Arial"),
used: Some(Name::new("Arimo CF")),
version: Some(Name::new("7.06.1")),
layout: crate::SubstituteLayout::Exact,
},
"font Arial is drawn with Arimo CF 7.06.1, which has its layout".to_owned(),
),
(
Warning::FontSubstituted {
asked: Name::new("Arial"),
used: Some(Name::new("Arimo CF")),
version: Some(Name::new("7.06.1")),
layout: crate::SubstituteLayout::OtherVersion {
family: Name::new("Arial"),
made_for: Name::new("7.06"),
target: Name::new("5.01.2x"),
},
},
"font Arial is drawn with Arimo CF 7.06.1, made for Arial 7.06; this target has Arial \
5.01.2x, so lines can break in other places"
.to_owned(),
),
];
for (warning, text) in cases {
assert_eq!(warning.kind(), "font-substituted");
assert_eq!(warning.to_string(), text);
}
}
#[test]
fn says_each_warning_with_its_names_cut() {
let long = format!("word/media/{}.png", "x".repeat(80));
let part = Name::new(&long);
let cut = &long[..Name::MAX_CHARS];
let cases = [
(
Warning::PartSkipped {
part: Name::new("word/diagrams/colors1.xml"),
reason: Reason::NotXml,
},
"part word/diagrams/colors1.xml is skipped: the part is not XML that reads".to_owned(),
),
(
Warning::RelationshipsSkipped {
part: Name::new("word/header1.xml"),
},
"the relationships of part word/header1.xml do not read, and what they name is \
left out"
.to_owned(),
),
(
Warning::DrawingSkipped {
drawing: Drawing::Picture,
part: part.clone(),
reason: Reason::Missing,
},
format!("a picture of part {cut} is left out: the package has no such part"),
),
(
Warning::DrawingSkipped {
drawing: Drawing::Chart,
part,
reason: Reason::Unsupported,
},
format!("a chart of part {cut} is left out: F-Office does not draw what it holds"),
),
(
Warning::ScriptNotShaped {
font: Some(Name::new("Arial")),
cause: ShapeFailure::NoShaper,
},
"text of a shaped script in Arial is not shaped: no shaper is available".to_owned(),
),
(
Warning::InvalidValue {
part: Name::new("word/styles.xml"),
element: Name::new("sz"),
place: ValuePlace::Attribute(Name::new("val")),
read_as: ReadAs::Zero,
},
"the value of attribute val of element sz in part word/styles.xml does not read and \
reads as 0"
.to_owned(),
),
(
Warning::InvalidValue {
part: Name::new("word/document.xml"),
element: Name::new("top"),
place: ValuePlace::Attribute(Name::new("space")),
read_as: ReadAs::Missing,
},
"the value of attribute space of element top in part word/document.xml does not \
read and counts as missing"
.to_owned(),
),
(
Warning::DrawingSkipped {
drawing: Drawing::Shape,
part: Name::new("word/document.xml"),
reason: Reason::OutOfRange,
},
"a shape of part word/document.xml is left out: a place or a size that its values \
give lies beyond the range of a length"
.to_owned(),
),
];
let kinds: Vec<&str> = cases.iter().map(|(warning, _)| warning.kind()).collect();
assert_eq!(
kinds,
[
"part-skipped",
"relationships-skipped",
"picture-skipped",
"chart-skipped",
"script-not-shaped",
"invalid-value",
"invalid-value",
"shape-skipped",
]
);
for (warning, text) in cases {
assert_eq!(warning.to_string(), text);
}
}
#[test]
fn says_why_a_chart_part_that_reads_is_left_out() {
let warning = Warning::DrawingSkipped {
drawing: Drawing::Chart,
part: Name::new("word/charts/chart1.xml"),
reason: Reason::Chart(ChartReason::Lines),
};
assert_eq!(warning.kind(), "chart-skipped");
assert_eq!(
warning.to_string(),
"a chart of part word/charts/chart1.xml is left out: F-Office does not draw a chart of lines on this target"
);
}
#[test]
fn says_a_font_whose_family_is_not_known_without_an_empty_name() {
// The caller gives an empty family for the first face, one that keeps no character as a
// name for the second, and none for the third.
let notes = super::FontNotes {
substituted: [("Lost Sans".to_owned(), FontId::from_index(0))].into(),
unshaped: [
(FontId::from_index(1), ShapeFailure::NoShaper),
(FontId::from_index(2), ShapeFailure::NoShaper),
]
.into(),
ink_not_measured: [
(FontId::from_index(1), OutlineError::NoOutlines),
(FontId::from_index(2), OutlineError::NoOutlines),
]
.into(),
not_drawn: std::collections::BTreeSet::new(),
faceless: std::collections::BTreeSet::new(),
};
let mut warnings = super::Warnings::new();
super::of_fonts(¬es, &Named(&["", "\u{202e}"]), &mut warnings);
let unshaped = Warning::ScriptNotShaped {
font: None,
cause: ShapeFailure::NoShaper,
};
let substituted = Warning::FontSubstituted {
asked: Name::new("Lost Sans"),
used: None,
version: None,
layout: crate::SubstituteLayout::Widths,
};
let ink = Warning::InkNotMeasured {
font: None,
cause: OutlineError::NoOutlines,
};
assert_eq!(
warnings.into_iter().collect::<Vec<_>>(),
[
(substituted.clone(), 1),
(unshaped.clone(), 2),
(ink.clone(), 2)
]
);
assert_eq!(
ink.to_string(),
"the ink of a glyph of a font of an unknown family is not measured, and the glyph is \
placed as one without ink: the font has no glyph outlines"
);
assert_eq!(
substituted.to_string(),
"font Lost Sans is drawn with another font"
);
assert_eq!(
unshaped.to_string(),
"text of a shaped script in a font of an unknown family is not shaped: no shaper is \
available"
);
}
#[test]
fn says_a_value_that_reaches_a_limit() {
let warning = Warning::LimitReached {
part: Name::new("word/document.xml"),
limit: Limit::GridColumns,
};
assert_eq!(warning.kind(), "limit-reached");
assert_eq!(
warning.to_string(),
"in part word/document.xml, a table asks for more grid columns than F-Office takes, and \
its grid stops at the limit"
);
}
#[test]
fn says_a_wrap_polygon_that_it_leaves_out_and_why() {
let warning = Warning::WrapPolygonSkipped {
part: Name::new("word/document.xml"),
reason: Reason::OutOfRange,
};
assert_eq!(warning.kind(), "wrap-polygon-skipped");
assert_eq!(
warning.to_string(),
"a wrap polygon of part word/document.xml is left out, and the text keeps out of its \
drawing's box: a place or a size that its values give lies beyond the range of a length"
);
}
#[test]
fn says_a_note_that_replaces_an_earlier_note_of_its_number() {
let warning = Warning::NoteIdRepeated {
part: Name::new("word/footnotes.xml"),
id: -2,
};
assert_eq!(warning.kind(), "note-id-repeated");
assert_eq!(
warning.to_string(),
"a note of part word/footnotes.xml has the ID -2 of an earlier note, and one of the two is kept"
);
}
#[test]
fn says_a_value_that_is_drawn_as_another_value() {
let warning = Warning::ValueNotSupported {
part: Name::new("word/document.xml"),
element: Name::new("u"),
place: ValuePlace::Attribute(Name::new("val")),
value: Name::new("double"),
};
assert_eq!(warning.kind(), "value-not-supported");
assert_eq!(
warning.to_string(),
"the value double of attribute val of element u in part word/document.xml is drawn as \
another value"
);
// The text of an element, such as the alignment of `wp:align`, has no attribute.
let text = Warning::ValueNotSupported {
part: Name::new("word/document.xml"),
element: Name::new("align"),
place: ValuePlace::Text,
value: Name::new("outside"),
};
assert_eq!(
text.to_string(),
"the value outside of the text of element align in part word/document.xml is drawn as \
another value"
);
// A keyword of the CSS declarations of a VML shape's style names its property.
let property = || ValuePlace::Property {
attribute: Name::new("style"),
property: Name::new("mso-position-horizontal-relative"),
};
let keyword = Warning::ValueNotSupported {
part: Name::new("word/document.xml"),
element: Name::new("rect"),
place: property(),
value: Name::new("char"),
};
assert_eq!(
keyword.to_string(),
"the value char of property mso-position-horizontal-relative of attribute style of \
element rect in part word/document.xml is drawn as another value"
);
let invalid = Warning::InvalidValue {
part: Name::new("word/document.xml"),
element: Name::new("rect"),
place: property(),
read_as: ReadAs::Missing,
};
assert_eq!(
invalid.to_string(),
"the value of property mso-position-horizontal-relative of attribute style of element \
rect in part word/document.xml does not read and counts as missing"
);
}
#[test]
fn says_the_text_of_an_element_and_a_value_of_drawingml_that_do_not_read() {
let offset = Warning::InvalidValue {
part: Name::new("word/document.xml"),
element: Name::new("posOffset"),
place: ValuePlace::Text,
read_as: ReadAs::Missing,
};
let line = Warning::DrawingMl {
part: Name::new("word/theme/theme1.xml"),
warning: DrawingMlWarning::InvalidValue {
element: Name::new("ln"),
attribute: Name::new("w"),
},
};
assert_eq!(
(offset.kind(), offset.to_string()),
(
"invalid-value",
"the text of element posOffset in part word/document.xml does not read and counts \
as missing"
.to_owned()
)
);
assert_eq!(
(line.kind(), line.to_string()),
(
"drawingml-invalid-value",
"in part word/theme/theme1.xml, the value of attribute w of element ln does not \
read and counts as missing"
.to_owned()
)
);
}
/// Fonts of the listed families only, each one face. The caller has no shaper.
struct Named(&'static [&'static str]);
impl Fonts for Named {
fn face(&self, family: &FamilyName, _bold: bool, _italic: bool) -> Option<ChosenFace> {
let index = self.0.iter().position(|name| family.is(name))?;
Some(ChosenFace {
font: FontId::from_index(u32::try_from(index).ok()?),
metrics: FaceMetrics {
units_per_em: 1000,
hhea_ascender: 800,
hhea_descender: -200,
hhea_line_gap: 0,
descent: 200,
underline_position: -100,
underline_thickness: 50,
strikeout_position: 250,
strikeout_thickness: 50,
superscript_offset: 0,
subscript_offset: 0,
superscript_size: 0,
subscript_size: 0,
line_top: 800,
script_top: 800,
east_asian: false,
average_width: 500,
},
synthetic_bold: false,
synthetic_italic: false,
stands_in: false,
})
}
fn glyph(&self, _font: FontId, ch: char) -> Option<u32> {
Some(u32::from(ch))
}
fn advance(&self, _font: FontId, _glyph: u32) -> Option<u16> {
Some(500)
}
fn family_name(&self, font: FontId) -> Option<String> {
let index = usize::try_from(font.index()).ok()?;
self.0.get(index).map(|name| (*name).to_owned())
}
}
/// The words of the test documents' own text, which no warning may hold.
const TEXT: &str = "Quiet harbour";
/// Asserts that no warning of `warnings` holds a word of [`TEXT`], the text of the document.
fn assert_holds_no_text(warnings: &[(Warning, u32)]) {
for (warning, _) in warnings {
let text = warning.to_string();
assert!(TEXT.split(' ').all(|word| !text.contains(word)), "{text}");
}
}
/// Asserts that the warnings `got` are `want`, in any order, and hold no word of [`TEXT`].
fn assert_warnings_hold_no_text(got: &[(Warning, u32)], want: &[(Warning, u32)]) {
let sorted = |warnings: &[(Warning, u32)]| {
let mut sorted = warnings.to_vec();
sorted.sort_by_key(|(warning, _)| warning.to_string());
sorted
};
assert_eq!(sorted(got), sorted(want));
assert_holds_no_text(got);
}
/// A paragraph of [`TEXT`] around a drawing whose `a:graphicData` holds `data`.
fn drawing(data: &str) -> String {
format!(
r#"<w:p><w:r><w:t>{TEXT}</w:t></w:r><w:r><w:drawing><wp:inline><wp:extent cx="914400" cy="457200"/><a:graphic><a:graphicData>{data}</a:graphicData></a:graphic></wp:inline></w:drawing></w:r><w:r><w:t>{TEXT}</w:t></w:r></w:p>"#
)
}
fn picture(id: &str) -> String {
drawing(&format!(
r#"<pic:pic><pic:blipFill><a:blip r:embed="{id}"/></pic:blipFill></pic:pic>"#
))
}
fn chart(id: &str) -> String {
drawing(&format!(r#"<c:chart r:id="{id}"/>"#))
}
/// Packs a DOCX file with `body`, a default header part `word/h1.xml` with `header`, the main
/// document's relationships of `rels` beside those of the header and the styles, and the other
/// parts of `parts`. Its styles part has empty document defaults, so that text names no font
/// unless its run does, and it has no theme.
fn package(body: &str, header: &str, rels: &[(&str, &str)], parts: &[(&str, &str)]) -> Vec<u8> {
let document = format!(
r#"<w:document xmlns:w="{W}" xmlns:r="{R}" xmlns:wp="{WP}" xmlns:a="{A}" xmlns:pic="{PIC}" xmlns:c="{C}" xmlns:dgm="{DGM}"><w:body>{body}<w:sectPr><w:headerReference w:type="default" r:id="h1"/></w:sectPr></w:body></w:document>"#
);
let header = format!(
r#"<w:hdr xmlns:w="{W}" xmlns:r="{R}" xmlns:wp="{WP}" xmlns:a="{A}" xmlns:pic="{PIC}">{header}</w:hdr>"#
);
let builder = testing::package(document)
.relationship(DOCUMENT, "h1", "header", "h1.xml")
.part("word/h1.xml", header)
.plain_styles();
let builder = rels.iter().fold(builder, |builder, (id, target)| {
builder.relationship(DOCUMENT, id, "image", target)
});
let builder = parts
.iter()
.fold(builder, |builder, (name, xml)| builder.part(name, *xml));
builder.zip().unwrap()
}
/// The warnings of laying out `bytes` with `fonts`, each with its count.
fn warnings_of(bytes: &[u8], fonts: &dyn Fonts) -> Vec<(Warning, u32)> {
let package = Package::open(bytes, &f_office_opc::Limits::default()).unwrap();
let laid_out = crate::layout(
&package,
(fonts, &crate::ArtPictures::new()),
&Options::base(),
)
.unwrap();
assert_eq!(laid_out.value.pages().len(), 1);
laid_out.warnings.into_iter().collect()
}
fn skipped(drawing: Drawing, part: &str, reason: Reason) -> Warning {
super::skipped(drawing, part, reason)
}
#[test]
fn warns_of_each_drawing_that_the_layout_leaves_out_and_holds_no_text_of_the_document() {
let body = [
picture("lost"),
picture("nowhere"),
picture("lost"),
chart("gone"),
chart("broken"),
chart("other"),
drawing(r#"<dgm:relIds r:dm="data" r:lo="layout" r:qs="style" r:cs="colors"/>"#),
]
.concat();
let rels = [
("lost", "media/lost.png"),
("gone", "charts/chart1.xml"),
("broken", "charts/chart2.xml"),
("other", "charts/chart3.xml"),
("data", "diagrams/data1.xml"),
];
let parts = [
("word/charts/chart2.xml", "<c:chartSpace"),
(
"word/charts/chart3.xml",
&*format!(r#"<c:chartSpace xmlns:c="{C}"><c:chart/></c:chartSpace>"#),
),
];
let bytes = package(&body, "", &rels, &parts);
let warnings = warnings_of(&bytes, &Named(&["Times New Roman"]));
let expected = [
(
skipped(
Drawing::SmartArt,
"word/diagrams/data1.xml",
Reason::Missing,
),
1,
),
(
skipped(Drawing::Chart, "word/charts/chart1.xml", Reason::Missing),
1,
),
(
skipped(Drawing::Chart, "word/charts/chart2.xml", Reason::NotXml),
1,
),
(
skipped(
Drawing::Chart,
"word/charts/chart3.xml",
Reason::Chart(ChartReason::NoPlotArea),
),
1,
),
// A picture that the file shows twice is one warning that came twice.
(
skipped(Drawing::Picture, "word/media/lost.png", Reason::Missing),
2,
),
(
skipped(Drawing::Picture, "word/document.xml", Reason::Unlinked),
1,
),
];
assert_warnings_hold_no_text(&warnings, &expected);
}
#[test]
fn warns_of_a_story_whose_relationships_do_not_read_and_still_draws_it() {
let header = format!("{}<w:p><w:r><w:t>{TEXT}</w:t></w:r></w:p>", picture("rId1"));
let parts = [("word/_rels/h1.xml.rels", "<Relationships")];
// The body has no text, so each glyph on the page is the header's.
let bytes = package("<w:p/>", &header, &[], &parts);
let package = Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
let fonts = Named(&["Times New Roman"]);
let laid_out = crate::layout(
&package,
(&fonts, &crate::ArtPictures::new()),
&Options::base(),
)
.unwrap();
let glyphs = laid_out.value.pages()[0].items().iter();
assert!(
glyphs
.into_iter()
.any(|item| matches!(item, f_office_paint::Item::Glyphs(_)))
);
let warnings: Vec<(Warning, u32)> = laid_out.warnings.into_iter().collect();
let part = Name::new("word/h1.xml");
// Without its relationships, the header's picture names no part.
let picture = skipped(Drawing::Picture, "word/h1.xml", Reason::Unlinked);
assert_eq!(
warnings,
[(Warning::RelationshipsSkipped { part }, 1), (picture, 1)]
);
}
#[test]
fn warns_of_each_family_that_another_draws_once_with_the_names_cut() {
// A family name of the file with a mark that turns text around, longer than a warning keeps.
let long = format!("Lost\u{202e} Sans {}", "x".repeat(80));
let run = |family: &str| {
format!(
r#"<w:p><w:r><w:rPr><w:rFonts w:ascii="{family}" w:hAnsi="{family}" w:cs="Cambria"/></w:rPr><w:t>{TEXT}</w:t></w:r></w:p>"#
)
};
let arabic = r#"<w:p><w:r><w:rPr><w:rFonts w:cs="Cambria"/></w:rPr><w:t>بلا</w:t></w:r></w:p>"#;
let body = [
run("Lost Sans"),
run("Lost Sans"),
run(&long),
arabic.to_owned(),
]
.concat();
let bytes = package(&body, "", &[], &[]);
let warnings = warnings_of(&bytes, &Named(&["Times New Roman", "Cambria"]));
let substituted = |asked: &str| {
let (asked, used) = (Name::new(asked), Some(Name::new("Cambria")));
(
Warning::FontSubstituted {
asked,
used,
version: None,
layout: crate::SubstituteLayout::Widths,
},
1,
)
};
let unshaped = Warning::ScriptNotShaped {
font: Some(Name::new("Cambria")),
cause: ShapeFailure::NoShaper,
};
// The shaper's record keeps the families in the order of their names in the file.
assert_eq!(
warnings,
[substituted("Lost Sans"), substituted(&long), (unshaped, 1)]
);
let text = warnings[1].0.to_string();
let kept: String = long
.chars()
.filter(|&ch| ch != '\u{202e}')
.take(64)
.collect();
assert_eq!(text, format!("font {kept} is drawn with Cambria"));
}
#[test]
fn gives_no_substitution_warning_for_text_that_names_no_font() {
let bytes = package(
&format!("<w:p><w:r><w:t>{TEXT}</w:t></w:r></w:p>"),
"",
&[],
&[],
);
// Word's own default draws the text, and it stands in for no family that the text asks for.
assert_eq!(warnings_of(&bytes, &Named(&["Times New Roman"])), []);
// Not even Word's own default is there: the text is left out, and the warning says so.
let warnings = warnings_of(&bytes, &Named(&["Cambria"]));
let not_drawn = Warning::TextNotDrawn {
asked: None,
tried: vec![Name::new("Times New Roman")],
};
assert_eq!(warnings, [(not_drawn.clone(), 1)]);
assert_eq!(not_drawn.kind(), "text-not-drawn");
assert_eq!(
not_drawn.to_string(),
"text that names no font is not drawn: the fonts have no face of Times New Roman, nor \
one that stands in for them"
);
}
#[test]
fn warns_of_a_paragraph_mark_whose_font_no_face_draws_but_not_again_of_text_left_out() {
let mark = |fonts: &str| format!(r"<w:pPr><w:rPr><w:rFonts {fonts}/></w:rPr></w:pPr>");
let carlito = r#"w:ascii="Carlito" w:hAnsi="Carlito""#;
let lost = r#"w:ascii="Lost Serif" w:hAnsi="Lost Serif""#;
let sans = r#"w:ascii="Lost Sans" w:hAnsi="Lost Sans""#;
let body = [
// An empty paragraph whose mark asks for a family that the fonts lack.
format!("<w:p>{}</w:p>", mark(lost)),
// Text that is drawn, with a mark of the same font.
format!(
r"<w:p>{}<w:r><w:rPr><w:rFonts {carlito}/></w:rPr><w:t>{TEXT}</w:t></w:r></w:p>",
mark(carlito)
),
// Text left out, with a mark of the same font: one warning, of the text.
format!(
r"<w:p>{}<w:r><w:rPr><w:rFonts {sans}/></w:rPr><w:t>{TEXT}</w:t></w:r></w:p>",
mark(sans)
),
]
.concat();
let bytes = package(&body, "", &[], &[]);
let tried = |asked: &str| {
[asked, "Cambria", "Times New Roman"]
.iter()
.map(|family| Name::new(family))
.collect::<Vec<_>>()
};
let faceless = Warning::FontNotFound {
asked: Some(Name::new("Lost Serif")),
tried: tried("Lost Serif"),
};
let not_drawn = |asked: &str| Warning::TextNotDrawn {
asked: Some(Name::new(asked)),
tried: tried(asked),
};
let warnings = warnings_of(&bytes, &Named(&["Carlito"]));
let mut kinds: Vec<_> = warnings
.iter()
.map(|(warning, _)| warning.clone())
.collect();
kinds.sort_by_key(ToString::to_string);
assert_eq!(kinds, [faceless.clone(), not_drawn("Lost Sans")]);
assert_eq!(faceless.kind(), "font-not-found");
assert_eq!(
faceless.to_string(),
"font Lost Serif is not found: the fonts have no face of Lost Serif, Cambria, Times New \
Roman, nor one that stands in for them"
);
let unnamed = Warning::FontNotFound {
asked: None,
tried: vec![Name::new("Times New Roman")],
};
assert_eq!(
unnamed.to_string(),
"the font of a mark, tab or break that names no font is not found: the fonts have no \
face of Times New Roman, nor one that stands in for them"
);
}
#[test]
fn warns_once_of_each_family_whose_text_no_face_draws_with_the_families_tried() {
let run = |fonts: &str, text: &str| {
format!(r"<w:p><w:r><w:rPr><w:rFonts {fonts}/></w:rPr><w:t>{text}</w:t></w:r></w:p>")
};
let latin = r#"w:ascii="Lost Sans" w:hAnsi="Lost Sans""#;
let body = [
run(latin, TEXT),
run(latin, TEXT),
// East Asian text, and a stretch of a shaped script.
run(r#"w:eastAsia="Lost Mincho""#, "静かな港"),
run(r#"w:cs="Lost Naskh""#, "بلا"),
]
.concat();
let bytes = package(&body, "", &[], &[]);
let package = Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
let laid_out = crate::layout(
&package,
(&Named(&["Carlito"]), &crate::ArtPictures::new()),
&Options::base(),
)
.unwrap();
// No glyph is drawn: the page holds no item.
let pages = laid_out.value.pages();
assert_eq!(
pages.iter().map(|page| page.items().len()).sum::<usize>(),
0
);
let not_drawn = |asked: &str, tried: &[&str]| {
let tried = tried.iter().map(|family| Name::new(family)).collect();
let asked = Some(Name::new(asked));
(Warning::TextNotDrawn { asked, tried }, 1)
};
// The paragraph marks name no font, and no face draws Word's own default for them.
let marks = Warning::FontNotFound {
asked: None,
tried: vec![Name::new("Times New Roman")],
};
let want = [
(marks, 1),
not_drawn("Lost Sans", &["Lost Sans", "Cambria", "Times New Roman"]),
not_drawn(
"Lost Mincho",
&[
"Lost Mincho",
"Microsoft YaHei",
"Cambria",
"Times New Roman",
],
),
not_drawn(
"Lost Naskh",
&["Lost Naskh", "Arial", "Cambria", "Times New Roman"],
),
];
let warnings: Vec<_> = laid_out.warnings.into_iter().collect();
assert_warnings_hold_no_text(&warnings, &want);
let [_, _, (mincho, _), _] = &want;
assert_eq!(
mincho.to_string(),
"text in font Lost Mincho is not drawn: the fonts have no face of Lost Mincho, \
Microsoft YaHei, Cambria, Times New Roman, nor one that stands in for them"
);
// A family name longer than a warning keeps is cut.
let long = format!("Lost Sans {}", "x".repeat(80));
let cut = &long[..Name::MAX_CHARS];
let warning = Warning::TextNotDrawn {
asked: Some(Name::new(&long)),
tried: vec![Name::new(&long), Name::new("Times New Roman")],
};
assert_eq!(
warning.to_string(),
format!(
"text in font {cut} is not drawn: the fonts have no face of {cut}, Times New Roman, \
nor one that stands in for them"
)
);
}
/// The fonts of [`Named`], whose ink of every glyph the caller measures as the second field
/// gives.
struct Inked(Named, Result<Option<(i32, i32)>, OutlineError>);
impl Fonts for Inked {
fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<ChosenFace> {
self.0.face(family, bold, italic)
}
fn glyph(&self, font: FontId, ch: char) -> Option<u32> {
self.0.glyph(font, ch)
}
fn advance(&self, font: FontId, glyph: u32) -> Option<u16> {
self.0.advance(font, glyph)
}
fn family_name(&self, font: FontId) -> Option<String> {
self.0.family_name(font)
}
fn ink(&self, _font: FontId, _glyph: u32) -> Result<Option<(i32, i32)>, OutlineError> {
self.1
}
}
#[test]
fn warns_once_of_each_font_whose_ink_is_not_measured_and_places_its_glyphs_without_ink() {
// Two inline equations, each a fraction, whose parts the layout keeps apart by their ink.
let run = |text: &str| format!("<m:r><m:t>{text}</m:t></m:r>");
let fraction = format!(
"<m:f><m:num>{}</m:num><m:den>{}</m:den></m:f>",
run("x"),
run("y")
);
let equation = format!(
r#"<w:p><w:r><w:t>{TEXT}</w:t></w:r><m:oMath xmlns:m="{M}">{fraction}</m:oMath></w:p>"#
);
let bytes = package(&equation.repeat(2), "", &[], &[]);
let package = Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
let lay_out = |ink| {
let fonts = Inked(Named(&["Times New Roman", "Cambria Math"]), ink);
let laid_out = crate::layout(
&package,
(&fonts, &crate::ArtPictures::new()),
&Options::base(),
)
.unwrap();
let warnings: Vec<_> = laid_out.warnings.into_iter().collect();
(laid_out.value, warnings)
};
let (without_ink, mut want) = lay_out(Ok(None));
let (unmeasured, warnings) = lay_out(Err(OutlineError::Unreadable));
// The glyphs whose ink is not measured stand where glyphs without ink stand.
assert_eq!(unmeasured, without_ink);
let ink = Warning::InkNotMeasured {
font: Some(Name::new("Cambria Math")),
cause: OutlineError::Unreadable,
};
want.push((ink.clone(), 1));
assert_eq!(warnings, want);
assert_eq!(ink.kind(), "ink-not-measured");
assert_eq!(
ink.to_string(),
"the ink of a glyph of Cambria Math is not measured, and the glyph is placed as one \
without ink: the glyph's outline does not read"
);
}
/// An EMF file whose bytes are all below 0x80, so that it fits in a test part: a header of a
/// frame of 1 by 1 mm, the records, each a type and its 32-bit fields, and the end record.
fn emf(records: &[(u32, &[i32])]) -> String {
let le = |values: &[i32]| -> Vec<u8> { values.iter().flat_map(|v| v.to_le_bytes()).collect() };
let record = |kind: u32, fields: Vec<u8>| -> Vec<u8> {
let size = u32::try_from(8 + fields.len()).unwrap();
[
kind.to_le_bytes().to_vec(),
size.to_le_bytes().to_vec(),
fields,
]
.concat()
};
let mut header = le(&[0, 0, 99, 99, 0, 0, 100, 100]);
header.extend_from_slice(&0x464D_4520_u32.to_le_bytes());
header.extend(le(&[0x10000, 0, 0, 0, 0, 0, 0, 100, 100, 10, 10]));
let mut file = record(1, header);
for (kind, fields) in records {
file.extend(record(*kind, le(fields)));
}
file.extend(record(14, le(&[0, 0, 0])));
String::from_utf8(file).unwrap()
}
#[test]
fn warns_of_the_records_of_a_metafile_picture_once_for_its_part() {
// An invalid PolyBezier16 record and an unknown background mode.
let file = emf(&[(85, &[0, 0, 0, 0, 1, 0]), (18, &[99])]);
let body = [picture("m"), picture("m")].concat();
let bytes = package(
&body,
"",
&[("m", "media/m.emf")],
&[("word/media/m.emf", &file)],
);
let part = Name::new("word/media/m.emf");
let metafile = |warning| Warning::Metafile {
part: part.clone(),
warning,
};
assert_eq!(
warnings_of(&bytes, &Named(&["Times New Roman"])),
[
(
metafile(MetafileWarning::RecordSkipped {
// EMF record 85 is EMR_POLYBEZIER16.
record: MetafileRecordType::Emf(85),
}),
1
),
(
metafile(MetafileWarning::StateNotHonoured {
// EMF record 18 is EMR_SETBKMODE.
record: MetafileRecordType::Emf(18),
}),
1
),
]
);
let warning = metafile(MetafileWarning::RecordSkipped {
// EMF record 85 is EMR_POLYBEZIER16.
record: MetafileRecordType::Emf(85),
});
assert_eq!(warning.kind(), "metafile-record-skipped");
assert_eq!(
warning.to_string(),
"in the picture word/media/m.emf, EMF record 0x0055 is left out"
);
}
#[test]
fn warns_of_metafile_text_that_no_face_draws() {
// Two UTF-16 code units in one field.
let units = |text: &str| -> Vec<i32> {
let units: Vec<i32> = text.encode_utf16().map(i32::from).collect();
units
.chunks(2)
.map(|pair| pair[0] | pair.get(1).map_or(0, |unit| unit << 16))
.collect()
};
// A font of 12 logical units in Lost Sans (EMR_EXTCREATEFONTINDIRECTW, handle 1), its
// selection (EMR_SELECTOBJECT), and a line of two characters (EMR_EXTTEXTOUTW) whose
// string starts at byte 76 of the record.
let font = [vec![1, 12, 0, 0, 0, 0, 0, 0], units("Lost Sans")].concat();
let text = [
vec![0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 76, 0, 0, 0, 0, 0, 0],
units("Hi"),
]
.concat();
let file = emf(&[(82, &font), (37, &[1]), (84, &text)]);
let bytes = package(
&picture("m"),
"",
&[("m", "media/m.emf")],
&[("word/media/m.emf", &file)],
);
// The paragraph's own text names no font, and Word's own default is missing too.
let paragraph = Warning::TextNotDrawn {
asked: None,
tried: vec![Name::new("Times New Roman")],
};
let metafile = Warning::TextNotDrawn {
asked: Some(Name::new("Lost Sans")),
tried: ["Lost Sans", "Cambria", "Times New Roman"]
.map(Name::new)
.to_vec(),
};
assert_eq!(
warnings_of(&bytes, &Named(&["Carlito"])),
[(paragraph.clone(), 1), (metafile, 1)]
);
// With Word's fallback for a missing font, the metafile's text is drawn in its place.
let substituted = Warning::FontSubstituted {
asked: Name::new("Lost Sans"),
used: Some(Name::new("Cambria")),
version: None,
layout: crate::SubstituteLayout::Widths,
};
assert_eq!(
warnings_of(&bytes, &Named(&["Cambria"])),
[(substituted, 1), (paragraph, 1)]
);
}
#[test]
fn finds_a_picture_whose_entry_differs_in_case_and_warns_of_a_second_equivalent_entry() {
let fonts = Named(&["Times New Roman"]);
let bytes = package(
&picture("p"),
"",
&[("p", "media/P.png")],
&[("word/media/p.png", "first")],
);
assert_eq!(warnings_of(&bytes, &fonts), []);
let bytes = package(
&picture("p"),
"",
&[("p", "media/p.png")],
&[
("word/media/p.png", "first"),
("word/Media/P.png", "second"),
],
);
let twin = Warning::PartSkipped {
part: Name::new("word/Media/P.png"),
reason: Reason::Equivalent,
};
assert_eq!(warnings_of(&bytes, &fonts), [(twin.clone(), 1)]);
assert_eq!(twin.kind(), "part-skipped");
assert_eq!(
twin.to_string(),
"part word/Media/P.png is skipped: an earlier entry has a name that differs only in case"
);
}
/// The relationships that name a part of [`LINKED`].
#[derive(Clone, Copy)]
enum Source {
/// The main document's relationships.
Main,
/// The package's relationships.
Package,
}
/// The parts of [`every_part`] besides the main document, the package's relationships and the
/// main document's relationships, each with the relationship type that names it and the
/// relationships that hold it.
const LINKED: [(&str, &str, Source); 11] = [
("word/h1.xml", "header", Source::Main),
("word/styles.xml", "styles", Source::Main),
("word/theme/theme1.xml", "theme", Source::Main),
("word/settings.xml", "settings", Source::Main),
("word/fontTable.xml", "fontTable", Source::Main),
("word/numbering.xml", "numbering", Source::Main),
("word/footnotes.xml", "footnotes", Source::Main),
("word/endnotes.xml", "endnotes", Source::Main),
("word/comments.xml", "comments", Source::Main),
(
"word/commentsExtended.xml",
"commentsExtended",
Source::Main,
),
("docProps/custom.xml", "custom-properties", Source::Package),
];
/// The XML of a part of [`LINKED`]: an empty root of its kind, or a styles part with empty
/// document defaults, so that the text names no font.
fn linked_xml(name: &str) -> String {
let empty = |root: &str| format!(r#"<w:{root} xmlns:w="{W}"/>"#);
match name {
"word/h1.xml" => format!(r#"<w:hdr xmlns:w="{W}"><w:p/></w:hdr>"#),
"word/styles.xml" => format!(
r#"<w:styles xmlns:w="{W}"><w:docDefaults><w:rPrDefault/><w:pPrDefault/></w:docDefaults></w:styles>"#
),
"word/theme/theme1.xml" => {
format!(r#"<a:theme xmlns:a="{A}"><a:themeElements/></a:theme>"#)
}
"word/commentsExtended.xml" => {
r#"<w15:commentsEx xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml"/>"#
.to_owned()
}
"docProps/custom.xml" => r#"<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties"/>"#.to_owned(),
other => empty(
other
.trim_start_matches("word/")
.trim_end_matches(".xml")
.replace("fontTable", "fonts")
.as_str(),
),
}
}
/// Packs a DOCX file with a paragraph of [`TEXT`] whose main document names every part of
/// [`LINKED`], each through the relationships of its [`Source`]. The entry `broken`
/// holds bytes that are not XML, and the package lacks the entry `missing`.
fn every_part(broken: &str, missing: &str) -> Vec<u8> {
let builder = Builder::default()
.relationship("", "l0", "officeDocument", DOCUMENT)
.part(
DOCUMENT,
testing::word(
"document",
&format!(
r#"<w:body><w:p><w:r><w:t>{TEXT}</w:t></w:r></w:p><w:sectPr><w:headerReference w:type="default" r:id="l0"/></w:sectPr></w:body>"#
),
),
);
let builder =
LINKED
.iter()
.enumerate()
.fold(builder, |builder, (id, &(name, kind, source))| {
let id = format!("l{id}");
match source {
Source::Main => {
builder.relationship(DOCUMENT, &id, kind, name.trim_start_matches("word/"))
}
Source::Package => builder.relationship("", &id, kind, name),
}
});
let builder = LINKED.iter().fold(builder, |builder, (name, _, _)| {
builder.part(name, linked_xml(name))
});
let entries = builder
.entries()
.into_iter()
.filter(|(name, _)| name != missing)
.map(|(name, xml)| {
let bytes = if name == broken {
b"<w:broken".to_vec()
} else {
xml
};
(name, bytes)
});
testing::zip(entries).unwrap()
}
/// The pages of laying out `bytes`, which show glyphs, with the warnings that name a part.
fn pages_and_part_warnings(bytes: &[u8]) -> (f_office_paint::DisplayList, Vec<(Warning, u32)>) {
let package = Package::open(bytes, &f_office_opc::Limits::default()).unwrap();
let laid_out = crate::layout(
&package,
(&Named(&["Times New Roman"]), &crate::ArtPictures::new()),
&Options::base(),
)
.unwrap();
let pages = laid_out.value.pages();
assert_eq!(pages.len(), 1);
let glyphs = |item: &f_office_paint::Item| matches!(item, f_office_paint::Item::Glyphs(_));
assert!(pages[0].items().iter().any(glyphs));
let warnings = laid_out.warnings.into_iter().filter(|(warning, _)| {
matches!(
warning,
Warning::PartSkipped { .. } | Warning::RelationshipsSkipped { .. }
)
});
(laid_out.value, warnings.collect())
}
#[test]
fn skips_each_part_but_the_main_document_that_does_not_read_as_if_the_package_lacked_it() {
assert_eq!(pages_and_part_warnings(&every_part("", "")).1, []);
for (part, _, _) in LINKED {
let (pages, warnings) = pages_and_part_warnings(&every_part(part, ""));
let skipped = Warning::PartSkipped {
part: Name::new(part),
reason: Reason::NotXml,
};
assert_eq!(warnings, [(skipped, 1)], "{part}");
let (without, none) = pages_and_part_warnings(&every_part("", part));
assert_eq!(none, [], "{part}");
assert_eq!(pages, without, "{part}");
}
let rels = "word/_rels/document.xml.rels";
let (pages, warnings) = pages_and_part_warnings(&every_part(rels, ""));
let main = Warning::RelationshipsSkipped {
part: Name::new("word/document.xml"),
};
assert_eq!(warnings, [(main, 1)]);
assert_eq!(pages, pages_and_part_warnings(&every_part("", rels)).0);
}
#[test]
fn stops_when_the_main_document_or_the_relationships_that_name_it_do_not_read() {
for part in ["word/document.xml", "_rels/.rels"] {
let bytes = every_part(part, "");
let package = Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
let laid_out = crate::layout(
&package,
(&Named(&["Times New Roman"]), &crate::ArtPictures::new()),
&Options::base(),
);
assert!(laid_out.is_err(), "{part}");
}
}
#[test]
fn warns_once_of_each_undeclared_prefix_of_a_part_and_draws_the_page_without_its_elements() {
let paragraph = format!("<w:p><w:r><w:t>{TEXT}</w:t></w:r></w:p>");
let header = |attribute: &str| format!("<w:p {attribute}><w:r><w:t>{TEXT}</w:t></w:r></w:p>");
// The body has a paragraph of the undeclared prefix `x` twice, the header an attribute of
// `q`, and the header's relationships part a relationship of `y`.
let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><y:Relationship Id="rId9" Type="t/image" Target="media/none.png"/></Relationships>"#;
let body = format!("{paragraph}<x:p>{paragraph}</x:p><x:p/>");
let undeclared = package(
&body,
&header(r#"q:rsidR="00A1""#),
&[],
&[("word/_rels/h1.xml.rels", rels)],
);
let declared = package(¶graph, &header(""), &[], &[]);
let fonts = Named(&["Times New Roman"]);
let lay_out = |bytes: &[u8]| {
let package = Package::open(bytes, &f_office_opc::Limits::default()).unwrap();
crate::layout(
&package,
(&fonts, &crate::ArtPictures::new()),
&Options::base(),
)
.unwrap()
};
let (with, without) = (lay_out(&undeclared), lay_out(&declared));
assert_eq!(with.value, without.value);
assert!(without.warnings.into_iter().next().is_none());
let warning = |part: &str, prefix: &str| Warning::UndeclaredPrefix {
part: Name::new(part),
prefix: Name::new(prefix),
};
let text = warning("word/h1.xml", "q").to_string();
assert_eq!(
text,
"part word/h1.xml uses the namespace prefix q without a declaration, and no reader \
takes an element of it"
);
assert_eq!(warning("word/h1.xml", "q").kind(), "undeclared-prefix");
let warnings: std::collections::HashSet<(Warning, u32)> = with.warnings.into_iter().collect();
assert_eq!(
warnings,
[
(warning("word/document.xml", "x"), 1),
(warning("word/h1.xml", "q"), 1),
(warning("word/_rels/h1.xml.rels", "y"), 1),
]
.into()
);
}
#[test]
fn warns_of_each_value_that_does_not_read_with_its_part_and_the_reading_taken() {
let run = format!(
r#"<w:r><w:rPr><w:sz w:val="thin"/><w:kern w:val="40x"/></w:rPr><w:t>{TEXT}</w:t></w:r>"#
);
let body = format!(r#"<w:p><w:pPr><w:spacing w:after="wide"/></w:pPr>{run}{run}</w:p>"#);
let header = format!(
r#"<w:p><w:pPr><w:pBdr><w:top w:val="single" w:sz="2pt" w:space="4"/></w:pBdr></w:pPr><w:r><w:t>{TEXT}</w:t></w:r></w:p>"#
);
let bytes = package(&body, &header, &[], &[]);
let invalid = |part: &str, element: &str, attribute: &str, read_as| Warning::InvalidValue {
part: Name::new(part),
element: Name::new(element),
place: ValuePlace::Attribute(Name::new(attribute)),
read_as,
};
let main = "word/document.xml";
assert_eq!(
warnings_of(&bytes, &Named(&["Times New Roman"])),
[
(invalid(main, "spacing", "after", ReadAs::Missing), 1),
(invalid(main, "sz", "val", ReadAs::Zero), 2),
(invalid(main, "kern", "val", ReadAs::Zero), 2),
(invalid("word/h1.xml", "top", "sz", ReadAs::Missing), 1),
]
);
let warning = invalid(main, "sz", "val", ReadAs::Zero);
assert_eq!(warning.kind(), "invalid-value");
}
/// A paragraph with a floating shape one inch wide whose custom path, one unit wide, runs to
/// `x` across.
fn custom_shape(x: i64) -> String {
format!(
r#"<w:p><w:r><w:drawing><wp:anchor><wp:positionH relativeFrom="column"><wp:posOffset>0</wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV><wp:extent cx="914400" cy="914400"/><wp:wrapNone/><a:graphic><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:custGeom><a:pathLst><a:path w="1" h="1"><a:moveTo><a:pt x="0" y="0"/></a:moveTo><a:lnTo><a:pt x="{x}" y="1"/></a:lnTo><a:lnTo><a:pt x="0" y="1"/></a:lnTo><a:close/></a:path></a:pathLst></a:custGeom><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r><w:r><w:t>{TEXT}</w:t></w:r></w:p>"#
)
}
/// The pages of a document whose body holds `body` and whose header holds `header`, and the
/// warnings of its layout.
fn laid_out(body: &str, header: &str) -> (f_office_paint::DisplayList, Vec<(Warning, u32)>) {
let package = package(body, header, &[], &[]);
let package = Package::open(&package, &f_office_opc::Limits::default()).unwrap();
let laid_out = crate::layout(
&package,
(&Named(&["Times New Roman"]), &crate::ArtPictures::new()),
&Options::base(),
)
.unwrap();
(laid_out.value, laid_out.warnings.into_iter().collect())
}
#[test]
fn warns_of_a_shape_whose_path_gives_a_place_out_of_range_with_its_part_and_leaves_it_out() {
let paths = |list: &f_office_paint::DisplayList| {
list.pages()[0]
.items()
.iter()
.filter(|item| matches!(item, f_office_paint::Item::Path(_)))
.count()
};
let far = custom_shape(f_office_drawingml::COORDINATE_LIMIT);
let (near, warnings) = laid_out(&custom_shape(1), "");
assert_eq!((paths(&near), warnings), (1, vec![]));
let skipped = |part| Warning::DrawingSkipped {
drawing: Drawing::Shape,
part: Name::new(part),
reason: Reason::OutOfRange,
};
let (list, warnings) = laid_out(&far, "");
assert_eq!((paths(&list), warnings), (0, vec![(skipped(DOCUMENT), 1)]));
// A shape of a header names the header's part, which its floating drawing keeps.
let (_, warnings) = laid_out("<w:p/>", &far);
let warnings = warnings.into_iter().map(|(warning, _)| warning);
assert_eq!(warnings.collect::<Vec<_>>(), [skipped("word/h1.xml")]);
}
/// A paragraph of [`TEXT`] around a floating drawing one inch square whose `a:graphicData`
/// holds `data`.
fn anchored(data: &str) -> String {
format!(
r#"<w:p><w:r><w:t>{TEXT}</w:t></w:r><w:r><w:drawing><wp:anchor><wp:positionH relativeFrom="column"><wp:posOffset>0</wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV><wp:extent cx="914400" cy="914400"/><wp:wrapNone/><a:graphic><a:graphicData>{data}</a:graphicData></a:graphic></wp:anchor></w:drawing></w:r><w:r><w:t>{TEXT}</w:t></w:r></w:p>"#
)
}
/// A paragraph of [`TEXT`] with a floating shape whose properties hold `props`, and whose text
/// box holds [`TEXT`] too.
fn shape_with(props: &str) -> String {
anchored(&format!(
r#"<wps:wsp xmlns:wps="{WPS}"><wps:spPr>{props}</wps:spPr><wps:txbx><w:txbxContent><w:p><w:r><w:t>{TEXT}</w:t></w:r></w:p></w:txbxContent></wps:txbx><wps:bodyPr/></wps:wsp>"#
))
}
/// A paragraph of [`TEXT`] around a run that holds `content`.
fn in_run(content: &str) -> String {
format!("<w:p><w:r><w:t>{TEXT}</w:t></w:r><w:r>{content}</w:r></w:p>")
}
/// A `w:pict` that holds the VML `shapes`.
fn pict(shapes: &str) -> String {
in_run(&format!(
r#"<w:pict xmlns:v="{V}" xmlns:o="{O}">{shapes}</w:pict>"#
))
}
#[test]
fn warns_of_each_whole_drawing_that_it_does_not_draw_with_its_part_and_holds_no_text() {
let chart_ex = format!(r#"<cx:chart xmlns:cx="{CX}" r:id="chart"/>"#);
let ink = format!(r#"<w14:contentPart xmlns:w14="{W14}" r:id="ink"/>"#);
let frame = |data: &str| {
format!(
"<wpg:graphicFrame><a:graphic><a:graphicData>{data}</a:graphicData></a:graphic></wpg:graphicFrame>"
)
};
let group = format!(
r#"<wpg:wgp xmlns:wpg="{WPG}" xmlns:mc="{MC}" xmlns:w14="{W14}"><wpg:grpSpPr/>{}{}{ink}<mc:AlternateContent><mc:Choice Requires="w14">{ink}</mc:Choice><mc:Fallback><pic:pic/></mc:Fallback></mc:AlternateContent></wpg:wgp>"#,
frame(r#"<c:chart r:id="chart"/>"#),
frame(r#"<dgm:relIds r:dm="data"/>"#),
);
let floating_image = r#"<v:shape style="position:absolute;width:10pt;height:10pt"><v:imagedata o:href="picture.png"/></v:shape>"#;
let second_vml_shape = r#"<v:rect style="position:absolute;width:10pt;height:10pt"/><v:rect style="position:absolute;width:10pt;height:10pt"/>"#;
let body = [
// A floating chart, of either markup, and a group's chart, SmartArt graphic
// and ink, the second time in alternate content.
anchored(r#"<c:chart r:id="chart"/>"#),
anchored(&chart_ex),
anchored(&group),
// An inline chart of Office 2016 and ink, and ink in a run.
drawing(&chart_ex),
drawing(&ink),
in_run(&ink),
// Linked images: of a picture, of a shape's picture fill, and of an inline and a
// floating VML picture.
drawing(r#"<pic:pic><pic:blipFill><a:blip r:link="file"/></pic:blipFill></pic:pic>"#),
shape_with(r#"<a:prstGeom prst="rect"/><a:blipFill><a:blip r:link="file"/></a:blipFill>"#),
pict(r#"<v:shape style="width:10pt;height:10pt"><v:imagedata o:href="picture.png"/></v:shape>"#),
pict(floating_image),
// A second shape in a VML picture.
pict(second_vml_shape),
]
.concat();
let (_, warnings) = laid_out(&body, &pict(second_vml_shape));
let want = vec![
// A floating chart whose part the package lacks, as an inline one, and a chart of
// Office 2016 floating and inline, and a group's chart.
(skipped(Drawing::Chart, DOCUMENT, Reason::Unlinked), 1),
(
skipped(
Drawing::Chart,
DOCUMENT,
Reason::Chart(ChartReason::ChartEx),
),
2,
),
(
skipped(
Drawing::Chart,
DOCUMENT,
Reason::Chart(ChartReason::InGroup),
),
1,
),
(skipped(Drawing::SmartArt, DOCUMENT, Reason::Unsupported), 1),
(skipped(Drawing::Shape, DOCUMENT, Reason::Unsupported), 5),
(skipped(Drawing::Picture, DOCUMENT, Reason::Unlinked), 4),
(
skipped(Drawing::Shape, "word/h1.xml", Reason::Unsupported),
1,
),
];
assert_warnings_hold_no_text(&warnings, &want);
}
#[test]
fn warns_of_each_feature_that_it_does_not_draw_with_its_part_and_holds_no_text_of_the_document() {
use f_office_drawingml::Feature;
const RECT: &str = r#"<a:prstGeom prst="rect"/>"#;
let pattern =
r#"<a:pattFill prst="pct5"><a:fgClr><a:srgbClr val="000000"/></a:fgClr></a:pattFill>"#;
let gradient = r#"<a:gradFill><a:gsLst><a:gs pos="0"><a:srgbClr val="00FF00"/></a:gs></a:gsLst></a:gradFill>"#;
let body = [
shape_with(&format!("{RECT}{pattern}")),
shape_with(&format!("{RECT}<a:grpFill/>")),
shape_with(&format!("{RECT}{gradient}")),
shape_with(&format!("{RECT}<a:ln>{pattern}</a:ln>")),
drawing(
r#"<pic:pic><pic:blipFill><a:blip r:embed="lost"/></pic:blipFill><pic:spPr><a:xfrm rot="1800000"/></pic:spPr></pic:pic>"#,
),
drawing(
r#"<pic:pic><pic:blipFill><a:blip r:embed="lost"/></pic:blipFill><pic:spPr><a:xfrm rot="2700000"/></pic:spPr></pic:pic>"#,
),
]
.concat();
let header = drawing(
r#"<pic:pic><pic:blipFill><a:blip r:embed="lost"/></pic:blipFill><pic:spPr><a:xfrm rot="2700000"/></pic:spPr></pic:pic>"#,
);
let (_, warnings) = laid_out(&body, &header);
let feature = |part: &str, feature| Warning::DrawingMl {
part: Name::new(part),
warning: DrawingMlWarning::FeatureNotSupported { feature },
};
let want = vec![
(feature(DOCUMENT, Feature::PatternFill), 1),
(feature(DOCUMENT, Feature::GroupFill), 1),
(feature(DOCUMENT, Feature::GradientFill), 1),
(feature(DOCUMENT, Feature::LineFill), 1),
// The turned shape and the turned picture of one part are one warning that came
// twice.
(feature(DOCUMENT, Feature::Turn), 2),
(feature("word/h1.xml", Feature::Turn), 1),
];
assert_warnings_hold_no_text(&warnings, &want);
assert_eq!(
feature(DOCUMENT, Feature::Turn).to_string(),
"in part word/document.xml, a rotation other than a whole number of quarter turns is \
not supported, and the shape or picture is not drawn"
);
assert_eq!(
feature(DOCUMENT, Feature::GradientFill).kind(),
"drawingml-gradient-fill-not-supported"
);
}
#[test]
fn warns_of_the_outlines_colors_and_effects_that_it_does_not_draw_and_holds_no_text() {
use f_office_drawingml::Feature;
const RECT: &str = r#"<a:prstGeom prst="rect"/>"#;
let solid = |color: &str| format!("{RECT}<a:solidFill>{color}</a:solidFill>");
let body = [
// A picture in an unsupported open line geometry, with a dashed line, tint effect, and shadow.
drawing(
r#"<pic:pic><pic:blipFill><a:blip r:embed="lost"><a:tint hue="0" amt="50000"/></a:blip></pic:blipFill><pic:spPr><a:prstGeom prst="line"/><a:ln><a:solidFill><a:srgbClr val="000000"/></a:solidFill><a:prstDash val="dash"/></a:ln><a:effectLst><a:outerShdw/></a:effectLst></pic:spPr></pic:pic>"#,
),
// A picture fill of an unsupported open line geometry, in two colors.
shape_with(
r#"<a:prstGeom prst="line"/><a:blipFill><a:blip r:embed="lost"><a:duotone/></a:blip></a:blipFill>"#,
),
shape_with(&solid(
r#"<a:srgbClr val="FF0000"><a:hueOff val="60000"/></a:srgbClr>"#,
)),
shape_with(&solid(r#"<a:hslClr hue="0" sat="100%" lum="50%"/>"#)),
shape_with(&format!(
r#"{RECT}<a:scene3d><a:camera prst="isometricTopUp"/><a:lightRig rig="threePt" dir="t"/></a:scene3d>"#
)),
shape_with(&format!(
r#"{RECT}<a:effectLst><a:blur/><a:glow rad="1"/><a:reflection/><a:softEdge rad="1"/></a:effectLst>"#
)),
// Modifiers that change nothing and an empty effect list give no warning.
shape_with(&format!(
"{}<a:effectLst/>",
solid(r#"<a:srgbClr val="FF0000"><a:satOff val="0"/></a:srgbClr>"#)
)),
]
.concat();
let header = shape_with(&format!("{RECT}<a:effectLst><a:outerShdw/></a:effectLst>"));
let (_, warnings) = laid_out(&body, &header);
let feature = |part: &str, feature| Warning::DrawingMl {
part: Name::new(part),
warning: DrawingMlWarning::FeatureNotSupported { feature },
};
let want = vec![
(feature(DOCUMENT, Feature::ShapedPicture), 2),
(feature(DOCUMENT, Feature::PictureLine), 1),
(feature(DOCUMENT, Feature::PictureEffect), 2),
// The picture's shadow, which the base target does not draw.
(feature(DOCUMENT, Feature::Shadow), 1),
(feature(DOCUMENT, Feature::ColorModifier), 1),
(feature(DOCUMENT, Feature::ColorModel), 1),
(feature(DOCUMENT, Feature::ThreeD), 1),
(feature(DOCUMENT, Feature::OtherEffect), 1),
(feature(DOCUMENT, Feature::Glow), 1),
(feature(DOCUMENT, Feature::Reflection), 1),
(feature(DOCUMENT, Feature::SoftEdge), 1),
(feature("word/h1.xml", Feature::Shadow), 1),
// The two pictures name an image that the package lacks.
(skipped(Drawing::Picture, DOCUMENT, Reason::Unlinked), 2),
];
assert_warnings_hold_no_text(&warnings, &want);
}
/// The warnings of laying out a document with `body` and a theme whose format scheme holds
/// `scheme`, each with its count.
fn warnings_with_theme(scheme: &str, body: &str) -> Vec<(Warning, u32)> {
let theme = format!(
r#"<a:theme xmlns:a="{A}"><a:themeElements><a:clrScheme><a:accent1><a:srgbClr val="4472C4"/></a:accent1></a:clrScheme><a:fmtScheme>{scheme}</a:fmtScheme></a:themeElements></a:theme>"#
);
let document = format!(
r#"<w:document xmlns:w="{W}" xmlns:r="{R}" xmlns:wp="{WP}" xmlns:a="{A}"><w:body>{body}</w:body></w:document>"#
);
let bytes = testing::package(document)
.relationship(DOCUMENT, "theme", "theme", "theme/theme1.xml")
.part("word/theme/theme1.xml", theme)
.plain_styles()
.zip()
.unwrap();
warnings_of(&bytes, &Named(&["Times New Roman"]))
}
/// A paragraph of [`TEXT`] with a floating shape of the geometry `geometry`, whose properties
/// hold `props` after it, whose style holds `style`, and whose text box holds [`TEXT`].
fn styled_shape(geometry: &str, props: &str, style: &str) -> String {
anchored(&format!(
r#"<wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:prstGeom prst="{geometry}"/>{props}</wps:spPr><wps:style>{style}</wps:style><wps:txbx><w:txbxContent><w:p><w:r><w:t>{TEXT}</w:t></w:r></w:p></w:txbxContent></wps:txbx><wps:bodyPr/></wps:wsp>"#
))
}
/// The warning of the feature `feature` of a drawing of the main document.
fn drawing_feature(feature: f_office_drawingml::Feature) -> Warning {
Warning::DrawingMl {
part: Name::new(DOCUMENT),
warning: DrawingMlWarning::FeatureNotSupported { feature },
}
}
#[test]
fn warns_of_each_shape_that_takes_a_style_of_the_theme_that_it_does_not_draw() {
use f_office_drawingml::Feature;
// The first fill style is a solid fill of the reference's own color, which F-Office draws,
// and the second a gradient, which it does not.
let scheme = r#"<a:fillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:gradFill/></a:fillStyleLst>"#;
let styled = |fill: u32| {
styled_shape(
"rect",
"",
&format!(
r#"<a:lnRef idx="0"/><a:fillRef idx="{fill}"><a:schemeClr val="accent1"/></a:fillRef><a:effectRef idx="0"/>"#
),
)
};
assert_eq!(warnings_with_theme(scheme, &styled(1)), []);
let warning = drawing_feature(Feature::ThemeStyle);
let body = [styled(1), styled(2), styled(2)].concat();
assert_eq!(warnings_with_theme(scheme, &body), [(warning.clone(), 2)]);
assert_eq!(warning.kind(), "drawingml-theme-style-not-supported");
assert_holds_no_text(&[(warning, 2)]);
}
#[test]
fn warns_of_the_dash_and_the_ends_of_a_line_its_own_or_of_its_line_style() {
use f_office_drawingml::Feature;
// The first line style is plain and solid, and the second dashed with an arrowhead.
let scheme = r#"<a:lnStyleLst><a:ln w="6350"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln><a:ln w="12700"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="dash"/><a:tailEnd type="triangle"/></a:ln></a:lnStyleLst>"#;
let line_style = |index: u32| {
format!(
r#"<a:lnRef idx="{index}"><a:schemeClr val="accent1"/></a:lnRef><a:fillRef idx="0"/><a:effectRef idx="0"/>"#
)
};
let own = r#"<a:ln><a:solidFill><a:srgbClr val="000000"/></a:solidFill><a:custDash><a:ds d="100000" sp="100000"/></a:custDash><a:headEnd type="arrow"/></a:ln>"#;
let empty_dash =
r#"<a:ln><a:solidFill><a:srgbClr val="000000"/></a:solidFill><a:custDash/></a:ln>"#;
let bad_end = r#"<a:ln><a:solidFill><a:srgbClr val="000000"/></a:solidFill><a:tailEnd type="unknown"/></a:ln>"#;
assert_eq!(
warnings_with_theme(scheme, &styled_shape("line", "", &line_style(1))),
[]
);
let body = [
// The line style's dash and triangle end (both drawn without warning), on a line.
styled_shape("line", "", &line_style(2)),
// Its dash only (drawn without warning), on a rectangle, whose outline is closed.
styled_shape("rect", "", &line_style(2)),
// An own custom dash and arrow end (both drawn without warning), with no style.
styled_shape("line", own, &line_style(0)),
// An empty custom dash still warns.
styled_shape("rect", empty_dash, &line_style(0)),
// An unrecognized end type on an open line still warns.
styled_shape("line", bad_end, &line_style(0)),
]
.concat();
let mut got = warnings_with_theme(scheme, &body);
got.sort_by_key(|(warning, _)| warning.to_string());
let want = [
(drawing_feature(Feature::LineDash), 1),
(drawing_feature(Feature::LineEnd), 1),
];
assert_eq!(got, want);
assert_holds_no_text(&got);
}
/// The layout draws a shape's own compound line in its parts on a straight line only, and
/// warns of one on another outline that it draws, once for each such shape.
#[test]
fn warns_of_a_compound_line_on_an_outline_other_than_a_straight_line() {
use f_office_drawingml::Feature;
let double =
r#"<a:ln w="38100" cmpd="dbl"><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:ln>"#;
let hidden = r#"<a:ln w="38100" cmpd="dbl"><a:noFill/></a:ln>"#;
let body = [
styled_shape("line", double, ""),
styled_shape("rect", double, ""),
styled_shape("ellipse", double, ""),
styled_shape("rightArrow", double, ""),
styled_shape("chevron", double, ""),
// A line without a fill is not drawn.
styled_shape("rightArrow", hidden, ""),
]
.concat();
let got = warnings_with_theme("", &body);
let warning = drawing_feature(Feature::CompoundOutline);
assert_eq!(got, [(warning.clone(), 2)]);
assert_eq!(warning.kind(), "drawingml-compound-outline-not-supported");
assert_holds_no_text(&got);
}
#[test]
fn draws_a_watermark_without_a_warning_of_its_geometry_or_rotation() {
let watermark = |face: &str| {
pict(&format!(
r##"<v:shape type="#_x0000_t136" style="position:absolute;width:400pt;height:100pt;rotation:315;mso-position-horizontal:center;mso-position-horizontal-relative:margin" fillcolor="silver" stroked="f"><v:fill opacity=".5"/><v:textpath style="font-family:"{face}";font-size:1pt" string="A"/></v:shape>"##
))
};
// A face that the caller lacks draws no text, and one whose outlines the caller cannot
// give leaves the shape out.
let header = [watermark("Lost Sans"), watermark("Times New Roman")].concat();
let package = package("", &header, &[], &[]);
let package = Package::open(&package, &f_office_opc::Limits::default()).unwrap();
let options = Options {
overrides: crate::profile::Overrides::default().with_quirk("VmlTextPath", "InkAligned"),
..Options::base()
};
let laid_out = crate::layout(
&package,
(&Named(&["Times New Roman"]), &crate::ArtPictures::new()),
&options,
)
.unwrap();
let warnings: Vec<_> = laid_out.warnings.into_iter().collect();
let lost = Name::new("Lost Sans");
let want = vec![
(
Warning::TextNotDrawn {
asked: Some(lost.clone()),
tried: vec![lost],
},
1,
),
(
Warning::DrawingSkipped {
drawing: Drawing::Shape,
part: Name::new("word/h1.xml"),
reason: Reason::Unsupported,
},
1,
),
];
assert_eq!(warnings, want);
}
#[test]
fn warns_of_the_vml_that_it_does_not_draw_with_its_part_and_holds_no_text() {
use crate::warnings::Feature;
let floating = "position:absolute;width:10pt;height:10pt";
let body = [
pict(&format!(
r##"<v:shape type="#_x0000_t5" style="{floating}"/>"##
)),
pict(r#"<v:rect style="width:10pt;height:10pt;rotation:30"><v:fill type="pattern"/></v:rect>"#),
// A picture in its line that turns gray, whose image the package lacks.
pict(
r#"<v:shape style="width:10pt;height:10pt"><v:imagedata r:id="lost" grayscale="t"/></v:shape>"#,
),
pict("<v:polyline/><v:image/>"),
]
.concat();
let header = pict(r#"<v:oval style="width:10pt;height:10pt;rotation:100"/>"#);
let (_, warnings) = laid_out(&body, &header);
let feature = |part: &str, feature| Warning::FeatureNotSupported {
part: Name::new(part),
feature,
};
let want = vec![
(feature(DOCUMENT, Feature::VmlGeometry), 1),
(feature(DOCUMENT, Feature::VmlRotation), 1),
(feature(DOCUMENT, Feature::VmlPictureColors), 1),
(feature("word/h1.xml", Feature::VmlRotation), 1),
(
Warning::ValueNotSupported {
part: Name::new(DOCUMENT),
element: Name::new("fill"),
place: ValuePlace::Attribute(Name::new("type")),
value: Name::new("pattern"),
},
1,
),
(skipped(Drawing::Shape, DOCUMENT, Reason::Unsupported), 1),
(skipped(Drawing::Picture, DOCUMENT, Reason::Unsupported), 1),
(skipped(Drawing::Picture, DOCUMENT, Reason::Unlinked), 1),
];
assert_warnings_hold_no_text(&warnings, &want);
}
#[test]
fn warns_of_the_fills_and_effects_of_text_with_their_part_and_holds_no_text() {
use crate::warnings::Feature;
let run = |props: &str| {
format!(
r#"<w:p><w:r><w:rPr xmlns:w14="{W14}">{props}</w:rPr><w:t>{TEXT}</w:t></w:r></w:p>"#
)
};
let body = [
run(r#"<w14:textFill><w14:gradFill><w14:path w14:path="circle"/></w14:gradFill></w14:textFill>"#),
run(r#"<w14:textOutline w14:w="9525"><w14:gradFill/></w14:textOutline>"#),
// A reflection that shows nothing gives no warning.
run(r#"<w14:reflection w14:sx="0" w14:sy="0"/>"#),
]
.concat();
let header = run(r#"<w14:glow w14:rad="63500"><w14:schemeClr w14:val="accent1"/></w14:glow>"#);
let (_, warnings) = laid_out(&body, &header);
let feature = |part: &str, feature| Warning::FeatureNotSupported {
part: Name::new(part),
feature,
};
let want = vec![
(feature(DOCUMENT, Feature::TextFill), 1),
(feature(DOCUMENT, Feature::TextOutlineFill), 1),
(feature("word/h1.xml", Feature::TextEffect), 1),
];
assert_warnings_hold_no_text(&warnings, &want);
}
#[test]
fn warns_of_the_structures_of_equations_with_their_part_and_holds_no_text() {
use crate::warnings::Feature;
let equation = |math: &str| {
format!(r#"<w:p><w:r><w:t>{TEXT}</w:t></w:r><m:oMath xmlns:m="{M}">{math}</m:oMath></w:p>"#)
};
let content = "<m:e><m:r><m:t>x</m:t></m:r></m:e>";
let body = [
equation(&format!(
r#"<m:box><m:boxPr><m:opEmu m:val="on"/></m:boxPr>{content}</m:box>"#
)),
// A box that only groups its content, a border box, a radical, an accent, a bar,
// a grouping character, and limits give no warning.
equation(&format!("<m:box>{content}</m:box>")),
equation(&format!("<m:borderBox>{content}</m:borderBox>")),
equation(&format!("<m:rad>{content}</m:rad>")),
equation(&format!("<m:acc>{content}</m:acc>")),
equation(&format!("<m:bar>{content}</m:bar>")),
equation(&format!("<m:groupChr>{content}</m:groupChr>")),
equation(&format!("<m:limLow>{content}<m:lim/></m:limLow>")),
equation(&format!("<m:limUpp>{content}<m:lim/></m:limUpp>")),
]
.concat();
let header = equation(&format!(
"<m:box><m:boxPr><m:brk/></m:boxPr>{content}</m:box>"
));
let (_, warnings) = laid_out(&body, &header);
let feature = |part: &str| Warning::FeatureNotSupported {
part: Name::new(part),
feature: Feature::MathStructure,
};
let want = vec![(feature(DOCUMENT), 1), (feature("word/h1.xml"), 1)];
// The test's fonts lack the font of equations, which warns of its own.
let features: Vec<_> = warnings
.iter()
.filter(|(warning, _)| matches!(warning, Warning::FeatureNotSupported { .. }))
.cloned()
.collect();
assert_warnings_hold_no_text(&features, &want);
assert_holds_no_text(&warnings);
}
#[test]
fn warns_of_the_run_and_cell_properties_that_it_does_not_draw_with_their_part_and_holds_no_text() {
use crate::warnings::Feature;
let run =
|props: &str| format!("<w:p><w:r><w:rPr>{props}</w:rPr><w:t>{TEXT}</w:t></w:r></w:p>");
let body = [
run("<w:shadow/>"),
run("<w:dstrike/>"),
run(r#"<w:bdr w:val="single" w:sz="4" w:space="0" w:color="auto"/>"#),
run(r#"<w:em w:val="dot"/>"#),
// A strike, and a border of no line, give no warning.
run(r#"<w:strike/><w:bdr w:val="nil"/>"#),
format!(
r#"<w:tbl><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid><w:tr><w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/><w:tcFitText/></w:tcPr><w:p><w:r><w:t>{TEXT}</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p/>"#
),
]
.concat();
let header = run(r#"<w:fitText w:val="1440" w:id="1"/>"#);
let (_, warnings) = laid_out(&body, &header);
let feature = |part: &str, feature| Warning::FeatureNotSupported {
part: Name::new(part),
feature,
};
let want = vec![
(feature(DOCUMENT, Feature::TextEffect), 1),
(feature(DOCUMENT, Feature::DoubleStrike), 1),
(feature(DOCUMENT, Feature::TextBorder), 1),
(feature(DOCUMENT, Feature::EastAsianLayout), 1),
(feature(DOCUMENT, Feature::FitText), 1),
(feature("word/h1.xml", Feature::FitText), 1),
];
assert_warnings_hold_no_text(&warnings, &want);
}
/// The feature warnings of a document with the main document `body`, the plain styles with
/// `styles` after them, and a numbering part that holds `numbering`.
fn run_feature_warnings(body: &str, styles: &str, numbering: &str) -> Vec<(Warning, u32)> {
let styles = format!("{}{styles}", testing::PLAIN_STYLES);
let bytes = testing::docx(body)
.word_part("s1", "styles", "styles.xml", "styles", &styles)
.word_part("n1", "numbering", "numbering.xml", "numbering", numbering)
.zip()
.unwrap();
warnings_of(&bytes, &Named(&["Times New Roman"]))
.into_iter()
.filter(|(warning, _)| matches!(warning, Warning::FeatureNotSupported { .. }))
.collect()
}
/// A character style `Outlined` whose text is outlined, and a style `Struck` whose text is
/// struck through twice.
const RUN_STYLES: &str = r#"<w:style w:type="character" w:styleId="Outlined"><w:name w:val="Outlined"/><w:rPr><w:outline/></w:rPr></w:style><w:style w:type="character" w:styleId="Struck"><w:name w:val="Struck"/><w:rPr><w:dstrike/></w:rPr></w:style>"#;
/// A list `1` whose level 0 shows its number in the run properties `props`, with the level's
/// text `text`.
fn list_with(props: &str, text: &str) -> String {
format!(
r#"<w:abstractNum w:abstractNumId="0"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="{text}"/><w:lvlJc w:val="left"/><w:rPr>{props}</w:rPr></w:lvl></w:abstractNum><w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>"#
)
}
/// A paragraph of the runs `runs`, each of [`TEXT`] with its run properties.
fn paragraph_of_runs(runs: &[&str]) -> String {
let runs = runs
.iter()
.map(|props| format!("<w:r><w:rPr>{props}</w:rPr><w:t>{TEXT}</w:t></w:r>"))
.collect::<Vec<_>>()
.concat();
format!("<w:p>{runs}</w:p>")
}
#[test]
fn warns_of_a_run_feature_once_for_each_paragraph_and_part_that_draws_it() {
use crate::warnings::Feature;
let warnings = |body: &str| run_feature_warnings(body, RUN_STYLES, "");
let styled = r#"<w:rStyle w:val="Outlined"/>"#;
let effect = |part: &str, count: u32| (warned_once(part, Feature::TextEffect).0, count);
// The style that three runs use: once where they share a paragraph, three times where
// each is a paragraph of its own.
assert_eq!(
warnings(¶graph_of_runs(&[styled, styled, styled])),
vec![effect("word/styles.xml", 1)]
);
assert_eq!(
warnings(¶graph_of_runs(&[styled]).repeat(3)),
vec![effect("word/styles.xml", 3)]
);
// Fifty outlined runs of one paragraph warn once.
assert_eq!(
warnings(¶graph_of_runs(&["<w:outline/>"; 50])),
vec![effect(DOCUMENT, 1)]
);
// One paragraph of a run that is outlined by its style and one by its own properties
// warns once for each part.
let mut got = warnings(¶graph_of_runs(&[styled, "<w:outline/>"]));
got.sort_by_key(|(warning, _)| warning.to_string());
assert_eq!(got, vec![effect(DOCUMENT, 1), effect("word/styles.xml", 1)]);
// An equation's run counts as a run of its paragraph.
let equation = format!(
r#"<w:p><m:oMath xmlns:m="{M}"><m:r><w:rPr><w:outline/></w:rPr><m:t>x</m:t></m:r></m:oMath></w:p>"#
);
assert_eq!(warnings(&equation), vec![effect(DOCUMENT, 1)]);
}
#[test]
fn warns_of_no_run_feature_where_no_text_draws_it() {
let plain = format!("<w:p><w:r><w:t>{TEXT}</w:t></w:r></w:p>");
let unused_paragraph_style = r#"<w:style w:type="paragraph" w:styleId="Embossed"><w:name w:val="Embossed"/><w:rPr><w:emboss/></w:rPr></w:style>"#;
let unused_table_style = r#"<w:style w:type="table" w:styleId="Shaded"><w:name w:val="Shaded"/><w:tblPr><w:shd w:val="clear" w:color="auto" w:fill="D9D9D9"/></w:tblPr></w:style>"#;
let styles = [RUN_STYLES, unused_paragraph_style, unused_table_style].concat();
let cases = [
// Styles and a list level that no text uses.
(plain.clone(), list_with("<w:outline/>", "%1.")),
// A paragraph mark, which draws no text, and its old properties before a tracked
// change.
(
format!(
r"<w:p><w:pPr><w:rPr><w:outline/><w:dstrike/></w:rPr></w:pPr><w:r><w:t>{TEXT}</w:t></w:r></w:p>"
),
String::new(),
),
(
format!(
r#"<w:p><w:pPr><w:pPrChange w:id="1" w:author="A"><w:pPr><w:mirrorIndents/><w:ind w:left="720"/><w:rPr><w:outline/></w:rPr></w:pPr></w:pPrChange></w:pPr><w:r><w:t>{TEXT}</w:t></w:r></w:p>"#
),
String::new(),
),
// A run's old properties before a tracked change.
(
paragraph_of_runs(&[
r#"<w:rPrChange w:id="2" w:author="A"><w:rPr><w:outline/></w:rPr></w:rPrChange>"#,
]),
String::new(),
),
// A run that turns off its style's double strike, a hidden run, and a run that holds
// no text.
(
paragraph_of_runs(&[r#"<w:rStyle w:val="Struck"/><w:dstrike w:val="0"/>"#]),
String::new(),
),
(
paragraph_of_runs(&["<w:vanish/><w:outline/>"]),
String::new(),
),
(
format!(
r"<w:p><w:r><w:rPr><w:outline/></w:rPr><w:tab/></w:r><w:r><w:t>{TEXT}</w:t></w:r></w:p>"
),
String::new(),
),
// A list level whose label shows no text.
(
format!(
r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>{TEXT}</w:t></w:r></w:p>"#
),
list_with("<w:outline/>", ""),
),
];
for (body, numbering) in cases {
assert_eq!(
run_feature_warnings(&body, &styles, &numbering),
vec![],
"{body} {numbering}"
);
}
}
#[test]
fn warns_of_the_run_features_of_a_list_label_as_of_a_run_of_its_paragraph() {
use crate::warnings::Feature;
let listed = |mark: &str| {
format!(
r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr><w:rPr>{mark}</w:rPr></w:pPr><w:r><w:t>{TEXT}</w:t></w:r></w:p>"#
)
};
// The level's own properties, with the numbering part.
assert_eq!(
run_feature_warnings(&listed(""), "", &list_with("<w:outline/>", "%1.")),
vec![warned_once("word/numbering.xml", Feature::TextEffect)]
);
// The paragraph mark's properties, which the label takes, with the main document.
assert_eq!(
run_feature_warnings(&listed("<w:dstrike/>"), "", &list_with("", "%1.")),
vec![warned_once(DOCUMENT, Feature::DoubleStrike)]
);
}
#[test]
fn warns_of_each_unsupported_run_property_with_its_feature() {
use crate::props::{TextEffect, UnsupportedProperty};
let black = r#"<w14:srgbClr w14:val="000000"/>"#;
// Markup of each property that shows its feature. The match has no wildcard, so a new
// property does not compile until it is named here.
let markup = |property: UnsupportedProperty| {
match property {
UnsupportedProperty::Outline => "<w:outline/>".to_owned(),
UnsupportedProperty::Shadow => "<w:shadow/>".to_owned(),
UnsupportedProperty::Emboss => "<w:emboss/>".to_owned(),
UnsupportedProperty::Imprint => "<w:imprint/>".to_owned(),
UnsupportedProperty::DoubleStrike => "<w:dstrike/>".to_owned(),
UnsupportedProperty::Border => r#"<w:bdr w:val="single" w:sz="4"/>"#.to_owned(),
UnsupportedProperty::FitText => r#"<w:fitText w:val="1440" w:id="1"/>"#.to_owned(),
UnsupportedProperty::Emphasis => r#"<w:em w:val="dot"/>"#.to_owned(),
UnsupportedProperty::EastAsianLayout => {
r#"<w:eastAsianLayout w:id="1" w:combine="1"/>"#.to_owned()
}
UnsupportedProperty::Effect(TextEffect::Glow) => {
format!(r#"<w14:glow w14:rad="63500">{black}</w14:glow>"#)
}
UnsupportedProperty::Effect(TextEffect::Shadow) => {
format!(r#"<w14:shadow w14:sx="100000" w14:sy="100000">{black}</w14:shadow>"#)
}
UnsupportedProperty::Effect(TextEffect::Reflection) => {
r#"<w14:reflection w14:stA="50000" w14:sx="100000" w14:sy="100000"/>"#.to_owned()
}
UnsupportedProperty::Effect(TextEffect::Scene) => {
r#"<w14:scene3d><w14:camera w14:prst="isometricTopUp"/></w14:scene3d>"#.to_owned()
}
UnsupportedProperty::Effect(TextEffect::Depth) => {
r#"<w14:props3d w14:extrusionH="57150"/>"#.to_owned()
}
UnsupportedProperty::TextFill => {
r#"<w14:textFill><w14:gradFill><w14:path w14:path="circle"/></w14:gradFill></w14:textFill>"#
.to_owned()
}
UnsupportedProperty::TextOutlineFill => {
r#"<w14:textOutline w14:w="9525"><w14:gradFill/></w14:textOutline>"#.to_owned()
}
}
};
for property in UnsupportedProperty::ALL {
let body = format!(
r#"<w:p><w:r><w:rPr xmlns:w14="{W14}">{}</w:rPr><w:t>{TEXT}</w:t></w:r></w:p>"#,
markup(property)
);
assert_eq!(
run_feature_warnings(&body, "", ""),
vec![warned_once(DOCUMENT, property.feature())],
"{property:?}"
);
}
}
#[test]
fn warns_of_fitted_cells_once_for_each_table_and_part() {
use crate::warnings::Feature;
let fitted = |fit: &str| {
format!(
r#"<w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/>{fit}</w:tcPr><w:p><w:r><w:t>{TEXT}</w:t></w:r></w:p></w:tc>"#
)
};
let table = |cells: &str| {
format!(
r#"<w:tbl><w:tblGrid><w:gridCol w:w="2000"/><w:gridCol w:w="2000"/></w:tblGrid><w:tr>{cells}</w:tr><w:tr>{cells}</w:tr></w:tbl><w:p/>"#
)
};
let two_fitted = table(&fitted("<w:tcFitText/>").repeat(2));
assert_eq!(
run_feature_warnings(&two_fitted, "", ""),
vec![warned_once(DOCUMENT, Feature::FitText)]
);
assert_eq!(
run_feature_warnings(&two_fitted.repeat(2), "", ""),
vec![(warned_once(DOCUMENT, Feature::FitText).0, 2)]
);
let unfitted = table(&fitted(r#"<w:tcFitText w:val="0"/>"#).repeat(2));
assert_eq!(run_feature_warnings(&unfitted, "", ""), vec![]);
}
/// The warnings of features that F-Office does not draw, of a document with the settings
/// `settings` laid out for `target`.
fn feature_warnings_with_settings(target: crate::Target, settings: &str) -> Vec<(Warning, u32)> {
let body = format!("<w:p><w:r><w:t>{TEXT}</w:t></w:r></w:p>");
let bytes = testing::docx(&body)
.plain_styles()
.word_part("s1", "settings", "settings.xml", "settings", settings)
.zip()
.unwrap();
let package = Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
let options = Options {
configuration: crate::Configuration::of(target),
..Options::base()
};
crate::layout(
&package,
(&Named(&["Times New Roman"]), &crate::ArtPictures::new()),
&options,
)
.unwrap()
.warnings
.into_iter()
.filter(|(warning, _)| matches!(warning, Warning::FeatureNotSupported { .. }))
.collect()
}
#[test]
fn warns_of_automatic_hyphenation_with_the_settings_part_where_the_target_hyphenates_nothing() {
use crate::quirks::AutomaticHyphenation;
use crate::warnings::Feature;
let mut seen = Vec::new();
for target in crate::Target::all() {
let options = crate::Options {
configuration: crate::Configuration::of(target),
..crate::Options::base()
};
let (quirks, _, _, _) = crate::quirks_and_device(&options.profile().unwrap()).unwrap();
let warned = match quirks.automatic_hyphenation {
AutomaticHyphenation::Off => vec![(
Warning::FeatureNotSupported {
part: Name::new("word/settings.xml"),
feature: Feature::AutoHyphenation,
},
1,
)],
AutomaticHyphenation::EnglishFrenchSpanish => vec![],
};
seen.push(quirks.automatic_hyphenation);
// Off, also as `off`, which the older set of the settings readers reads as on.
let none = vec![];
for (settings, expected) in [
("<w:autoHyphenation/>", &warned),
(
r#"<w:autoHyphenation w:val="true"/><w:hyphenationZone w:val="357"/>"#,
&warned,
),
(r#"<w:autoHyphenation w:val="0"/>"#, &none),
(r#"<w:autoHyphenation w:val="off"/>"#, &none),
("<w:doNotHyphenateCaps/>", &none),
] {
assert_eq!(
&feature_warnings_with_settings(target, settings),
expected,
"{target:?} {settings}"
);
}
}
// Some target hyphenates, and some hyphenates nothing.
assert!(seen.contains(&AutomaticHyphenation::Off));
assert!(seen.contains(&AutomaticHyphenation::EnglishFrenchSpanish));
}
/// The warnings of features and values of a document with the main document `body` and a table
/// style `Shaded` whose table properties hold `style_shading`.
fn feature_and_value_warnings(body: &str, style_shading: &str) -> Vec<(Warning, u32)> {
let style = format!(
r#"<w:style w:type="table" w:styleId="Shaded"><w:name w:val="Shaded"/><w:tblPr>{style_shading}</w:tblPr></w:style>"#
);
warnings_with_style(body, &style)
}
/// The warnings of features and values of a document with the main document `body` and the
/// plain styles with `style` after them.
fn warnings_with_style(body: &str, style: &str) -> Vec<(Warning, u32)> {
let styles = format!("{}{style}", testing::PLAIN_STYLES);
let bytes = testing::docx(body)
.word_part("s1", "styles", "styles.xml", "styles", &styles)
.zip()
.unwrap();
warnings_of(&bytes, &Named(&["Times New Roman"]))
.into_iter()
.filter(|(warning, _)| {
matches!(
warning,
Warning::FeatureNotSupported { .. } | Warning::ValueNotSupported { .. }
)
})
.collect()
}
/// The warning of `feature` in `part`, once.
fn warned_once(part: &str, feature: crate::warnings::Feature) -> (Warning, u32) {
(
Warning::FeatureNotSupported {
part: Name::new(part),
feature,
},
1,
)
}
#[test]
fn warns_of_a_whole_table_shading_with_its_part_and_no_value_warning() {
use crate::warnings::Feature;
let table = |shading: &str, row_shading: &str| {
format!(
r#"<w:tbl><w:tblPr><w:tblStyle w:val="Shaded"/>{shading}</w:tblPr><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid><w:tr><w:tblPrEx>{row_shading}</w:tblPrEx><w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/></w:tcPr><w:p><w:r><w:t>{TEXT}</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p/>"#
)
};
let fill = r#"<w:shd w:val="clear" w:color="auto" w:fill="D9D9D9"/>"#;
let pattern = r#"<w:shd w:val="pct20" w:color="auto" w:fill="auto"/>"#;
let stripes = r#"<w:shd w:val="horzStripe" w:color="FF0000" w:fill="auto"/>"#;
let shaded = warned_once(DOCUMENT, Feature::TableShading);
assert_eq!(
feature_and_value_warnings(&table(fill, ""), ""),
vec![shaded.clone()]
);
assert_eq!(
feature_and_value_warnings(&table("", pattern), ""),
vec![shaded.clone()]
);
// A pattern of stripes, which a cell's shading draws as its fill alone with a warning of
// its value, warns of the table's shading only, once for the table and its part: the
// row's shading takes the place of the table's in the row.
assert_eq!(
feature_and_value_warnings(&table(stripes, stripes), ""),
vec![shaded.clone()]
);
assert_eq!(
feature_and_value_warnings(&table("", ""), fill),
vec![warned_once("word/styles.xml", Feature::TableShading)]
);
// No fill and no pattern give no warning.
for none in [
r#"<w:shd w:val="clear" w:color="auto" w:fill="auto"/>"#,
r#"<w:shd w:val="nil" w:fill="D9D9D9"/>"#,
r#"<w:shd w:val="clear"/>"#,
] {
assert_eq!(
feature_and_value_warnings(&table(none, none), none),
vec![],
"{none}"
);
}
}
#[test]
fn warns_of_a_turned_section_with_its_part_and_no_value_warning() {
use crate::warnings::Feature;
let section = |direction: &str| {
feature_and_value_warnings(
&format!(
r#"<w:p><w:r><w:t>{TEXT}</w:t></w:r></w:p><w:sectPr><w:textDirection w:val="{direction}"/></w:sectPr>"#
),
"",
)
};
for turned in ["tbRl", "btLr", "lrTbV", "rl"] {
assert_eq!(
section(turned),
vec![warned_once(DOCUMENT, Feature::SectionTextDirection)],
"{turned}"
);
}
// Upright, in either schema's name, and a value outside the type give no warning.
for upright in ["lrTb", "tb", "sideways"] {
assert_eq!(section(upright), vec![], "{upright}");
}
}
#[test]
fn reads_a_text_direction_outside_the_type_as_missing_with_a_warning() {
let invalid = |body: &str| {
let bytes = testing::docx(body).zip().unwrap();
warnings_of(&bytes, &Named(&["Times New Roman"]))
.into_iter()
.filter(|(warning, _)| matches!(warning, Warning::InvalidValue { .. }))
.collect::<Vec<_>>()
};
let direction = |value: &str| format!(r#"<w:textDirection w:val="{value}"/>"#);
let section = |value: &str| {
format!(
"<w:p><w:r><w:t>{TEXT}</w:t></w:r></w:p><w:sectPr>{}</w:sectPr>",
direction(value)
)
};
let paragraph = |value: &str| {
format!(
"<w:p><w:pPr>{}</w:pPr><w:r><w:t>{TEXT}</w:t></w:r></w:p>",
direction(value)
)
};
let warned = vec![(
Warning::InvalidValue {
part: Name::new(DOCUMENT),
element: Name::new("textDirection"),
place: ValuePlace::Attribute(Name::new("val")),
read_as: ReadAs::Missing,
},
1,
)];
for body in [section("sideways"), paragraph("sideways")] {
assert_eq!(invalid(&body), warned, "{body}");
}
for body in [section("btLr"), section("tb"), paragraph("lrTb")] {
assert_eq!(invalid(&body), vec![], "{body}");
}
}
/// The feature warnings of a document of two sections on one page, the first with
/// `first_section` and the second with `last_section` of the section properties, whose settings
/// hold `settings`, and whose body references a footnote and an endnote when `noted`.
fn note_position_warnings(
(first_section, last_section): (&str, &str),
settings: &str,
noted: bool,
) -> Vec<(Warning, u32)> {
let references = if noted {
r#"<w:r><w:footnoteReference w:id="1"/></w:r><w:r><w:endnoteReference w:id="1"/></w:r>"#
} else {
""
};
let body = format!(
r#"<w:p><w:pPr><w:sectPr>{first_section}<w:type w:val="continuous"/></w:sectPr></w:pPr><w:r><w:t>{TEXT}</w:t></w:r>{references}</w:p><w:p/><w:sectPr>{last_section}<w:type w:val="continuous"/></w:sectPr>"#
);
let note = |kind: &str| {
let note = if noted {
format!(r#"<w:{kind} w:id="1"><w:p><w:r><w:t>{TEXT}</w:t></w:r></w:p></w:{kind}>"#)
} else {
String::new()
};
format!(
r#"<w:{kind} w:type="separator" w:id="-1"><w:p><w:r><w:separator/></w:r></w:p></w:{kind}>{note}"#
)
};
let bytes = testing::docx(&body)
.word_part("s1", "settings", "settings.xml", "settings", settings)
.word_part(
"n1",
"footnotes",
"footnotes.xml",
"footnotes",
¬e("footnote"),
)
.word_part(
"e1",
"endnotes",
"endnotes.xml",
"endnotes",
¬e("endnote"),
)
.plain_styles()
.zip()
.unwrap();
warnings_of(&bytes, &Named(&["Times New Roman"]))
.into_iter()
.filter(|(warning, _)| matches!(warning, Warning::FeatureNotSupported { .. }))
.collect()
}
#[test]
fn warns_of_each_section_whose_footnotes_stand_off_the_page_bottom_in_a_noted_document() {
use crate::warnings::Feature;
let footnotes = |pos: &str| format!(r#"<w:footnotePr><w:pos w:val="{pos}"/></w:footnotePr>"#);
let warned = |count| {
let warning = Warning::FeatureNotSupported {
part: Name::new(DOCUMENT),
feature: Feature::FootnotePosition,
};
vec![(warning, count)]
};
// The settings' place holds in both sections, and a section's own place stands over it.
let beneath = footnotes("beneathText");
assert_eq!(note_position_warnings(("", ""), &beneath, true), warned(2));
let bottom = footnotes("pageBottom");
assert_eq!(
note_position_warnings((&bottom, ""), &beneath, true),
warned(1)
);
for pos in ["sectEnd", "docEnd"] {
assert_eq!(
note_position_warnings(("", &footnotes(pos)), "", true),
warned(1),
"{pos}"
);
}
// The bottom of the page, and any place in a document without footnotes, give no warning.
assert_eq!(note_position_warnings((&bottom, &bottom), "", true), vec![]);
assert_eq!(note_position_warnings(("", ""), &beneath, false), vec![]);
}
#[test]
fn warns_of_each_section_whose_endnotes_stand_at_its_end_in_a_noted_document() {
use crate::warnings::Feature;
let endnotes = |pos: &str| format!(r#"<w:endnotePr><w:pos w:val="{pos}"/></w:endnotePr>"#);
let section_end = endnotes("sectEnd");
let warning = Warning::FeatureNotSupported {
part: Name::new(DOCUMENT),
feature: Feature::EndnotePosition,
};
assert_eq!(
note_position_warnings(("", §ion_end), "", true),
vec![(warning.clone(), 1)]
);
assert_eq!(
note_position_warnings(("", ""), §ion_end, true),
vec![(warning.clone(), 2)]
);
// The last section's own place stands over the settings', and only the first section's
// place is the end of its section.
let document_end = endnotes("docEnd");
assert_eq!(
note_position_warnings(("", &document_end), §ion_end, true),
vec![(warning, 1)]
);
assert_eq!(
note_position_warnings(("", ""), §ion_end, false),
vec![]
);
}
#[test]
fn warns_once_for_each_paragraph_aligned_off_the_baseline_with_a_line_of_two_heights() {
use crate::warnings::Feature;
let run = |props: &str| {
format!(r#"<w:r><w:rPr>{props}</w:rPr><w:t xml:space="preserve">{TEXT} </w:t></w:r>"#)
};
let (small, large) = (run(r#"<w:sz w:val="16"/>"#), run(r#"<w:sz w:val="24"/>"#));
let two_sizes = format!("{small}{large}");
let paragraph = |props: &str, runs: &str| format!("<w:p><w:pPr>{props}</w:pPr>{runs}</w:p>");
let aligned = |value: &str| format!(r#"<w:textAlignment w:val="{value}"/>"#);
// A paragraph style `Centered` whose characters are aligned in the middle of the line.
let centered = format!(
r#"<w:style w:type="paragraph" w:styleId="Centered"><w:name w:val="Centered"/><w:pPr>{}</w:pPr></w:style>"#,
aligned("center")
);
let warnings = |body: &str| warnings_with_style(body, ¢ered);
for value in ["top", "center", "bottom"] {
assert_eq!(
warnings(¶graph(&aligned(value), &two_sizes)),
vec![warned_once(DOCUMENT, Feature::TextAlignment)],
"{value}"
);
}
// Once for each paragraph, also with two lines of two heights, and with the part of the
// style that sets it.
let two_lines = format!("{two_sizes}<w:r><w:br/></w:r>{two_sizes}");
let center = aligned("center");
assert_eq!(
warnings(
&[
paragraph(¢er, &two_lines),
paragraph(¢er, &two_sizes)
]
.concat()
),
vec![(warned_once(DOCUMENT, Feature::TextAlignment).0, 2)]
);
let styled = r#"<w:pStyle w:val="Centered"/>"#;
assert_eq!(
warnings(¶graph(styled, &two_sizes)),
vec![warned_once("word/styles.xml", Feature::TextAlignment)]
);
// An inline shape 36 pt high beside text of one size.
let shape = format!(
r#"<w:r><w:drawing><wp:inline xmlns:wp="{WP}" xmlns:a="{A}"><wp:extent cx="457200" cy="457200"/><a:graphic><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:prstGeom prst="rect"/></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>"#
);
assert_eq!(
warnings(¶graph(¢er, &format!("{small}{shape}"))),
vec![warned_once(DOCUMENT, Feature::TextAlignment)]
);
// No warning: the paragraph's own baseline over its style's middle, the values on the
// baseline, a line of one size, a raised run of the line's size, and a paragraph mark of
// another size.
let baseline = format!("{styled}{}", aligned("baseline"));
let raised = format!(
"{small}{}",
run(r#"<w:sz w:val="16"/><w:position w:val="6"/>"#)
);
let large_mark = format!(r#"{center}<w:rPr><w:sz w:val="40"/></w:rPr>"#);
for (props, runs) in [
(baseline.as_str(), two_sizes.as_str()),
(&aligned("auto"), &two_sizes),
(&aligned("baseline"), &two_sizes),
(¢er, &format!("{small}{small}")),
(¢er, &shape),
(¢er, &raised),
(&large_mark, &small),
(&large_mark, ""),
] {
assert_eq!(warnings(¶graph(props, runs)), vec![], "{props} {runs}");
}
}
#[test]
fn warns_once_for_each_paragraph_where_word_would_hang_a_mark() {
use crate::warnings::Feature;
// Each glyph of the test font is 5 pt wide at 10 pt, and the column is 52 pt wide, so a
// line holds ten characters. The default paragraph style gives the text a Chinese language.
let normal = r#"<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:rPr><w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman" w:eastAsia="Times New Roman" w:cs="Times New Roman"/><w:lang w:eastAsia="zh-CN"/></w:rPr></w:style>"#;
let page = r#"<w:sectPr><w:pgSz w:w="2880" w:h="2880"/><w:pgMar w:top="360" w:right="360" w:bottom="360" w:left="1480" w:header="0" w:footer="0" w:gutter="0"/></w:sectPr>"#;
let paragraph = |props: &str, text: &str| {
format!("<w:p><w:pPr>{props}</w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>")
};
let warnings = |body: &str| warnings_with_style(&format!("{body}{page}"), normal);
// Ten ideographs fill the line, and the comma after them may not start the next line: the
// tenth goes to the next line with it, where Word keeps it and hangs the comma. One
// warning for each such paragraph.
let full = "一二三四五六七八九十,";
assert_eq!(
warnings(¶graph("", full)),
vec![warned_once(DOCUMENT, Feature::HangingPunctuation)]
);
assert_eq!(
warnings(&[paragraph("", full), paragraph("", full)].concat()),
vec![(warned_once(DOCUMENT, Feature::HangingPunctuation).0, 2)]
);
// The warning names the part that sets `w:overflowPunct`: the main document's where no
// layer sets it, as above, else the layer's, here the default paragraph style's, and the
// paragraph's own over its style's.
let hanging_style = normal.replace("<w:rPr>", "<w:pPr><w:overflowPunct/></w:pPr><w:rPr>");
let in_style = |props: &str| {
warnings_with_style(&format!("{}{page}", paragraph(props, full)), &hanging_style)
};
assert_eq!(
in_style(""),
vec![warned_once("word/styles.xml", Feature::HangingPunctuation)]
);
assert_eq!(
in_style("<w:overflowPunct/>"),
vec![warned_once(DOCUMENT, Feature::HangingPunctuation)]
);
// No warning with `w:overflowPunct` off, and none where no mark of the list follows the
// full line: an ideograph, which may start the next line, or "…", which may not but does
// not hang.
let off = r#"<w:overflowPunct w:val="0"/>"#;
for (props, text) in [
(off, full),
("", "一二三四五六七八九十一"),
("", "一二三四五六七八九十…"),
] {
assert_eq!(warnings(¶graph(props, text)), vec![], "{props} {text}");
}
}
#[test]
fn warns_once_for_each_turned_paragraph_in_a_frame_with_the_part_that_turns_it() {
use crate::warnings::Feature;
let frame = r#"<w:framePr w:w="2000" w:h="1000" w:hAnchor="page" w:vAnchor="page" w:x="1440" w:y="1440"/>"#;
let turned = |value: &str| format!(r#"<w:textDirection w:val="{value}"/>"#);
let paragraph =
|props: &str| format!("<w:p><w:pPr>{props}</w:pPr><w:r><w:t>{TEXT}</w:t></w:r></w:p>");
// A paragraph style `Turned` whose text runs from the bottom up.
let style = format!(
r#"<w:style w:type="paragraph" w:styleId="Turned"><w:name w:val="Turned"/><w:pPr>{}</w:pPr></w:style>"#,
turned("btLr")
);
let warnings = |body: &str| warnings_with_style(body, &style);
let warned = warned_once(DOCUMENT, Feature::ParagraphTextDirection);
for value in ["btLr", "tbRl", "tbRlV", "lrTbV", "lr", "rl"] {
assert_eq!(
warnings(¶graph(&format!("{frame}{}", turned(value)))),
vec![warned.clone()],
"{value}"
);
}
// Once for each paragraph of a frame of two paragraphs, and with the part of the style
// that turns it.
let in_frame = paragraph(&format!("{frame}{}", turned("btLr")));
assert_eq!(
warnings(&[in_frame.as_str(), &in_frame, "<w:p/>"].concat()),
vec![(warned.0, 2)]
);
assert_eq!(
warnings(¶graph(&format!(r#"<w:pStyle w:val="Turned"/>{frame}"#))),
vec![warned_once(
"word/styles.xml",
Feature::ParagraphTextDirection
)]
);
// No warning outside a frame, where Word lays the paragraph out upright too, in a
// `w:framePr` that makes no frame, for an upright direction, its own upright direction
// over its style's, or a value outside the type.
let plain = r#"<w:framePr w:w="0"/>"#;
for props in [
turned("btLr"),
r#"<w:pStyle w:val="Turned"/>"#.to_string(),
format!("{plain}{}", turned("btLr")),
format!("{frame}{}", turned("lrTb")),
format!("{frame}{}", turned("tb")),
format!(r#"<w:pStyle w:val="Turned"/>{frame}{}"#, turned("lrTb")),
format!("{frame}{}", turned("sideways")),
] {
assert_eq!(warnings(¶graph(&props)), vec![], "{props}");
}
}
#[test]
fn warns_once_for_each_paragraph_of_a_header_or_footer_that_a_page_shows() {
// A warning of a header's or a footer's paragraph counts once, whatever the number of
// pages and of measures, and none comes from a header or footer that no page shows.
use crate::warnings::Feature;
let turned = format!(
r#"<w:p><w:pPr><w:framePr w:w="2000" w:h="400" w:hAnchor="page" w:vAnchor="page" w:x="1440" w:y="200"/><w:textDirection w:val="btLr"/></w:pPr><w:r><w:t>{TEXT}</w:t></w:r></w:p>"#
);
let page = format!("<w:p><w:r><w:t>{TEXT}</w:t></w:r></w:p>");
let six_pages = vec![page; 6].join(r#"<w:p><w:r><w:br w:type="page"/></w:r></w:p>"#);
let reference = |side: &str, kind: &str, id: &str| {
format!(r#"<w:{side}Reference w:type="{kind}" r:id="{id}"/>"#)
};
// The pages and the warnings of the turned paragraph with the header and footer
// `references` and the `settings`.
let laid_out = |references: &str, settings: &str| {
let body = format!("{six_pages}<w:sectPr>{references}</w:sectPr>");
let bytes = testing::docx(&body)
.word_part("h1", "header", "header1.xml", "hdr", &turned)
.word_part("f1", "footer", "footer1.xml", "ftr", &turned)
.word_part("s1", "settings", "settings.xml", "settings", settings)
.zip()
.unwrap();
let package = Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
let fonts = Named(&["Times New Roman"]);
let laid_out = crate::layout(
&package,
(&fonts, &crate::ArtPictures::new()),
&Options::base(),
)
.unwrap();
let warnings: Vec<_> = laid_out
.warnings
.into_iter()
.filter(|(warning, _)| matches!(warning, Warning::FeatureNotSupported { .. }))
.collect();
(laid_out.value.pages().len(), warnings)
};
let header = warned_once("word/header1.xml", Feature::ParagraphTextDirection);
let footer = warned_once("word/footer1.xml", Feature::ParagraphTextDirection);
// One paragraph of a header on six pages, and of a footer: one warning each.
let default = reference("header", "default", "h1") + &reference("footer", "default", "f1");
assert_eq!(
laid_out(&default, ""),
(6, vec![header.clone(), footer.clone()])
);
// An even footer and a first page header give none where no page shows them, and one
// each with even and odd headers and a title page.
let other = reference("footer", "even", "f1") + &reference("header", "first", "h1");
assert_eq!(laid_out(&other, ""), (6, vec![]));
let shown = format!("{other}<w:titlePg/>");
assert_eq!(
laid_out(&shown, "<w:evenAndOddHeaders/>").1,
vec![header, footer]
);
}
#[test]
fn warns_once_for_each_turned_text_box_with_its_part() {
use crate::warnings::Feature;
let content = format!("<w:txbxContent><w:p><w:r><w:t>{TEXT}</w:t></w:r></w:p></w:txbxContent>");
let shape = |text_box: &str, body: &str| {
in_run(&format!(
r#"<w:drawing><wp:anchor xmlns:wp="{WP}" xmlns:a="{A}"><wp:extent cx="914400" cy="914400"/><wp:wrapNone/><a:graphic><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:prstGeom prst="rect"/></wps:spPr>{text_box}{body}</wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
))
};
let text_box = format!("<wps:txbx>{content}</wps:txbx>");
let vertical = |value: &str| format!(r#"<wps:bodyPr vert="{value}"/>"#);
let vml = |style: &str| {
pict(&format!(
r#"<v:shape style="position:absolute;width:72pt;height:72pt"><v:textbox style="{style}">{content}</v:textbox></v:shape>"#
))
};
let warnings = |body: &str| feature_and_value_warnings(body, "");
let warned = warned_once(DOCUMENT, Feature::TurnedTextBox);
for value in ["wordArtVert", "mongolianVert", "wordArtVertRtl"] {
assert_eq!(
warnings(&shape(&text_box, &vertical(value))),
vec![warned.clone()],
"{value}"
);
}
for flow in ["layout-flow:vertical", "LAYOUT-FLOW: vertical-ideographic"] {
assert_eq!(warnings(&vml(flow)), vec![warned.clone()], "{flow}");
}
// Once for each box.
let turned = shape(&text_box, &vertical("wordArtVert"));
assert_eq!(
warnings(&[turned.as_str(), &turned, &vml("layout-flow:vertical")].concat()),
vec![(warned.0, 3)]
);
// No warning for text across the box, text that runs down or up it, which F-Office turns,
// East Asian text that runs down it, a shape without a text box, and a value outside the
// type.
for body in [
shape(&text_box, &vertical("horz")),
shape(&text_box, &vertical("vert")),
shape(&text_box, &vertical("eaVert")),
shape(&text_box, &vertical("vert270")),
shape(&text_box, "<wps:bodyPr/>"),
shape(&text_box, ""),
shape("", &vertical("vert")),
shape(&text_box, &vertical("sideways")),
vml("layout-flow:horizontal"),
vml("v-text-anchor:middle"),
vml(""),
] {
assert_eq!(warnings(&body), vec![], "{body}");
}
}
#[test]
fn warns_once_for_a_text_box_whose_shape_and_body_both_turn_its_text() {
use crate::warnings::Feature;
let content = format!("<w:txbxContent><w:p><w:r><w:t>{TEXT}</w:t></w:r></w:p></w:txbxContent>");
let shape = |xfrm: &str, body: &str| {
in_run(&format!(
r#"<w:drawing><wp:anchor xmlns:wp="{WP}" xmlns:a="{A}"><wp:extent cx="914400" cy="457200"/><wp:wrapNone/><a:graphic><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:xfrm {xfrm}/><a:prstGeom prst="rect"/></wps:spPr><wps:txbx>{content}</wps:txbx><wps:bodyPr {body}/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
))
};
let warnings = |body: &str| feature_and_value_warnings(body, "");
let warned = warned_once(DOCUMENT, Feature::TurnedTextBox);
// Once for a box whose shape and body both turn its text.
for rot in ["5400000", "10800000", "-5400000", "27000000"] {
let both = shape(&format!(r#"rot="{rot}""#), r#"vert="vert""#);
assert_eq!(warnings(&both), vec![warned.clone()], "{rot}");
}
// A non-quarter-turn shape with a text box warns of a turned text box unless `upright` is set.
assert_eq!(
warnings(&shape(r#"rot="2700000""#, "")),
vec![warned.clone()]
);
// No warning for a box whose text turns with its shape, which F-Office turns, a box that
// keeps its text upright, or a box turned by whole turns.
for (xfrm, body) in [
(r#"rot="5400000""#, ""),
(r#"rot="-5400000""#, ""),
(r#"rot="27000000""#, ""),
(r#"rot="5400000""#, r#"upright="1""#),
(r#"rot="10800000""#, r#"upright="true""#),
(r#"rot="21600000""#, ""),
(r#"rot="2700000""#, r#"upright="1""#),
("", ""),
] {
assert_eq!(warnings(&shape(xfrm, body)), vec![], "{xfrm} {body}");
}
}
/// A paragraph of [`TEXT`] with the paragraph properties `props`.
fn paragraph_with(props: &str) -> String {
format!("<w:p><w:pPr>{props}</w:pPr><w:r><w:t>{TEXT}</w:t></w:r></w:p>")
}
#[test]
fn warns_once_for_each_paragraph_with_mirrored_indents_that_differ() {
use crate::warnings::Feature;
let style = r#"<w:style w:type="paragraph" w:styleId="Mirrored"><w:name w:val="Mirrored"/><w:pPr><w:mirrorIndents/></w:pPr></w:style>"#;
let warnings = |props: &str| warnings_with_style(¶graph_with(props), style);
// Each warning names the part that sets the mirror: the paragraph's own, or its style's.
for (props, part) in [
(r#"<w:mirrorIndents/><w:ind w:left="720"/>"#, DOCUMENT),
(
r#"<w:mirrorIndents w:val="1"/><w:ind w:start="720" w:end="360"/>"#,
DOCUMENT,
),
(
r#"<w:pStyle w:val="Mirrored"/><w:ind w:right="720"/>"#,
"word/styles.xml",
),
] {
let warned = warned_once(part, Feature::MirrorIndents);
assert_eq!(warnings(props), vec![warned], "{props}");
}
// None where the indents are equal, which mirroring does not change, and none without the
// mirror.
for props in [
"<w:mirrorIndents/>",
r#"<w:mirrorIndents/><w:ind w:left="720" w:right="720"/>"#,
r#"<w:mirrorIndents w:val="0"/><w:ind w:left="720"/>"#,
r#"<w:pStyle w:val="Mirrored"/><w:mirrorIndents w:val="0"/><w:ind w:left="720"/>"#,
r#"<w:ind w:left="720"/>"#,
] {
assert_eq!(warnings(props), vec![], "{props}");
}
}
#[test]
fn warns_once_for_each_paragraph_on_a_grid_of_characters_whose_right_indent_moves_to_it() {
use crate::warnings::Feature;
let section = |grid: &str| format!("<w:sectPr>{grid}</w:sectPr>");
let chars = r#"<w:docGrid w:type="linesAndChars" w:linePitch="360" w:charSpace="0"/>"#;
let warnings = |body: &str| feature_and_value_warnings(body, "");
let two = [paragraph_with(""), paragraph_with("<w:adjustRightInd/>")].concat();
assert_eq!(
warnings(&format!("{two}{}", section(chars))),
vec![(warned_once(DOCUMENT, Feature::GridRightIndent).0, 2)]
);
// None where the right indent stays, off the grid, on a grid of lines, or without a grid.
let lines = r#"<w:docGrid w:type="lines" w:linePitch="360"/>"#;
for body in [
format!(
"{}{}",
paragraph_with(r#"<w:adjustRightInd w:val="0"/>"#),
section(chars)
),
format!(
"{}{}",
paragraph_with(r#"<w:snapToGrid w:val="0"/>"#),
section(chars)
),
format!("{two}{}", section(lines)),
format!("{two}{}", section("")),
] {
assert_eq!(warnings(&body), vec![], "{body}");
}
}
#[test]
fn warns_once_for_each_frame_that_overlaps_an_earlier_one_where_one_must_not() {
use crate::warnings::Feature;
let frame = |x: u32, more: &str| {
paragraph_with(&format!(
r#"<w:framePr w:w="2000" w:h="1000" w:hRule="exact" w:hAnchor="page" w:vAnchor="page" w:x="{x}" w:y="1440"/>{more}"#
))
};
let apart = "<w:p/>";
let warnings = |body: &str| feature_and_value_warnings(body, "");
let warned = warned_once(DOCUMENT, Feature::FrameOverlap);
let keeps = "<w:suppressOverlap/>";
for body in [
[frame(1440, keeps), apart.into(), frame(2440, "")].concat(),
[frame(1440, ""), apart.into(), frame(2440, keeps)].concat(),
] {
assert_eq!(warnings(&body), vec![warned.clone()], "{body}");
}
// None for frames that may overlap, for frames apart, and for one frame of two
// paragraphs.
for body in [
[frame(1440, ""), apart.into(), frame(2440, "")].concat(),
[frame(1440, keeps), apart.into(), frame(4440, keeps)].concat(),
[frame(1440, keeps), frame(1440, keeps)].concat(),
] {
assert_eq!(warnings(&body), vec![], "{body}");
}
}
#[test]
fn warns_once_for_each_paragraph_of_a_text_box_in_its_tight_wrap() {
use crate::warnings::Feature;
let text_box = |props: &str| {
in_run(&format!(
r#"<w:drawing><wp:anchor xmlns:wp="{WP}" xmlns:a="{A}"><wp:extent cx="914400" cy="914400"/><wp:wrapTight wrapText="bothSides"/><a:graphic><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:prstGeom prst="rect"/></wps:spPr><wps:txbx><w:txbxContent>{}</w:txbxContent></wps:txbx><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#,
paragraph_with(props)
))
};
let warnings = |body: &str| {
feature_and_value_warnings(body, "")
.into_iter()
.filter(|(warning, _)| warning.kind() == Feature::TextBoxTightWrap.kind())
.collect::<Vec<_>>()
};
for value in [
"allLines",
"firstAndLastLine",
"firstLineOnly",
"lastLineOnly",
] {
let props = format!(r#"<w:textboxTightWrap w:val="{value}"/>"#);
assert_eq!(
warnings(&text_box(&props)),
vec![warned_once(DOCUMENT, Feature::TextBoxTightWrap)],
"{value}"
);
}
// None for `none`, and none outside a text box, where it does nothing.
assert_eq!(
warnings(&text_box(r#"<w:textboxTightWrap w:val="none"/>"#)),
vec![]
);
assert_eq!(
warnings(¶graph_with(r#"<w:textboxTightWrap w:val="allLines"/>"#)),
vec![]
);
}
#[test]
fn warns_once_for_each_row_whose_own_alignment_or_cell_spacing_would_move_it() {
use crate::warnings::Feature;
// A table of one column of `width` twips with the table properties `table` and a row for
// each of the row properties `rows`.
let sized = |width: u32, table: &str, rows: &[&str]| {
let cell = format!(
r#"<w:tc><w:tcPr><w:tcW w:w="{width}" w:type="dxa"/></w:tcPr><w:p/></w:tc></w:tr>"#
);
let rows = rows
.iter()
.map(|row| ["<w:tr>", row, &cell].concat())
.collect::<String>();
format!(
r#"<w:tbl><w:tblPr><w:tblW w:w="{width}" w:type="dxa"/>{table}</w:tblPr><w:tblGrid><w:gridCol w:w="{width}"/></w:tblGrid>{rows}</w:tbl><w:p/>"#
)
};
// A table narrower than the column, and one wider than the page.
let table = |table: &str, rows: &[&str]| sized(2000, table, rows);
let wide = |rows: &[&str]| sized(15000, "", rows);
let narrow = "";
let centered = r#"<w:trPr><w:jc w:val="center"/></w:trPr>"#;
let spaced = r#"<w:trPr><w:tblCellSpacing w:w="15" w:type="dxa"/></w:trPr>"#;
let warnings = |body: &str| feature_and_value_warnings(body, "");
let aligned = warned_once(DOCUMENT, Feature::RowAlignment);
let spacing = warned_once(DOCUMENT, Feature::RowCellSpacing);
assert_eq!(
warnings(&table(narrow, &[centered, "", centered])),
vec![(aligned.0, 2)]
);
assert_eq!(warnings(&wide(&[spaced, ""])), vec![spacing.clone()]);
assert_eq!(
warnings(&table(
narrow,
&[r#"<w:tblPrEx><w:tblCellSpacing w:w="20" w:type="dxa"/></w:tblPrEx>"#]
)),
vec![spacing]
);
// None for an alignment that cannot move a row as wide as its column, for the table's own
// alignment and spacing, for no spacing below zero in a table without one, and for the
// alignment of a row's exceptions, which does not move the row.
let table_spaced = r#"<w:tblCellSpacing w:w="15" w:type="dxa"/>"#;
for body in [
wide(&[centered]),
table(narrow, &[r#"<w:tblPrEx><w:jc w:val="right"/></w:tblPrEx>"#]),
table(&format!(r#"{narrow}<w:jc w:val="center"/>"#), &[centered]),
table(&format!("{narrow}{table_spaced}"), &[spaced]),
table(
narrow,
&[r#"<w:trPr><w:tblCellSpacing w:w="-15" w:type="dxa"/></w:trPr>"#],
),
] {
assert_eq!(warnings(&body), vec![], "{body}");
}
}
#[test]
fn warns_once_for_each_paragraph_of_an_html_div_with_margins_or_borders() {
use crate::warnings::Feature;
let web = concat!(
r#"<w:divs><w:div w:id="1"><w:marLeft w:val="0"/><w:divsChild>"#,
r#"<w:div w:id="2"><w:marLeft w:val="480"/></w:div></w:divsChild></w:div>"#,
r#"<w:div w:id="3"><w:divBdr><w:top w:val="single" w:sz="4" w:space="0" w:color="auto"/></w:divBdr></w:div>"#,
r#"</w:divs>"#
);
let warnings = |body: &str, web: Option<&str>| {
let mut builder = testing::docx(body).plain_styles();
if let Some(web) = web {
builder = builder.word_part("w1", "webSettings", "webSettings.xml", "webSettings", web);
}
warnings_of(&builder.zip().unwrap(), &Named(&["Times New Roman"]))
.into_iter()
.filter(|(warning, _)| matches!(warning, Warning::FeatureNotSupported { .. }))
.collect::<Vec<_>>()
};
let div = |id: &str| paragraph_with(&format!(r#"<w:divId w:val="{id}"/>"#));
assert_eq!(
warnings(&[div("2"), div("3"), div("2")].concat(), Some(web)),
vec![(warned_once(DOCUMENT, Feature::HtmlDiv).0, 3)]
);
// None for a div of no margin and no line, for a div that the part lacks, and for a
// document without a web settings part.
assert_eq!(warnings(&[div("1"), div("9")].concat(), Some(web)), vec![]);
assert_eq!(warnings(&div("2"), None), vec![]);
}
#[test]
fn reads_the_web_settings_part_only_for_a_paragraph_that_names_a_div() {
// A document that was a web page fills the part with its divs, so the layout reads it on
// the first question about a div (`web_settings::HtmlDivs`): a part that is not XML warns
// only when a paragraph names a div.
let skipped = |body: &str| {
let bytes = testing::docx(body)
.plain_styles()
.relationship(DOCUMENT, "w1", "webSettings", "webSettings.xml")
.part("word/webSettings.xml", "<w:webSettings")
.zip()
.unwrap();
warnings_of(&bytes, &Named(&["Times New Roman"]))
.into_iter()
.filter(|(warning, _)| matches!(warning, Warning::PartSkipped { .. }))
.collect::<Vec<_>>()
};
let part_skipped = Warning::PartSkipped {
part: Name::new("word/webSettings.xml"),
reason: Reason::NotXml,
};
let div = paragraph_with(r#"<w:divId w:val="2"/>"#);
assert_eq!(
skipped(&[div.clone(), div].concat()),
vec![(part_skipped, 1)]
);
assert_eq!(skipped(¶graph_with("")), vec![]);
}
/// The place of `feature` in `Feature::ALL`. The match has no wildcard, so a new feature does not
/// compile until it is named here with the next place, which `Feature::ALL` must hold.
const fn feature_place_in_all(feature: crate::warnings::Feature) -> usize {
use crate::warnings::Feature;
match feature {
Feature::VmlGeometry => 0,
Feature::VmlRotation => 1,
Feature::VmlPictureColors => 2,
Feature::VmlPictureTextBox => 3,
Feature::TextFill => 4,
Feature::TextEffect => 5,
Feature::TextOutlineFill => 6,
Feature::MathStructure => 7,
Feature::DoubleStrike => 8,
Feature::TextBorder => 9,
Feature::FitText => 10,
Feature::EastAsianLayout => 11,
Feature::AutoHyphenation => 12,
Feature::TableShading => 13,
Feature::SectionTextDirection => 14,
Feature::FootnotePosition => 15,
Feature::EndnotePosition => 16,
Feature::TextAlignment => 17,
Feature::HangingPunctuation => 18,
Feature::ParagraphTextDirection => 19,
Feature::TurnedTextBox => 20,
Feature::MirrorIndents => 21,
Feature::GridRightIndent => 22,
Feature::FrameOverlap => 23,
Feature::TextBoxTightWrap => 24,
Feature::RowAlignment => 25,
Feature::RowCellSpacing => 26,
Feature::HtmlDiv => 27,
Feature::GroupTransform(_) => 28,
Feature::SymbolExtension => 29,
Feature::AlternateChoice => 30,
Feature::BidirectionalEmbedding => 31,
Feature::Ruby => 32,
Feature::PageNumberElement => 33,
Feature::DateBlock => 34,
Feature::BetweenBorder => 35,
Feature::BarBorder => 36,
Feature::MathElement => 37,
Feature::ChartLabels => 38,
Feature::PictureBullet => 39,
Feature::NoteMarkInBox => 40,
Feature::DataLabels => 41,
}
}
#[test]
fn lists_each_feature_once_in_its_place() {
for (index, feature) in crate::warnings::Feature::ALL.into_iter().enumerate() {
assert_eq!(feature_place_in_all(feature), index, "{feature:?}");
}
}
#[test]
fn gives_each_feature_a_kind_of_its_own_and_says_what_is_drawn_in_its_place() {
use crate::warnings::Feature;
let mut kinds = Vec::new();
for feature in Feature::ALL {
let warning = Warning::FeatureNotSupported {
part: Name::new(DOCUMENT),
feature,
};
let kind = warning.kind();
assert_eq!(kind, feature.kind());
assert!(
kind.ends_with("-not-supported") && !kinds.contains(&kind),
"{kind}"
);
kinds.push(kind);
let text = feature.to_string();
assert!(text.contains(" is not supported"), "{text}");
assert_eq!(warning.to_string(), format!("in part {DOCUMENT}, {text}"));
}
}
#[test]
fn says_what_a_group_transform_does_not_draw_under_one_kind() {
use crate::warnings::{Feature, GroupTransform};
for transform in GroupTransform::ALL {
let feature = Feature::GroupTransform(transform);
assert_eq!(feature.kind(), "group-transform-not-supported");
let text = feature.to_string();
let (start, end) = match transform {
GroupTransform::Turn => ("a turn ", " drawn upright"),
GroupTransform::Flip => ("a flip ", " drawn unflipped"),
GroupTransform::TurnAndFlip => ("a turn and flip ", " upright and unflipped"),
};
assert!(text.starts_with(start) && text.ends_with(end), "{text}");
assert!(text.contains(" is not supported"), "{text}");
}
}
/// A rectangle of 100 by 100 in its group's coordinates, as a part of a drawing group.
fn group_shape() -> String {
format!(
r#"<wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="100" cy="100"/></a:xfrm><a:prstGeom prst="rect"/></wps:spPr><wps:bodyPr/></wps:wsp>"#
)
}
/// An inner group (`wpg:grpSp`) of one rectangle, whose `a:xfrm` has the attributes `xfrm`.
fn inner_group(xfrm: &str) -> String {
let shape = group_shape();
format!(
r#"<wpg:grpSp><wpg:grpSpPr><a:xfrm {xfrm}><a:off x="0" y="0"/><a:ext cx="100" cy="100"/><a:chOff x="0" y="0"/><a:chExt cx="100" cy="100"/></a:xfrm></wpg:grpSpPr>{shape}</wpg:grpSp>"#
)
}
/// A paragraph with a floating drawing group of `parts`, whose `a:xfrm` has the attributes
/// `xfrm`.
fn floating_group(xfrm: &str, parts: &str) -> String {
in_run(&format!(
r#"<w:drawing><wp:anchor xmlns:wp="{WP}" xmlns:a="{A}"><wp:extent cx="914400" cy="914400"/><wp:wrapNone/><a:graphic><a:graphicData><wpg:wgp xmlns:wpg="{WPG}"><wpg:grpSpPr><a:xfrm {xfrm}><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/><a:chOff x="0" y="0"/><a:chExt cx="100" cy="100"/></a:xfrm></wpg:grpSpPr>{parts}</wpg:wgp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
))
}
/// The warning of the group transform `transform` in the main document, `count` times.
fn group_transform_warned(
transform: crate::warnings::GroupTransform,
count: u32,
) -> (Warning, u32) {
let (warning, _) = warned_once(
DOCUMENT,
crate::warnings::Feature::GroupTransform(transform),
);
(warning, count)
}
#[test]
fn warns_once_for_each_group_with_a_turn_or_flip_of_its_own() {
use crate::warnings::GroupTransform;
let shape = group_shape();
let warnings = |xfrm: &str| feature_and_value_warnings(&floating_group(xfrm, &shape), "");
// Non-quarter-turn group rotations warn once; flips and whole quarter turns are drawn.
for xfrm in [r#"rot="2700000""#, r#"rot="1200000" flipH="1""#] {
assert_eq!(
warnings(xfrm),
vec![group_transform_warned(GroupTransform::Turn, 1)],
"{xfrm}"
);
}
for xfrm in [
r#"rot="0""#,
r#"rot="5400000""#,
r#"rot="-10800000""#,
r#"rot="16200000" flipH="1""#,
r#"rot="21600000""#,
r#"flipH="1""#,
r#"flipV="true""#,
r#"flipH="0" flipV="false""#,
"",
] {
assert_eq!(warnings(xfrm), vec![], "{xfrm}");
}
}
#[test]
fn warns_of_the_transform_of_an_inner_group_and_counts_a_turn_that_does_not_read_as_none() {
use crate::warnings::GroupTransform;
let slanted = r#"rot="2700000""#;
let warnings =
|xfrm: &str| feature_and_value_warnings(&floating_group(xfrm, &inner_group(slanted)), "");
// Each group warns of its own non-quarter turn once; a flip on the outer group does not warn.
assert_eq!(
warnings(""),
vec![group_transform_warned(GroupTransform::Turn, 1)]
);
assert_eq!(
warnings(slanted),
vec![group_transform_warned(GroupTransform::Turn, 2)]
);
assert_eq!(
warnings(r#"flipV="1""#),
vec![group_transform_warned(GroupTransform::Turn, 1)]
);
// A turn that does not read counts as missing, with its own warning and none of the
// group's transform.
let unread = testing::docx(&floating_group(r#"rot="ninety""#, &group_shape()))
.zip()
.unwrap();
let kinds: Vec<&str> = warnings_of(&unread, &Named(&["Times New Roman"]))
.iter()
.map(|(warning, _)| warning.kind())
.filter(|kind| kind.starts_with("invalid-") || kind.starts_with("group-"))
.collect();
assert_eq!(kinds, vec!["invalid-value"]);
}
#[test]
fn warns_of_each_length_in_emu_that_does_not_read_with_its_part() {
let body = format!(
r#"<w:p><w:r><w:drawing><wp:anchor distL="0.5in"><wp:positionH relativeFrom="column"><wp:posOffset> 914400 </wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV><wp:extent cx="1in" cy="914400"/><wp:wrapNone/><a:graphic><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:prstGeom prst="rect"/><a:ln w="9525.5"><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:ln></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r><w:r><w:t>{TEXT}</w:t></w:r></w:p>"#
);
let bytes = package(&body, "", &[], &[]);
let main = Name::new("word/document.xml");
assert_eq!(
warnings_of(&bytes, &Named(&["Times New Roman"])),
[
(
Warning::InvalidValue {
part: main.clone(),
element: Name::new("posOffset"),
place: ValuePlace::Text,
read_as: ReadAs::Missing,
},
1
),
(
Warning::DrawingMl {
part: main,
warning: DrawingMlWarning::InvalidValue {
element: Name::new("ln"),
attribute: Name::new("w"),
},
},
1
),
]
);
}
/// The number of pages and the warnings of features of laying out `bytes`, each with its count.
fn pages_and_feature_warnings(bytes: &[u8]) -> (usize, Vec<(Warning, u32)>) {
let package = Package::open(bytes, &f_office_opc::Limits::default()).unwrap();
let fonts = Named(&["Times New Roman"]);
let laid_out = crate::layout(
&package,
(&fonts, &crate::ArtPictures::new()),
&Options::base(),
)
.unwrap();
let warnings = laid_out
.warnings
.into_iter()
.filter(|(warning, _)| matches!(warning, Warning::FeatureNotSupported { .. }))
.collect();
(laid_out.value.pages().len(), warnings)
}
#[test]
fn warns_once_for_each_paragraph_of_a_footnote_or_a_separator_whatever_the_number_of_its_layouts() {
// A footnote's warnings count once, as a header's do, though the layout lays it out to
// measure it, to find its breaks and to place it, whole or in parts; and a separator's, laid
// out on each page with footnotes and for each question of its height.
use crate::warnings::Feature;
let mirrored = r#"<w:pPr><w:mirrorIndents/><w:ind w:left="720"/></w:pPr>"#;
let plain = format!("<w:p><w:r><w:t>{TEXT}</w:t></w:r></w:p>");
let mirrored_paragraph = format!("<w:p>{mirrored}<w:r><w:t>{TEXT}</w:t></w:r></w:p>");
let note = |id: usize, paragraphs: &str| {
format!(r#"<w:footnote w:id="{id}">{paragraphs}</w:footnote>"#)
};
let separators = |props: &str| {
format!(
r#"<w:footnote w:type="separator" w:id="-1"><w:p>{props}<w:r><w:separator/></w:r></w:p></w:footnote><w:footnote w:type="continuationSeparator" w:id="0"><w:p><w:r><w:continuationSeparator/></w:r></w:p></w:footnote>"#
)
};
// `count` pages, each with a paragraph that refers to the footnote of its number.
let pages = |count: usize| {
(1..=count)
.map(|id| {
format!(
r#"<w:p><w:r><w:t>{TEXT}</w:t></w:r><w:r><w:footnoteReference w:id="{id}"/></w:r></w:p>"#
)
})
.collect::<Vec<_>>()
.join(r#"<w:p><w:r><w:br w:type="page"/></w:r></w:p>"#)
};
let laid_out = |count: usize, notes: &str| {
// The settings list the special footnotes, so the separators are those of the part.
let settings =
r#"<w:footnotePr><w:footnote w:id="-1"/><w:footnote w:id="0"/></w:footnotePr>"#;
let bytes = testing::docx(&(pages(count) + &plain.repeat(80)))
.word_part("n1", "footnotes", "footnotes.xml", "footnotes", notes)
.word_part("s1", "settings", "settings.xml", "settings", settings)
.plain_styles()
.zip()
.unwrap();
pages_and_feature_warnings(&bytes)
};
// The footnotes part sets the mirror of the notes' and the separators' paragraphs.
let warned = warned_once("word/footnotes.xml", Feature::MirrorIndents);
// A footnote with a mirrored paragraph, and one so long that it goes on over pages.
let short = note(1, &mirrored_paragraph);
let (pages_of_short, warnings) = laid_out(1, &(separators("") + &short));
assert_eq!(warnings, vec![warned.clone()]);
let long = note(1, &(mirrored_paragraph.clone() + &plain.repeat(120)));
let (pages_of_long, warnings) = laid_out(1, &(separators("") + &long));
assert!(pages_of_long > pages_of_short, "{pages_of_long}");
assert_eq!(warnings, vec![warned.clone()]);
// A separator with a mirrored paragraph, on the pages of three footnotes.
let notes: String = (1..=3).map(|id| note(id, &plain)).collect();
let (pages, warnings) = laid_out(3, &(separators(mirrored) + ¬es));
assert!(pages >= 3, "{pages}");
assert_eq!(warnings, vec![warned]);
}
#[test]
fn warns_once_for_each_paragraph_and_row_that_a_rewind_lays_out_again() {
// Balanced columns, kept rows, floating and nested tables lay their blocks out again
// after a rewind (`Mark`), and a row lays out its cells again where it moves to the next
// column or page, where it does not split after all, and where a cell moves for its
// vertical alignment (`PassOutput::start_trial`). The layout that the layout takes back
// takes its warnings with it.
use crate::warnings::Feature;
let mirrored = paragraph_with(r#"<w:mirrorIndents/><w:ind w:left="720"/>"#);
let row = |props: &str, cell: &str| {
format!(
r#"<w:tr><w:trPr>{props}<w:jc w:val="center"/></w:trPr><w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/>{cell}</w:tcPr>{mirrored}</w:tc></w:tr>"#
)
};
let table = format!(
r#"<w:tbl><w:tblPr><w:tblW w:w="2000" w:type="dxa"/></w:tblPr><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid>{}{}{}</w:tbl>"#,
row("", ""),
row("<w:cantSplit/>", ""),
row(
r#"<w:trHeight w:val="1200"/>"#,
r#"<w:vAlign w:val="center"/>"#
)
);
let blocks = format!("{mirrored}{table}{mirrored}");
let warnings = |body: &str| {
let bytes = testing::docx(body).plain_styles().zip().unwrap();
pages_and_feature_warnings(&bytes).1
};
let warned = |feature, count| (warned_once(DOCUMENT, feature).0, count);
let expected = vec![
warned(Feature::MirrorIndents, 5),
warned(Feature::RowAlignment, 3),
];
// In one column, and in two columns that a continuous section balances.
assert_eq!(warnings(&blocks), expected);
let balanced = format!(
r#"{blocks}<w:p><w:pPr><w:sectPr><w:cols w:num="2"/></w:sectPr></w:pPr></w:p><w:p/><w:sectPr><w:type w:val="continuous"/></w:sectPr>"#
);
assert_eq!(warnings(&balanced), expected);
}
#[test]
fn warns_once_for_each_paragraph_of_a_frame_or_a_text_box_that_the_layout_measures_first() {
// A frame whose place comes from its height, a frame that stands in the flow below a line
// of its page and a text box whose text stands in the middle of the box are laid out to
// measure them, and again where they stand (`Layout::layout_without_warnings`).
use crate::warnings::Feature;
let mirrored = r#"<w:mirrorIndents/><w:ind w:left="720"/>"#;
let text_box = in_run(&format!(
r#"<w:drawing><wp:anchor xmlns:wp="{WP}" xmlns:a="{A}"><wp:extent cx="914400" cy="914400"/><wp:wrapSquare wrapText="bothSides"/><a:graphic><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:prstGeom prst="rect"/></wps:spPr><wps:txbx><w:txbxContent>{}</w:txbxContent></wps:txbx><wps:bodyPr anchor="ctr"/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#,
paragraph_with(mirrored)
));
let framed = |frame: &str| paragraph_with(&format!("{frame}{mirrored}"));
let centered =
r#"<w:framePr w:w="2000" w:hAnchor="page" w:vAnchor="page" w:x="1440" w:yAlign="center"/>"#;
let flowing = r#"<w:framePr w:w="2000" w:hAnchor="text" w:vAnchor="text"/>"#;
let warned = warned_once(DOCUMENT, Feature::MirrorIndents).0;
// The count of the warning for the text box, the centered frame and the frame in the flow.
let below_a_line = paragraph_with("") + &framed(flowing);
let counts: Vec<u32> = [text_box, framed(centered), below_a_line]
.iter()
.map(|body| {
feature_and_value_warnings(body, "")
.into_iter()
.find(|(warning, _)| *warning == warned)
.map_or(0, |(_, count)| count)
})
.collect();
assert_eq!(counts, [1, 1, 1]);
}
#[test]
fn warns_once_for_each_paragraph_of_a_header_row_whatever_the_number_of_its_pages() {
// The warnings of a table's header rows come once for each row, not once for each page that
// repeats them, also where a row splits over pages (`Layout::headers`).
use crate::warnings::Feature;
let cell = |paragraphs: &str| {
format!(r#"<w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr>{paragraphs}</w:tc>"#)
};
let plain = format!("<w:p><w:r><w:t>{TEXT}</w:t></w:r></w:p>");
let header = format!(
"<w:tr><w:trPr><w:tblHeader/></w:trPr>{}</w:tr>",
cell(¶graph_with(
r#"<w:mirrorIndents/><w:ind w:left="720"/>"#
))
);
let table = |rows: &str| {
format!(
r#"<w:tbl><w:tblPr><w:tblW w:w="4000" w:type="dxa"/></w:tblPr><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid>{header}{rows}</w:tbl><w:p/>"#
)
};
// Many rows over pages, and one row that splits over pages.
let rows = format!("<w:tr>{}</w:tr>", cell(&plain)).repeat(200);
let split = format!("<w:tr>{}</w:tr>", cell(&plain.repeat(200)));
let warned = warned_once(DOCUMENT, Feature::MirrorIndents).0;
let counts: Vec<u32> = [table(&rows), table(&split)]
.iter()
.map(|body| {
let bytes = testing::docx(body).plain_styles().zip().unwrap();
let (pages, warnings) = pages_and_feature_warnings(&bytes);
assert!(pages >= 3, "{pages} pages");
warnings
.into_iter()
.find(|(warning, _)| *warning == warned)
.map_or(0, |(_, count)| count)
})
.collect();
assert_eq!(counts, [1, 1]);
}