use super::extract::{RawPage, extract_page};
use super::fonts::{FontInfo, FontRegistry, UNKNOWN_FONT};
use super::render::PageRenderer;
use crate::common::parallel;
use anyhow::{Result, anyhow};
use hayro_interpret::{InterpreterCache, InterpreterSettings};
use hayro_syntax::Pdf;
use std::collections::HashMap;
const FILE_NAME_TITLE_MARKS: [&str; 7] = [".tex", ".dvi", ".pdf", ".doc", ".docx", ".indd", "Microsoft Word - "];
pub struct PdfFile {
pdf: Pdf,
}
impl PdfFile {
pub fn open(data: Vec<u8>) -> Result<Self> {
let pdf = Pdf::new(data).map_err(|err| anyhow!("cannot read PDF: {err:?}"))?;
if pdf.pages().is_empty() {
return Err(anyhow!("the PDF has no pages"));
}
Ok(Self { pdf })
}
pub fn page_count(&self) -> usize {
self.pdf.pages().len()
}
pub fn renderer(&self) -> PageRenderer<'_> {
PageRenderer::new(&self.pdf)
}
pub fn extract(&self, jobs: usize) -> (Vec<RawPage>, Vec<FontInfo>) {
let pages = self.pdf.pages();
let extracted = parallel::map(
pages.len(),
jobs,
|| {
(
FontRegistry::new(),
InterpreterCache::new(),
InterpreterSettings::default(),
)
},
|(fonts, cache, settings), page_idx| {
let page = extract_page(&pages[page_idx], page_idx, fonts, cache, settings);
let used = fonts_used(&page, fonts);
(page, used)
},
);
unify_fonts(extracted)
}
pub fn info_title(&self) -> Option<String> {
let raw = self.pdf.metadata().title.as_deref()?;
let title = decode_text_string(raw).split_whitespace().collect::<Vec<_>>().join(" ");
let is_file_name = FILE_NAME_TITLE_MARKS
.iter()
.any(|mark| title.ends_with(mark) || title.starts_with(mark));
(!title.is_empty() && !is_file_name).then_some(title)
}
}
fn decode_text_string(raw: &[u8]) -> String {
let utf16 = |bytes: &[u8], big_endian: bool| {
let units: Vec<u16> = bytes
.as_chunks::<2>()
.0
.iter()
.map(|pair| {
if big_endian {
u16::from_be_bytes(*pair)
} else {
u16::from_le_bytes(*pair)
}
})
.collect();
String::from_utf16_lossy(&units)
};
match raw {
[0xFE, 0xFF, rest @ ..] => utf16(rest, true),
[0xFF, 0xFE, rest @ ..] => utf16(rest, false),
_ => {
std::str::from_utf8(raw).map_or_else(|_| raw.iter().map(|&byte| char::from(byte)).collect(), str::to_string)
}
}
}
fn fonts_used(page: &RawPage, fonts: &FontRegistry<'_>) -> Vec<(u16, FontInfo)> {
let mut used: Vec<(u16, FontInfo)> = Vec::new();
for glyph in &page.glyphs {
if !used.iter().any(|(font, _)| *font == glyph.font) {
used.push((glyph.font, fonts.infos[glyph.font as usize].clone()));
}
}
used
}
fn unify_fonts(extracted: Vec<(RawPage, Vec<(u16, FontInfo)>)>) -> (Vec<RawPage>, Vec<FontInfo>) {
let mut infos = FontRegistry::new().infos; let mut by_name: HashMap<String, u16> = HashMap::new();
let mut raw = Vec::with_capacity(extracted.len());
for (mut page, used) in extracted {
let to_global: HashMap<u16, u16> = used
.into_iter()
.map(|(local, info)| {
if local == UNKNOWN_FONT {
return (local, local);
}
let global = *by_name.entry(info.name.clone()).or_insert_with(|| {
infos.push(info);
(infos.len() - 1) as u16
});
(local, global)
})
.collect();
for glyph in &mut page.glyphs {
glyph.font = to_global[&glyph.font];
}
raw.push(page);
}
(raw, infos)
}
#[cfg(test)]
mod tests {
use super::decode_text_string;
#[test]
fn text_strings_are_decoded() {
assert_eq!(decode_text_string(b"Plain title"), "Plain title");
assert_eq!(decode_text_string(&[0xFE, 0xFF, 0x00, 0x4D, 0x00, 0xE9]), "Mé");
assert_eq!(decode_text_string(&[0x4D, 0xE9]), "Mé");
assert_eq!(decode_text_string("Mé".as_bytes()), "Mé");
}
}