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)]
248pub struct TextMap {
249 addresses: HashMap<ParagraphId, Address>,
250 marks: HashMap<ParagraphId, RunMarks>,
251 lines: Vec<CompactLine>,
252}
253
254impl TextMap {
255 pub(crate) fn new(
258 (addresses, marks): (
259 HashMap<ParagraphId, Address>,
260 HashMap<ParagraphId, RunMarks>,
261 ),
262 upright: &[PlacedLine],
263 turned: Vec<(usize, PlacedLine)>,
264 ) -> Self {
265 let mut turned = turned.into_iter().peekable();
266 let mut lines = Vec::with_capacity(upright.len() + turned.len());
267 for (index, line) in upright.iter().enumerate() {
268 while let Some((_, before)) = turned.next_if(|&(at, _)| at <= index) {
269 lines.push(CompactLine::from_owned(before));
270 }
271 lines.push(CompactLine::from_ref(line));
272 }
273 lines.extend(turned.map(|(_, line)| CompactLine::from_owned(line)));
274 Self {
275 addresses,
276 marks,
277 lines,
278 }
279 }
280
281 #[must_use]
285 pub fn page(&self, page: usize) -> Vec<TextLine> {
286 self.pages(&[page]).pop().unwrap_or_default()
287 }
288
289 #[must_use]
294 pub fn pages(&self, pages: &[usize]) -> Vec<Vec<TextLine>> {
295 let slots: HashMap<usize, usize> = pages
296 .iter()
297 .enumerate()
298 .map(|(slot, &page)| (page, slot))
299 .collect();
300 let mut stories: Vec<TextStory> = self
301 .lines
302 .iter()
303 .filter(|line| slots.contains_key(&line.page))
304 .map(TextStory::of_compact)
305 .collect();
306 stories.sort_unstable();
307 stories.dedup();
308 let mut maps = vec![Vec::new(); pages.len()];
309 for story in stories {
310 for (line, text_line) in self.read(story).lines {
311 if let Some(map) = slots.get(&line.page).and_then(|&slot| maps.get_mut(slot)) {
312 map.push(text_line);
313 }
314 }
315 }
316 maps
317 }
318
319 #[must_use]
321 pub fn story(&self, story: TextStory) -> Vec<StoryParagraph> {
322 self.read(story).paragraphs
323 }
324
325 fn read(&self, story: TextStory) -> Read<'_> {
329 let mut read = Read::default();
330 let mut indices: HashMap<ParagraphId, usize> = HashMap::new();
331 let mut spans: Vec<(ParagraphId, Vec<RunSpan>)> = Vec::new();
333 for line in self
334 .lines
335 .iter()
336 .filter(|line| TextStory::of_compact(line) == story)
337 {
338 let text = &line.text;
339 let paragraph = match indices.entry(line.paragraph) {
340 Entry::Occupied(entry) => *entry.get(),
341 Entry::Vacant(entry) => {
342 read.paragraphs.push(StoryParagraph {
343 address: self.addresses.get(&line.paragraph).cloned(),
344 cell: line.cell,
345 ..StoryParagraph::default()
346 });
347 spans.push((line.paragraph, Vec::new()));
348 *entry.insert(read.paragraphs.len() - 1)
349 }
350 };
351 let Some(own) = read.paragraphs.get_mut(paragraph) else {
352 continue;
353 };
354 let start = text_offset(own.text.len());
355 own.text.push_str(&text.text);
356 if let Some((_, own_spans)) = spans.get_mut(paragraph) {
357 own_spans.extend(text.runs.iter().map(|span| RunSpan {
358 start: span.start.saturating_add(start),
359 end: span.end.saturating_add(start),
360 run: span.run,
361 }));
362 }
363 read.lines
364 .push((line, text_line(line, text, (story, paragraph), start)));
365 }
366 for ((id, own_spans), own) in spans.iter().zip(&mut read.paragraphs) {
367 if let Some(marks) = self.marks.get(id) {
368 (own.links, own.bookmarks) = marks.placed(own_spans, text_offset(own.text.len()));
369 }
370 }
371 let cells: Vec<Option<CellPlace>> = read.paragraphs.iter().map(|p| p.cell).collect();
373 for (_, text_line) in &mut read.lines {
374 let paragraph = text_line.paragraph;
375 let cell = cells.get(paragraph).copied().flatten();
376 let next = cells.get(paragraph + 1).copied().flatten();
377 if text_line.ends == LineTextEnd::Paragraph && cell.is_some() && next != cell {
378 text_line.ends = LineTextEnd::Cell;
379 }
380 }
381 read
382 }
383}
384
385#[derive(Default)]
388struct Read<'a> {
389 paragraphs: Vec<StoryParagraph>,
390 lines: Vec<(&'a CompactLine, TextLine)>,
391}
392
393fn text_line(
396 line: &CompactLine,
397 text: &LineText,
398 (story, paragraph): (TextStory, usize),
399 start: u32,
400) -> TextLine {
401 TextLine {
402 story,
403 paragraph,
404 start,
405 end: start + text_offset(text.text.len()),
406 top: line.top,
407 height: line.height,
408 baseline: line.baseline,
409 clusters: text
410 .clusters
411 .iter()
412 .map(|cluster| TextCluster {
413 start: start + cluster.start,
414 end: start + cluster.end,
415 ..*cluster
416 })
417 .collect(),
418 left: text.left,
419 ends: text.end,
420 hyphen: text.hyphen,
421 turn: text.turn,
422 }
423}
424
425pub(crate) fn turned_apart(lines: Vec<PlacedLine>) -> (Vec<PlacedLine>, Vec<(usize, PlacedLine)>) {
431 let mut upright: Vec<PlacedLine> = Vec::with_capacity(lines.len());
432 let mut turned: Vec<(usize, PlacedLine)> = Vec::new();
433 let mut run: Vec<PlacedLine> = Vec::new();
434 for line in lines {
435 if line.upright() {
436 turned.extend(place_run(&upright, std::mem::take(&mut run)));
437 upright.push(line);
438 } else {
439 run.push(line);
440 }
441 }
442 turned.extend(place_run(&upright, run));
443 turned.sort_by_key(|&(before, _)| before);
444 (upright, turned)
445}
446
447fn place_run(upright: &[PlacedLine], run: Vec<PlacedLine>) -> Vec<(usize, PlacedLine)> {
453 let outer = run
454 .iter()
455 .filter_map(|line| line.cell)
456 .map(|cell| cell.table)
457 .min();
458 let of_outer = |line: &PlacedLine| {
459 line.cell
460 .filter(|cell| Some(cell.table) == outer)
461 .map(|cell| (cell, TextStory::of_placed(line)))
462 };
463 let mut frame = run.iter().find_map(of_outer);
464 let mut found: Option<((CellPlace, TextStory), usize)> = None;
465 let mut placed = Vec::with_capacity(run.len());
466 for line in run {
467 frame = of_outer(&line).or(frame);
468 let before = match (frame, found) {
469 (Some(cell), Some((known, before))) if known == cell => before,
470 (Some(cell), _) => {
471 let before = before_later_cells(upright, cell);
472 found = Some((cell, before));
473 before
474 }
475 (None, _) => upright.len(),
476 };
477 placed.push((before, line));
478 }
479 placed
480}
481
482fn before_later_cells(upright: &[PlacedLine], (cell, story): (CellPlace, TextStory)) -> usize {
486 let mut before = upright.len();
487 for (index, other) in upright.iter().enumerate().rev() {
488 let Some(other_cell) = other.cell.filter(|_| TextStory::of_placed(other) == story) else {
489 continue;
490 };
491 if other_cell.table == cell.table && other_cell.row < cell.row {
492 break;
493 }
494 if other_cell.table == cell.table
495 && other_cell.row == cell.row
496 && other_cell.column > cell.column
497 {
498 before = index;
499 }
500 }
501 before
502}
503
504pub(crate) fn text_offset(bytes: usize) -> u32 {
506 u32::try_from(bytes).unwrap_or(u32::MAX)
507}