mod contents;
mod drawings;
pub(crate) mod field_code;
mod fields;
pub(crate) mod links;
mod runs;
mod section;
pub(crate) mod toc;
pub(crate) use drawings::{DrawingMut, visit_drawings};
pub(crate) use runs::{FIELD_CHAR, FieldChar, RunWrapper, author_color, read_wrapped};
pub(crate) use section::first_column_width;
use std::borrow::Cow;
use std::collections::HashSet;
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};
use f_office_units::Length;
use f_office_xml::enumeration::{Values, another, own};
use f_office_xml::{Document, NodeId};
pub(crate) use fields::Updates;
use fields::resolve_fields;
pub use fields::{refers_to_pages, refers_to_pages_and_numbers, refers_to_styles};
use runs::{bookmark_run, read_paragraph};
pub use section::{
ArtSide, BorderPages, Columns, LineNumberRestart, PageAlign, PageBorders, PageSide, References,
Section, SectionPart, SectionStart, Sections,
};
use section::{inherit_references, read_section_part};
use crate::mode::ModeRules;
use crate::ns::{
A, C, DGM, DSP, M, MC, O, PIC, R, V, W, W10, W14, W15, W16SE, WP, WP14, WPC, WPG, WPS,
};
use crate::picture::Picture;
use crate::props::{CodeFormat, ParaProps, RunProps};
use crate::reader::PartReader;
use crate::reader::settings::ReaderSettings;
use crate::source_span::SourceSpan;
use crate::table::Table;
use crate::warnings::{Feature, Reason};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Content {
Text(String),
Tab,
PositionTab {
kind: crate::props::TabKind,
leader: Option<char>,
},
LineBreak,
ClearingBreak,
PageBreak,
ColumnBreak,
FieldBegin,
FieldLock,
CheckBox(CheckBox),
DropDown(String),
FieldCode(String),
FieldSeparate,
FieldEnd,
PageNumber,
PageCount,
Date(Box<DateField>),
DocProperty(Box<DocProperty>),
StyleRef(Box<StyleRef>),
PageRef(Box<PageRef>),
NumberRef(Box<NumberRef>),
Bookmark(String),
FieldMark,
HyperlinkEdge,
ControlEdge,
RemovedEdge,
CommentAnchor(String),
If(Box<IfField>),
Advance(Length),
FootnoteReference(NoteId, NoteMark),
FootnoteMark,
EndnoteReference(NoteId, NoteMark),
EndnoteMark,
CommentMark,
Separator,
ContinuationSeparator,
Stack(StackMark),
Grown(GrownMark),
Radical(RadicalMark),
Accent(AccentMark),
Matrix(MatrixMark),
MathBar(BarMark),
MathSlash(SlashMark),
MathLimit(LimitMark),
GroupChr(GroupChrMark),
MathBox(MathBoxMark),
Scripts(ScriptMark),
Floating(Box<crate::floating::Floating>),
Object {
width: Length,
height: Length,
picture: Option<Box<Picture>>,
extent: Option<Length>,
},
Drawing(Rc<InlineDrawing>),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StackMark {
Start {
bar: Option<GapMinimum>,
centered: bool,
},
StartBeside(char),
Middle,
End,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GrownMark {
Start,
Character(char),
End,
SpaceBefore,
SpaceAfter,
NestedStart,
NestedEnd,
}
pub const ROOT_SIGN: char = '\u{221A}';
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RadicalMark {
Start {
degree: bool,
},
Sign,
Element,
End,
}
pub const DEFAULT_ACCENT: char = '\u{0302}';
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AccentMark {
Start,
Character,
End,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BarMark {
Start(BarSide),
End,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BarSide {
Top,
#[default]
Bottom,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SlashKind {
Linear,
Skewed,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SlashMark {
Start(SlashKind),
Slash,
Denominator,
End,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LimitSide {
Lower,
Upper,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LimitMark {
Start(LimitSide),
Limit,
End {
operand: bool,
},
}
pub const DEFAULT_GROUP_CHR: char = '\u{23DF}';
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GroupChrPlacement {
pub position: BarSide,
pub vertical_align: BarSide,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GroupChrMark {
Start(GroupChrPlacement),
Character,
End {
operand: bool,
},
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct BorderBoxFlags(u8);
impl BorderBoxFlags {
pub const TOP: u8 = 1;
pub const BOTTOM: u8 = Self::TOP << 1;
pub const LEFT: u8 = Self::BOTTOM << 1;
pub const RIGHT: u8 = Self::LEFT << 1;
pub const STRIKE_H: u8 = Self::RIGHT << 1;
pub const STRIKE_V: u8 = Self::STRIKE_H << 1;
pub const STRIKE_BLTR: u8 = Self::STRIKE_V << 1;
pub const STRIKE_TLBR: u8 = Self::STRIKE_BLTR << 1;
pub const EMPTY: Self = Self(0);
#[must_use]
pub const fn with(self, flag: u8) -> Self {
Self(self.0 | flag)
}
#[must_use]
pub const fn is_empty(self) -> bool {
self.0 == 0
}
#[must_use]
pub const fn has(self, flag: u8) -> bool {
self.0 & flag != 0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MathBoxMark {
BorderStart(BorderBoxFlags),
BorderEnd,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MatrixMark {
Start(MatrixSettings),
Cell(CellJustification),
Row,
End,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MatrixSettings {
pub base: MatrixBase,
pub rows: RowSpacing,
pub column_width: Length,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum MatrixBase {
Top,
#[default]
Center,
Bottom,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RowSpacing {
#[default]
Single,
OneAndAHalf,
Double,
Exactly(Length),
HalfLines(i64),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CellJustification {
Left,
#[default]
Center,
Right,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ScriptMark {
Base {
stacked: bool,
followed: bool,
boxed: bool,
},
BoxStart {
delimited: bool,
},
Operator {
stacked: bool,
drops: bool,
},
Start(ScriptSide),
End,
After,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ScriptSide {
Sub,
Sup,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GapMinimum {
Display,
Line,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CheckBox {
pub size: Option<i64>,
pub checked: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InlineDrawing {
pub width: Length,
pub height: Length,
pub left: Length,
pub top: Length,
pub shape: crate::floating::Floating,
pub drops: bool,
pub anchor_locked: bool,
pub extent: Option<Length>,
}
#[cfg(test)]
impl InlineDrawing {
pub(crate) fn of_shape(shape: crate::floating::Floating) -> Self {
Self {
width: Length::ZERO,
height: Length::ZERO,
left: Length::ZERO,
top: Length::ZERO,
shape,
drops: false,
anchor_locked: false,
extent: None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DateField {
pub picture: String,
pub stored: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DocProperty {
pub name: String,
pub picture: Option<String>,
pub stored: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StyleRef {
pub style: String,
pub last: bool,
pub number: bool,
pub stored: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PageRef {
pub bookmark: String,
pub stored: String,
pub code: Option<CodeRun>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CodeRun {
pub style: Option<String>,
pub props: RunProps,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NumberRef {
pub bookmark: String,
pub kind: Option<crate::numbering::ReferenceKind>,
pub stored: String,
pub code: Option<CodeRun>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IfField {
pub parts: Vec<CodePart>,
pub stored: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CodePart {
Text(String),
Field(Content),
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct BufferOnly {
pub characters: usize,
pub relationship: Option<String>,
pub open: usize,
pub held: usize,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Run {
pub style: Option<String>,
pub props: RunProps,
pub content: Vec<Content>,
pub revisions: [Option<u32>; 3],
pub starts_buffer: bool,
pub buffer_only: BufferOnly,
pub record: RunRecord,
pub code_format: Option<Box<CodeFormat>>,
pub links: Vec<links::LinkMark>,
}
impl Run {
#[must_use]
pub fn direct_props(&self, code_format: bool, page_decorations: bool) -> Cow<'_, RunProps> {
let props = match &self.code_format {
Some(code) if code_format => Cow::Owned(code.over(&self.props)),
_ => Cow::Borrowed(&self.props),
};
let page_value = self
.content
.iter()
.any(|content| matches!(content, Content::PageNumber | Content::PageCount));
if !page_decorations && page_value {
Cow::Owned(RunProps {
underline: None,
strike: None,
highlight: None,
..props.into_owned()
})
} else {
props
}
}
}
const ON_OFF_RUN_PROPERTIES: [&str; 20] = [
"b",
"bCs",
"i",
"iCs",
"caps",
"smallCaps",
"strike",
"dstrike",
"outline",
"shadow",
"emboss",
"imprint",
"noProof",
"snapToGrid",
"vanish",
"webHidden",
"rtl",
"cs",
"specVanish",
"oMath",
];
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RunRecord(Vec<RecordChild>);
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
struct RecordChild {
namespace: String,
local: String,
value: RecordValue,
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum RecordValue {
OnOff(bool),
Attributes(Vec<(String, String, String)>),
}
impl RunRecord {
pub(crate) fn read(doc: &Document, rpr: NodeId) -> Self {
let mut children: Vec<RecordChild> = doc
.child_elements(rpr)
.filter(|&child| !doc.is(child, W, "rPrChange"))
.filter_map(|child| {
let element = doc.element(child)?;
let namespace = element
.name
.namespace
.map_or_default(|id| doc.namespace_uri(id).to_owned());
let local = element.name.local.to_owned();
let value = if namespace == W && ON_OFF_RUN_PROPERTIES.contains(&local.as_str()) {
RecordValue::OnOff(crate::on_off::element(doc, child, W))
} else {
let mut attributes: Vec<(String, String, String)> = element
.attributes
.iter()
.filter(|attribute| {
attribute.name.prefix != Some("xmlns")
&& !(attribute.name.prefix.is_none()
&& attribute.name.local == "xmlns")
})
.map(|attribute| {
(
attribute
.name
.namespace
.map_or_default(|id| doc.namespace_uri(id).to_owned()),
attribute.name.local.to_owned(),
attribute.value.to_owned(),
)
})
.collect();
attributes.sort();
RecordValue::Attributes(attributes)
};
Some(RecordChild {
namespace,
local,
value,
})
})
.collect();
children.sort();
Self(children)
}
}
impl Run {
#[must_use]
pub(crate) fn new(props: RunProps, content: Vec<Content>) -> Self {
Self {
props,
content,
..Self::default()
}
}
#[must_use]
pub(crate) fn part(&self, props: RunProps, content: Vec<Content>) -> Self {
Self {
style: self.style.clone(),
props,
content,
revisions: self.revisions,
starts_buffer: false,
buffer_only: BufferOnly::default(),
record: self.record.clone(),
code_format: None,
links: Vec::new(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ParagraphId(u64);
#[derive(Debug, Default)]
pub struct ParagraphIds(AtomicU64);
#[cfg(test)]
pub(crate) static TEST_PARAGRAPH_IDS: ParagraphIds = ParagraphIds(AtomicU64::new(0));
impl ParagraphIds {
pub fn next(&self) -> ParagraphId {
ParagraphId(self.0.fetch_add(1, Ordering::Relaxed))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Paragraph {
pub id: ParagraphId,
pub props: ParaProps,
pub runs: Vec<Run>,
pub source: SourceSpan,
}
#[cfg(test)]
impl Paragraph {
pub(crate) fn empty() -> Self {
Self {
id: TEST_PARAGRAPH_IDS.next(),
props: ParaProps::default(),
runs: Vec::new(),
source: SourceSpan::NONE,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Block {
Paragraph(Paragraph),
Table(Table),
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Body {
pub blocks: Vec<Block>,
pub sections: Sections<SectionPart>,
pub without_section: bool,
pub part: std::rc::Rc<f_office_warnings::Name>,
pub(crate) table_of_contents: Option<toc::TableOfContents>,
}
impl Body {
pub fn place_pages(&mut self, template: &Section, gutter_at_top: bool) {
self.place_template_page(template);
self.place_gutters(gutter_at_top);
}
fn place_template_page(&mut self, section: &Section) {
if !self.without_section {
return;
}
for part in &mut self.sections {
part.section = *section;
}
}
fn place_gutters(&mut self, at_top: bool) {
if !at_top {
return;
}
for part in &mut self.sections {
part.section = part.section.with_gutter_at_top();
}
}
pub(crate) fn read(
reader: &mut PartReader,
body: NodeId,
(settings, mode): (ReaderSettings, ModeRules),
) -> Self {
let doc = reader.doc;
let mut out = Self {
part: std::rc::Rc::new(f_office_warnings::Name::new(reader.part())),
..Self::default()
};
let mut parts = Vec::new();
let mut bookmarks = Vec::new();
let mut text_columns = Vec::new();
let mut marks = 0;
for child in block_children(reader, body) {
let block = read_block(reader, child);
let shapes = reader.take_text_columns().into_iter();
if let Some(mut block) = block {
give_bookmarks(&mut bookmarks, &mut block);
give_marks(&mut marks, &mut block);
text_columns.extend(shapes.map(|shape| (out.blocks.len(), child, shape)));
out.push_block(reader, child, block, &mut parts);
} else if doc.is(child, W, "sectPr") {
parts.push(MetSection::Body(child));
} else if doc.is(child, W, "bookmarkStart") {
bookmarks.extend(bookmark_run(doc, child));
} else if doc.is(child, W, "sdt") || doc.is(child, W, "sdtContent") {
marks += crate::params::TEXT_BUFFER_MARK_LENGTH;
}
}
let count = out.blocks.len();
out.without_section = parts.is_empty();
let own = match parts.pop() {
Some(MetSection::Body(node)) => Some(node),
other => {
parts.extend(other);
None
}
};
let before = parts
.into_iter()
.map(|part| match part {
MetSection::Ended(part) => *part,
MetSection::Body(node) => read_section_part(reader, node, count),
})
.collect();
let last = match own {
Some(node) => read_section_part(reader, node, count),
None => SectionPart {
end: count,
..SectionPart::default()
},
};
out.sections = Sections::ending_with(before, last);
warn_text_columns(reader, &out.sections, &text_columns);
inherit_references(&mut out.sections);
keep_section_ends(&mut out.blocks, &out.sections, (settings, mode));
out.table_of_contents = toc::read(&out.blocks);
resolve_fields(reader, &mut out.blocks, settings.body_updates());
fields::keep_stored_properties(&mut out.blocks);
out
}
pub(crate) fn read_streamed(
main_bytes: &[u8],
streamed: &f_office_xml::StreamedBody,
(main_part, xml_limits): (&str, &f_office_xml::Limits),
reading: &mut crate::parts::Reading<'_>,
(settings, mode): (ReaderSettings, ModeRules),
) -> Result<Self, crate::Error> {
let mut out = Self {
part: std::rc::Rc::new(f_office_warnings::Name::new(main_part)),
..Self::default()
};
let mut parts: Vec<StreamedSection> = Vec::new();
let mut bookmarks = Vec::new();
let mut text_columns: Vec<(usize, f_office_warnings::Name)> = Vec::new();
let mut marks = 0;
let mut seen_undeclared: HashSet<String> = HashSet::new();
for range in &streamed.children {
let Some(slice) = main_bytes.get(range.clone()) else {
continue;
};
let frag = Document::parse_fragment_with_aliases_at(
slice,
&streamed.in_scope,
crate::ns::STRICT_ALIASES,
u64::try_from(range.start).unwrap_or(u64::MAX),
xml_limits,
)
.map_err(crate::Error::Xml)?;
for prefix in frag.document().undeclared_prefixes() {
if seen_undeclared.insert(prefix.clone()) {
crate::parts::undeclared_prefixes(
main_part,
std::slice::from_ref(prefix),
reading.warnings,
);
}
}
let Some(&child) = frag.nodes().first() else {
continue;
};
crate::parts::read_with(
frag.document(),
(main_part, child),
reading,
|part_reader, node| {
let doc = part_reader.doc;
let block = read_block(part_reader, node);
let shapes = part_reader.take_text_columns();
if let Some(mut block) = block {
give_bookmarks(&mut bookmarks, &mut block);
give_marks(&mut marks, &mut block);
if !shapes.is_empty() && doc.is(node, W, "p") {
let outside = outside_text_boxes(doc, node);
let block_idx = out.blocks.len();
for shape in shapes {
if outside.contains(&shape) {
let name = doc.element(shape).map_or_default(|e| {
f_office_warnings::Name::new(e.name.local)
});
text_columns.push((block_idx, name));
}
}
}
out.push_streamed_block(part_reader, node, block, &mut parts);
} else if doc.is(node, W, "sectPr") {
let sect = read_section_part(part_reader, node, 0);
parts.push(StreamedSection::Body(Box::new(sect)));
} else if doc.is(node, W, "bookmarkStart") {
bookmarks.extend(bookmark_run(doc, node));
} else if doc.is(node, W, "sdt") || doc.is(node, W, "sdtContent") {
marks += crate::params::TEXT_BUFFER_MARK_LENGTH;
}
},
);
}
out.finish_streamed_sections(parts);
let empty = Document::parse(b"<r/>", xml_limits).map_err(crate::Error::Xml)?;
let empty_root = empty.root().map_err(crate::Error::Xml)?;
crate::parts::read_with(
&empty,
(main_part, empty_root),
reading,
|part_reader, _| {
warn_streamed_text_columns(part_reader, &out.sections, &text_columns);
inherit_references(&mut out.sections);
keep_section_ends(&mut out.blocks, &out.sections, (settings, mode));
out.table_of_contents = toc::read(&out.blocks);
resolve_fields(part_reader, &mut out.blocks, settings.body_updates());
fields::keep_stored_properties(&mut out.blocks);
},
);
Ok(out)
}
fn finish_streamed_sections(&mut self, mut parts: Vec<StreamedSection>) {
let count = self.blocks.len();
self.without_section = parts.is_empty();
let own = match parts.pop() {
Some(StreamedSection::Body(mut sect)) => {
sect.end = count;
Some(*sect)
}
other => {
parts.extend(other);
None
}
};
let before = parts
.into_iter()
.map(|part| match part {
StreamedSection::Ended(sect) => *sect,
StreamedSection::Body(mut sect) => {
sect.end = count;
*sect
}
})
.collect();
let last = own.unwrap_or_else(|| SectionPart {
end: count,
..SectionPart::default()
});
self.sections = Sections::ending_with(before, last);
}
fn push_streamed_block(
&mut self,
reader: &mut PartReader,
node: NodeId,
block: Block,
parts: &mut Vec<StreamedSection>,
) {
let doc = reader.doc;
self.blocks.push(block);
let inner = doc
.child(node, W, "pPr")
.and_then(|ppr| doc.child(ppr, W, "sectPr"));
if let Some(sect) = inner.filter(|_| doc.is(node, W, "p")) {
let part = read_section_part(reader, sect, self.blocks.len());
parts.push(StreamedSection::Ended(Box::new(part)));
}
}
fn push_block(
&mut self,
reader: &mut PartReader,
node: NodeId,
block: Block,
parts: &mut Vec<MetSection>,
) {
let doc = reader.doc;
self.blocks.push(block);
let inner = doc
.child(node, W, "pPr")
.and_then(|ppr| doc.child(ppr, W, "sectPr"));
if let Some(sect) = inner.filter(|_| doc.is(node, W, "p")) {
let part = read_section_part(reader, sect, self.blocks.len());
parts.push(MetSection::Ended(Box::new(part)));
}
}
}
fn warn_text_columns(
reader: &mut PartReader,
sections: &Sections<SectionPart>,
shapes: &[(usize, NodeId, NodeId)],
) {
let doc = reader.doc;
let mut parts = sections.iter().peekable();
let mut walked: Option<(NodeId, HashSet<NodeId>)> = None;
for &(index, block, shape) in shapes {
while parts
.next_if(|part| {
count_text_column_step();
index >= part.end
})
.is_some()
{}
let columns = parts.peek().map_or(1, |part| part.section.columns.count);
if columns <= 1 || !doc.is(block, W, "p") {
continue;
}
if walked.as_ref().is_none_or(|(node, _)| *node != block) {
walked = Some((block, outside_text_boxes(doc, block)));
}
if walked
.as_ref()
.is_some_and(|(_, outside)| outside.contains(&shape))
{
crate::vml::warn_text_column(reader, shape);
}
}
}
fn outside_text_boxes(doc: &Document, node: NodeId) -> HashSet<NodeId> {
let mut outside = HashSet::new();
let mut stack = vec![node];
while let Some(next) = stack.pop() {
count_text_column_step();
outside.insert(next);
stack.extend(
doc.child_elements(next)
.filter(|&child| !crate::ns::is_text_box_content(doc, child)),
);
}
outside
}
#[cfg(test)]
thread_local! {
static TEXT_COLUMN_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
fn count_text_column_step() {
#[cfg(test)]
TEXT_COLUMN_STEPS.with(|steps| steps.set(steps.get() + 1));
}
fn warn_streamed_text_columns(
reader: &mut PartReader,
sections: &Sections<SectionPart>,
shapes: &[(usize, f_office_warnings::Name)],
) {
let mut parts = sections.iter().peekable();
for (index, element_name) in shapes {
while parts.next_if(|part| *index >= part.end).is_some() {}
let columns = parts.peek().map_or(1, |part| part.section.columns.count);
if columns > 1 {
crate::vml::warn_text_column_named(reader, element_name.clone());
}
}
}
#[derive(Debug)]
enum StreamedSection {
Ended(Box<SectionPart>),
Body(Box<SectionPart>),
}
#[derive(Debug)]
enum MetSection {
Ended(Box<SectionPart>),
Body(NodeId),
}
fn keep_section_ends(
blocks: &mut [Block],
sections: &Sections<SectionPart>,
(settings, mode): (ReaderSettings, ModeRules),
) {
let mut start = 0;
for (part, next) in sections.iter().zip(sections.iter().skip(1)) {
let alone = part.end <= start + 1;
start = part.end;
let after_paragraph = part
.end
.checked_sub(2)
.and_then(|i| blocks.get(i))
.is_some_and(|b| matches!(b, Block::Paragraph(_)));
let last = part.end.checked_sub(1).and_then(|i| blocks.get_mut(i));
let Some(Block::Paragraph(paragraph)) = last else {
continue;
};
if next.start != SectionStart::Continuous {
if is_empty_paragraph(paragraph) {
paragraph.props.page_break_before = Some(false);
paragraph.props.section_end = Some(true);
}
continue;
}
if alone {
continue;
}
let keeps_spaces = settings.keeps_end_spaces(part.section.columns.count);
mark_continuous_end(paragraph, (keeps_spaces, after_paragraph), mode);
}
}
fn mark_continuous_end(
paragraph: &mut Paragraph,
(keeps_spaces, after_paragraph): (bool, bool),
mode: ModeRules,
) {
if keeps_spaces && after_paragraph {
if holds_only_bookmarks(paragraph) {
paragraph.props.continuous_end = Some(true);
}
return;
}
let keeps_line = keeps_spaces && mode.keeps_section_end_line_after_table();
if !keeps_line && holds_nothing(paragraph) {
paragraph.props.mark.hidden = Some(true);
}
}
fn is_empty_paragraph(paragraph: &Paragraph) -> bool {
paragraph
.runs
.iter()
.flat_map(|r| &r.content)
.all(|c| match c {
Content::Text(text) => text.trim().is_empty(),
Content::LineBreak
| Content::ClearingBreak
| Content::PageBreak
| Content::ColumnBreak
| Content::FieldBegin
| Content::FieldLock
| Content::DropDown(_)
| Content::FieldCode(_)
| Content::FieldSeparate
| Content::FieldEnd
| Content::FieldMark
| Content::HyperlinkEdge
| Content::ControlEdge
| Content::RemovedEdge
| Content::Bookmark(_)
| Content::CommentAnchor(_)
| Content::CommentMark
| Content::Advance(_) => true,
Content::Tab
| Content::PositionTab { .. }
| Content::CheckBox(_)
| Content::PageNumber
| Content::PageCount
| Content::Date(_)
| Content::DocProperty(_)
| Content::StyleRef(_)
| Content::PageRef(_)
| Content::NumberRef(_)
| Content::If(_)
| Content::FootnoteReference(..)
| Content::FootnoteMark
| Content::EndnoteReference(..)
| Content::EndnoteMark
| Content::Separator
| Content::ContinuationSeparator
| Content::Stack(_)
| Content::Grown(_)
| Content::Radical(_)
| Content::Accent(_)
| Content::Matrix(_)
| Content::MathBar(_)
| Content::MathSlash(_)
| Content::MathLimit(_)
| Content::GroupChr(_)
| Content::MathBox(_)
| Content::Scripts(_)
| Content::Floating(_)
| Content::Object { .. }
| Content::Drawing(_) => false,
})
}
fn holds_only_bookmarks(paragraph: &Paragraph) -> bool {
paragraph
.runs
.iter()
.flat_map(|r| &r.content)
.all(|c| match c {
Content::Text(text) => text.is_empty(),
Content::Bookmark(_) => true,
_ => false,
})
}
pub(crate) fn holds_nothing(paragraph: &Paragraph) -> bool {
paragraph
.runs
.iter()
.flat_map(|r| &r.content)
.all(|c| matches!(c, Content::Text(text) if text.is_empty()))
}
pub(crate) fn read_block(reader: &mut PartReader, node: NodeId) -> Option<Block> {
let doc = reader.doc;
if doc.is(node, W, "p") {
Some(Block::Paragraph(read_paragraph(reader, node)))
} else if doc.is(node, W, "tbl") {
Some(Block::Table(Table::read(reader, node)))
} else {
None
}
}
pub(crate) fn read_story(reader: &mut PartReader, root: NodeId) -> Vec<Block> {
let mut blocks = read_blocks(reader, root);
resolve_fields(reader, &mut blocks, Updates::Computed);
blocks
}
pub(crate) fn read_header_story(
reader: &mut PartReader,
root: NodeId,
settings: ReaderSettings,
) -> Vec<Block> {
let mut blocks = read_blocks(reader, root);
resolve_fields(reader, &mut blocks, settings.header_updates());
blocks
}
pub(crate) fn read_blocks(reader: &mut PartReader, node: NodeId) -> Vec<Block> {
let doc = reader.doc;
let mut bookmarks = Vec::new();
let mut blocks = Vec::new();
let mut marks = 0;
for child in block_children(reader, node) {
if let Some(mut block) = read_block(reader, child) {
give_bookmarks(&mut bookmarks, &mut block);
give_marks(&mut marks, &mut block);
blocks.push(block);
} else if doc.is(child, W, "bookmarkStart") {
bookmarks.extend(bookmark_run(doc, child));
} else if doc.is(child, W, "sdt") || doc.is(child, W, "sdtContent") {
marks += crate::params::TEXT_BUFFER_MARK_LENGTH;
}
}
blocks
}
fn give_marks(marks: &mut usize, block: &mut Block) {
if *marks == 0 {
return;
}
if let Some(run) = first_run(block) {
run.buffer_only.characters += std::mem::take(marks);
}
}
fn first_run(block: &mut Block) -> Option<&mut Run> {
match block {
Block::Paragraph(paragraph) => paragraph.runs.first_mut(),
Block::Table(table) => table
.rows
.first_mut()?
.cells
.first_mut()?
.blocks
.first_mut()
.and_then(first_run),
}
}
fn give_bookmarks(bookmarks: &mut Vec<Run>, block: &mut Block) {
if bookmarks.is_empty() {
return;
}
if let Some(paragraph) = paragraphs_mut(std::slice::from_mut(block))
.into_iter()
.next()
{
paragraph.runs.splice(0..0, bookmarks.drain(..));
}
}
pub(crate) fn all_paragraphs(blocks: &[Block]) -> Vec<&Paragraph> {
let mut out = Vec::new();
for block in blocks {
match block {
Block::Paragraph(paragraph) => out.push(paragraph),
Block::Table(table) => {
for cell in table.rows.iter().flat_map(|row| &row.cells) {
out.extend(all_paragraphs(&cell.blocks));
}
}
}
}
out
}
fn paragraphs_mut(blocks: &mut [Block]) -> Vec<&mut Paragraph> {
let mut out = Vec::new();
for block in blocks {
match block {
Block::Paragraph(paragraph) => out.push(paragraph),
Block::Table(table) => {
for cell in table.rows.iter_mut().flat_map(|row| row.cells.iter_mut()) {
out.extend(paragraphs_mut(&mut cell.blocks));
}
}
}
}
out
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct NoteId(i64);
impl NoteId {
pub(crate) fn read(reader: &mut PartReader, node: NodeId) -> Option<Self> {
reader.number(node, "id", crate::numbers::ANY).map(Self)
}
pub(crate) const fn number(self) -> i64 {
self.0
}
#[cfg(test)]
pub(crate) const fn of(number: i64) -> Self {
Self(number)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NoteMark {
#[default]
Number,
Custom,
}
impl NoteMark {
pub(crate) fn read(doc: &Document, node: NodeId) -> Self {
let custom = doc
.attribute(node, Some(W), "customMarkFollows")
.is_some_and(|value| crate::on_off::read(value) == Some(true));
if custom { Self::Custom } else { Self::Number }
}
}
pub(crate) type NoteIds = crate::note_setup::ByNoteKind<std::collections::HashSet<NoteId>>;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Notes {
pub separator: Vec<Block>,
pub continuation: Vec<Block>,
pub by_id: std::collections::HashMap<NoteId, Vec<Block>>,
pub order: Vec<NoteId>,
pub part: std::rc::Rc<f_office_warnings::Name>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum NoteType {
Normal,
Separator,
ContinuationSeparator,
ContinuationNotice,
}
const NOTE_TYPE: &Values<NoteType> = &Values::new(&[
own("normal", NoteType::Normal),
own("separator", NoteType::Separator),
own("continuationSeparator", NoteType::ContinuationSeparator),
another("continuationNotice", NoteType::ContinuationNotice),
]);
impl Notes {
pub(crate) fn ids(&self) -> std::collections::HashSet<NoteId> {
self.by_id.keys().copied().collect()
}
pub(crate) fn read(reader: &mut PartReader, root: NodeId, settings: ReaderSettings) -> Self {
let doc = reader.doc;
let mut out = Self {
part: std::rc::Rc::new(f_office_warnings::Name::new(reader.part())),
..Self::default()
};
for note in doc
.child_elements(root)
.filter(|n| doc.is(*n, W, "footnote") || doc.is(*n, W, "endnote"))
{
let story = read_story(reader, note);
match reader.enumeration(note, "type", NOTE_TYPE) {
Some(NoteType::Separator) => out.separator = story,
Some(NoteType::ContinuationSeparator) => out.continuation = story,
Some(NoteType::ContinuationNotice) => {}
Some(NoteType::Normal) | None => {
let Some(id) = NoteId::read(reader, note) else {
continue;
};
if !out.by_id.contains_key(&id) {
out.order.push(id);
}
if settings.file_note(&mut out.by_id, id, story) {
reader.note_id_repeated(id.number());
}
}
}
}
out
}
#[must_use]
pub fn with_own_separator(mut self, ids: &ParagraphIds, props: &ParaProps) -> Self {
let holds = |rule: Content| {
let rule = Run {
content: vec![rule],
..Run::default()
};
vec![Block::Paragraph(Paragraph {
id: ids.next(),
props: props.clone(),
runs: vec![rule],
source: SourceSpan::NONE,
})]
};
self.separator = holds(Content::Separator);
self.continuation = holds(Content::ContinuationSeparator);
self
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TakenBecause {
Read,
FallbackRejected,
}
const TAKEN_CHOICES: [(&str, TakenBecause); 19] = [
(W, TakenBecause::Read),
(R, TakenBecause::Read),
(W14, TakenBecause::Read),
(W15, TakenBecause::Read),
(WP, TakenBecause::Read),
(WP14, TakenBecause::Read),
(WPS, TakenBecause::Read),
(WPG, TakenBecause::Read),
(WPC, TakenBecause::Read),
(A, TakenBecause::Read),
(PIC, TakenBecause::Read),
(C, TakenBecause::Read),
(DGM, TakenBecause::Read),
(DSP, TakenBecause::Read),
(V, TakenBecause::Read),
(W10, TakenBecause::Read),
(O, TakenBecause::Read),
(M, TakenBecause::Read),
(W16SE, TakenBecause::FallbackRejected),
];
pub fn alternate_branch(doc: &Document, node: NodeId) -> Option<NodeId> {
let mut fallback = None;
for child in doc.child_elements(node) {
if doc.is(child, MC, "Choice") {
if takes_choice(doc, child) {
return Some(child);
}
} else if fallback.is_none() && doc.is(child, MC, "Fallback") {
fallback = Some(child);
}
}
fallback
}
pub(crate) fn passed_choices(doc: &Document, node: NodeId) -> impl Iterator<Item = NodeId> + '_ {
doc.child_elements(node)
.filter(move |child| doc.is(*child, MC, "Choice"))
.take_while(move |choice| !takes_choice(doc, *choice))
}
fn takes_choice(doc: &Document, choice: NodeId) -> bool {
doc.attribute(choice, None, "Requires")
.unwrap_or("")
.split_whitespace()
.all(|prefix| {
doc.prefix_namespace(choice, prefix)
.is_some_and(|namespace| TAKEN_CHOICES.iter().any(|(taken, _)| *taken == namespace))
})
}
pub(crate) fn shown_branch(reader: &mut PartReader, node: NodeId) -> Option<NodeId> {
let doc = reader.doc;
for choice in passed_choices(doc, node) {
match passed_choice(doc, choice) {
PassedChoice::Drawing(drawing) => reader.drawing_skipped(drawing, Reason::Unsupported),
PassedChoice::Other => reader.feature_not_supported(Feature::AlternateChoice),
}
}
alternate_branch(doc, node)
}
enum PassedChoice {
Drawing(crate::warnings::Drawing),
Other,
}
fn passed_choice(doc: &Document, choice: NodeId) -> PassedChoice {
let mut stack: Vec<NodeId> = doc.child_elements(choice).collect();
stack.reverse();
while let Some(node) = stack.pop() {
if doc.is(node, A, "graphicData") {
return PassedChoice::Drawing(crate::floating::graphic_data_drawing(doc, node));
}
if doc.is(node, W14, "contentPart") {
return PassedChoice::Drawing(crate::warnings::Drawing::Shape);
}
let start = stack.len();
stack.extend(doc.child_elements(node));
if let Some(added) = stack.get_mut(start..) {
added.reverse();
}
}
PassedChoice::Other
}
pub(crate) fn block_children(reader: &mut PartReader, node: NodeId) -> Vec<NodeId> {
let doc = reader.doc;
let mut out = Vec::new();
for child in doc.child_elements(node) {
if doc.is(child, W, "sdt") {
if let Some(content) = doc.child(child, W, "sdtContent") {
out.push(child);
out.extend(block_children(reader, content));
out.push(content);
}
} else if doc.is(child, W, "customXml") {
out.extend(block_children(reader, child));
} else if doc.is(child, MC, "AlternateContent") {
if let Some(branch) = shown_branch(reader, child) {
out.extend(block_children(reader, branch));
}
} else {
out.push(child);
}
}
out
}
#[cfg(test)]
mod tests;