Files
pdfcraft/crates/engine/src/optimizer.rs
T
PiohrunandClaude Opus 5.5 8582c84da8 M11: Optimize runs when a category it discards holds nothing (#5742)
* M11: Optimize runs when a category it discards holds nothing

PDF Optimizer's Discard Objects ticks pass their categories to
remove_hidden, which refuses a run that removes nothing. Ticking "Discard
bookmarks" on a file without bookmarks, or doc_optimize with such a
discard, ended the whole optimization with "there are no redaction marks
to apply". An empty category is now nothing discarded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AmsdeUCdTaD72jkDw2pJKY

* M8: doc_remove_hidden says when the listed categories hold nothing

Its error came from remove_hidden's refusal: "there are no redaction marks
to apply". It now checks the scan first, as redact_apply checks for marks,
and says there is nothing to remove. The scan counts what removal takes
(an AcroForm with no fields as 1), so the check refuses only what the
removal would. The tool description says it fails then.

The tool test also runs doc_optimize discarding categories that hold
nothing, end to end.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AmsdeUCdTaD72jkDw2pJKY

* M11: Optimize passes remove_hidden only the ticked categories that hold something

Catching remove_hidden's refusal kept a copy it may have changed: with
bookmarks ticked it drops an empty outline root before counting nothing,
and its own documentation says to drop such a copy. The optimizer now
scans first and passes only the ticked categories the scan finds something
in, and with none doesn't call it, so an empty outline root stays, as
Remove Hidden Information leaves it.

Corrects 278a588bf's message: the ticks are under Discard Objects and
Discard User Data, and hidden text is one of them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AmsdeUCdTaD72jkDw2pJKY

* M8: doc_remove_hidden reads one scan, and says why it can't edit

A document that can't be edited has no scan, so the check read every
category as empty and said the listed ones hold nothing; the reason it
can't be edited comes through again. The check and the count of what was
removed now share the one scan the tool took already.

Corrects ada2a1ccb's message: the removal also takes what its scan counts
as 0 (an empty outline root); what the check matches is that the removal
refuses when its scan counts every listed category as 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AmsdeUCdTaD72jkDw2pJKY

* M11: the optimizer test discards a category that holds something

Mutants of the category filter survived: no test ticked a category that
holds something, or an empty one beside an unticked one that does. A page
with a comment and no bookmarks, discarding both, discards the comment
and only it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AmsdeUCdTaD72jkDw2pJKY

* M11: Optimize passes every ticked category, and keeps the copy from before a refusal

c7c018ac6 passed remove_hidden only the ticked categories its scan finds
something in. But with form fields ticked, discarding hidden text also
takes the hidden text the flattened appearances bring onto the page,
which no scan before flattening counts, so with Flatten form fields and
Discard hidden text ticked, the hidden text was dropped from the list and
stayed in the file, where main removes it.

Every ticked category goes to remove_hidden again, as on main. When it
refuses (every category counts 0), it may have changed the copy (an
empty outline root goes with bookmarks, and then it refuses), so the copy
from before the call is kept and nothing is discarded. That also drops
the extra scan c7c018ac6 added.

Corrects c7c018ac6's message: remove_hidden counts first, then drops an
empty outline root, then refuses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AmsdeUCdTaD72jkDw2pJKY

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 00:33:04 -05:00

133 lines
6.0 KiB
Rust

//! Optimize PDF ▸ Advanced optimization as a job that reports its progress.
//!
//! Optimizing a large file takes a while (every image is decoded, resampled and re-encoded), so
//! it is split like OCR: [`Session::optimize_job`] captures a copy of the document and the
//! choices, and [`OptimizeJob::run`] works anywhere (the UI runs it on a worker thread),
//! reporting each [`OptimizeStage`] and stopping when asked to.
use std::sync::Arc;
use pdfcraft_cos::{SaveOptions, write_full};
use crate::{DocId, EditError, Hidden, OptimizeReport, Session, guard, optimize};
/// Where an optimization is.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum OptimizeStage {
/// Removing the user data chosen under Discard User Data.
#[default]
Discarding,
/// Merging the fragments of a page picture into one image.
Fragments,
/// About to process image `done` (0-based) of `total`.
Images { done: usize, total: usize },
/// Discarding objects and compressing unencoded streams.
CleaningUp,
/// Merging identical fonts and images.
Merging,
/// Writing the compressed copy.
Writing,
}
impl OptimizeStage {
/// How far along the whole run is, from 0 to 1. Images take most of the time; the rest are
/// small fixed steps.
pub fn fraction(self) -> f32 {
match self {
OptimizeStage::Discarding => 0.0,
OptimizeStage::Fragments => 0.03,
OptimizeStage::Images { done, total } => 0.05 + 0.75 * if total == 0 { 1.0 } else { done.min(total) as f32 / total as f32 },
OptimizeStage::CleaningUp => 0.8,
OptimizeStage::Merging => 0.85,
OptimizeStage::Writing => 0.9,
}
}
}
/// The optimized copy's bytes and what was done.
pub type Optimized = (Arc<Vec<u8>>, OptimizeReport);
/// What an optimization needs, independent of the session.
pub struct OptimizeJob {
cos: pdfcraft_cos::Document,
settings: optimize::Settings,
discard: Vec<Hidden>,
opts: SaveOptions,
}
impl Session {
/// Capture what optimizing document `id` with `settings` and the Remove Hidden Information
/// `discard` categories needs. A full rewrite: signed documents are refused.
pub fn optimize_job(&self, id: DocId, settings: &optimize::Settings, discard: &[Hidden]) -> Result<OptimizeJob, EditError> {
let doc = self.get(id).ok_or(EditError::NoDocument)?;
if doc.is_signed() {
return Err(EditError::Signed);
}
let editor = doc.editor.as_ref().ok_or_else(|| EditError::ReadOnly(doc.read_only_reason.clone().unwrap_or_default()))?;
Ok(OptimizeJob {
cos: editor.cos.clone(),
settings: settings.clone(),
discard: discard.to_vec(),
opts: SaveOptions {
mod_date: self.now().map(pdfcraft_cos::pdf_date),
object_streams: settings.effective_object_streams(),
..SaveOptions::default()
},
})
}
}
impl OptimizeJob {
/// Optimize and write the copy. `progress` is called as each stage starts and before each
/// image; returning `false` stops with [`EditError::Cancelled`]. A panic is returned as an
/// error, so a worker thread always reports back.
pub fn run(self, mut progress: impl FnMut(OptimizeStage) -> bool) -> Result<Optimized, EditError> {
guard(move || self.work(&mut progress)).map_err(EditError::Optimize)?
}
fn work(self, progress: &mut dyn FnMut(OptimizeStage) -> bool) -> Result<Optimized, EditError> {
let OptimizeJob { mut cos, settings, discard, opts } = self;
// Like every file written, without the values of Password-flag fields (#3926, #3944).
pdfcraft_forms::clear_password_values(&mut cos).map_err(|e| EditError::Write(e.to_string()))?;
pdfcraft_xfa::clear_password_values(&mut cos).map_err(|e| EditError::Write(e.to_string()))?;
let mut step = |stage| if progress(stage) { Ok(()) } else { Err(EditError::Cancelled) };
step(OptimizeStage::Discarding)?;
let discarded = if discard.is_empty() {
Vec::new()
} else {
// Every ticked category, as `remove_hidden` decides between them: with form fields
// ticked, discarding hidden text also takes the hidden text the flattened appearances
// bring onto the page, which no scan before flattening counts. It refuses when its scan
// counts every one as 0, which would end the whole optimization, and may have changed
// the copy by then (an empty outline root goes with bookmarks), so the copy from before
// is kept instead: nothing is discarded.
let before = cos.clone();
match pdfcraft_redact::sanitize::remove_hidden(&mut cos, &discard) {
Err(pdfcraft_redact::RedactError::NothingToApply) => {
cos = before;
Vec::new()
}
r => r?,
}
};
let report = optimize::optimize_with_progress(&mut cos, &settings, &mut |s| {
step(match s {
optimize::Stage::Fragments => OptimizeStage::Fragments,
optimize::Stage::Images { done, total } => OptimizeStage::Images { done, total },
optimize::Stage::CleanUp => OptimizeStage::CleaningUp,
})
.is_ok()
})
.map_err(|e| match e {
optimize::OptimizeError::Cancelled => EditError::Cancelled,
e => EditError::Optimize(e.to_string()),
})?;
step(OptimizeStage::Merging)?;
let all: Vec<pdfcraft_cos::ObjRef> = cos.object_numbers().into_iter().map(|n| pdfcraft_cos::ObjRef::new(n, cos.generation(n))).collect();
let merged = pdfcraft_organize::dedupe_resources(&mut cos, &all, false);
step(OptimizeStage::Writing)?;
let bytes = write_full(&cos, &opts).map_err(|e| EditError::Write(e.to_string()))?;
Ok((Arc::new(bytes), OptimizeReport { optimize: report, merged, discarded }))
}
}