use std::collections::HashMap;
use f_office_drawingml::color::{DrawColor, percentage};
use f_office_drawingml::shape::ShapeLook;
use f_office_drawingml::theme::ShapeTheme;
use f_office_units::scale::{DRAWING_WHOLE, HALF_POINTS_PER_POINT, LINE, PERCENT};
use f_office_units::{Edges, Length, div_round};
use f_office_xml::enumeration::{Values, another, own};
use f_office_xml::{Document, NodeId};
use crate::body::{Block, Content, DrawingMut, Paragraph, Run, visit_drawings};
use crate::floating::{BoxText, Floating, TextAnchor, body_insets};
use crate::ns::{A, DGM, DSP, R};
use crate::params::{DRAWING_FONT_SIZE, DRAWING_LINE_SCALE};
use crate::props::{Alignment, Color, FontRef, LineSpacing, ParaProps, RunProps, Underline};
use crate::reader::{PartReader, attribute};
use crate::warnings::ReadAs;
pub type Parts = Vec<(Length, Length, Floating)>;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Diagram {
pub data: String,
pub colors: Option<String>,
}
#[must_use]
pub fn diagram(doc: &Document, graphic_data: NodeId) -> Option<Diagram> {
let ids = doc.child(graphic_data, DGM, "relIds")?;
Some(Diagram {
data: doc.attribute(ids, Some(R), "dm")?.to_owned(),
colors: doc.attribute(ids, Some(R), "cs").map(str::to_owned),
})
}
#[must_use]
pub(crate) fn text_colors(
(data, data_root): (&Document, NodeId),
(reader, colors_root): (&mut PartReader, NodeId),
theme: &ShapeTheme,
) -> HashMap<String, Color> {
let colors = reader.doc;
let mut fills: HashMap<&str, Color> = HashMap::new();
for label in doc_children(colors, colors_root, DGM, "styleLbl") {
let fill = colors
.child(label, DGM, "txFillClrLst")
.and_then(|list| color_of(reader, list, theme));
if let (Some(name), Some(fill)) = (colors.attribute(label, None, "name"), fill) {
fills.insert(name, fill);
}
}
let mut by_model = HashMap::new();
let points = data.child(data_root, DGM, "ptLst");
for point in points
.into_iter()
.flat_map(|list| doc_children(data, list, DGM, "pt"))
{
let label = data
.child(point, DGM, "prSet")
.and_then(|set| data.attribute(set, None, "presStyleLbl"));
let model = data.attribute(point, None, "modelId");
if let (Some(model), Some(fill)) = (model, label.and_then(|l| fills.get(l))) {
by_model.insert(model.to_owned(), *fill);
}
}
by_model
}
fn doc_children<'a>(
doc: &'a Document,
node: NodeId,
namespace: &'a str,
name: &'a str,
) -> impl Iterator<Item = NodeId> + 'a {
doc.child_elements(node)
.filter(move |child| doc.is(*child, namespace, name))
}
#[must_use]
pub fn drawing_id(doc: &Document, root: NodeId) -> Option<String> {
let list = doc.child(root, DGM, "extLst")?;
doc.child_elements(list)
.filter_map(|ext| doc.child(ext, DSP, "dataModelExt"))
.find_map(|node| doc.attribute(node, None, "relId"))
.map(str::to_owned)
}
pub fn attach_drawings(blocks: &mut [Block], find: &mut dyn FnMut(&Diagram) -> Parts) {
visit_drawings(blocks, &mut |drawing| {
if let DrawingMut::Floating(floating) = drawing
&& let Some(diagram) = &floating.diagram
{
floating.parts = find(diagram);
}
});
}
pub(crate) fn read_drawing(
reader: &mut PartReader,
root: NodeId,
theme: &ShapeTheme,
text_colors: &HashMap<String, Color>,
) -> Parts {
let mut parts = Vec::new();
if let Some(tree) = reader.doc.child(root, DSP, "spTree") {
let context = Context { theme, text_colors };
shapes(reader, tree, &context, &mut parts);
}
parts
}
struct Context<'a> {
theme: &'a ShapeTheme,
text_colors: &'a HashMap<String, Color>,
}
fn shapes(reader: &mut PartReader, tree: NodeId, context: &Context, parts: &mut Parts) {
let doc = reader.doc;
for child in doc.child_elements(tree) {
if doc.is(child, DSP, "grpSp") {
shapes(reader, child, context, parts);
} else if doc.is(child, DSP, "sp") {
shape(reader, child, context, parts);
}
}
}
fn frame(reader: &mut PartReader, node: NodeId) -> Option<Edges<Length>> {
let doc = reader.doc;
let mut value = |child: &str, name: &str| {
let node = doc.child(node, A, child)?;
reader.emu_length(node, name)
};
Edges::placed(
value("off", "x")?,
value("off", "y")?,
value("ext", "cx")?,
value("ext", "cy")?,
)
}
fn shape(reader: &mut PartReader, sp: NodeId, context: &Context, parts: &mut Parts) {
let doc = reader.doc;
let theme = context.theme;
let props = doc.child(sp, DSP, "spPr");
let style = doc.child(sp, DSP, "style");
let Some(shape_box) = props
.and_then(|p| doc.child(p, A, "xfrm"))
.and_then(|x| frame(reader, x))
else {
return;
};
reader.warn_of_picture_fill(props);
parts.push((
shape_box.left,
shape_box.top,
Floating {
width: shape_box.width(),
height: shape_box.height(),
look: Some(ShapeLook::read(
doc,
(props, style),
reader.drawing_warnings(),
)),
..Floating::in_part(reader.part())
},
));
let Some(text) = doc.child(sp, DSP, "txBody") else {
return;
};
let text_box = doc
.child(sp, DSP, "txXfrm")
.and_then(|t| frame(reader, t))
.unwrap_or(shape_box);
let font_ref = style.and_then(|s| doc.child(s, A, "fontRef"));
let label_color = doc
.attribute(sp, None, "modelId")
.and_then(|id| context.text_colors.get(id))
.copied();
let base = Base {
font: match font_ref.and_then(|f| doc.attribute(f, None, "idx")) {
Some("major") => FontRef::MajorLatin,
_ => FontRef::MinorLatin,
},
color: label_color.or_else(|| font_ref.and_then(|f| color_of(reader, f, theme))),
scale: autofit_scale(reader, text),
};
let body = doc.child(text, A, "bodyPr");
let anchor = TextAnchor::of(body.and_then(|b| doc.attribute(b, None, "anchor")));
let blocks = doc
.child_elements(text)
.filter(|p| doc.is(*p, A, "p"))
.map(|p| Block::Paragraph(paragraph(reader, p, &base, theme)))
.collect();
parts.push((
text_box.left,
text_box.top,
Floating {
width: text_box.width(),
height: text_box.height(),
blocks,
insets: body_insets(reader, body, crate::params::TEXT_BOX_INSETS),
anchor,
box_text: BoxText::SmartArt,
..Floating::in_part(reader.part())
},
));
}
struct Base {
font: FontRef,
color: Option<Color>,
scale: i64,
}
fn autofit_scale(reader: &mut PartReader, text: NodeId) -> i64 {
let doc = reader.doc;
doc.child(text, A, "bodyPr")
.and_then(|b| doc.child(b, A, "normAutofit"))
.and_then(|n| reader.or_missing_in(n, (None, "fontScale"), percentage))
.unwrap_or(DRAWING_WHOLE)
}
fn color_of(reader: &mut PartReader, node: NodeId, theme: &ShapeTheme) -> Option<Color> {
let (rgb, _) =
DrawColor::read(reader.doc, node, reader.drawing_warnings())?.resolve(&theme.colors)?;
Some(Color::Rgb([rgb.r, rgb.g, rgb.b]))
}
const TEXT_ALIGN: &Values<Alignment> = &Values::new(&[
own("l", Alignment::Start),
own("ctr", Alignment::Center),
own("r", Alignment::End),
own("just", Alignment::Both),
another("justLow", Alignment::Start),
another("dist", Alignment::Both),
another("thaiDist", Alignment::Start),
]);
fn paragraph(reader: &mut PartReader, p: NodeId, base: &Base, theme: &ShapeTheme) -> Paragraph {
let id = reader.paragraph_id();
let doc = reader.doc;
let ppr = doc.child(p, A, "pPr");
let mut length = |name: &str| {
ppr.and_then(|n| reader.emu_length(n, name))
.unwrap_or(Length::ZERO)
};
let (indent_left, indent_first) = (length("marL"), length("indent"));
let alignment = ppr
.and_then(|n| reader.enumeration_in(n, (None, "algn"), TEXT_ALIGN))
.unwrap_or(Alignment::Start);
let mut runs: Vec<Run> = Vec::new();
for child in doc.child_elements(p) {
if doc.is(child, A, "r") || doc.is(child, A, "fld") {
let props = run_props(reader, doc.child(child, A, "rPr"), base, theme);
let text = doc
.child(child, A, "t")
.map_or_default(|t| doc.text_content(t));
runs.push(Run::new(props, vec![Content::Text(text)]));
} else if doc.is(child, A, "br") {
let props = run_props(reader, doc.child(child, A, "rPr"), base, theme);
runs.push(Run::new(props, vec![Content::LineBreak]));
}
}
let bullet = ppr
.and_then(|n| doc.child(n, A, "buChar"))
.and_then(|n| doc.attribute(n, None, "char"))
.and_then(|text| text.chars().next());
let has_text = runs.iter().any(|run| {
run.content
.iter()
.any(|content| matches!(content, Content::Text(text) if !text.is_empty()))
});
if let (Some(bullet), true, Some(first)) = (bullet, has_text, runs.first()) {
let label = Run::new(
first.props.clone(),
vec![Content::Text(bullet.to_string()), Content::Tab],
);
runs.insert(0, label);
}
let mark = run_props(reader, doc.child(p, A, "endParaRPr"), base, theme);
let size = runs.first().map_or(&mark, |r| &r.props).drawn_half_points();
let line = ppr
.and_then(|n| doc.child(n, A, "lnSpc"))
.and_then(|n| doc.child(n, A, "spcPct"))
.and_then(|s| reader.or_missing_in(s, (None, "val"), percentage))
.map_or(LineSpacing::Auto(LINE), |share| {
let multiple = div_round(LINE.saturating_mul(share), DRAWING_WHOLE);
LineSpacing::Auto(reader.bounded_line_multiple(multiple))
});
let mut spacing = |name: &str| -> Length {
let Some(node) = ppr.and_then(|n| doc.child(n, A, name)) else {
return Length::ZERO;
};
if let Some(points) = doc
.child(node, A, "spcPts")
.and_then(|s| reader.or_missing_in(s, (None, "val"), f_office_drawingml::integer))
{
return Length::from_units(points * Length::UNITS_PER_POINT / PERCENT);
}
let percent = doc.child(node, A, "spcPct");
let share = percent
.and_then(|s| reader.or_missing_in(s, (None, "val"), percentage))
.unwrap_or(0);
let (part, whole) = DRAWING_LINE_SCALE;
let units = i128::from(size) * i128::from(Length::UNITS_PER_HALF_POINT) * i128::from(part)
/ i128::from(whole)
* i128::from(share)
/ i128::from(DRAWING_WHOLE);
let limit = Length::FILE_LIMIT;
match i64::try_from(units) {
Ok(units) if (-limit..=limit).contains(&units) => Length::from_units(units),
_ => {
if let Some(percent) = percent {
reader.invalid(percent, attribute("val"), ReadAs::Missing);
}
Length::ZERO
}
}
};
Paragraph {
id,
props: ParaProps {
alignment: Some(alignment),
before: Some(spacing("spcBef")),
after: Some(spacing("spcAft")),
line: Some(line),
indent_left: Some(indent_left),
indent_right: Some(Length::ZERO),
indent_first: Some(indent_first),
contextual_spacing: Some(false),
mark,
..ParaProps::default()
},
runs,
source: crate::source_span::SourceSpan::NONE,
}
}
fn run_props(
reader: &mut PartReader,
rpr: Option<NodeId>,
base: &Base,
theme: &ShapeTheme,
) -> RunProps {
let doc = reader.doc;
let attribute = |name: &str| rpr.and_then(|n| doc.attribute(n, None, name));
let hundredths = rpr
.and_then(|n| reader.or_missing_in(n, (None, "sz"), f_office_drawingml::integer))
.unwrap_or(DRAWING_FONT_SIZE * PERCENT);
let size = reader.bounded_font_size(
hundredths * base.scale / DRAWING_WHOLE / (PERCENT / HALF_POINTS_PER_POINT),
);
let per_half_point = PERCENT / HALF_POINTS_PER_POINT;
let kern = rpr
.and_then(|n| {
reader.or_missing_in(n, (None, "kern"), |value| {
f_office_drawingml::integer(value).filter(|hundredths| *hundredths >= 0)
})
})
.map(|hundredths| ((hundredths + per_half_point - 1) / per_half_point).max(1));
let on = |name: &str| attribute(name).is_some_and(f_office_drawingml::boolean);
let font = rpr
.and_then(|n| doc.child(n, A, "latin"))
.and_then(|l| doc.attribute(l, None, "typeface"))
.map_or(base.font.clone(), FontRef::of_typeface);
let color = rpr
.and_then(|n| doc.child(n, A, "solidFill"))
.and_then(|fill| color_of(reader, fill, theme))
.or(base.color);
RunProps {
font_ascii: Some(font.clone()),
font_hansi: Some(font),
size: Some(size),
kern,
bold: Some(on("b")),
italic: Some(on("i")),
underline: Some(if attribute("u").is_some_and(|u| u != "none") {
Underline::Single
} else {
Underline::None
}),
color: Some(color.unwrap_or(Color::Auto)),
..RunProps::default()
}
}
#[cfg(test)]
mod tests;