PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge current main into PR4279 and retain unsigned delete-save policy
FredApps7165ff1ace0b
diff --cc crates/engine/src/session/editing.rsindex 000000000,7758dc7c8..55eec0095mode 000000,100644..100644--- a/crates/engine/src/session/editing.rs+++ b/crates/engine/src/session/editing.rs@@@ -1,0 -1,541 +1,555 @@@+ #[cfg(test)]+ use super::check_refresh_panic;+ use super::{+ Arc, DocId, Document, Edit, EditCtx, EditError, Label, MAX_UNDO, ObjectKind, OnceLock, RenderPool, SaveOptions, Scope, Session,+ XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, check_permission, comment_list, display_bytes, display_config, guard, info_fields, inspect, js, keys_after,+ note_warnings, render_threads, run_edit, scan_colours, scope_of, shown_under_redactions, signatures_of, sync_xfa_state, undrawn_notices,+ uses_scripts, write_incremental, xfa, xfa_sync_datasets,+ };+ use crate::{EditNotice, MarkKind};+++/// Whether the edit, or any edit inside a batch, deletes pages.++fn deletes_pages(edit: &Edit) -> bool {++ match edit {++ Edit::DeletePages { .. } => true,++ Edit::Batch { edits, .. } => edits.iter().any(deletes_pages),++ _ => false,++ }++}+++ impl Session {+ /// Apply an edit. On success the previous state is undoable and the view data is refreshed.+ pub fn apply(&mut self, id: DocId, edit: Edit) -> Result<(), EditError> {+ let now = self.now();+ let today = self.today();+ let js_off = self.js_off;+ let xfa_time_scale = self.xfa_time_scale.unwrap_or(1);+ let doc = self.doc_mut(id)?;+ doc.edit_notices.clear();+ let name = doc.name.clone();+ let is_xfa = doc.info.xfa.is_some();+ let mut scope = scope_of(&edit);+ let mut cx = EditCtx::new(now, doc.generation ^ (id.0 << 48));+ if !js_off {+ cx.xfa = doc.xfa_template.clone();+ }+ cx.xfa_time_scale = xfa_time_scale;+ cx.pages = doc.info.pages.len();+ cx.today = today;+ let reason = doc.read_only_reason.clone().unwrap_or_default();+ let signed = doc.is_signed();+ let editor = doc.editor.as_mut().ok_or(EditError::ReadOnly(reason))?;+ if let Some(p) = editor.cos.permissions() {+ check_permission(&edit, &p)?;+ }+ // Rewriting an OCR word (invisible text over a scan) also hides the scanned word: cover it+ // in the paper's colour and draw the new text in the ink's.+ let edit = match edit {+ Edit::EditTextBlock { page, block, text, mut style } => {+ // Only invisible text is sampled; the blocks are usually cached from opening it.+ if style.cover.is_none()+ && let Some(info) = doc.info.pages.get(page)+ && let Some(b) = editor.text_blocks(page).ok().and_then(|b| b.get(block).filter(|b| b.invisible).cloned())+ && let Some((paper, ink)) = guard(|| scan_colours::sample(&editor.cos, info, page, &b)).ok().flatten()+ {+ style.cover = Some(paper);+ style.color = style.color.or(Some(ink));+ }+ Edit::EditTextBlock { page, block, text, style }+ }+ other => other,+ };+ // Nothing to bake: leave undo history and the dirty flag alone.+ if matches!(&edit, Edit::FlattenFillSign) && !pdfcraft_annot::has_visible_fill_sign(&editor.cos) {+ return Ok(());+ }+ let mut next = editor.cos.clone();+ if !js_off && uses_scripts(&edit) {+ cx.js = Some(js::JsRunner::new(&next, &name));+ }+ cx.renamed_fields.clear();+ cx.redaction_overlays.clear();+ // `next` is a copy: if the edit fails or crashes, the document is unchanged.+ guard(|| run_edit(&mut next, &edit, &mut cx))+ .unwrap_or_else(|m| Err(EditError::Invalid(format!("{} failed unexpectedly ({m}); the document was not changed", edit.label()))))?;+ // Redaction removed what its own interpreter places under the marks. The marks were drawn+ // over the page as the renderer shows it, so the renderer has the last word.+ if let Edit::ApplyRedactions { pages } = &edit {+ let marks: Vec<pdfcraft_redact::Mark> =+ pdfcraft_redact::marks(&editor.cos).into_iter().filter(|m| pages.as_ref().is_none_or(|p| p.contains(&m.page))).collect();+ guard(|| shown_under_redactions(&next, &marks, &cx.redaction_overlays, &doc.info.pages, doc.password.as_deref()))+ .unwrap_or_else(|m| Err(EditError::Invalid(format!("{} failed unexpectedly ({m}); the document was not changed", edit.label()))))?;+ }+ // Renamed fields are said, not slipped in: a repair-log note (with the caveat that+ // scripts were left alone) and a count in the undo step's label.+ let renamed_note = |renamed: &[(String, String)]| {+ (!renamed.is_empty()).then(|| {+ let shown: Vec<String> = renamed.iter().take(5).map(|(old, new)| format!("{old} → {new}")).collect();+ let more = renamed.len().saturating_sub(shown.len());+ let more = if more > 0 { format!(", and {more} more") } else { String::new() };+ format!(+ "inserted pages renamed {} form field{} to keep their names separate ({}{more}); scripts that refer to the old names were not rewritten",+ renamed.len(),+ if renamed.len() == 1 { "" } else { "s" },+ shown.join(", ")+ )+ })+ };+ if let Some(note) = renamed_note(&cx.renamed_fields) {+ next.note_repair(note);+ }+ // Only Insert from File renames fields; its label says so in a wording the interface+ // translates (the count lives in the repair note).+ let label = match (&edit, cx.renamed_fields.len()) {+ (_, 0) => edit.label(),+ (Edit::InsertPagesFrom { name, .. }, n) => Label::with(+ if n == 1 { "Insert pages from {name} — 1 field renamed" } else { "Insert pages from {name} — fields renamed" },+ name.as_str(),+ ),+ _ => edit.label(),+ };+ // An XFA form's scripts answer the change: exit and validate scripts of the field, then+ // every calculation (and a reset recalculates). They read the data, so it is brought up+ // to date first.+ if let Some(tpl) = cx.xfa.clone() {+ if is_xfa && matches!(scope_of(&edit), Scope::Form | Scope::Full | Scope::Content) {+ let datasets = &mut cx.xfa_datasets;+ let notes = guard(|| xfa_sync_datasets(&mut next, Some(&tpl), datasets))+ .unwrap_or_else(|m| Err(format!("writing the XFA data failed unexpectedly ({m})")))+ .map_err(EditError::Write)?;+ cx.xfa_out.errors.extend(notes);+ }+ fn collect(e: &Edit, changed: &mut Vec<String>, reset: &mut bool) {+ match e {+ Edit::SetFieldValue { name, .. } => changed.push(name.clone()),+ Edit::ResetForm { .. } => *reset = true,+ Edit::Batch { edits, .. } => edits.iter().for_each(|e| collect(e, changed, reset)),+ _ => {}+ }+ }+ let mut changed: Vec<String> = Vec::new();+ let mut reset = false;+ collect(&edit, &mut changed, &mut reset);+ if !changed.is_empty() || reset {+ let mut run = xfa::XfaRun {+ page_count: cx.pages,+ out: &mut cx.xfa_out,+ datasets: cx.xfa_datasets,+ ran_away: false,+ time_scale: cx.xfa_time_scale,+ };+ // Every changed field's scripts, then the calculations once (after a reset,+ // only those).+ let ran = guard(|| xfa::on_changes(&mut next, &tpl, &changed, &mut run))+ .unwrap_or_else(|m| Err(format!("the form's scripts failed unexpectedly ({m})")));+ cx.xfa_datasets = run.datasets;+ cx.xfa_ran_away |= run.ran_away;+ if let Err(e) = ran {+ cx.xfa_out.errors.push(e);+ }+ }+ }+ // XFA forms keep their values in the datasets packet too, for Adobe's viewers.+ let mut xfa_notes = Vec::new();+ if is_xfa && matches!(scope_of(&edit), Scope::Form | Scope::Full | Scope::Content) {+ let (tpl, datasets) = (cx.xfa.as_deref(), &mut cx.xfa_datasets);+ xfa_notes = guard(|| xfa_sync_datasets(&mut next, tpl, datasets))+ .unwrap_or_else(|m| Err(format!("writing the XFA data failed unexpectedly ({m})")))+ .map_err(EditError::Write)?;+ // Rebuilding from stale data would discard accepted widget values.+ if xfa_notes.is_empty() {+ let reflow = guard(|| xfa::relayout_changed_text(&mut next, tpl, &doc.form))+ .unwrap_or_else(|m| Err(format!("laying out the XFA text failed unexpectedly ({m})")))+ .map_err(EditError::Write)?;+ if let Some(warnings) = reflow {+ xfa_notes.extend(warnings);+ // Layout replaces pages and widgets, even if the page count is unchanged.+ // Undo/redo must rebuild these too instead of refreshing only field values.+ scope = Scope::Full;+ }+ }+ }+ // Signed documents are only ever saved incrementally: an edit that needs a full rewrite+ // (applying redactions, changing security, sanitizing) would invalidate the signatures.+ // So does any edit to a file rebuilt from object headers: it has no chain to append to.++ // Deleted pages remain in earlier incremental revisions (#3407), so rewrite++ // unsigned files in full. Signed files must retain their signed bytes.++ if !signed && deletes_pages(&edit) {++ next.require_full_save();++ }+ let rewrites = |c: &pdfcraft_cos::Document| c.full_save_required() || c.encryption_changed();+ if signed && ((rewrites(&next) && !rewrites(&editor.cos)) || (next.is_modified() && next.revisions().is_empty())) {+ return Err(EditError::SignedRewrite(edit.label().to_string()));+ }+ let notices = edit_notices(&edit, &editor.cos, &next);+ let previous = std::mem::replace(&mut editor.cos, next);+ let keys = keys_after(&edit).unwrap_or_else(|| editor.keys.clone());+ let previous_keys = std::mem::replace(&mut editor.keys, keys);+ editor.undo.push((label, previous, previous_keys, scope));+ if editor.undo.len() > MAX_UNDO {+ editor.undo.remove(0);+ }+ editor.redo.clear();+ Self::adopt_keys(doc);+ let refreshed = guard(|| if scope == Scope::Content { Self::refresh_content(doc, Some(&edit)) } else { Self::refresh_scoped(doc, scope) })+ .unwrap_or_else(|m| Err(EditError::Reopen(m)));+ if let Err(e) = refreshed {+ // Roll back: the edit produced something we cannot display.+ if let Some(ed) = doc.editor.as_mut()+ && let Some((_, prev, keys, _)) = ed.undo.pop()+ {+ ed.cos = prev;+ ed.keys = keys;+ }+ Self::adopt_keys(doc);+ if !matches!(guard(|| Self::refresh(doc)), Ok(Ok(()))) {+ Self::show_released(doc);+ }+ return Err(e);+ }+ doc.dirty = true;+ doc.generation += 1;+ doc.edit_notices = notices;+ if !cx.xfa_removed.is_empty() {+ let removed: Vec<String> = cx.xfa_removed.iter().map(|n| format!("{XFA_REMOVED_PREFIX}{n}")).collect();+ doc.xfa_warnings.retain(|w| w.starts_with(XFA_REMOVED_PREFIX));+ note_warnings(&mut doc.xfa_warnings, &removed);+ note_warnings(&mut doc.info.warnings, &removed);+ }+ note_warnings(&mut doc.xfa_warnings, &xfa_notes);+ let notes = doc.xfa_warnings.clone();+ note_warnings(&mut doc.info.warnings, ¬es);+ if let Some(js) = cx.js {+ doc.js_output.append(js.output);+ }+ doc.js_output.append(cx.xfa_out);+ if cx.xfa_ran_away {+ doc.xfa_template = None;+ doc.xfa_scripts_off = true;+ doc.js_output.errors.push(XFA_SCRIPTS_OFF.into());+ }+ Ok(())+ }++ pub fn undo(&mut self, id: DocId) -> Result<Label, EditError> {+ let doc = self.doc_mut(id)?;+ let editor = doc.editor.as_mut().ok_or(EditError::NothingToUndo)?;+ let (label, prev, keys, scope) = editor.undo.pop().ok_or(EditError::NothingToUndo)?;+ let current = std::mem::replace(&mut editor.cos, prev);+ let current_keys = std::mem::replace(&mut editor.keys, keys);+ editor.redo.push((label.clone(), current, current_keys, scope));+ Self::adopt_keys(doc);+ let refreshed = guard(|| Self::refresh_scoped(doc, scope)).unwrap_or_else(|m| Err(EditError::Reopen(m)));+ if let Err(e) = refreshed {+ if let Some(ed) = doc.editor.as_mut()+ && let Some((label, current, current_keys, scope)) = ed.redo.pop()+ {+ let prev = std::mem::replace(&mut ed.cos, current);+ let keys = std::mem::replace(&mut ed.keys, current_keys);+ ed.undo.push((label, prev, keys, scope));+ }+ Self::adopt_keys(doc);+ if !matches!(guard(|| Self::refresh(doc)), Ok(Ok(()))) {+ Self::show_released(doc);+ }+ return Err(e);+ }+ doc.edit_notices.clear();+ Self::sync_dirty(doc);+ doc.generation += 1;+ Ok(label)+ }++ pub fn redo(&mut self, id: DocId) -> Result<Label, EditError> {+ let doc = self.doc_mut(id)?;+ let editor = doc.editor.as_mut().ok_or(EditError::NothingToRedo)?;+ let (label, next, keys, scope) = editor.redo.pop().ok_or(EditError::NothingToRedo)?;+ let current = std::mem::replace(&mut editor.cos, next);+ let current_keys = std::mem::replace(&mut editor.keys, keys);+ editor.undo.push((label.clone(), current, current_keys, scope));+ Self::adopt_keys(doc);+ let refreshed = guard(|| Self::refresh_scoped(doc, scope)).unwrap_or_else(|m| Err(EditError::Reopen(m)));+ if let Err(e) = refreshed {+ if let Some(ed) = doc.editor.as_mut()+ && let Some((label, current, current_keys, scope)) = ed.undo.pop()+ {+ let next = std::mem::replace(&mut ed.cos, current);+ let keys = std::mem::replace(&mut ed.keys, current_keys);+ ed.redo.push((label, next, keys, scope));+ }+ Self::adopt_keys(doc);+ if !matches!(guard(|| Self::refresh(doc)), Ok(Ok(()))) {+ Self::show_released(doc);+ }+ return Err(e);+ }+ doc.edit_notices.clear();+ Self::sync_dirty(doc);+ doc.generation += 1;+ Ok(label)+ }++ /// Unsaved when the working graph is not the last opened or saved file. Undo back to that+ /// file is clean; undo past a later save is not, because the restored snapshot's own base+ /// is an earlier revision.+ pub(super) fn sync_dirty(doc: &mut Document) {+ doc.dirty = doc.editor.as_ref().is_some_and(|e| e.unsaved_file || e.cos.is_modified() || !Arc::ptr_eq(e.cos.bytes(), &e.saved));+ }++ /// Use the current state's password for viewing (protection edits change it).+ pub(super) fn adopt_keys(doc: &mut Document) {+ if let Some(e) = doc.editor.as_ref() {+ doc.password = e.keys.render.clone();+ doc.config.password = e.keys.render.as_deref().map(Arc::from);+ }+ }++ /// Rebuild the working bytes and the view data that `scope` may have changed. Metadata edits+ /// keep the renderer; other scopes also replace it.+ /// Comment and form edits skip the full re-inspection (seconds on very large files): the+ /// comment list and field values are re-read from the object graph instead.+ fn refresh_scoped(doc: &mut Document, scope: Scope) -> Result<(), EditError> {+ if scope == Scope::Full || doc.info.encrypted != doc.editor.as_ref().is_some_and(|e| e.cos.output_handler().is_some()) {+ return Self::refresh(doc);+ }+ if scope == Scope::Content {+ return Self::refresh_content(doc, None);+ }+ if scope == Scope::Links {+ return Self::refresh_links(doc);+ }+ // Metadata edits keep the renderer, which holds the working file anyway.+ if scope != Scope::Metadata {+ Self::release_working(doc);+ }+ let Some(editor) = doc.editor.as_mut() else { return Ok(()) };+ // Comment edits, and form edits (a script may change annotation properties), may change+ // annotation dictionaries, invalidating cached appearances.+ if matches!(scope, Scope::Comments | Scope::Form) {+ editor.appearances.clear();+ }+ let bytes = if editor.cos.is_modified() {+ Arc::new(write_incremental(&editor.cos, &SaveOptions::default()).map_err(|e| EditError::Write(e.to_string()))?)+ } else {+ editor.cos.bytes().clone()+ };+ if scope == Scope::Metadata {+ for (field, value) in info_fields(&mut doc.info, &editor.cos) {+ *field = value;+ }+ doc.info.custom = pdfcraft_organize::custom_info(&editor.cos);+ doc.info.file_size = bytes.len();+ #[cfg(test)]+ check_refresh_panic();+ if !doc.signatures.is_empty() {+ let signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache);+ doc.signatures = Arc::new(signatures);+ }+ doc.bytes = bytes;+ return Ok(());+ }+ let mut form = pdfcraft_forms::fields(&editor.cos);+ xfa::mark_script_buttons(&editor.cos, &mut form);+ let form = Arc::new(form);+ match scope {+ Scope::Metadata => return Ok(()),+ Scope::Comments => {+ doc.info.annotations = comment_list(&editor.cos);+ // Link indexes are positions in /Annots, so comment insertion/deletion can move them.+ doc.links = OnceLock::new();+ }+ Scope::Form => {+ // PERF: keystroke path, index once. A linear find per field is O(F^2);+ // forms reach 10k fields.+ let mut by_name = std::collections::HashMap::with_capacity(form.len());+ for x in form.iter() {+ // First match wins (do not simplify to collect: it keeps the last).+ by_name.entry(x.name.as_str()).or_insert(x);+ }+ for f in &mut doc.info.fields {+ if let Some(ff) = by_name.get(f.name.as_str()) {+ f.value = match ff.kind {+ pdfcraft_forms::FieldKind::CheckBox | pdfcraft_forms::FieldKind::Radio => {+ Some(ff.value.first().cloned().unwrap_or_else(|| "Off".into()))+ }+ _ if ff.value.is_empty() => None,+ _ => Some(ff.value.join(", ")),+ };+ }+ }+ }+ Scope::Links => return Self::refresh_links(doc),+ // Handled above; kept as a full refresh so the match stays total.+ Scope::Full => return Self::refresh(doc),+ // Handled above (content-only refresh); the arm keeps the match total.+ Scope::Content => return Self::refresh_content(doc, None),+ }+ doc.info.file_size = bytes.len();+ doc.form = form;+ let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) };+ doc.display = display_bytes(Some(editor), &bytes);+ doc.signatures = Arc::new(signatures);+ doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));+ doc.bytes = bytes;+ Ok(())+ }++ /// Which derived lists a content-only edit can change: added content (`None`, from+ /// undo/redo, re-reads both: always correct, rarely paid).+ pub(crate) fn content_refresh_lists(edit: Option<&Edit>) -> (bool, bool) {+ if let Some(Edit::Batch { edits, .. }) = edit {+ // A batch of content edits (from a script, say) changes what its parts change.+ return edits.iter().fold((false, false), |(added, marks), part| {+ let (a, m) = Self::content_refresh_lists(Some(part));+ (added || a, marks || m)+ });+ }+ let touches_added = edit.is_none_or(|e| {+ matches!(+ e,+ Edit::AddText { .. }+ | Edit::AddImage { .. }+ | Edit::UpdateContent { .. }+ | Edit::DeleteContent { .. }+ | Edit::ReplaceImage { .. }+ | Edit::PasteContent { .. }+ ) || matches!(e, Edit::MoveObjects { objects, .. } if objects.iter().any(|o| o.kind == ObjectKind::Added))+ });+ let touches_marks = edit.is_none_or(|e| {+ matches!(e, Edit::AddHeaderFooter { .. } | Edit::AddWatermark { .. } | Edit::AddBackground { .. } | Edit::RemoveMarks { .. })+ });+ (touches_added, touches_marks)+ }++ /// Rebuild working bytes, display bytes and renderer after a content-only edit: page+ /// content streams, resources and added content/marks. The page tree, annotations, form+ /// fields, links, outline and fonts are unchanged, so the full re-inspection (seconds on+ /// very large files) is skipped. `edit` selects which derived lists are re-read (`None`,+ /// from undo/redo, re-reads both: always correct, rarely paid). The cached display+ /// appearances are kept: content edits leave every annotation dictionary alone.+ fn refresh_content(doc: &mut Document, edit: Option<&Edit>) -> Result<(), EditError> {+ Self::release_working(doc);+ sync_xfa_state(doc);+ let Some(editor) = doc.editor.as_mut() else { return Ok(()) };+ let bytes = if editor.cos.is_modified() {+ Arc::new(write_incremental(&editor.cos, &SaveOptions::default()).map_err(|e| EditError::Write(e.to_string()))?)+ } else {+ editor.cos.bytes().clone()+ };+ // The edit must still leave a file the viewer can open; anything else rolls back above.+ pdfcraft_render::check_pages(bytes.clone(), doc.password.as_deref(), doc.info.pages.len()).map_err(|e| EditError::Reopen(e.to_string()))?;+ let (touches_added, touches_marks) = Self::content_refresh_lists(edit);+ if touches_added || touches_marks {+ doc.marker_scan = OnceLock::new();+ }+ doc.info.file_size = bytes.len();+ let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) };+ doc.display = display_bytes(Some(editor), &bytes);+ doc.signatures = Arc::new(signatures);+ doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));+ doc.bytes = bytes;+ doc.fonts_stale = true;+ Ok(())+ }++ /// Let go of the working file before the next one is written (gap 13). The working file is+ /// the original plus one appended revision, so on a 1 GiB file keeping the old one (in the+ /// working bytes, the display bytes and the renderer) while writing the new one held three+ /// copies at once; this keeps two. Until the refresh finishes, the working and display bytes+ /// are the original's (already held by the editor, so free) and the renderer draws nothing.+ /// A failed edit rolls back and refreshes again, which replaces all three; where a refresh+ /// still fails, [`Self::show_released`] draws the original rather than nothing. Save writes+ /// from the editor, never from these.+ pub(crate) fn release_working(doc: &mut Document) {+ let Some(original) = doc.editor.as_ref().map(|e| e.cos.bytes().clone()) else { return };+ // Dropping the pool stops its workers; each lets go of the file when it exits.+ doc.renderer = RenderPool::new_inline(Arc::new(Vec::new()), doc.config.clone());+ doc.display = original.clone();+ doc.bytes = original;+ #[cfg(test)]+ check_refresh_panic();+ }++ /// After a refresh failed: draw the display bytes it left (the original, once released),+ /// so the page still shows a document.+ pub(super) fn show_released(doc: &mut Document) {+ doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));+ }++ /// Rebuild working bytes, inspection and renderer from the current edit state.+ pub(crate) fn refresh(doc: &mut Document) -> Result<(), EditError> {+ Self::refresh_with_indexes(doc, true, true)+ }++ /// Reinspect a link edit while preserving the page-content marker scan cache.+ fn refresh_links(doc: &mut Document) -> Result<(), EditError> {+ Self::refresh_with_indexes(doc, false, true)+ }++ fn refresh_with_indexes(doc: &mut Document, invalidate_markers: bool, invalidate_links: bool) -> Result<(), EditError> {+ // 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() {+ editor.appearances.clear();+ }+ Self::release_working(doc);+ sync_xfa_state(doc);+ let Some(editor) = doc.editor.as_mut() else { return Ok(()) };+ let bytes = if editor.cos.is_modified() {+ Arc::new(write_incremental(&editor.cos, &SaveOptions::default()).map_err(|e| EditError::Write(e.to_string()))?)+ } else {+ editor.cos.bytes().clone()+ };+ let info = inspect(bytes.clone(), doc.password.as_deref()).map_err(|e| EditError::Reopen(e.to_string()))?;+ // Keep the user's layer choices where the layers still exist.+ let mut info = info;+ for l in &mut info.layers {+ if let Some(old) = doc.info.layers.iter().find(|o| o.id == l.id) {+ l.visible = old.visible;+ }+ }+ note_warnings(&mut info.warnings, &doc.xfa_warnings);+ // As in `build_document`: the inspection reads only `/Info`, so fields stated only in XMP+ // are filled in again after every full refresh.+ for (field, value) in info_fields(&mut info, &editor.cos) {+ if field.is_none() {+ *field = value;+ }+ }+ doc.info = info;+ doc.fonts_stale = false;+ let mut form = pdfcraft_forms::fields(&editor.cos);+ xfa::mark_script_buttons(&editor.cos, &mut form);+ doc.form = Arc::new(form);+ if invalidate_markers {+ doc.marker_scan = OnceLock::new();+ }+ if invalidate_links {+ doc.links = OnceLock::new();+ }+ let signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache);+ doc.display = display_bytes(Some(editor), &bytes);+ doc.signatures = Arc::new(signatures);+ doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));+ doc.bytes = bytes;+ Ok(())+ }+ }++ /// What `edit`, taking `prev` to `next`, wants said: never silent (AGENTS.md §4).+ fn edit_notices(edit: &Edit, prev: &pdfcraft_cos::Document, next: &pdfcraft_cos::Document) -> Vec<EditNotice> {+ // What it drew with `?` (a value or comment text its font can't draw, stored as typed).+ let mut notices: Vec<EditNotice> = if matches!(scope_of(edit), Scope::Form | Scope::Comments | Scope::Full) {+ guard(|| undrawn_notices(prev, next)).unwrap_or_default().into_iter().map(EditNotice::Undrawn).collect()+ } else {+ Vec::new()+ };+ // Pages whose own white backdrop Remove background couldn't turn back on.+ if matches!(edit, Edit::RemoveMarks { kind: MarkKind::Background }) {+ let pages = guard(|| pdfcraft_edit::backdrops_left_off(next)).unwrap_or_default();+ if !pages.is_empty() {+ notices.push(EditNotice::BackdropsLeftOff { pages });+ }+ }+ notices+ }diff --cc crates/engine/src/tests.rsindex 624079ca4,333d0fd49..6fc0df2f2--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@@ -7498,3 -9117,295 +9118,354 @@@ fn a_page_truncated_for_forms_and_pictuassert!(pages[0].images.is_empty(), "the picture is past the budget");assert_eq!(truncated, [0]);}++ /// ISO 32000-2 Table 192, 12.7.5.2.3 and Table 228 (Comb): a check box, a push button, a comb+ /// field the file leaves to the viewer. The page as displayed and printed as an image shows the+ /// check box's caption symbol in its text colour, the button's grey face and the comb's cells in+ /// the border colour, and saving writes the file as it was.+ #[test]+ fn buttons_and_combs_left_to_the_viewer_are_displayed() {+ let pdf = b"%PDF-1.7\n\+ 1 0 obj << /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >> endobj\n\+ 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\+ 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 400 200] /Annots [6 0 R 7 0 R 8 0 R] >> endobj\n\+ 4 0 obj << /Fields [6 0 R 7 0 R 8 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> endobj\n\+ 5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> endobj\n\+ 6 0 obj << /Type /Annot /Subtype /Widget /FT /Btn /T (k) /V /Yes /AS /Yes /DA (/ZaDb 0 Tf 1 0 0 rg) /MK << /CA (8) /BC [0 0 0] >> /Rect [20 150 60 190] /F 4 /P 3 0 R >> endobj\n\+ 7 0 obj << /Type /Annot /Subtype /Widget /FT /Btn /Ff 65536 /T (o) /DA (/Helv 12 Tf 0 g) /MK << /CA (Press) /BG [0.8 0.8 0.8] /BC [0 0 0] >> /BS << /W 2 /S /B >> /Rect [100 150 220 190] /F 4 /P 3 0 R >> endobj\n\+ 8 0 obj << /Type /Annot /Subtype /Widget /FT /Tx /Ff 16777216 /MaxLen 4 /T (d) /V (AB) /DA (/Helv 12 Tf 0 g) /MK << /BC [0 0 1] >> /Rect [20 80 220 110] /F 4 /P 3 0 R >> endobj\n\+ trailer << /Root 1 0 R >>\n%%EOF"+ .to_vec();+ let render = |bytes: Arc<Vec<u8>>| {+ let mut r = pdfcraft_render::PageRenderer::new(bytes, pdfcraft_render::RenderConfig::default());+ r.render(pdfcraft_render::RenderRequest { page: 0, scale: 1.0, ..Default::default() })+ };+ // Pixels of the page (drawn at scale 1, 400 x 200) in user-space box x0..x1, y0..y1 that `keep`.+ let count = |page: &pdfcraft_render::RenderedPage, (x0, y0, x1, y1): (u32, u32, u32, u32), keep: &dyn Fn(&[u8; 4]) -> bool| {+ let (px, _) = page.rgba.as_chunks::<4>();+ (200 - y1..200 - y0)+ .flat_map(|y| (x0..x1).map(move |x| (x, y)))+ .filter(|&(x, y)| px.get((y * page.width + x) as usize).is_some_and(keep))+ .count()+ };+ let red = |p: &[u8; 4]| p[0] > 200 && p[1] < 80 && p[2] < 80;+ let grey = |p: &[u8; 4]| (180..=230).contains(&p[0]) && p[0] == p[1] && p[1] == p[2];+ // Bluish: a 1 pt line on a pixel edge is half blue on each side.+ let blue = |p: &[u8; 4]| p[2] > 200 && p[0] < 180 && p[1] < 180 && p[0] + 40 < p[2];+ let mut s = Session::new();+ let id = s.open("form.pdf", None, Arc::new(pdf), None).unwrap();+ let shown = render(s.get(id).unwrap().display.clone());+ assert!(count(&shown, (24, 154, 56, 186), &red) > 60, "the check box's red cross");+ assert!(count(&shown, (104, 154, 216, 186), &grey) > 1000, "the push button's grey face");+ // The comb's three inner lines at x = 70, 120 and 170, between its cells.+ for x in [70, 120, 170] {+ assert!(count(&shown, (x - 1, 84, x + 1, 106), &blue) >= 20, "a cell line at {x}");+ }+ assert_eq!(count(&shown, (95, 84, 97, 106), &blue), 0, "no line inside a cell");+ // Print as Image: the page as a picture, at 72 dpi so it is the size of the page here.+ let raster = pdfcraft_print::Raster { dpi: 72.0, grayscale: false };+ let pictures = crate::print_raster::rasterize(s.get(id).unwrap(), &[0], &raster, pdfcraft_print::Content::Document).unwrap();+ let printed = render(Arc::new(pictures));+ assert!(count(&printed, (24, 154, 56, 186), &red) > 60, "the check box prints");+ assert!(count(&printed, (104, 154, 216, 186), &grey) > 1000, "and the push button");+ // The file is saved as it was: no widget has an appearance.+ let saved = pdfcraft_cos::Document::open(s.save_bytes(id).unwrap()).unwrap();+ for f in pdfcraft_forms::fields(&saved) {+ assert!(saved.get(f.widgets[0].obj).as_dict().is_some_and(|d| !d.contains(b"AP")), "{} has no appearance", f.name);+ }+ }++ /// ISO 32000-2 Tables 166 and 183, drawn on the page: a square without an appearance whose+ /// `/Border [0 0 3 [6 3]]` names its width before a dash array is stroked 3 pt wide and dashed+ /// (it was 1 pt and solid), and a caret with `/Sy /P` shows a ¶ to its right.+ #[test]+ fn legacy_border_dashes_and_the_caret_paragraph_symbol_are_drawn() {+ let original = Arc::new(pdf_with_annots(&[+ b"<< /Type /Annot /Subtype /Square /Rect [20 180 120 280] /Border [0 0 3 [6 3]] /C [1 0 0] >>",+ b"<< /Type /Annot /Subtype /Caret /Rect [20 20 80 80] /Sy /P /C [0 0 1] >>",+ ]));+ let mut s = Session::new().with_clock(|| 1_700_000_000);+ let id = s.open("noap.pdf", None, original, None).expect("opens");+ let p = shown(&s, id, 0);+ let px = |x: u32, y: u32| p.rgba[((y * p.width + x) * 4) as usize..][..4].to_vec();+ // y down: the bottom edge's stroke is centred 1.5 pt inside /Rect, on row 118.+ let row: Vec<Vec<u8>> = (24..116).map(|x| px(x, 118)).collect();+ let red = row.iter().filter(|c| c[0] > 200 && c[1] < 80).count();+ let white = row.iter().filter(|c| c[1] > 200).count();+ assert!(red > 40 && white > 15, "3 pt and dashed: {red} red, {white} white");+ // The ¶ sits in the right part of the caret's /Rect, where the caret no longer reaches.+ let blue = (250..270).flat_map(|y| (68..80).map(move |x| (x, y))).filter(|&(x, y)| {+ let c = px(x, y);+ c[2] > 150 && c[0] < 100+ });+ assert!(blue.count() > 20, "the pilcrow is drawn beside the caret");+ }++ /// Import comments with a PDF chosen copies that PDF's comments in one undoable step, and refuses+ /// a PDF that has none.+ #[test]+ fn importing_a_pdf_copies_its_comments() {+ let mut s = Session::new();+ let id = s.open("doc.pdf", None, Arc::new(pdf_with_annots(&[])), None).unwrap();+ let review = pdf_with_annots(&[+ b"<< /Type /Annot /Subtype /Text /Rect [10 10 30 30] /Contents (from the review) /P 3 0 R >>",+ b"<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /A << /S /URI /URI (https://example.com/) >> /P 3 0 R >>",+ ]);+ s.apply(id, Edit::ImportData { name: "review.pdf".into(), bytes: Arc::new(review.clone()) }).unwrap();+ let contents = |s: &Session| s.get(id).unwrap().info.annotations.iter().map(|a| a.contents.clone()).collect::<Vec<_>>();+ assert_eq!(contents(&s), [Some("from the review".to_string())], "the comment, not the link");+ assert_eq!(s.undo(id).unwrap().to_string(), "Import review.pdf");+ assert!(s.get(id).unwrap().info.annotations.is_empty());++ // Bytes before the header, as the reader allows them.+ let prefixed = [b"\r\n \n".as_slice(), &review].concat();+ s.apply(id, Edit::ImportData { name: "prefixed.pdf".into(), bytes: Arc::new(prefixed) }).unwrap();+ assert_eq!(contents(&s), [Some("from the review".to_string())]);+ s.undo(id).unwrap();++ let links = pdf_with_annots(&[b"<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /P 3 0 R >>"]);+ let err = s.apply(id, Edit::ImportData { name: "links.pdf".into(), bytes: Arc::new(links.clone()) }).unwrap_err();+ assert_eq!(err.to_string(), pdfcraft_xfdf::DataError::NothingImported.to_string());+ // A PDF that needs a password is refused with that reason, with or without bytes before its header.+ let mut locked = pdfcraft_cos::Document::open(Arc::new(review)).unwrap();+ locked+ .set_encryption(&pdfcraft_cos::NewEncryption {+ algorithm: pdfcraft_cos::Algorithm::Aes256,+ user_password: "u",+ owner_password: "o",+ permissions: 0,+ encrypt_metadata: true,+ seed: [1; 32],+ })+ .unwrap();+ let locked = pdfcraft_cos::write_full(&locked, &Default::default()).unwrap();+ for bytes in [locked.clone(), [b"\n".as_slice(), &locked].concat()] {+ let err = s.apply(id, Edit::ImportData { name: "locked.pdf".into(), bytes: Arc::new(bytes) }).unwrap_err();+ assert_eq!(err.to_string(), EditError::Source("locked.pdf: it is password-protected".into()).to_string());+ }++ // An XFDF file that mentions the PDF header is still read as XFDF.+ let xfdf = r#"<?xml version="1.0"?><!-- exported from a file starting %PDF-1.7 --><xfdf xmlns="http://ns.adobe.com/xfdf/"><annots><text page="0" name="n1" rect="10,10,30,30"><contents>from the data file</contents></text></annots></xfdf>"#;+ s.apply(id, Edit::ImportData { name: "notes.xfdf".into(), bytes: Arc::new(xfdf.as_bytes().to_vec()) }).unwrap();+ assert_eq!(contents(&s), [Some("from the data file".to_string())]);+ }++ /// An XFA form imports the comments of a PDF with binary bytes before its header, instead of+ /// refusing it as a data file in an unknown encoding.+ #[test]+ fn an_xfa_form_imports_comments_from_a_pdf_with_binary_bytes_before_its_header() {+ let data = "<form><page1><country>JP</country></page1></form>";+ let bytes = Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::fields_template(data)));+ let mut s = Session::new().with_clock(|| 1_700_000_000);+ let id = s.open("fields.pdf", None, bytes, None).expect("opens");+ let review = pdf_with_annots(&[b"<< /Type /Annot /Subtype /Text /Rect [10 10 30 30] /Contents (from the review) /P 3 0 R >>"]);+ let prefixed = [b"\xC0\xC1\xF5\n".as_slice(), &review].concat();+ s.apply(id, Edit::ImportData { name: "prefixed.pdf".into(), bytes: Arc::new(prefixed) }).unwrap();+ let contents: Vec<_> = s.get(id).unwrap().info.annotations.iter().map(|a| a.contents.clone()).collect();+ assert!(contents.contains(&Some("from the review".to_string())), "{contents:?}");+ }++ /// A one-page 200 × 300 document whose page lists `annots` (objects 4, 5, …).+ fn pdf_with_annots(annots: &[&[u8]]) -> Vec<u8> {+ let list: String = (0..annots.len()).map(|i| format!("{} 0 R ", i + 4)).collect();+ let page = format!("<< /Type /Page /Parent 2 0 R /Annots [{list}] >>");+ let mut objs: Vec<&[u8]> =+ vec![b"<< /Type /Catalog /Pages 2 0 R >>", b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>", page.as_bytes()];+ objs.extend_from_slice(annots);+ let mut bytes = b"%PDF-1.7\n".to_vec();+ let mut offsets = Vec::new();+ for (i, o) in objs.iter().enumerate() {+ offsets.push(bytes.len());+ bytes.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());+ bytes.extend_from_slice(o);+ bytes.extend_from_slice(b"\nendobj\n");+ }+ let xref = bytes.len();+ bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());+ for o in offsets {+ bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());+ }+ bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());+ bytes+ }++ /// ISO 32000-2 Table 224 (`/NeedAppearances`) and Table 192 (`/MK /CA`): a form that leaves its+ /// appearances to the viewer shows its check boxes and radio buttons drawn from `/MK`, over the+ /// filled squares the file carries: a checked box its check mark (ZapfDingbats `4`), an unchecked+ /// one its empty border, a radio button its dot (`l`), on screen and printed as an image. Without+ /// `/NeedAppearances` the file's own squares show. Saving writes the file as it was.+ #[test]+ fn need_appearances_buttons_are_displayed_from_their_captions() {+ let pdf = |need: bool| {+ let flag = if need { "/NeedAppearances true " } else { "" };+ format!(+ "%PDF-1.7\n\+ 1 0 obj << /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >> endobj\n\+ 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\+ 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 400 200] /Annots [6 0 R 7 0 R 8 0 R] >> endobj\n\+ 4 0 obj << /Fields [6 0 R 7 0 R 8 0 R] {flag}/DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> endobj\n\+ 5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> endobj\n\+ 6 0 obj << /Type /Annot /Subtype /Widget /FT /Btn /T (on) /V /Yes /AS /Yes /DA (/Helv 0 Tf 0 g) /MK << /BC [0 0 0] /CA (4) >> /Rect [20 100 60 140] /F 4 /P 3 0 R /AP << /N << /Yes 9 0 R /Off 9 0 R >> >> >> endobj\n\+ 7 0 obj << /Type /Annot /Subtype /Widget /FT /Btn /T (off) /V /Off /AS /Off /DA (/Helv 0 Tf 0 g) /MK << /BC [0 0 0] /CA (4) >> /Rect [100 100 140 140] /F 4 /P 3 0 R /AP << /N << /Yes 9 0 R /Off 9 0 R >> >> >> endobj\n\+ 8 0 obj << /Type /Annot /Subtype /Widget /FT /Btn /Ff 32768 /T (radio) /V /B /AS /B /DA (/Helv 0 Tf 0 g) /MK << /BC [0 0 0] /CA (l) >> /Rect [180 100 220 140] /F 4 /P 3 0 R /AP << /N << /B 9 0 R /Off 9 0 R >> >> >> endobj\n\+ 9 0 obj << /Type /XObject /Subtype /Form /BBox [0 0 40 40] /Length 18 >> stream\n0 g 4 4 32 32 re f\nendstream endobj\n\+ trailer << /Root 1 0 R >>\n%%EOF"+ )+ .into_bytes()+ };+ let render = |bytes: Arc<Vec<u8>>| {+ let mut r = pdfcraft_render::PageRenderer::new(bytes, pdfcraft_render::RenderConfig::default());+ r.render(pdfcraft_render::RenderRequest { page: 0, scale: 1.0, ..Default::default() })+ };+ // Dark pixels of the page (drawn at scale 1, 400 x 200) in the user-space box x0..x1, y0..y1.+ let ink = |page: &pdfcraft_render::RenderedPage, (x0, y0, x1, y1): (u32, u32, u32, u32)| {+ let (px, _) = page.rgba.as_chunks::<4>();+ (200 - y1..200 - y0)+ .flat_map(|y| (x0..x1).map(move |x| (x, y)))+ .filter(|&(x, y)| px.get((y * page.width + x) as usize).is_some_and(|p| p[0] < 128 && p[1] < 128 && p[2] < 128))+ .count()+ };+ // In a widget whose lower-left corner is (x, y): its whole inside, the top-left of its inside+ // (where a check mark leaves the box empty), and the lower-left corner (outside a dot).+ let inside = |x: u32, y: u32| (x + 6, y + 6, x + 34, y + 34);+ let top_left = |x: u32, y: u32| (x + 6, y + 26, x + 14, y + 34);+ let corner = |x: u32, y: u32| (x + 5, y + 5, x + 9, y + 9);+ let mut s = Session::new();+ let id = s.open("form.pdf", None, Arc::new(pdf(true)), None).unwrap();+ let shown = render(s.get(id).unwrap().display.clone());+ let raster = pdfcraft_print::Raster { dpi: 72.0, grayscale: false };+ let pictures = crate::print_raster::rasterize(s.get(id).unwrap(), &[0], &raster, pdfcraft_print::Content::Document).unwrap();+ let printed = render(Arc::new(pictures));+ for (page, how) in [(&shown, "shown"), (&printed, "printed")] {+ let (check, check_corner) = (ink(page, inside(20, 100)), ink(page, top_left(20, 100)));+ assert!(check > 100 && check < 600, "{how}: a check mark, not the 28 x 28 square: {check}");+ assert_eq!(check_corner, 0, "{how}: the check mark leaves the top left empty");+ assert_eq!(ink(page, inside(100, 100)), 0, "{how}: the unchecked box is empty");+ assert!(ink(page, (100, 100, 140, 102)) > 30, "{how}: and keeps its border");+ let dot = ink(page, (188, 108, 212, 132));+ assert!(dot > 300 && ink(page, corner(180, 100)) == 0, "{how}: the radio button's dot: {dot}");+ }+ let saved = s.save_bytes(id).unwrap();+ assert!(saved.windows(18).any(|w| w == b"0 g 4 4 32 32 re f"), "the file keeps its own appearances");++ // Without /NeedAppearances the file's filled squares are shown.+ let id = s.open("plain.pdf", None, Arc::new(pdf(false)), None).unwrap();+ let shown = render(s.get(id).unwrap().display.clone());+ for x in [20, 100, 180] {+ assert!(ink(&shown, inside(x, 100)) > 700, "the file's square at {x}");+ }+ }++ #[test]+ fn repeated_backdrop_artwork_survives_background_undo_redo_and_both_save_modes() {+ let white = "1 g";+ let rectangle = "0 0 100 100 re f";+ let artwork = "q 0 g 0.25 0 0 0.25 20 20 cm";+ let raw = format!(+ "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\+ 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\+ 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents [4 0 R 5 0 R 6 0 R 5 0 R 7 0 R] >> endobj\n\+ 4 0 obj << /Length {} >> stream\n{white}\nendstream endobj\n\+ 5 0 obj << /Length {} >> stream\n{rectangle}\nendstream endobj\n\+ 6 0 obj << /Length {} >> stream\n{artwork}\nendstream endobj\n\+ 7 0 obj << /Length 1 >> stream\nQ\nendstream endobj\ntrailer << /Root 1 0 R >>\n%%EOF",+ white.len(),+ rectangle.len(),+ artwork.len()+ );+ // Start with a conventional xref, so the first save can exercise incremental output.+ let source = pdfcraft_cos::Document::open(Arc::new(raw.into_bytes())).unwrap();+ let bytes = pdfcraft_cos::write_full(&source, &pdfcraft_cos::SaveOptions::default()).unwrap();+ let mut s = Session::new();+ let id = s.open("shared-backdrop.pdf", None, Arc::new(bytes), None).unwrap();+ let black = |s: &Session, id| {+ let doc = s.get(id).unwrap();+ let mut renderer = pdfcraft_render::PageRenderer::new(doc.bytes.clone(), doc.config.clone());+ let out = renderer.render(pdfcraft_render::RenderRequest { page: 0, scale: 1.0, ..Default::default() });+ assert!(out.error.is_none(), "{:?}", out.error);+ assert_eq!((out.width, out.height), (100, 100));+ // PDF point (30, 30), inside the later black square, in top-down raster coordinates.+ let i = ((70 * out.width + 30) * 4) as usize;+ let rgba = &out.rgba[i..i + 4];+ assert!(rgba[0] < 20 && rgba[1] < 20 && rgba[2] < 20, "later artwork survives: {rgba:?}");+ };+ black(&s, id);+ s.apply(+ id,+ Edit::AddBackground { pages: vec![0], settings: Background { color: [1.0, 0.0, 0.0], ..Background::default() }, replace: false, file: None },+ )+ .unwrap();+ black(&s, id);+ s.undo(id).unwrap();+ black(&s, id);+ s.redo(id).unwrap();+ black(&s, id);+ let saved = s.save_bytes(id).unwrap();+ let reopened = s.open("incremental.pdf", None, saved.clone(), None).unwrap();+ black(&s, reopened);+ let doc = pdfcraft_cos::Document::open(saved).unwrap();+ let full = pdfcraft_cos::write_full(&doc, &pdfcraft_cos::SaveOptions::default()).unwrap();+ let rewritten = s.open("full.pdf", None, Arc::new(full), None).unwrap();+ black(&s, rewritten);+ s.apply(rewritten, Edit::RemoveMarks { kind: MarkKind::Background }).unwrap();+ black(&s, rewritten);+ }++++fn contains(haystack: &[u8], needle: &[u8]) -> bool {++ haystack.windows(needle.len()).any(|w| w == needle)++}++++#[test]++fn saving_after_deleting_pages_rewrites_the_file_without_them() {++ let (mut s, id) = session_with(6);++ let original = s.save_bytes(id).unwrap();++ s.apply(id, Edit::DeletePages { pages: vec![1, 2, 3, 4] }).unwrap();++ let saved = s.save_bytes(id).unwrap();++ assert!(saved.len() < original.len(), "the file shrank: {} -> {}", original.len(), saved.len());++ assert!(!saved.starts_with(original.as_slice()), "a full rewrite, not an update appended to the old file");++ assert!(!contains(&saved, b"Page 3"), "a deleted page's text is not left in an earlier revision");++ let mut again = Session::new();++ let id2 = again.open("saved.pdf", None, saved, None).unwrap();++ assert_eq!(page_texts(&again, id2), ["Page 1", "Page 6"]);++}++++#[test]++fn saving_after_deleting_pages_from_a_signed_file_stays_incremental() {++ let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap();++ let digital_id = sign::pkcs12::open(&p12, "test").unwrap();++ let mut s = Session::new().with_clock(|| 1_800_000_000);++ let id = s.open("fixture.pdf", None, Arc::new(fixture(3)), None).unwrap();++ let opts = SignOptions { page: 0, rect: Some([20.0, 20.0, 160.0, 50.0]), ..SignOptions::default() };++ let signed = s.sign(id, &digital_id, opts).unwrap();++ s.mark_signed(id, signed.clone(), None).unwrap();++ s.apply(id, Edit::DeletePages { pages: vec![2] }).unwrap();++ let saved = s.save_bytes(id).unwrap();++ assert!(saved.starts_with(signed.as_ref()), "the signed bytes stay an incremental update");++ assert!(s.get(id).unwrap().is_signed());++}++++#[test]++fn saving_after_a_batch_that_deletes_pages_rewrites_the_file() {++ let (mut s, id) = session_with(6);++ let original = s.save_bytes(id).unwrap();++ let batch = Edit::Batch {++ label: "Delete and rotate".into(),++ edits: vec![++ Edit::Batch { label: "Delete pages".into(), edits: vec![Edit::DeletePages { pages: vec![1, 2, 3, 4] }] },++ Edit::RotatePages { pages: vec![0], degrees: 90 },++ ],++ };++ s.apply(id, batch).unwrap();++ let saved = s.save_bytes(id).unwrap();++ assert!(!saved.starts_with(original.as_slice()), "a full rewrite, not an update appended to the old file");++ assert!(!contains(&saved, b"Page 3"), "a deleted page's text is not left in an earlier revision");++}++++#[test]++fn saving_without_deleting_pages_stays_incremental() {++ let (mut s, id) = session_with(3);++ let original = s.save_bytes(id).unwrap();++ s.apply(id, Edit::RotatePages { pages: vec![0], degrees: 90 }).unwrap();++ let saved = s.save_bytes(id).unwrap();++ assert!(saved.starts_with(original.as_slice()), "an edit that deletes nothing is still appended");++}diff --cc parity/acrobat-features.tomlindex 01b694c97,0b6f658dd..5f52e8fbc--- a/parity/acrobat-features.toml+++ b/parity/acrobat-features.toml@@@ -1274,8 -1286,8 +1286,8 @@@ milestone = "M4status = "shipped"commands = []tools = []- evidence = ["crates/ui-egui/tests/it/editing.rs::dragging_pages_panel_thumbnails_reorders_pages", "crates/ui-egui/tests/it/viewer.rs::pages_panel_thumbnails_have_a_context_menu", "crates/ui-egui/tests/it/editing.rs::deleting_pages_from_the_pages_panel_menu", "crates/ui-egui/tests/it/editing.rs::the_delete_key_deletes_pages_picked_in_the_pages_panel_but_never_every_page"]- notes = "Drag the selection (or the page grabbed) to reorder, with a drop bar and edge scrolling; right-click offers Extract pages, Cut, Copy, Paste after and Delete pages (also the Delete key over the panel). Deleting pages makes the next Save a full rewrite (unsigned files), so the deleted pages leave the file; signed files stay incremental. Not yet: Rotate, Insert and Page labels in the menu, dragging pages between documents, or dropping files onto the panel."+ evidence = ["crates/ui-egui/tests/it/view.rs::pages_sidebar_select_all_keeps_current_page_and_keyboard_scope", "crates/ui-egui/tests/it/editing.rs::dragging_pages_panel_thumbnails_reorders_pages", "crates/ui-egui/tests/it/viewer.rs::pages_panel_thumbnails_have_a_context_menu", "crates/ui-egui/tests/it/editing.rs::split_from_pages_panel_context_menu", "crates/ui-egui/tests/it/editing.rs::deleting_pages_from_the_pages_panel_menu", "crates/ui-egui/tests/it/editing.rs::the_delete_key_deletes_pages_picked_in_the_pages_panel_but_never_every_page"]-notes = "Ctrl/Cmd+A selects every page while the Pages sidebar owns the keyboard, without navigation; Escape clears that selection. Viewer and text-field shortcuts keep their own scope. Drag the selection (or the page grabbed) to reorder, with a drop bar and edge scrolling; right-click offers Split document…, Extract pages, Cut, Copy, Paste after and Delete pages (also the Delete key over the panel). Not yet: Rotate, Insert and Page labels in the menu, dragging pages between documents, or dropping files onto the panel."++notes = "Ctrl/Cmd+A selects every page while the Pages sidebar owns the keyboard, without navigation; Escape clears that selection. Viewer and text-field shortcuts keep their own scope. Drag the selection (or the page grabbed) to reorder, with a drop bar and edge scrolling; right-click offers Split document…, Extract pages, Cut, Copy, Paste after and Delete pages (also the Delete key over the panel). Deleting pages makes the next Save a full rewrite (unsigned files), so the deleted pages leave the file; signed files stay incremental. Not yet: Rotate, Insert and Page labels in the menu, dragging pages between documents, or dropping files onto the panel."[[feature]]id = "view.bookmarks-panel"