mod stacked;
use super::assets::origin_key;
use super::mathml::MATH_FACE;
use super::*;
use crate::common::geom::{Rect, median};
use crate::model::{Line, LineGlyph};
use std::collections::HashSet;
const CSS: &str = include_str!("hard95.css");
const JS: &str = include_str!("hard95.js");
const NOTES_CSS: &str = include_str!("notes.css");
const NOTES_JS: &str = include_str!("notes.js");
const LATIN_MODERN: [(&str, &str, &str, &[u8]); 5] = [
(
"P2H LM Roman",
"normal",
"400",
include_bytes!("fonts/lmroman10-regular.woff2"),
),
(
"P2H LM Roman",
"italic",
"400",
include_bytes!("fonts/lmroman10-italic.woff2"),
),
(
"P2H LM Roman",
"normal",
"700",
include_bytes!("fonts/lmroman10-bold.woff2"),
),
(
"P2H LM Roman",
"italic",
"700",
include_bytes!("fonts/lmroman10-bolditalic.woff2"),
),
(
"P2H LM Mono",
"normal",
"400",
include_bytes!("fonts/lmmono10-regular.woff2"),
),
];
const BASELINE: f32 = 0.84;
const COMPUTER_MODERN_PREFIXES: [&str; 6] = ["cmr", "lmr", "lmroman", "cmu", "sfrm", "ecrm"];
const TEX_MATH_NAMES: [&str; 7] = ["cmmi", "cmsy", "cmex", "lmmi", "lmsy", "lmex", "latinmodern-math"];
const PICTURE_CHARS: [char; 2] = ['\u{FFFD}', '\u{221A}'];
const TALL_GLYPH_MIN_EM: f32 = 1.3;
const GAP_WIDTH_RANGE_EM: (f32, f32) = (0.1, 3.0);
const DEFAULT_GAP_EM: f32 = 0.5;
const COLUMN_BREAK_RISE_EM: f32 = 0.5;
const MIN_PITCH_EM: f32 = 0.5;
const MIN_LEAD_EM: f32 = 0.9;
const FONT_SIZE_TOLERANCE_PT: f32 = 0.3;
const FULL_LINE_TOLERANCE_PT: f32 = 1.5;
const CENTRED_TOLERANCE_PT: f32 = 2.5;
const CENTRED_MIN_OFFSET_PT: f32 = 3.0;
const CENTRED_MIN_LINES: usize = 2;
const JUSTIFY_MIN_LINES: usize = 3;
const JUSTIFY_FULL_TENTHS: usize = 6;
const MIN_LINE_SHIFT_PT: f32 = 0.1;
const TABLE_MIN_ROW_EM: f32 = 0.95;
const TABLE_MAX_GROWTH_RATIO: f32 = 0.10;
const FIGURE_REGION_MARGIN_PT: f32 = 2.0;
struct Units {
page_width: f32,
page_height: f32,
}
impl Units {
fn x(&self, value: f32) -> String {
format!("{:.3}%", value / self.page_width * 100.0)
}
fn y(&self, value: f32) -> String {
format!("{:.3}%", value / self.page_height * 100.0)
}
fn len(&self, value: f32) -> String {
format!("{:.3}cqw", value / self.page_width * 100.0)
}
fn width_attr(&self, value: f32) -> String {
format!("{:.3}", value / self.page_width * 100.0)
}
}
struct Fragment {
start: usize,
end: usize,
page: usize,
x0: f32,
x1: f32,
}
struct BoxStyle {
size: f32,
lead: f32,
width: f32,
indent: f32,
centred: bool,
align: &'static str,
}
struct LinePlacement {
shifts: Vec<f32>,
extra: Vec<f32>,
}
struct PageLayer<'u> {
units: &'u Units,
page_idx: usize,
html: String,
drawn: HashSet<(i32, i32)>,
}
impl PageLayer<'_> {
fn block(&mut self, doc: &Document, block: &Block) {
if let Some(anchor) = block.anchor.as_deref().filter(|_| block.page == self.page_idx) {
self.html.push_str(&format!(
"<a class=\"anc\" id=\"{}\" style=\"left:{};top:{}\"></a>\n",
esc(anchor),
self.units.x(block.bbox.x0),
self.units.y(block.bbox.y0)
));
}
match &block.kind {
BlockKind::Equation { .. } => self.equation(block),
BlockKind::Authors => self.authors(doc, block),
_ => {
self.text_block(doc, block);
self.float_content(block);
}
}
}
fn equation(&mut self, block: &Block) {
if block.lines.first().is_some_and(|line| line.page == self.page_idx) {
self.html.push_str(&equation(block, self.units));
block
.lines
.iter()
.for_each(|line| add_origins(&mut self.drawn, line, true));
}
}
fn authors(&mut self, doc: &Document, block: &Block) {
if is_edited(block) {
self.text_block(doc, block);
return;
}
let mut html = String::new();
for (line, hline) in block
.lines
.iter()
.zip(&block.hlines)
.filter(|(line, _)| line.page == self.page_idx)
{
html.push_str(&placed_line(self.units, line, &hline.spans));
add_origins(&mut self.drawn, line, true);
}
if !html.is_empty() {
self.html.push_str(&format!(
"<div class=\"b\" data-kind=\"authors\" data-block=\"{}\">{html}</div>\n",
block.id
));
}
}
fn text_block(&mut self, doc: &Document, block: &Block) {
let html = flow_block(doc, block, self.page_idx, self.units);
if !html.is_empty() {
self.html.push_str(&html);
let edited = is_edited(block);
for line in block.lines.iter().filter(|line| line.page == self.page_idx) {
if edited {
add_all_origins(&mut self.drawn, line);
} else {
add_origins(&mut self.drawn, line, true);
}
}
}
}
fn float_content(&mut self, block: &Block) {
if !block.inner_lines.first().is_some_and(|line| line.page == self.page_idx)
|| replaced_picture(block).is_some()
{
return;
}
match block.table.as_ref().filter(|table| table_fits(table)) {
Some(table) => {
self.html
.push_str(&table_box(table, is_edited_table(block), self.units));
block
.inner_lines
.iter()
.for_each(|line| add_origins(&mut self.drawn, line, false));
}
None => {
let mut html = String::new();
for (line, spans) in block.inner_lines.iter().zip(&block.inner_spans) {
html.push_str(&placed_line(self.units, line, spans));
}
self.html.push_str(&format!(
"<div class=\"b\" data-kind=\"figure-text\" data-block=\"{}\">{html}</div>\n",
block.id
));
}
}
}
fn furniture(&mut self, loose: &[PLine]) {
let mut html = String::new();
for loose_line in loose {
html.push_str(&placed_line(self.units, &loose_line.line, &loose_line.spans));
add_origins(&mut self.drawn, &loose_line.line, true);
}
if !html.is_empty() {
self.html
.push_str(&format!("<div class=\"b\" data-kind=\"page-furniture\">{html}</div>\n"));
}
}
fn rotated(&mut self, doc: &Document, rotated: &[RotatedRun]) {
let figures = figure_regions(doc, self.page_idx);
let replaced: Vec<Rect> = doc
.blocks
.iter()
.filter_map(replaced_picture)
.filter(|spec| spec.page == self.page_idx)
.map(|spec| spec.rect)
.collect();
let mut visible = String::new();
let mut in_figure = String::new();
for run in rotated {
let html = rotated_run_html(run, self.units);
if replaced.iter().any(|rect| run_in_region(run, rect)) {
continue;
}
if figures.iter().any(|rect| run_in_region(run, rect)) {
in_figure.push_str(&html);
} else {
visible.push_str(&html);
for &(x, y) in &run.origins {
self.drawn.insert(origin_key(x, y));
}
}
}
if !visible.is_empty() {
self.html.push_str(&format!(
"<div class=\"b\" data-kind=\"rotated-text\">{visible}</div>\n"
));
}
if !in_figure.is_empty() {
self.html.push_str(&format!(
"<div class=\"b\" data-kind=\"figure-text\">{in_figure}</div>\n"
));
}
}
}
fn replaced_picture(block: &Block) -> Option<&ImageSpec> {
match &block.kind {
BlockKind::Figure { image: Some(spec), .. } if spec.embedded.is_some() => Some(spec),
_ => None,
}
}
fn replaced_figure(id: usize, spec: &ImageSpec, images: &mut ImageStore<'_>, units: &Units) -> String {
format!(
"<div class=\"b\" data-kind=\"figure-picture\" data-block=\"{id}\" style=\"position:absolute;left:{};top:{};width:{};height:{};background:#fff\"><img src=\"{}\" alt=\"\" style=\"display:block;width:100%;height:100%;object-fit:contain\"></div>\n",
units.x(spec.rect.x0),
units.y(spec.rect.y0),
units.x(spec.rect.width()),
units.y(spec.rect.height()),
images.region(spec, "fig"),
)
}
fn figure_regions(doc: &Document, page_idx: usize) -> Vec<Rect> {
doc.blocks
.iter()
.filter(|block| block.table.is_none())
.filter_map(|block| match &block.kind {
BlockKind::Figure { image: Some(image), .. } if image.page == page_idx => Some(image.rect),
_ => None,
})
.collect()
}
pub(crate) fn run_in_region(run: &RotatedRun, rect: &Rect) -> bool {
let (sin, cos) = run.angle.to_radians().sin_cos();
let half = run.length * 0.5;
let mid_x = run.x + cos * half + sin * run.size * 0.3;
let mid_y = run.y + sin * half - cos * run.size * 0.3;
rect.inflate(FIGURE_REGION_MARGIN_PT, FIGURE_REGION_MARGIN_PT)
.contains_point(mid_x, mid_y)
}
fn rotated_run_html(run: &RotatedRun, units: &Units) -> String {
let span = Span {
text: run.text.clone(),
style: run.style,
href: None,
color: run.color,
math: None,
note: None,
};
format!(
"<span class=\"rt\" style=\"left:{};top:{};font-size:{};transform:rotate({:.2}deg)\" data-w=\"{}\">{}</span>",
units.x(run.x),
units.y(run.y - BASELINE * run.size),
units.len(run.size),
run.angle,
units.width_attr(run.length),
span_html(&span, &run.text, &mut [].iter()),
)
}
pub(crate) struct Hard95;
impl Renderer for Hard95 {
fn render(&self, analysis: &Analysis, images: &mut ImageStore<'_>) -> String {
render(analysis, images)
}
}
pub(crate) fn render(analysis: &Analysis, images: &mut ImageStore<'_>) -> String {
let doc = &analysis.doc;
let title = doc_title(doc);
let lower = doc.body_font.to_ascii_lowercase();
let computer_modern = COMPUTER_MODERN_PREFIXES.iter().any(|prefix| lower.contains(prefix));
let math_lower = doc.math_font.to_ascii_lowercase();
let tex_math = TEX_MATH_NAMES.iter().any(|name| math_lower.contains(name));
let mut pages = String::new();
for (page_idx, page) in doc.pages.iter().enumerate() {
pages.push_str(&page_html(analysis, page_idx, page, images));
}
let source = arxiv_abs_link(doc);
let fonts = if (computer_modern || tex_math) && images.opts.embed_fonts {
let mut faces: String = LATIN_MODERN
.iter()
.map(|(family, style, weight, data)| font_face(family, style, weight, data))
.collect();
faces.push_str(&MATH_FACE);
faces
} else {
String::new()
};
let (notes_css, notes_js) = if pages.contains("<sup class=\"an\"") {
(NOTES_CSS, format!("<script>\n{NOTES_JS}</script>\n"))
} else {
("", String::new())
};
format!(
r#"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="generator" content="kakemono (hard-95)">
<title>{title}</title>
<style>
{fonts}{CSS}{notes_css}</style>
</head>
<body class="hard95 fit{cm}{tm}">
<div class="topbar"><span class="t">{title}</span>{source}<span>{n} pages</span><button id="zout" type="button" aria-label="Zoom out">−</button><button id="zfit" type="button">Fit</button><button id="zin" type="button" aria-label="Zoom in">+</button></div>
<main class="pages">
{pages}</main>
<script>
{JS}</script>
{notes_js}</body>
</html>
"#,
title = esc(&title),
n = doc.pages.len(),
cm = if computer_modern { " cm" } else { "" },
tm = if tex_math { " tm" } else { "" },
)
}
fn page_html(analysis: &Analysis, page_idx: usize, page: &PageInfo, images: &mut ImageStore<'_>) -> String {
crate::common::cancel::check();
let doc = &analysis.doc;
let units = Units {
page_width: page.width,
page_height: page.height,
};
let mut layer = PageLayer {
units: &units,
page_idx,
html: String::new(),
drawn: HashSet::new(),
};
for block in &doc.blocks {
layer.block(doc, block);
}
if let Some(loose) = analysis.loose.get(page_idx) {
layer.furniture(loose);
}
if let Some(rotated) = analysis.rotated.get(page_idx) {
layer.rotated(doc, rotated);
}
let PageLayer {
html: mut layer, drawn, ..
} = layer;
for block in &doc.blocks {
if let Some(spec) = replaced_picture(block).filter(|spec| spec.page == page_idx) {
layer.push_str(&replaced_figure(block.id, spec, images, &units));
}
}
let bg = format!(
"<img class=\"bg\" src=\"{}\" alt=\"\" width=\"{}\" height=\"{}\" loading=\"lazy\" decoding=\"async\">",
images.page_without_text(page_idx, drawn),
page.width,
page.height
);
format!(
"<section class=\"page\" id=\"page-{n}\" data-page=\"{n}\" style=\"--pw:{};--ph:{};aspect-ratio:{}/{}\">\n{bg}\n<div class=\"tl\">\n{layer}</div>\n</section>\n",
page.width,
page.height,
page.width,
page.height,
n = page_idx + 1,
)
}
fn is_tall(glyph: &LineGlyph) -> bool {
glyph.text.chars().count() == 1 && glyph.ink.height() > TALL_GLYPH_MIN_EM * glyph.size
}
fn gaps_of(line: &Line) -> Vec<f32> {
line.glyphs
.iter()
.filter(|glyph| glyph.text.contains(PICTURE_CHARS))
.map(|glyph| ((glyph.x1 - glyph.x0) / line.size.max(1.0)).clamp(GAP_WIDTH_RANGE_EM.0, GAP_WIDTH_RANGE_EM.1))
.collect()
}
fn span_html(span: &Span, text: &str, gaps: &mut std::slice::Iter<'_, f32>) -> String {
let mut out = String::new();
let mut piece = String::new();
for ch in text.chars() {
if !PICTURE_CHARS.contains(&ch) {
piece.push(ch);
continue;
}
out.push_str(&esc(&piece));
piece.clear();
let width_em = gaps.next().copied().unwrap_or(DEFAULT_GAP_EM);
let unseen = if ch == '\u{FFFD}' {
String::new()
} else {
ch.to_string()
};
out.push_str(&format!(
"<span class=\"ph\" style=\"width:{width_em:.3}em\">{unseen}</span>"
));
}
out.push_str(&esc(&piece));
wrap_span(span, out)
}
fn wrap_span(span: &Span, inner: String) -> String {
if let Some(note) = &span.note {
return note_call(span, note);
}
let mut out = inner;
let mut classes: Vec<&str> = Vec::new();
if span.style & MONO != 0 {
classes.push("m");
} else if span.style & SANS != 0 {
classes.push("s");
}
if span.style & MATH != 0 {
classes.push("x");
}
if span.style & SMALL_CAPS != 0 {
classes.push("sc");
}
if span.style & SUP != 0 {
out = format!("<sup>{out}</sup>");
}
if span.style & SUB != 0 {
out = format!("<sub>{out}</sub>");
}
if span.style & ITALIC != 0 {
out = format!("<i>{out}</i>");
}
if span.style & BOLD != 0 {
out = format!("<b>{out}</b>");
}
let color = (span.color != [0; 3])
.then(|| format!("color:#{:02x}{:02x}{:02x}", span.color[0], span.color[1], span.color[2]));
if !classes.is_empty() || color.is_some() {
let cls = if classes.is_empty() {
String::new()
} else {
format!(" class=\"{}\"", classes.join(" "))
};
let style = color.map(|color| format!(" style=\"{color}\"")).unwrap_or_default();
out = format!("<span{cls}{style}>{out}</span>");
}
match &span.href {
Some(href) if href.starts_with('#') => format!("<a href=\"{}\">{out}</a>", esc(href)),
Some(href) => format!(
"<a href=\"{}\" target=\"_blank\" rel=\"noopener noreferrer\">{out}</a>",
esc(href)
),
None => out,
}
}
fn spans_h95(spans: &[Span], gaps: &[f32]) -> (String, bool) {
let mut out = String::new();
let mut trailing = false;
let mut gaps = gaps.iter();
for (i, span) in spans.iter().enumerate() {
let mut text = span.text.as_str();
if i + 1 == spans.len() && text.ends_with(' ') {
text = text.trim_end_matches(' ');
trailing = true;
}
if !text.is_empty() {
out.push_str(&span_html(span, text, &mut gaps));
}
}
(out, trailing)
}
fn placed_line(units: &Units, line: &Line, spans: &[Span]) -> String {
let (html, _) = stacked::line_html(line, spans, units);
if html.is_empty() {
return String::new();
}
format!(
"<span class=\"pl\" style=\"left:{};top:{};font-size:{}\" data-w=\"{}\">{html}</span>",
units.x(line.bbox.x0),
units.y(line.baseline - BASELINE * line.size),
units.len(line.size),
units.width_attr(line.bbox.width()),
)
}
fn fragments(lines: &[Line]) -> Vec<Fragment> {
let mut out: Vec<Fragment> = Vec::new();
for (i, line) in lines.iter().enumerate() {
let new = match (out.last(), i.checked_sub(1).map(|prev_idx| &lines[prev_idx])) {
(Some(frag), Some(prev)) => {
line.page != frag.page || line.baseline < prev.baseline - COLUMN_BREAK_RISE_EM * line.size
}
_ => true,
};
if new {
out.push(Fragment {
start: i,
end: i + 1,
page: line.page,
x0: line.bbox.x0,
x1: line.bbox.x1,
});
} else {
let frag = out.last_mut().unwrap();
frag.end = i + 1;
frag.x0 = frag.x0.min(line.bbox.x0);
frag.x1 = frag.x1.max(line.bbox.x1);
}
}
out
}
fn flow_block(doc: &Document, block: &Block, page_idx: usize, units: &Units) -> String {
let edited = is_edited(block);
if block.lines.is_empty() || (!edited && block.hlines.len() != block.lines.len()) {
return String::new();
}
let frags = fragments(&block.lines);
if !frags.iter().any(|frag| frag.page == page_idx) {
return String::new();
}
let size = median(
&block.lines.iter().map(|line| line.size).collect::<Vec<_>>(),
doc.body_size,
);
let lead = line_pitch(doc, block, &frags, size);
let width = frags.iter().map(|frag| frag.x1 - frag.x0).fold(0.0, f32::max);
let placement = line_placement(block, &frags, lead);
let style = box_style(block, &frags, size, lead, width);
let inner = if edited {
edited_html(block)
} else {
flow_lines(block, &frags, size, &placement.shifts, style.align == "justify", units)
};
fragment_boxes(block, &frags, page_idx, &style, &placement.extra, &inner, edited, units)
}
fn note_call(call: &Span, note: &[Span]) -> String {
let plain: String = note.iter().map(|span| span.text.as_str()).collect();
let content: String = note.iter().map(|span| wrap_span(span, esc(&span.text))).collect();
format!(
"<sup class=\"an\" tabindex=\"0\" role=\"button\" title=\"{}\">{}<span class=\"an-c\" hidden>{content}</span></sup>",
esc(plain.trim()),
esc(&call.text)
)
}
fn is_edited(block: &Block) -> bool {
!matches!(block.kind, BlockKind::Equation { .. })
&& !block.lines.is_empty()
&& block.hlines.is_empty()
&& !block.spans.is_empty()
}
fn is_edited_table(block: &Block) -> bool {
!block.inner_lines.is_empty() && block.inner_spans.is_empty()
}
fn edited_html(block: &Block) -> String {
let spans_html = |spans: &[Span]| -> String {
spans
.iter()
.map(|span| wrap_span(span, esc(&span.text.replace('\u{FFFD}', ""))))
.collect()
};
let html = if matches!(block.kind, BlockKind::Authors) && !block.rows.is_empty() {
block
.rows
.iter()
.map(|row| spans_html(row))
.collect::<Vec<_>>()
.join("<br>")
} else {
spans_html(&block.spans)
};
format!("<span class=\"ln end\">{html}</span>")
}
fn line_pitch(doc: &Document, block: &Block, frags: &[Fragment], size: f32) -> f32 {
let mut pitches = Vec::new();
for frag in frags {
for pair in block.lines[frag.start..frag.end].windows(2) {
let pitch = pair[1].baseline - pair[0].baseline;
if pitch > MIN_PITCH_EM * size {
pitches.push(pitch);
}
}
}
median(&pitches, doc.leading * size / doc.body_size).max(MIN_LEAD_EM * size)
}
fn line_placement(block: &Block, frags: &[Fragment], lead: f32) -> LinePlacement {
let mut shifts = Vec::with_capacity(block.lines.len());
let mut extra = Vec::with_capacity(frags.len());
let mut carried = 0.0;
for frag in frags {
let first = block.lines[frag.start].baseline;
let mut lowest = 0.0f32;
for (line_no, line) in block.lines[frag.start..frag.end].iter().enumerate() {
let below_first = line.baseline - first;
lowest = lowest.max(below_first);
shifts.push(below_first - line_no as f32 * lead + carried);
}
let mut added = lowest - (frag.end - frag.start - 1) as f32 * lead;
if added < MIN_LINE_SHIFT_PT {
added = 0.0;
}
extra.push(added);
carried += added;
}
LinePlacement { shifts, extra }
}
fn flow_lines(block: &Block, frags: &[Fragment], size: f32, shifts: &[f32], justified: bool, units: &Units) -> String {
let mut inner = String::new();
for (frag_idx, frag) in frags.iter().enumerate() {
let range = frag.start..frag.end;
let lines = block.lines[range.clone()].iter().zip(&block.hlines[range.clone()]);
for (i, ((line, hline), &shift)) in range.clone().zip(lines.zip(&shifts[range])) {
let (html, trailing) = stacked::line_html(line, &hline.spans, units);
let mut style = format!("margin-left:{}", units.len((line.bbox.x0 - frag.x0).max(0.0)));
if (line.size - size).abs() > FONT_SIZE_TOLERANCE_PT {
style.push_str(&format!(";font-size:{}", units.len(line.size)));
}
if shift.abs() >= MIN_LINE_SHIFT_PT {
style.push_str(&format!(";top:{}", units.len(shift)));
}
let last = frag_idx + 1 == frags.len() && i + 1 == frag.end;
let full = justified && (frag.x1 - line.bbox.x1).abs() < FULL_LINE_TOLERANCE_PT;
inner.push_str(&format!(
"<span class=\"ln{}{}\" style=\"{style}\" data-w=\"{}\"{}>{html}</span>{}",
if hline.soft_hyphen { " hy" } else { "" },
if last { " end" } else { "" },
units.width_attr(line.bbox.width()),
if full { " data-j=\"1\"" } else { "" },
if trailing { " " } else { "" },
));
}
}
inner
}
fn box_style(block: &Block, frags: &[Fragment], size: f32, lead: f32, width: f32) -> BoxStyle {
let first = &block.lines[0];
let rest_x0 = block.lines[frags[0].start + 1..frags[0].end]
.iter()
.map(|line| line.bbox.x0)
.fold(f32::INFINITY, f32::min);
let indent = if rest_x0.is_finite() {
first.bbox.x0 - rest_x0
} else {
0.0
};
let full = block
.lines
.iter()
.enumerate()
.filter(|(i, line)| {
let frag = frags.iter().find(|frag| frag.start <= *i && *i < frag.end).unwrap();
(frag.x1 - line.bbox.x1).abs() < FULL_LINE_TOLERANCE_PT
})
.count();
let centred = block.lines.len() >= CENTRED_MIN_LINES && {
let centers: Vec<f32> = block.lines.iter().map(|line| line.bbox.cx()).collect();
let mid = median(¢ers, 0.0);
centers.iter().all(|center| (center - mid).abs() < CENTRED_TOLERANCE_PT)
&& block
.lines
.iter()
.any(|line| (line.bbox.x0 - frags[0].x0).abs() > CENTRED_MIN_OFFSET_PT)
};
let align = if centred {
"center"
} else if block.lines.len() >= JUSTIFY_MIN_LINES && full * 10 >= (block.lines.len() - 1) * JUSTIFY_FULL_TENTHS {
"justify"
} else {
"left"
};
BoxStyle {
size,
lead,
width,
indent,
centred,
align,
}
}
#[allow(
clippy::too_many_arguments,
reason = "the parts of one flowing block, computed by flow_block"
)]
fn fragment_boxes(
block: &Block,
frags: &[Fragment],
page_idx: usize,
style: &BoxStyle,
extra: &[f32],
inner: &str,
edited: bool,
units: &Units,
) -> String {
let BoxStyle {
size,
lead,
width,
indent,
centred,
align,
} = *style;
let mut out = String::new();
let mut lines_before = 0usize;
let mut extra_before = 0.0;
for (frag_idx, frag) in frags.iter().enumerate() {
let n = frag.end - frag.start;
if frag.page == page_idx {
let top = block.lines[frag.start].baseline - (lead * 0.5 + (BASELINE - 0.5) * size);
let geometry = format!(
"left:{};top:{};width:{};height:{};font-size:{};line-height:{};--ti:{};--pl:{}",
units.x(frag.x0),
units.y(top),
units.x(width),
units.len(n as f32 * lead + extra[frag_idx]),
units.len(size),
units.len(lead),
units.len(if centred { 0.0 } else { indent }),
units.len(if centred { 0.0 } else { (-indent).max(0.0) }),
);
if frag_idx == 0 {
out.push_str(&format!(
"<div class=\"fb{}{}\" data-kind=\"{}\" data-block=\"{}\" data-align=\"{align}\" data-parts=\"{}\" style=\"{geometry}\"><div class=\"in\">{inner}</div></div>\n",
if frags.len() == 1 { " one" } else { "" },
if edited { " rf ed" } else { "" },
kind_name(&block.kind),
block.id,
frags.len(),
));
} else {
out.push_str(&format!(
"<div class=\"fb cont{}{}\" data-of=\"{}\" data-skip=\"{lines_before}\" data-align=\"{align}\" translate=\"no\" aria-hidden=\"true\" style=\"{geometry}\"><div class=\"in\" style=\"margin-top:-{}\">{inner}</div></div>\n",
if frag_idx + 1 == frags.len() { " tail" } else { "" },
if edited { " rf" } else { "" },
block.id,
units.len(lines_before as f32 * lead + extra_before),
));
}
}
lines_before += n;
extra_before += extra[frag_idx];
}
out
}
fn table_fits(table: &Table) -> bool {
let geom = &table.geom;
let needed = TABLE_MIN_ROW_EM * geom.size;
let growth: f32 = geom
.row_bounds
.windows(2)
.map(|rows| (needed - (rows[1] - rows[0])).max(0.0))
.sum();
growth <= TABLE_MAX_GROWTH_RATIO * geom.bbox.height().max(1.0)
}
fn table_box(table: &Table, edited: bool, units: &Units) -> String {
let geom = &table.geom;
let (box_width, box_height) = (geom.bbox.width().max(1.0), geom.bbox.height().max(1.0));
let mut out = format!(
"<div class=\"tb{}\" data-kind=\"table\" style=\"left:{};top:{};width:{};height:{};font-size:{}\"><table><colgroup>",
if edited { " rf" } else { "" },
units.x(geom.bbox.x0),
units.y(geom.bbox.y0),
units.x(box_width),
units.y(box_height),
units.len(geom.size),
);
for col in 0..table.n_cols {
out.push_str(&format!(
"<col style=\"width:{:.3}%\">",
(geom.col_bounds[col + 1] - geom.col_bounds[col]) / box_width * 100.0
));
}
out.push_str("</colgroup>");
let mut open_row: Option<usize> = None;
table_walk(table, |row_idx, col, cell| {
if open_row != Some(row_idx) {
if open_row.is_some() {
out.push_str("</tr>");
}
out.push_str(&format!(
"<tr style=\"height:{:.3}%\">",
(geom.row_bounds[row_idx + 1] - geom.row_bounds[row_idx]) / box_height * 100.0
));
open_row = Some(row_idx);
}
let tag = if row_idx < table.header_rows { "th" } else { "td" };
match cell {
None => out.push_str(&format!(
"<{tag} class=\"e{}\"></{tag}>",
table_rule_classes(table, row_idx, col, 1, 1)
)),
Some(cell) => out.push_str(&table_cell(table, units, row_idx, cell, tag)),
}
});
if open_row.is_some() {
out.push_str("</tr>");
}
out.push_str("</table></div>\n");
out
}
fn table_cell(table: &Table, units: &Units, row_idx: usize, cell: &TableCell, tag: &str) -> String {
let geom = &table.geom;
let first_col = cell.col.min(table.n_cols - 1);
let last_col = (cell.col + cell.colspan).min(table.n_cols) - 1;
let top = if cell.rowspan > 1 {
0.0
} else {
(geom.row_baselines[row_idx] - BASELINE * geom.size - geom.row_bounds[row_idx]).max(0.0)
};
let (align, pad) = if cell.colspan > 1 {
("c", format!(" style=\"padding-top:{}\"", units.len(top)))
} else {
let left = (geom.col_text[first_col].0 - geom.col_bounds[first_col]).max(0.0);
let right = (geom.col_bounds[last_col + 1] - geom.col_text[last_col].1).max(0.0);
(
&table.col_align[first_col][..1],
format!(
" style=\"padding:{} {} 0 {}\"",
units.len(top),
units.len(right),
units.len(left)
),
)
};
let attrs = span_attrs(cell);
let (html, _) = spans_h95(&cell.spans, &[]);
format!(
"<{tag}{attrs} class=\"{align}{}{}\"{pad}>{html}</{tag}>",
if cell.rowspan > 1 { " mid" } else { "" },
table_rule_classes(table, row_idx, cell.col, cell.colspan, cell.rowspan),
)
}
fn equation(block: &Block, units: &Units) -> String {
let mut out = format!(
"<div class=\"eq\" data-kind=\"equation\" data-block=\"{}\" translate=\"no\">",
block.id
);
for run in &block.eq_runs {
let span = Span {
text: run.text.clone(),
style: run.style | MATH,
href: None,
color: run.color,
math: None,
note: None,
};
let mut html = span_html(&span, &run.text, &mut [].iter());
if run.ink.is_some_and(|ink| ink.height() > TALL_GLYPH_MIN_EM * run.size) {
html = format!("<span class=\"ph\">{html}</span>");
}
let ink = run
.ink
.map(|ink| {
format!(
" data-ink=\"{:.3},{:.3},{:.3},{:.3}\"",
ink.x0 / units.page_width * 100.0,
ink.y0 / units.page_height * 100.0,
ink.x1 / units.page_width * 100.0,
ink.y1 / units.page_height * 100.0
)
})
.unwrap_or_default();
out.push_str(&format!(
"<span class=\"g\" style=\"left:{};top:{};font-size:{}\" data-w=\"{}\"{ink}>{html}</span>",
units.x(run.x),
units.y(run.y - BASELINE * run.size),
units.len(run.size),
units.width_attr(run.width),
));
}
out.push_str("</div>\n");
out
}
fn add_origins(set: &mut HashSet<(i32, i32)>, line: &Line, tall_in_picture: bool) {
add_glyph_origins(set, line, |glyph| {
glyph.text.contains(PICTURE_CHARS) || (tall_in_picture && is_tall(glyph))
});
}
fn add_all_origins(set: &mut HashSet<(i32, i32)>, line: &Line) {
add_glyph_origins(set, line, |_| false);
}
fn add_glyph_origins(set: &mut HashSet<(i32, i32)>, line: &Line, keep: impl Fn(&LineGlyph) -> bool) {
for glyph in &line.glyphs {
if keep(glyph) {
continue;
}
set.insert(origin_key(glyph.ox, glyph.oy));
for &(x, y) in &glyph.extra {
set.insert(origin_key(x, y));
}
}
}