1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
//! The HTML divs of the web settings part (`w:divs` of `w:webSettings`, ECMA-376 Part 1,
//! 17.15.2), which a document that was a web page keeps: blocks of paragraphs, one inside
//! another, with margins and borders that Word adds to the paragraphs that name them
//! (`w:divId`, 17.3.1.10).
use std::collections::BTreeSet;
use std::sync::OnceLock;
use f_office_opc::Package;
use f_office_units::Length;
use f_office_xml::NodeId;
use crate::body::ParagraphIds;
use crate::ns::W;
use crate::numbers;
use crate::parts::{self, Role};
use crate::reader::PartReader;
use crate::reader::settings::ReaderSettings;
use crate::{Error, Warnings};
/// The margins of a div (`w:marLeft`, `w:marRight`, `w:marTop` and `w:marBottom`, 17.15.2.21
/// to 17.15.2.24).
const MARGINS: [&str; 4] = ["marLeft", "marRight", "marTop", "marBottom"];
/// The sides of a div's borders (`w:divBdr`, 17.15.2.7).
const SIDES: [&str; 4] = ["top", "left", "bottom", "right"];
/// The divs of a document that change their paragraphs: those with a margin other than 0 or a
/// border line, and every div inside one. Word adds the margins and borders of a div and of the
/// divs around it to its paragraphs; F-Office lays the paragraphs out without them, and the layout
/// warns of each paragraph of such a div.
///
/// The divs are read from the web settings part on the first question about a div, as the
/// package reads a relationships part on its first use. Few paragraphs name a div, and a
/// document saved from HTML can carry a large `webSettings.xml` part that no paragraph references,
/// so parsing it lazily avoids unnecessary work.
#[derive(Debug, Default)]
pub struct HtmlDivs<'p> {
/// The package and the name of its web settings part, when it has one, with the
/// document's source of paragraph IDs and its reader's settings, which every part reader
/// takes.
part: Option<(&'p Package, String, &'p ParagraphIds, ReaderSettings)>,
/// The divs that shape their paragraphs, with the warnings of the part's values, once a
/// question has read the part.
read: OnceLock<Result<(BTreeSet<i64>, Warnings), Error>>,
}
impl<'p> HtmlDivs<'p> {
/// No div, as in a document without a web settings part: the context of the layout's
/// tests.
#[cfg(test)]
#[must_use]
pub(crate) const fn none() -> Self {
Self {
part: None,
read: OnceLock::new(),
}
}
/// The divs of the web settings part `name` of `package`, which the first question reads
/// with the document's source of paragraph IDs `ids` and its reader's settings `settings`.
pub(crate) fn of_part(
package: &'p Package,
name: Option<String>,
(ids, settings): (&'p ParagraphIds, ReaderSettings),
) -> Self {
Self {
part: name.map(|name| (package, name, ids, settings)),
read: OnceLock::new(),
}
}
/// Whether the div `id`, or a div around it, has a margin other than 0 or a border line.
#[must_use]
pub fn shapes(&self, id: i64) -> bool {
self.read()
.as_ref()
.is_ok_and(|(shaping, _)| shaping.contains(&id))
}
/// The divs that shape their paragraphs, read on the first call.
fn read(&self) -> &Result<(BTreeSet<i64>, Warnings), Error> {
self.read.get_or_init(|| {
let mut warnings = Warnings::new();
let Some((package, name, ids, settings)) = &self.part else {
return Ok((BTreeSet::new(), warnings));
};
let role = (Role::WebSettings, Some(name.clone()));
let mut reading = parts::Reading {
warnings: &mut warnings,
ids,
settings: *settings,
notes: None,
colors: f_office_drawingml::color::SchemeColors::default(),
styles: None,
};
parts::read(package, role, &mut reading, shaping).map(|divs| (divs, warnings))
})
}
/// The warnings of the web settings part, when a question read it, and none otherwise.
///
/// # Errors
///
/// When a question read the part and it did not read, as for any part whose role stops
/// the document.
pub(crate) fn finish(self) -> Result<Warnings, Error> {
self.read.into_inner().map_or_else(
|| Ok(Warnings::new()),
|read| read.map(|(_, warnings)| warnings),
)
}
}
/// The IDs of the divs that shape their paragraphs, from the root element `w:webSettings`: each
/// div list (`w:divs`, and `w:divsChild` inside a div) with whether a div around it shapes it.
/// It walks the lists with a stack, so that the depth of the part's divs takes no depth of
/// calls; the part's parse limits the depth.
fn shaping(reader: &mut PartReader, root: NodeId) -> BTreeSet<i64> {
let doc = reader.doc;
let mut shaping = BTreeSet::new();
let mut lists: Vec<(NodeId, bool)> = doc
.child(root, W, "divs")
.map(|list| (list, false))
.into_iter()
.collect();
while let Some((list, outer)) = lists.pop() {
for div in doc
.child_elements(list)
.filter(|&div| doc.is(div, W, "div"))
{
let shapes = outer || own_shape(reader, div);
if shapes && let Some(id) = reader.number(div, "id", numbers::ANY) {
shaping.insert(id);
}
if let Some(inner) = doc.child(div, W, "divsChild") {
lists.push((inner, shapes));
}
}
}
shaping
}
/// Whether a div has a margin other than 0, or a border side with a line.
fn own_shape(reader: &mut PartReader, div: NodeId) -> bool {
let doc = reader.doc;
let margin = MARGINS.iter().any(|&name| {
doc.child(div, W, name)
.and_then(|margin| reader.twips(margin, "val"))
.is_some_and(|length| length != Length::ZERO)
});
let border = doc.child(div, W, "divBdr").is_some_and(|borders| {
SIDES.iter().any(|&name| {
doc.child(borders, W, name)
.and_then(|side| crate::props::read_border(reader, side))
.is_some()
})
});
margin || border
}
#[cfg(test)]
mod tests {
use std::collections::BTreeSet;
use f_office_xml::{Document, Limits};
use super::{HtmlDivs, shaping};
use crate::ns::W;
use crate::reader::PartReader;
fn divs(inner: &str) -> BTreeSet<i64> {
let xml =
format!(r#"<w:webSettings xmlns:w="{W}"><w:divs>{inner}</w:divs></w:webSettings>"#);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let mut reader = PartReader::new(&doc);
shaping(&mut reader, doc.root().unwrap())
}
#[test]
fn a_div_with_a_margin_or_a_border_line_shapes_its_paragraphs_and_its_inner_divs() {
let read = divs(concat!(
r#"<w:div w:id="1"><w:marLeft w:val="0"/><w:marTop w:val="0"/>"#,
r#"<w:divBdr><w:top w:val="none" w:sz="0" w:space="0" w:color="auto"/></w:divBdr>"#,
r#"<w:divsChild><w:div w:id="2"><w:marLeft w:val="480"/>"#,
r#"<w:divsChild><w:div w:id="3"/></w:divsChild></w:div></w:divsChild></w:div>"#,
r#"<w:div w:id="4"><w:marTop w:val="250"/></w:div>"#,
r#"<w:div w:id="5"><w:divBdr><w:left w:val="single" w:sz="4" w:space="0" w:color="auto"/></w:divBdr></w:div>"#,
r#"<w:div w:id="6"/>"#,
));
// The div of no margin and no line, and the one without them, shape nothing; the
// div inside a div with a margin shapes its paragraphs with the outer margin.
assert_eq!(read, BTreeSet::from([2, 3, 4, 5]));
}
#[test]
fn no_web_settings_part_shapes_no_paragraph_and_gives_no_warning() {
let none = HtmlDivs::none();
assert!(!none.shapes(1));
assert!(none.finish().unwrap().is_empty());
assert!(divs("").is_empty());
}
}