use std::{fs, path::Path};
use merry_runtime::ToolExecutionOutcome;
use serde::{Deserialize, Serialize};
#[cfg(not(feature = "pdf"))]
use crate::errors::{DomainError, ERROR_INVALID_DOCUMENT};
use crate::{
config::WorkspaceToolLimits, errors::BlockingToolError, path::ValidatedToolPath,
read::input::PdfReadFormat,
};
#[cfg(all(test, feature = "pdf"))]
pub(crate) use super::pdf_hayro::parse_page_range;
const PDF_MAGIC: &[u8; 5] = b"%PDF-";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkspaceReadPdfPagesSuccess {
pub ok: bool,
pub tool: String,
pub kind: String,
pub path: String,
pub total_pages: usize,
pub rendered_pages: Vec<usize>,
pub source_bytes: usize,
pub total_png_bytes: usize,
}
pub(super) fn is_pdf_file(path: &Path, sniff_bytes: &[u8]) -> bool {
sniff_bytes.starts_with(PDF_MAGIC) || super::has_extension(path, "pdf")
}
pub(super) struct PdfReadRequest<'a> {
pub(super) pages: Option<&'a str>,
pub(super) format: PdfReadFormat,
pub(super) start_line: usize,
pub(super) max_lines: usize,
}
pub(super) fn read_resolved_pdf(
relative: &ValidatedToolPath,
file: &mut fs::File,
request: PdfReadRequest<'_>,
limits: &WorkspaceToolLimits,
is_cancelled: &dyn Fn() -> bool,
) -> Result<ToolExecutionOutcome, BlockingToolError> {
#[cfg(feature = "pdf")]
{
super::pdf_hayro::read_resolved_pdf(relative, file, request, limits, is_cancelled)
}
#[cfg(not(feature = "pdf"))]
{
let _ = (
relative,
file,
request.pages,
request.format,
request.start_line,
request.max_lines,
limits,
);
if is_cancelled() {
return Err(BlockingToolError::Cancelled);
}
Err(DomainError::new(
ERROR_INVALID_DOCUMENT,
"PDF reading is disabled in this build (compiled without the `pdf` feature)",
)
.into())
}
}