use std::collections::HashMap;
use f_office_xml::{Document, NodeId};
use crate::ns::{MC, W};
use crate::params::TEXT_BUFFER_MARK_LENGTH;
use crate::reader::settings::ReaderSettings;
pub(crate) fn accept(doc: &mut Document, settings: ReaderSettings) {
if let Ok(root) = doc.root() {
note_inserted_runs(doc, root, settings);
note_deleted_characters(doc, root, settings);
accept_below(doc, root);
}
}
fn note_deleted_characters(doc: &mut Document, root: NodeId, settings: ReaderSettings) {
let mut found = Vec::new();
let mut pending = 0;
let mut after_runs = false;
let mut stack = vec![Some(root)];
while let Some(item) = stack.pop() {
let Some(node) = item else {
pending += TEXT_BUFFER_MARK_LENGTH;
continue;
};
if REMOVED.iter().any(|name| doc.is(node, W, name)) && doc.child(node, W, "r").is_some() {
pending += deleted_characters(doc, node, settings);
after_runs = true;
continue;
}
if doc.is(node, W, "tr") && marked(doc, node, "trPr", &REMOVED) {
continue;
}
if doc.is(node, W, "r") && pending > 0 {
found.push((
node,
std::mem::take(&mut pending),
std::mem::take(&mut after_runs),
));
}
if mark_removed(doc, node) {
stack.push(None);
}
let children: Vec<NodeId> = doc.child_elements(node).collect();
stack.extend(children.into_iter().rev().map(Some));
}
for (run, characters, after_runs) in found {
doc.set_attribute(
run,
Some(crate::ns::NOTE),
"buffered",
&characters.to_string(),
);
if after_runs {
doc.set_attribute(run, Some(crate::ns::NOTE), "removed", "1");
}
}
}
fn deleted_characters(doc: &Document, node: NodeId, settings: ReaderSettings) -> usize {
doc.child_elements(node)
.map(|child| {
if doc.is(child, W, "r") {
run_characters(doc, child, settings)
} else {
deleted_characters(doc, child, settings)
}
})
.sum()
}
const RUN_MARKS: [&str; 18] = [
"tab",
"ptab",
"cr",
"br",
"noBreakHyphen",
"softHyphen",
"sym",
"fldChar",
"footnoteReference",
"footnoteRef",
"endnoteReference",
"endnoteRef",
"annotationRef",
"separator",
"continuationSeparator",
"drawing",
"pict",
"object",
];
fn run_characters(doc: &Document, node: NodeId, settings: ReaderSettings) -> usize {
doc.child_elements(node)
.map(|child| {
let local = doc.element(child).map_or("", |e| e.name.local);
match local {
"AlternateContent" if doc.is(child, MC, "AlternateContent") => {
crate::body::alternate_branch(doc, child)
.map_or(0, |branch| run_characters(doc, branch, settings))
}
"t" | "delText" | "instrText" | "delInstrText" => {
crate::buffers::characters(&doc.text_content(child))
}
"commentReference" => settings.comment_anchor_length(),
_ if RUN_MARKS.contains(&local) => TEXT_BUFFER_MARK_LENGTH,
_ => 0,
}
})
.sum()
}
fn note_inserted_runs(doc: &mut Document, root: NodeId, settings: ReaderSettings) {
let mut revisions: HashMap<(&str, Option<&str>), u32> = HashMap::new();
let mut found = Vec::new();
let mut stack = vec![(root, None::<u32>)];
while let Some((node, change)) = stack.pop() {
let change = if doc.is(node, W, "ins") || doc.is(node, W, "moveTo") {
let author = doc.attribute(node, Some(W), "author").unwrap_or("");
let date = doc.attribute(node, Some(W), "date");
let number = u32::try_from(revisions.len() + 1).unwrap_or(u32::MAX);
Some(
*revisions
.entry(settings.revision_key(author, date))
.or_insert(number),
)
} else {
change
};
if let (true, Some(number)) = (doc.is(node, W, "r"), change) {
found.push((node, number));
}
stack.extend(doc.child_elements(node).map(|child| (child, change)));
}
for (run, number) in found {
doc.set_attribute(run, Some(crate::ns::NOTE), "change", &number.to_string());
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Role {
Kept,
Removed,
Unwrapped,
}
pub(crate) const REMOVED: [&str; 2] = ["del", "moveFrom"];
const RECORDS: [&str; 12] = [
"rPrChange",
"pPrChange",
"sectPrChange",
"tblPrChange",
"tblPrExChange",
"tblGridChange",
"trPrChange",
"tcPrChange",
"numberingChange",
"cellIns",
"cellDel",
"cellMerge",
];
const BLOCKS: [&str; 6] = ["p", "tbl", "sdt", "customXml", "sectPr", "altChunk"];
fn is_block(doc: &Document, node: NodeId) -> bool {
BLOCKS.iter().any(|name| doc.is(node, W, name))
}
fn role(doc: &Document, node: NodeId) -> Role {
let Some(element) = doc.element(node) else {
return Role::Kept;
};
let in_w = element
.name
.namespace
.is_some_and(|ns| doc.namespace_uri(ns) == W);
if !in_w {
return Role::Kept;
}
let local = element.name.local;
match local {
_ if REMOVED.contains(&local) => Role::Removed,
"ins" | "moveTo" => Role::Unwrapped,
"tr" if marked(doc, node, "trPr", &REMOVED) => Role::Removed,
_ if RECORDS.contains(&local) => Role::Removed,
_ => Role::Kept,
}
}
fn marked(doc: &Document, node: NodeId, props: &str, marks: &[&str]) -> bool {
doc.child(node, W, props).is_some_and(|props| {
doc.child_elements(props)
.any(|mark| marks.iter().any(|name| doc.is(mark, W, name)))
})
}
fn mark_removed(doc: &Document, paragraph: NodeId) -> bool {
doc.is(paragraph, W, "p")
&& doc
.child(paragraph, W, "pPr")
.is_some_and(|ppr| marked(doc, ppr, "rPr", &REMOVED))
}
fn kept_children(doc: &Document, node: NodeId, out: &mut Vec<(NodeId, bool)>) {
for &child in doc.children(node) {
match role(doc, child) {
Role::Removed => {}
Role::Unwrapped => kept_children(doc, child, out),
Role::Kept => out.push((child, mark_removed(doc, child))),
}
}
}
fn accept_below(doc: &mut Document, node: NodeId) {
let mut kept = Vec::new();
kept_children(doc, node, &mut kept);
let marks: Vec<(NodeId, NodeId)> = kept
.iter()
.filter_map(|&(child, _)| Some((child, mark_in_deleted_rows(doc, child)?)))
.collect();
for &child in kept
.iter()
.map(|(child, _)| child)
.chain(marks.iter().map(|(_, p)| p))
{
accept_below(doc, child);
}
let children = join_paragraphs(doc, &kept, &marks);
for &child in &children {
if doc.is(child, W, "tbl") && !holds_row(doc, child) {
doc.set_children(child, Vec::new());
}
}
doc.set_children(node, children);
}
fn holds_row(doc: &Document, node: NodeId) -> bool {
doc.child_elements(node).any(|child| {
doc.is(child, W, "tr")
|| ["sdt", "sdtContent", "customXml"]
.iter()
.any(|name| doc.is(child, W, name))
&& holds_row(doc, child)
|| ["AlternateContent", "Choice", "Fallback"]
.iter()
.any(|name| doc.is(child, MC, name))
&& holds_row(doc, child)
})
}
fn holds_content(doc: &Document, node: NodeId) -> bool {
if doc.is(node, W, "r") {
return doc
.child_elements(node)
.any(|child| !doc.is(child, W, "rPr") && !doc.is(child, W, "lastRenderedPageBreak"));
}
doc.child_elements(node)
.any(|child| holds_content(doc, child))
}
fn mark_in_deleted_rows(doc: &Document, table: NodeId) -> Option<NodeId> {
let cells = |row: NodeId| doc.child_elements(row).filter(|&c| doc.is(c, W, "tc"));
doc.is(table, W, "tbl")
.then(|| doc.child_elements(table))?
.filter(|&row| doc.is(row, W, "tr") && role(doc, row) == Role::Removed)
.flat_map(cells)
.flat_map(|cell| doc.child_elements(cell))
.find(|¶graph| doc.is(paragraph, W, "p") && !mark_removed(doc, paragraph))
}
fn next_properties(
doc: &Document,
blocks: impl Iterator<Item = NodeId>,
marks: &[(NodeId, NodeId)],
) -> Option<NodeId> {
let mark = |table: NodeId| marks.iter().find(|&&(t, _)| t == table).map(|&(_, p)| p);
let paragraph = blocks
.filter(|&block| is_block(doc, block))
.find_map(|block| {
if !doc.is(block, W, "tbl") {
return Some(Some(block));
}
match doc.child(block, W, "tr") {
Some(row) => Some(doc.child(row, W, "tc").and_then(|c| doc.child(c, W, "p"))),
None => mark(block).map(Some),
}
})??;
doc.is(paragraph, W, "p")
.then(|| doc.child(paragraph, W, "pPr"))
.flatten()
}
fn keep_before_table(doc: &mut Document, paragraph: NodeId, props: Option<NodeId>) -> bool {
let own: Vec<NodeId> = doc
.children(paragraph)
.iter()
.copied()
.filter(|&child| !doc.is(child, W, "pPr"))
.collect();
let stays = own.iter().any(|&child| holds_content(doc, child));
if stays {
let mut content = Vec::new();
if let (Some(own_props), Some(props)) = (doc.child(paragraph, W, "pPr"), props) {
let taken = doc
.children(props)
.iter()
.copied()
.filter(|&child| !doc.is(child, W, "sectPr"))
.collect();
doc.set_children(own_props, taken);
content.push(own_props);
}
content.extend(own);
doc.set_children(paragraph, content);
}
stays
}
fn join_paragraphs(
doc: &mut Document,
kept: &[(NodeId, bool)],
marks: &[(NodeId, NodeId)],
) -> Vec<NodeId> {
let mut children: Vec<Option<NodeId>> = kept.iter().map(|&(child, _)| Some(child)).collect();
let mut next: Option<usize> = None;
let mut joining: Vec<NodeId> = Vec::new();
for (index, &(child, joins)) in kept.iter().enumerate().rev() {
let later = next.and_then(|at| children.get(at..)).unwrap_or_default();
let fate = if joins {
fate(doc, child, later, marks)
} else {
Fate::Stays
};
match fate {
Fate::Joins => joining.push(child),
Fate::Goes => {}
Fate::Stays if is_block(doc, child) => {
join(doc, next.and_then(|at| kept.get(at)), &mut joining);
next = Some(index);
continue;
}
Fate::Stays => continue,
}
if let Some(slot) = children.get_mut(index) {
*slot = None;
}
}
join(doc, next.and_then(|at| kept.get(at)), &mut joining);
children.into_iter().flatten().collect()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Fate {
Stays,
Goes,
Joins,
}
fn fate(
doc: &mut Document,
paragraph: NodeId,
later: &[Option<NodeId>],
marks: &[(NodeId, NodeId)],
) -> Fate {
let Some(&Some(block)) = later.first() else {
return Fate::Stays;
};
count_join_steps(1);
if doc.is(block, W, "p") {
return Fate::Joins;
}
if !doc.is(block, W, "tbl") {
return Fate::Stays;
}
let blocks = later
.iter()
.flatten()
.copied()
.inspect(|_| count_join_steps(1));
let props = next_properties(doc, blocks, marks);
if keep_before_table(doc, paragraph, props) {
Fate::Stays
} else {
Fate::Goes
}
}
fn join(doc: &mut Document, next: Option<&(NodeId, bool)>, parts: &mut Vec<NodeId>) {
let (Some(&(next, _)), false) = (next, parts.is_empty()) else {
return;
};
let is_props = |child: &&NodeId| doc.is(**child, W, "pPr");
count_join_steps(doc.children(next).len());
let mut joined: Vec<NodeId> = doc
.children(next)
.iter()
.filter(is_props)
.copied()
.collect();
for &part in parts.iter().rev().chain([&next]) {
count_join_steps(doc.children(part).len());
joined.extend(
doc.children(part)
.iter()
.filter(|child| !is_props(child))
.copied(),
);
}
doc.set_children(next, joined);
parts.clear();
}
#[cfg(test)]
thread_local! {
static JOIN_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
fn count_join_steps(children: usize) {
#[cfg(test)]
JOIN_STEPS.with(|steps| steps.set(steps.get() + children));
#[cfg(not(test))]
let _ = children;
}
#[cfg(test)]
mod tests;