use std::collections::HashMap;
use std::collections::hash_map::Entry;
use f_office_units::Length;
use crate::body::ParagraphId;
use crate::body::links::LinkTarget;
use crate::layout::{
CellPlace, LineStory, LineText, LineTextEnd, LineTurn, PlacedLine, RunSpan, StoryPart,
TextCluster,
};
use crate::lines::EndHyphen;
use crate::text_blocks::Address;
use crate::text_links::RunMarks;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TextStory {
Header {
page: usize,
},
Body,
Endnotes,
Frame {
page: usize,
number: u32,
},
TextBox {
page: usize,
number: u32,
},
Footnotes,
Footer {
page: usize,
},
}
impl TextStory {
pub const RUNNING: [Self; 3] = [Self::Body, Self::Footnotes, Self::Endnotes];
const fn of_placed(line: &PlacedLine) -> Self {
Self::from_parts(line.page, line.story, line.part)
}
const fn of_compact(line: &CompactLine) -> Self {
Self::from_parts(line.page, line.story, line.part)
}
const fn from_parts(page: usize, story: LineStory, part: StoryPart) -> Self {
match (story, part) {
(LineStory::Header, _) => Self::Header { page },
(LineStory::Footer, _) => Self::Footer { page },
(LineStory::Footnote, _) => Self::Footnotes,
(LineStory::Body | LineStory::TextBox, StoryPart::Endnotes) => Self::Endnotes,
(LineStory::Body | LineStory::TextBox, StoryPart::Frame(number)) => {
Self::Frame { page, number }
}
(LineStory::Body | LineStory::TextBox, StoryPart::TextBox(number)) => {
Self::TextBox { page, number }
}
(LineStory::Body, StoryPart::Own) => Self::Body,
(LineStory::TextBox, StoryPart::Own) => Self::TextBox { page, number: 0 },
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct StoryParagraph {
pub address: Option<Address>,
pub cell: Option<CellPlace>,
pub text: String,
pub links: Vec<StoryLink>,
pub bookmarks: Vec<StoryBookmark>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct StoryLink {
pub start_byte: u32,
pub end_byte: u32,
pub target: LinkTarget,
pub tooltip: Option<String>,
}
impl StoryLink {
pub(crate) const fn new(
start_byte: u32,
end_byte: u32,
target: LinkTarget,
tooltip: Option<String>,
) -> Self {
Self {
start_byte,
end_byte,
target,
tooltip,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct StoryBookmark {
pub name: String,
pub offset_byte: u32,
}
impl StoryBookmark {
pub(crate) const fn new(name: String, offset_byte: u32) -> Self {
Self { name, offset_byte }
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextLine {
pub story: TextStory,
pub paragraph: usize,
pub start: u32,
pub end: u32,
pub top: Length,
pub height: Length,
pub baseline: Length,
pub clusters: Vec<TextCluster>,
pub left: Length,
pub ends: LineTextEnd,
pub hyphen: Option<EndHyphen>,
pub turn: Option<LineTurn>,
}
#[derive(Clone, Debug)]
struct CompactLine {
paragraph: ParagraphId,
page: usize,
story: LineStory,
part: StoryPart,
cell: Option<CellPlace>,
top: Length,
height: Length,
baseline: Length,
text: LineText,
}
impl CompactLine {
fn from_ref(line: &PlacedLine) -> Self {
Self {
paragraph: line.paragraph,
page: line.page,
story: line.story,
part: line.part,
cell: line.cell,
top: line.top,
height: line.height,
baseline: line.baseline,
text: line.text.clone(),
}
}
fn from_owned(line: PlacedLine) -> Self {
Self {
paragraph: line.paragraph,
page: line.page,
story: line.story,
part: line.part,
cell: line.cell,
top: line.top,
height: line.height,
baseline: line.baseline,
text: line.text,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct TextMapDelta(Vec<CompactLine>);
impl TextMapDelta {
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
#[derive(Clone, Debug, Default)]
pub struct TextMap {
addresses: HashMap<ParagraphId, Address>,
marks: HashMap<ParagraphId, RunMarks>,
lines: Vec<CompactLine>,
}
impl TextMap {
pub(crate) fn from_paragraphs(
(addresses, marks): (
HashMap<ParagraphId, Address>,
HashMap<ParagraphId, RunMarks>,
),
) -> Self {
Self {
addresses,
marks,
lines: Vec::new(),
}
}
pub(crate) fn delta_from_placed(placed: Vec<PlacedLine>) -> TextMapDelta {
let (upright, turned) = turned_apart(placed);
let mut turned = turned.into_iter().peekable();
let mut lines = Vec::with_capacity(upright.len() + turned.len());
for (index, line) in upright.into_iter().enumerate() {
while let Some((_, before)) = turned.next_if(|&(at, _)| at <= index) {
lines.push(CompactLine::from_owned(before));
}
lines.push(CompactLine::from_owned(line));
}
lines.extend(turned.map(|(_, line)| CompactLine::from_owned(line)));
TextMapDelta(lines)
}
pub fn extend_delta(&mut self, delta: TextMapDelta) {
self.lines.extend(delta.0);
}
pub(crate) fn new(
(addresses, marks): (
HashMap<ParagraphId, Address>,
HashMap<ParagraphId, RunMarks>,
),
upright: &[PlacedLine],
turned: Vec<(usize, PlacedLine)>,
) -> Self {
let mut turned = turned.into_iter().peekable();
let mut lines = Vec::with_capacity(upright.len() + turned.len());
for (index, line) in upright.iter().enumerate() {
while let Some((_, before)) = turned.next_if(|&(at, _)| at <= index) {
lines.push(CompactLine::from_owned(before));
}
lines.push(CompactLine::from_ref(line));
}
lines.extend(turned.map(|(_, line)| CompactLine::from_owned(line)));
Self {
addresses,
marks,
lines,
}
}
#[must_use]
pub fn page(&self, page: usize) -> Vec<TextLine> {
self.pages(&[page]).pop().unwrap_or_default()
}
#[must_use]
pub fn pages(&self, pages: &[usize]) -> Vec<Vec<TextLine>> {
let slots: HashMap<usize, usize> = pages
.iter()
.enumerate()
.map(|(slot, &page)| (page, slot))
.collect();
let mut stories: Vec<TextStory> = self
.lines
.iter()
.filter(|line| slots.contains_key(&line.page))
.map(TextStory::of_compact)
.collect();
stories.sort_unstable();
stories.dedup();
let mut maps = vec![Vec::new(); pages.len()];
for story in stories {
for (line, text_line) in self.read(story).lines {
if let Some(map) = slots.get(&line.page).and_then(|&slot| maps.get_mut(slot)) {
map.push(text_line);
}
}
}
maps
}
#[must_use]
pub fn story(&self, story: TextStory) -> Vec<StoryParagraph> {
self.read(story).paragraphs
}
fn read(&self, story: TextStory) -> Read<'_> {
let mut read = Read::default();
let mut indices: HashMap<ParagraphId, usize> = HashMap::new();
let mut spans: Vec<(ParagraphId, Vec<RunSpan>)> = Vec::new();
for line in self
.lines
.iter()
.filter(|line| TextStory::of_compact(line) == story)
{
let text = &line.text;
let paragraph = match indices.entry(line.paragraph) {
Entry::Occupied(entry) => *entry.get(),
Entry::Vacant(entry) => {
read.paragraphs.push(StoryParagraph {
address: self.addresses.get(&line.paragraph).cloned(),
cell: line.cell,
..StoryParagraph::default()
});
spans.push((line.paragraph, Vec::new()));
*entry.insert(read.paragraphs.len() - 1)
}
};
let Some(own) = read.paragraphs.get_mut(paragraph) else {
continue;
};
let start = text_offset(own.text.len());
own.text.push_str(&text.text);
if let Some((_, own_spans)) = spans.get_mut(paragraph) {
own_spans.extend(text.runs.iter().map(|span| RunSpan {
start: span.start.saturating_add(start),
end: span.end.saturating_add(start),
run: span.run,
}));
}
read.lines
.push((line, text_line(line, text, (story, paragraph), start)));
}
for ((id, own_spans), own) in spans.iter().zip(&mut read.paragraphs) {
if let Some(marks) = self.marks.get(id) {
(own.links, own.bookmarks) = marks.placed(own_spans, text_offset(own.text.len()));
}
}
let cells: Vec<Option<CellPlace>> = read.paragraphs.iter().map(|p| p.cell).collect();
for (_, text_line) in &mut read.lines {
let paragraph = text_line.paragraph;
let cell = cells.get(paragraph).copied().flatten();
let next = cells.get(paragraph + 1).copied().flatten();
if text_line.ends == LineTextEnd::Paragraph && cell.is_some() && next != cell {
text_line.ends = LineTextEnd::Cell;
}
}
read
}
}
#[derive(Default)]
struct Read<'a> {
paragraphs: Vec<StoryParagraph>,
lines: Vec<(&'a CompactLine, TextLine)>,
}
fn text_line(
line: &CompactLine,
text: &LineText,
(story, paragraph): (TextStory, usize),
start: u32,
) -> TextLine {
TextLine {
story,
paragraph,
start,
end: start + text_offset(text.text.len()),
top: line.top,
height: line.height,
baseline: line.baseline,
clusters: text
.clusters
.iter()
.map(|cluster| TextCluster {
start: start + cluster.start,
end: start + cluster.end,
..*cluster
})
.collect(),
left: text.left,
ends: text.end,
hyphen: text.hyphen,
turn: text.turn,
}
}
pub(crate) fn turned_apart(lines: Vec<PlacedLine>) -> (Vec<PlacedLine>, Vec<(usize, PlacedLine)>) {
let mut upright: Vec<PlacedLine> = Vec::with_capacity(lines.len());
let mut turned: Vec<(usize, PlacedLine)> = Vec::new();
let mut run: Vec<PlacedLine> = Vec::new();
for line in lines {
if line.upright() {
turned.extend(place_run(&upright, std::mem::take(&mut run)));
upright.push(line);
} else {
run.push(line);
}
}
turned.extend(place_run(&upright, run));
turned.sort_by_key(|&(before, _)| before);
(upright, turned)
}
fn place_run(upright: &[PlacedLine], run: Vec<PlacedLine>) -> Vec<(usize, PlacedLine)> {
let outer = run
.iter()
.filter_map(|line| line.cell)
.map(|cell| cell.table)
.min();
let of_outer = |line: &PlacedLine| {
line.cell
.filter(|cell| Some(cell.table) == outer)
.map(|cell| (cell, TextStory::of_placed(line)))
};
let mut frame = run.iter().find_map(of_outer);
let mut found: Option<((CellPlace, TextStory), usize)> = None;
let mut placed = Vec::with_capacity(run.len());
for line in run {
frame = of_outer(&line).or(frame);
let before = match (frame, found) {
(Some(cell), Some((known, before))) if known == cell => before,
(Some(cell), _) => {
let before = before_later_cells(upright, cell);
found = Some((cell, before));
before
}
(None, _) => upright.len(),
};
placed.push((before, line));
}
placed
}
fn before_later_cells(upright: &[PlacedLine], (cell, story): (CellPlace, TextStory)) -> usize {
let mut before = upright.len();
for (index, other) in upright.iter().enumerate().rev() {
let Some(other_cell) = other.cell.filter(|_| TextStory::of_placed(other) == story) else {
continue;
};
if other_cell.table == cell.table && other_cell.row < cell.row {
break;
}
if other_cell.table == cell.table
&& other_cell.row == cell.row
&& other_cell.column > cell.column
{
before = index;
}
}
before
}
pub(crate) fn text_offset(bytes: usize) -> u32 {
u32::try_from(bytes).unwrap_or(u32::MAX)
}