mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-17 15:44:37 +00:00
## What this changes Batch processing now keeps the caller's "Enable JavaScript" setting. Before, each file was processed in a fresh `Session::new()`, where JavaScript is on, so open-time XFA scripts and "Run a JavaScript" steps ran and their results were saved. - `actions::run_on` and `ocr::recognize_file` take a `javascript: bool` and call `set_javascript` before opening the file. In `recognize_file` the open now goes through a small private helper, `ocr::open_file`, so the open path can be tested without the recognition models. - `doc_batch`'s `Recipe` carries the setting into its per-file session and its OCR step. - Callers pass their own `session.javascript()`: the desktop Action Wizard, desktop multi-file OCR, `action_run`, `ocr_recognize_files` and `doc_batch`. Also relevant to #5054: an administrator's `DisableJavaScript` policy now reaches these sessions. Fixes #5080 ## How you verified it Regression tests, adopted from the reviewers' patches, plus one for the OCR open path: - `crates/engine/src/tests.rs::an_action_runs_a_javascript_step_only_when_javascript_is_on` (croquete1): a "Run a JavaScript" step writes its field with JavaScript on, and `run_on(.., false, ..)` refuses it instead of saving a scripted value. croquete1 reported it failing with the `set_javascript` call in `run_on` removed. - `crates/automation/tests/it/automation.rs::file_processing_keeps_javascript_off_for_xfa_open_scripts` (Harrison-Booth): with `js_enabled` off, an XFA initialize script that sets `qty` to 42 doesn't reach the output of `action_run`, `doc_batch` or (only when its models are installed) `ocr_recognize_files`. The contributor reported that each propagation removed on its own makes it fail. - `crates/engine/src/ocr.rs::tests::files_open_for_recognition_with_the_callers_javascript_preference`: opens the scripted XFA fixture through `recognize_file`'s open path with JavaScript off (the initialize script leaves `qty` empty) and on (it sets `qty` to 2). This covers the OCR propagation in runs without the OCR models. What was run locally, and what wasn't: - `cargo fmt --check` and `cargo clippy --all-targets -- -D warnings` were clean on `pdfcraft-engine`, `pdfcraft-automation` and `pdfcraft-ui-egui` at the earlier heads. On the latest commit only `cargo fmt --all` was run; clippy was not re-run. - No tests were run locally, including the new `ocr::tests` one: test builds time out on this machine, and the run was stopped before it compiled. The new test has not been seen failing either. If `set_javascript` is removed, the session keeps its JavaScript-on default, so the off case would read `qty` = 2 like the on case, and the first assertion would fail. Seeing that happen is still owed. - The tests are left to the maintainers' CI. No CI result is claimed for this PR. - [x] `cargo fmt --check` - [ ] clippy with `-D warnings` on the crates I changed (clean at the earlier heads; not re-run on the latest commit) - [ ] tests pass on the crates I changed (not run locally) - [x] `cargo xtask layers` and `cargo xtask assets`: N/A. No crate boundaries, dependencies or assets change. ## Never-crash - [x] No new `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!` outside tests. The new non-test code only passes a `bool` and propagates errors with `?`. - [x] No indexing or slicing with input-derived positions, no new arithmetic, allocations or recursion. - [x] No `unsafe` - [x] Any crash this fixes has a regression test: N/A, this fixes no crash. ## Provenance - [x] No asset from an Adobe product, and no Adobe icon recreated, traced or imitated (no assets change) - [x] No font files committed here - [x] No GPL/AGPL code copied in - [x] Behaviour comes from the project's own JavaScript preference (`Session::set_javascript`) and issue #5080, not from another implementation's source - [x] Every new asset has an `ATTRIBUTION.toml` entry: N/A, no new assets ## Security - [x] `--root` confinement still holds: `action_run` and `ocr_recognize_files` still resolve every input and output through `resolve`, and `doc_batch`'s path handling is unchanged. No new paths are read or written. - [x] MCP and the UI control channel are untouched. - [x] No new outbound network access. - This narrows script execution: with JavaScript off, the per-file sessions of the Action Wizard, multi-file OCR, `action_run`, `ocr_recognize_files` and `doc_batch` no longer run document or step scripts. ## Parity and reach - [ ] `parity/acrobat-features.toml` not updated: this is a bug fix, and the `misc.batch-processing` entry's status (`partial`) and notes stay true. - [x] Reachable headlessly: `action_run`, `ocr_recognize_files` and `doc_batch` take the setting from the session, which `js_enabled` sets. - [x] Docs: N/A. No documented behaviour changes (`docs/cli-batch.md` doesn't describe JavaScript handling). ## Anything a reviewer should look at first - The existing `run_on` tests pass `true` to keep their behaviour; the tests above cover the JavaScript-off path. - `recognize_file` now has 7 parameters, the `too_many_arguments` limit. - The OCR branch of the end-to-end test runs only where the OCR models are installed. The engine unit test covers the OCR open path without them. Provisioning the models in CI is left as a separate decision. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * File actions, batch processing, and OCR now honor the JavaScript setting from your current session for each file. * When JavaScript is disabled, document scripts—including scripts that run when a document opens—won’t execute during processing. When enabled, JavaScript steps can run as expected. * This behavior applies across automated and in-app workflows. Per-file results and OCR output handling remain unchanged. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
256 lines
11 KiB
Rust
256 lines
11 KiB
Rust
//! Action Wizard: named sequences of steps run over files (Acrobat's guided actions), the
|
|
//! built-in actions, and running an action over many files (batch processing).
|
|
|
|
use std::sync::Arc;
|
|
|
|
use crate::{DocId, Edit, EditError, Session};
|
|
|
|
/// One step of an action.
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub enum Step {
|
|
/// Scan & OCR ▸ Recognize text (pages without text).
|
|
RecognizeText,
|
|
/// Reduce file size.
|
|
ReduceFileSize,
|
|
/// Remove hidden information (every category).
|
|
RemoveHiddenInformation,
|
|
/// Sanitize document.
|
|
Sanitize,
|
|
FlattenComments,
|
|
FlattenFields,
|
|
/// Add a text watermark (diagonal, 50% opaque).
|
|
AddWatermark(String),
|
|
/// Add a footer with this centre text (tokens such as `<<Page 1 of n>>` work).
|
|
AddFooter(String),
|
|
/// Add a header with this centre text.
|
|
AddHeader(String),
|
|
/// Set the document title.
|
|
SetTitle(String),
|
|
/// Prepare a form: detect fields.
|
|
DetectFormFields,
|
|
/// Run a JavaScript (console context).
|
|
RunJavaScript(String),
|
|
}
|
|
|
|
impl Step {
|
|
/// Every step, with an empty argument where it takes one (for the step picker).
|
|
pub fn all() -> Vec<Step> {
|
|
vec![
|
|
Step::RecognizeText,
|
|
Step::ReduceFileSize,
|
|
Step::RemoveHiddenInformation,
|
|
Step::Sanitize,
|
|
Step::FlattenComments,
|
|
Step::FlattenFields,
|
|
Step::AddWatermark(String::new()),
|
|
Step::AddHeader(String::new()),
|
|
Step::AddFooter(String::new()),
|
|
Step::SetTitle(String::new()),
|
|
Step::DetectFormFields,
|
|
Step::RunJavaScript(String::new()),
|
|
]
|
|
}
|
|
|
|
/// A stable id (agents, saved actions).
|
|
pub fn id(&self) -> &'static str {
|
|
match self {
|
|
Step::RecognizeText => "recognize_text",
|
|
Step::ReduceFileSize => "reduce_file_size",
|
|
Step::RemoveHiddenInformation => "remove_hidden_information",
|
|
Step::Sanitize => "sanitize",
|
|
Step::FlattenComments => "flatten_comments",
|
|
Step::FlattenFields => "flatten_fields",
|
|
Step::AddWatermark(_) => "add_watermark",
|
|
Step::AddHeader(_) => "add_header",
|
|
Step::AddFooter(_) => "add_footer",
|
|
Step::SetTitle(_) => "set_title",
|
|
Step::DetectFormFields => "detect_form_fields",
|
|
Step::RunJavaScript(_) => "run_javascript",
|
|
}
|
|
}
|
|
|
|
pub fn label(&self) -> &'static str {
|
|
match self {
|
|
Step::RecognizeText => "Recognize text",
|
|
Step::ReduceFileSize => "Reduce file size",
|
|
Step::RemoveHiddenInformation => "Remove hidden information",
|
|
Step::Sanitize => "Sanitize document",
|
|
Step::FlattenComments => "Flatten comments",
|
|
Step::FlattenFields => "Flatten form fields",
|
|
Step::AddWatermark(_) => "Add watermark",
|
|
Step::AddHeader(_) => "Add header",
|
|
Step::AddFooter(_) => "Add footer",
|
|
Step::SetTitle(_) => "Set document title",
|
|
Step::DetectFormFields => "Detect form fields",
|
|
Step::RunJavaScript(_) => "Run a JavaScript",
|
|
}
|
|
}
|
|
|
|
/// The step's text argument, if it takes one.
|
|
pub fn arg(&self) -> Option<&str> {
|
|
match self {
|
|
Step::AddWatermark(s) | Step::AddHeader(s) | Step::AddFooter(s) | Step::SetTitle(s) | Step::RunJavaScript(s) => Some(s),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
pub fn arg_mut(&mut self) -> Option<&mut String> {
|
|
match self {
|
|
Step::AddWatermark(s) | Step::AddHeader(s) | Step::AddFooter(s) | Step::SetTitle(s) | Step::RunJavaScript(s) => Some(s),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// Build a step from its id and argument.
|
|
pub fn from_id(id: &str, arg: &str) -> Option<Step> {
|
|
let mut s = Step::all().into_iter().find(|s| s.id() == id)?;
|
|
if let Some(a) = s.arg_mut() {
|
|
*a = arg.to_string();
|
|
}
|
|
Some(s)
|
|
}
|
|
}
|
|
|
|
/// A named action.
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct Action {
|
|
pub name: String,
|
|
pub description: String,
|
|
pub steps: Vec<Step>,
|
|
/// One of PdfCraft's own actions (can't be edited or deleted).
|
|
pub builtin: bool,
|
|
}
|
|
|
|
/// The built-in actions.
|
|
pub fn builtin() -> Vec<Action> {
|
|
let a = |name: &str, description: &str, steps: Vec<Step>| Action { name: name.into(), description: description.into(), steps, builtin: true };
|
|
vec![
|
|
a(
|
|
"Prepare for Distribution",
|
|
"Remove hidden information and flatten comments and form fields, so recipients see only the pages.",
|
|
vec![Step::RemoveHiddenInformation, Step::FlattenComments, Step::FlattenFields],
|
|
),
|
|
a("Optimize Scanned Documents", "Make scans searchable, then make them smaller.", vec![Step::RecognizeText, Step::ReduceFileSize]),
|
|
a("Add Page Numbers", "Number every page in the footer.", vec![Step::AddFooter("Page <<1>> of <<n>>".into())]),
|
|
a("Mark as Confidential", "A diagonal CONFIDENTIAL watermark on every page.", vec![Step::AddWatermark("CONFIDENTIAL".into())]),
|
|
a("Sanitize Documents", "Remove hidden information, metadata, scripts and embedded content, and rewrite the files.", vec![Step::Sanitize]),
|
|
]
|
|
}
|
|
|
|
/// What running an action on one file did.
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct FileResult {
|
|
pub name: String,
|
|
pub bytes: Arc<Vec<u8>>,
|
|
/// One line per step.
|
|
pub log: Vec<String>,
|
|
}
|
|
|
|
/// What an action's log says of the images a Reduce File Size step left, if there are any.
|
|
fn images_refused_note(images: usize) -> Option<String> {
|
|
(images > 0).then(|| format!("Reduce file size: {images} image(s) stayed as they were, past what one run may decode"))
|
|
}
|
|
|
|
/// Apply one action step to document `id`, adding what it did to `log`; returns the new
|
|
/// document when the step replaced it.
|
|
fn apply_step(s: &mut Session, id: DocId, step: &Step, log: &mut Vec<String>) -> Result<Option<DocId>, EditError> {
|
|
let pages = s.get(id).map_or(0, |d| d.info.pages.len());
|
|
let all: Vec<usize> = (0..pages).collect();
|
|
let edit = match step {
|
|
Step::RecognizeText => {
|
|
let found = s.recognize_text(id, &[], crate::ocr::OcrSettings::default()).map_err(EditError::Invalid)?;
|
|
log.push(format!("Recognize text: {} words", found.iter().map(|p| p.words.len()).sum::<usize>()));
|
|
return Ok(None);
|
|
}
|
|
Step::ReduceFileSize => {
|
|
let (bytes, report) = s.optimized_bytes(id, &crate::optimize::Settings::default(), &[])?;
|
|
let before = s.get(id).map_or(0, |d| d.bytes.len());
|
|
log.push(format!("Reduce file size: {} → {} bytes", before, bytes.len()));
|
|
log.extend(images_refused_note(report.optimize.images_refused));
|
|
let name = s.get(id).map(|d| d.name.clone()).unwrap_or_default();
|
|
s.close(id);
|
|
let new = s.open(name, None, bytes, None).map_err(|e| EditError::Reopen(e.to_string()))?;
|
|
return Ok(Some(new));
|
|
}
|
|
Step::RemoveHiddenInformation => Edit::RemoveHidden { which: crate::HIDDEN.to_vec() },
|
|
Step::Sanitize => Edit::Sanitize,
|
|
Step::FlattenComments => Edit::Flatten { comments: true, fields: false },
|
|
Step::FlattenFields => Edit::Flatten { comments: false, fields: true },
|
|
Step::AddWatermark(t) => {
|
|
Edit::AddWatermark { pages: all, settings: crate::Watermark { text: t.clone(), ..Default::default() }, replace: false, file: None }
|
|
}
|
|
Step::AddHeader(t) | Step::AddFooter(t) => {
|
|
let mut settings = crate::HeaderFooter::default();
|
|
settings.text[if matches!(step, Step::AddHeader(_)) { 1 } else { 4 }] = t.clone();
|
|
Edit::AddHeaderFooter { pages: all, settings, replace: false }
|
|
}
|
|
Step::SetTitle(t) => Edit::SetInfo { key: "Title".into(), value: t.clone() },
|
|
Step::DetectFormFields => {
|
|
let n = s.auto_detect_fields(id, &[])?.len();
|
|
log.push(format!("Detect form fields: {n}"));
|
|
return Ok(None);
|
|
}
|
|
Step::RunJavaScript(js) => {
|
|
let o = s.run_javascript(id, js, None)?;
|
|
log.push(match o.error {
|
|
Some(e) => format!("Run a JavaScript: {e}"),
|
|
None => "Run a JavaScript".into(),
|
|
});
|
|
return Ok(None);
|
|
}
|
|
};
|
|
// A step that finds nothing to do is not a failure. Any other error fails the file, so nothing is
|
|
// published for it: the file would otherwise be passed on without the step it was asked to apply.
|
|
let removes = matches!(step, Step::RemoveHiddenInformation | Step::Sanitize);
|
|
match s.apply(id, edit) {
|
|
Ok(()) => log.push(step.label().to_string()),
|
|
Err(EditError::Redact(pdfcraft_redact::RedactError::NothingToApply)) if removes => log.push(format!("{}: nothing to remove", step.label())),
|
|
Err(EditError::Redact(pdfcraft_redact::RedactError::NothingToApply)) => log.push(format!("{}: nothing to do", step.label())),
|
|
Err(e) => return Err(e),
|
|
}
|
|
Ok(None)
|
|
}
|
|
|
|
/// Run `action` on one file. `javascript` is the caller's [`Session::javascript`] preference:
|
|
/// when off, neither open-time scripts nor "Run a JavaScript" steps run. `progress(step, steps)`
|
|
/// is called before each step.
|
|
pub fn run_on(
|
|
action: &Action,
|
|
name: &str,
|
|
bytes: Arc<Vec<u8>>,
|
|
javascript: bool,
|
|
mut progress: impl FnMut(usize, usize),
|
|
) -> Result<FileResult, String> {
|
|
let mut s = Session::new();
|
|
// Before the open: open-time (XFA) scripts read it there.
|
|
s.set_javascript(javascript);
|
|
let mut id = s.open(name, None, bytes, None).map_err(|e| e.to_string())?;
|
|
if let Some(why) = s.get(id).and_then(|d| d.read_only_reason.clone()) {
|
|
return Err(why);
|
|
}
|
|
let mut log = Vec::new();
|
|
for (i, step) in action.steps.iter().enumerate() {
|
|
progress(i, action.steps.len());
|
|
if let Some(new) = apply_step(&mut s, id, step, &mut log).map_err(|e| format!("{}: {e}", step.label()))? {
|
|
id = new;
|
|
}
|
|
}
|
|
let d = s.get(id).ok_or("the document was lost")?;
|
|
// A signed file keeps its signatures: incremental. Otherwise a clean full rewrite.
|
|
let bytes = if d.is_signed() { s.save_bytes(id) } else { s.save_full_bytes(id) }.map_err(|e| e.to_string())?;
|
|
Ok(FileResult { name: name.to_string(), bytes, log })
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::images_refused_note;
|
|
|
|
/// A log line only for images that stayed, saying how many.
|
|
#[test]
|
|
fn the_log_says_when_images_stayed_as_they_were() {
|
|
assert_eq!(images_refused_note(0), None);
|
|
assert!(images_refused_note(1).is_some_and(|note| note.contains("1 image(s)")));
|
|
assert!(images_refused_note(3).is_some_and(|note| note.contains("3 image(s)")));
|
|
}
|
|
}
|