use std::rc::Rc;
use crate::body::{Content, Paragraph, ParagraphId, StyleRef};
use crate::numbering::{Label, ReferenceKind};
use crate::styles::Styles;
use super::{Layout, decisions};
#[derive(Debug, Default)]
struct Styled {
style: Option<String>,
text: String,
runs: Vec<(String, String)>,
number: Option<i64>,
pattern: Option<String>,
}
#[derive(Debug, Default)]
pub(super) struct StyledPages {
paragraphs: Vec<Styled>,
pages: Vec<(usize, usize)>,
}
impl StyledPages {
fn text(&self, styles: &Styles, field: &StyleRef, page: usize) -> Option<String> {
let (index, text) = self.find(styles, field, page)?;
if field.number {
let paragraph = self.paragraphs.get(index)?;
return match paragraph.number {
None => Some("0".to_owned()),
Some(_) => paragraph.pattern.clone(),
};
}
Some(text.to_owned())
}
fn find(&self, styles: &Styles, field: &StyleRef, page: usize) -> Option<(usize, &str)> {
let id = styles.id_of(&field.style);
let found = |index: usize| -> Option<(usize, &str)> {
let paragraph = self.paragraphs.get(index)?;
if paragraph.style.as_deref() == Some(id) {
return Some((index, paragraph.text.as_str()));
}
paragraph
.runs
.iter()
.find(|(style, _)| style == id)
.map(|(_, text)| (index, text.trim_matches([' ', '\u{a0}'])))
};
let on = |p: &&(usize, usize), wanted: fn(usize, usize) -> bool| wanted(p.0, page);
let mut here = self
.pages
.iter()
.filter(|p| on(p, |a, b| a == b))
.filter_map(|p| found(p.1));
let first = if field.last {
here.next_back()
} else {
here.next()
};
first
.or_else(|| {
self.pages
.iter()
.rev()
.filter(|p| on(p, |a, b| a < b))
.find_map(|p| found(p.1))
})
.or_else(|| {
self.pages
.iter()
.filter(|p| on(p, |a, b| a > b))
.find_map(|p| found(p.1))
})
}
fn chapter(&self, styles: &Styles, level: u8, page: usize) -> Option<i64> {
let name = format!("heading {level}");
let id = styles.id_of(&name);
let number = |p: &(usize, usize)| {
let paragraph = self.paragraphs.get(p.1)?;
paragraph
.number
.filter(|_| paragraph.style.as_deref() == Some(id))
};
self.pages
.iter()
.filter(|p| p.0 == page)
.find_map(number)
.or_else(|| {
self.pages
.iter()
.rev()
.filter(|p| p.0 < page)
.find_map(number)
})
}
}
fn styled(paragraph: &Paragraph, field_text: impl Fn(&Content) -> String) -> Styled {
let mut out = Styled {
style: paragraph.props.style.clone(),
..Styled::default()
};
let mut previous: Option<&String> = None;
for run in ¶graph.runs {
let mut text = String::new();
for content in &run.content {
push_text(&mut text, content, &field_text);
}
out.text.push_str(&text);
if let Some(style) = &run.style {
match out.runs.last_mut() {
Some((last, joined)) if last == style && previous == Some(style) => {
joined.push_str(&text);
}
_ => out.runs.push((style.clone(), text.clone())),
}
}
if !text.is_empty() || run.style.is_some() {
previous = run.style.as_ref();
}
}
out
}
fn push_text(text: &mut String, content: &Content, field_text: &impl Fn(&Content) -> String) {
match content {
Content::Text(piece) => text.push_str(piece),
Content::Tab => text.push('\t'),
Content::LineBreak | Content::ClearingBreak => text.push('\n'),
Content::PageNumber
| Content::PageCount
| Content::Date(_)
| Content::DocProperty(_)
| Content::StyleRef(_)
| Content::PageRef(_)
| Content::NumberRef(_)
| Content::If(_) => text.push_str(&field_text(content)),
_ => {}
}
}
impl Layout<'_> {
pub(super) fn note_styled(&mut self, paragraph: &Paragraph, label: Option<&Label>) {
let number = label.map(|label| label.value);
let page = self.output.pages.len();
if let (Some(chapter), Some(number)) = (self.section.chapter, number) {
let name = format!("heading {}", chapter.level);
if paragraph.props.style.as_deref() == Some(self.styles.id_of(&name)) {
self.output.chapter_number = Some(number);
}
}
if let Some(mut record) = self.output.styled.take() {
record.note(paragraph, page, || Styled {
number,
pattern: label
.and_then(|label| label.reference.reference(ReferenceKind::Pattern, None)),
..styled(paragraph, |content| self.field_text(content))
});
self.output.styled = Some(record);
}
}
pub(super) fn chapter_prefix(&self) -> Option<String> {
let chapter = self.section.chapter?;
let number = match &self.style_page {
Some((pages, page)) => pages.chapter(self.styles, chapter.level, *page),
None => self.output.chapter_number,
}?;
Some(format!("{number}{}", chapter.separator.char()))
}
pub(super) fn style_ref_text(&self, field: &StyleRef) -> String {
let found = self
.style_page
.as_ref()
.and_then(|(pages, page)| pages.text(self.styles, field, *page));
found.map_or_else(
|| field.stored.clone(),
|text| decisions::style_ref_text(&self.context.quirks, text),
)
}
pub(super) fn back_to_styled(
&mut self,
record: Option<RecordMark>,
chapter_number: Option<i64>,
) {
if let (Some(kept), Some(record)) = (self.output.styled.as_mut(), record) {
kept.rewind(record);
}
self.output.chapter_number = chapter_number;
}
}
#[derive(Debug, Default)]
pub(super) struct Record {
styled: StyledPages,
current: Option<ParagraphId>,
}
impl Record {
fn note(&mut self, paragraph: &Paragraph, page: usize, entry: impl FnOnce() -> Styled) {
let index = match self.styled.pages.last() {
Some(&(_, last)) if self.current == Some(paragraph.id) => last,
_ => {
self.current = Some(paragraph.id);
self.styled.paragraphs.push(entry());
self.styled.paragraphs.len() - 1
}
};
if self.styled.pages.last() != Some(&(page, index)) {
self.styled.pages.push((page, index));
}
}
pub(super) fn mark(&self) -> RecordMark {
RecordMark {
paragraphs: self.styled.paragraphs.len(),
pages: self.styled.pages.len(),
current: self.current,
}
}
pub(super) fn rewind(&mut self, mark: RecordMark) {
self.styled.paragraphs.truncate(mark.paragraphs);
self.styled.pages.truncate(mark.pages);
self.current = mark.current;
}
pub(super) fn finish(self) -> Rc<StyledPages> {
Rc::new(self.styled)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct RecordMark {
paragraphs: usize,
pages: usize,
current: Option<ParagraphId>,
}
#[cfg(test)]
mod tests {
use f_office_xml::{Document, Limits};
use super::{Record, Styled, StyledPages};
use crate::body::Paragraph;
use crate::layout::testing::{
find_all, lay_out_with_header, on_base_with, pass_with, with_layout,
};
use crate::ns::W;
use crate::numbering::Numbering;
use crate::quirks::{StyleRefNoBreakSpace, StyleRefTrailingSpaces};
use crate::reader::PartReader;
use crate::styles::Styles;
#[test]
fn finds_the_chapter_heading_on_a_page_or_before_it() {
let xml = format!(
r#"<w:styles xmlns:w="{W}"><w:style w:type="paragraph" w:styleId="H1"><w:name w:val="heading 1"/></w:style></w:styles>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
let paragraph = |style: &str, number| Styled {
style: Some(style.into()),
number,
..Styled::default()
};
let pages = StyledPages {
paragraphs: vec![
paragraph("H1", Some(1)),
paragraph("Body", Some(7)),
paragraph("H1", Some(2)),
paragraph("H1", None),
],
pages: vec![(0, 0), (1, 1), (2, 2), (2, 3), (3, 3)],
};
let chapters: Vec<Option<i64>> =
(0..4).map(|page| pages.chapter(&styles, 1, page)).collect();
assert_eq!(chapters, [Some(1), Some(1), Some(2), Some(2)]);
assert_eq!(pages.chapter(&styles, 2, 2), None);
}
#[test]
fn gives_another_paragraph_in_the_place_of_the_last_one_an_entry_of_its_own() {
let mut record = Record::default();
let mut place = Paragraph::empty();
record.note(&place, 0, Styled::default);
record.note(&place, 1, Styled::default);
place = Paragraph::empty();
record.note(&place, 1, Styled::default);
assert_eq!(record.styled.paragraphs.len(), 2);
assert_eq!(record.styled.pages, [(0, 0), (1, 0), (1, 1)]);
}
#[test]
fn forgets_at_a_rewind_what_a_trial_noted_and_which_paragraph_it_placed_last() {
let (text, heading) = (Paragraph::empty(), Paragraph::empty());
let mut record = Record::default();
record.note(&text, 0, Styled::default);
let mark = record.mark();
record.note(&heading, 0, Styled::default);
record.rewind(mark);
record.note(&heading, 1, Styled::default);
assert_eq!(record.styled.paragraphs.len(), 2);
assert_eq!(record.styled.pages, [(0, 0), (1, 1)]);
}
#[test]
fn a_rewind_of_the_layout_takes_back_the_styled_text_and_the_chapter_number_of_a_trial() {
with_layout(|layout| {
layout.output.styled = Some(Record::default());
layout.note_styled(&Paragraph::empty(), None);
let before = layout.output.styled.as_ref().map(Record::mark);
let mark = layout.mark();
layout.note_styled(&Paragraph::empty(), None);
layout.output.chapter_number = Some(2);
layout.rewind(&mark);
assert_eq!(layout.output.styled.as_ref().map(Record::mark), before);
assert_eq!(layout.output.chapter_number, None);
});
}
#[test]
fn takes_the_text_that_the_layout_gives_the_computed_fields_of_a_paragraph() {
use crate::body::{Content, DocProperty, Run};
let paragraph = Paragraph {
runs: vec![Run {
content: vec![
Content::Text("C1 ".into()),
Content::DocProperty(Box::new(DocProperty {
name: "P".into(),
picture: None,
stored: "P1".into(),
})),
Content::Text(" ".into()),
Content::PageNumber,
Content::Text(" C2".into()),
],
..Run::default()
}],
..Paragraph::empty()
};
with_layout(|layout| {
layout.output.styled = Some(Record::default());
layout.note_styled(¶graph, None);
let record = layout.output.styled.take().unwrap();
assert_eq!(record.styled.paragraphs[0].text, "C1 P1 1 C2");
});
}
#[test]
fn gives_a_tab_for_a_tab_and_a_break_for_a_line_break_and_nothing_for_a_positional_tab() {
use crate::body::{Content, Run};
let content = vec![
Content::Text("A".into()),
Content::Tab,
Content::Text("B".into()),
Content::PositionTab {
kind: crate::props::TabKind::Right,
leader: None,
},
Content::Text("C".into()),
Content::LineBreak,
Content::Text("D".into()),
Content::ColumnBreak,
Content::Bookmark("x".into()),
Content::Text("E".into()),
];
let paragraph = Paragraph {
runs: vec![Run {
content,
..Run::default()
}],
..Paragraph::empty()
};
let styled = super::styled(¶graph, |_| String::new());
assert_eq!(styled.text, "A\tBC\nDE");
}
#[test]
fn leaves_out_the_spaces_around_text_of_a_character_style() {
let xml = format!(r#"<w:styles xmlns:w="{W}"/>"#);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
let pages = StyledPages {
paragraphs: vec![Styled {
text: " 25.\tWord".into(),
runs: vec![("Number".into(), " 25\u{a0}".into())],
..Styled::default()
}],
pages: vec![(0, 0)],
};
let field = crate::body::StyleRef {
style: "Number".into(),
last: false,
number: false,
stored: String::new(),
};
assert_eq!(pages.text(&styles, &field, 0).as_deref(), Some("25"));
}
#[test]
fn gives_the_paragraph_number_zero_to_a_paragraph_without_a_list_number() {
let xml = format!(r#"<w:styles xmlns:w="{W}"/>"#);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
let paragraph = |number, pattern: Option<&str>| Styled {
text: "3.\tWord".into(),
runs: vec![("Number".into(), "3".into())],
number,
pattern: pattern.map(Into::into),
..Styled::default()
};
let field = crate::body::StyleRef {
style: "Number".into(),
last: false,
number: true,
stored: "1".into(),
};
let pages = StyledPages {
paragraphs: vec![paragraph(None, None)],
pages: vec![(0, 0)],
};
assert_eq!(pages.text(&styles, &field, 0).as_deref(), Some("0"));
let pages = StyledPages {
paragraphs: vec![paragraph(Some(5), Some("3.5"))],
pages: vec![(0, 0)],
};
assert_eq!(pages.text(&styles, &field, 0).as_deref(), Some("3.5"));
let pages = StyledPages {
paragraphs: vec![paragraph(Some(5), None)],
pages: vec![(0, 0)],
};
assert_eq!(pages.text(&styles, &field, 0), None);
let field = crate::body::StyleRef {
number: false,
..field
};
assert_eq!(pages.text(&styles, &field, 0).as_deref(), Some("3"));
}
#[test]
fn ends_a_stretch_of_a_character_style_at_other_text() {
let run = |style: Option<&str>, text: &str| crate::body::Run {
style: style.map(Into::into),
content: vec![crate::body::Content::Text(text.into())],
..crate::body::Run::default()
};
let paragraph = Paragraph {
runs: vec![
run(Some("Number"), "31"),
run(None, ". Other text "),
run(Some("Number"), "6"),
run(Some("Number"), ".18"),
],
..Paragraph::empty()
};
let styled = super::styled(¶graph, |_| String::new());
let runs: Vec<&str> = styled.runs.iter().map(|(_, text)| text.as_str()).collect();
assert_eq!(runs, ["31", "6.18"]);
}
#[test]
fn lays_out_the_tab_and_the_line_break_of_the_paragraph_that_a_header_field_shows() {
let style =
r#"<w:style w:type="paragraph" w:styleId="Ref"><w:name w:val="Ref"/></w:style>"#;
let header = r#"<w:p><w:r><w:t>H</w:t></w:r><w:fldSimple w:instr=" STYLEREF Ref "><w:r><w:t>Z</w:t></w:r></w:fldSimple></w:p>"#;
let body = r#"<w:p><w:pPr><w:pStyle w:val="Ref"/></w:pPr><w:r><w:t>a</w:t><w:tab/><w:t>b</w:t><w:br/><w:t>c</w:t></w:r></w:p>"#;
let list = lay_out_with_header(body, style, None, Some(header));
let places = |ch: char| {
let mut found = find_all(&list, ch);
found.sort_by_key(|&(page, _, y)| (page, y));
assert_eq!(found.len(), 2, "{ch}");
(found[0], found[1])
};
let ((_, h, h_y), (a, b, c)) = (
find_all(&list, 'H')[0],
(places('a'), places('b'), places('c')),
);
assert_eq!(find_all(&list, 'Z'), Vec::new());
assert_eq!((a.0.2, b.0.2), (h_y, h_y));
assert_eq!(b.0.1, b.1.1);
assert_eq!((c.0.1, c.1.1), (h, a.1.1));
assert!(c.0.2 > h_y);
assert_eq!(c.0.2 - h_y, c.1.2 - a.1.2);
}
#[test]
fn shows_a_no_break_space_of_the_page_s_text_as_a_plain_space_where_the_quirk_says_so() {
let style =
r#"<w:style w:type="paragraph" w:styleId="Ref"><w:name w:val="Ref"/></w:style>"#;
let header = r#"<w:p><w:fldSimple w:instr=" STYLEREF Ref "><w:r><w:t>Z</w:t></w:r></w:fldSimple></w:p>"#;
let body =
"<w:p><w:pPr><w:pStyle w:val=\"Ref\"/></w:pPr><w:r><w:t>a\u{a0}b</w:t></w:r></w:p>";
let spaces = |rule| {
let target = on_base_with(|p| p.with_variant(rule));
let pass = pass_with(
body,
(style, None),
Some(header),
Numbering::default(),
target,
);
(
find_all(&pass.list, '\u{a0}').len(),
find_all(&pass.list, 'b').len(),
)
};
assert_eq!(spaces(StyleRefNoBreakSpace::Kept), (2, 2));
assert_eq!(spaces(StyleRefNoBreakSpace::Plain), (1, 2));
}
#[test]
fn leaves_out_the_spaces_at_the_end_of_the_page_s_paragraph_where_the_quirk_says_so() {
let style =
r#"<w:style w:type="paragraph" w:styleId="Ref"><w:name w:val="Ref"/></w:style>"#;
let header = r#"<w:p><w:pPr><w:jc w:val="right"/></w:pPr><w:fldSimple w:instr=" STYLEREF Ref "><w:r><w:t>Z</w:t></w:r></w:fldSimple></w:p>"#;
let body = r#"<w:p><w:pPr><w:pStyle w:val="Ref"/></w:pPr><w:r><w:t xml:space="preserve">ab </w:t></w:r></w:p>"#;
let glyphs = |rule| {
let target = on_base_with(|p| p.with_variant(rule));
let pass = pass_with(
body,
(style, None),
Some(header),
Numbering::default(),
target,
);
(
find_all(&pass.list, ' ').len(),
find_all(&pass.list, 'b').len(),
)
};
let (kept, dropped) = (
glyphs(StyleRefTrailingSpaces::Kept),
glyphs(StyleRefTrailingSpaces::Dropped),
);
assert_eq!((kept.1, dropped.1), (2, 2));
assert_eq!(kept.0, dropped.0 + 2);
}
}