use super::{Units, esc, gaps_of, is_tall, span_html, spans_h95};
use crate::common::geom::median;
use crate::model::{Line, SUB, SUP, Span};
const OFF_BASELINE_EM: f32 = 0.1;
const STACK_MIN_OVERLAP_PT: f32 = 0.5;
const STACK_MIN_RISE_EM: f32 = 0.4;
const RESIZED_MIN_RATIO: f32 = 0.08;
const TAB_MIN_GAP_EM: f32 = 0.8;
const TAB_MIN_SPACE_RATIO: f32 = 3.0;
const TAB_MAX_ALONE_COUNT: usize = 2;
struct Cluster {
first: usize,
end: usize,
chars: std::ops::Range<usize>,
}
struct LineText<'a> {
glyph_of_char: &'a [Option<usize>],
gaps: &'a [f32],
tabs: &'a [Option<f32>],
}
#[derive(Default)]
struct Plain {
text: String,
size: Option<f32>,
}
impl Plain {
fn flush(&mut self, out: &mut String, span: &Span, gaps: &mut std::slice::Iter<'_, f32>, units: &Units) {
if self.text.is_empty() {
return;
}
let html = span_html(span, &self.text, gaps);
match self.size {
Some(size) => out.push_str(&format!("<span style=\"font-size:{}\">{html}</span>", units.len(size))),
None => out.push_str(&html),
}
self.text.clear();
}
}
pub(super) fn line_html(line: &Line, spans: &[Span], units: &Units) -> (String, bool) {
let gaps = gaps_of(line);
let runs = stacked_runs(line);
let tabs = tabs_of(line);
if runs.is_empty()
&& tabs.iter().all(Option::is_none)
&& !line.glyphs.iter().any(is_tall)
&& !(0..line.glyphs.len()).any(|idx| own_size(line, idx).is_some())
{
return spans_h95(spans, &gaps);
}
let Some(glyph_of_char) = glyph_of_chars(line, spans) else {
return spans_h95(spans, &gaps);
};
let clusters = clusters_of(&runs, &glyph_of_char);
let text_info = LineText {
glyph_of_char: &glyph_of_char,
gaps: &gaps,
tabs: &tabs,
};
write_line(line, spans, &clusters, &text_info, units)
}
fn tabs_of(line: &Line) -> Vec<Option<f32>> {
let spaces: Vec<f32> = (1..line.glyphs.len())
.filter(|&idx| line.glyphs[idx].space_before)
.map(|idx| line.glyphs[idx].x0 - line.glyphs[idx - 1].x1)
.collect();
let min_gap = TAB_MIN_GAP_EM * line.size;
let words: Vec<f32> = spaces.iter().copied().filter(|&gap| gap <= min_gap).collect();
let wide_count = spaces.len() - words.len();
if words.is_empty() && wide_count > TAB_MAX_ALONE_COUNT {
return vec![None; line.glyphs.len()];
}
let word_space = median(&words, 0.0);
std::iter::once(None)
.chain(line.glyphs.windows(2).map(|pair| {
let gap = pair[1].x0 - pair[0].x1;
(pair[1].space_before && gap > min_gap && gap >= TAB_MIN_SPACE_RATIO * word_space).then_some(gap)
}))
.take(line.glyphs.len())
.collect()
}
fn stacked_runs(line: &Line) -> Vec<(usize, usize)> {
let mut runs = off_baseline_runs(line);
runs.extend(overlapping_runs(line));
runs.sort_unstable();
let mut merged: Vec<(usize, usize)> = Vec::new();
for (first, end) in runs {
match merged.last_mut() {
Some(last) if first < last.1 => last.1 = last.1.max(end),
_ => merged.push((first, end)),
}
}
merged.retain(|&(first, end)| {
has_stacked_pair(line, first, end)
&& !line.glyphs[first..end]
.iter()
.any(|glyph| glyph.text.contains('\u{FFFD}'))
});
merged
}
fn off_baseline_runs(line: &Line) -> Vec<(usize, usize)> {
let off_baseline = |idx: usize| (line.glyphs[idx].y - line.baseline).abs() > OFF_BASELINE_EM * line.size;
let mut runs = Vec::new();
let mut idx = 0;
while idx < line.glyphs.len() {
if !off_baseline(idx) {
idx += 1;
continue;
}
let first = idx;
while idx < line.glyphs.len() && off_baseline(idx) {
idx += 1;
}
runs.push((first, idx));
}
runs
}
fn overlapping_runs(line: &Line) -> Vec<(usize, usize)> {
let glyphs = &line.glyphs;
let mut runs = Vec::new();
let mut idx = 0;
while idx < glyphs.len() {
let first = idx;
let mut right = glyphs[idx].x1;
idx += 1;
while idx < glyphs.len() && glyphs[idx].x0 < right - STACK_MIN_OVERLAP_PT {
right = right.max(glyphs[idx].x1);
idx += 1;
}
if idx - first >= 2 {
runs.push((first, idx));
}
}
runs
}
fn own_size(line: &Line, idx: usize) -> Option<f32> {
let glyph = &line.glyphs[idx];
let on_baseline = (glyph.y - line.baseline).abs() <= OFF_BASELINE_EM * line.size;
let resized = (glyph.size - line.size).abs() > RESIZED_MIN_RATIO * line.size;
let larger = glyph.size > line.size * (1.0 + RESIZED_MIN_RATIO);
((on_baseline && resized) || larger).then_some(glyph.size)
}
fn has_stacked_pair(line: &Line, first: usize, end: usize) -> bool {
let glyphs = &line.glyphs[first..end];
glyphs.iter().enumerate().any(|(i, upper)| {
glyphs[i + 1..].iter().any(|other| {
let overlap = upper.x1.min(other.x1) - upper.x0.max(other.x0);
overlap > STACK_MIN_OVERLAP_PT && (upper.y - other.y).abs() > STACK_MIN_RISE_EM * line.size
})
})
}
fn glyph_of_chars(line: &Line, spans: &[Span]) -> Option<Vec<Option<usize>>> {
let mut expected: Vec<(char, Option<usize>)> = Vec::new();
for (glyph_idx, glyph) in line.glyphs.iter().enumerate() {
if glyph.space_before && glyph_idx > 0 {
expected.push((' ', None));
}
expected.extend(glyph.text.chars().map(|ch| (ch, Some(glyph_idx))));
}
let text: Vec<char> = spans.iter().flat_map(|span| span.text.chars()).collect();
let matches = |len: usize| {
len <= expected.len() && text.len() >= len && expected[..len].iter().zip(&text).all(|(exp, ch)| exp.0 == *ch)
};
let mut map: Vec<Option<usize>> = expected.iter().map(|exp| exp.1).collect();
if text.len() == expected.len() && matches(expected.len()) {
Some(map)
} else if text.len() + 1 == expected.len() && expected.last()?.0 == '-' && matches(text.len()) {
map.pop();
Some(map)
} else if text.len() == expected.len() + 1 && text.last() == Some(&' ') && matches(expected.len()) {
map.push(None);
Some(map)
} else {
reordered_glyph_of_chars(&expected, &text)
}
}
fn reordered_glyph_of_chars(expected: &[(char, Option<usize>)], text: &[char]) -> Option<Vec<Option<usize>>> {
let mut taken = vec![false; expected.len()];
let mut map = Vec::with_capacity(text.len());
for &ch in text {
if ch == ' ' {
map.push(None);
continue;
}
let pos = (0..expected.len()).find(|&pos| !taken[pos] && expected[pos].0 == ch)?;
taken[pos] = true;
map.push(expected[pos].1);
}
let left: Vec<usize> = (0..expected.len())
.filter(|&pos| !taken[pos] && expected[pos].0 != ' ')
.collect();
match left.as_slice() {
[] => Some(map),
[pos] if *pos + 1 == expected.len() && expected[*pos].0 == '-' => Some(map),
_ => None,
}
}
fn clusters_of(runs: &[(usize, usize)], glyph_of_char: &[Option<usize>]) -> Vec<Cluster> {
let in_run = |glyph: Option<usize>, first: usize, end: usize| glyph.is_some_and(|idx| first <= idx && idx < end);
runs.iter()
.filter_map(|&(first, end)| {
let start = glyph_of_char.iter().position(|&glyph| in_run(glyph, first, end))?;
let last = glyph_of_char.iter().rposition(|&glyph| in_run(glyph, first, end))?;
Some(Cluster {
first,
end,
chars: start..last + 1,
})
})
.collect()
}
fn placed_char_html(line: &Line, ch: char, pos: usize, text_info: &LineText<'_>, units: &Units) -> Option<String> {
let glyph_of_char = text_info.glyph_of_char;
if let Some(glyph_idx) = glyph_of_char[pos]
&& is_tall(&line.glyphs[glyph_idx])
{
let glyph = &line.glyphs[glyph_idx];
return Some(format!(
"<span class=\"ph\" style=\"width:{}\">{}</span>",
units.len(glyph.x1 - glyph.x0),
esc(&glyph.text)
));
}
let tab = match (glyph_of_char[pos], glyph_of_char.get(pos + 1)) {
(None, Some(&Some(next))) if ch == ' ' => text_info.tabs[next],
_ => None,
};
tab.map(|width| format!("<span class=\"tab\" style=\"width:{}\"> </span>", units.len(width)))
}
fn write_line(
line: &Line,
spans: &[Span],
clusters: &[Cluster],
text_info: &LineText<'_>,
units: &Units,
) -> (String, bool) {
let glyph_of_char = text_info.glyph_of_char;
let mut gaps = text_info.gaps.iter();
let mut out = String::new();
let mut trailing = false;
let mut pos = 0usize;
let mut next_cluster = 0usize;
for (span_idx, span) in spans.iter().enumerate() {
let mut text = span.text.as_str();
if span_idx + 1 == spans.len() && text.ends_with(' ') {
text = text.trim_end_matches(' ');
trailing = true;
}
let mut plain = Plain::default();
for ch in text.chars() {
match clusters.get(next_cluster) {
Some(cluster) if cluster.chars.contains(&pos) => {
plain.flush(&mut out, span, &mut gaps, units);
if pos + 1 == cluster.chars.end {
out.push_str(&cluster_html(line, spans, cluster, glyph_of_char, units));
next_cluster += 1;
}
}
_ => {
if let Some(html) = placed_char_html(line, ch, pos, text_info, units) {
plain.flush(&mut out, span, &mut gaps, units);
out.push_str(&html);
} else {
if let Some(glyph_idx) = glyph_of_char[pos] {
let size = own_size(line, glyph_idx);
if size != plain.size {
plain.flush(&mut out, span, &mut gaps, units);
plain.size = size;
}
}
plain.text.push(ch);
}
}
}
pos += 1;
}
plain.flush(&mut out, span, &mut gaps, units);
}
(out, trailing)
}
fn cluster_html(
line: &Line,
spans: &[Span],
cluster: &Cluster,
glyph_of_char: &[Option<usize>],
units: &Units,
) -> String {
let span_of_char = span_of_chars(spans);
let glyphs = &line.glyphs[cluster.first..cluster.end];
let mut cursor = glyphs[0].x0;
let right = glyphs.iter().map(|glyph| glyph.x1).fold(cursor, f32::max);
let mut out = String::from("<span class=\"st\" translate=\"no\">");
for (offset, glyph) in glyphs.iter().enumerate() {
let glyph_idx = cluster.first + offset;
let char_idx = glyph_of_char.iter().position(|&glyph| glyph == Some(glyph_idx));
let source = char_idx.and_then(|idx| span_of_char.get(idx)).map(|&idx| &spans[idx]);
let style = Span {
text: String::new(),
style: source.map_or(0, |span| span.style) & !(SUP | SUB),
href: source.and_then(|span| span.href.clone()),
color: glyph.color,
math: None,
note: None,
};
let mut css = format!(
"width:{};top:{};font-size:{}",
units.len(glyph.x1 - glyph.x0),
units.len(glyph.y - line.baseline),
units.len(glyph.size),
);
if glyph.x0 != cursor {
css.push_str(&format!(";margin-left:{}", units.len(glyph.x0 - cursor)));
}
if offset + 1 == glyphs.len() && right > glyph.x1 {
css.push_str(&format!(";margin-right:{}", units.len(right - glyph.x1)));
}
cursor = glyph.x1;
let class = if is_tall(glyph) { "sg ph" } else { "sg" };
out.push_str(&format!(
"<span class=\"{class}\" style=\"{css}\">{}</span>",
span_html(&style, &glyph.text, &mut [].iter())
));
}
out.push_str("</span>");
out
}
fn span_of_chars(spans: &[Span]) -> Vec<usize> {
spans
.iter()
.enumerate()
.flat_map(|(idx, span)| std::iter::repeat_n(idx, span.text.chars().count()))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::common::geom::Rect;
use crate::model::LineGlyph;
fn line(starts: &[f32]) -> Line {
let glyphs: Vec<LineGlyph> = starts
.iter()
.enumerate()
.map(|(i, &x)| LineGlyph {
text: "w".to_string(),
x0: x,
x1: x + 20.0,
y: 100.0,
size: 10.0,
font: 0,
script: 0,
space_before: i > 0,
drawn_space: false,
link: None,
ink: Rect::new(x, 93.0, x + 20.0, 100.0),
ox: x,
oy: 100.0,
extra: Vec::new(),
color: [0; 3],
})
.collect();
Line {
page: 0,
bbox: Rect::new(starts[0], 90.0, starts[starts.len() - 1] + 20.0, 102.0),
ink: Rect::new(starts[0], 93.0, starts[starts.len() - 1] + 20.0, 100.0),
baseline: 100.0,
size: 10.0,
font: 0,
glyphs,
fixed_pitch: false,
}
}
#[test]
fn inline_fraction_text_is_matched_to_its_glyphs() {
let mut fraction = line(&[0.0, 12.0, 15.0, 16.0, 19.0, 23.0]);
for (glyph, text) in fraction.glyphs.iter_mut().zip(["≤", "√", "d", "c", "−", "1"]) {
glyph.text = text.to_string();
glyph.space_before = false;
}
let spans = [Span::plain("≤c √d−1")];
let map = glyph_of_chars(&fraction, &spans).expect("the text is the glyphs reordered");
assert_eq!(map, vec![Some(0), Some(3), None, Some(1), Some(2), Some(4), Some(5)]);
}
#[test]
fn page_number_of_a_contents_entry_is_after_a_tab() {
let tabs = tabs_of(&line(&[0.0, 23.0, 46.0, 186.0]));
assert_eq!(tabs, vec![None, None, None, Some(120.0)]);
}
#[test]
fn chapter_number_and_page_number_are_both_tabs() {
let tabs = tabs_of(&line(&[0.0, 30.0, 53.0, 83.0]));
assert_eq!(tabs, vec![None, Some(10.0), None, Some(10.0)]);
}
#[test]
fn loose_justified_line_has_no_tab() {
let tabs = tabs_of(&line(&[0.0, 38.0, 80.0, 120.0]));
assert!(tabs.iter().all(Option::is_none));
}
}