pdfsift 0.1.0

PDF to structured Markdown for LLM agents. Heuristics only: no AI model, no network.
//! Locates and binds the PDFium library.
//!
//! For now PDFium is loaded dynamically (no static builds exist, see decision 0002).
//! Search order:
//! 1. `PDFSIFT_PDFIUM` (path to the library file or to its directory)
//! 2. next to the executable or in `pdfium/` beside it (the release archive layout),
//!    both as invoked and with symlinks resolved (Homebrew and the install scripts put
//!    a symlink on the PATH); then `../lib` and `../share/pdfsift[/pdfium]` relative to
//!    it (Homebrew installs the extra archive files into `share/<name>`)
//! 3. debug builds only: `.pdfium/<platform>/{bin,lib}` in the current directory (dev
//!    setup, `scripts/fetch-pdfium.sh`)
//! 4. the system library search path, except on Windows
//!
//! Loading a library is running its code, so no lookup depends on the current
//! directory in release builds: running pdfsift inside a directory holding an
//! untrusted `pdfium.dll` must not execute it. Windows' `LoadLibrary` search includes
//! the current directory, hence no system fallback there.

use std::path::{Path, PathBuf};

use anyhow::{Context, Result, anyhow};
use pdfium_render::prelude::*;

/// The PDFium build the releases ship and the code is tested against.
pub const PDFIUM_BUILD: &str = "chromium/8179";

fn platform_dir() -> &'static str {
    match (std::env::consts::OS, std::env::consts::ARCH) {
        ("windows", "x86_64") => "win-x64",
        ("windows", "aarch64") => "win-arm64",
        ("macos", "aarch64") => "mac-arm64",
        ("macos", "x86_64") => "mac-x64",
        ("linux", "aarch64") => "linux-arm64",
        _ => "linux-x64",
    }
}

fn candidates() -> Vec<PathBuf> {
    let mut dirs = Vec::new();
    if let Some(p) = std::env::var_os("PDFSIFT_PDFIUM") {
        let p = PathBuf::from(p);
        if p.is_file() {
            return vec![p];
        }
        dirs.push(p);
    }
    if let Ok(exe) = std::env::current_exe() {
        // Only resolve real symlinks: on Windows canonicalize() also rewrites the path
        // into its verbatim (`\\?\`) form, which would just repeat every candidate.
        let resolved = std::fs::symlink_metadata(&exe)
            .is_ok_and(|m| m.file_type().is_symlink())
            .then(|| std::fs::canonicalize(&exe).ok())
            .flatten();
        for exe in std::iter::once(exe).chain(resolved) {
            if let Some(dir) = exe.parent() {
                dirs.push(dir.to_path_buf());
                dirs.push(dir.join("pdfium"));
                if let Some(prefix) = dir.parent() {
                    let share = prefix.join("share").join("pdfsift");
                    dirs.push(prefix.join("lib"));
                    dirs.push(share.join("pdfium"));
                    dirs.push(share);
                }
            }
        }
    }
    if cfg!(debug_assertions) {
        let dev = Path::new(".pdfium").join(platform_dir());
        dirs.push(dev.join("bin"));
        dirs.push(dev.join("lib"));
    }
    let mut libs: Vec<PathBuf> = dirs
        .into_iter()
        .map(|d| Pdfium::pdfium_platform_library_name_at_path(&d))
        .collect();
    libs.dedup();
    libs
}

pub fn load() -> Result<Pdfium> {
    let libs = candidates();
    for lib in &libs {
        if lib.is_file() {
            let bindings = Pdfium::bind_to_library(lib).with_context(|| {
                format!(
                    "failed to load PDFium from {} (pdfsift needs the PDFium {PDFIUM_BUILD} \
                     build for this platform from github.com/bblanchon/pdfium-binaries)",
                    lib.display()
                )
            })?;
            return Ok(Pdfium::new(bindings));
        }
    }
    let system = if cfg!(windows) {
        Err("not searched on Windows".to_string())
    } else {
        Pdfium::bind_to_system_library().map_err(|e| format!("{e:?}"))
    };
    let bindings = system.map_err(|e| not_found(&libs, &e))?;
    Ok(Pdfium::new(bindings))
}

fn not_found(searched: &[PathBuf], system: &str) -> anyhow::Error {
    let mut msg = format!(
        "PDFium library not found. pdfsift loads {name} at runtime; the release archives \
         and the npm/PyPI packages ship it next to the executable, but `cargo install` \
         does not.\n\
         To fix it, download pdfium-{platform}.tgz from \
         https://github.com/bblanchon/pdfium-binaries/releases/tag/{tag} \
         and either copy {name} (in its bin/ or lib/ folder) next to the pdfsift \
         executable, or set PDFSIFT_PDFIUM to its path.\n\
         Searched:",
        name = Pdfium::pdfium_platform_library_name().to_string_lossy(),
        platform = platform_dir(),
        tag = PDFIUM_BUILD.replace('/', "%2F"),
    );
    for p in searched {
        msg.push_str(&format!("\n  {}", p.display()));
    }
    msg.push_str(&format!("\n  system library path: {system}"));
    anyhow!(msg)
}