use std::collections::HashMap;
use super::{autofit_scale, diagram, drawing_id, read_drawing, text_colors};
use crate::body::{Block, Content};
use crate::floating::TextAnchor;
use crate::ns::{A, DGM, DSP, R};
use crate::params::MAX_FONT_SIZE;
use crate::props::{Alignment, Color, FontRef, LineSpacing};
use crate::reader::PartReader;
use crate::testing::Replaced as _;
use crate::warnings::Limit;
use f_office_drawingml::theme::ShapeTheme;
use f_office_units::Length;
use f_office_warnings::Warnings;
use f_office_xml::{Document, Limits};
fn parse(xml: &str) -> Document {
Document::parse(xml.as_bytes(), &Limits::default()).unwrap()
}
fn theme() -> ShapeTheme {
let doc = parse(&format!(
r#"<a:theme xmlns:a="{A}"><a:themeElements><a:clrScheme><a:dk1><a:srgbClr val="000000"/></a:dk1><a:lt1><a:srgbClr val="FFFFFF"/></a:lt1><a:accent1><a:srgbClr val="4472C4"/></a:accent1></a:clrScheme></a:themeElements></a:theme>"#
));
ShapeTheme::read(&doc, doc.root().unwrap(), &mut Warnings::new())
}
#[test]
fn reads_the_parts_of_a_smartart_graphic() {
let doc = parse(&format!(
r#"<a:graphicData xmlns:a="{A}" xmlns:dgm="{DGM}" xmlns:r="{R}"><dgm:relIds r:dm="rId4" r:lo="rId5" r:qs="rId6" r:cs="rId7"/></a:graphicData>"#
));
let found = diagram(&doc, doc.root().unwrap()).unwrap();
assert_eq!(
(found.data.as_str(), found.colors.as_deref()),
("rId4", Some("rId7"))
);
let data = parse(&format!(
r#"<dgm:dataModel xmlns:dgm="{DGM}" xmlns:a="{A}"><dgm:ptLst/><dgm:extLst><a:ext uri="x"><dsp:dataModelExt xmlns:dsp="{DSP}" relId="rId9"/></a:ext></dgm:extLst></dgm:dataModel>"#
));
assert_eq!(
drawing_id(&data, data.root().unwrap()).as_deref(),
Some("rId9")
);
}
/// A saved drawing with one blue rounded rectangle that holds centered text in a box of its
/// own.
const DRAWING: &str = r#"<dsp:spTree><dsp:sp modelId="{M1}"><dsp:spPr><a:xfrm><a:off x="12700" y="25400"/><a:ext cx="1270000" cy="635000"/></a:xfrm><a:prstGeom prst="roundRect"/><a:solidFill><a:schemeClr val="accent1"/></a:solidFill></dsp:spPr><dsp:style><a:lnRef idx="0"/><a:fillRef idx="1"/><a:effectRef idx="0"/><a:fontRef idx="minor"><a:schemeClr val="lt1"/></a:fontRef></dsp:style><dsp:txBody><a:bodyPr lIns="12700" tIns="0" rIns="12700" bIns="0" anchor="ctr"><a:normAutofit fontScale="50%"/></a:bodyPr><a:p><a:pPr algn="ctr"><a:lnSpc><a:spcPct val="90%"/></a:lnSpc><a:spcAft><a:spcPts val="600"/></a:spcAft></a:pPr><a:r><a:rPr sz="2400" b="1"/><a:t>Item</a:t></a:r></a:p></dsp:txBody><dsp:txXfrm><a:off x="25400" y="38100"/><a:ext cx="1244600" cy="609600"/></dsp:txXfrm></dsp:sp></dsp:spTree>"#;
fn drawing(colors: &HashMap<String, Color>) -> Vec<(Length, Length, crate::floating::Floating)> {
let doc = parse(&format!(
r#"<dsp:drawing xmlns:dsp="{DSP}" xmlns:a="{A}">{DRAWING}</dsp:drawing>"#
));
read_drawing(
&mut PartReader::new(&doc),
doc.root().unwrap(),
&theme(),
colors,
)
}
fn points(value: i64) -> Length {
Length::from_points(value).unwrap()
}
#[test]
fn draws_each_shape_in_its_box() {
let parts = drawing(&HashMap::new());
assert_eq!(parts.len(), 2);
let (x, y, shape) = &parts[0];
assert_eq!((*x, *y, shape.width), (points(1), points(2), points(100)));
assert!(shape.look.is_some() && shape.blocks.is_empty());
}
#[test]
fn puts_the_text_of_a_shape_in_a_box_of_its_own() {
let parts = drawing(&HashMap::new());
let (x, y, text) = &parts[1];
assert_eq!((*x, *y), (points(2), points(3)));
assert_eq!(text.anchor, TextAnchor::Center);
assert_eq!(
(text.insets.left, text.insets.top),
(points(1), Length::ZERO)
);
}
#[test]
fn reads_a_spacing_beyond_the_range_of_a_length_as_missing_with_a_warning() {
// The spacing after the paragraph as the largest 32-bit share of its line, with the run
// size of the font size at its largest 32-bit value or at 24 points: the product of the
// two passes `i64`, and the spacing lies beyond the range of a length.
let after = |sz: &str| {
let shapes = DRAWING
.replaced(
r#"<a:spcPts val="600"/>"#,
r#"<a:spcPct val="2147483647"/>"#,
)
.replaced(r#"sz="2400""#, &format!(r#"sz="{sz}""#));
let doc = parse(&format!(
r#"<dsp:drawing xmlns:dsp="{DSP}" xmlns:a="{A}">{shapes}</dsp:drawing>"#
));
let mut reader = PartReader::new(&doc);
let parts = read_drawing(&mut reader, doc.root().unwrap(), &theme(), &HashMap::new());
let Some(Block::Paragraph(paragraph)) = parts[1].2.blocks.first() else {
panic!();
};
let invalid: Vec<(String, Option<String>, u32)> = reader
.invalid_values()
.into_iter()
.map(|(element, attribute, _, count)| (element, attribute, count))
.collect();
(paragraph.props.after, invalid)
};
// 24 points at half the font size is a line of 14.4 points, so the spacing is
// 21,474.8 lines.
assert_eq!(
after("2400"),
(Some(Length::from_units(7_854_636_187)), vec![])
);
assert_eq!(
after("4294967295"),
(
Some(Length::ZERO),
vec![("spcPct".to_owned(), Some("val".to_owned()), 1)]
)
);
}
/// The first paragraph of the text box of [`DRAWING`].
fn first_paragraph() -> crate::body::Paragraph {
let parts = drawing(&HashMap::new());
let Some(Block::Paragraph(paragraph)) = parts[1].2.blocks.first() else {
panic!();
};
paragraph.clone()
}
#[test]
fn draws_a_distributed_paragraph_justified_with_a_warning() {
let aligned = |algn: &str| {
let shapes = DRAWING.replaced(r#"algn="ctr""#, &format!(r#"algn="{algn}""#));
let doc = parse(&format!(
r#"<dsp:drawing xmlns:dsp="{DSP}" xmlns:a="{A}">{shapes}</dsp:drawing>"#
));
let mut reader = PartReader::new(&doc);
let parts = read_drawing(&mut reader, doc.root().unwrap(), &theme(), &HashMap::new());
let Some(Block::Paragraph(paragraph)) = parts[1].2.blocks.first() else {
panic!();
};
let unsupported: Vec<(String, Option<String>, &str)> = reader
.unsupported_values()
.into_iter()
.map(|(element, attribute, value, _)| (element, attribute, value))
.collect();
(
paragraph.props.alignment,
unsupported,
reader.invalid_values().len(),
)
};
let warned = |value| vec![("pPr".to_owned(), Some("algn".to_owned()), value)];
assert_eq!(aligned("just"), (Some(Alignment::Both), vec![], 0));
assert_eq!(aligned("dist"), (Some(Alignment::Both), warned("dist"), 0));
assert_eq!(
aligned("thaiDist"),
(Some(Alignment::Start), warned("thaiDist"), 0)
);
// Text outside the type is the start, as a missing name is, with a warning.
assert_eq!(aligned("center"), (Some(Alignment::Start), vec![], 1));
}
#[test]
fn warns_of_a_picture_fill_of_a_shape_that_it_does_not_draw() {
let fill_kinds = |fill: &str| {
let shapes = DRAWING.replaced(
r#"<a:solidFill><a:schemeClr val="accent1"/></a:solidFill>"#,
fill,
);
let doc = parse(&format!(
r#"<dsp:drawing xmlns:dsp="{DSP}" xmlns:a="{A}">{shapes}</dsp:drawing>"#
));
let mut reader = PartReader::new(&doc);
let parts = read_drawing(&mut reader, doc.root().unwrap(), &theme(), &HashMap::new());
assert!(parts[0].2.picture.is_none());
let kinds: Vec<(&str, u32)> = reader
.drawing_warnings()
.iter()
.map(|(warning, count)| (warning.kind(), count))
.collect();
kinds
};
assert_eq!(
fill_kinds("<a:blipFill><a:blip/></a:blipFill>"),
[("drawingml-picture-fill-not-supported", 1)]
);
assert_eq!(
fill_kinds(r#"<a:solidFill><a:schemeClr val="accent1"/></a:solidFill>"#),
[]
);
}
#[test]
fn converts_the_paragraph_properties() {
let paragraph = first_paragraph();
let props = ¶graph.props;
assert_eq!(props.alignment, Some(Alignment::Center));
assert_eq!(props.line, Some(LineSpacing::Auto(216)));
assert_eq!(props.after, Some(points(6)));
}
#[test]
fn converts_the_run_size_font_and_color() {
let paragraph = first_paragraph();
let run = ¶graph.runs[0];
// 24 pt at the autofit scale of 50% is 12 pt, in half-points.
assert_eq!(run.props.size, Some(24));
assert_eq!(run.props.bold, Some(true));
assert_eq!(run.props.font_ascii, Some(FontRef::MinorLatin));
// The style's font color is white.
assert_eq!(run.props.color, Some(Color::Rgb([255, 255, 255])));
assert_eq!(run.content, [Content::Text("Item".into())]);
}
#[test]
fn reads_a_line_spacing_or_a_share_before_that_does_not_read_as_missing_with_a_warning() {
let spaced = |line: &str, before: &str| {
let shapes = DRAWING.replaced(r#"<a:lnSpc><a:spcPct val="90%"/></a:lnSpc>"#, &format!(
r#"<a:lnSpc><a:spcPct val="{line}"/></a:lnSpc><a:spcBef><a:spcPct val="{before}"/></a:spcBef>"#
));
let doc = parse(&format!(
r#"<dsp:drawing xmlns:dsp="{DSP}" xmlns:a="{A}">{shapes}</dsp:drawing>"#
));
let mut reader = PartReader::new(&doc);
let parts = read_drawing(&mut reader, doc.root().unwrap(), &theme(), &HashMap::new());
let Some(Block::Paragraph(paragraph)) = parts[1].2.blocks.first() else {
panic!();
};
let warnings: u32 = reader
.invalid_values()
.iter()
.map(|(_, _, _, count)| count)
.sum();
(paragraph.props.line, paragraph.props.before, warnings)
};
let (line, before, invalid) = spaced("90%", "0");
assert_eq!(
(line, before, invalid),
(Some(LineSpacing::Auto(216)), Some(Length::ZERO), 0)
);
// A line spacing that does not read is single, and a share before none, each with a
// warning.
assert_eq!(
spaced("x", "x"),
(Some(LineSpacing::Auto(240)), Some(Length::ZERO), 2)
);
}
#[test]
fn reads_the_autofit_scale_as_a_drawingml_percentage() {
let scale = |value: &str| {
let doc = parse(&format!(
r#"<a:txBody xmlns:a="{A}"><a:bodyPr><a:normAutofit fontScale="{value}"/></a:bodyPr></a:txBody>"#
));
let mut reader = PartReader::new(&doc);
let scale = autofit_scale(&mut reader, doc.root().unwrap());
(scale, reader.invalid_values().len())
};
assert_eq!(scale("62500"), (62_500, 0));
// The fraction keeps the sign of the whole number.
assert_eq!(scale("-1.5%"), (-1_500, 0));
assert_eq!(scale(" 45500 "), (45_500, 0));
// A value beyond the integers of 64 bits does not read, so the whole size stays, with a
// warning.
assert_eq!(scale("99999999999999999%"), (100_000, 1));
}
/// The first paragraph of the text box of [`DRAWING`] with the run size `sz`, the autofit
/// scale `scale` and the spacing after `after`, and the limits that the reader reached.
fn sized_paragraph(
sz: &str,
scale: &str,
after: &str,
) -> (crate::body::Paragraph, Vec<(Limit, u32)>) {
let shapes = DRAWING
.replaced(r#"sz="2400""#, &format!(r#"sz="{sz}""#))
.replaced(r#"fontScale="50%""#, &format!(r#"fontScale="{scale}""#))
.replaced(r#"<a:spcPts val="600"/>"#, after);
let doc = parse(&format!(
r#"<dsp:drawing xmlns:dsp="{DSP}" xmlns:a="{A}">{shapes}</dsp:drawing>"#
));
let mut reader = PartReader::new(&doc);
let parts = read_drawing(&mut reader, doc.root().unwrap(), &theme(), &HashMap::new());
let Some(Block::Paragraph(paragraph)) = parts[1].2.blocks.first() else {
panic!();
};
(paragraph.clone(), reader.limits_reached())
}
#[test]
fn reads_a_run_size_as_the_reader_of_w_sz_reads_it() {
let size = |sz: &str, scale: &str| {
let (paragraph, limits) = sized_paragraph(sz, scale, r#"<a:spcPts val="600"/>"#);
(paragraph.runs[0].props.size, limits)
};
let none = Vec::new();
// The largest `sz` at the largest autofit scale is 1,844,674,406,082 half points, so it
// reads as the limit with a warning.
assert_eq!(
size("4294967295", "2147483647"),
(Some(MAX_FONT_SIZE), vec![(Limit::FontSize, 1)])
);
// 13,421,772.8 pt at 1,000% is the limit, and 0.5 pt more is above it.
assert_eq!(
size("1342177280", "1000000"),
(Some(MAX_FONT_SIZE), none.clone())
);
assert_eq!(
size("1342177330", "1000000"),
(Some(MAX_FONT_SIZE), vec![(Limit::FontSize, 1)])
);
// A product of 0 or below stays, as a `w:sz` of 0 or below does: the smallest `sz` at the
// largest scale, the largest `sz` at the smallest scale, and a negative `sz` at 50%.
assert_eq!(
size("-2147483648", "2147483647"),
(Some(-922_337_203_255), none.clone())
);
assert_eq!(
size("4294967295", "-2147483648"),
(Some(-1_844_674_406_941), none.clone())
);
assert_eq!(size("-2400", "50%"), (Some(-24), none.clone()));
assert_eq!(size("0", "50%"), (Some(0), none));
}
#[test]
fn reads_the_smallest_kerned_size_of_a_run_in_half_points() {
// The helper writes `sz="{sz}"`, so a `kern` after the size goes inside its quotes.
let kern = |value: Option<&str>| {
let sz = value.map_or_else(|| "2400".to_owned(), |v| format!(r#"2400" kern="{v}"#));
let (paragraph, _) = sized_paragraph(&sz, "50%", r#"<a:spcPts val="600"/>"#);
paragraph.runs[0].props.kern
};
// 12 pt is 24 half points, 12.25 pt is above 24 and so 25, and 0 kerns every size. A run
// without `kern`, or with a value below 0 or not a number, gets none of its own and keeps
// the one that the layout gives it from the styles part.
for (value, threshold) in [
(Some("1200"), Some(24)),
(Some("1225"), Some(25)),
(Some("0"), Some(1)),
(None, None),
(Some("-1"), None),
(Some("twelve"), None),
] {
assert_eq!(kern(value), threshold, "{value:?}");
}
}
#[test]
fn counts_the_lines_of_a_spacing_at_the_size_that_the_run_draws() {
// A spacing after of one line is 1.2 times the run's size: 12 pt at 50% gives 14.4 pt, and
// a size of 0 or below draws at Word's default of 10 pt, which gives 12 pt.
let after = |sz: &str| {
let (paragraph, _) = sized_paragraph(sz, "50%", r#"<a:spcPct val="100000"/>"#);
paragraph.props.after
};
assert_eq!(
after("2400"),
Some(Length::from_units(points(144).units() / 10))
);
assert_eq!(after("-2400"), Some(points(12)));
assert_eq!(after("0"), Some(points(12)));
}
#[test]
fn takes_the_text_color_of_the_shape_style_label() {
let data = parse(&format!(
r#"<dgm:dataModel xmlns:dgm="{DGM}"><dgm:ptLst><dgm:pt modelId="{{M1}}" type="pres"><dgm:prSet presStyleLbl="node1"/></dgm:pt><dgm:pt modelId="{{M2}}" type="pres"><dgm:prSet presStyleLbl="bgShp"/></dgm:pt></dgm:ptLst></dgm:dataModel>"#
));
let colors = parse(&format!(
r#"<dgm:colorsDef xmlns:dgm="{DGM}" xmlns:a="{A}"><dgm:styleLbl name="node1"><dgm:txFillClrLst meth="repeat"><a:schemeClr val="dk1"/></dgm:txFillClrLst></dgm:styleLbl><dgm:styleLbl name="bgShp"><dgm:txFillClrLst/></dgm:styleLbl></dgm:colorsDef>"#
));
let found = text_colors(
(&data, data.root().unwrap()),
(&mut PartReader::new(&colors), colors.root().unwrap()),
&theme(),
);
assert_eq!(found.get("{M1}"), Some(&Color::Rgb([0, 0, 0])));
assert_eq!(found.get("{M2}"), None);
let parts = drawing(&found);
let Block::Paragraph(paragraph) = &parts[1].2.blocks[0] else {
panic!();
};
assert_eq!(paragraph.runs[0].props.color, Some(Color::Rgb([0, 0, 0])));
}
#[test]
fn gives_a_smartart_graphic_in_a_text_box_of_a_group_its_parts() {
use std::rc::Rc;
use crate::body::{InlineDrawing, Paragraph, Run};
use crate::floating::Floating;
use super::{Diagram, attach_drawings};
let paragraph = |content| {
Block::Paragraph(Paragraph {
runs: vec![Run {
content: vec![content],
..Run::default()
}],
..Paragraph::empty()
})
};
// An inline SmartArt graphic in the text box of a shape of a floating group.
let graphic = Floating {
diagram: Some(Diagram {
data: "rId4".to_owned(),
colors: None,
}),
..Floating::default()
};
let shape = Floating {
blocks: vec![paragraph(Content::Drawing(Rc::new(
InlineDrawing::of_shape(graphic),
)))],
..Floating::default()
};
let group = Floating {
parts: vec![(Length::ZERO, Length::ZERO, shape)],
..Floating::default()
};
let mut blocks = vec![paragraph(Content::Floating(Box::new(group)))];
attach_drawings(&mut blocks, &mut |diagram| {
if diagram.data == "rId4" {
vec![(Length::ZERO, Length::ZERO, Floating::default())]
} else {
Vec::new()
}
});
let Block::Paragraph(outer) = &blocks[0] else {
panic!("no paragraph");
};
let Content::Floating(group) = &outer.runs[0].content[0] else {
panic!("no group");
};
let Block::Paragraph(inner) = &group.parts[0].2.blocks[0] else {
panic!("no paragraph in the text box");
};
let Content::Drawing(drawing) = &inner.runs[0].content[0] else {
panic!("no inline drawing");
};
assert_eq!(drawing.shape.parts.len(), 1);
}
/// The runs of the first paragraph of [`DRAWING`] with `bullet` at the end of its paragraph
/// properties and `text` as the text of its run.
fn bulleted_runs(bullet: &str, text: &str) -> Vec<crate::body::Run> {
let shapes = DRAWING
.replaced(
r#"<a:spcPts val="600"/></a:spcAft></a:pPr>"#,
&format!(r#"<a:spcPts val="600"/></a:spcAft>{bullet}</a:pPr>"#),
)
.replaced("<a:t>Item</a:t>", &format!("<a:t>{text}</a:t>"));
let doc = parse(&format!(
r#"<dsp:drawing xmlns:dsp="{DSP}" xmlns:a="{A}">{shapes}</dsp:drawing>"#
));
let mut reader = PartReader::new(&doc);
let parts = read_drawing(&mut reader, doc.root().unwrap(), &theme(), &HashMap::new());
let Some(Block::Paragraph(paragraph)) = parts[1].2.blocks.first() else {
panic!();
};
paragraph.runs.clone()
}
#[test]
fn starts_a_paragraph_with_its_bullet_and_a_tab_in_the_look_of_its_first_run() {
let runs = bulleted_runs(r#"<a:buChar char="•"/>"#, "Item");
assert_eq!(runs.len(), 2);
assert_eq!(runs[0].content, [Content::Text("•".into()), Content::Tab]);
assert_eq!(runs[0].props, runs[1].props);
assert_eq!(runs[1].content, [Content::Text("Item".into())]);
// The bullet is the first character of `char`.
assert_eq!(
bulleted_runs(r#"<a:buChar char="••"/>"#, "Item")[0].content,
[Content::Text("•".into()), Content::Tab]
);
// No bullet without a bullet character, nor in a paragraph without text.
for (bullet, text) in [
("<a:buNone/>", "Item"),
("", "Item"),
(r#"<a:buChar char=""/>"#, "Item"),
(r#"<a:buChar char="•"/>"#, ""),
] {
assert_eq!(bulleted_runs(bullet, text).len(), 1, "{bullet} {text}");
}
}