use std::collections::HashMap;
use std::ops::Range;
use f_office_xml::{Document, Limits as XmlLimits, NodeId};
use super::styles::Styles;
use super::{Main, NamedFault};
use crate::ns::{MC, W};
const RANGES: [(&str, &str); 3] = [
("w:bookmarkStart", "w:bookmarkEnd"),
("w:commentRangeStart", "w:commentRangeEnd"),
("w:permStart", "w:permEnd"),
];
const OTHER_STORIES: [(&str, &str); 4] = [
(W, "drawing"),
(W, "pict"),
(W, "object"),
(MC, "AlternateContent"),
];
pub(super) struct Built {
pub(super) xml: String,
pub(super) style: Option<String>,
}
pub(super) fn paragraph(
main: &Main<'_>,
styles: &Styles,
(node, paragraph): (NodeId, bool),
given: Option<String>,
content: &dyn Fn(&str) -> String,
) -> Result<Built, NamedFault> {
let w = prefix(main.doc, node)?;
let doc = main.doc;
let properties = paragraph.then(|| doc.child(node, W, "pPr")).flatten();
let own = properties
.and_then(|ppr| doc.child(ppr, W, "pStyle"))
.and_then(|style| doc.attribute(style, Some(W), "val"))
.map(str::to_owned)
.or_else(|| {
paragraph
.then(|| styles.default_paragraph().map(str::to_owned))
.flatten()
});
let followed = own
.as_deref()
.and_then(|own| styles.next(own))
.map(str::to_owned)
.or_else(|| own.clone());
let style = given.or(followed);
let kept = paragraph && style == own;
let written = style.filter(|id| Some(id.as_str()) != styles.default_paragraph());
let reference = written
.as_deref()
.map(|id| format!(r#"<{w}:pStyle {w}:val="{}"/>"#, escaped(id)));
let copied = properties.map(|ppr| {
copy_children(main, ppr, &|child| {
["pStyle", "sectPr", "pPrChange"]
.iter()
.any(|local| doc.is(child, W, local))
})
});
let inner = format!(
"{}{}",
reference.unwrap_or_default(),
copied.unwrap_or_default()
);
let ppr = if inner.is_empty() {
String::new()
} else {
format!("<{w}:pPr>{inner}</{w}:pPr>")
};
let inner = content(&w);
let run = if inner.is_empty() {
String::new()
} else {
let formatting = kept
.then(|| first_run_properties(main, node))
.flatten()
.unwrap_or_default();
format!("<{w}:r>{formatting}{inner}</{w}:r>")
};
Ok(Built {
xml: format!("<{w}:p>{ppr}{run}</{w}:p>"),
style: written,
})
}
pub(super) fn run_text(w: &str, text: &str) -> String {
text.split('\t')
.map(|piece| {
if piece.is_empty() {
String::new()
} else {
text_element(w, piece)
}
})
.collect::<Vec<String>>()
.join(&format!("<{w}:tab/>"))
}
pub(super) fn text_element(w: &str, text: &str) -> String {
if text.is_empty() {
return format!("<{w}:t/>");
}
let space = if text.starts_with(char::is_whitespace) || text.ends_with(char::is_whitespace) {
r#" xml:space="preserve""#
} else {
""
};
format!("<{w}:t{space}>{}</{w}:t>", escaped(text))
}
pub(super) fn first_run_properties(main: &Main<'_>, node: NodeId) -> Option<String> {
let doc = main.doc;
let mut stack = vec![node];
while let Some(current) = stack.pop() {
if doc.is(current, W, "r") {
return doc
.child(current, W, "rPr")
.map(|rpr| main.text(main.span(rpr)));
}
if current != node && is_other_story(doc, current) {
continue;
}
let children: Vec<NodeId> = doc.child_elements(current).collect();
stack.extend(children.into_iter().rev());
}
None
}
pub(super) fn is_other_story(doc: &Document, node: NodeId) -> bool {
OTHER_STORIES
.iter()
.any(|(namespace, local)| doc.is(node, namespace, local))
}
pub(super) fn copy_children(
main: &Main<'_>,
node: NodeId,
skip: &dyn Fn(NodeId) -> bool,
) -> String {
let doc = main.doc;
doc.children(node)
.iter()
.filter(|&&child| doc.element(child).is_none() || !skip(child))
.map(|&child| main.text(main.span(child)))
.collect()
}
pub(super) fn prefix(doc: &Document, node: NodeId) -> Result<String, NamedFault> {
doc.element(node)
.and_then(|element| element.name.prefix.clone())
.ok_or(NamedFault::NoPrefix)
}
pub(super) fn check_fragment(main: &Main<'_>, node: NodeId, xml: &str) -> Result<(), NamedFault> {
parses_in(main, main.parent(node), xml)
}
pub(super) fn check_content(main: &Main<'_>, node: NodeId, xml: &str) -> Result<(), NamedFault> {
parses_in(main, Some(node), xml)
}
fn parses_in(main: &Main<'_>, scope: Option<NodeId>, xml: &str) -> Result<(), NamedFault> {
let scope = scope.map_or_else(Vec::new, |node| main.doc.namespaces_in_scope(node));
Document::parse_fragment(xml.as_bytes(), &scope, &XmlLimits::default())
.map(drop)
.map_err(NamedFault::NewXml)
}
pub(super) fn ends_section(doc: &Document, node: NodeId) -> bool {
doc.child(node, W, "pPr")
.and_then(|ppr| doc.child(ppr, W, "sectPr"))
.is_some()
}
pub(super) fn open_range(doc: &Document, node: NodeId) -> Option<&'static str> {
open_range_in(doc, &[node])
}
pub(super) fn open_range_in(doc: &Document, nodes: &[NodeId]) -> Option<&'static str> {
let mut ends: Vec<RangeEnd> = Vec::new();
let mut stack = nodes.to_vec();
while let Some(current) = stack.pop() {
ends.extend(range_end(doc, current));
stack.extend(doc.child_elements(current));
}
let mut sides: HashMap<(usize, &str), (bool, bool)> = HashMap::new();
for end in &ends {
let (has_start, has_end) = sides.entry((end.range, end.id.as_str())).or_default();
if end.start {
*has_start = true;
} else {
*has_end = true;
}
}
ends.iter()
.find(|end| {
let (has_start, has_end) = sides
.get(&(end.range, end.id.as_str()))
.copied()
.unwrap_or_default();
if end.start { !has_end } else { !has_start }
})
.map(|end| end.element)
}
struct RangeEnd {
range: usize,
start: bool,
id: String,
element: &'static str,
}
fn range_end(doc: &Document, node: NodeId) -> Option<RangeEnd> {
RANGES.iter().enumerate().find_map(|(range, (start, end))| {
[(*start, true), (*end, false)]
.into_iter()
.find(|(element, _)| doc.is(node, W, element.trim_start_matches("w:")))
.map(|(element, is_start)| RangeEnd {
range,
start: is_start,
id: doc.attribute(node, Some(W), "id").unwrap_or("").to_owned(),
element,
})
})
}
pub(super) fn holds_note_reference(doc: &Document, node: NodeId) -> bool {
holds_note_reference_in(doc, &[node])
}
pub(super) fn holds_note_reference_in(doc: &Document, nodes: &[NodeId]) -> bool {
let mut stack = nodes.to_vec();
while let Some(current) = stack.pop() {
if doc.is(current, W, "footnoteReference") || doc.is(current, W, "endnoteReference") {
return true;
}
stack.extend(doc.child_elements(current));
}
false
}
pub(super) fn set_style(
main: &Main<'_>,
node: NodeId,
properties: &str,
element: &str,
id: &str,
) -> Result<Vec<(Range<usize>, String)>, NamedFault> {
let doc = main.doc;
let w = prefix(doc, node)?;
let reference = format!(r#"<{w}:{element} {w}:val="{}"/>"#, escaped(id));
let Some(holder) = doc.child(node, W, properties) else {
let wrapped = format!("<{w}:{properties}>{reference}</{w}:{properties}>");
return Ok(vec![insert_first(main, node, &wrapped)]);
};
if let Some(old) = doc.child(holder, W, element) {
return Ok(vec![(main.span(old), reference)]);
}
Ok(vec![insert_first(main, holder, &reference)])
}
fn insert_first(main: &Main<'_>, node: NodeId, xml: &str) -> (Range<usize>, String) {
let span = main.span(node);
if let Some(wrapped) = wrap_empty(main.bytes, &span, xml) {
return (span, wrapped);
}
let end = start_tag_end(main.bytes, span.start);
(end..end, xml.to_owned())
}
pub(super) fn insert_last(bytes: &[u8], span: Range<usize>, xml: &str) -> (Range<usize>, String) {
if let Some(wrapped) = wrap_empty(bytes, &span, xml) {
return (span, wrapped);
}
let end = end_tag_start(bytes, &span);
(end..end, xml.to_owned())
}
pub(super) fn content_after(
bytes: &[u8],
span: &Range<usize>,
after: Option<Range<usize>>,
) -> Option<Range<usize>> {
let open = start_tag_end(bytes, span.start);
if open == span.end {
return None;
}
let start = after.map_or(open, |child| child.end);
Some(start..end_tag_start(bytes, span))
}
fn wrap_empty(bytes: &[u8], span: &Range<usize>, xml: &str) -> Option<String> {
let end = start_tag_end(bytes, span.start);
if end != span.end || bytes.get(end.saturating_sub(2)) != Some(&b'/') {
return None;
}
let open = String::from_utf8_lossy(bytes.get(span.start..end - 2)?).into_owned();
let name = open
.trim_start_matches('<')
.split(|c: char| c.is_whitespace())
.next()
.unwrap_or_default()
.to_owned();
Some(format!("{}>{xml}</{name}>", open.trim_end()))
}
fn end_tag_start(bytes: &[u8], span: &Range<usize>) -> usize {
bytes
.get(span.clone())
.and_then(|element| element.windows(2).rposition(|pair| pair == b"</"))
.map_or(span.end, |at| span.start + at)
}
fn start_tag_end(bytes: &[u8], start: usize) -> usize {
let mut quote = None;
for (index, &byte) in bytes.iter().enumerate().skip(start) {
match (quote, byte) {
(None, b'"' | b'\'') => quote = Some(byte),
(Some(open), _) if byte == open => quote = None,
(None, b'>') => return index + 1,
_ => {}
}
}
bytes.len()
}
pub(super) fn escaped(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for c in text.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
_ => out.push(c),
}
}
out
}