1use std::collections::HashMap;
11use std::fmt;
12use std::num::NonZeroUsize;
13use std::ops::{Range, RangeInclusive};
14use std::str::FromStr;
15
16use crate::body::toc::TableOfContents;
17use crate::body::{Block, Content, Paragraph, ParagraphId};
18use crate::layout::PlacedLine;
19use crate::params;
20use crate::styles::Styles;
21
22pub(crate) const PICTURE_MARKER: &str = "{PICTURE}";
24
25#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
28#[non_exhaustive]
29pub enum AddressStep {
30 Header(NonZeroUsize),
33 Footer(NonZeroUsize),
36 Footnote(NonZeroUsize),
39 Endnote(NonZeroUsize),
42 Paragraph(NonZeroUsize),
44 Table(NonZeroUsize),
46 Row(NonZeroUsize),
48 Cell(NonZeroUsize),
50 TextBox(NonZeroUsize),
52}
53
54impl AddressStep {
55 const fn letter(self) -> char {
57 match self {
58 Self::Header(_) => 'h',
59 Self::Footer(_) => 'f',
60 Self::Footnote(_) => 'n',
61 Self::Endnote(_) => 'e',
62 Self::Paragraph(_) => 'p',
63 Self::Table(_) => 't',
64 Self::Row(_) => 'r',
65 Self::Cell(_) => 'c',
66 Self::TextBox(_) => 'b',
67 }
68 }
69
70 const fn number(self) -> NonZeroUsize {
72 match self {
73 Self::Header(n)
74 | Self::Footer(n)
75 | Self::Footnote(n)
76 | Self::Endnote(n)
77 | Self::Paragraph(n)
78 | Self::Table(n)
79 | Self::Row(n)
80 | Self::Cell(n)
81 | Self::TextBox(n) => n,
82 }
83 }
84
85 const fn is_story(self) -> bool {
87 matches!(
88 self,
89 Self::Header(_) | Self::Footer(_) | Self::Footnote(_) | Self::Endnote(_)
90 )
91 }
92}
93
94#[derive(Clone, Debug, PartialEq, Eq, Hash)]
110pub struct Address {
111 steps: Vec<AddressStep>,
112}
113
114impl Address {
115 #[must_use]
117 pub fn steps(&self) -> &[AddressStep] {
118 &self.steps
119 }
120
121 #[must_use]
123 pub fn in_body(&self) -> bool {
124 !self
125 .steps
126 .iter()
127 .any(|step| step.is_story() || matches!(step, AddressStep::TextBox(_)))
128 }
129
130 pub(crate) fn then(&self, step: AddressStep) -> Self {
133 let mut steps = self.steps.clone();
134 steps.push(step);
135 Self { steps }
136 }
137
138 pub(crate) fn top(step: AddressStep) -> Self {
140 Self { steps: vec![step] }
141 }
142
143 pub(crate) fn within(cell: Option<&Self>, step: AddressStep) -> Self {
145 cell.map_or_else(|| Self::top(step), |cell| cell.then(step))
146 }
147
148 pub(crate) fn table_of_row(&self) -> Option<Self> {
150 match self.steps.split_last() {
151 Some((AddressStep::Row(_), table)) if !table.is_empty() => Some(Self {
152 steps: table.to_vec(),
153 }),
154 _ => None,
155 }
156 }
157
158 pub(crate) fn row_of_cell(&self) -> Option<(Self, NonZeroUsize)> {
161 match self.steps.split_last() {
162 Some((AddressStep::Cell(number), row)) => Some((
163 Self {
164 steps: row.to_vec(),
165 },
166 *number,
167 )),
168 _ => None,
169 }
170 }
171
172 pub(crate) fn container(&self) -> &[AddressStep] {
175 self.steps
176 .split_last()
177 .map_or(&[], |(_, container)| container)
178 }
179}
180
181impl fmt::Display for Address {
182 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183 for (index, step) in self.steps.iter().enumerate() {
184 if index > 0 {
185 f.write_str("/")?;
186 }
187 write!(f, "{}{}", step.letter(), step.number())?;
188 }
189 Ok(())
190 }
191}
192
193#[derive(Clone, Debug, PartialEq, Eq)]
195#[non_exhaustive]
196pub enum AddressError {
197 Empty,
199 Step {
201 step: String,
203 },
204 Order {
206 step: String,
208 expected: &'static str,
210 },
211 Unfinished {
213 expected: &'static str,
215 },
216}
217
218impl fmt::Display for AddressError {
219 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220 match self {
221 Self::Empty => f.write_str(
222 "the address is empty: name a paragraph or a table, such as p12 or t2/r4/c1/p1",
223 ),
224 Self::Step { step } => write!(
225 f,
226 "`{step}` is not a step of an address: write h, f, n, e, p, t, r, c or b and a \
227 number from 1, such as p12 or t2/r4/c1/p1"
228 ),
229 Self::Order { step, expected } => write!(
230 f,
231 "`{step}` cannot stand there: the address needs {expected}, as in t2/r4/c1/p1 \
232 or h1/p3/b1/p1"
233 ),
234 Self::Unfinished { expected } => write!(
235 f,
236 "the address ends too soon: it needs {expected}, as in h1/p3/b1/p1"
237 ),
238 }
239 }
240}
241
242impl std::error::Error for AddressError {}
243
244#[derive(Clone, Copy, PartialEq, Eq)]
246enum Next {
247 Start,
249 Block,
251 Row,
253 Cell,
255 BlockInCell,
257 TextBox,
259}
260
261impl Next {
262 const fn expected(self) -> &'static str {
264 match self {
265 Self::Start => "a story (h, f, n or e), a paragraph (p) or a table (t)",
266 Self::Block | Self::BlockInCell => "a paragraph (p) or a table (t)",
267 Self::Row => "a row (r) after a table",
268 Self::Cell => "a cell (c) after a row",
269 Self::TextBox => "a text box (b) or nothing after a paragraph",
270 }
271 }
272
273 const fn after(self, step: AddressStep) -> Option<Self> {
275 Some(match (self, step) {
276 (Self::Start, step) if step.is_story() => Self::Block,
277 (Self::Start | Self::Block | Self::BlockInCell, AddressStep::Paragraph(_)) => {
278 Self::TextBox
279 }
280 (Self::Start | Self::Block | Self::BlockInCell, AddressStep::Table(_)) => Self::Row,
281 (Self::TextBox, AddressStep::TextBox(_)) => Self::Block,
282 (Self::Row, AddressStep::Row(_)) => Self::Cell,
283 (Self::Cell, AddressStep::Cell(_)) => Self::BlockInCell,
284 _ => return None,
285 })
286 }
287}
288
289impl FromStr for Address {
290 type Err = AddressError;
291
292 fn from_str(text: &str) -> Result<Self, Self::Err> {
293 if text.is_empty() {
294 return Err(AddressError::Empty);
295 }
296 let mut steps = Vec::new();
297 let mut next = Next::Start;
298 for part in text.split('/') {
299 let step = read_step(part)?;
300 next = next.after(step).ok_or_else(|| AddressError::Order {
301 step: part.to_owned(),
302 expected: next.expected(),
303 })?;
304 steps.push(step);
305 }
306 if next == Next::Block {
307 return Err(AddressError::Unfinished {
308 expected: next.expected(),
309 });
310 }
311 Ok(Self { steps })
312 }
313}
314
315fn read_step(part: &str) -> Result<AddressStep, AddressError> {
317 let bad = || AddressError::Step {
318 step: part.to_owned(),
319 };
320 let mut chars = part.chars();
321 let kind = chars.next().ok_or_else(bad)?;
322 let digits = chars.as_str();
323 if digits.is_empty() || digits.starts_with('0') || !digits.bytes().all(|b| b.is_ascii_digit()) {
324 return Err(bad());
325 }
326 let number = digits.parse::<NonZeroUsize>().map_err(|_| bad())?;
327 Ok(match kind {
328 'h' => AddressStep::Header(number),
329 'f' => AddressStep::Footer(number),
330 'n' => AddressStep::Footnote(number),
331 'e' => AddressStep::Endnote(number),
332 'b' => AddressStep::TextBox(number),
333 'p' => AddressStep::Paragraph(number),
334 't' => AddressStep::Table(number),
335 'r' => AddressStep::Row(number),
336 'c' => AddressStep::Cell(number),
337 _ => return Err(bad()),
338 })
339}
340
341#[derive(Clone, Debug, PartialEq, Eq)]
343#[non_exhaustive]
344pub enum TextBlockKind {
345 Paragraph {
347 style: Option<String>,
349 text: String,
357 },
358 Table {
361 rows: usize,
363 },
364}
365
366#[derive(Clone, Debug, PartialEq, Eq)]
368#[non_exhaustive]
369pub struct TextBlock {
370 pub address: Address,
372 pub kind: TextBlockKind,
374 pub page_indices: Option<RangeInclusive<usize>>,
380 pub source: Option<Range<usize>>,
384 pub row_sources: Vec<Option<Range<usize>>>,
387 pub outline_level: Option<u8>,
391 pub toc_level: Option<u8>,
402}
403
404#[must_use]
408pub(crate) fn text_blocks(
409 blocks: &[Block],
410 lines: &[PlacedLine],
411 (styles, toc): (&Styles, Option<&TableOfContents>),
412) -> Vec<TextBlock> {
413 let mut pages: HashMap<ParagraphId, RangeInclusive<usize>> = HashMap::new();
414 for line in lines {
415 let page = line.page..=line.page;
416 let span = pages.remove(&line.paragraph);
417 if let Some(span) = widen(span, Some(&page)) {
418 pages.insert(line.paragraph, span);
419 }
420 }
421 let levels = toc_levels::toc_levels(blocks, styles, toc);
422 let mut out = Vec::new();
423 add_blocks(blocks, None, (&pages, styles, &levels), &mut out);
424 out
425}
426
427fn add_blocks(
430 blocks: &[Block],
431 within: Option<&Address>,
432 (pages, styles, levels): (
433 &HashMap<ParagraphId, RangeInclusive<usize>>,
434 &Styles,
435 &HashMap<ParagraphId, u8>,
436 ),
437 out: &mut Vec<TextBlock>,
438) -> Option<RangeInclusive<usize>> {
439 let (mut paragraphs, mut tables) = (0, 0);
440 let mut all = None;
441 for block in blocks {
442 let (block_address, kind, span, source, (outline_level, toc_level)) = match block {
443 Block::Paragraph(paragraph) => {
444 paragraphs += 1;
445 let kind = TextBlockKind::Paragraph {
446 style: paragraph.props.style.clone(),
447 text: paragraph_text(paragraph),
448 };
449 let step = AddressStep::Paragraph(number(paragraphs));
450 let source = paragraph.source.range();
451 let address = Address::within(within, step);
452 (
453 address,
454 kind,
455 pages.get(¶graph.id).cloned(),
456 source,
457 (
458 outline_level(paragraph, styles),
459 levels.get(¶graph.id).copied(),
460 ),
461 )
462 }
463 Block::Table(table) => {
464 tables += 1;
465 let table_address = Address::within(within, AddressStep::Table(number(tables)));
466 let at = out.len();
467 let mut span = None;
468 for (row_index, row) in table.rows.iter().enumerate() {
469 let row_address = table_address.then(AddressStep::Row(number(row_index + 1)));
470 for (cell_index, cell) in row.cells.iter().enumerate() {
471 let step = AddressStep::Cell(number(cell_index + 1));
472 let cell_span = add_blocks(
473 &cell.blocks,
474 Some(&row_address.then(step)),
475 (pages, styles, levels),
476 out,
477 );
478 span = widen(span, cell_span.as_ref());
479 }
480 }
481 let kind = TextBlockKind::Table {
482 rows: table.rows.len(),
483 };
484 out.insert(
486 at,
487 TextBlock {
488 address: table_address,
489 kind,
490 page_indices: span.clone(),
491 source: table.source.range(),
492 row_sources: table.rows.iter().map(|row| row.source.range()).collect(),
493 outline_level: None,
494 toc_level: None,
495 },
496 );
497 all = widen(all, span.as_ref());
498 continue;
499 }
500 };
501 all = widen(all, span.as_ref());
502 out.push(TextBlock {
503 address: block_address,
504 kind,
505 page_indices: span,
506 source,
507 row_sources: Vec::new(),
508 outline_level,
509 toc_level,
510 });
511 }
512 all
513}
514
515pub(super) fn outline_level(paragraph: &Paragraph, styles: &Styles) -> Option<u8> {
518 let props = styles.paragraph_properties_without_list_level(¶graph.props, None);
519 props
520 .outline_level
521 .filter(|level| *level < params::BODY_TEXT_OUTLINE_LEVEL)
522}
523
524fn widen(
527 pages: Option<RangeInclusive<usize>>,
528 more: Option<&RangeInclusive<usize>>,
529) -> Option<RangeInclusive<usize>> {
530 match (pages, more) {
531 (Some(a), Some(b)) => Some((*a.start()).min(*b.start())..=(*a.end()).max(*b.end())),
532 (a, b) => a.or_else(|| b.cloned()),
533 }
534}
535
536pub(crate) fn number(count: usize) -> NonZeroUsize {
539 NonZeroUsize::MIN.saturating_add(count.saturating_sub(1))
540}
541
542#[must_use]
544fn paragraph_text(paragraph: &Paragraph) -> String {
545 let mut text = String::new();
546 for content in paragraph.runs.iter().flat_map(|run| &run.content) {
547 match content {
548 Content::Text(piece) => text.push_str(piece),
549 Content::Tab | Content::PositionTab { .. } => text.push('\t'),
550 Content::LineBreak
551 | Content::ClearingBreak
552 | Content::PageBreak
553 | Content::ColumnBreak => text.push('\n'),
554 Content::CheckBox(check_box) => {
555 text.push(if check_box.checked { '☒' } else { '☐' });
556 }
557 Content::PageNumber => text.push_str("{PAGE}"),
558 Content::PageCount => text.push_str("{NUMPAGES}"),
559 Content::Date(field) => text.push_str(&field.stored),
560 Content::DocProperty(field) => text.push_str(&field.stored),
561 Content::StyleRef(field) => text.push_str(&field.stored),
562 Content::PageRef(field) => text.push_str(&field.stored),
563 Content::NumberRef(field) => text.push_str(&field.stored),
564 Content::If(field) => text.push_str(&field.stored),
565 Content::FootnoteReference(..) => text.push_str("{FOOTNOTE}"),
566 Content::EndnoteReference(..) => text.push_str("{ENDNOTE}"),
567 Content::Object { picture, .. } => {
568 text.push_str(if picture.is_some() {
569 PICTURE_MARKER
570 } else {
571 "{OBJECT}"
572 });
573 }
574 Content::Drawing(_) | Content::Floating(_) => text.push_str("{DRAWING}"),
575 Content::FieldBegin
576 | Content::FieldLock
577 | Content::DropDown(_)
578 | Content::FieldCode(_)
579 | Content::FieldSeparate
580 | Content::FieldEnd
581 | Content::Bookmark(_)
582 | Content::FieldMark
583 | Content::HyperlinkEdge
584 | Content::ControlEdge
585 | Content::RemovedEdge
586 | Content::CommentAnchor(_)
587 | Content::FootnoteMark
588 | Content::EndnoteMark
589 | Content::CommentMark
590 | Content::Separator
591 | Content::ContinuationSeparator
592 | Content::Stack(_)
593 | Content::Grown(_)
594 | Content::Radical(_)
595 | Content::Accent(_)
596 | Content::Matrix(_)
597 | Content::MathBar(_)
598 | Content::MathSlash(_)
599 | Content::MathLimit(_)
600 | Content::GroupChr(_)
601 | Content::MathBox(_)
602 | Content::Scripts(_)
603 | Content::Advance(_) => {}
604 }
605 }
606 text
607}
608
609mod toc_levels;
610
611#[cfg(test)]
612mod tests;