use std::path::{Path, PathBuf};
use std::process::Command;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LinkTarget {
Url(String),
Page(u32),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PdfLink {
pub rect: (u32, u32, u32, u32),
pub target: LinkTarget,
}
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct PageLinks {
pub page_w: u32,
pub page_h: u32,
pub links: Vec<PdfLink>,
}
impl PageLinks {
pub fn link_at(&self, frac: (f64, f64, f64, f64)) -> Option<&PdfLink> {
if self.page_w == 0 || self.page_h == 0 {
return None;
}
let (w, h) = (self.page_w as f64, self.page_h as f64);
self.links
.iter()
.filter_map(|l| {
let (lx0, ly0, lx1, ly1) = l.rect;
let ox = (frac.2.min(lx1 as f64 / w) - frac.0.max(lx0 as f64 / w)).max(0.0);
let oy = (frac.3.min(ly1 as f64 / h) - frac.1.max(ly0 as f64 / h)).max(0.0);
(ox > 0.0 && oy > 0.0).then_some((l, ox * oy))
})
.max_by(|a, b| a.1.total_cmp(&b.1))
.map(|(l, _)| l)
}
}
pub fn page_links(pdf: &Path, page: u32) -> std::io::Result<PageLinks> {
let program = which("pdftohtml")
.ok_or_else(|| std::io::Error::other("install poppler (pdftohtml) to open PDF links"))?;
let p = page.to_string();
let flags = ["-xml", "-stdout", "-i", "-f", &p, "-l", &p];
let args: Vec<&std::ffi::OsStr> = flags
.iter()
.map(std::ffi::OsStr::new)
.chain(std::iter::once(pdf.as_os_str()))
.collect();
let (status, out) = run_bounded_stdout(&program, &args, PDF_LINKS_BUDGET)
.ok_or_else(|| std::io::Error::other("pdftohtml did not finish in time"))?;
if !status.success() {
return Err(std::io::Error::other(format!(
"pdftohtml exited with {status}"
)));
}
Ok(parse_pdf2xml_links(&out, page).unwrap_or_default())
}
pub fn parse_pdf2xml_links(xml: &str, page: u32) -> Option<PageLinks> {
let mut in_page = false;
let mut out = PageLinks::default();
let mut found = false;
for line in xml.lines() {
if let Some(pos) = line.find("<page ") {
let tag = &line[pos + "<page ".len()..];
in_page = attr_u32(tag, "number") == Some(page);
if in_page {
found = true;
out.page_w = attr_u32(tag, "width").unwrap_or(0);
out.page_h = attr_u32(tag, "height").unwrap_or(0);
}
continue;
}
if !in_page {
continue;
}
if line.contains("</page>") {
break;
}
let Some(pos) = line.find("<text ") else {
continue;
};
let tag = &line[pos + "<text ".len()..];
let (Some(left), Some(top), Some(w), Some(h)) = (
attr_u32(tag, "left"),
attr_u32(tag, "top"),
attr_u32(tag, "width"),
attr_u32(tag, "height"),
) else {
continue;
};
let Some(gt) = tag.find('>') else { continue };
let content = tag[gt + 1..].split("</text>").next().unwrap_or("");
let total = visible_chars(content);
let mut pre = 0usize;
let mut rest = content;
while let Some(pos) = rest.find("<a href=\"") {
pre += visible_chars(&rest[..pos]);
let after = &rest[pos + "<a href=\"".len()..];
let Some(end) = after.find('"') else { break };
let href = xml_unescape(&after[..end]);
let Some(tag_close) = after[end..].find('>') else {
break;
};
let (inner, after_anchor) = after[end + tag_close + 1..]
.split_once("</a>")
.unwrap_or((&after[end + tag_close + 1..], ""));
let inner_len = visible_chars(inner);
if let Some(target) = classify_href(&href) {
let (x0, x1) = if total == 0 {
(left, left + w.max(1))
} else {
let at = |chars: usize| {
left + (w as f64 * chars.min(total) as f64 / total as f64).round() as u32
};
let run_right = left + w.max(1);
let x0 = at(pre).min(run_right - 1);
(x0, at(pre + inner_len).clamp(x0 + 1, run_right))
};
out.links.push(PdfLink {
rect: (x0, top, x1, top + h.max(1)),
target,
});
}
pre += inner_len;
rest = after_anchor;
}
}
found.then_some(out)
}
fn visible_chars(s: &str) -> usize {
let mut n = 0;
let mut in_tag = false;
let mut it = s.char_indices();
while let Some((i, c)) = it.next() {
match c {
'<' => in_tag = true,
'>' => in_tag = false,
'&' if !in_tag => {
let rest = &s[i + 1..];
if let Some(semi) = rest.find(';')
&& (1..=8).contains(&semi)
&& rest[..semi]
.chars()
.all(|c| c == '#' || c.is_ascii_alphanumeric())
{
for _ in 0..=semi {
it.next();
}
}
n += 1;
}
_ if !in_tag => n += 1,
_ => {}
}
}
n
}
fn attr_u32(tag: &str, name: &str) -> Option<u32> {
let pat = format!("{name}=\"");
let start = tag.find(&pat)? + pat.len();
let rest = &tag[start..];
rest[..rest.find('"')?].parse().ok()
}
fn classify_href(href: &str) -> Option<LinkTarget> {
let lower = href.to_ascii_lowercase();
if lower.starts_with("http://") || lower.starts_with("https://") || lower.starts_with("mailto:")
{
return Some(LinkTarget::Url(href.to_string()));
}
if lower.contains("://") {
return None;
}
let (_, frag) = href.rsplit_once('#')?;
frag.parse().ok().map(LinkTarget::Page)
}
fn xml_unescape(s: &str) -> String {
s.replace("<", "<")
.replace(">", ">")
.replace(""", "\"")
.replace("'", "'")
.replace("'", "'")
.replace("&", "&")
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PdfBackend {
PdftoppmCli,
SipsCli,
}
pub fn detect_backend() -> Option<PdfBackend> {
if which("pdftoppm").is_some() {
return Some(PdfBackend::PdftoppmCli);
}
if cfg!(target_os = "macos") && which("sips").is_some() {
return Some(PdfBackend::SipsCli);
}
None
}
fn which(cmd: &str) -> Option<PathBuf> {
let path_var = std::env::var_os("PATH")?;
for dir in std::env::split_paths(&path_var) {
let candidate = dir.join(cmd);
if candidate.is_file() {
return Some(candidate);
}
}
None
}
pub fn detect_page_count(pdf: &Path) -> Option<u32> {
if let Some(n) = page_count_via_pdfinfo(pdf) {
return Some(n);
}
if cfg!(target_os = "macos")
&& let Some(n) = page_count_via_mdls(pdf)
{
return Some(n);
}
None
}
fn page_count_via_pdfinfo(pdf: &Path) -> Option<u32> {
let program = which("pdfinfo")?;
let (status, out) = run_bounded_stdout(&program, &[pdf.as_os_str()], PDF_INFO_BUDGET)?;
if !status.success() {
return None;
}
parse_pdfinfo_pages(&out)
}
pub fn parse_pdfinfo_pages(out: &str) -> Option<u32> {
for line in out.lines() {
if let Some(rest) = line.strip_prefix("Pages:")
&& let Ok(n) = rest.trim().parse::<u32>()
{
return Some(n);
}
}
None
}
fn mdls_argv(pdf: &Path) -> [&std::ffi::OsStr; 4] {
[
std::ffi::OsStr::new("-raw"),
std::ffi::OsStr::new("-name"),
std::ffi::OsStr::new("kMDItemNumberOfPages"),
pdf.as_os_str(),
]
}
fn page_count_via_mdls(pdf: &Path) -> Option<u32> {
let (status, out) = run_bounded_stdout(
std::path::Path::new("mdls"),
&mdls_argv(pdf),
PDF_INFO_BUDGET,
)?;
if !status.success() {
return None;
}
out.trim().parse::<u32>().ok()
}
fn run_bounded_stdout(
program: &Path,
args: &[&std::ffi::OsStr],
budget: std::time::Duration,
) -> Option<(std::process::ExitStatus, String)> {
use std::io::Read;
use std::process::Stdio;
let mut child = Command::new(program)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.ok()?;
let Some(mut stdout) = child.stdout.take() else {
let _ = child.kill();
let _ = child.wait();
return None;
};
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = stdout.by_ref().take(MAX_PROBE_STDOUT).read_to_end(&mut buf);
let _ = tx.send(buf);
});
let started = std::time::Instant::now();
let out = rx.recv_timeout(budget).ok();
if out.is_some() {
while started.elapsed() < budget {
match child.try_wait() {
Ok(Some(status)) => {
return out.map(|b| (status, String::from_utf8_lossy(&b).into_owned()));
}
Ok(None) => std::thread::sleep(EXIT_POLL_TICK),
Err(_) => break,
}
}
}
let _ = child.kill();
let status = child.wait().ok()?;
out.map(|bytes| (status, String::from_utf8_lossy(&bytes).into_owned()))
}
const PDF_RENDER_BUDGET: std::time::Duration = std::time::Duration::from_secs(10);
const PDF_INFO_BUDGET: std::time::Duration = std::time::Duration::from_secs(2);
const PDF_LINKS_BUDGET: std::time::Duration = std::time::Duration::from_secs(5);
const MAX_PROBE_STDOUT: u64 = 1 << 20;
const STDERR_SETTLE_GRACE: std::time::Duration = std::time::Duration::from_millis(200);
#[cfg(test)]
#[derive(Debug, Clone, Copy)]
struct SettleOutcome {
waited: std::time::Duration,
on_quiet: bool,
bytes: usize,
}
#[cfg(test)]
thread_local! {
static LAST_SETTLE: std::cell::Cell<Option<SettleOutcome>> =
const { std::cell::Cell::new(None) };
}
const SETTLE_TICK: std::time::Duration = std::time::Duration::from_millis(5);
const EXIT_POLL_TICK: std::time::Duration = std::time::Duration::from_millis(5);
#[cfg(unix)]
fn set_nonblocking_on(fd: std::os::fd::RawFd) -> bool {
fn retry_on_eintr(mut call: impl FnMut() -> libc::c_int) -> libc::c_int {
for _ in 0..4 {
let rc = call();
if rc >= 0 || std::io::Error::last_os_error().raw_os_error() != Some(libc::EINTR) {
return rc;
}
}
-1
}
unsafe {
let flags = retry_on_eintr(|| libc::fcntl(fd, libc::F_GETFL));
if flags < 0 {
return false;
}
retry_on_eintr(|| libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK)) >= 0
}
}
fn set_nonblocking(pipe: Option<&std::process::ChildStderr>) -> bool {
#[cfg(unix)]
{
let Some(pipe) = pipe else {
return true;
};
use std::os::fd::AsRawFd;
set_nonblocking_on(pipe.as_raw_fd())
}
#[cfg(not(unix))]
{
pipe.is_none()
}
}
fn drain_available(pipe: Option<&mut std::process::ChildStderr>, into: &mut Vec<u8>) {
let Some(pipe) = pipe else {
return;
};
use std::io::Read;
let mut chunk = [0u8; 4096];
loop {
match pipe.read(&mut chunk) {
Ok(0) => break,
Ok(n) => into.extend_from_slice(&chunk[..n]),
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Err(_) => break,
}
}
}
fn read_once(pipe: Option<&mut std::process::ChildStderr>, into: &mut Vec<u8>) {
let Some(pipe) = pipe else {
return;
};
use std::io::Read;
let mut chunk = [0u8; 4096];
if let Ok(n) = pipe.read(&mut chunk) {
into.extend_from_slice(&chunk[..n]);
}
}
const QUIET_RUN_TICKS: u32 = 12;
#[cfg(test)]
fn record_settle(outcome: SettleOutcome) {
LAST_SETTLE.with(|c| c.set(Some(outcome)));
}
#[cfg(all(test, unix))]
fn last_settle() -> String {
match LAST_SETTLE.with(std::cell::Cell::get) {
Some(o) => format!(
"settle ended on {} after {:?} holding {} byte(s)",
if o.on_quiet {
"the QUIET RUN"
} else {
"the DEADLINE"
},
o.waited,
o.bytes
),
None => String::from("settle did not run"),
}
}
#[cfg(test)]
pub static FAIL_RASTERIZE_ONCE_FOR_TEST: std::sync::Mutex<Option<(PathBuf, u32)>> =
std::sync::Mutex::new(None);
pub fn rasterize_page(pdf: &Path, page: u32, backend: PdfBackend) -> std::io::Result<Vec<u8>> {
#[cfg(test)]
{
let mut fail = FAIL_RASTERIZE_ONCE_FOR_TEST.lock().unwrap();
if fail.as_ref() == Some(&(pdf.to_path_buf(), page)) {
*fail = None;
return Err(std::io::Error::other("transient failure injected by test"));
}
}
match backend {
PdfBackend::PdftoppmCli => rasterize_with_pdftoppm(pdf, page),
PdfBackend::SipsCli => {
if page != 1 {
return Err(std::io::Error::other("sips backend can only render page 1"));
}
rasterize_with_sips(pdf)
}
}
}
fn rasterize_with_pdftoppm(pdf: &Path, page: u32) -> std::io::Result<Vec<u8>> {
run_pdftoppm(Path::new("pdftoppm"), pdf, page, PDF_RENDER_BUDGET)
}
fn run_pdftoppm(
program: &Path,
pdf: &Path,
page: u32,
budget: std::time::Duration,
) -> std::io::Result<Vec<u8>> {
use std::process::Stdio;
let dir = unique_temp_dir("croft-pdf")?;
let guard = TempDirGuard(dir.clone());
let prefix = dir.join("page");
let mut cmd = Command::new(program);
cmd.arg("-f")
.arg(page.to_string())
.arg("-l")
.arg(page.to_string())
.arg("-r")
.arg("144")
.args(["-png", "-singlefile"])
.arg(pdf)
.arg(&prefix)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::piped());
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
let mut child = cmd.spawn()?;
let mut stderr_pipe = child.stderr.take();
let nonblocking = set_nonblocking(stderr_pipe.as_ref());
let mut stderr_bytes: Vec<u8> = Vec::new();
let deadline = std::time::Instant::now() + budget;
let status = loop {
if nonblocking {
drain_available(stderr_pipe.as_mut(), &mut stderr_bytes);
}
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) if std::time::Instant::now() < deadline => {
std::thread::sleep(EXIT_POLL_TICK);
}
Ok(None) => {
kill_group(child, guard);
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
format!(
"{} took longer than {:.1} s rendering page {page}; killed",
program.display(),
budget.as_secs_f64()
),
));
}
Err(e) => {
kill_group(child, guard);
return Err(e);
}
}
};
if !status.success() {
let text = if nonblocking {
drain_available(stderr_pipe.as_mut(), &mut stderr_bytes);
settle_late_writes(stderr_pipe.as_mut(), &mut stderr_bytes, STDERR_SETTLE_GRACE)
} else {
read_once(stderr_pipe.as_mut(), &mut stderr_bytes);
String::from_utf8_lossy(&stderr_bytes).trim().to_string()
};
return Err(std::io::Error::other(format!(
"{} exited with {status}: {text}",
program.display()
)));
}
let png_path = prefix.with_extension("png");
std::fs::read(&png_path)
}
fn settle_late_writes(
mut pipe: Option<&mut std::process::ChildStderr>,
into: &mut Vec<u8>,
grace: std::time::Duration,
) -> String {
let started = std::time::Instant::now();
let deadline = started + grace;
let (text, on_quiet) = settle_over(QUIET_RUN_TICKS, |_| {
drain_available(pipe.as_deref_mut(), into);
let text = String::from_utf8_lossy(into).trim().to_string();
if std::time::Instant::now() >= deadline {
return Sample::Last(text);
}
std::thread::sleep(SETTLE_TICK);
Sample::More(text)
});
#[cfg(test)]
record_settle(SettleOutcome {
waited: started.elapsed(),
on_quiet,
bytes: text.len(),
});
let _ = on_quiet;
text
}
enum Sample {
More(String),
Last(String),
}
fn settle_over(quiet_run: u32, mut sample: impl FnMut(u32) -> Sample) -> (String, bool) {
let quiet_run = quiet_run.max(1);
let mut seen = 0usize;
let mut quiet = 0u32;
let mut tick = 0u32;
loop {
let (text, last) = match sample(tick) {
Sample::More(t) => (t, false),
Sample::Last(t) => (t, true),
};
quiet = if text.len() == seen { quiet + 1 } else { 0 };
if quiet >= quiet_run || last {
return (text, quiet >= quiet_run && !last);
}
seen = text.len();
tick += 1;
}
}
fn kill_group(mut child: std::process::Child, scratch: TempDirGuard) {
#[cfg(unix)]
{
if let Ok(pid) = libc::pid_t::try_from(child.id()) {
unsafe {
libc::kill(-pid, libc::SIGKILL);
}
}
}
std::thread::spawn(move || {
let _ = child.kill();
let _ = child.wait();
drop(scratch);
});
}
fn rasterize_with_sips(pdf: &Path) -> std::io::Result<Vec<u8>> {
let dir = unique_temp_dir("croft-pdf")?;
let _guard = TempDirGuard(dir.clone());
let out = dir.join("page.png");
let status = Command::new("sips")
.args(["-s", "format", "png"])
.arg(pdf)
.arg("--out")
.arg(&out)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()?;
if !status.success() {
return Err(std::io::Error::other(format!("sips exited with {status}")));
}
std::fs::read(&out)
}
fn unique_temp_dir(stem: &str) -> std::io::Result<PathBuf> {
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let pid = std::process::id();
let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let base = crate::session_state::dirs_cache_croft().join("tmp");
std::fs::create_dir_all(&base)?;
let path = base.join(format!("{stem}-{pid}-{seq}"));
if path.exists() {
std::fs::remove_dir_all(&path)?;
}
std::fs::create_dir_all(&path)?;
Ok(path)
}
struct TempDirGuard(PathBuf);
impl Drop for TempDirGuard {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(unix)]
fn budget(base_ms: u64) -> std::time::Duration {
crate::test_budget::spawn_budget(std::time::Duration::from_millis(base_ms))
}
#[cfg(unix)]
fn fake_pdftoppm(dir: &Path, body: &str) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let script = dir.join("pdftoppm");
std::fs::write(&script, format!("#!/bin/sh\n{body}\n")).unwrap();
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
script
}
#[cfg(unix)]
#[test]
fn a_pdftoppm_that_overruns_the_budget_is_killed_and_reported() {
let tmp = tempfile::tempdir().unwrap();
let timeout = budget(300);
let script = fake_pdftoppm(
tmp.path(),
&format!("sleep {}", timeout.as_secs_f64() * 20.0),
);
let pdf = tmp.path().join("doc.pdf");
std::fs::write(&pdf, b"%PDF-1.4\n").unwrap();
let started = std::time::Instant::now();
let err = run_pdftoppm(&script, &pdf, 1, timeout)
.expect_err("an overrunning renderer is a failure, not a wait");
let elapsed = started.elapsed();
assert!(
elapsed < timeout * 4,
"the open returned at the budget, not when the child felt like it: {elapsed:?}"
);
assert_eq!(err.kind(), std::io::ErrorKind::TimedOut, "{err}");
assert!(
err.to_string().contains("longer than"),
"the error names the budget: {err}"
);
}
#[cfg(unix)]
#[test]
fn a_pdftoppm_whose_descendant_lingers_does_not_hold_the_call() {
let tmp = tempfile::tempdir().unwrap();
let timeout = budget(500);
let linger = timeout.as_secs_f64() * 6.0;
let script = fake_pdftoppm(
tmp.path(),
&format!(r#"sleep {linger} & for last; do :; done; printf 'x' > "$last.png""#),
);
let pdf = tmp.path().join("doc.pdf");
std::fs::write(&pdf, b"%PDF-1.4\n").unwrap();
let started = std::time::Instant::now();
let bytes = run_pdftoppm(&script, &pdf, 1, timeout).unwrap_or_else(|e| {
panic!("the page was written; a lingering descendant is not a failure: {e}")
});
let elapsed = started.elapsed();
assert_eq!(bytes, b"x");
assert!(
elapsed < std::time::Duration::from_secs_f64(linger / 2.0),
"the call returned when the page was ready, not when the descendant exited: {elapsed:?}"
);
}
#[cfg(unix)]
#[test]
fn a_pdftoppm_that_fails_reports_its_stderr() {
let tmp = tempfile::tempdir().unwrap();
let script = fake_pdftoppm(tmp.path(), r#"echo "Syntax Error: no trailer" >&2; exit 1"#);
let pdf = tmp.path().join("doc.pdf");
std::fs::write(&pdf, b"%PDF-1.4\n").unwrap();
let err = run_pdftoppm(&script, &pdf, 1, budget(5_000))
.expect_err("a non-zero exit is a failure");
let text = err.to_string();
assert!(
text.contains("exited with") && text.contains("Syntax Error: no trailer"),
"the error carries the exit and the stderr: {text}"
);
}
#[cfg(unix)]
#[test]
fn a_failing_pdftoppm_with_a_lingering_descendant_still_reports_its_stderr() {
let tmp = tempfile::tempdir().unwrap();
let script = fake_pdftoppm(
tmp.path(),
r#"sleep 5 & echo "Syntax Error: no trailer" >&2; exit 1"#,
);
let pdf = tmp.path().join("doc.pdf");
std::fs::write(&pdf, b"%PDF-1.4\n").unwrap();
let err = run_pdftoppm(&script, &pdf, 1, budget(5_000))
.expect_err("a non-zero exit is a failure");
let text = err.to_string();
assert!(
text.contains("Syntax Error: no trailer"),
"the stderr is reported despite the lingering descendant: {text}"
);
}
#[cfg(unix)]
#[test]
fn a_failing_pdftoppm_reports_the_stderr_it_sprayed() {
let tmp = tempfile::tempdir().unwrap();
let script = fake_pdftoppm(
tmp.path(),
r#"( sleep 0.05; echo "Syntax Error: second" >&2 ) & echo "Syntax Error: first" >&2; exit 1"#,
);
let pdf = tmp.path().join("doc.pdf");
std::fs::write(&pdf, b"%PDF-1.4\n").unwrap();
let err = run_pdftoppm(&script, &pdf, 1, budget(5_000))
.expect_err("a non-zero exit is a failure");
let text = err.to_string();
assert!(
text.contains("Syntax Error: first"),
"the renderer's spray reaches the error: {text}\n[#548] {}",
last_settle()
);
assert!(
text.contains("exited with"),
"and so does the exit status: {text}"
);
}
#[test]
fn the_settle_rule_bridges_a_gap_shorter_than_the_quiet_run() {
let script = |gap: u32| {
move |tick: u32| {
let text = if tick < gap {
String::from("Syntax Error: first")
} else {
String::from("Syntax Error: first\nSyntax Error: second")
};
if tick > gap + 60 {
Sample::Last(text)
} else {
Sample::More(text)
}
}
};
let (text, on_quiet) = settle_over(QUIET_RUN_TICKS, script(10));
assert!(
text.contains("second") && on_quiet,
"a 10-tick gap is inside the production run and must be bridged, \
settling on the run rather than the deadline: {text:?}"
);
let (text, _) = settle_over(QUIET_RUN_TICKS, script(15));
assert!(
!text.contains("second"),
"a 15-tick gap is outside it and must NOT be waited for - without \
this half the pair above is satisfied by a rule that waits \
forever: {text:?}"
);
}
#[cfg(unix)]
#[test]
fn every_line_the_renderer_wrote_before_exiting_is_reported() {
let tmp = tempfile::tempdir().unwrap();
let script = fake_pdftoppm(
tmp.path(),
r#"echo "Syntax Error: couldn't find trailer dictionary" >&2; sleep 0.05; echo "Syntax Error: Couldn't read xref table" >&2; exit 1"#,
);
let pdf = tmp.path().join("doc.pdf");
std::fs::write(&pdf, b"%PDF-1.4\n").unwrap();
for _ in 0..5 {
let err = run_pdftoppm(&script, &pdf, 1, budget(5_000))
.expect_err("a non-zero exit is a failure");
let text = err.to_string();
assert!(
text.contains("trailer dictionary") && text.contains("xref table"),
"both of the renderer's own lines reach the error: {text}\n[#548] {}",
last_settle()
);
}
}
#[test]
fn a_stream_that_has_stopped_settles_on_the_quiet_run() {
for seed in ["Syntax Error: complete", ""] {
let (text, on_quiet) = settle_over(QUIET_RUN_TICKS, |tick| {
let text = seed.to_string();
if tick > QUIET_RUN_TICKS * 10 {
Sample::Last(text)
} else {
Sample::More(text)
}
});
assert!(
on_quiet,
"a stream that stopped settles on the run, not the deadline: {text:?}"
);
assert_eq!(text, seed.trim(), "and returns what had arrived");
}
}
#[test]
fn a_stream_that_never_pauses_is_cut_off_at_the_deadline() {
let budget = QUIET_RUN_TICKS * 3;
let (text, on_quiet) = settle_over(QUIET_RUN_TICKS, |tick| {
let text = "x".repeat(tick as usize + 1);
if tick >= budget {
Sample::Last(text)
} else {
Sample::More(text)
}
});
assert!(
!on_quiet,
"the deadline is the exit when nothing settles: {text:?}"
);
assert_eq!(
text.len() as u32,
budget + 1,
"and it returns everything that had arrived by then"
);
}
#[cfg(unix)]
#[test]
fn a_silently_failing_pdftoppm_still_names_its_exit() {
let tmp = tempfile::tempdir().unwrap();
let script = fake_pdftoppm(tmp.path(), "exit 3");
let pdf = tmp.path().join("doc.pdf");
std::fs::write(&pdf, b"%PDF-1.4\n").unwrap();
let err = run_pdftoppm(&script, &pdf, 1, budget(5_000))
.expect_err("a non-zero exit is a failure");
assert!(err.to_string().contains("exited with"), "{err}");
}
#[cfg(unix)]
#[test]
fn a_hung_pdftoppm_takes_its_descendants_down_with_it() {
let tmp = tempfile::tempdir().unwrap();
let marker = tmp.path().join("alive");
let timeout = budget(300);
let helper_delay = timeout.as_secs_f64() * 3.0;
let script = fake_pdftoppm(
tmp.path(),
&format!(
"(sleep {helper_delay}; touch '{}') & sleep {}",
marker.display(),
helper_delay * 10.0
),
);
let pdf = tmp.path().join("doc.pdf");
std::fs::write(&pdf, b"%PDF-1.4\n").unwrap();
run_pdftoppm(&script, &pdf, 1, timeout).expect_err("an overrun is a failure");
std::thread::sleep(std::time::Duration::from_secs_f64(helper_delay * 2.0));
assert!(
!marker.exists(),
"the forked helper survived the group kill"
);
}
#[cfg(unix)]
#[test]
fn a_pdftoppm_that_finishes_in_time_hands_back_its_page() {
let tmp = tempfile::tempdir().unwrap();
let script = fake_pdftoppm(
tmp.path(),
r#"for last; do :; done; printf 'x' > "$last.png""#,
);
let pdf = tmp.path().join("doc.pdf");
std::fs::write(&pdf, b"%PDF-1.4\n").unwrap();
let bytes = run_pdftoppm(&script, &pdf, 1, budget(5_000))
.expect("a renderer that finishes is not a failure");
assert_eq!(bytes, b"x");
}
#[test]
fn concurrent_scratch_dirs_are_distinct() {
let dirs: Vec<_> = std::thread::scope(|s| {
let handles: Vec<_> = (0..16)
.map(|_| s.spawn(|| unique_temp_dir("croft-pdf-test").unwrap()))
.collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
});
let unique: std::collections::HashSet<_> = dirs.iter().collect();
assert_eq!(unique.len(), dirs.len(), "every render needs its own dir");
for d in dirs {
let _ = std::fs::remove_dir_all(d);
}
}
#[test]
fn pdftoppm_failure_captures_stderr_instead_of_writing_to_tty() {
if which("pdftoppm").is_none() {
eprintln!("skipping: pdftoppm not installed");
return;
}
let dir = unique_temp_dir("croft-pdf-test-stderr").unwrap();
let truncated = dir.join("half-written.pdf");
std::fs::write(&truncated, b"%PDF-1.7\ntruncated mid-write, no xref").unwrap();
let err = rasterize_with_pdftoppm(&truncated, 1).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("Syntax Error") || msg.contains("trailer"),
"error must carry the child's stderr, got: {msg}"
);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn parses_links_from_pdf2xml_output() {
let xml = r##"<?xml version="1.0" encoding="UTF-8"?>
<pdf2xml producer="poppler" version="25.04.0">
link to page 2 <page number="1" position="absolute" top="0" left="0" height="1188" width="918">
<text top="192" left="223" width="55" height="13" font="0">Jump to</text>
<text top="192" left="283" width="65" height="13" font="1"><a href="ilink.html#2">the target</a></text>
</page>
<page number="2" position="absolute" top="0" left="0" height="1188" width="918">
<text top="192" left="511" width="58" height="13" font="3"><a href="https://a.b/c?d=1&e=2">amp link</a></text>
<text top="300" left="100" width="90" height="12" font="2"><a href="mailto:x@y.z">mailto:x@y.z</a></text>
<text top="500" left="100" width="90" height="12" font="0">plain text</text>
</page>
</pdf2xml>
"##;
let p1 = parse_pdf2xml_links(xml, 1).unwrap();
assert_eq!((p1.page_w, p1.page_h), (918, 1188));
assert_eq!(
p1.links,
vec![PdfLink {
rect: (283, 192, 348, 205),
target: LinkTarget::Page(2),
}]
);
let p2 = parse_pdf2xml_links(xml, 2).unwrap();
assert_eq!(
p2.links,
vec![
PdfLink {
rect: (511, 192, 569, 205),
target: LinkTarget::Url(String::from("https://a.b/c?d=1&e=2")),
},
PdfLink {
rect: (100, 300, 190, 312),
target: LinkTarget::Url(String::from("mailto:x@y.z")),
},
]
);
assert!(
parse_pdf2xml_links(xml, 3).is_none(),
"a page absent from the output has no links"
);
}
#[test]
fn a_partial_run_link_covers_only_its_own_words() {
let xml = r##"<?xml version="1.0" encoding="UTF-8"?>
<pdf2xml producer="poppler" version="25.04.0">
<page number="1" position="absolute" top="0" left="0" height="1188" width="918">
<text top="700" left="514" width="196" height="21" font="3"><a href="https://pycoders.com">) is another </a>popular weekly </text>
</page>
</pdf2xml>
"##;
let p = parse_pdf2xml_links(xml, 1).unwrap();
assert_eq!(p.links.len(), 1);
let (x0, y0, x1, y1) = p.links[0].rect;
assert_eq!((x0, y0, y1), (514, 700, 721));
assert!(
(600..=610).contains(&x1),
"link rect must stop at the linked words, got x1={x1}"
);
}
#[test]
fn overlapping_toc_rects_resolve_to_the_most_covered_link() {
let links = PageLinks {
page_w: 1000,
page_h: 1188,
links: vec![
PdfLink {
rect: (100, 189, 400, 212),
target: LinkTarget::Page(509),
},
PdfLink {
rect: (100, 208, 400, 231),
target: LinkTarget::Page(511),
},
],
};
let hit = links
.link_at((0.15, 203.7 / 1188.0, 0.30, 237.6 / 1188.0))
.expect("the cell overlaps both rects");
assert_eq!(hit.target, LinkTarget::Page(511));
}
#[test]
fn only_web_and_mail_hrefs_open_externally() {
assert_eq!(
classify_href("file:///System/Applications/Calculator.app"),
None
);
assert_eq!(classify_href("vscode://extension/whatever"), None);
assert_eq!(classify_href("ssh://root@host"), None);
assert_eq!(
classify_href("https://a.b/c"),
Some(LinkTarget::Url(String::from("https://a.b/c")))
);
assert_eq!(
classify_href("HTTPS://A.B/c"),
Some(LinkTarget::Url(String::from("HTTPS://A.B/c")))
);
assert_eq!(
classify_href("mailto:x@y.z"),
Some(LinkTarget::Url(String::from("mailto:x@y.z")))
);
}
#[test]
fn a_zero_extent_run_still_yields_a_clickable_rect() {
let xml = r##"<?xml version="1.0" encoding="UTF-8"?>
<pdf2xml producer="poppler" version="25.04.0">
<page number="1" position="absolute" top="0" left="0" height="1000" width="1000">
<text top="100" left="50" width="120" height="0"><a href="https://a.b/">flat</a></text>
<text top="300" left="50" width="0" height="12"><a href="https://c.d/"></a></text>
</page>
</pdf2xml>
"##;
let p = parse_pdf2xml_links(xml, 1).unwrap();
assert_eq!(p.links.len(), 2);
for l in &p.links {
let (x0, y0, x1, y1) = l.rect;
assert!(x1 > x0 && y1 > y0, "degenerate rect survived: {:?}", l.rect);
}
assert!(p.link_at((0.05, 0.099, 0.18, 0.102)).is_some());
assert!(p.link_at((0.049, 0.30, 0.052, 0.312)).is_some());
}
#[test]
fn an_empty_anchor_at_the_run_edge_stays_inside_the_run() {
let xml = r##"<?xml version="1.0" encoding="UTF-8"?>
<pdf2xml producer="poppler" version="25.04.0">
<page number="1" position="absolute" top="0" left="0" height="1000" width="1000">
<text top="100" left="200" width="120" height="12">text<a href="https://a.b/"></a></text>
</page>
</pdf2xml>
"##;
let p = parse_pdf2xml_links(xml, 1).unwrap();
assert_eq!(p.links.len(), 1);
let (x0, _, x1, _) = p.links[0].rect;
assert!(
x0 >= 200 && x1 <= 320 && x0 < x1,
"the forced width must stay inside the run rect (200..320), got {x0}..{x1}"
);
}
#[test]
fn an_unterminated_entity_cannot_push_a_link_past_its_run() {
let xml = r##"<?xml version="1.0" encoding="UTF-8"?>
<pdf2xml producer="poppler" version="25.04.0">
<page number="1" position="absolute" top="0" left="0" height="1000" width="1000">
<text top="100" left="200" width="120" height="12">a & b<a href="https://a.b/">L</a></text>
</page>
</pdf2xml>
"##;
let p = parse_pdf2xml_links(xml, 1).unwrap();
assert_eq!(p.links.len(), 1);
let (x0, _, x1, _) = p.links[0].rect;
assert!(
x0 >= 200 && x1 <= 320 && x0 < x1,
"the link slice must stay inside its run rect (200..320), got {x0}..{x1}"
);
let ent = r##"<?xml version="1.0" encoding="UTF-8"?>
<pdf2xml producer="poppler" version="25.04.0">
<page number="1" position="absolute" top="0" left="0" height="1000" width="1000">
<text top="100" left="0" width="600" height="12">& ab<a href="https://a.b/">cd</a></text>
</page>
</pdf2xml>
"##;
let p = parse_pdf2xml_links(ent, 1).unwrap();
assert_eq!(p.links[0].rect.0, 400, "4 of 6 chars precede the anchor");
}
#[test]
fn link_at_matches_on_overlap_not_containment() {
let links = PageLinks {
page_w: 1000,
page_h: 1000,
links: vec![PdfLink {
rect: (100, 100, 200, 113),
target: LinkTarget::Page(2),
}],
};
assert!(links.link_at((0.15, 0.110, 0.16, 0.130)).is_some());
assert!(links.link_at((0.15, 0.120, 0.16, 0.140)).is_none());
assert!(links.link_at((0.05, 0.105, 0.09, 0.110)).is_none());
}
#[test]
fn parses_page_count_from_pdfinfo_output() {
let sample = "\
Title: \nAuthor: \nCreator: \nProducer: \n\
Pages: 12\nEncrypted: no\nPage size: 612 x 792 pts\n";
assert_eq!(parse_pdfinfo_pages(sample), Some(12));
}
#[test]
fn the_mdls_argv_names_the_page_count_attribute_in_order() {
let pdf = std::path::Path::new("/tmp/doc.pdf");
let argv = mdls_argv(pdf);
assert_eq!(argv[0], std::ffi::OsStr::new("-raw"));
assert_eq!(argv[1], std::ffi::OsStr::new("-name"));
assert_eq!(argv[2], std::ffi::OsStr::new("kMDItemNumberOfPages"));
assert_eq!(argv[3], pdf.as_os_str(), "the file is the last argument");
}
#[test]
fn the_probe_budget_stays_under_the_render_budget() {
assert!(
PDF_INFO_BUDGET < PDF_RENDER_BUDGET,
"a page-count probe must not be allowed to outlive a rasterisation"
);
}
#[cfg(unix)]
#[test]
fn a_hanging_probe_is_killed_at_the_budget_not_waited_on() {
let timeout = budget(150);
let start = std::time::Instant::now();
let out = run_bounded_stdout(
std::path::Path::new("sleep"),
&[std::ffi::OsStr::new("30")],
timeout,
);
let elapsed = start.elapsed();
assert!(out.is_none(), "a child that outruns the budget yields None");
assert!(
elapsed < timeout.mul_f64(20.0),
"the deadline must fire rather than wait out the child: took {elapsed:?}"
);
}
#[cfg(unix)]
#[test]
fn a_quick_probe_returns_its_output() {
let (status, out) = run_bounded_stdout(
std::path::Path::new("sh"),
&[
std::ffi::OsStr::new("-c"),
std::ffi::OsStr::new("sleep 0.05; echo 'Pages: 7'"),
],
budget(2000),
)
.expect("a child that exits in time yields its stdout");
assert!(status.success(), "a clean exit is reported as success");
assert_eq!(parse_pdfinfo_pages(&out), Some(7));
}
#[cfg(unix)]
#[test]
fn a_failing_probe_reports_its_status_even_with_parseable_output() {
let (status, out) = run_bounded_stdout(
std::path::Path::new("sh"),
&[
std::ffi::OsStr::new("-c"),
std::ffi::OsStr::new("echo 'Pages: 9'; exit 1"),
],
budget(2000),
)
.expect("output is still returned; the status is what says to ignore it");
assert!(
!status.success(),
"a non-zero exit must be visible to the caller"
);
assert_eq!(
parse_pdfinfo_pages(&out),
Some(9),
"the output really would have parsed, which is why the guard matters"
);
}
#[test]
fn pdfinfo_returns_none_when_pages_line_missing() {
let sample = "Title: Untitled\nAuthor: Anon\n";
assert!(parse_pdfinfo_pages(sample).is_none());
}
#[test]
fn pdfinfo_handles_extra_whitespace() {
let sample = "Pages: 7\n";
assert_eq!(parse_pdfinfo_pages(sample), Some(7));
}
#[cfg(unix)]
#[test]
fn a_blocking_pipe_still_yields_what_the_renderer_wrote() {
let mut child = std::process::Command::new("sh")
.args(["-c", "echo 'Syntax Error: no trailer' >&2; exit 1"])
.stderr(std::process::Stdio::piped())
.spawn()
.expect("spawn");
let mut pipe = child.stderr.take().expect("piped stderr");
let status = child.wait().expect("wait");
assert!(!status.success(), "the fixture must fail");
let mut buf = Vec::new();
read_once(Some(&mut pipe), &mut buf);
let text = String::from_utf8_lossy(&buf).trim().to_string();
assert_eq!(
text, "Syntax Error: no trailer",
"the renderer's own line must survive the blocking path"
);
}
#[cfg(unix)]
#[test]
fn set_nonblocking_reports_whether_the_pipe_is_now_non_blocking() {
let mut child = std::process::Command::new("sh")
.args(["-c", "exit 0"])
.stderr(std::process::Stdio::piped())
.spawn()
.expect("spawn");
let pipe = child.stderr.take().expect("piped stderr");
assert!(
set_nonblocking(Some(&pipe)),
"a live pipe must report non-blocking"
);
assert!(
!set_nonblocking_on(-1),
"a bad descriptor must report failure, not be ignored"
);
assert!(set_nonblocking(None), "no pipe means nothing to block on");
let _ = child.wait();
}
}