1use std::collections::HashMap;
6use std::collections::hash_map::Entry;
7
8use f_office_units::Length;
9
10use crate::body::ParagraphId;
11use crate::body::links::LinkTarget;
12use crate::layout::{
13 CellPlace, LineStory, LineText, LineTextEnd, LineTurn, PlacedLine, RunSpan, StoryPart,
14 TextCluster,
15};
16use crate::lines::EndHyphen;
17use crate::text_blocks::Address;
18use crate::text_links::RunMarks;
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
25pub enum TextStory {
26 Header {
28 page: usize,
30 },
31 Body,
33 Endnotes,
35 Frame {
37 page: usize,
39 number: u32,
42 },
43 TextBox {
45 page: usize,
47 number: u32,
50 },
51 Footnotes,
53 Footer {
55 page: usize,
57 },
58}
59
60impl TextStory {
61 pub const RUNNING: [Self; 3] = [Self::Body, Self::Footnotes, Self::Endnotes];
63
64 const fn of_placed(line: &PlacedLine) -> Self {
66 Self::from_parts(line.page, line.story, line.part)
67 }
68
69 const fn of_compact(line: &CompactLine) -> Self {
72 Self::from_parts(line.page, line.story, line.part)
73 }
74
75 const fn from_parts(page: usize, story: LineStory, part: StoryPart) -> Self {
76 match (story, part) {
77 (LineStory::Header, _) => Self::Header { page },
78 (LineStory::Footer, _) => Self::Footer { page },
79 (LineStory::Footnote, _) => Self::Footnotes,
80 (LineStory::Body | LineStory::TextBox, StoryPart::Endnotes) => Self::Endnotes,
81 (LineStory::Body | LineStory::TextBox, StoryPart::Frame(number)) => {
82 Self::Frame { page, number }
83 }
84 (LineStory::Body | LineStory::TextBox, StoryPart::TextBox(number)) => {
85 Self::TextBox { page, number }
86 }
87 (LineStory::Body, StoryPart::Own) => Self::Body,
88 (LineStory::TextBox, StoryPart::Own) => Self::TextBox { page, number: 0 },
89 }
90 }
91}
92
93#[derive(Clone, Debug, Default, PartialEq, Eq)]
97pub struct StoryParagraph {
98 pub address: Option<Address>,
100 pub cell: Option<CellPlace>,
102 pub text: String,
105 pub links: Vec<StoryLink>,
108 pub bookmarks: Vec<StoryBookmark>,
110}
111
112#[derive(Clone, Debug, PartialEq, Eq)]
115#[non_exhaustive]
116pub struct StoryLink {
117 pub start_byte: u32,
119 pub end_byte: u32,
121 pub target: LinkTarget,
123 pub tooltip: Option<String>,
125}
126
127impl StoryLink {
128 pub(crate) const fn new(
131 start_byte: u32,
132 end_byte: u32,
133 target: LinkTarget,
134 tooltip: Option<String>,
135 ) -> Self {
136 Self {
137 start_byte,
138 end_byte,
139 target,
140 tooltip,
141 }
142 }
143}
144
145#[derive(Clone, Debug, PartialEq, Eq)]
147#[non_exhaustive]
148pub struct StoryBookmark {
149 pub name: String,
151 pub offset_byte: u32,
154}
155
156impl StoryBookmark {
157 pub(crate) const fn new(name: String, offset_byte: u32) -> Self {
159 Self { name, offset_byte }
160 }
161}
162
163#[derive(Clone, Debug, PartialEq, Eq)]
166pub struct TextLine {
167 pub story: TextStory,
169 pub paragraph: usize,
171 pub start: u32,
173 pub end: u32,
175 pub top: Length,
178 pub height: Length,
180 pub baseline: Length,
182 pub clusters: Vec<TextCluster>,
184 pub left: Length,
188 pub ends: LineTextEnd,
190 pub hyphen: Option<EndHyphen>,
193 pub turn: Option<LineTurn>,
197}
198
199#[derive(Clone, Debug)]
202struct CompactLine {
203 paragraph: ParagraphId,
204 page: usize,
205 story: LineStory,
206 part: StoryPart,
207 cell: Option<CellPlace>,
208 top: Length,
209 height: Length,
210 baseline: Length,
211 text: LineText,
212}
213
214impl CompactLine {
215 fn from_ref(line: &PlacedLine) -> Self {
216 Self {
217 paragraph: line.paragraph,
218 page: line.page,
219 story: line.story,
220 part: line.part,
221 cell: line.cell,
222 top: line.top,
223 height: line.height,
224 baseline: line.baseline,
225 text: line.text.clone(),
226 }
227 }
228
229 fn from_owned(line: PlacedLine) -> Self {
230 Self {
231 paragraph: line.paragraph,
232 page: line.page,
233 story: line.story,
234 part: line.part,
235 cell: line.cell,
236 top: line.top,
237 height: line.height,
238 baseline: line.baseline,
239 text: line.text,
240 }
241 }
242}
243
244#[derive(Clone, Debug, Default)]
246pub struct TextMapDelta(Vec<CompactLine>);
247
248impl TextMapDelta {
249 #[must_use]
251 pub fn is_empty(&self) -> bool {
252 self.0.is_empty()
253 }
254}
255
256#[derive(Clone, Debug, Default)]
260pub struct TextMap {
261 addresses: HashMap<ParagraphId, Address>,
262 marks: HashMap<ParagraphId, RunMarks>,
263 lines: Vec<CompactLine>,
264}
265
266impl TextMap {
267 pub(crate) fn from_paragraphs(
270 (addresses, marks): (
271 HashMap<ParagraphId, Address>,
272 HashMap<ParagraphId, RunMarks>,
273 ),
274 ) -> Self {
275 Self {
276 addresses,
277 marks,
278 lines: Vec::new(),
279 }
280 }
281
282 pub(crate) fn delta_from_placed(placed: Vec<PlacedLine>) -> TextMapDelta {
285 let (upright, turned) = turned_apart(placed);
286 let mut turned = turned.into_iter().peekable();
287 let mut lines = Vec::with_capacity(upright.len() + turned.len());
288 for (index, line) in upright.into_iter().enumerate() {
289 while let Some((_, before)) = turned.next_if(|&(at, _)| at <= index) {
290 lines.push(CompactLine::from_owned(before));
291 }
292 lines.push(CompactLine::from_owned(line));
293 }
294 lines.extend(turned.map(|(_, line)| CompactLine::from_owned(line)));
295 TextMapDelta(lines)
296 }
297
298 pub fn extend_delta(&mut self, delta: TextMapDelta) {
300 self.lines.extend(delta.0);
301 }
302
303 pub(crate) fn new(
306 (addresses, marks): (
307 HashMap<ParagraphId, Address>,
308 HashMap<ParagraphId, RunMarks>,
309 ),
310 upright: &[PlacedLine],
311 turned: Vec<(usize, PlacedLine)>,
312 ) -> Self {
313 let mut turned = turned.into_iter().peekable();
314 let mut lines = Vec::with_capacity(upright.len() + turned.len());
315 for (index, line) in upright.iter().enumerate() {
316 while let Some((_, before)) = turned.next_if(|&(at, _)| at <= index) {
317 lines.push(CompactLine::from_owned(before));
318 }
319 lines.push(CompactLine::from_ref(line));
320 }
321 lines.extend(turned.map(|(_, line)| CompactLine::from_owned(line)));
322 Self {
323 addresses,
324 marks,
325 lines,
326 }
327 }
328
329 #[must_use]
333 pub fn page(&self, page: usize) -> Vec<TextLine> {
334 self.pages(&[page]).pop().unwrap_or_default()
335 }
336
337 #[must_use]
342 pub fn pages(&self, pages: &[usize]) -> Vec<Vec<TextLine>> {
343 let slots: HashMap<usize, usize> = pages
344 .iter()
345 .enumerate()
346 .map(|(slot, &page)| (page, slot))
347 .collect();
348 let mut stories: Vec<TextStory> = self
349 .lines
350 .iter()
351 .filter(|line| slots.contains_key(&line.page))
352 .map(TextStory::of_compact)
353 .collect();
354 stories.sort_unstable();
355 stories.dedup();
356 let mut maps = vec![Vec::new(); pages.len()];
357 for story in stories {
358 for (line, text_line) in self.read(story).lines {
359 if let Some(map) = slots.get(&line.page).and_then(|&slot| maps.get_mut(slot)) {
360 map.push(text_line);
361 }
362 }
363 }
364 maps
365 }
366
367 #[must_use]
369 pub fn story(&self, story: TextStory) -> Vec<StoryParagraph> {
370 self.read(story).paragraphs
371 }
372
373 fn read(&self, story: TextStory) -> Read<'_> {
377 let mut read = Read::default();
378 let mut indices: HashMap<ParagraphId, usize> = HashMap::new();
379 let mut spans: Vec<(ParagraphId, Vec<RunSpan>)> = Vec::new();
381 for line in self
382 .lines
383 .iter()
384 .filter(|line| TextStory::of_compact(line) == story)
385 {
386 let text = &line.text;
387 let paragraph = match indices.entry(line.paragraph) {
388 Entry::Occupied(entry) => *entry.get(),
389 Entry::Vacant(entry) => {
390 read.paragraphs.push(StoryParagraph {
391 address: self.addresses.get(&line.paragraph).cloned(),
392 cell: line.cell,
393 ..StoryParagraph::default()
394 });
395 spans.push((line.paragraph, Vec::new()));
396 *entry.insert(read.paragraphs.len() - 1)
397 }
398 };
399 let Some(own) = read.paragraphs.get_mut(paragraph) else {
400 continue;
401 };
402 let start = text_offset(own.text.len());
403 own.text.push_str(&text.text);
404 if let Some((_, own_spans)) = spans.get_mut(paragraph) {
405 own_spans.extend(text.runs.iter().map(|span| RunSpan {
406 start: span.start.saturating_add(start),
407 end: span.end.saturating_add(start),
408 run: span.run,
409 }));
410 }
411 read.lines
412 .push((line, text_line(line, text, (story, paragraph), start)));
413 }
414 for ((id, own_spans), own) in spans.iter().zip(&mut read.paragraphs) {
415 if let Some(marks) = self.marks.get(id) {
416 (own.links, own.bookmarks) = marks.placed(own_spans, text_offset(own.text.len()));
417 }
418 }
419 let cells: Vec<Option<CellPlace>> = read.paragraphs.iter().map(|p| p.cell).collect();
421 for (_, text_line) in &mut read.lines {
422 let paragraph = text_line.paragraph;
423 let cell = cells.get(paragraph).copied().flatten();
424 let next = cells.get(paragraph + 1).copied().flatten();
425 if text_line.ends == LineTextEnd::Paragraph && cell.is_some() && next != cell {
426 text_line.ends = LineTextEnd::Cell;
427 }
428 }
429 read
430 }
431}
432
433#[derive(Default)]
436struct Read<'a> {
437 paragraphs: Vec<StoryParagraph>,
438 lines: Vec<(&'a CompactLine, TextLine)>,
439}
440
441fn text_line(
444 line: &CompactLine,
445 text: &LineText,
446 (story, paragraph): (TextStory, usize),
447 start: u32,
448) -> TextLine {
449 TextLine {
450 story,
451 paragraph,
452 start,
453 end: start + text_offset(text.text.len()),
454 top: line.top,
455 height: line.height,
456 baseline: line.baseline,
457 clusters: text
458 .clusters
459 .iter()
460 .map(|cluster| TextCluster {
461 start: start + cluster.start,
462 end: start + cluster.end,
463 ..*cluster
464 })
465 .collect(),
466 left: text.left,
467 ends: text.end,
468 hyphen: text.hyphen,
469 turn: text.turn,
470 }
471}
472
473pub(crate) fn turned_apart(lines: Vec<PlacedLine>) -> (Vec<PlacedLine>, Vec<(usize, PlacedLine)>) {
479 let mut upright: Vec<PlacedLine> = Vec::with_capacity(lines.len());
480 let mut turned: Vec<(usize, PlacedLine)> = Vec::new();
481 let mut run: Vec<PlacedLine> = Vec::new();
482 for line in lines {
483 if line.upright() {
484 turned.extend(place_run(&upright, std::mem::take(&mut run)));
485 upright.push(line);
486 } else {
487 run.push(line);
488 }
489 }
490 turned.extend(place_run(&upright, run));
491 turned.sort_by_key(|&(before, _)| before);
492 (upright, turned)
493}
494
495fn place_run(upright: &[PlacedLine], run: Vec<PlacedLine>) -> Vec<(usize, PlacedLine)> {
501 let outer = run
502 .iter()
503 .filter_map(|line| line.cell)
504 .map(|cell| cell.table)
505 .min();
506 let of_outer = |line: &PlacedLine| {
507 line.cell
508 .filter(|cell| Some(cell.table) == outer)
509 .map(|cell| (cell, TextStory::of_placed(line)))
510 };
511 let mut frame = run.iter().find_map(of_outer);
512 let mut found: Option<((CellPlace, TextStory), usize)> = None;
513 let mut placed = Vec::with_capacity(run.len());
514 for line in run {
515 frame = of_outer(&line).or(frame);
516 let before = match (frame, found) {
517 (Some(cell), Some((known, before))) if known == cell => before,
518 (Some(cell), _) => {
519 let before = before_later_cells(upright, cell);
520 found = Some((cell, before));
521 before
522 }
523 (None, _) => upright.len(),
524 };
525 placed.push((before, line));
526 }
527 placed
528}
529
530fn before_later_cells(upright: &[PlacedLine], (cell, story): (CellPlace, TextStory)) -> usize {
534 let mut before = upright.len();
535 for (index, other) in upright.iter().enumerate().rev() {
536 let Some(other_cell) = other.cell.filter(|_| TextStory::of_placed(other) == story) else {
537 continue;
538 };
539 if other_cell.table == cell.table && other_cell.row < cell.row {
540 break;
541 }
542 if other_cell.table == cell.table
543 && other_cell.row == cell.row
544 && other_cell.column > cell.column
545 {
546 before = index;
547 }
548 }
549 before
550}
551
552pub(crate) fn text_offset(bytes: usize) -> u32 {
554 u32::try_from(bytes).unwrap_or(u32::MAX)
555}