use crate::backend::{Dir, FontInfo, Glyph, RawPage};
use crate::common::geom::{Rect, median, weighted_mode};
use crate::model::style::{BOLD, ITALIC, MATH, MONO, SANS, SMALL_CAPS, SUB, SUP};
use crate::model::{FRACTION_TERM, Line, LineGlyph, RAISED_FRACTION_TERM, RotatedText};
use std::collections::HashMap;
use std::hash::{BuildHasherDefault, Hasher};
use unicode_normalization::UnicodeNormalization;
const FIXED_PITCH_BRACKETS_MAX: usize = 3;
const FIXED_PITCH_SHORT_RUN: usize = 2;
const DUPLICATE_CELL_PT: f32 = 8.0;
const TIGHT_SPACE_MAX_RUN: usize = 2;
const NEGATION: char = '\u{0338}';
const UNKNOWN_DUPLICATE_MAX_OFFSET_PT: f32 = 0.25;
const DEFAULT_CONFIG: LinesConfig = LinesConfig {
page_margin_pt: 5.0,
near_black_max_value: 48,
duplicate_max_offset_em: 0.1,
rotated_max_angle_diff_deg: 2.0,
rotated_max_offset_em: 0.25,
rotated_max_backstep_em: 0.3,
rotated_max_gap_em: 1.2,
rotated_space_gap_em: 0.14,
size_bin_pt: 0.25,
default_size_pt: 10.0,
baseline_size_tolerance_pt: 0.3,
same_baseline_pt: 0.25,
same_baseline_em: 0.03,
merge_max_gap_em: 1.0,
justified_max_gap_em: 2.5,
justified_edge_tol_pt: 1.5,
justified_max_indent_em: 3.0,
justified_min_step_em: 0.7,
justified_max_step_em: 2.0,
justified_gutter_reach_em: 4.0,
justified_gutter_tol_pt: 1.0,
justified_max_gap_ratio: 3.0,
gutter_zone: (0.25, 0.75),
gutter_max_cover_ratio: 0.02,
gutter_min_column_lines: 10,
gutter_min_width_pt: 3.0,
gutter_min_span_ratio: 0.7,
gutter_window_rows: 6,
gutter_edge_reach_pt: 4.0,
gutter_window_min_lines: 4,
gutter_window_min_width_pt: 5.0,
gutter_window_space_factor: 2.0,
gutter_window_min_piece_chars: 15,
gutter_window_min_letter_ratio: 0.7,
merge_max_size_factor: 2.2,
math_axis_em: 0.25,
math_reanchor_min_offset_em: 0.5,
host_min_size_factor: 1.12,
script_max_rise_em: 0.62,
script_max_drop_em: 0.42,
script_slack_em: 0.3,
superscript_min_rise_em: 0.12,
subscript_min_drop_em: 0.07,
row_script_max_size_ratio: 0.9,
space_gap_em: 0.14,
tight_space_gap_em: 0.085,
drawn_space_min_gap_em: 0.08,
link_probe_height_em: 0.3,
link_margin_pt: 0.5,
drawn_space_max_offset_em: 0.2,
tight_space_min_count: 3,
tight_space_ratio: 3.0,
fixed_pitch_min_run: 3,
fixed_pitch_gap_tolerance_pt: 0.05,
fixed_pitch_min_gap_em: 0.03,
fixed_pitch_max_gap_em: 0.4,
fixed_pitch_space_gap_em: 0.45,
fixed_pitch_min_lines: 3,
fixed_pitch_max_line_gap_em: 4.0,
space_lookback_count: 3,
line_box_ascent_em: 0.75,
line_box_descent_em: 0.25,
accent_min_width_pt: 0.5,
accent_min_overlap_ratio: 0.4,
raised_accent_max_rise_em: 0.5,
raised_accent_overlap_em: 0.1,
raised_accent_size_tolerance_ratio: 0.1,
raised_accent_lookaround_count: 4,
squeezed_punctuation_overlap_ratio: 0.5,
ruby_max_size_ratio: 0.65,
ruby_max_gap_em: 0.6,
ruby_over_kanji_min_ratio: 0.8,
fraction_bar_slack_em: 0.3,
drop_cap_min_size_ratio: 2.0,
drop_cap_min_lines_count: 2,
drop_cap_max_gap_em: 0.5,
drop_cap_baseline_slack_em: 0.2,
fraction_raised_min_rise_em: 0.4,
fraction_bar_max_axis_em: 0.6,
fraction_host_max_gap_em: 1.5,
fraction_numerator_max_rise_em: 1.0,
fraction_denominator_max_drop_em: 1.4,
fraction_term_max_size_ratio: 0.85,
fraction_term_max_glyphs_count: 8,
fraction_term_script_max_size_ratio: 0.85,
fraction_lines_max_distance_em: 3.0,
blank_max_thickness_pt: 1.5,
blank_max_drop_em: 0.4,
blank_max_rise_em: 0.1,
blank_max_gap_em: 1.0,
blank_stacked_max_distance_em: 0.9,
underline_piece_max_gap_pt: 6.0,
blank_underscore_em: 0.5,
blank_max_underscores_count: 8,
};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LinesConfig {
pub page_margin_pt: f32,
pub near_black_max_value: u8,
pub duplicate_max_offset_em: f32,
pub rotated_max_angle_diff_deg: f32,
pub rotated_max_offset_em: f32,
pub rotated_max_backstep_em: f32,
pub rotated_max_gap_em: f32,
pub rotated_space_gap_em: f32,
pub size_bin_pt: f32,
pub default_size_pt: f32,
pub baseline_size_tolerance_pt: f32,
pub same_baseline_pt: f32,
pub same_baseline_em: f32,
pub merge_max_gap_em: f32,
pub justified_max_gap_em: f32,
pub justified_edge_tol_pt: f32,
pub justified_max_indent_em: f32,
pub justified_min_step_em: f32,
pub justified_max_step_em: f32,
pub justified_gutter_reach_em: f32,
pub justified_gutter_tol_pt: f32,
pub justified_max_gap_ratio: f32,
pub gutter_zone: (f32, f32),
pub gutter_max_cover_ratio: f32,
pub gutter_min_column_lines: usize,
pub gutter_min_width_pt: f32,
pub gutter_min_span_ratio: f32,
pub gutter_window_rows: usize,
pub gutter_edge_reach_pt: f32,
pub gutter_window_min_lines: usize,
pub gutter_window_min_width_pt: f32,
pub gutter_window_space_factor: f32,
pub gutter_window_min_piece_chars: usize,
pub gutter_window_min_letter_ratio: f32,
pub merge_max_size_factor: f32,
pub math_axis_em: f32,
pub math_reanchor_min_offset_em: f32,
pub host_min_size_factor: f32,
pub script_max_rise_em: f32,
pub script_max_drop_em: f32,
pub script_slack_em: f32,
pub superscript_min_rise_em: f32,
pub subscript_min_drop_em: f32,
pub row_script_max_size_ratio: f32,
pub space_gap_em: f32,
pub tight_space_gap_em: f32,
pub drawn_space_min_gap_em: f32,
pub link_probe_height_em: f32,
pub link_margin_pt: f32,
pub drawn_space_max_offset_em: f32,
pub tight_space_min_count: usize,
pub tight_space_ratio: f32,
pub fixed_pitch_min_run: usize,
pub fixed_pitch_gap_tolerance_pt: f32,
pub fixed_pitch_min_gap_em: f32,
pub fixed_pitch_max_gap_em: f32,
pub fixed_pitch_space_gap_em: f32,
pub fixed_pitch_min_lines: usize,
pub fixed_pitch_max_line_gap_em: f32,
pub space_lookback_count: usize,
pub line_box_ascent_em: f32,
pub line_box_descent_em: f32,
pub accent_min_width_pt: f32,
pub accent_min_overlap_ratio: f32,
pub raised_accent_max_rise_em: f32,
pub raised_accent_overlap_em: f32,
pub raised_accent_size_tolerance_ratio: f32,
pub raised_accent_lookaround_count: usize,
pub squeezed_punctuation_overlap_ratio: f32,
pub ruby_max_size_ratio: f32,
pub ruby_max_gap_em: f32,
pub ruby_over_kanji_min_ratio: f32,
pub fraction_bar_slack_em: f32,
pub drop_cap_min_size_ratio: f32,
pub drop_cap_min_lines_count: usize,
pub drop_cap_max_gap_em: f32,
pub drop_cap_baseline_slack_em: f32,
pub fraction_raised_min_rise_em: f32,
pub fraction_bar_max_axis_em: f32,
pub fraction_host_max_gap_em: f32,
pub fraction_numerator_max_rise_em: f32,
pub fraction_denominator_max_drop_em: f32,
pub fraction_term_max_size_ratio: f32,
pub fraction_term_max_glyphs_count: usize,
pub fraction_term_script_max_size_ratio: f32,
pub fraction_lines_max_distance_em: f32,
pub blank_max_thickness_pt: f32,
pub blank_max_drop_em: f32,
pub blank_max_rise_em: f32,
pub blank_max_gap_em: f32,
pub underline_piece_max_gap_pt: f32,
pub blank_stacked_max_distance_em: f32,
pub blank_underscore_em: f32,
pub blank_max_underscores_count: usize,
}
impl Default for LinesConfig {
fn default() -> Self {
DEFAULT_CONFIG
}
}
impl Line {
pub fn text(&self) -> String {
let mut text = String::new();
for glyph in &self.glyphs {
if glyph.space_before && !text.is_empty() {
text.push(' ');
}
text.push_str(&glyph.text);
}
text
}
pub fn char_count(&self) -> usize {
self.glyphs.len()
}
pub fn first_word_width(&self) -> f32 {
let mut end = self.bbox.x0;
for (i, glyph) in self.glyphs.iter().enumerate() {
if i > 0 && glyph.space_before {
break;
}
end = end.max(glyph.x1);
}
end - self.bbox.x0
}
pub fn style_of(&self, glyph: &LineGlyph, fonts: &[FontInfo]) -> u8 {
let font = &fonts[glyph.font as usize];
let mut style = 0;
if font.bold {
style |= BOLD;
}
if font.italic {
style |= ITALIC;
}
if font.mono || self.fixed_pitch {
style |= MONO;
}
if font.math {
style |= MATH;
}
if font.sans {
style |= SANS;
}
if font.small_caps {
style |= SMALL_CAPS;
}
match glyph.script {
1 | RAISED_FRACTION_TERM => style |= SUP,
-1 => style |= SUB,
script if script == -RAISED_FRACTION_TERM => style |= SUP,
_ => {}
}
style
}
pub fn font_frac(&self, fonts: &[FontInfo], pred: impl Fn(&FontInfo) -> bool) -> f32 {
if self.glyphs.is_empty() {
return 0.0;
}
let n = self
.glyphs
.iter()
.filter(|glyph| pred(&fonts[glyph.font as usize]))
.count();
n as f32 / self.glyphs.len() as f32
}
pub fn starts_with_superscript(&self) -> bool {
self.glyphs.first().is_some_and(|glyph| glyph.script == 1)
}
}
struct Segment {
glyphs: Vec<LineGlyph>,
y: f32,
size: f32,
x0: f32,
x1: f32,
}
impl Segment {
fn from_glyphs(glyphs: Vec<LineGlyph>, cfg: &LinesConfig) -> Self {
let mut segment = Segment {
glyphs,
y: 0.0,
size: 0.0,
x0: 0.0,
x1: 0.0,
};
segment.refresh(cfg);
segment
}
fn refresh(&mut self, cfg: &LinesConfig) {
self.x0 = self.glyphs.iter().map(|glyph| glyph.x0).fold(f32::INFINITY, f32::min);
self.x1 = self
.glyphs
.iter()
.map(|glyph| glyph.x1)
.fold(f32::NEG_INFINITY, f32::max);
let base: Vec<&LineGlyph> = self.glyphs.iter().filter(|glyph| glyph.script == 0).collect();
let pool: Vec<&LineGlyph> = if base.is_empty() {
self.glyphs.iter().collect()
} else {
base
};
self.size = weighted_mode(
pool.iter().map(|glyph| (glyph.size, 1.0)),
cfg.size_bin_pt,
cfg.default_size_pt,
);
let size = self.size;
let ys: Vec<f32> = pool
.iter()
.filter(|glyph| (glyph.size - size).abs() < cfg.baseline_size_tolerance_pt)
.map(|glyph| glyph.y)
.collect();
self.y = if ys.is_empty() {
pool[0].y
} else {
median(&ys, pool[0].y)
};
}
}
#[derive(Default)]
struct RotatedRuns {
runs: Vec<RotatedText>,
last: Option<(f32, f32, f32, f32)>,
}
impl RotatedRuns {
fn push(&mut self, glyph: &Glyph, cfg: &LinesConfig) {
let (dir_x, dir_y) = (glyph.angle.to_radians().cos(), glyph.angle.to_radians().sin());
let step = self.last.map(|(x, y, adv, angle)| {
let (dx, dy) = (glyph.x - x, glyph.y - y);
let along = dx * dir_x + dy * dir_y;
let across = (dx * dir_y - dy * dir_x).abs();
(along, across, adv, angle)
});
let same = step.is_some_and(|(along, across, adv, angle)| {
(angle - glyph.angle).abs() < cfg.rotated_max_angle_diff_deg
&& across < cfg.rotated_max_offset_em * glyph.size
&& along > -cfg.rotated_max_backstep_em * glyph.size
&& along < adv + cfg.rotated_max_gap_em * glyph.size
});
if same {
let (along, _, adv, _) = step.unwrap();
let run = self.runs.last_mut().unwrap();
if along > adv + cfg.rotated_space_gap_em * glyph.size {
run.text.push(' ');
}
run.text.push_str(&glyph.text);
run.bbox = run.bbox.union(&glyph.ink);
run.length = ((glyph.x - run.x).powi(2) + (glyph.y - run.y).powi(2)).sqrt() + glyph.adv.max(0.0);
run.origins.push((glyph.x, glyph.y));
} else {
self.runs.push(RotatedText {
text: glyph.text.clone(),
bbox: glyph.ink,
x: glyph.x,
y: glyph.y,
angle: glyph.angle,
size: glyph.size,
length: glyph.adv.max(0.0),
font: glyph.font,
color: display_color(glyph.color, cfg),
origins: vec![(glyph.x, glyph.y)],
});
}
self.last = Some((glyph.x, glyph.y, glyph.adv, glyph.angle));
}
}
pub fn merge_row(page: usize, lines: Vec<Line>, cfg: &LinesConfig) -> Line {
if lines.len() == 1 {
return lines.into_iter().next().unwrap();
}
let main = lines
.iter()
.max_by_key(|line| line.glyphs.len())
.map(|line| (line.baseline, line.size))
.unwrap();
let fixed_pitch = lines.iter().any(|line| line.fixed_pitch);
let mut glyphs = Vec::new();
for line in lines {
let dy = line.baseline - main.0;
let small = line.size < cfg.row_script_max_size_ratio * main.1;
let flag = if !small { 0 } else { script_level(dy, main.1, cfg) };
for mut glyph in line.glyphs {
if glyph.script == 0 {
glyph.script = flag;
}
glyphs.push(glyph);
}
}
let mut row = finalize(page, Segment::from_glyphs(glyphs, cfg), cfg);
if fixed_pitch {
set_fixed_pitch(&mut row, cfg);
}
row
}
fn set_fixed_pitch(line: &mut Line, cfg: &LinesConfig) {
line.fixed_pitch = true;
let size = line.size;
mark_spaces(&mut line.glyphs, size, true, cfg);
}
pub fn split_at_gaps(line: &Line, min_gap: f32, cfg: &LinesConfig) -> Vec<Line> {
let mut groups: Vec<Vec<LineGlyph>> = Vec::new();
let mut right = f32::NEG_INFINITY;
for glyph in &line.glyphs {
if groups.is_empty() || glyph.x0 - right >= min_gap {
groups.push(Vec::new());
}
groups.last_mut().unwrap().push(glyph.clone());
right = right.max(glyph.x1);
}
if groups.len() <= 1 {
return vec![line.clone()];
}
groups
.into_iter()
.map(|group| finalize(line.page, Segment::from_glyphs(group, cfg), cfg))
.collect()
}
pub fn split_at_positions(line: &Line, cuts: &[f32], cfg: &LinesConfig) -> Vec<Line> {
if cuts.is_empty() {
return vec![line.clone()];
}
let mut groups: Vec<Vec<LineGlyph>> = vec![Vec::new(); cuts.len() + 1];
for glyph in &line.glyphs {
let group = cuts.iter().filter(|&&cut| glyph.x0 >= cut).count();
groups[group].push(glyph.clone());
}
groups
.into_iter()
.filter(|group| group.iter().any(|glyph| !glyph.text.trim().is_empty()))
.map(|group| finalize(line.page, Segment::from_glyphs(group, cfg), cfg))
.collect()
}
pub fn build_lines(raw: &RawPage, cfg: &LinesConfig) -> (Vec<Line>, Vec<RotatedText>) {
let (mut glyphs, rotated) = collect_glyphs(raw, cfg);
let drop_caps = take_drop_caps(raw, &mut glyphs, cfg);
let segments: Vec<Segment> = glyphs
.into_iter()
.map(|glyph| Segment::from_glyphs(vec![glyph], cfg))
.collect();
let mut segments = merge_same_baseline(segments, cfg);
reanchor_hanging_math(&mut segments, cfg);
let segments = attach_scripts(segments, cfg);
let segments = merge_same_baseline(segments, cfg);
let segments = merge_justified_gaps(segments, cfg);
let segments = split_at_gutters(segments, raw.width, cfg);
let mut lines: Vec<Line> = segments
.into_iter()
.map(|segment| finalize(raw.index, segment, cfg))
.collect();
lines.sort_by(|a, b| a.baseline.total_cmp(&b.baseline).then(a.bbox.x0.total_cmp(&b.bbox.x0)));
for (drop_cap, baseline, spaced) in drop_caps {
put_drop_cap(&mut lines, drop_cap, baseline, spaced, cfg);
}
mark_fixed_pitch(&mut lines, cfg);
gather_fractions(&mut lines, raw, cfg);
for line in &mut lines {
mark_fractions(line, raw, cfg);
}
(lines, rotated)
}
fn take_drop_caps(raw: &RawPage, glyphs: &mut Vec<LineGlyph>, cfg: &LinesConfig) -> Vec<(LineGlyph, f32, bool)> {
let mut found: Vec<(usize, f32)> = Vec::new();
for (idx, cap) in glyphs.iter().enumerate() {
if !cap.text.chars().all(char::is_alphabetic) || cap.text.is_empty() {
continue;
}
let reach = cfg.drop_cap_max_gap_em * cap.size;
let mut beside: Vec<(f32, f32)> = glyphs
.iter()
.filter(|glyph| {
glyph.size * cfg.drop_cap_min_size_ratio <= cap.size
&& glyph.y > cap.ink.y0
&& glyph.y <= cap.y + cfg.drop_cap_baseline_slack_em * glyph.size
&& glyph.x0 >= cap.x0
&& glyph.x0 <= cap.ink.x1.max(cap.x1) + reach
})
.map(|glyph| (glyph.y, glyph.size))
.collect();
beside.sort_by(|a, b| a.0.total_cmp(&b.0));
beside.dedup_by(|a, b| (a.0 - b.0).abs() <= cfg.drop_cap_baseline_slack_em * b.1);
if beside.len() >= cfg.drop_cap_min_lines_count {
found.push((idx, beside[0].0));
}
}
let mut taken: Vec<(usize, f32)> = Vec::new();
for &(idx, baseline) in &found {
let cap = &glyphs[idx];
let quote = glyphs.iter().position(|glyph| {
(glyph.size - cap.size).abs() <= cfg.drop_cap_baseline_slack_em * cap.size
&& (glyph.y - cap.y).abs() <= cfg.drop_cap_baseline_slack_em * cap.size
&& (cap.x0 - glyph.x1).abs() <= cfg.drop_cap_baseline_slack_em * cap.size
&& glyph.text.chars().all(|ch| "\"'\u{2018}\u{201C}\u{AB}".contains(ch))
});
if let Some(quote) = quote {
taken.push((quote, baseline));
}
taken.push((idx, baseline));
}
taken.sort_by_key(|&(idx, _)| std::cmp::Reverse(idx));
taken.dedup_by_key(|&mut (idx, _)| idx);
let spaced = |cap: &LineGlyph| {
raw.glyphs.iter().any(|glyph| {
glyph.text == " "
&& (glyph.y - cap.y).abs() <= cfg.drop_cap_baseline_slack_em * cap.size
&& (glyph.x - cap.x1).abs() <= cfg.drop_cap_baseline_slack_em * cap.size
})
};
let mut caps: Vec<(LineGlyph, f32, bool)> = taken
.into_iter()
.map(|(idx, baseline)| {
let cap = glyphs.remove(idx);
let space = spaced(&cap);
(cap, baseline, space)
})
.collect();
caps.sort_by(|a, b| b.0.x0.total_cmp(&a.0.x0));
caps
}
fn put_drop_cap(lines: &mut [Line], cap: LineGlyph, baseline: f32, spaced: bool, cfg: &LinesConfig) {
let line = lines
.iter_mut()
.filter(|line| {
(line.baseline - baseline).abs() <= cfg.drop_cap_baseline_slack_em * line.size && line.bbox.x0 >= cap.x0
})
.min_by(|a, b| a.bbox.x0.total_cmp(&b.bbox.x0));
let Some(line) = line else {
return;
};
if let Some(first) = line.glyphs.first_mut() {
first.space_before = spaced || first.x0 - cap.x1.max(cap.ink.x1) > cfg.space_gap_em * line.size;
}
line.bbox.x0 = line.bbox.x0.min(cap.x0);
line.ink.x0 = line.ink.x0.min(cap.ink.x0);
let mut cap = cap;
cap.script = 0;
cap.space_before = false;
line.glyphs.insert(0, cap);
}
fn gather_fractions(lines: &mut Vec<Line>, raw: &RawPage, cfg: &LinesConfig) {
let mut bars: Vec<Rect> = raw
.paths
.iter()
.chain(&raw.pixel_rules)
.filter(|path| path.is_hrule())
.map(|path| path.bbox)
.collect();
bars.sort_by(|a, b| b.width().total_cmp(&a.width()));
let mut moved = false;
for bar in bars {
let slack = cfg.fraction_bar_slack_em * lines.first().map_or(0.0, |line| line.size);
if lines.iter().any(|line| radical_bar(&line.glyphs, &bar, slack)) {
continue;
}
let Some((host, mut taken)) = fraction_on_bar(lines, &bar, cfg) else {
continue;
};
let line = &lines[host];
let level = if line.baseline - bar.cy() > cfg.fraction_raised_min_rise_em * line.size {
RAISED_FRACTION_TERM
} else {
FRACTION_TERM
};
taken.sort_by_key(|&(idx, k, _)| std::cmp::Reverse((idx, k)));
for (idx, k, sign) in taken {
if idx == host {
lines[host].glyphs[k].script = sign * level;
continue;
}
let mut glyph = lines[idx].glyphs.remove(k);
glyph.script = sign * level;
glyph.space_before = false;
lines[host].glyphs.push(glyph);
}
moved = true;
}
if !moved {
return;
}
lines.retain(|line| !line.glyphs.is_empty());
for line in lines.iter_mut() {
line.glyphs
.sort_by(|a, b| a.x0.total_cmp(&b.x0).then(b.script.cmp(&a.script)));
let first = line.glyphs.first().map_or(line.bbox.x0, |glyph| glyph.x0);
let last = line
.glyphs
.iter()
.map(|glyph| glyph.x1)
.fold(f32::NEG_INFINITY, f32::max);
line.bbox = Rect::new(first, line.bbox.y0, last, line.bbox.y1);
line.ink = line.glyphs.iter().fold(Rect::EMPTY, |acc, glyph| acc.union(&glyph.ink));
}
}
fn fraction_on_bar(lines: &[Line], bar: &Rect, cfg: &LinesConfig) -> Option<(usize, Vec<TermGlyph>)> {
let cy = bar.cy();
let host = lines.iter().position(|line| {
let rise = line.baseline - cy;
let reach = cfg.fraction_host_max_gap_em * line.size;
rise >= 0.0
&& rise <= cfg.fraction_bar_max_axis_em * line.size
&& bar.x0 <= line.bbox.x1 + reach
&& bar.x1 >= line.bbox.x0 - reach
&& !line
.glyphs
.iter()
.any(|glyph| glyph.script == 0 && glyph.x1 > bar.x0 && glyph.x0 < bar.x1)
})?;
let size = lines[host].size;
let slack = cfg.fraction_bar_slack_em * size;
let smallest = lines[host]
.glyphs
.iter()
.filter(|glyph| glyph.script == 0 && !glyph.text.chars().any(|ch| BIG_OPERATORS.contains(ch)))
.map(|glyph| glyph.size)
.reduce(f32::min)?;
let term = |glyph: &LineGlyph, sign: i8| {
let centre = (glyph.x0 + glyph.x1) / 2.0;
let middle = glyph.ink.cy();
let reach = if sign > 0 && glyph.text == "\u{221A}" {
cy - middle >= 0.0 && cy - glyph.y <= cfg.fraction_numerator_max_rise_em * size
} else if sign > 0 {
cy - middle >= 0.0 && cy - glyph.ink.y0 <= cfg.fraction_numerator_max_rise_em * size
} else {
middle - cy > 0.0 && glyph.ink.y1 - cy <= cfg.fraction_denominator_max_drop_em * size
};
reach && centre >= bar.x0 - slack && centre <= bar.x1 + slack
};
let near = |line: &Line| (line.baseline - cy).abs() <= cfg.fraction_lines_max_distance_em * size;
let found = |sign: i8| {
lines
.iter()
.enumerate()
.filter(|&(_, line)| near(line))
.flat_map(|(idx, line)| (0..line.glyphs.len()).map(move |k| (idx, k)))
.filter(|&(idx, k)| {
(lines[idx].baseline - lines[host].baseline).abs() > slack || lines[idx].glyphs[k].script != 0
})
.filter(|&(idx, k)| term(&lines[idx].glyphs[k], sign))
.map(|(idx, k)| (idx, k, sign))
.collect::<Vec<_>>()
};
let simple = |term: &[TermGlyph]| {
let glyph = |&(idx, k, _): &TermGlyph| &lines[idx].glyphs[k];
let measured: Vec<&TermGlyph> = term.iter().filter(|part| glyph(part).text != "\u{221A}").collect();
let largest = measured.iter().map(|part| glyph(part).size).fold(0.0, f32::max);
let base = |part: &TermGlyph| glyph(part).size > cfg.fraction_term_script_max_size_ratio * largest;
let base_count = measured.iter().filter(|part| base(part)).count();
measured.iter().find(|part| base(part)).is_some_and(|first| {
base_count <= cfg.fraction_term_max_glyphs_count
&& measured.iter().all(|part| {
(!base(part) || (glyph(part).y - glyph(first).y).abs() <= slack)
&& glyph(part).size <= cfg.fraction_term_max_size_ratio * smallest
})
})
};
let (mut numerator, denominator) = (found(1), found(-1));
let radicand_follows = |sign: &LineGlyph| {
numerator.iter().any(|&(idx, k, _)| {
let glyph = &lines[idx].glyphs[k];
glyph.text != "\u{221A}" && (glyph.x0 - sign.ink.x1).abs() <= slack && sign.ink.y1 >= glyph.y - slack
})
};
let radicals: Vec<bool> = numerator
.iter()
.map(|&(idx, k, _)| lines[idx].glyphs[k].text != "\u{221A}" || radicand_follows(&lines[idx].glyphs[k]))
.collect();
let mut keep = radicals.into_iter();
numerator.retain(|_| keep.next().unwrap_or(true));
if !simple(&numerator) || !simple(&denominator) {
return None;
}
numerator.extend(denominator);
Some((host, numerator))
}
fn radical_bar(glyphs: &[LineGlyph], bar: &Rect, slack: f32) -> bool {
glyphs.iter().any(|glyph| {
glyph.text == "\u{221A}" && (bar.x0 - glyph.ink.x1).abs() <= slack && (bar.cy() - glyph.ink.y0).abs() <= slack
})
}
type TermGlyph = (usize, usize, i8);
const BIG_OPERATORS: &str = "\u{2211}\u{220F}\u{222B}\u{22C3}\u{22C2}";
fn mark_fractions(line: &mut Line, raw: &RawPage, cfg: &LinesConfig) {
if !line.glyphs.iter().any(|glyph| glyph.script != 0) {
return;
}
let mut bars: Vec<Rect> = raw
.paths
.iter()
.chain(&raw.pixel_rules)
.filter(|path| path.is_hrule())
.map(|path| path.bbox)
.filter(|bar| bar.cy() > line.ink.y0 && bar.cy() < line.ink.y1 && bar.cy() < line.baseline)
.collect();
bars.sort_by(|a, b| b.width().total_cmp(&a.width()));
for bar in bars {
let Some((numerator, denominator)) = fraction_terms(line, &bar, cfg) else {
continue;
};
let raised = line.baseline - bar.cy() > cfg.fraction_raised_min_rise_em * line.size;
let level = if raised { RAISED_FRACTION_TERM } else { FRACTION_TERM };
for k in numerator {
line.glyphs[k].script = level;
}
for k in denominator {
line.glyphs[k].script = -level;
}
}
}
fn fraction_terms(line: &Line, bar: &Rect, cfg: &LinesConfig) -> Option<(Vec<usize>, Vec<usize>)> {
let glyphs = &line.glyphs;
let slack = cfg.fraction_bar_slack_em * line.size;
if radical_bar(glyphs, bar, slack) {
return None;
}
let terms: Vec<usize> = (0..glyphs.len())
.filter(|&k| {
let glyph = &glyphs[k];
let centre = (glyph.x0 + glyph.x1) / 2.0;
glyph.script != 0 && !glyph.is_fraction_term() && centre >= bar.x0 - slack && centre <= bar.x1 + slack
})
.collect();
let (first, last) = (*terms.first()?, *terms.last()?);
if (first..=last).any(|k| glyphs[k].script == 0 || glyphs[k].is_fraction_term()) {
return None;
}
let (numerator, denominator): (Vec<usize>, Vec<usize>) =
terms.iter().partition(|&&k| glyphs[k].ink.cy() < bar.cy());
if numerator.is_empty() || denominator.is_empty() {
return None;
}
let left = terms.iter().map(|&k| glyphs[k].x0).fold(f32::INFINITY, f32::min);
let right = terms.iter().map(|&k| glyphs[k].x1).fold(f32::NEG_INFINITY, f32::max);
let spans_terms = bar.x0 <= left + slack && bar.x1 >= right - slack && bar.width() <= right - left + 2.0 * slack;
let relation = terms.iter().any(|&k| {
glyphs[k]
.text
.chars()
.any(|ch| "=<>\u{2264}\u{2265}\u{2248}".contains(ch))
});
(spans_terms && !relation).then_some((numerator, denominator))
}
pub fn join_math_letters(lines: &mut [Line], fonts: &[FontInfo], cfg: &LinesConfig) {
let math = |glyph: &LineGlyph| fonts.get(glyph.font as usize).is_some_and(|font| font.math);
let letter = |glyph: &LineGlyph| {
let mut chars = glyph.text.chars();
matches!((chars.next(), chars.next()), (Some(ch), None) if ch.is_alphabetic())
};
for line in lines {
for i in 1..line.glyphs.len() {
let (prev, cur) = (&line.glyphs[i - 1], &line.glyphs[i]);
if !cur.space_before || !math(prev) || !letter(prev) || (letter(cur) && !math(cur)) {
continue;
}
let gap = cur.x0 - prev.x1.max(prev.ink.x1);
if gap <= cfg.space_gap_em * line.size {
line.glyphs[i].space_before = false;
}
}
}
}
fn collect_glyphs(raw: &RawPage, cfg: &LinesConfig) -> (Vec<LineGlyph>, Vec<RotatedText>) {
let has_visible = raw.glyphs.iter().any(|glyph| !glyph.invisible);
let mut copies = GlyphCopies::default();
let mut glyphs: Vec<LineGlyph> = Vec::new();
let mut rotated = RotatedRuns::default();
let mut space: Option<(f32, f32, f32)> = None;
for glyph in &raw.glyphs {
if glyph.invisible && has_visible {
continue;
}
if glyph.text.trim().is_empty() {
if glyph.text.contains(' ') && glyph.dir != Dir::Rotated {
space = Some((glyph.x, glyph.y, glyph.size));
}
continue;
}
let spaced = space
.take()
.is_some_and(|(x, y, size)| (glyph.y - y).abs() <= cfg.drawn_space_max_offset_em * size && glyph.x > x);
if is_off_page(glyph, raw, cfg) {
continue;
}
if glyph.dir == Dir::Rotated {
rotated.push(glyph, cfg);
continue;
}
let hash = GlyphCopies::hash(glyph);
if let Some(kept) = copies.find(glyph, hash, cfg) {
if glyphs[kept].color == display_color(glyph.color, cfg) {
glyphs[kept].extra.push((glyph.x, glyph.y));
} else {
let under = std::mem::replace(&mut glyphs[kept], line_glyph(glyph, cfg));
glyphs[kept].extra = under.extra;
glyphs[kept].extra.push((under.ox, under.oy));
}
continue;
}
copies.insert(glyph, hash, glyphs.len());
let mut kept = line_glyph(glyph, cfg);
kept.drawn_space = spaced;
kept.link = link_at(raw, glyph, cfg);
glyphs.push(kept);
}
lower_raised_accents(&mut glyphs, cfg);
let blanks = blank_glyphs(raw, &glyphs, cfg);
glyphs.extend(blanks);
(glyphs, rotated.runs)
}
fn is_brace_piece(ch: char) -> bool {
matches!(ch, '\u{23B4}'..='\u{23B6}' | '\u{23DC}'..='\u{23E1}' | '\u{FE35}'..='\u{FE44}')
}
const BLANK_NEIGHBOUR_MARKS: &str = "_-.,:;'\"()[]/、。,:「」『』()";
fn blank_glyphs(raw: &RawPage, glyphs: &[LineGlyph], cfg: &LinesConfig) -> Vec<LineGlyph> {
let rules: Vec<Rect> = raw
.paths
.iter()
.chain(&raw.pixel_rules)
.filter(|rule| rule.is_hrule() && rule.bbox.height() <= cfg.blank_max_thickness_pt && !rule.is_white())
.map(|rule| rule.bbox)
.collect();
let mut blanks = Vec::new();
if rules.is_empty() {
return blanks;
}
let mut by_y: Vec<&LineGlyph> = glyphs.iter().collect();
by_y.sort_by(|a, b| a.y.total_cmp(&b.y));
let max_size = glyphs.iter().map(|glyph| glyph.size).fold(0.0, f32::max);
let band = 2.0 * cfg.blank_stacked_max_distance_em * max_size;
for (idx, &bbox) in rules.iter().enumerate() {
let cy = bbox.cy();
let from = by_y.partition_point(|glyph| glyph.y < cy - band);
let to = by_y.partition_point(|glyph| glyph.y <= cy + band);
let near = &by_y[from..to];
let on_baseline = |glyph: &&LineGlyph| {
cy - glyph.y >= -cfg.blank_max_rise_em * glyph.size && cy - glyph.y <= cfg.blank_max_drop_em * glyph.size
};
let neighbour = near.iter().copied().filter(on_baseline).find(|glyph| {
let reach = cfg.blank_max_gap_em * glyph.size;
(glyph.x1 <= bbox.x0 + reach / 4.0 && bbox.x0 - glyph.x1 <= reach)
|| (glyph.x0 >= bbox.x1 - reach / 4.0 && glyph.x0 - bbox.x1 <= reach)
});
let after_operator = near
.iter()
.copied()
.filter(on_baseline)
.filter(|glyph| glyph.x1 <= bbox.x0 + glyph.size * cfg.blank_max_gap_em / 4.0)
.max_by(|a, b| a.x1.total_cmp(&b.x1))
.is_some_and(|left| {
bbox.x0 - left.x1 <= cfg.blank_max_gap_em * left.size
&& !left
.text
.chars()
.all(|ch| ch.is_alphanumeric() || BLANK_NEIGHBOUR_MARKS.contains(ch))
});
let Some(word) = neighbour.filter(|_| !after_operator) else {
continue;
};
if part_of_formula(near, &bbox, cfg) || part_of_drawing(raw, &rules, idx, cfg) {
continue;
}
let count = ((bbox.width() / (cfg.blank_underscore_em * word.size)).round() as usize)
.clamp(1, cfg.blank_max_underscores_count);
let mut blank = word.clone();
blank.text = "_".repeat(count);
blank.x0 = bbox.x0;
blank.x1 = bbox.x1;
blank.ox = bbox.x0;
blank.ink = Rect::new(bbox.x0, word.y, bbox.x1, bbox.y1);
blank.extra = Vec::new();
blanks.push(blank);
}
blanks
}
fn part_of_drawing(raw: &RawPage, rules: &[Rect], idx: usize, cfg: &LinesConfig) -> bool {
let bbox = rules[idx];
let underline_piece = rules.iter().enumerate().any(|(other_idx, other)| {
other_idx != idx
&& (other.cy() - bbox.cy()).abs() <= cfg.blank_max_thickness_pt
&& (other.x0 - bbox.x1).max(bbox.x0 - other.x1) <= cfg.underline_piece_max_gap_pt
});
let grow = cfg.blank_max_thickness_pt;
let near = Rect::new(bbox.x0 - grow, bbox.y0 - grow, bbox.x1 + grow, bbox.y1 + grow);
let touches_drawing = raw
.paths
.iter()
.map(|path| path.bbox)
.chain(raw.images.iter().map(|image| image.bbox))
.any(|other| other != bbox && near.intersects(&other) && !other.contains(&bbox));
underline_piece || touches_drawing
}
fn part_of_formula(glyphs: &[&LineGlyph], bbox: &Rect, cfg: &LinesConfig) -> bool {
let cy = bbox.cy();
let stacked = |glyph: &LineGlyph, factor: f32| {
(glyph.y - cy).abs() <= factor * cfg.blank_stacked_max_distance_em * glyph.size
};
glyphs.iter().any(|glyph| {
let inset = glyph.size * cfg.blank_underscore_em / 2.0;
let reach = cfg.blank_max_gap_em * glyph.size;
let covered = glyph.x1 > bbox.x0 + inset && glyph.x0 < bbox.x1 - inset && stacked(glyph, 1.0);
let radical = glyph.text.contains('\u{221A}') && (glyph.x1 - bbox.x0).abs() <= reach && stacked(glyph, 2.0);
let brace = glyph.text.chars().any(is_brace_piece)
&& glyph.x1 >= bbox.x0 - reach
&& glyph.x0 <= bbox.x1 + reach
&& stacked(glyph, 1.0);
covered || radical || brace
})
}
fn line_glyph(glyph: &Glyph, cfg: &LinesConfig) -> LineGlyph {
LineGlyph {
text: glyph.text.clone(),
x0: glyph.x,
x1: glyph.x + glyph.adv.max(0.0),
y: glyph.y,
size: glyph.size,
font: glyph.font,
script: 0,
space_before: false,
drawn_space: false,
link: None,
ink: glyph.ink,
ox: glyph.x,
oy: glyph.y,
extra: Vec::new(),
color: display_color(glyph.color, cfg),
}
}
fn link_at(raw: &RawPage, glyph: &Glyph, cfg: &LinesConfig) -> Option<std::sync::Arc<str>> {
if raw.links.is_empty() {
return None;
}
let x = glyph.x + glyph.adv.max(0.0) / 2.0;
let y = glyph.y - cfg.link_probe_height_em * glyph.size;
raw.links
.iter()
.find(|link| {
let tol = cfg.link_margin_pt;
x >= link.rect.x0 - tol && x <= link.rect.x1 + tol && y >= link.rect.y0 - tol && y <= link.rect.y1 + tol
})
.map(|link| link.uri.clone())
}
fn is_off_page(glyph: &Glyph, raw: &RawPage, cfg: &LinesConfig) -> bool {
glyph.x < -cfg.page_margin_pt
|| glyph.y < -cfg.page_margin_pt
|| glyph.x > raw.width + cfg.page_margin_pt
|| glyph.y > raw.height + cfg.page_margin_pt
}
struct KeptGlyph {
idx: usize,
x: f32,
y: f32,
next: Option<usize>,
}
#[derive(Default)]
struct GlyphCopies {
cells: HashMap<(u64, i32, i32), usize, BuildHasherDefault<FnvHasher>>,
kept: Vec<KeptGlyph>,
}
impl GlyphCopies {
fn find(&self, glyph: &Glyph, hash: u64, cfg: &LinesConfig) -> Option<usize> {
let tol = if glyph.text.contains('\u{FFFD}') {
UNKNOWN_DUPLICATE_MAX_OFFSET_PT
} else {
cfg.duplicate_max_offset_em * glyph.size
};
for row in cell(glyph.y - tol)..=cell(glyph.y + tol) {
for column in cell(glyph.x - tol)..=cell(glyph.x + tol) {
let mut at = self.cells.get(&(hash, row, column)).copied();
while let Some(i) = at {
let kept = &self.kept[i];
if (glyph.x - kept.x).abs() <= tol && (glyph.y - kept.y).abs() <= tol {
return Some(kept.idx);
}
at = kept.next;
}
}
}
None
}
fn insert(&mut self, glyph: &Glyph, hash: u64, idx: usize) {
let at = self.kept.len();
let next = self.cells.insert((hash, cell(glyph.y), cell(glyph.x)), at);
self.kept.push(KeptGlyph {
idx,
x: glyph.x,
y: glyph.y,
next,
});
}
fn hash(glyph: &Glyph) -> u64 {
let mut hasher = FnvHasher::default();
hasher.write(glyph.text.as_bytes());
hasher.finish()
}
}
fn cell(coord: f32) -> i32 {
(coord / DUPLICATE_CELL_PT).floor() as i32
}
struct FnvHasher(u64);
impl Default for FnvHasher {
fn default() -> Self {
Self(FNV_OFFSET_BASIS)
}
}
impl Hasher for FnvHasher {
fn finish(&self) -> u64 {
self.0
}
fn write(&mut self, bytes: &[u8]) {
for &byte in bytes {
self.0 = (self.0 ^ u64::from(byte)).wrapping_mul(FNV_PRIME);
}
}
}
const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0100_0000_01b3;
fn display_color(color: [u8; 3], cfg: &LinesConfig) -> [u8; 3] {
if color.iter().all(|&channel| channel < cfg.near_black_max_value) {
[0; 3]
} else {
color
}
}
fn script_level(dy: f32, size: f32, cfg: &LinesConfig) -> i8 {
if dy < -cfg.superscript_min_rise_em * size {
1
} else if dy > cfg.subscript_min_drop_em * size {
-1
} else {
0
}
}
fn combining_for(ch: char) -> Option<char> {
Some(match ch {
'\u{00B4}' | '\u{02CA}' => '\u{0301}',
'`' | '\u{02CB}' => '\u{0300}',
'\u{00A8}' => '\u{0308}',
'\u{02C6}' | '^' => '\u{0302}',
'\u{02DC}' | '~' => '\u{0303}',
'\u{00AF}' | '\u{02C9}' => '\u{0304}',
'\u{02C7}' => '\u{030C}',
'\u{02D8}' => '\u{0306}',
'\u{02D9}' => '\u{0307}',
'\u{02DA}' => '\u{030A}',
'\u{00B8}' => '\u{0327}',
'\u{02DD}' => '\u{030B}',
'\u{02DB}' => '\u{0328}',
'\u{0300}'..='\u{036F}' => ch,
_ => return None,
})
}
fn lower_raised_accents(glyphs: &mut [LineGlyph], cfg: &LinesConfig) {
for i in 0..glyphs.len() {
let mut chars = glyphs[i].text.chars();
let (Some(ch), None) = (chars.next(), chars.next()) else {
continue;
};
if ch.is_ascii() || combining_for(ch).is_none() {
continue;
}
let accent = &glyphs[i];
let width = |glyph: &LineGlyph| glyph.ink.width().max(cfg.accent_min_width_pt);
let from = i.saturating_sub(cfg.raised_accent_lookaround_count);
let to = (i + cfg.raised_accent_lookaround_count + 1).min(glyphs.len());
let letter = (from..to)
.filter(|&j| j != i)
.filter(|&j| {
let letter = &glyphs[j];
let single = letter.text.chars().count() == 1 && letter.text.chars().all(char::is_alphabetic);
let rise = letter.y - accent.y;
let overlap = accent.ink.x1.min(letter.ink.x1) - accent.ink.x0.max(letter.ink.x0);
single
&& (letter.size - accent.size).abs() <= cfg.raised_accent_size_tolerance_ratio * accent.size
&& rise > 0.0
&& rise <= cfg.raised_accent_max_rise_em * letter.size
&& overlap >= cfg.accent_min_overlap_ratio * width(accent).min(width(letter))
&& accent.ink.y1 <= letter.ink.y0 + cfg.raised_accent_overlap_em * letter.size
})
.min_by(|&a, &b| (glyphs[a].y - accent.y).total_cmp(&(glyphs[b].y - accent.y)));
if let Some(j) = letter {
glyphs[i].y = glyphs[j].y;
}
}
}
fn compose_accents(glyphs: &mut Vec<LineGlyph>, cfg: &LinesConfig) {
let mut i = 0;
while i < glyphs.len() {
let mut chars = glyphs[i].text.chars();
let (Some(ch), None) = (chars.next(), chars.next()) else {
i += 1;
continue;
};
let Some(mark) = combining_for(ch) else {
i += 1;
continue;
};
let target = if mark == NEGATION {
negation_target(glyphs, i, cfg)
} else {
accent_target(glyphs, i, cfg)
};
let Some(target) = target else {
i += 1;
continue;
};
let base = match glyphs[target].text.as_str() {
"\u{0131}" => "i".to_string(),
"\u{0237}" => "j".to_string(),
other => other.to_string(),
};
let composed: String = format!("{base}{mark}").nfc().collect();
let (accent_x0, accent_x1) = (glyphs[i].x0, glyphs[i].x1);
let ink = glyphs[i].ink;
let accent_origin = (glyphs[i].ox, glyphs[i].oy);
let accent_copies = std::mem::take(&mut glyphs[i].extra);
let letter = &mut glyphs[target];
letter.extra.push(accent_origin);
letter.extra.extend(accent_copies);
letter.text = composed;
letter.x0 = letter.x0.min(accent_x0);
letter.x1 = letter.x1.max(accent_x1);
letter.ink = letter.ink.union(&ink);
glyphs.remove(i);
if target < i {
continue;
}
}
}
fn negation_target(glyphs: &[LineGlyph], slash_idx: usize, cfg: &LinesConfig) -> Option<usize> {
let slash = &glyphs[slash_idx].ink;
let overlap = |other: &LineGlyph| -> f32 {
let mut chars = other.text.chars();
let (Some(ch), None) = (chars.next(), chars.next()) else {
return 0.0;
};
let composed: String = [ch, NEGATION].iter().collect::<String>().nfc().collect();
if composed.chars().count() != 1 {
return 0.0;
}
let ink = &other.ink;
(slash.x1.min(ink.x1) - slash.x0.max(ink.x0)) / slash.width().min(ink.width()).max(cfg.accent_min_width_pt)
};
let next = glyphs.get(slash_idx + 1).map_or(0.0, overlap);
let prev = slash_idx.checked_sub(1).map_or(0.0, |idx| overlap(&glyphs[idx]));
if next >= cfg.accent_min_overlap_ratio && next >= prev {
Some(slash_idx + 1)
} else if prev >= cfg.accent_min_overlap_ratio {
Some(slash_idx - 1)
} else {
None
}
}
fn accent_target(glyphs: &[LineGlyph], accent_idx: usize, cfg: &LinesConfig) -> Option<usize> {
let accent = &glyphs[accent_idx];
let accent_width = (accent.x1 - accent.x0).max(cfg.accent_min_width_pt);
let overlap = |other: &LineGlyph| -> f32 {
let single_letter =
other.text.chars().count() == 1 && other.text.chars().next().is_some_and(|ch| ch.is_alphabetic());
if !single_letter || other.script != accent.script {
return 0.0;
}
(accent.x1.min(other.x1) - accent.x0.max(other.x0))
/ accent_width.min((other.x1 - other.x0).max(cfg.accent_min_width_pt))
};
let next = if accent_idx + 1 < glyphs.len() {
overlap(&glyphs[accent_idx + 1])
} else {
0.0
};
let prev = if accent_idx > 0 {
overlap(&glyphs[accent_idx - 1])
} else {
0.0
};
if next >= cfg.accent_min_overlap_ratio && next >= prev {
Some(accent_idx + 1)
} else if prev >= cfg.accent_min_overlap_ratio {
Some(accent_idx - 1)
} else {
None
}
}
fn order_squeezed_punctuation(glyphs: &mut [LineGlyph], cfg: &LinesConfig) {
let punctuation = |glyph: &LineGlyph| {
let mut chars = glyph.text.chars();
matches!((chars.next(), chars.next()), (Some(ch), None) if is_cjk_punctuation(ch))
};
for i in 1..glyphs.len() {
let (prev, cur) = (&glyphs[i - 1], &glyphs[i]);
if !punctuation(prev) || !punctuation(cur) || prev.ink.is_unset() || cur.ink.is_unset() {
continue;
}
let overlap = prev.x1.min(cur.x1) - prev.x0.max(cur.x0);
let narrower = (prev.x1 - prev.x0).min(cur.x1 - cur.x0);
if overlap > cfg.squeezed_punctuation_overlap_ratio * narrower && cur.ink.cx() < prev.ink.cx() {
glyphs.swap(i - 1, i);
}
}
}
pub fn take_ruby(lines: &mut Vec<Line>, cfg: &LinesConfig) -> Vec<Line> {
let is_ruby: Vec<bool> = lines.iter().map(|line| is_ruby_line(line, lines, cfg)).collect();
let mut ruby = Vec::new();
let mut kept = Vec::with_capacity(lines.len());
for (line, flag) in std::mem::take(lines).into_iter().zip(is_ruby) {
if flag {
ruby.push(line);
} else {
kept.push(line);
}
}
*lines = kept;
ruby
}
fn is_ruby_line(line: &Line, lines: &[Line], cfg: &LinesConfig) -> bool {
let kana = |ch: char| matches!(ch, '\u{3041}'..='\u{30FF}');
let kanji = |text: &str| {
text.chars()
.any(|ch| matches!(ch, '\u{4E00}'..='\u{9FFF}' | '\u{3400}'..='\u{4DBF}' | '\u{3005}'))
};
let glyphs: Vec<&LineGlyph> = line
.glyphs
.iter()
.filter(|glyph| !glyph.text.trim().is_empty())
.collect();
if glyphs.is_empty() || !glyphs.iter().all(|glyph| glyph.text.chars().all(kana)) {
return false;
}
lines.iter().any(|base| {
let gap = base.bbox.y0 - line.bbox.y1;
line.size <= cfg.ruby_max_size_ratio * base.size
&& base.baseline > line.baseline
&& gap <= cfg.ruby_max_gap_em * base.size
&& gap >= -cfg.ruby_max_gap_em * base.size
&& {
let over = glyphs
.iter()
.filter(|glyph| {
let cx = (glyph.x0 + glyph.x1) / 2.0;
base.glyphs.iter().any(|kanji_glyph| {
kanji(&kanji_glyph.text)
&& cx >= kanji_glyph.x0 - line.size
&& cx <= kanji_glyph.x1 + line.size
})
})
.count();
over as f32 >= cfg.ruby_over_kanji_min_ratio * glyphs.len() as f32
}
})
}
fn is_cjk_punctuation(ch: char) -> bool {
matches!(ch, '\u{3000}'..='\u{303F}' | '\u{30FB}')
|| (matches!(ch, '\u{FF01}'..='\u{FF65}') && !ch.is_alphanumeric())
}
fn finalize(page: usize, mut segment: Segment, cfg: &LinesConfig) -> Line {
segment.glyphs.sort_by(|a, b| a.x0.total_cmp(&b.x0));
order_squeezed_punctuation(&mut segment.glyphs, cfg);
compose_accents(&mut segment.glyphs, cfg);
segment.refresh(cfg);
let size = segment.size;
mark_spaces(&mut segment.glyphs, size, false, cfg);
let ink = segment
.glyphs
.iter()
.fold(Rect::EMPTY, |acc, glyph| acc.union(&glyph.ink));
let font = {
let mut counts: std::collections::HashMap<u16, usize> = std::collections::HashMap::new();
for glyph in segment.glyphs.iter().filter(|glyph| glyph.script == 0) {
*counts.entry(glyph.font).or_default() += 1;
}
counts
.into_iter()
.max_by_key(|&(font, count)| (count, std::cmp::Reverse(font)))
.map(|(font, _)| font)
.unwrap_or(segment.glyphs[0].font)
};
Line {
page,
bbox: Rect::new(
segment.x0,
segment.y - cfg.line_box_ascent_em * size,
segment.x1,
segment.y + cfg.line_box_descent_em * size,
),
ink,
baseline: segment.y,
size,
font,
glyphs: segment.glyphs,
fixed_pitch: false,
}
}
fn mark_fixed_pitch(lines: &mut [Line], cfg: &LinesConfig) {
let spreads: Vec<Spread> = lines
.iter()
.map(|line| spread_of(&line.glyphs, line.size, cfg))
.collect();
let mut groups: Vec<(Vec<usize>, Rect)> = Vec::new();
for idx in (0..lines.len()).filter(|&idx| spreads[idx] == Spread::Columns) {
let line = &lines[idx];
let joins = groups.last().is_some_and(|(group, hull)| {
let prev = &lines[group[group.len() - 1]];
line.baseline - prev.baseline <= cfg.fixed_pitch_max_line_gap_em * line.size && overlaps(&line.bbox, hull)
});
match groups.last_mut() {
Some((group, hull)) if joins => {
group.push(idx);
*hull = hull.union(&line.bbox);
}
_ => groups.push((vec![idx], line.bbox)),
}
}
let mut marked = vec![false; lines.len()];
for (group, hull) in groups
.iter()
.filter(|(group, _)| group.len() >= cfg.fixed_pitch_min_lines)
{
let (first, last) = (group[0], group[group.len() - 1]);
for idx in first..=last {
marked[idx] |= overlaps(&lines[idx].bbox, hull);
}
let neighbour = |from: usize, to: usize| {
(lines[to].baseline - lines[from].baseline).abs() <= cfg.fixed_pitch_max_line_gap_em * lines[to].size
};
let mut edge = first;
for idx in (0..first).rev() {
if !overlaps(&lines[idx].bbox, hull) {
continue;
}
if spreads[idx] == Spread::None || !neighbour(edge, idx) {
break;
}
marked[idx] = true;
edge = idx;
}
let mut edge = last;
for idx in last + 1..lines.len() {
if !overlaps(&lines[idx].bbox, hull) {
continue;
}
if spreads[idx] == Spread::None || !neighbour(edge, idx) {
break;
}
marked[idx] = true;
edge = idx;
}
}
for (line, _) in lines.iter_mut().zip(&marked).filter(|(_, marked)| **marked) {
set_fixed_pitch(line, cfg);
}
}
fn overlaps(a: &Rect, b: &Rect) -> bool {
a.x0 < b.x1 && b.x0 < a.x1
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Spread {
None,
Some,
Columns,
}
fn spread_of(glyphs: &[LineGlyph], size: f32, cfg: &LinesConfig) -> Spread {
let tolerance = cfg.fixed_pitch_gap_tolerance_pt;
let mut trackings: Vec<f32> = Vec::new();
let mut short_word = false;
let mut run: Option<(f32, usize)> = None;
let mut close_run = |run: &mut Option<(f32, usize)>| {
if let Some((gap, len)) = run.take()
&& gap > cfg.fixed_pitch_min_gap_em * size
{
if len >= cfg.fixed_pitch_min_run {
trackings.push(gap);
} else if len >= FIXED_PITCH_SHORT_RUN {
short_word = true;
}
}
};
for pair in glyphs.windows(2) {
let gap = pair[1].x0 - pair[0].x1;
if gap > cfg.fixed_pitch_max_gap_em * size {
close_run(&mut run);
continue;
}
match run {
Some((first, len)) if (gap - first).abs() < tolerance => run = Some((first, len + 1)),
_ => {
close_run(&mut run);
run = Some((gap, 1));
}
}
}
close_run(&mut run);
let brackets = !glyphs.is_empty()
&& glyphs.len() <= FIXED_PITCH_BRACKETS_MAX
&& glyphs
.iter()
.all(|glyph| glyph.text.chars().all(|ch| "(){}[];,".contains(ch)));
match trackings.first() {
Some(&first) if trackings.iter().any(|tracking| (tracking - first).abs() >= tolerance) => Spread::Columns,
Some(_) => Spread::Some,
None if brackets || short_word => Spread::Some,
None => Spread::None,
}
}
fn mark_spaces(glyphs: &mut [LineGlyph], size: f32, fixed_pitch: bool, cfg: &LinesConfig) {
let n = glyphs.len();
let usual_gap = median_glyph_gap(glyphs).max(0.0);
let mut gaps: Vec<(f32, f32)> = vec![(f32::NEG_INFINITY, size); n];
for i in 1..n {
let (prev, cur) = (&glyphs[i - 1], &glyphs[i]);
let reference = if prev.script != 0 && cur.script != 0 {
prev.size.max(cur.size)
} else {
size
};
let right = glyphs[..i]
.iter()
.rev()
.take(cfg.space_lookback_count)
.map(|glyph| glyph.x1)
.fold(f32::NEG_INFINITY, f32::max);
gaps[i] = (cur.x0 - right.max(prev.x1), reference);
}
let is_tight = |&(gap, reference): &(f32, f32)| {
gap > cfg.tight_space_gap_em * reference
&& gap <= cfg.space_gap_em * reference
&& gap > cfg.tight_space_ratio * usual_gap
};
let gap_is_tight: Vec<bool> = (0..n).map(|i| i > 0 && is_tight(&gaps[i])).collect();
let mut run_len = vec![0usize; n];
let mut start = 0;
while start < n {
let mut end = start;
while end < n && gap_is_tight[end] {
end += 1;
}
for len in &mut run_len[start..end] {
*len = end - start;
}
start = end + 1;
}
let tight: Vec<bool> = (0..n)
.map(|i| {
gap_is_tight[i] && glyphs[i].script == 0 && glyphs[i - 1].script == 0 && run_len[i] <= TIGHT_SPACE_MAX_RUN
})
.collect();
let tight_spaces = tight.iter().filter(|&&is_space| is_space).count() >= cfg.tight_space_min_count;
for (i, glyph) in glyphs.iter_mut().enumerate() {
glyph.space_before = if fixed_pitch {
gaps[i].0 > cfg.fixed_pitch_space_gap_em * gaps[i].1
} else {
gaps[i].0 > cfg.space_gap_em * gaps[i].1
|| (tight_spaces && tight[i])
|| (glyph.drawn_space && gaps[i].0 > cfg.drawn_space_min_gap_em * gaps[i].1)
};
}
if let Some(glyph) = glyphs.first_mut() {
glyph.space_before = false;
}
}
fn median_glyph_gap(glyphs: &[LineGlyph]) -> f32 {
let mut gaps: Vec<f32> = glyphs.windows(2).map(|pair| pair[1].x0 - pair[0].x1).collect();
gaps.sort_by(f32::total_cmp);
gaps.get(gaps.len() / 2).copied().unwrap_or(0.0)
}
fn merge_same_baseline(mut segments: Vec<Segment>, cfg: &LinesConfig) -> Vec<Segment> {
segments.sort_by(|a, b| a.y.total_cmp(&b.y).then(a.x0.total_cmp(&b.x0)));
let mut out: Vec<Segment> = Vec::with_capacity(segments.len());
let mut rest = segments.into_iter().peekable();
while let Some(first) = rest.next() {
let (first_y, reach) = (first.y, cfg.same_baseline_pt + cfg.same_baseline_em * first.size);
let mut group = vec![first];
while let Some(segment) = rest.next_if(|segment| segment.y - first_y <= reach) {
group.push(segment);
}
group.sort_by(|a, b| a.x0.total_cmp(&b.x0));
merge_group(group, cfg, &mut out);
}
out
}
fn merge_group(group: Vec<Segment>, cfg: &LinesConfig, out: &mut Vec<Segment>) {
let mut cur: Option<(Segment, Option<SizeTally>)> = None;
for segment in group {
match cur.as_mut() {
Some((current, tally))
if segment.x0 - current.x1 <= cfg.merge_max_gap_em * current.size.max(segment.size)
&& (current.size / segment.size).max(segment.size / current.size) < cfg.merge_max_size_factor =>
{
let tally = tally.get_or_insert_with(|| SizeTally::new(¤t.glyphs, cfg.size_bin_pt));
tally.add(&segment.glyphs, cfg.size_bin_pt);
current.x0 = current.x0.min(segment.x0);
current.x1 = current.x1.max(segment.x1);
current.glyphs.extend(segment.glyphs);
current.size = tally.dominant(cfg.size_bin_pt, cfg.default_size_pt);
}
_ => {
out.extend(
cur.take()
.map(|(current, tally)| finish_merge(current, tally.is_some(), cfg)),
);
cur = Some((segment, None));
}
}
}
out.extend(cur.map(|(current, tally)| finish_merge(current, tally.is_some(), cfg)));
}
fn finish_merge(mut segment: Segment, merged: bool, cfg: &LinesConfig) -> Segment {
if merged {
segment.refresh(cfg);
}
segment
}
struct SizeTally {
base: HashMap<i32, u32>,
all: HashMap<i32, u32>,
}
impl SizeTally {
fn new(glyphs: &[LineGlyph], step: f32) -> Self {
let mut tally = SizeTally {
base: HashMap::new(),
all: HashMap::new(),
};
tally.add(glyphs, step);
tally
}
fn add(&mut self, glyphs: &[LineGlyph], step: f32) {
for glyph in glyphs {
let bucket = (glyph.size / step).round() as i32;
*self.all.entry(bucket).or_insert(0) += 1;
if glyph.script == 0 {
*self.base.entry(bucket).or_insert(0) += 1;
}
}
}
fn dominant(&self, step: f32, default: f32) -> f32 {
let hist = if self.base.is_empty() { &self.all } else { &self.base };
hist.iter()
.max_by(|a, b| a.1.cmp(b.1).then(b.0.cmp(a.0)))
.map_or(default, |(bucket, _)| *bucket as f32 * step)
}
}
fn merge_justified_gaps(mut segments: Vec<Segment>, cfg: &LinesConfig) -> Vec<Segment> {
segments.sort_by(|a, b| a.y.total_cmp(&b.y).then(a.x0.total_cmp(&b.x0)));
let mut runs: Vec<(usize, usize)> = Vec::new();
let mut i = 0;
while i < segments.len() {
let mut end = i;
while end + 1 < segments.len() && joinable(&segments[end], &segments[end + 1], cfg) {
end += 1;
}
let found = (i + 1..=end).rev().find(|&last| {
let pieces = &segments[i..=last];
let widest = pieces
.windows(2)
.map(|pair| pair[1].x0 - pair[0].x1)
.fold(0.0, f32::max);
stretched(pieces, widest, cfg)
&& pieces[1..].iter().all(has_word)
&& spanned(pieces, &segments, cfg)
&& pieces
.windows(2)
.all(|pair| !gutter(&pair[0], &pair[1], &segments, cfg))
});
match found {
Some(last) => {
runs.push((i, last));
i = last + 1;
}
None => i += 1,
}
}
for &(first, last) in runs.iter().rev() {
let rest: Vec<Segment> = segments.drain(first + 1..=last).collect();
for piece in rest {
segments[first].glyphs.extend(piece.glyphs);
}
segments[first].refresh(cfg);
}
segments
}
fn joinable(left: &Segment, right: &Segment, cfg: &LinesConfig) -> bool {
let gap = right.x0 - left.x1;
(right.y - left.y).abs() <= cfg.same_baseline_pt + cfg.same_baseline_em * left.size
&& gap > 0.0
&& gap <= cfg.justified_max_gap_em * left.size.max(right.size)
&& (left.size / right.size).max(right.size / left.size) < cfg.merge_max_size_factor
}
fn stretched(pieces: &[Segment], widest: f32, cfg: &LinesConfig) -> bool {
let mut spaces: Vec<f32> = Vec::new();
for piece in pieces {
let mut glyphs: Vec<&LineGlyph> = piece
.glyphs
.iter()
.filter(|glyph| !glyph.text.trim().is_empty())
.collect();
glyphs.sort_by(|a, b| a.x0.total_cmp(&b.x0));
spaces.extend(
glyphs
.windows(2)
.map(|pair| pair[1].x0 - pair[0].x1)
.filter(|&gap| gap > cfg.space_gap_em * piece.size),
);
}
if spaces.len() < 2 {
return false;
}
spaces.sort_by(f32::total_cmp);
widest <= cfg.justified_max_gap_ratio * spaces[spaces.len() / 2]
}
fn has_word(piece: &Segment) -> bool {
let mut glyphs: Vec<&LineGlyph> = piece.glyphs.iter().collect();
glyphs.sort_by(|a, b| a.x0.total_cmp(&b.x0));
let lower = |glyph: &LineGlyph| !glyph.text.is_empty() && glyph.text.chars().all(char::is_lowercase);
glyphs.windows(2).any(|pair| lower(pair[0]) && lower(pair[1]))
}
fn spanned(pieces: &[Segment], all: &[Segment], cfg: &LinesConfig) -> bool {
let (first, last) = (&pieces[0], &pieces[pieces.len() - 1]);
let size = pieces.iter().map(|piece| piece.size).fold(0.0, f32::max);
all.iter().any(|other| {
let step = (other.y - first.y).abs();
step >= cfg.justified_min_step_em * size
&& step <= cfg.justified_max_step_em * size
&& (other.size - size).abs() <= cfg.justified_edge_tol_pt
&& other.x0 <= first.x0 + cfg.justified_edge_tol_pt
&& other.x0 >= first.x0 - cfg.justified_max_indent_em * size
&& (other.x1 - last.x1).abs() <= cfg.justified_edge_tol_pt
})
}
fn gutter(left: &Segment, right: &Segment, all: &[Segment], cfg: &LinesConfig) -> bool {
let size = left.size.max(right.size);
all.iter().any(|other| {
!std::ptr::eq(other, left)
&& !std::ptr::eq(other, right)
&& (other.y - left.y).abs() <= cfg.justified_gutter_reach_em * size
&& ((other.x1 - left.x1).abs() <= cfg.justified_gutter_tol_pt
|| (other.x0 - right.x0).abs() <= cfg.justified_gutter_tol_pt)
})
}
fn split_at_gutters(segments: Vec<Segment>, page_width: f32, cfg: &LinesConfig) -> Vec<Segment> {
let zone = (cfg.gutter_zone.0 * page_width, cfg.gutter_zone.1 * page_width);
let all: Vec<&Segment> = segments.iter().collect();
let mut gutters: Vec<Option<(f32, f32)>> = vec![None; segments.len()];
if let Some(gutter) = find_gutter(&all, zone, cfg.gutter_min_column_lines, cfg.gutter_min_width_pt, cfg) {
gutters.fill(Some(gutter));
} else {
let mut order: Vec<usize> = (0..segments.len()).collect();
order.sort_by(|&a, &b| segments[a].y.total_cmp(&segments[b].y));
let mut rows: Vec<Vec<usize>> = Vec::new();
for index in order {
match rows.last_mut() {
Some(row)
if (segments[row[0]].y - segments[index].y).abs()
<= cfg.same_baseline_pt + cfg.same_baseline_em * segments[index].size =>
{
row.push(index)
}
_ => rows.push(vec![index]),
}
}
let rows_per_window = cfg.gutter_window_rows;
for start in (0..rows.len()).step_by((rows_per_window / 2).max(1)) {
let members: Vec<usize> = rows[start..(start + rows_per_window).min(rows.len())].concat();
let window: Vec<&Segment> = members.iter().map(|&index| &segments[index]).collect();
let min_width = cfg
.gutter_window_min_width_pt
.max(cfg.gutter_window_space_factor * median_space(&window, cfg));
let lines = cfg.gutter_window_min_lines;
if let Some(gutter) = find_gutter(&window, zone, lines, min_width, cfg)
.filter(|&gutter| prose_on_both_sides(&window, gutter, cfg))
{
for index in members {
gutters[index] = gutters[index].or(Some(gutter));
}
}
}
}
let mut out = Vec::with_capacity(segments.len());
for (segment, gutter) in segments.into_iter().zip(gutters) {
match gutter {
Some(gutter) => out.extend(cut_at_gutter(segment, gutter, cfg)),
None => out.push(segment),
}
}
out
}
fn prose_on_both_sides(segments: &[&Segment], gutter: (f32, f32), cfg: &LinesConfig) -> bool {
let side_is_prose = |left: bool| {
let pieces: Vec<String> = segments
.iter()
.map(|segment| {
visible_glyphs(segment)
.into_iter()
.filter(|glyph| {
if left {
glyph.x1 <= gutter.1
} else {
glyph.x0 >= gutter.0
}
})
.map(|glyph| glyph.text.as_str())
.collect::<String>()
})
.filter(|piece| !piece.is_empty())
.collect();
let mut lengths: Vec<usize> = pieces.iter().map(|piece| piece.chars().count()).collect();
lengths.sort_unstable();
let chars: usize = lengths.iter().sum();
let letters: usize = pieces
.iter()
.map(|piece| piece.chars().filter(|ch| ch.is_alphabetic()).count())
.sum();
lengths
.get(lengths.len() / 2)
.is_some_and(|&median| median >= cfg.gutter_window_min_piece_chars)
&& letters as f32 >= cfg.gutter_window_min_letter_ratio * chars as f32
};
side_is_prose(true) && side_is_prose(false)
}
fn visible_glyphs(segment: &Segment) -> Vec<&LineGlyph> {
let mut glyphs: Vec<&LineGlyph> = segment
.glyphs
.iter()
.filter(|glyph| !glyph.text.trim().is_empty())
.collect();
glyphs.sort_by(|a, b| a.x0.total_cmp(&b.x0));
glyphs
}
fn median_space(segments: &[&Segment], cfg: &LinesConfig) -> f32 {
let mut spaces: Vec<f32> = segments
.iter()
.flat_map(|segment| {
let glyphs = visible_glyphs(segment);
glyphs
.windows(2)
.map(|pair| pair[1].x0 - pair[0].x1)
.filter(|&gap| gap > cfg.space_gap_em * segment.size)
.collect::<Vec<f32>>()
})
.collect();
spaces.sort_by(f32::total_cmp);
spaces.get(spaces.len() / 2).copied().unwrap_or(0.0)
}
fn find_gutter(
segments: &[&Segment],
zone: (f32, f32),
min_lines: usize,
min_width: f32,
cfg: &LinesConfig,
) -> Option<(f32, f32)> {
let (lo, hi) = zone;
let bins = (hi - lo).max(0.0).ceil() as usize;
if bins == 0 || segments.len() < min_lines {
return None;
}
let mut covered = vec![0usize; bins];
let mut gapped = vec![0usize; bins];
let bin_of = |x: f32| ((x - lo).floor().max(0.0) as usize).min(bins);
for segment in segments {
let glyphs = visible_glyphs(segment);
let mut ink = vec![false; bins];
for glyph in &glyphs {
let (from, to) = (bin_of(glyph.x0), bin_of(glyph.x1));
for flag in ink.iter_mut().take(to).skip(from) {
*flag = true;
}
}
for (count, flag) in covered.iter_mut().zip(&ink) {
*count += usize::from(*flag);
}
for pair in glyphs.windows(2) {
let (from, to) = (bin_of(pair[0].x1), bin_of(pair[1].x0));
for count in gapped.iter_mut().take(to).skip(from) {
*count += 1;
}
}
}
let max_cover = (cfg.gutter_max_cover_ratio * segments.len() as f32).max(1.0) as usize;
let mut best: Option<(usize, usize)> = None;
let mut start = None;
for bin in 0..=bins {
match (bin < bins && covered[bin] <= max_cover, start) {
(true, None) => start = Some(bin),
(false, Some(first)) => {
let reach = cfg.gutter_edge_reach_pt as usize;
let left = covered[first.saturating_sub(reach)..first]
.iter()
.max()
.copied()
.unwrap_or(0);
let right = covered[bin..(bin + reach).min(bins)].iter().max().copied().unwrap_or(0);
let flanked = left >= min_lines && right >= min_lines;
let crossed = gapped[first..bin].iter().any(|&count| count > 0);
if flanked && crossed && best.is_none_or(|(a, b)| bin - first > b - a) {
best = Some((first, bin));
}
start = None;
}
_ => {}
}
}
best.filter(|(first, last)| (last - first) as f32 >= min_width)
.map(|(first, last)| (lo + first as f32, lo + last as f32))
}
fn cut_at_gutter(segment: Segment, gutter: (f32, f32), cfg: &LinesConfig) -> Vec<Segment> {
let (gutter_x0, gutter_x1) = gutter;
let mut glyphs = segment.glyphs.clone();
glyphs.sort_by(|a, b| a.x0.total_cmp(&b.x0));
let cut = glyphs.windows(2).position(|pair| {
pair[1].x0.min(gutter_x1) - pair[0].x1.max(gutter_x0) >= cfg.gutter_min_span_ratio * (gutter_x1 - gutter_x0)
});
match cut {
Some(at) => {
let right = glyphs.split_off(at + 1);
vec![Segment::from_glyphs(glyphs, cfg), Segment::from_glyphs(right, cfg)]
}
None => vec![segment],
}
}
fn reanchor_hanging_math(segments: &mut [Segment], cfg: &LinesConfig) {
for segment in segments.iter_mut() {
let ink = segment
.glyphs
.iter()
.fold(Rect::EMPTY, |acc, glyph| acc.union(&glyph.ink));
if ink.is_unset() {
continue;
}
let axis = segment.y - cfg.math_axis_em * segment.size;
if (ink.cy() - axis).abs() > cfg.math_reanchor_min_offset_em * segment.size {
let y = ink.cy() + cfg.math_axis_em * segment.size;
for glyph in segment.glyphs.iter_mut() {
glyph.y = y;
}
segment.refresh(cfg);
}
}
}
fn attach_scripts(mut segments: Vec<Segment>, cfg: &LinesConfig) -> Vec<Segment> {
let mut order: Vec<usize> = (0..segments.len()).collect();
order.sort_by(|&a, &b| segments[a].size.total_cmp(&segments[b].size));
let mut slots: Vec<Option<Segment>> = segments.drain(..).map(Some).collect();
for script_idx in order {
let Some(host_idx) = find_host(&slots, script_idx, cfg) else {
continue;
};
let script = slots[script_idx].take().unwrap();
let host = slots[host_idx].as_mut().unwrap();
let dy = script.y - host.y;
let flag = script_level(dy, host.size, cfg);
for mut glyph in script.glyphs {
if flag != 0 {
glyph.script = flag;
}
host.glyphs.push(glyph);
}
host.x0 = host.x0.min(script.x0);
host.x1 = host.x1.max(script.x1);
}
slots.into_iter().flatten().collect()
}
fn find_host(slots: &[Option<Segment>], script_idx: usize, cfg: &LinesConfig) -> Option<usize> {
let script = slots[script_idx].as_ref()?;
let (script_y, script_size, script_x0, script_x1) = (script.y, script.size, script.x0, script.x1);
let mut best: Option<(usize, f32)> = None;
for (host_idx, host) in slots.iter().enumerate() {
let Some(host) = host else { continue };
if host_idx == script_idx || host.size < cfg.host_min_size_factor * script_size {
continue;
}
let dy = script_y - host.y;
if dy < -cfg.script_max_rise_em * host.size || dy > cfg.script_max_drop_em * host.size {
continue;
}
let slack = cfg.script_slack_em * host.size;
if script_x0 > host.x1 + slack || script_x1 < host.x0 - slack {
continue;
}
let score = dy.abs() / host.size;
if best.is_none_or(|(_, best_score)| score < best_score) {
best = Some((host_idx, score));
}
}
best.map(|(host_idx, _)| host_idx)
}
#[cfg(test)]
mod tests {
use super::*;
fn glyph(text: &str, x: f32, color: [u8; 3]) -> Glyph {
Glyph {
text: text.to_string(),
x,
y: 100.0,
adv: 5.0,
size: 10.0,
font: 0,
dir: Dir::Horizontal,
angle: 0.0,
invisible: false,
color,
ink: Rect::new(x, 93.0, x + 5.0, 100.0),
}
}
fn page(glyphs: Vec<Glyph>) -> RawPage {
RawPage {
width: 200.0,
height: 200.0,
glyphs,
..Default::default()
}
}
pub(crate) fn sized(text: &str, x: f32, y: f32, size: f32) -> Glyph {
let adv = 0.5 * size;
Glyph {
text: text.to_string(),
x,
y,
adv,
size,
font: 0,
dir: Dir::Horizontal,
angle: 0.0,
invisible: false,
color: [0; 3],
ink: Rect::new(x, y - 0.7 * size, x + adv, y),
}
}
pub(crate) fn words(text: &str, x: f32, y: f32, size: f32) -> Vec<Glyph> {
let mut x = x;
text.chars()
.map(|ch| {
let glyph = sized(&ch.to_string(), x, y, size);
x += glyph.adv;
glyph
})
.collect()
}
fn drop_cap_page(first_line: &str, spaced: bool) -> RawPage {
let mut cap = sized("I", 10.0, 112.0, 30.0);
cap.ink = Rect::new(10.0, 92.0, 22.0, 112.0);
let mut glyphs = vec![cap];
if spaced {
glyphs.push(sized(" ", 25.0, 112.0, 30.0));
}
let start = if spaced { 31.0 } else { 25.2 };
glyphs.extend(words(first_line, start, 100.0, 10.0));
glyphs.extend(words("universally acknowledged that", start, 112.0, 10.0));
glyphs.extend(words("a single man in possession", 10.0, 124.0, 10.0));
page(glyphs)
}
#[test]
fn drop_cap_starts_the_line_beside_its_top() {
let (lines, _) = build_lines(&drop_cap_page("t is a truth", false), &LinesConfig::default());
let texts: Vec<String> = lines.iter().map(Line::text).collect();
assert_eq!(
texts,
[
"It is a truth",
"universally acknowledged that",
"a single man in possession"
]
);
assert!(
lines
.iter()
.all(|line| line.glyphs.iter().all(|glyph| glyph.script == 0))
);
}
#[test]
fn drop_cap_followed_by_a_drawn_space_is_a_word() {
let (lines, _) = build_lines(&drop_cap_page("couldn't sleep", true), &LinesConfig::default());
assert_eq!(lines[0].text(), "I couldn't sleep");
}
#[test]
fn white_halo_copies_give_way_to_the_text_on_top() {
let white = [255; 3];
let raw = page(vec![
glyph("g", 49.5, white),
glyph("g", 50.5, white),
glyph("g", 50.0, [0; 3]),
]);
let (glyphs, _) = collect_glyphs(&raw, &LinesConfig::default());
assert_eq!(glyphs.len(), 1);
assert_eq!(glyphs[0].color, [0; 3]);
assert_eq!(glyphs[0].ox, 50.0);
let mut copies = glyphs[0].extra.clone();
copies.sort_by(|a, b| a.0.total_cmp(&b.0));
assert_eq!(copies, vec![(49.5, 100.0), (50.5, 100.0)]);
}
fn line_glyph_at(text: &str, (x0, x1): (f32, f32), (ink_x0, ink_x1): (f32, f32)) -> LineGlyph {
LineGlyph {
text: text.to_string(),
x0,
x1,
y: 100.0,
size: 10.0,
font: 0,
script: 0,
space_before: false,
drawn_space: false,
link: None,
ink: Rect::new(ink_x0, 93.0, ink_x1, 101.0),
ox: x0,
oy: 100.0,
extra: Vec::new(),
color: [0; 3],
}
}
#[test]
fn squeezed_japanese_punctuation_keeps_its_order() {
let mut glyphs = vec![
line_glyph_at("\u{300C}", (364.75, 375.02), (370.0, 374.0)),
line_glyph_at("\u{3002}", (365.57, 375.84), (366.0, 369.0)),
];
order_squeezed_punctuation(&mut glyphs, &LinesConfig::default());
assert_eq!(glyphs[0].text, "\u{3002}");
assert_eq!(glyphs[1].text, "\u{300C}");
}
#[test]
fn negation_slash_over_equals_is_not_equal() {
let mut glyphs = vec![
line_glyph_at("\u{0338}", (50.0, 50.0), (51.0, 56.0)),
line_glyph_at("=", (50.0, 57.8), (50.6, 57.2)),
];
compose_accents(&mut glyphs, &LinesConfig::default());
assert_eq!(glyphs.len(), 1);
assert_eq!(glyphs[0].text, "\u{2260}");
}
#[test]
fn tilde_raised_over_a_capital_joins_it() {
let letter = line_glyph_at("B", (50.0, 56.5), (50.5, 56.0));
let mut tilde = line_glyph_at("\u{02DC}", (51.0, 55.0), (51.5, 54.5));
tilde.y = 98.0;
tilde.ink = Rect::new(51.5, 91.0, 54.5, 92.0);
let mut sub = line_glyph_at("i", (56.5, 59.0), (56.8, 58.5));
sub.y = 102.0;
sub.size = 7.0;
let cfg = LinesConfig::default();
let mut glyphs = vec![tilde, letter, sub];
lower_raised_accents(&mut glyphs, &cfg);
assert_eq!(glyphs[0].y, 100.0);
glyphs.swap(0, 1);
compose_accents(&mut glyphs, &cfg);
assert_eq!(glyphs[0].text, "B\u{0303}");
assert_eq!(glyphs.len(), 2);
}
#[test]
fn neighbouring_equal_letters_are_not_copies() {
let raw = page(vec![glyph("l", 50.0, [0; 3]), glyph("l", 52.8, [0; 3])]);
let (glyphs, _) = collect_glyphs(&raw, &LinesConfig::default());
assert_eq!(glyphs.len(), 2);
}
#[test]
fn close_glyphs_without_unicode_are_kept() {
let raw = page(vec![glyph("\u{FFFD}", 50.0, [0; 3]), glyph("\u{FFFD}", 50.6, [0; 3])]);
let (glyphs, _) = collect_glyphs(&raw, &LinesConfig::default());
assert_eq!(glyphs.len(), 2);
}
}
#[cfg(test)]
mod ruby_tests {
use super::*;
fn line_at(text: &str, x: f32, baseline: f32, size: f32) -> Line {
let glyphs: Vec<LineGlyph> = text
.chars()
.enumerate()
.map(|(i, ch)| {
let x0 = x + i as f32 * size;
LineGlyph {
text: ch.to_string(),
x0,
x1: x0 + size,
y: baseline,
size,
font: 0,
script: 0,
space_before: false,
drawn_space: false,
link: None,
ink: Rect::new(x0, baseline - 0.8 * size, x0 + size, baseline),
ox: x0,
oy: baseline,
extra: Vec::new(),
color: [0, 0, 0],
}
})
.collect();
let x1 = glyphs.last().map_or(x, |glyph| glyph.x1);
Line {
page: 0,
bbox: Rect::new(x, baseline - 0.8 * size, x1, baseline + 0.2 * size),
ink: Rect::new(x, baseline - 0.8 * size, x1, baseline),
baseline,
size,
font: 0,
glyphs,
fixed_pitch: false,
}
}
#[test]
fn furigana_over_kanji_leave_the_text() {
let cfg = LinesConfig::default();
let mut lines = vec![
line_at("きょう", 100.0, 100.0, 5.0),
line_at("今日はいい天気", 100.0, 110.0, 10.0),
];
let ruby = take_ruby(&mut lines, &cfg);
assert_eq!(ruby.len(), 1);
assert_eq!(lines.len(), 1);
let mut lines = vec![
line_at("そうですね", 100.0, 100.0, 10.0),
line_at("今日", 100.0, 112.0, 10.0),
];
assert!(take_ruby(&mut lines, &cfg).is_empty());
}
}