use crate::body::{Block, Content, Paragraph, Run, field_code};
use crate::params::{
HYPERLINK_FIELD_EXTRA_LENGTH, TEXT_BUFFER_FIRST_FILL, TEXT_BUFFER_LENGTH,
TEXT_BUFFER_MARK_LENGTH,
};
use crate::reader::settings::ReaderSettings;
#[derive(Clone, Copy)]
pub struct Counting<'a> {
pub settings: ReaderSettings,
pub target: &'a dyn Fn(&str) -> usize,
}
pub fn mark(blocks: &mut [Block], counting: &Counting<'_>) {
let mut filled = TEXT_BUFFER_FIRST_FILL;
mark_blocks(blocks, &mut filled, counting);
}
fn mark_blocks(blocks: &mut [Block], filled: &mut usize, counting: &Counting<'_>) {
for block in blocks {
match block {
Block::Paragraph(paragraph) => mark_paragraph(paragraph, filled, counting),
Block::Table(table) => {
for row in &mut table.rows {
for cell in &mut row.cells {
mark_blocks(&mut cell.blocks, filled, counting);
*filled += TEXT_BUFFER_MARK_LENGTH;
}
*filled += TEXT_BUFFER_MARK_LENGTH;
}
}
}
}
}
fn mark_paragraph(paragraph: &mut Paragraph, filled: &mut usize, counting: &Counting<'_>) {
let mut carried = false;
for run in &mut paragraph.runs {
let text = run
.content
.iter()
.any(|content| matches!(content, Content::Text(_)));
if carried && text {
run.starts_buffer = true;
carried = false;
}
let length = buffer_only(run, counting)
+ run
.content
.iter()
.map(|content| length_of(content, counting))
.sum::<usize>();
let (open, held) = open_marks(run, counting);
if *filled + length > TEXT_BUFFER_LENGTH + open {
run.starts_buffer = true;
carried |= run.content.is_empty() || length > TEXT_BUFFER_LENGTH;
*filled = held
+ if length > TEXT_BUFFER_LENGTH {
0
} else {
length
};
} else {
*filled += length;
}
}
*filled += TEXT_BUFFER_MARK_LENGTH;
}
fn buffer_only(run: &Run, counting: &Counting<'_>) -> usize {
counting
.settings
.buffer_only(&run.buffer_only, counting.target)
}
fn open_marks(run: &Run, counting: &Counting<'_>) -> (usize, usize) {
counting.settings.open_marks(&run.buffer_only)
}
pub(crate) fn address_characters(target: &str) -> usize {
match target.split_once('#') {
Some((address, fragment)) => {
characters(address) + characters(&format!(" \\l \"{fragment}\""))
}
None => characters(target),
}
}
pub(crate) fn characters(text: &str) -> usize {
text.encode_utf16().count()
}
pub(crate) fn field_characters(content: &[Content]) -> usize {
content
.iter()
.map(|item| match item {
Content::FieldBegin | Content::FieldSeparate | Content::FieldEnd => {
TEXT_BUFFER_MARK_LENGTH
}
Content::FieldCode(code) => {
code.encode_utf16().count()
+ usize::from(field_code::links(code)) * HYPERLINK_FIELD_EXTRA_LENGTH
}
_ => 0,
})
.sum()
}
fn length_of(content: &Content, counting: &Counting<'_>) -> usize {
match content {
Content::CommentAnchor(_) => counting.settings.comment_anchor_length(),
Content::PageNumber
| Content::PageCount
| Content::Date(_)
| Content::DocProperty(_)
| Content::StyleRef(_)
| Content::PageRef(_)
| Content::NumberRef(_)
| Content::If(_) => counting.settings.computed_value_length(),
Content::Text(text) | Content::FieldCode(text) => text.encode_utf16().count(),
Content::Bookmark(_)
| Content::FieldMark
| Content::HyperlinkEdge
| Content::ControlEdge
| Content::RemovedEdge
| Content::Stack(_)
| Content::Grown(_)
| Content::Radical(_)
| Content::Accent(_)
| Content::Matrix(_)
| Content::MathBar(_)
| Content::MathSlash(_)
| Content::MathLimit(_)
| Content::GroupChr(_)
| Content::MathBox(_)
| Content::Scripts(_)
| Content::Advance(_)
| Content::FieldLock
| Content::DropDown(_) => 0,
Content::Tab
| Content::PositionTab { .. }
| Content::LineBreak
| Content::ClearingBreak
| Content::PageBreak
| Content::ColumnBreak
| Content::FieldBegin
| Content::CheckBox(_)
| Content::FieldSeparate
| Content::FieldEnd
| Content::FootnoteReference(..)
| Content::FootnoteMark
| Content::EndnoteReference(..)
| Content::EndnoteMark
| Content::CommentMark
| Content::Separator
| Content::ContinuationSeparator
| Content::Floating(_)
| Content::Object { .. }
| Content::Drawing(_) => TEXT_BUFFER_MARK_LENGTH,
}
}
#[cfg(test)]
mod tests {
use crate::body::{Block, Body, Content, Paragraph, Run};
use crate::quirks::{BodyFieldResults, CommentBuffer, FieldBuffer};
use crate::reader::PartReader;
use crate::reader::settings::ReaderSettings;
use f_office_xml::{Document, Limits};
fn paragraph(lengths: &[usize]) -> Block {
Block::Paragraph(Paragraph {
runs: lengths
.iter()
.map(|&length| Run {
content: vec![Content::Text("x".repeat(length))],
..Run::default()
})
.collect(),
..Paragraph::empty()
})
}
fn text_only() -> super::Counting<'static> {
super::Counting {
settings: ReaderSettings::base()
.with_fields(FieldBuffer::ResultOnly)
.with_comments(CommentBuffer::Nothing),
target: &|_| 0,
}
}
fn starts(blocks: &[Block]) -> Vec<Vec<usize>> {
blocks
.iter()
.map(|block| match block {
Block::Paragraph(paragraph) => paragraph
.runs
.iter()
.enumerate()
.filter_map(|(index, run)| run.starts_buffer.then_some(index))
.collect(),
Block::Table(_) => Vec::new(),
})
.collect()
}
fn trailing_run_start(between: &str, counting: &super::Counting<'_>) -> Vec<usize> {
let run = |length: usize| format!("<w:r><w:t>{}</w:t></w:r>", text(length));
let body = format!(
"<w:p>{}</w:p>{between}<w:p>{}{}</w:p>",
run(600),
run(430),
run(1).repeat(82)
);
read_starts(&body, counting).pop().unwrap()
}
fn text(length: usize) -> String {
"x".repeat(length)
}
fn read_starts(body: &str, counting: &super::Counting<'_>) -> Vec<Vec<usize>> {
let xml = format!(
r#"<w:body xmlns:w="{}" xmlns:r="{}">{body}</w:body>"#,
crate::ns::W,
crate::ns::R,
);
let mut doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
crate::revisions::accept(
&mut doc,
counting
.settings
.with_insertions(crate::quirks::InsertionRevision::Author),
);
let mut body = Body::read(
&mut PartReader::new(&doc),
doc.root().unwrap(),
(
ReaderSettings::base()
.with_body_results(BodyFieldResults::ComputesFields)
.with_section_ends(crate::quirks::ContinuousSectionEnd::OnlyBlockKeepsLine),
crate::mode::ModeRules::default(),
),
);
super::mark(&mut body.blocks, counting);
starts(&body.blocks)
}
fn count_after(case: &str, counting: &super::Counting<'_>) -> Option<usize> {
count_after_blocks(&format!("<w:p>{case}</w:p>"), counting)
}
fn count_after_blocks(blocks: &str, counting: &super::Counting<'_>) -> Option<usize> {
let run = |length: usize| format!("<w:r><w:t>{}</w:t></w:r>", text(length));
let body = format!(
"<w:p>{}</w:p>{blocks}<w:p>{}</w:p>",
run(600),
run(1).repeat(512)
);
let starts = read_starts(&body, counting);
Some(511 - starts.last()?.first()?)
}
#[test]
fn holds_the_open_marks_of_fields_again() {
let run = |length: usize| format!("<w:r><w:t>{}</w:t></w:r>", text(length));
let mark = |kind: &str| format!(r#"<w:r><w:fldChar w:fldCharType="{kind}"/></w:r>"#);
let code = |code: &str| {
format!(r#"<w:r><w:instrText xml:space="preserve">{code}</w:instrText></w:r>"#)
};
let field = |code_runs: &str, result: &str| {
format!(
"{}{code_runs}{}{result}{}",
mark("begin"),
mark("separate"),
mark("end")
)
};
let addin = |length: usize| code(&format!(" ADDIN F {}", "b".repeat(length - 9)));
let short = field(&addin(20), &run(3));
let link = |length: usize| {
format!(
r#"{}<w:hyperlink w:anchor="none" w:history="1">{}{}</w:hyperlink>"#,
run(length),
run(3),
run(40)
)
};
let cases = [
(run(488) + &field(&addin(20), &(run(3) + &run(40))), 43),
(run(470) + &field(&addin(20), &(run(3) + &run(40))), 43),
(run(500) + &short, 26),
(run(489) + &short, 6),
(run(486) + &short, 1),
(run(475) + &field(&addin(20), &(run(3) + &short)), 29),
(run(463) + &field(&addin(20), &(run(3) + &short)), 4),
(field(&addin(700), &run(3)), 6),
(link(495), 64),
(link(470), 41),
];
let counting = super::Counting {
settings: ReaderSettings::base()
.with_fields(FieldBuffer::MarksAndCode)
.with_comments(CommentBuffer::Nothing),
target: &|_| 0,
};
for (case, count) in cases {
assert_eq!(count_after(&case, &counting), Some(count), "{case}");
}
}
#[test]
fn counts_stored_results_links_and_locations() {
let ham = format!("<w:r><w:t>{}</w:t></w:r>", text(3));
let mark = |kind: &str| format!(r#"<w:r><w:fldChar w:fldCharType="{kind}"/></w:r>"#);
let complex = |code: &str, result: &str| {
format!(
r#"{}<w:r><w:instrText xml:space="preserve">{code}</w:instrText></w:r>{}<w:r><w:t>{result}</w:t></w:r>{}"#,
mark("begin"),
mark("separate"),
mark("end")
)
};
let simple = |code: &str, result: &str| {
format!(r#"<w:fldSimple w:instr="{code}"><w:r><w:t>{result}</w:t></w:r></w:fldSimple>"#)
};
let marked = |field: String| {
format!(
r#"<w:bookmarkStart w:id="1" w:name="bk01"/>{ham}<w:bookmarkEnd w:id="1"/>{field}"#
)
};
let cases = [
(simple(" PAGE ", "99999"), 15),
(r#"<w:fldSimple w:instr=" PAGE "/>"#.to_owned(), 10),
(
format!(
r#"{}<w:r><w:instrText xml:space="preserve"> PAGE </w:instrText></w:r>{}"#,
mark("begin"),
mark("end")
),
9,
),
(simple(" NUMPAGES ", "999"), 17),
(
simple(" DATE \\@ "yyyy-MM-dd" ", "2000-01-01"),
36,
),
(marked(complex(" PAGEREF bk01 \\h ", "99999")), 30),
(marked(complex(" PAGEREF bk01 ", "99999")), 26),
(marked(complex(" REF bk01 \\h ", "99999")), 26),
(marked(complex(" REF bk01 ", "99999")), 22),
(complex(" ADDIN \\h ", "Ham"), 17),
(
format!(
r#"<w:hyperlink w:anchor="none" w:docLocation="abcdefgh">{ham}</w:hyperlink>"#
),
44,
),
(
format!(r#"<w:hyperlink r:id="rId9">{ham}</w:hyperlink>"#),
42,
),
];
let counting = super::Counting {
settings: ReaderSettings::base()
.with_fields(FieldBuffer::MarksAndCode)
.with_comments(CommentBuffer::Nothing),
target: &|id| {
if id == "rId9" {
super::address_characters("http://a.b/#xy")
} else {
0
}
},
};
for (case, count) in cases {
assert_eq!(count_after(&case, &counting), Some(count), "{case}");
}
assert_eq!(super::address_characters("http://a.b/%7Eb"), 15);
}
#[test]
fn counts_deletions_and_content_controls() {
let ham = format!("<w:r><w:t>{}</w:t></w:r>", text(3));
let run = |length: usize| format!("<w:r><w:t>{}</w:t></w:r>", text(length));
let cases = [
(
format!(
r#"<w:p>{ham}<w:del w:id="1" w:author="a"><w:r><w:delText>{}</w:delText></w:r></w:del></w:p>"#,
text(5)
),
9,
),
(
format!(
r#"<w:p><w:pPr><w:rPr><w:del w:id="1" w:author="a"/></w:rPr></w:pPr>{ham}</w:p><w:p/>"#
),
5,
),
(
format!(
r#"<w:p><w:sdt><w:sdtPr><w:id w:val="1"/></w:sdtPr><w:sdtContent>{ham}</w:sdtContent></w:sdt></w:p>"#
),
6,
),
(
format!(
r#"<w:sdt><w:sdtPr><w:id w:val="1"/></w:sdtPr><w:sdtContent><w:p>{ham}</w:p></w:sdtContent></w:sdt>"#
),
6,
),
(
format!(
"<w:p>{}<w:sdt><w:sdtContent>{ham}{}</w:sdtContent></w:sdt></w:p>",
run(490),
run(40)
),
42,
),
];
let counting = super::Counting {
settings: ReaderSettings::base()
.with_fields(FieldBuffer::MarksAndCode)
.with_comments(CommentBuffer::Nothing),
target: &|_| 0,
};
for (case, count) in cases {
assert_eq!(count_after_blocks(&case, &counting), Some(count), "{case}");
}
}
#[test]
fn starts_a_buffer_at_the_run_that_does_not_fit() {
let mut blocks = vec![
paragraph(&[700]),
paragraph(&[700]),
paragraph(&[48, 256, 96]),
paragraph(&[48, 256, 96]),
paragraph(&[35, 256, 256, 127]),
paragraph(&[35, 256, 256, 127]),
paragraph(&[226, 256, 256, 73]),
paragraph(&[226, 256, 256, 73]),
paragraph(&[103, 97]),
paragraph(&[103, 97]),
];
super::mark(&mut blocks, &text_only());
assert_eq!(
starts(&blocks),
[
vec![0],
vec![0],
vec![],
vec![1],
vec![1, 3],
vec![2],
vec![0, 2],
vec![0, 2],
vec![1],
vec![],
]
);
}
#[test]
fn counts_a_paragraph_end_as_one_character() {
let mut blocks = vec![paragraph(&[507]), paragraph(&[1]), paragraph(&[1])];
super::mark(&mut blocks, &text_only());
assert_eq!(starts(&blocks), [vec![], vec![0], vec![]]);
}
#[test]
fn starts_with_four_characters_in_the_buffer() {
let trailing = |first: usize| {
let mut lengths = vec![first];
lengths.extend([1; 82]);
paragraph(&lengths)
};
let mut blocks = vec![trailing(430)];
super::mark(&mut blocks, &text_only());
assert_eq!(starts(&blocks), [vec![508 - 430 + 1]]);
let mut blocks = vec![
paragraph(&[27]),
paragraph(&[46]),
paragraph(&[18]),
paragraph(&[]),
trailing(340),
];
super::mark(&mut blocks, &text_only());
assert_eq!(starts(&blocks).pop().unwrap(), [413 - 340 + 1]);
}
#[test]
fn counts_the_marks_of_paragraphs_and_tables() {
let cell = "<w:tc><w:p/></w:tc>";
let cases = [
(String::new(), 0),
("<w:p/>".to_owned(), 1),
("<w:p><w:r><w:t>Ham</w:t></w:r></w:p>".to_owned(), 4),
(format!("<w:tbl><w:tr>{cell}</w:tr></w:tbl>"), 3),
(format!("<w:tbl><w:tr>{cell}{cell}</w:tr></w:tbl>"), 5),
(
format!("<w:tbl><w:tr>{cell}{cell}</w:tr><w:tr>{cell}{cell}</w:tr></w:tbl>"),
10,
),
("<w:p><w:r><w:tab/></w:r></w:p>".to_owned(), 2),
("<w:p><w:r><w:br/></w:r></w:p>".to_owned(), 2),
];
for (between, count) in cases {
assert_eq!(
trailing_run_start(&between, &text_only()),
[82 - count],
"{between}"
);
}
}
#[test]
fn counts_fields_and_hyperlinks_as_the_quirk_says() {
let link = |attributes: &str, runs: &str| {
format!("<w:p><w:hyperlink {attributes}>{runs}</w:hyperlink></w:p>")
};
let ham = "<w:r><w:t>Ham</w:t></w:r>";
let field = r#"<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> HYPERLINK \l "none" </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>Ham</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>"#;
let page = r#"<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> PAGE </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>1</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>"#;
let simple_page =
r#"<w:p><w:fldSimple w:instr=" PAGE "><w:r><w:t>1</w:t></w:r></w:fldSimple></w:p>"#;
let cases = [
(link(r#"w:anchor="a""#, ham), 27, 4),
(link(r#"w:anchor="none""#, ham), 30, 4),
(link(r#"w:anchor="abcdefghijklmnop""#, ham), 42, 4),
(link(r#"r:id="rId9""#, ham), 34, 4),
(link(r#"w:anchor="none" w:tooltip="tip""#, ham), 39, 4),
(link(r#"w:anchor="none" w:history="1""#, ham), 27, 4),
(link(r#"w:anchor="none" w:tgtFrame="_blank""#, ham), 42, 4),
(
link(
r#"w:anchor="none""#,
"<w:r><w:t>Ha</w:t></w:r><w:r><w:t>m</w:t></w:r>",
),
30,
4,
),
(field.to_owned(), 29, 4),
(page.to_owned(), 11, 2),
(simple_page.to_owned(), 11, 2),
];
let counting = super::Counting {
settings: ReaderSettings::base()
.with_fields(FieldBuffer::MarksAndCode)
.with_comments(CommentBuffer::Nothing),
target: &|id| if id == "rId9" { 11 } else { 0 },
};
for (between, field_count, text_count) in cases {
assert_eq!(
trailing_run_start(&between, &counting),
[82 - field_count],
"{between}"
);
assert_eq!(
trailing_run_start(&between, &text_only()),
[82 - text_count],
"{between}"
);
}
}
#[test]
fn counts_a_deleted_run_as_the_same_run_live() {
let counting = super::Counting {
settings: ReaderSettings::base()
.with_fields(FieldBuffer::MarksAndCode)
.with_comments(CommentBuffer::ReferenceMark),
target: &|_| 0,
};
let alternate = format!(
r#"<mc:AlternateContent xmlns:mc="{}" xmlns:w14="{}"><mc:Choice Requires="w14"><w:t>ab</w:t></mc:Choice><mc:Fallback><w:t>abcde</w:t></mc:Fallback></mc:AlternateContent>"#,
crate::ns::MC,
crate::ns::W14,
);
let cases = [
("<w:t>abcde</w:t>".to_owned(), 6),
(r#"<w:commentReference w:id="1"/>"#.to_owned(), 2),
(
r#"<w:t>ab</w:t><w:commentReference w:id="1"/>"#.to_owned(),
4,
),
("<w:footnoteRef/>".to_owned(), 2),
("<w:annotationRef/>".to_owned(), 2),
("<w:separator/>".to_owned(), 2),
("<w:continuationSeparator/>".to_owned(), 2),
(alternate, 3),
];
for (content, count) in cases {
let live = format!("<w:p><w:r>{content}</w:r></w:p>");
let deleted =
format!(r#"<w:p><w:del w:id="9" w:author="A"><w:r>{content}</w:r></w:del></w:p>"#);
assert_eq!(trailing_run_start(&live, &counting), [82 - count], "{live}");
assert_eq!(
trailing_run_start(&deleted, &counting),
[82 - count],
"{deleted}"
);
}
}
#[test]
fn counts_a_comment_reference_as_a_mark() {
let counting = super::Counting {
settings: text_only()
.settings
.with_comments(CommentBuffer::ReferenceMark),
..text_only()
};
let letters = "<w:r><w:t>Ham</w:t></w:r>";
let reference = |id: u32| format!(r#"<w:r><w:commentReference w:id="{id}"/></w:r>"#);
let range =
format!(r#"<w:commentRangeStart w:id="1"/>{letters}<w:commentRangeEnd w:id="1"/>"#);
for (case, word) in [
(letters.to_owned(), 4),
(format!("{range}{}", reference(1)), 5),
(format!("{letters}{}", reference(1)), 5),
(range.clone(), 4),
(format!("{letters}{}{}", reference(1), reference(2)), 6),
] {
assert_eq!(count_after(&case, &counting), Some(word), "{case}");
assert_eq!(count_after(&case, &text_only()), Some(4), "{case}");
}
}
#[test]
fn run_after_oversized_run_starts_new_buffer_from_zero() {
let run = |length: usize| format!("<w:r><w:t>{}</w:t></w:r>", text(length));
let counting = text_only();
assert_eq!(
read_starts(&format!("<w:p>{}{}</w:p>", run(512), run(40)), &counting),
vec![vec![0, 1]]
);
assert_eq!(
read_starts(&format!("<w:p>{}{}</w:p>", run(513), run(40)), &counting),
vec![vec![0, 1]]
);
assert_eq!(
read_starts(
&format!("<w:p>{}{}{}{}</w:p>", run(40), run(600), run(40), run(100)),
&counting
),
vec![vec![1, 2]]
);
assert_eq!(
read_starts(
&format!("<w:p>{}<w:r/>{}</w:p>", run(600), run(40)),
&counting
),
vec![vec![0, 2]]
);
let body = format!(
"<w:p>{}{}{}{}</w:p>",
run(600),
run(40),
run(400),
run(1).repeat(80)
);
assert_eq!(read_starts(&body, &counting), vec![vec![0, 1, 75]]);
}
}