use super::fonts::{FontRegistry, UNKNOWN_FONT};
use super::symbols::MAPSTO_STEM;
use crate::common::geom::Rect;
use hayro_interpret::font::{Glyph as PdfGlyph, GlyphRun};
use hayro_interpret::hayro_cmap::BfString;
use hayro_interpret::util::TransformExt;
use hayro_interpret::{
BlendMode, ClipPath, Context, Device, DrawMode, DrawProps, Image, ImageDrawProps, InterpreterCache,
InterpreterSettings, Paint, SoftMask, interpret_page,
};
use hayro_syntax::page::Page;
use kurbo::{Affine, BezPath, Point, Shape};
const EM_BOX_ASCENT_EM: f32 = 0.75;
const EM_BOX_DESCENT_EM: f32 = 0.22;
const WHITE_CHANNEL_MIN: u8 = 250;
const RULE_MAX_THICKNESS_PT: f32 = 2.5;
const RULE_MIN_ASPECT: f32 = 4.0;
const RULE_MIN_THICKNESS_PT: f32 = 0.5;
const PATTERN_COLOR: [u8; 4] = [128, 128, 128, 255];
const EMPTY_CLIP: kurbo::Rect = kurbo::Rect::new(-1e6, -1e6, -1e6 + 1e-3, -1e6 + 1e-3);
const GLYPH_CLIP_MARGIN_PT: f64 = 2.0;
const GLYPH_UNITS_PER_EM: f64 = 1000.0;
const MIN_GLYPH_SIZE_PT: f32 = 0.5;
const HORIZONTAL_MAX_ANGLE_DEG: f32 = 3.0;
const DEFAULT_ADVANCE_UNITS: f32 = 500.0;
const FALLBACK_INK_ASCENT_EM: f32 = 0.7;
const FALLBACK_INK_DESCENT_EM: f32 = 0.2;
const SLASH_MIN_ASPECT: f64 = 1.5;
const MIN_IMAGE_SIDE_PT: f32 = 0.5;
const STENCIL_RULE_MAX_PIXELS: u32 = 1;
const STENCIL_RULE_ELEMENTS: u16 = 5;
const PIXEL_RULE_COLOR: [u8; 4] = [0, 0, 0, 255];
const PIXEL_RULE_MAX_THICKNESS_PT: f32 = 2.0;
const MAPSTO_MAX_OFFSET_EM: f32 = 0.3;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Dir {
Horizontal,
Rotated,
}
#[derive(Debug, Clone)]
pub struct Glyph {
pub text: String,
pub x: f32,
pub y: f32,
pub adv: f32,
pub size: f32,
pub font: u16,
pub dir: Dir,
pub angle: f32,
pub invisible: bool,
pub color: [u8; 3],
pub ink: Rect,
}
impl Glyph {
pub fn bbox(&self) -> Rect {
match self.dir {
Dir::Horizontal => Rect::new(
self.x,
self.y - EM_BOX_ASCENT_EM * self.size,
self.x + self.adv.max(0.0),
self.y + EM_BOX_DESCENT_EM * self.size,
),
Dir::Rotated => {
let radius = self.size.max(self.adv.abs());
Rect::new(self.x - radius, self.y - radius, self.x + radius, self.y + radius)
}
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct ImageBox {
pub bbox: Rect,
pub px_width: u32,
pub px_height: u32,
}
#[derive(Debug, Clone, Copy)]
pub struct PathBox {
pub bbox: Rect,
pub stroked: bool,
pub filled: bool,
pub color: [u8; 4],
pub line_width: f32,
pub elements: u16,
}
impl PathBox {
pub fn is_white(&self) -> bool {
self.color[0] > WHITE_CHANNEL_MIN && self.color[1] > WHITE_CHANNEL_MIN && self.color[2] > WHITE_CHANNEL_MIN
}
pub fn is_hrule(&self) -> bool {
self.bbox.height() <= RULE_MAX_THICKNESS_PT
&& self.bbox.width() >= RULE_MIN_ASPECT * self.bbox.height().max(RULE_MIN_THICKNESS_PT)
}
pub fn is_vrule(&self) -> bool {
self.bbox.width() <= RULE_MAX_THICKNESS_PT
&& self.bbox.height() >= RULE_MIN_ASPECT * self.bbox.width().max(RULE_MIN_THICKNESS_PT)
}
}
#[derive(Debug, Default)]
pub struct RawPage {
pub index: usize,
pub width: f32,
pub height: f32,
pub glyphs: Vec<Glyph>,
pub images: Vec<ImageBox>,
pub paths: Vec<PathBox>,
pub pixel_rules: Vec<PathBox>,
pub links: Vec<LinkArea>,
}
#[derive(Debug, Clone)]
pub struct LinkArea {
pub rect: Rect,
pub uri: std::sync::Arc<str>,
}
const LINK_SCHEMES: &[&str] = &["http://", "https://", "mailto:", "ftp://"];
fn uri_links(page: &Page<'_>) -> Vec<LinkArea> {
use hayro_syntax::object::{Array, Dict, Name, Rect as PdfRect, String as PdfString};
let transform = page.initial_transform(true).to_kurbo();
let Some(annots) = page.raw().get::<Array>(b"Annots") else {
return Vec::new();
};
annots
.iter::<Dict>()
.filter_map(|annot| {
if annot.get::<Name>(b"Subtype")?.as_ref() != b"Link" {
return None;
}
let action = annot.get::<Dict>(b"A")?;
if action.get::<Name>(b"S")?.as_ref() != b"URI" {
return None;
}
let uri = action.get::<PdfString>(b"URI")?;
let uri = std::str::from_utf8(uri.as_bytes()).ok()?.trim();
let lower = uri.to_ascii_lowercase();
if !LINK_SCHEMES.iter().any(|scheme| lower.starts_with(scheme)) {
return None;
}
let area = annot.get::<PdfRect>(b"Rect")?;
let area = transform.transform_rect_bbox(kurbo::Rect::new(area.x0, area.y0, area.x1, area.y1));
Some(LinkArea {
rect: Rect::new(area.x0 as f32, area.y0 as f32, area.x1 as f32, area.y1 as f32),
uri: std::sync::Arc::from(uri),
})
})
.collect()
}
struct Extractor<'r, 'a> {
fonts: &'r mut FontRegistry<'a>,
page: RawPage,
page_rect: kurbo::Rect,
clips: Vec<kurbo::Rect>,
}
struct GlyphPlacement {
origin: Point,
size: f32,
x_scale: f64,
angle: f32,
dir: Dir,
}
impl GlyphPlacement {
fn new(transform: Affine, clip: kurbo::Rect) -> Option<Self> {
let origin = transform * Point::ZERO;
if origin.x < clip.x0 - GLYPH_CLIP_MARGIN_PT
|| origin.x > clip.x1 + GLYPH_CLIP_MARGIN_PT
|| origin.y < clip.y0 - GLYPH_CLIP_MARGIN_PT
|| origin.y > clip.y1 + GLYPH_CLIP_MARGIN_PT
{
return None;
}
let [xx, yx, xy, yy, _, _] = transform.as_coeffs();
let size = (xy.hypot(yy) * GLYPH_UNITS_PER_EM) as f32;
let x_scale = xx.hypot(yx) * GLYPH_UNITS_PER_EM;
if size < MIN_GLYPH_SIZE_PT || !size.is_finite() {
return None;
}
let angle = (yx.atan2(xx)).to_degrees() as f32;
let dir = if angle.abs() < HORIZONTAL_MAX_ANGLE_DEG {
Dir::Horizontal
} else {
Dir::Rotated
};
Some(Self {
origin,
size,
x_scale,
angle,
dir,
})
}
}
impl Extractor<'_, '_> {
fn join_mapsto(&mut self, placement: &GlyphPlacement, adv: f32, ink: Rect) -> bool {
let Some(stem) = self.page.glyphs.last_mut() else {
return false;
};
let (x, y) = (placement.origin.x as f32, placement.origin.y as f32);
let near = (stem.y - y).abs() <= MAPSTO_MAX_OFFSET_EM * placement.size
&& (x - stem.x).abs() <= MAPSTO_MAX_OFFSET_EM * placement.size;
if stem.text != MAPSTO_STEM || !near {
return false;
}
stem.adv = (x + adv - stem.x).max(stem.adv);
stem.ink = stem.ink.union(&ink);
true
}
fn clip(&self) -> kurbo::Rect {
self.clips.last().copied().unwrap_or(self.page_rect)
}
fn visible(&self, bbox: kurbo::Rect) -> Option<Rect> {
let clip = self.clip();
let inside = bbox.intersect(clip);
if bbox.x0 > clip.x1 || bbox.x1 < clip.x0 || bbox.y0 > clip.y1 || bbox.y1 < clip.y0 {
return None;
}
Some(Rect::new(
inside.x0 as f32,
inside.y0 as f32,
inside.x1 as f32,
inside.y1 as f32,
))
}
fn record_stencil_rule(&mut self, stencil: &hayro_interpret::StencilImage<'_, '_>, bbox: kurbo::Rect) {
let mut painted = false;
let mut color = [0, 0, 0, 255];
stencil.with_stencil(
|luma, paint| {
painted = luma.data.first().is_some_and(|&sample| sample != 0);
color = paint_color(paint);
},
None,
);
if !painted || color[3] == 0 {
return;
}
let Some(bbox) = self.visible(bbox) else {
return;
};
self.page.paths.push(PathBox {
bbox,
stroked: false,
filled: true,
color,
line_width: 0.0,
elements: STENCIL_RULE_ELEMENTS,
});
}
fn describe_glyph(&mut self, glyph: &PdfGlyph<'_>) -> (Option<BfString>, Option<f32>, u16, Option<kurbo::Rect>) {
match glyph {
PdfGlyph::Outline(outline) => (
outline.as_unicode(),
outline.advance_width(),
self.fonts.identify(outline),
self.fonts.outline_bbox(outline),
),
PdfGlyph::Type3(type3) => (type3.as_unicode(), type3.advance_width(), UNKNOWN_FONT, None),
}
}
}
impl<'a> Device<'a> for Extractor<'_, 'a> {
fn draw_path(&mut self, path: &BezPath, props: DrawProps<'a>, draw_mode: &DrawMode) {
let (stroked, filled, line_width) = match draw_mode {
DrawMode::Fill(_) => (false, true, 0.0),
DrawMode::Stroke(stroke) => (true, false, stroke.line_width),
DrawMode::FillAndStroke(_, stroke) => (true, true, stroke.line_width),
DrawMode::Invisible => return,
};
let color = paint_color(&props.paint);
if color[3] == 0 {
return;
}
let [xx, yx, xy, yy, _, _] = props.transform.as_coeffs();
let scale = ((xx * yy - yx * xy).abs()).sqrt();
let line_width_page = line_width as f64 * scale;
let mut bbox = props.transform.transform_rect_bbox(path.bounding_box());
if stroked {
bbox = bbox.inflate(line_width_page * 0.5, line_width_page * 0.5);
}
let Some(bbox) = self.visible(bbox) else {
return;
};
self.page.paths.push(PathBox {
bbox,
stroked,
filled,
color,
line_width: line_width_page as f32,
elements: path.elements().len().min(u16::MAX as usize) as u16,
});
}
fn push_clip_path(&mut self, clip_path: &ClipPath) {
let bbox = clip_path.path.bounding_box();
let current = self.clip();
let mut clip = bbox.intersect(current);
if bbox.x0 > current.x1 || bbox.x1 < current.x0 || bbox.y0 > current.y1 || bbox.y1 < current.y0 {
clip = EMPTY_CLIP;
}
self.clips.push(clip);
}
fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'a>>, _: BlendMode) {}
fn draw_glyph_run(&mut self, glyph_run: &GlyphRun<'_, 'a>, props: DrawProps<'a>, draw_mode: &DrawMode) {
let invisible = matches!(draw_mode, DrawMode::Invisible);
let color = paint_color(&props.paint);
let clip = self.clip();
for glyph in glyph_run.glyphs() {
let transform: Affine = props.transform * glyph.transform();
let Some(placement) = GlyphPlacement::new(transform, clip) else {
continue;
};
let (unicode, advance, font, outline_box) = self.describe_glyph(glyph);
let info = &self.fonts.infos[font as usize];
let private = match (&unicode, info.symbols) {
(Some(BfString::Char(ch)), Some(symbols)) => symbols.private_text(*ch),
_ => None,
};
let mut text = match (info.mathabx, private) {
(Some(abx), _) => abx.text(glyph.char_code()).unwrap_or("\u{FFFD}").to_string(),
(None, Some(known)) => known.to_string(),
(None, None) => glyph_text(unicode, info.libertine),
};
if text == "\u{FFFD}"
&& let Some(known) = info.symbols.and_then(|symbols| symbols.text(glyph.char_code()))
{
text = known;
}
let blank = font != UNKNOWN_FONT && outline_box.is_none();
if text.is_empty() || text == "\u{FFFD}" && (matches!(glyph.char_code(), 9 | 10 | 13) || blank) {
continue;
}
if self.fonts.infos[font as usize].math_pi {
text = remap_math_pi(&text);
}
if self.fonts.infos[font as usize].math {
text = remap_tex_math(&text);
}
if self.fonts.infos[font as usize].radical_pi {
text = match text.as_str() {
"p" => "√".into(),
"ffi" | "ff" | "fi" | "fl" => continue,
_ => text,
};
}
if text == "=" && outline_box.is_some_and(|outline| outline.height() > SLASH_MIN_ASPECT * outline.width()) {
text = "/".into();
}
let adv = advance.unwrap_or(DEFAULT_ADVANCE_UNITS) as f64 / GLYPH_UNITS_PER_EM * placement.x_scale;
let ink = ink_box(outline_box, transform, &placement, adv);
if text == "\u{2192}" && self.join_mapsto(&placement, adv as f32, ink) {
continue;
}
self.page.glyphs.push(Glyph {
text,
x: placement.origin.x as f32,
y: placement.origin.y as f32,
adv: adv as f32,
size: placement.size,
font,
dir: placement.dir,
angle: placement.angle,
invisible,
color: [color[0], color[1], color[2]],
ink,
});
}
}
fn draw_image(&mut self, image: Image<'a, '_>, props: ImageDrawProps<'a>) {
let (px_width, px_height) = (image.width(), image.height());
let rect = kurbo::Rect::new(0.0, 0.0, px_width as f64, px_height as f64);
let bbox = props.transform.transform_rect_bbox(rect);
let mut rule = false;
if px_width * px_height <= STENCIL_RULE_MAX_PIXELS
&& let Image::Stencil(stencil) = &image
{
self.record_stencil_rule(stencil, bbox);
rule = true;
}
if (px_width, px_height) == (1, 1)
&& let Some(bar) = self.visible(bbox)
&& bar.width().min(bar.height()) <= PIXEL_RULE_MAX_THICKNESS_PT
&& bar.width().max(bar.height()) > MIN_IMAGE_SIDE_PT
{
self.page.pixel_rules.push(PathBox {
bbox: bar,
stroked: false,
filled: true,
color: PIXEL_RULE_COLOR,
line_width: 0.0,
elements: 5,
});
rule = true;
}
if rule {
return;
}
if let Some(bbox) = self.visible(bbox)
&& bbox.width() > MIN_IMAGE_SIDE_PT
&& bbox.height() > MIN_IMAGE_SIDE_PT
{
self.page.images.push(ImageBox {
bbox,
px_width,
px_height,
});
}
}
fn pop_clip(&mut self) {
self.clips.pop();
}
fn pop_transparency_group(&mut self) {}
}
pub fn extract_page<'a>(
page: &'a Page<'a>,
index: usize,
fonts: &mut FontRegistry<'a>,
cache: &InterpreterCache<'a>,
settings: &InterpreterSettings,
) -> RawPage {
let (width, height) = page.render_dimensions();
let page_rect = kurbo::Rect::new(0.0, 0.0, width as f64, height as f64);
let mut ctx = Context::new(
page.initial_transform(true).to_kurbo(),
page_rect,
cache,
page.xref(),
settings.clone(),
);
fonts.begin_page(page);
let mut device = Extractor {
fonts,
page: RawPage {
index,
width,
height,
..Default::default()
},
page_rect,
clips: Vec::new(),
};
interpret_page(page, &mut ctx, &mut device);
device.page.links = uri_links(page);
device.page
}
fn paint_color(paint: &Paint<'_>) -> [u8; 4] {
match paint {
Paint::Color(color) => color.to_rgba().to_rgba8(),
Paint::Pattern(_) => PATTERN_COLOR,
}
}
fn glyph_text(unicode: Option<BfString>, libertine: bool) -> String {
let mut text = String::new();
let raw = match unicode {
Some(BfString::Char(ch)) => ch.to_string(),
Some(BfString::String(string)) => string,
None => return '\u{FFFD}'.to_string(),
};
if libertine {
normalize_text(&libertine_text(&raw), &mut text);
} else {
normalize_text(&raw, &mut text);
}
text
}
fn libertine_text(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for ch in text.chars() {
let code = ch as u32;
match code {
0xE039 => out.push_str("ft"),
0xE03A => out.push_str("ck"),
0xE03B => out.push_str("ch"),
0xE03C => out.push_str("tt"),
0xE048 => out.push_str("Qu"),
0xE049 => out.push_str("Th"),
0xE0E0 => out.push('f'),
0xE051..=0xE06A => out.push(char::from(b'a' + (code - 0xE051) as u8)),
0xE118..=0xE121 => out.push(char::from(b'0' + (code - 0xE118) as u8)),
_ => out.push(ch),
}
}
out
}
fn normalize_text(text: &str, out: &mut String) {
for ch in text.chars() {
match ch {
'\u{FB00}' => out.push_str("ff"),
'\u{FB01}' => out.push_str("fi"),
'\u{FB02}' => out.push_str("fl"),
'\u{FB03}' => out.push_str("ffi"),
'\u{FB04}' => out.push_str("ffl"),
'\u{FB05}' | '\u{FB06}' => out.push_str("st"),
'\u{00A0}' | '\u{2002}' | '\u{2003}' | '\u{2009}' | '\u{200A}' | '\u{202F}' => out.push(' '),
'\u{00AD}' => out.push('-'),
'\u{2010}' | '\u{2011}' => out.push('-'),
'\u{0}'..='\u{1F}' | '\u{7F}' | '\u{200B}'..='\u{200F}' | '\u{FEFF}' => {}
'\u{F8E5}'..='\u{F8FE}' => out.push(symbol_piece(ch)),
'\u{F730}'..='\u{F739}' => out.push(char::from(b'0' + (ch as u32 - 0xF730) as u8)),
'\u{F761}'..='\u{F77A}' => out.push(char::from(b'a' + (ch as u32 - 0xF761) as u8)),
'\u{E000}'..='\u{F8FF}' => out.push('\u{FFFD}'),
other => out.push(other),
}
}
}
fn symbol_piece(ch: char) -> char {
const PIECES: [char; 26] = [
'\u{F8E5}', '\u{F8E6}', '\u{23AF}', '\u{AE}', '\u{A9}', '\u{2122}', '\u{239B}', '\u{239C}', '\u{239D}',
'\u{23A1}', '\u{23A2}', '\u{23A3}', '\u{23A7}', '\u{23A8}', '\u{23A9}', '\u{23AA}', '\u{23AE}', '\u{239E}',
'\u{239F}', '\u{23A0}', '\u{23A4}', '\u{23A5}', '\u{23A6}', '\u{23AB}', '\u{23AC}', '\u{23AD}',
];
let piece = PIECES[(ch as u32 - 0xF8E5) as usize];
if ('\u{E000}'..='\u{F8FF}').contains(&piece) {
'\u{FFFD}'
} else {
piece
}
}
fn remap_tex_math(text: &str) -> String {
text.chars()
.map(|ch| match ch {
'\u{01EB}' => '\u{03F5}',
'\u{2737}' => '\u{25A1}',
other => other,
})
.collect()
}
fn remap_math_pi(text: &str) -> String {
text.chars()
.map(|ch| match ch {
'¼' => '=',
'þ' => '+',
'ð' => '(',
'Þ' => ')',
'½' => '[',
'f' => '{',
'g' => '}',
other => other,
})
.collect()
}
fn ink_box(outline_box: Option<kurbo::Rect>, transform: Affine, placement: &GlyphPlacement, adv: f64) -> Rect {
let origin = placement.origin;
let size = placement.size;
match outline_box {
Some(outline) => {
let page_box = transform.transform_rect_bbox(outline);
Rect::new(
page_box.x0 as f32,
page_box.y0 as f32,
page_box.x1 as f32,
page_box.y1 as f32,
)
}
None => Rect::new(
origin.x as f32,
origin.y as f32 - FALLBACK_INK_ASCENT_EM * size,
(origin.x + adv) as f32,
origin.y as f32 + FALLBACK_INK_DESCENT_EM * size,
),
}
}
#[cfg(test)]
mod tests {
use super::normalize_text;
#[test]
fn private_use_ligature_is_unknown() {
let mut text = String::new();
normalize_text("le\u{E039}most", &mut text);
assert_eq!(text, "le\u{FFFD}most");
}
#[test]
fn libertine_private_use_glyphs_are_read() {
use super::libertine_text;
assert_eq!(
libertine_text("\u{E049}e pa\u{E03C}ern a\u{E039}er"),
"The pattern after"
);
assert_eq!(
libertine_text("\u{E05D}\u{E059}\u{E064} \u{E119}\u{E121}\u{E11F}\u{E120}"),
"mit 1978"
);
}
#[test]
fn delimiter_pieces_are_read() {
let mut text = String::new();
normalize_text("\u{F8EB}\u{F8F4}\u{F8FE}", &mut text);
assert_eq!(text, "\u{239B}\u{23AA}\u{23AD}");
}
}