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
404pub(crate) struct IncrementalTextBlocks {
406 by_paragraph: HashMap<ParagraphId, Vec<usize>>,
407 spans: Vec<Option<RangeInclusive<usize>>>,
408}
409
410#[derive(Default)]
411struct BlockIndex {
412 enclosing: Vec<usize>,
413 by_paragraph: HashMap<ParagraphId, Vec<usize>>,
414}
415
416impl BlockIndex {
417 fn record_paragraph(&mut self, id: ParagraphId, block_idx: usize) {
418 let entry = self.by_paragraph.entry(id).or_default();
419 entry.push(block_idx);
420 entry.extend(self.enclosing.iter().copied());
421 }
422}
423
424impl IncrementalTextBlocks {
425 #[must_use]
429 pub(crate) fn new(
430 blocks: &[Block],
431 (styles, toc): (&Styles, Option<&TableOfContents>),
432 ) -> (Vec<TextBlock>, Self) {
433 let levels = toc_levels::toc_levels(blocks, styles, toc);
434 let empty_pages = HashMap::new();
435 let mut out = Vec::new();
436 let mut index = BlockIndex::default();
437 add_blocks_indexed(
438 blocks,
439 None,
440 (&empty_pages, styles, &levels),
441 Some(&mut index),
442 &mut out,
443 );
444 let spans = vec![None; out.len()];
445 (
446 out,
447 Self {
448 by_paragraph: index.by_paragraph,
449 spans,
450 },
451 )
452 }
453
454 pub(crate) fn update(&mut self, lines: &[PlacedLine]) -> Vec<(usize, RangeInclusive<usize>)> {
457 let mut dirty: Vec<usize> = Vec::new();
458 for line in lines {
459 let Some(indices) = self.by_paragraph.get(&line.paragraph) else {
460 continue;
461 };
462 let page = line.page..=line.page;
463 for &idx in indices {
464 let Some(slot) = self.spans.get_mut(idx) else {
465 continue;
466 };
467 let next = widen(slot.clone(), Some(&page));
468 if next != *slot {
469 *slot = next;
470 if !dirty.contains(&idx) {
471 dirty.push(idx);
472 }
473 }
474 }
475 }
476 dirty
477 .into_iter()
478 .filter_map(|idx| {
479 self.spans
480 .get(idx)
481 .and_then(Clone::clone)
482 .map(|span| (idx, span))
483 })
484 .collect()
485 }
486}
487
488#[must_use]
492pub(crate) fn text_blocks(
493 blocks: &[Block],
494 lines: &[PlacedLine],
495 (styles, toc): (&Styles, Option<&TableOfContents>),
496) -> Vec<TextBlock> {
497 let mut pages: HashMap<ParagraphId, RangeInclusive<usize>> = HashMap::new();
498 for line in lines {
499 let page = line.page..=line.page;
500 let span = pages.remove(&line.paragraph);
501 if let Some(span) = widen(span, Some(&page)) {
502 pages.insert(line.paragraph, span);
503 }
504 }
505 let levels = toc_levels::toc_levels(blocks, styles, toc);
506 let mut out = Vec::new();
507 add_blocks_indexed(blocks, None, (&pages, styles, &levels), None, &mut out);
508 out
509}
510
511fn add_blocks_indexed(
514 blocks: &[Block],
515 within: Option<&Address>,
516 context: (
517 &HashMap<ParagraphId, RangeInclusive<usize>>,
518 &Styles,
519 &HashMap<ParagraphId, u8>,
520 ),
521 mut index: Option<&mut BlockIndex>,
522 out: &mut Vec<TextBlock>,
523) -> Option<RangeInclusive<usize>> {
524 let (mut paragraphs, mut tables) = (0, 0);
525 let mut all = None;
526 for block in blocks {
527 let span = match block {
528 Block::Paragraph(paragraph) => {
529 paragraphs += 1;
530 push_paragraph_block(
531 paragraph,
532 within,
533 paragraphs,
534 context,
535 index.as_deref_mut(),
536 out,
537 )
538 }
539 Block::Table(table) => {
540 tables += 1;
541 push_table_block(table, within, tables, context, index.as_deref_mut(), out)
542 }
543 };
544 all = widen(all, span.as_ref());
545 }
546 all
547}
548
549fn push_paragraph_block(
550 paragraph: &Paragraph,
551 within: Option<&Address>,
552 ordinal: usize,
553 (pages, styles, levels): (
554 &HashMap<ParagraphId, RangeInclusive<usize>>,
555 &Styles,
556 &HashMap<ParagraphId, u8>,
557 ),
558 index: Option<&mut BlockIndex>,
559 out: &mut Vec<TextBlock>,
560) -> Option<RangeInclusive<usize>> {
561 let span = pages.get(¶graph.id).cloned();
562 let block_idx = out.len();
563 if let Some(index) = index {
564 index.record_paragraph(paragraph.id, block_idx);
565 }
566 out.push(TextBlock {
567 address: Address::within(within, AddressStep::Paragraph(number(ordinal))),
568 kind: TextBlockKind::Paragraph {
569 style: paragraph.props.style.clone(),
570 text: paragraph_text(paragraph),
571 },
572 page_indices: span.clone(),
573 source: paragraph.source.range(),
574 row_sources: Vec::new(),
575 outline_level: outline_level(paragraph, styles),
576 toc_level: levels.get(¶graph.id).copied(),
577 });
578 span
579}
580
581fn push_table_block(
582 table: &crate::table::Table,
583 within: Option<&Address>,
584 ordinal: usize,
585 context: (
586 &HashMap<ParagraphId, RangeInclusive<usize>>,
587 &Styles,
588 &HashMap<ParagraphId, u8>,
589 ),
590 mut index: Option<&mut BlockIndex>,
591 out: &mut Vec<TextBlock>,
592) -> Option<RangeInclusive<usize>> {
593 let table_address = Address::within(within, AddressStep::Table(number(ordinal)));
594 let at = out.len();
595 out.push(TextBlock {
597 address: table_address.clone(),
598 kind: TextBlockKind::Table {
599 rows: table.rows.len(),
600 },
601 page_indices: None,
602 source: table.source.range(),
603 row_sources: table.rows.iter().map(|row| row.source.range()).collect(),
604 outline_level: None,
605 toc_level: None,
606 });
607 if let Some(index) = index.as_deref_mut() {
608 index.enclosing.push(at);
609 }
610 let mut span = None;
611 for (row_index, row) in table.rows.iter().enumerate() {
612 let row_address = table_address.then(AddressStep::Row(number(row_index + 1)));
613 for (cell_index, cell) in row.cells.iter().enumerate() {
614 let step = AddressStep::Cell(number(cell_index + 1));
615 let cell_span = add_blocks_indexed(
616 &cell.blocks,
617 Some(&row_address.then(step)),
618 context,
619 index.as_deref_mut(),
620 out,
621 );
622 span = widen(span, cell_span.as_ref());
623 }
624 }
625 if let Some(index) = index {
626 let _ = index.enclosing.pop();
627 }
628 if let Some(table_block) = out.get_mut(at) {
629 table_block.page_indices.clone_from(&span);
630 }
631 span
632}
633
634pub(super) fn outline_level(paragraph: &Paragraph, styles: &Styles) -> Option<u8> {
637 let props = styles.paragraph_properties_without_list_level(¶graph.props, None);
638 props
639 .outline_level
640 .filter(|level| *level < params::BODY_TEXT_OUTLINE_LEVEL)
641}
642
643fn widen(
646 pages: Option<RangeInclusive<usize>>,
647 more: Option<&RangeInclusive<usize>>,
648) -> Option<RangeInclusive<usize>> {
649 match (pages, more) {
650 (Some(a), Some(b)) => Some((*a.start()).min(*b.start())..=(*a.end()).max(*b.end())),
651 (a, b) => a.or_else(|| b.cloned()),
652 }
653}
654
655pub(crate) fn number(count: usize) -> NonZeroUsize {
658 NonZeroUsize::MIN.saturating_add(count.saturating_sub(1))
659}
660
661#[must_use]
663fn paragraph_text(paragraph: &Paragraph) -> String {
664 let mut text = String::new();
665 for content in paragraph.runs.iter().flat_map(|run| &run.content) {
666 match content {
667 Content::Text(piece) => text.push_str(piece),
668 Content::Tab | Content::PositionTab { .. } => text.push('\t'),
669 Content::LineBreak
670 | Content::ClearingBreak
671 | Content::PageBreak
672 | Content::ColumnBreak => text.push('\n'),
673 Content::CheckBox(check_box) => {
674 text.push(if check_box.checked { '☒' } else { '☐' });
675 }
676 Content::PageNumber => text.push_str("{PAGE}"),
677 Content::PageCount => text.push_str("{NUMPAGES}"),
678 Content::Date(field) => text.push_str(&field.stored),
679 Content::DocProperty(field) => text.push_str(&field.stored),
680 Content::FileName(field) => text.push_str(&field.stored),
681 Content::StyleRef(field) => text.push_str(&field.stored),
682 Content::PageRef(field) => text.push_str(&field.stored),
683 Content::NumberRef(field) => text.push_str(&field.stored),
684 Content::If(field) => text.push_str(&field.stored),
685 Content::FootnoteReference(..) => text.push_str("{FOOTNOTE}"),
686 Content::EndnoteReference(..) => text.push_str("{ENDNOTE}"),
687 Content::Object { picture, .. } => {
688 text.push_str(if picture.is_some() {
689 PICTURE_MARKER
690 } else {
691 "{OBJECT}"
692 });
693 }
694 Content::Drawing(_) | Content::Floating(_) => text.push_str("{DRAWING}"),
695 Content::FieldBegin
696 | Content::FieldLock
697 | Content::DropDown(_)
698 | Content::FieldCode(_)
699 | Content::FieldSeparate
700 | Content::FieldEnd
701 | Content::Bookmark(_)
702 | Content::FieldMark
703 | Content::HyperlinkEdge
704 | Content::ControlEdge
705 | Content::RemovedEdge
706 | Content::CommentAnchor(_)
707 | Content::FootnoteMark
708 | Content::EndnoteMark
709 | Content::CommentMark
710 | Content::Separator
711 | Content::ContinuationSeparator
712 | Content::Stack(_)
713 | Content::Grown(_)
714 | Content::Radical(_)
715 | Content::Accent(_)
716 | Content::Matrix(_)
717 | Content::MathBar(_)
718 | Content::MathSlash(_)
719 | Content::MathLimit(_)
720 | Content::GroupChr(_)
721 | Content::MathBox(_)
722 | Content::Scripts(_)
723 | Content::Advance(_) => {}
724 }
725 }
726 text
727}
728
729mod toc_levels;
730
731#[cfg(test)]
732mod tests;