mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-15 23:32:37 +00:00
Merge remote-tracking branch 'upstream/main' into fix/xfa-relevant-print
This commit is contained in:
commit
cdd446dcfb
101 files changed
+5141
-390
No files matched your search
@@ -32,7 +32,8 @@ pub struct Document {
|
||||
pub dirty: bool,
|
||||
/// Bumped on every change to the working file (edit, undo, redo, save); autosave compares it.
|
||||
pub(crate) generation: u64,
|
||||
/// The generation last handed out by `autosave_snapshots`.
|
||||
/// The generation last handed out by `autosave_snapshots`, or another one when storing that
|
||||
/// snapshot failed (`autosave_failed`), so it is due again.
|
||||
pub(crate) snapshot_generation: u64,
|
||||
/// Why the document cannot be edited (e.g. encryption), if so.
|
||||
pub read_only_reason: Option<String>,
|
||||
@@ -727,6 +728,14 @@ pub(crate) fn write_display_copy(
|
||||
}
|
||||
}
|
||||
|
||||
/// `doc` as the reader shows it: comments without an appearance stream drawn
|
||||
/// (`pdfcraft_annot::with_missing_appearances`) and form fields drawn from their values where the
|
||||
/// file leaves that to the viewer. `None` when `doc` needs neither. The vector print draws from
|
||||
/// this copy too, so what prints is what the page shows (#371, #3475 draw them for display only).
|
||||
pub(crate) fn as_displayed(doc: &pdfcraft_cos::Document) -> Option<pdfcraft_cos::Document> {
|
||||
with_field_appearances(pdfcraft_annot::with_missing_appearances(doc), doc)
|
||||
}
|
||||
|
||||
/// Carry the marks across a revalidation that leaves the display copy alone, when it may: only
|
||||
/// when every verdict is the one the copy was drawn with. Returns whether it did; otherwise the
|
||||
/// copy has to be drawn again.
|
||||
@@ -778,7 +787,7 @@ pub fn display_bytes_for(bytes: Arc<Vec<u8>>, password: Option<&str>) -> Arc<Vec
|
||||
let cos = pdfcraft_cos::Document::open_with_password(bytes.clone(), password).ok()?;
|
||||
let mut signatures = signatures_of(&cos, &bytes, &TrustStore::default(), &pdfcraft_sign::DigestCache::default());
|
||||
let layered = pdfcraft_sign::has_status_layers(&cos, &signatures);
|
||||
let (mut display, added) = match with_field_appearances(pdfcraft_annot::with_missing_appearances(&cos), &cos) {
|
||||
let (mut display, added) = match as_displayed(&cos) {
|
||||
Some(display) => (display, true),
|
||||
None if layered => (cos, false),
|
||||
None => return None,
|
||||
|
||||
@@ -95,7 +95,11 @@ pub(crate) fn scope_of(edit: &Edit) -> Scope {
|
||||
| Edit::AddHeaderFooter { .. }
|
||||
| Edit::AddWatermark { .. }
|
||||
| Edit::AddBackground { .. }
|
||||
| Edit::RemoveMarks { .. } => Scope::Content,
|
||||
| Edit::RemoveMarks { .. }
|
||||
// Recognized text is an invisible text layer stamped on its page, with its font in the
|
||||
// page's resources (#6310): a full re-inspection made applying one word cost seconds on
|
||||
// a large file.
|
||||
| Edit::AddOcrText { .. } => Scope::Content,
|
||||
Edit::Batch { edits, .. } => {
|
||||
let mut scopes = edits.iter().map(scope_of);
|
||||
let first = scopes.next().unwrap_or(Scope::Full);
|
||||
|
||||
@@ -246,6 +246,7 @@ impl Scripts for JsRunner {
|
||||
self.run_logged(event, script, target, value, fields, true).unwrap_or_else(|| ScriptResult {
|
||||
rc: true,
|
||||
value: value.to_string(),
|
||||
value_set: false,
|
||||
changes: Vec::new(),
|
||||
message: None,
|
||||
})
|
||||
@@ -282,6 +283,7 @@ impl JsRunner {
|
||||
Some(ScriptResult {
|
||||
rc: o.rc,
|
||||
value: o.value.clone(),
|
||||
value_set: o.value_set,
|
||||
changes: changes(&states, &o.changed),
|
||||
message: (!o.rc).then(|| o.alerts.last().map(|m| m.text.clone())).flatten(),
|
||||
})
|
||||
|
||||
@@ -161,7 +161,10 @@ pub use session::Session;
|
||||
pub use sources::{CombineSource, Combined, combine_source_check, source_page_count};
|
||||
use sources::{open_source, open_source_with};
|
||||
#[cfg(test)]
|
||||
use test_hooks::{check_refresh_panic, panic_on_refresh, record_link_scan, record_marker_scan, reset_secondary_scan_counts, secondary_scan_counts};
|
||||
use test_hooks::{
|
||||
check_refresh_panic, panic_on_refresh, record_full_refresh, record_link_scan, record_marker_scan, reset_secondary_scan_counts,
|
||||
secondary_scan_counts, take_full_refreshes,
|
||||
};
|
||||
use xfa_form::{
|
||||
XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, decode_data_file, image_content_type, is_xfa_data_file, note_warnings, strip_xfa, sync_xfa_state,
|
||||
undrawn_field_warnings, xfa_after_data_change, xfa_layout, xfa_redraw, xfa_sync_datasets, xfa_values_from_datasets,
|
||||
|
||||
@@ -971,10 +971,23 @@ impl Session {
|
||||
pub fn ocr_job(&self, id: DocId, pages: &[usize], settings: OcrSettings) -> Option<OcrJob> {
|
||||
let doc = self.get(id)?;
|
||||
let all = doc.info.pages.len();
|
||||
let pages: Vec<usize> = if pages.is_empty() { (0..all).collect() } else { pages.iter().copied().filter(|p| *p < all).collect() };
|
||||
let mut seen = vec![false; all];
|
||||
let pages: Vec<usize> = if pages.is_empty() {
|
||||
seen.fill(true);
|
||||
(0..all).collect()
|
||||
} else {
|
||||
let mut deduped = Vec::new();
|
||||
for &p in pages {
|
||||
if seen.get(p) == Some(&false) {
|
||||
seen[p] = true;
|
||||
deduped.push(p);
|
||||
}
|
||||
}
|
||||
deduped
|
||||
};
|
||||
let native = (0..all)
|
||||
.map(|p| {
|
||||
if !pages.contains(&p) {
|
||||
if seen.get(p) != Some(&true) {
|
||||
return None;
|
||||
}
|
||||
doc.page_images(p)
|
||||
@@ -2234,6 +2247,59 @@ mod tests {
|
||||
assert_eq!(page, 0);
|
||||
}
|
||||
|
||||
/// A scan selected explicitly is rendered at its native scale, like the same page in an
|
||||
/// all-pages job: selecting pages must not lose the native-resolution lookup and render
|
||||
/// the scan above its own resolution at a higher chosen dpi.
|
||||
#[test]
|
||||
fn selected_scan_page_uses_native_scale_like_all_pages() {
|
||||
let mut s = Session::new();
|
||||
let page = export::encode_png(2480, 3508, &vec![255; (2480 * 3508 * 4) as usize]).unwrap();
|
||||
let bytes = s.create_from_images(&[("a4.png".into(), page)]).unwrap();
|
||||
let id = s.open("scan.pdf", None, bytes, None).unwrap();
|
||||
let settings = OcrSettings { dpi: 300.0, ..Default::default() };
|
||||
let all = s.ocr_job(id, &[], settings.clone()).unwrap();
|
||||
let selected = s.ocr_job(id, &[0], settings).unwrap();
|
||||
assert_eq!(selected.pages, vec![0]);
|
||||
let wanted = 300.0 / 72.0;
|
||||
assert!(all.render_scale(0) < wanted, "native resolution limits the all-pages job: {}", all.render_scale(0));
|
||||
assert!(
|
||||
(selected.render_scale(0) - all.render_scale(0)).abs() < 1e-4,
|
||||
"selected page {} vs all-pages {}",
|
||||
selected.render_scale(0),
|
||||
all.render_scale(0)
|
||||
);
|
||||
}
|
||||
|
||||
/// A job requested with the same page twice carries each page once: a duplicate would
|
||||
/// otherwise be recognized twice.
|
||||
#[test]
|
||||
fn ocr_job_deduplicates_requested_pages() {
|
||||
let mut s = Session::new();
|
||||
let id = s.open("t.pdf", None, Arc::new(fixture(3)), None).unwrap();
|
||||
let job = s.ocr_job(id, &[2, 0, 2, 1, 0, 2], OcrSettings::default()).unwrap();
|
||||
assert_eq!(job.pages, vec![2, 0, 1], "each requested page appears once, in request order");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ocr_job_bounds_page_vector_reservation_by_page_count() {
|
||||
let mut s = Session::new();
|
||||
let id = s.open("t.pdf", None, Arc::new(fixture(3)), None).unwrap();
|
||||
let requested = vec![999usize; 1024];
|
||||
let job = s.ocr_job(id, &requested, OcrSettings::default()).unwrap();
|
||||
assert!(job.pages.is_empty());
|
||||
assert!(job.pages.capacity() <= 3, "reservation {} exceeds the 3 pages that can survive deduplication", job.pages.capacity());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ocr_job_does_not_reserve_capacity_for_invalid_pages() {
|
||||
let mut s = Session::new();
|
||||
let id = s.open("t.pdf", None, Arc::new(fixture(1024)), None).unwrap();
|
||||
let requested = vec![4096usize; 1024];
|
||||
let job = s.ocr_job(id, &requested, OcrSettings::default()).unwrap();
|
||||
assert!(job.pages.is_empty());
|
||||
assert_eq!(job.pages.capacity(), 0, "no valid pages were found, so no capacity should be reserved");
|
||||
}
|
||||
|
||||
/// #1848: an A4 scan at 300 dpi whose page box is its pixel size (2480 x 3508 pt, one pixel
|
||||
/// per point) gets a smaller bitmap for each lower "Downsample to" choice, and a low-resolution
|
||||
/// letter page is still never shrunk below one pixel per point.
|
||||
|
||||
@@ -12,11 +12,12 @@ 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)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum OptimizeStage {
|
||||
/// Removing the user data chosen under Discard User Data.
|
||||
#[default]
|
||||
/// Removing the user data chosen under Discard User Data, if any was.
|
||||
Discarding,
|
||||
/// Reading what the pages draw: `done` of `total` read.
|
||||
Reading { done: usize, total: usize },
|
||||
/// Merging the fragments of a page picture into one image.
|
||||
Fragments,
|
||||
/// About to process image `done` (0-based) of `total`.
|
||||
@@ -29,14 +30,21 @@ pub enum OptimizeStage {
|
||||
Writing,
|
||||
}
|
||||
|
||||
impl Default for OptimizeStage {
|
||||
fn default() -> Self {
|
||||
OptimizeStage::Reading { done: 0, total: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
/// How far along the whole run is, from 0 to 1, weighed by where the time goes: reading pages
|
||||
/// and pictures. The rest are small fixed steps.
|
||||
pub fn fraction(self) -> f32 {
|
||||
let part = |done: usize, total: usize| if total == 0 { 1.0 } else { done.min(total) as f32 / total as 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::Discarding | OptimizeStage::Fragments => 0.0,
|
||||
OptimizeStage::Reading { done, total } => 0.25 * if total == 0 { 0.0 } else { part(done, total) },
|
||||
OptimizeStage::Images { done, total } => 0.25 + 0.55 * part(done, total),
|
||||
OptimizeStage::CleaningUp => 0.8,
|
||||
OptimizeStage::Merging => 0.85,
|
||||
OptimizeStage::Writing => 0.9,
|
||||
@@ -91,10 +99,10 @@ impl OptimizeJob {
|
||||
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 {
|
||||
step(OptimizeStage::Discarding)?;
|
||||
// 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
|
||||
@@ -112,6 +120,7 @@ impl OptimizeJob {
|
||||
};
|
||||
let report = optimize::optimize_with_progress(&mut cos, &settings, &mut |s| {
|
||||
step(match s {
|
||||
optimize::Stage::Reading { done, total } => OptimizeStage::Reading { done, total },
|
||||
optimize::Stage::Fragments => OptimizeStage::Fragments,
|
||||
optimize::Stage::Images { done, total } => OptimizeStage::Images { done, total },
|
||||
optimize::Stage::CleanUp => OptimizeStage::CleaningUp,
|
||||
|
||||
@@ -515,6 +515,8 @@ impl Session {
|
||||
}
|
||||
|
||||
fn refresh_with_indexes(doc: &mut Document, invalidate_markers: bool, invalidate_links: bool) -> Result<(), EditError> {
|
||||
#[cfg(test)]
|
||||
crate::record_full_refresh();
|
||||
// A full refresh may follow structural or annotation changes: cached appearances
|
||||
// may be stale, so they are rebuilt below.
|
||||
if let Some(editor) = doc.editor.as_mut() {
|
||||
|
||||
@@ -164,6 +164,13 @@ impl Session {
|
||||
pdfcraft_cos::Document::open_with_password(doc.bytes.clone(), doc.password.as_deref()).map_err(|e| EditError::Write(e.to_string()))?
|
||||
}
|
||||
};
|
||||
// Comments and fields without an appearance print as the page shows them (and as Print
|
||||
// as Image already printed them): the vector print drew only appearance streams, so a
|
||||
// text box without one was on screen but not on paper. ISO 32000-2 §12.5.3: an
|
||||
// annotation with the Print flag is printed.
|
||||
if let Some(displayed) = guard(|| crate::document::as_displayed(&cos)).ok().flatten() {
|
||||
cos = displayed;
|
||||
}
|
||||
// #3046: the layers print as they are shown. Once the Layers panel (or a set-layer
|
||||
// action) has changed one, the print copy's default configuration says which are on, so a
|
||||
// hidden layer stays off on paper too; untouched, the document's own configuration prints.
|
||||
|
||||
@@ -217,6 +217,15 @@ impl Session {
|
||||
out
|
||||
}
|
||||
|
||||
/// The snapshot [`Self::autosave_snapshots`] handed out for `id` could not be stored: the
|
||||
/// document is due again, so the next autosave tries it again.
|
||||
pub fn autosave_failed(&mut self, id: DocId) {
|
||||
if let Some(d) = self.docs.iter_mut().find(|d| d.id == id) {
|
||||
// Any generation but the current one leaves it due.
|
||||
d.snapshot_generation = d.generation.wrapping_sub(1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark a document opened from a recovery file: it has unsaved changes and belongs at
|
||||
/// `path` (where Save writes), as when the session ended.
|
||||
pub fn mark_recovered(&mut self, id: DocId, path: Option<String>) {
|
||||
|
||||
@@ -40,3 +40,17 @@ pub(crate) fn record_link_scan() {
|
||||
counts.set((markers, links + 1));
|
||||
});
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static FULL_REFRESHES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// A whole-document refresh (re-inspection) ran on this thread.
|
||||
pub(crate) fn record_full_refresh() {
|
||||
FULL_REFRESHES.with(|n| n.set(n.get() + 1));
|
||||
}
|
||||
|
||||
/// How many whole-document refreshes ran on this thread since the last call, and starts over.
|
||||
pub(crate) fn take_full_refreshes() -> usize {
|
||||
FULL_REFRESHES.with(|n| n.replace(0))
|
||||
}
|
||||
+163
-1
@@ -1779,6 +1779,45 @@ fn low_resolution_printing_prints_only_the_chosen_content() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A comment and a field the file leaves without an appearance print as the page shows them:
|
||||
/// a text box (`/FreeText` with only `/Contents` and `/DA`) and a check box set on with
|
||||
/// `/NeedAppearances`. The vector print drew only appearance streams, so both were on screen and
|
||||
/// in Print as Image but not on paper (pdf.js `bug1865341`, `freetext_print_no_appearance`).
|
||||
/// ISO 32000-2 §12.5.3: an annotation with the Print flag is printed.
|
||||
#[test]
|
||||
fn comments_and_fields_without_an_appearance_print_as_shown() {
|
||||
let content = "";
|
||||
let pdf = format!(
|
||||
"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [6 0 R] /NeedAppearances true /DA (/Helv 0 Tf 0 g) >> >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R /Annots [5 0 R 6 0 R] >> endobj
|
||||
4 0 obj << /Length {} >> stream
|
||||
{content}
|
||||
endstream endobj
|
||||
5 0 obj << /Type /Annot /Subtype /FreeText /F 4 /P 3 0 R /Rect [10 120 190 190] /DA (/Helv 40 Tf 0 g) /Contents (WWWW) >> endobj
|
||||
6 0 obj << /Type /Annot /Subtype /Widget /FT /Btn /T (Box) /V /Yes /AS /Yes /F 4 /P 3 0 R /Rect [10 10 110 110] /MK << /CA (8) >> >> endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF",
|
||||
content.len(),
|
||||
);
|
||||
let mut s = Session::new();
|
||||
let id = s.open("bare.pdf", None, Arc::new(pdf.into_bytes()), None).unwrap();
|
||||
let settings =
|
||||
print::Settings { pages: vec![0], paper: (200.0, 200.0), layout: print::Layout::Size(print::SizeMode::Actual), ..Default::default() };
|
||||
let (w, h, rgba) = printed_pixels(s.print_pdf(id, &settings).unwrap());
|
||||
assert_eq!((w, h), (200, 200));
|
||||
// Dark pixels in the text box (top half) and in the check box (bottom half).
|
||||
let dark = |y0: usize, y1: usize| {
|
||||
(y0..y1)
|
||||
.flat_map(|y| (0..w as usize).map(move |x| (x, y)))
|
||||
.filter(|&(x, y)| rgba.get((y * w as usize + x) * 4).is_some_and(|&r| r < 128))
|
||||
.count()
|
||||
};
|
||||
assert!(dark(10, 80) > 50, "the text box prints");
|
||||
assert!(dark(90, 190) > 50, "the check box prints");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_permissions_password_unlocks_an_open_document() {
|
||||
// Only a permissions password (#995, #1077): opens without asking. Changes are allowed,
|
||||
@@ -3120,6 +3159,66 @@ fn setting_the_calculation_order_recalculates_and_undoes() {
|
||||
assert!(matches!(s.apply(id, Edit::SetCalculationOrder { names: vec!["qty".into()] }), Err(EditError::Form(_))));
|
||||
}
|
||||
|
||||
/// A Calculate script that sets its own field through the field object, not `event.value`,
|
||||
/// gives the field that value, text included; when it sets `event.value` as well, that wins.
|
||||
#[test]
|
||||
fn a_calculate_script_setting_its_own_field_object_keeps_the_value() {
|
||||
let (mut s, id) = session_with(1);
|
||||
for (i, name) in ["origin", "copy", "both"].into_iter().enumerate() {
|
||||
let y = 250.0 - 40.0 * i as f64;
|
||||
let kind = NewField::Text { multiline: false };
|
||||
s.apply(id, Edit::AddField { page: 0, rect: [20.0, y, 180.0, y + 22.0], kind, name: Some(name.into()) }).unwrap();
|
||||
}
|
||||
let script = |name: &str, js: &str| Edit::SetFieldScript { name: name.into(), event: "calculate".into(), script: Some(js.into()) };
|
||||
s.apply(id, script("copy", "var o = this.getField(\"origin\");\nthis.getField(\"copy\").value = o.value;")).unwrap();
|
||||
s.apply(id, script("both", "this.getField(\"both\").value = \"field\";\nevent.value = this.getField(\"origin\").value + \"!\";")).unwrap();
|
||||
s.apply(id, Edit::SetFieldValue { name: "origin".into(), value: FieldValue::Text("abc".into()) }).unwrap();
|
||||
let value = |s: &Session, n: &str| s.get(id).unwrap().form.iter().find(|f| f.name == n).and_then(|f| f.value.first().cloned());
|
||||
assert_eq!(value(&s, "copy").as_deref(), Some("abc"));
|
||||
assert_eq!(value(&s, "both").as_deref(), Some("abc!"), "event.value decides when the script sets both");
|
||||
s.apply(id, Edit::SetFieldValue { name: "origin".into(), value: FieldValue::Text("12".into()) }).unwrap();
|
||||
assert_eq!(value(&s, "copy").as_deref(), Some("12"));
|
||||
}
|
||||
|
||||
/// A Calculate script that assigns `event.value` the value its field already holds keeps it, even
|
||||
/// after writing another value through its field object; and a combo box a script moves to
|
||||
/// another option selects that option in `/I` too.
|
||||
#[test]
|
||||
fn a_calculate_script_assigning_event_value_wins_and_a_combo_keeps_its_selection() {
|
||||
let (mut s, id) = session_with(1);
|
||||
s.apply(
|
||||
id,
|
||||
Edit::AddField { page: 0, rect: [20.0, 250.0, 180.0, 272.0], kind: NewField::Text { multiline: false }, name: Some("origin".into()) },
|
||||
)
|
||||
.unwrap();
|
||||
s.apply(id, Edit::AddField { page: 0, rect: [20.0, 210.0, 180.0, 232.0], kind: NewField::Text { multiline: false }, name: Some("kept".into()) })
|
||||
.unwrap();
|
||||
let kind = NewField::Combo { options: vec!["Small".into(), "Large".into()], editable: false };
|
||||
s.apply(id, Edit::AddField { page: 0, rect: [20.0, 170.0, 180.0, 192.0], kind, name: Some("size".into()) }).unwrap();
|
||||
s.apply(id, Edit::SetFieldValue { name: "size".into(), value: FieldValue::Choice(vec!["Small".into()]) }).unwrap();
|
||||
let script = |name: &str, js: &str| Edit::SetFieldScript { name: name.into(), event: "calculate".into(), script: Some(js.into()) };
|
||||
s.apply(
|
||||
id,
|
||||
script(
|
||||
"kept",
|
||||
"var v = event.value;
|
||||
this.getField(\"kept\").value = \"field\";
|
||||
event.value = v;",
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
s.apply(id, script("size", "event.value = this.getField(\"origin\").value > 5 ? \"Large\" : \"Small\";")).unwrap();
|
||||
s.apply(id, Edit::SetFieldValue { name: "origin".into(), value: FieldValue::Text("9".into()) }).unwrap();
|
||||
assert!(s.take_js_output(id).errors.is_empty(), "both scripts ran to the end");
|
||||
let doc = s.get(id).unwrap();
|
||||
let value = |n: &str| doc.form.iter().find(|f| f.name == n).and_then(|f| f.value.first().cloned());
|
||||
assert_eq!(value("kept").as_deref(), None, "event.value, set to the field's own value, decides");
|
||||
assert_eq!(value("size").as_deref(), Some("Large"));
|
||||
let size = doc.form.iter().find(|f| f.name == "size").map(|f| f.obj).unwrap();
|
||||
let selected = doc.editor.as_ref().unwrap().cos.get(size).as_dict().and_then(|d| d.get(b"I")).cloned();
|
||||
assert_eq!(selected, Some(pdfcraft_cos::Object::Array(vec![pdfcraft_cos::Object::Int(1)])));
|
||||
}
|
||||
|
||||
/// One 612×300 page with the content stream `body`. Object 4 is Helvetica; `resources` is what
|
||||
/// the page's /Resources holds.
|
||||
fn one_line_page(resources: &str, body: &str) -> Vec<u8> {
|
||||
@@ -4122,7 +4221,9 @@ fn an_optimize_job_reports_its_stages_and_can_be_cancelled() {
|
||||
})
|
||||
.unwrap();
|
||||
assert!(bytes.starts_with(b"%PDF-"));
|
||||
assert_eq!(stages.first(), Some(&OptimizeStage::Discarding));
|
||||
assert_eq!(stages.first(), Some(&OptimizeStage::Reading { done: 0, total: 2 }), "it says what it does first");
|
||||
assert!(!stages.contains(&OptimizeStage::Discarding), "nothing was chosen to discard: {stages:?}");
|
||||
assert!(stages.iter().any(|st| matches!(st, OptimizeStage::Images { .. })), "{stages:?}");
|
||||
assert_eq!(&stages[stages.len() - 3..], [OptimizeStage::CleaningUp, OptimizeStage::Merging, OptimizeStage::Writing]);
|
||||
let fractions: Vec<f32> = stages.iter().map(|st| st.fraction()).collect();
|
||||
assert!(fractions.windows(2).all(|w| w[0] <= w[1]), "the bar never goes back: {fractions:?}");
|
||||
@@ -4133,6 +4234,20 @@ fn an_optimize_job_reports_its_stages_and_can_be_cancelled() {
|
||||
"no images: no division by zero"
|
||||
);
|
||||
|
||||
// What the bar shows before anything is reported says nothing of user data either.
|
||||
assert_eq!(OptimizeStage::default(), OptimizeStage::Reading { done: 0, total: 0 });
|
||||
assert_eq!(OptimizeStage::default().fraction(), 0.0);
|
||||
assert!(OptimizeStage::Reading { done: 2, total: 4 }.fraction() > 0.0, "reading pages moves the bar");
|
||||
|
||||
// Discarding says so when something is. This document has no metadata, which only stops it after
|
||||
// the stage is reported.
|
||||
let mut with_discard = Vec::new();
|
||||
let _ = s.optimize_job(id, &settings, &[crate::Hidden::Metadata]).unwrap().run(|st| {
|
||||
with_discard.push(st);
|
||||
true
|
||||
});
|
||||
assert_eq!(with_discard.first(), Some(&OptimizeStage::Discarding));
|
||||
|
||||
// Cancelled at the merge: nothing is written, the open document is untouched.
|
||||
let before = s.get(id).unwrap().bytes.clone();
|
||||
let r = s.optimize_job(id, &settings, &[]).unwrap().run(|st| st != OptimizeStage::Merging);
|
||||
@@ -5234,6 +5349,7 @@ fn sign_prepared_with(
|
||||
v.set(b"Contents".to_vec(), Object::String(PdfString { bytes: vec![0; reserve], hex: true }));
|
||||
v.set(b"M".to_vec(), PdfString::literal(date.as_bytes().to_vec()));
|
||||
value(&mut v);
|
||||
let certifies = v.get(b"Reference").is_some();
|
||||
let sig = doc.add(Object::Dict(v));
|
||||
// The field by name, never by number: a full save (encryption, repairs) is
|
||||
// free to renumber objects, and a hardcoded reference would stamp the value
|
||||
@@ -5243,6 +5359,12 @@ fn sign_prepared_with(
|
||||
let fields = doc.resolve(&af).as_dict().expect("AcroForm dict").get(b"Fields").cloned().expect("Fields");
|
||||
let field = doc.resolve(&fields).as_array().expect("Fields array").iter().filter_map(|o| o.as_ref()).next().expect("signature field");
|
||||
doc.update_dict(field, |d| d.set(b"V".to_vec(), Object::Ref(sig))).unwrap();
|
||||
if certifies {
|
||||
// A certification is the signature the catalog's /Perms /DocMDP names (ISO 32000-2, 12.8.2.2).
|
||||
let mut perms = Dict::new();
|
||||
perms.set(b"DocMDP".to_vec(), Object::Ref(sig));
|
||||
doc.update_dict(root, |c| c.set(b"Perms".to_vec(), Object::Dict(perms))).unwrap();
|
||||
}
|
||||
let save = pdfcraft_cos::SaveOptions { object_streams: false, ..pdfcraft_cos::SaveOptions::default() };
|
||||
let mut out = pdfcraft_cos::write_incremental(doc, &save).unwrap();
|
||||
let mark = format!("0 {} {} {}", LAYERED_BR_MARK[0], LAYERED_BR_MARK[1], LAYERED_BR_MARK[2]);
|
||||
@@ -9089,6 +9211,46 @@ fn content_refresh_lists_match_the_storages_an_edit_touches() {
|
||||
assert_eq!(Session::content_refresh_lists(None), (true, true), "undo/redo re-read both");
|
||||
}
|
||||
|
||||
/// Recognized text is an invisible text layer on its page, so applying it refreshes like any
|
||||
/// other content edit, not by re-inspecting the whole document (#6310): on a 567-page file with
|
||||
/// 60,102 font resources one word took 2.4 s, the full refresh nearly all of it. The page tree,
|
||||
/// comments, fields, links and marks stay as they were; the words are on their page, the font
|
||||
/// list picks up the OCR font on `refresh_fonts`, undo and redo take the words out and back
|
||||
/// without a full refresh either, and a save keeps them.
|
||||
#[test]
|
||||
fn ocr_words_refresh_only_the_page_content_they_add() {
|
||||
use crate::ocr::{OcrPage, PlacedWord};
|
||||
let (mut s, id) = session_with(3);
|
||||
let words_on = |s: &Session, page: usize| s.get(id).unwrap().text_lines(page).iter().map(|l| l.text.trim().to_string()).collect::<Vec<_>>();
|
||||
let before = s.get(id).unwrap();
|
||||
let view = format!("{:?}", (&before.info.pages, &before.info.annotations, &before.info.fields, &before.links, before.marks()));
|
||||
let others = (words_on(&s, 0), words_on(&s, 2));
|
||||
assert!(!words_on(&s, 1).iter().any(|w| w.contains("HELLO")));
|
||||
take_full_refreshes();
|
||||
let word =
|
||||
PlacedWord { text: "HELLO".into(), origin: [40.0, 40.0], across: [60.0, 0.0], up: [0.0, 20.0], confidence: None, source: "ocrs".into() };
|
||||
assert_eq!(s.apply_ocr(id, &[OcrPage { page: 1, words: vec![word], already_on_page: 0, skipped: None, notes: Vec::new() }]).unwrap(), 1);
|
||||
assert_eq!(take_full_refreshes(), 0, "applying OCR words doesn't re-inspect the document");
|
||||
let after = s.get(id).unwrap();
|
||||
assert_eq!(format!("{:?}", (&after.info.pages, &after.info.annotations, &after.info.fields, &after.links, after.marks())), view);
|
||||
assert!(words_on(&s, 1).iter().any(|w| w == "HELLO"), "{:?}", words_on(&s, 1));
|
||||
assert_eq!((words_on(&s, 0), words_on(&s, 2)), others, "the other pages are untouched");
|
||||
s.refresh_fonts(id);
|
||||
let d = s.get(id).unwrap();
|
||||
let full = pdfcraft_render::inspect(d.bytes.clone(), None).unwrap();
|
||||
assert_eq!(format!("{:?}", d.info.fonts), format!("{:?}", full.fonts), "the font list is what a full inspection reads");
|
||||
assert_eq!(d.info.file_size, full.file_size);
|
||||
s.undo(id).unwrap();
|
||||
assert!(!words_on(&s, 1).iter().any(|w| w.contains("HELLO")), "undo takes the words out");
|
||||
s.redo(id).unwrap();
|
||||
assert!(words_on(&s, 1).iter().any(|w| w == "HELLO"), "redo puts them back");
|
||||
assert_eq!(take_full_refreshes(), 0, "undo and redo refresh the content alone too");
|
||||
let saved = s.save_bytes(id).unwrap();
|
||||
let mut reopened = Session::new();
|
||||
let rid = reopened.open("saved.pdf", None, saved, None).unwrap();
|
||||
assert!(reopened.get(rid).unwrap().text_lines(1).iter().any(|l| l.text.trim() == "HELLO"), "the save keeps the words");
|
||||
}
|
||||
|
||||
/// A content edit can add a font (Add text in Times); the narrow refresh leaves the font list
|
||||
/// as it was, and `refresh_fonts` reads it again before Properties ▸ Fonts or `doc_info` show it.
|
||||
#[test]
|
||||
|
||||
Reference in new issue
Block a user