1use std::{fs, path::Path};
4
5use merry_runtime::ToolExecutionOutcome;
6use serde::{Deserialize, Serialize};
7
8#[cfg(not(feature = "pdf"))]
9use crate::errors::{DomainError, ERROR_INVALID_DOCUMENT};
10use crate::{
11 config::WorkspaceToolLimits, errors::BlockingToolError, path::ValidatedToolPath,
12 read::input::PdfReadFormat,
13};
14
15#[cfg(all(test, feature = "pdf"))]
16pub(crate) use super::pdf_hayro::parse_page_range;
17
18const PDF_MAGIC: &[u8; 5] = b"%PDF-";
19
20#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
22pub struct WorkspaceReadPdfPagesSuccess {
23 pub ok: bool,
25 pub tool: String,
27 pub kind: String,
29 pub path: String,
31 pub total_pages: usize,
33 pub rendered_pages: Vec<usize>,
35 pub source_bytes: usize,
37 pub total_png_bytes: usize,
39}
40
41pub(super) fn is_pdf_file(path: &Path, sniff_bytes: &[u8]) -> bool {
43 sniff_bytes.starts_with(PDF_MAGIC) || super::has_extension(path, "pdf")
44}
45
46pub(super) struct PdfReadRequest<'a> {
47 pub(super) pages: Option<&'a str>,
48 pub(super) format: PdfReadFormat,
49 pub(super) start_line: usize,
50 pub(super) max_lines: usize,
51}
52
53pub(super) fn read_resolved_pdf(
54 relative: &ValidatedToolPath,
55 file: &mut fs::File,
56 request: PdfReadRequest<'_>,
57 limits: &WorkspaceToolLimits,
58 is_cancelled: &dyn Fn() -> bool,
59) -> Result<ToolExecutionOutcome, BlockingToolError> {
60 #[cfg(feature = "pdf")]
61 {
62 super::pdf_hayro::read_resolved_pdf(relative, file, request, limits, is_cancelled)
63 }
64 #[cfg(not(feature = "pdf"))]
65 {
66 let _ = (
67 relative,
68 file,
69 request.pages,
70 request.format,
71 request.start_line,
72 request.max_lines,
73 limits,
74 );
75 if is_cancelled() {
76 return Err(BlockingToolError::Cancelled);
77 }
78 Err(DomainError::new(
79 ERROR_INVALID_DOCUMENT,
80 "PDF reading is disabled in this build (compiled without the `pdf` feature)",
81 )
82 .into())
83 }
84}