Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Merge remote-tracking branch 'refs/remotes/origin/main' into fix/background-hidden-by-page-backdrop

alehel993d3f922780
diff --cc crates/automation/src/dispatch.rs
index 000000000,26e1f9536..6e92616ce
mode 000000,100644..100644
--- a/crates/automation/src/dispatch.rs
+++ b/crates/automation/src/dispatch.rs
@@@ -1,0 -1,784 +1,785 @@@
+ use super::error::{Result, ToolError, failed};
+ use super::json::{Args, document_attachment_keys, info, one_based, parse_style_ranges, security, summary};
+ use super::paths::{read_input, write_atomic};
+ use super::*;
+
+ /// One piece of a tool's result.
+ #[derive(Clone, Debug, PartialEq)]
+ pub enum Content {
+ /// Structured data (MCP: a text block with the JSON plus `structuredContent`).
+ Json(Value),
+ /// A PNG image.
+ Png { data: Vec<u8>, width: u32, height: u32 },
+ }
+
+ impl Automation {
+ /// Run the tool `name` with JSON `args` (an object; `null` means no arguments).
+ pub fn call(&mut self, name: &str, args: &Value) -> Result<Vec<Content>> {
+ let empty = json!({});
+ let args = if args.is_null() { &empty } else { args };
+ if !args.is_object() {
+ return Err(ToolError::InvalidArgs("arguments must be a JSON object".into()));
+ }
+ let def = tools::find(name).ok_or_else(|| ToolError::UnknownTool(name.into()))?;
+ tools::check_args(def, args)?;
+ let a = Args(args);
+ let out = match name {
+ "doc_open" => self.doc_open(&a)?,
+ "doc_batch" => self.doc_batch(&a)?,
+ "doc_list" => json!({ "documents": self.session.docs().iter().map(summary).collect::<Vec<_>>() }),
+ "doc_info" => {
+ let id = self.doc(&a)?.id;
+ self.session.refresh_fonts(id);
+ info(self.doc(&a)?)
+ }
+ "doc_close" => self.doc_close(&a)?,
+ "doc_save" => self.doc_save(&a)?,
+ "doc_set_info" => {
+ let edit = Edit::SetInfo { key: a.str("key")?.into(), value: a.str("value")?.into() };
+ self.apply(&a, edit)?
+ }
+ "page_render" => return self.page_render(&a).map(|c| vec![c]),
+ "comment_image_preview" => return self.comment_image_preview(&a),
+ "text_extract" => self.text_extract(&a)?,
+ "text_word_count" => self.text_word_count(&a)?,
+ "text_find" => self.text_find(&a)?,
+ "page_rotate" => {
+ let degrees = a.int("degrees")?;
+ if degrees % 90 != 0 {
+ return Err(ToolError::InvalidArgs("degrees must be a multiple of 90".into()));
+ }
+ let doc = self.doc(&a)?;
+ let base = match a.opt_ints("pages")? {
+ Some(_) => self.pages(&a, "pages")?,
+ None => (0..doc.info.pages.len()).collect(),
+ };
+ let parity = match a.opt_str("subset")?.unwrap_or("all") {
+ "all" => pdfcraft_engine::PageParity::Both,
+ "even" => pdfcraft_engine::PageParity::Even,
+ "odd" => pdfcraft_engine::PageParity::Odd,
+ s => return Err(ToolError::InvalidArgs(format!("unknown subset {s:?} (all, even, odd)"))),
+ };
+ let orientation = match a.opt_str("orientation")?.unwrap_or("all") {
+ "all" => pdfcraft_engine::PageOrientation::Both,
+ "landscape" => pdfcraft_engine::PageOrientation::Landscape,
+ "portrait" => pdfcraft_engine::PageOrientation::Portrait,
+ o => return Err(ToolError::InvalidArgs(format!("unknown orientation {o:?} (all, landscape, portrait)"))),
+ };
+ let pages = pdfcraft_engine::filter_pages(&self.doc(&a)?.info, &base, parity, orientation);
+ if pages.is_empty() {
+ return Err(failed("no pages match the filters"));
+ }
+ let n = pages.len();
+ let mut out = self.apply(&a, Edit::RotatePages { pages, degrees })?;
+ out["rotated"] = json!(n);
+ out
+ }
+ "page_enhance_camera" => {
+ let page = self.page(&a)?;
+ let given = a.nums::<8>("corners")?;
+ let doc = self.doc(&a)?;
+ let (id, info) = (doc.id, doc.info.pages.get(page).cloned().ok_or_else(|| failed("no such page"))?);
+ let corners = match given {
+ Some(c) => [0, 1, 2, 3].map(|i| {
+ let [x, y] = info.view_to_user(c[2 * i] as f32, c[2 * i + 1] as f32);
+ [x as f64, y as f64]
+ }),
+ None => self.session.detect_camera_corners(id, page).ok_or_else(|| {
+ failed("the document's edges could not be found on this page: pass `corners` [x1, y1, x2, y2, x3, y3, x4, y4]")
+ })?,
+ };
+ let level = match a.opt_int("level")? {
+ None => 0,
+ Some(l @ 0..=100) => l as u8,
+ Some(l) => return Err(ToolError::InvalidArgs(format!("level must be between 0 and 100, not {l}"))),
+ };
+ let look = match a.opt_str("mode")? {
+ None => pdfcraft_engine::camera_clean::Look::Colour,
+ Some(m) => pdfcraft_engine::camera_clean::Look::from_name(m)
+ .ok_or_else(|| ToolError::InvalidArgs(format!("unknown mode {m:?} (original, colour, greyscale, bw)")))?,
+ };
+ self.session.enhance_camera_page_at(id, page, corners, look, level).map_err(failed)?;
+ let r = |v: f32| (v * 100.0).round() / 100.0;
+ let used: Vec<f32> = corners.iter().flat_map(|&[x, y]| info.user_to_view(x as f32, y as f32)).map(r).collect();
+ let mut out = summary(self.doc(&a)?);
+ out["corners"] = json!(used);
+ out["detected"] = json!(given.is_none());
+ out
+ }
+ "page_delete" => {
+ let pages = self.pages(&a, "pages")?;
+ self.apply(&a, Edit::DeletePages { pages })?
+ }
+ "page_move" => {
+ let pages = self.pages(&a, "pages")?;
+ let to = self.position(&a, "to")?;
+ self.apply(&a, Edit::MovePages { pages, to })?
+ }
+ "page_reverse" => {
+ let pages = match a.opt_ints("pages")? {
+ Some(_) => self.pages(&a, "pages")?,
+ None => (0..self.doc(&a)?.info.pages.len()).collect(),
+ };
+ self.apply(&a, Edit::ReversePages { pages })?
+ }
+ "page_insert_blank" => self.insert_blank(&a)?,
+ "page_insert_file" => self.insert_file(&a)?,
+ "page_extract" => self.page_extract(&a)?,
+ "doc_combine" => self.doc_combine(&a)?,
+ "doc_create_multiple" => self.doc_create_multiple(&a)?,
+ "doc_split" => self.doc_split(&a)?,
+ "edit_undo" => {
+ let id = self.doc(&a)?.id;
+ let label = self.session.undo(id).map_err(failed)?.to_string();
+ json!({ "undone": label, "document": summary(self.doc(&a)?) })
+ }
+ "edit_redo" => {
+ let id = self.doc(&a)?.id;
+ let label = self.session.redo(id).map_err(failed)?.to_string();
+ json!({ "redone": label, "document": summary(self.doc(&a)?) })
+ }
+ "command_list" => self.command_list(&a)?,
+ "command_run" => return self.command_run(&a),
+ "command_batch" => self.command_batch(&a)?,
+ "doc_inspect" => self.doc_inspect(&a)?,
+ "render_preview" => return self.render_preview(&a).map(|c| vec![c]),
+ "page_number" => {
+ use pdfcraft_organize::LabelStyle as L;
+ let n = self.doc(&a)?.info.pages.len();
+ let (from, to) = (a.int("from")?, a.int("to")?);
+ if from < 1 || to < from || to as usize > n {
+ return Err(ToolError::InvalidArgs(format!("from and to must satisfy 1 ≤ from ≤ to ≤ {n}")));
+ }
+ let style = match a.opt_str("style")?.unwrap_or("decimal") {
+ "decimal" => L::Decimal,
+ "upper-roman" => L::UpperRoman,
+ "lower-roman" => L::LowerRoman,
+ "upper-alpha" => L::UpperAlpha,
+ "lower-alpha" => L::LowerAlpha,
+ "none" => L::None,
+ other => return Err(ToolError::InvalidArgs(format!("unknown style {other:?}"))),
+ };
+ let prefix = a.opt_str("prefix")?.unwrap_or_default().to_string();
+ let first = a.opt_int("start")?.unwrap_or(1).clamp(1, u32::MAX as i64) as u32;
+ let mut out = self.apply(&a, Edit::NumberPages { from: from as usize - 1, to: to as usize - 1, style, prefix, first })?;
+ out["labels"] = json!(self.doc(&a)?.info.pages.iter().map(|p| p.label.clone()).collect::<Vec<_>>());
+ out
+ }
+ "bookmark_list" => self.bookmark_listing(&a)?,
+ "bookmark_add" => {
+ let page = self.page(&a)?;
+ let parent = a.opt_path("parent")?.unwrap_or_default();
+ let index = a.opt_int("position")?.map_or(usize::MAX, |p| (p.max(1) - 1) as usize);
+ let title = a.str("title")?.to_string();
+ let (left, top) = (a.bookmark_coordinate("left")?, a.bookmark_coordinate("top")?);
+ let [left, top] = match self.doc(&a)?.info.pages.get(page) {
+ Some(p) => p.xyz_for_view(left, top),
+ None => [None, None],
+ };
+ let (left, top) = (left.map(f64::from), top.map(f64::from));
+ self.apply(&a, Edit::AddBookmark { parent, index, title, page, left, top })?
+ }
+ "bookmark_rename" => {
+ let (path, title) = (a.path("path")?, a.str("title")?.to_string());
+ self.apply(&a, Edit::RenameBookmark { path, title })?
+ }
+ "bookmark_delete" => {
+ let path = a.path("path")?;
+ self.apply(&a, Edit::DeleteBookmark { path })?
+ }
+ "bookmark_move" => {
+ let from = a.path("path")?;
+ let to_parent = a.opt_path("parent")?.unwrap_or_default();
+ let index = a.opt_int("position")?.map_or(usize::MAX, |p| (p.max(1) - 1) as usize);
+ self.apply(&a, Edit::MoveBookmark { from, to_parent, index })?
+ }
+ "bookmark_set_page" => {
+ let (path, page) = (a.path("path")?, self.page(&a)?);
+ self.apply(&a, Edit::SetBookmarkPage { path, page })?
+ }
+ "bookmark_set_style" => {
+ let path = a.path("path")?;
+ // Left out keeps the colour; [0, 0, 0] is the default black.
+ let color = match a.get("color") {
+ None => None,
+ Some(v) => {
+ let rgb: Option<Vec<f64>> = v.as_array().and_then(|c| c.iter().map(Value::as_f64).collect());
+ match rgb.as_deref() {
+ Some(&[r, g, b]) if [r, g, b].iter().all(|c| (0.0..=1.0).contains(c)) => Some([r, g, b]),
+ _ => return Err(ToolError::InvalidArgs("color must be [r, g, b], each from 0 to 1".into())),
+ }
+ }
+ };
+ let (bold, italic) = (a.opt_bool("bold")?, a.opt_bool("italic")?);
+ if color.is_none() && bold.is_none() && italic.is_none() {
+ return Err(ToolError::InvalidArgs("give color, bold or italic".into()));
+ }
+ let mut edits = Vec::new();
+ if let Some(color) = color {
+ edits.push(Edit::SetBookmarkColor { path: path.clone(), color: Some(color) });
+ }
+ if bold.is_some() || italic.is_some() {
+ edits.push(Edit::SetBookmarkStyle { path, bold, italic });
+ }
+ // A colour and a style given together are one step to undo, applied all or nothing.
+ match edits.len() {
+ 1 => self.apply(&a, edits.remove(0))?,
+ _ => self.apply(&a, Edit::Batch { label: "Style".into(), edits })?,
+ }
+ }
+ "bookmark_from_structure" => {
+ let mut out = self.apply(&a, Edit::BookmarksFromStructure)?;
+ let listing = self.bookmark_listing(&a)?;
+ out["bookmarks"] = listing["bookmarks"].clone();
+ out["next"] = listing["next"].clone();
+ out
+ }
+ "doc_protect" => self.doc_protect(&a)?,
+ "page_replace" => {
+ let pages = self.pages(&a, "pages")?;
+ let path = self.resolve(a.str("path")?, false)?;
+ let bytes = Arc::new(read_input(&path)?);
+ let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
+ let src_pages = match a.opt_ints("from_pages")? {
+ Some(p) => one_based(&p)?,
+ None => (0..pages.len()).collect(),
+ };
+ self.apply(&a, Edit::ReplacePages { pages, name, bytes, src_pages })?
+ }
+ "page_duplicate" => {
+ let pages = self.pages(&a, "pages")?;
+ let at = self.opt_position(&a, "at")?;
+ self.apply(&a, Edit::DuplicatePages { pages, at })?
+ }
+ "page_set_box" => self.page_set_box(&a)?,
+ "page_transition_set" => self.page_transition_set(&a)?,
+ "doc_create" => self.doc_create(&a)?,
+ "xfa_to_static" => self.apply(&a, Edit::XfaToStatic)?,
+ "doc_flatten" => {
+ let (comments, fields) = (a.opt_bool("comments")?.unwrap_or(true), a.opt_bool("fields")?.unwrap_or(true));
+ if !comments && !fields {
+ return Err(ToolError::InvalidArgs("nothing to flatten".into()));
+ }
+ self.apply(&a, Edit::Flatten { comments, fields })?
+ }
+ "doc_reduce" => {
+ let id = self.doc(&a)?.id;
+ let before = self.doc(&a)?.bytes.len();
+ let path = self.resolve(a.str("path")?, true)?;
+ let (bytes, merged) = self.session.reduced_bytes(id).map_err(failed)?;
+ // As in the app, a copy that isn't smaller is not written (#490).
+ let written = bytes.len() < before;
+ if written {
+ write_atomic(&path, &bytes)?;
+ }
+ json!({ "path": path.to_string_lossy(), "written": written, "bytes_before": before, "bytes_after": bytes.len(), "merged_objects": merged })
+ }
+ "doc_optimize" => self.doc_optimize(&a)?,
+ "doc_initial_view" => self.doc_initial_view(&a)?,
+ "doc_revisions" => self.doc_revisions(&a)?,
+ "text_lines" => {
+ let page = self.page(&a)?;
+ let doc = self.doc_to_copy(&a)?;
+ let info = &doc.info.pages[page];
+ let r = |x: f32| (x as f64 * 100.0).round() / 100.0;
+ let lines: Vec<Value> = doc
+ .text_lines(page)
+ .iter()
+ .enumerate()
+ .map(|(i, l)| {
+ let (u, v) = (info.user_to_view(l.rect[0] as f32, l.rect[1] as f32), info.user_to_view(l.rect[2] as f32, l.rect[3] as f32));
+ json!({
+ "line": i + 1,
+ "text": l.text,
+ "rect": [r(u[0].min(v[0])), r(u[1].min(v[1])), r(u[0].max(v[0])), r(u[1].max(v[1]))],
+ "font": l.base_font,
+ "size": (l.size * 100.0).round() / 100.0,
+ })
+ })
+ .collect();
+ json!({ "page": page + 1, "count": lines.len(), "lines": lines })
+ }
+ "image_hit" => {
+ let page = self.page(&a)?;
+ let point = a
+ .get("point")
+ .and_then(Value::as_array)
+ .filter(|p| p.len() == 2)
+ .and_then(|p| Some([p.first()?.as_f64()?, p.get(1)?.as_f64()?]))
+ .filter(|p| p.iter().all(|v| v.is_finite() && v.abs() <= 1e9))
+ .ok_or_else(|| ToolError::InvalidArgs("point must contain two finite coordinates".into()))?;
+ let doc = self.doc(&a)?;
+ let p = &doc.info.pages[page];
+ let user = p.view_to_user(point[0] as f32, point[1] as f32).map(f64::from);
+ let images: Vec<_> = doc.page_images(page).iter().enumerate().filter(|(_, im)| im.contains(user)).map(|(i, _)| i + 1).collect();
+ json!({"page":page+1,"images":images})
+ }
+ "page_images" => {
+ let page = self.page(&a)?;
+ let doc = self.doc(&a)?;
+ let info = &doc.info.pages[page];
+ let r = |x: f32| (x as f64 * 100.0).round() / 100.0;
+ let list: Vec<Value> = doc
+ .page_images(page)
+ .iter()
+ .enumerate()
+ .map(|(i, im)| {
+ let (u, v) = (info.user_to_view(im.rect[0] as f32, im.rect[1] as f32), info.user_to_view(im.rect[2] as f32, im.rect[3] as f32));
+ let visible = im.visible_rect.map(|rect| {
+ let (u, v) = (info.user_to_view(rect[0] as f32, rect[1] as f32), info.user_to_view(rect[2] as f32, rect[3] as f32));
+ [r(u[0].min(v[0])), r(u[1].min(v[1])), r(u[0].max(v[0])), r(u[1].max(v[1]))]
+ });
+ json!({ "visible_rect": visible, "image": i + 1, "rect": [r(u[0].min(v[0])), r(u[1].min(v[1])), r(u[0].max(v[0])), r(u[1].max(v[1]))], "pixels": [im.width, im.height], "name": im.name, "kind": if im.is_form { "form" } else { "image" } })
+ })
+ .collect();
+ json!({ "page": page + 1, "count": list.len(), "images": list })
+ }
+ "image_edit" | "image_save" => {
+ let page = self.page(&a)?;
+ let n = self.doc(&a)?.page_images(page).len();
+ let k = a.int("image")?;
+ if k < 1 || k as usize > n {
+ return Err(ToolError::InvalidArgs(format!("image {k} is out of range: page {} has {n} images", page + 1)));
+ }
+ let index = k as usize - 1;
+ if name == "image_save" {
+ let (ext, bytes) = self.doc(&a)?.page_image_file(page, index).map_err(failed)?;
+ let mut path = self.resolve(a.str("path")?, true)?;
+ if path.is_dir() {
+ // Adding the extension to a folder's name would write beside it: "." is the
+ // root, so that would land outside it.
+ return Err(failed(format!("{}: is a folder, not a file", path.display())));
+ }
+ if path.extension().is_none() {
+ path.set_extension(ext);
+ }
+ write_atomic(&path, &bytes)?;
+ json!({ "path": path.to_string_lossy(), "format": ext, "bytes": bytes.len() })
+ } else {
+ use pdfcraft_engine::ImageEdit;
+ let change = match a.str("action")? {
+ "move" => {
+ let r: Vec<f64> =
+ a.get("rect").and_then(Value::as_array).map(|x| x.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
+ let r = <[f64; 4]>::try_from(r).map_err(|_| ToolError::InvalidArgs("move needs rect: 4 numbers".into()))?;
+ // Top-left-origin points → user space.
+ let info = &self.doc(&a)?.info.pages[page];
+ let (u0, u1) = (info.view_to_user(r[0] as f32, r[1] as f32), info.view_to_user(r[2] as f32, r[3] as f32));
+ ImageEdit::Move([u0[0].min(u1[0]) as f64, u0[1].min(u1[1]) as f64, u0[0].max(u1[0]) as f64, u0[1].max(u1[1]) as f64])
+ }
+ "rotate_by" => ImageEdit::RotateBy(
+ a.get("degrees")
+ .and_then(Value::as_f64)
+ .ok_or_else(|| ToolError::InvalidArgs("rotate_by needs degrees: a number (clockwise)".into()))?,
+ ),
+ "rotate" => ImageEdit::Rotate(a.opt_int("quarters")?.unwrap_or(1) as i32),
+ "crop" => {
+ let r: Vec<f64> =
+ a.get("rect").and_then(Value::as_array).map(|x| x.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
+ let r =
+ <[f64; 4]>::try_from(r).map_err(|_| ToolError::InvalidArgs("crop needs rect: 4 numbers, the part to keep".into()))?;
+ let info = &self.doc(&a)?.info.pages[page];
+ let (u0, u1) = (info.view_to_user(r[0] as f32, r[1] as f32), info.view_to_user(r[2] as f32, r[3] as f32));
+ ImageEdit::Crop([u0[0].min(u1[0]) as f64, u0[1].min(u1[1]) as f64, u0[0].max(u1[0]) as f64, u0[1].max(u1[1]) as f64])
+ }
+ "flip_horizontal" => ImageEdit::Flip { horizontal: true },
+ "flip_vertical" => ImageEdit::Flip { horizontal: false },
+ "delete" => ImageEdit::Delete,
+ "replace" => {
+ let path = self.resolve(a.str("path")?, false)?;
+ let bytes = read_input(&path)?;
+ ImageEdit::Replace {
+ name: path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
+ bytes: Arc::new(bytes),
+ }
+ }
+ other => return Err(ToolError::InvalidArgs(format!("unknown action {other:?}"))),
+ };
+ self.apply(&a, Edit::EditPageImage { page, index, change })?
+ }
+ }
+ "text_paragraphs" => {
+ let page = self.page(&a)?;
+ let doc = self.doc_to_copy(&a)?;
+ let info = &doc.info.pages[page];
+ let r = |x: f32| (x as f64 * 100.0).round() / 100.0;
+ let current = doc.text_blocks(page);
+ let id = doc.id;
+ let blocks: Vec<Value> = current
+ .iter()
+ .enumerate()
+ .map(|(i, b)| {
+ let (u, v) = (info.user_to_view(b.rect[0] as f32, b.rect[1] as f32), info.user_to_view(b.rect[2] as f32, b.rect[3] as f32));
+ json!({
+ "paragraph": i + 1,
+ "text": b.text,
+ "editor_text": b.editor_text,
+ "rows": b.rows.iter().map(|row| row.iter().map(|i| i + 1).collect::<Vec<_>>()).collect::<Vec<_>>(),
+ "lines": b.lines.iter().map(|l| l + 1).collect::<Vec<_>>(),
+ "rect": [r(u[0].min(v[0])), r(u[1].min(v[1])), r(u[0].max(v[0])), r(u[1].max(v[1]))],
+ "font": b.base_font,
+ "size": (b.size * 100.0).round() / 100.0,
+ })
+ })
+ .collect();
+ self.record_listing(id, page, &current);
+ json!({ "page": page + 1, "count": blocks.len(), "paragraphs": blocks })
+ }
+ "text_font_files" => {
+ let roots = if let Some(paths) = a.get("directories") {
+ let paths = paths
+ .as_array()
+ .filter(|p| p.len() <= 16)
+ .ok_or_else(|| ToolError::InvalidArgs("directories must be at most 16 paths".into()))?;
+ paths
+ .iter()
+ .map(|p| self.resolve(p.as_str().ok_or_else(|| ToolError::InvalidArgs("directory must be a path".into()))?, false))
+ .collect::<Result<Vec<_>>>()?
+ } else if let Some(roots) = &self.roots {
+ // The installed fonts are outside the roots: look in the read root instead.
+ let read = roots
+ .read_root()
+ .ok_or_else(|| failed("automation filesystem access is not granted: read authority is absent: installed fonts"))?;
+ vec![self.resolve(&read.to_string_lossy(), false)?]
+ } else if let Some(root) = &self.root {
+ vec![root.clone()]
+ } else {
+ pdfcraft_engine::text_fonts::installed_directories()
+ };
+ json!({"fonts": pdfcraft_engine::text_fonts::discover(&roots).into_iter().map(|f| json!({"path":f.path,"family":f.family,"font":f.face})).collect::<Vec<_>>()})
+ }
+ "text_font_import" => {
+ let page = self.page(&a)?;
+ let path = self.resolve(a.str("path")?, false)?;
+ let file = std::fs::File::open(&path).map_err(failed)?;
+ use std::io::Read;
+ let mut bytes = Vec::new();
+ file.take((16 << 20) + 1).read_to_end(&mut bytes).map_err(failed)?;
+ if bytes.len() > 16 << 20 {
+ return Err(ToolError::InvalidArgs("font input exceeds 16 MiB".into()));
+ }
+ let before: Vec<_> = self.doc(&a)?.text_editor_fonts(page).into_iter().map(|f| f.resource).collect();
+ let mut out = self.apply(&a, Edit::RegisterTextFont { page, bytes: Arc::new(bytes) })?;
+ let added = self
+ .doc(&a)?
+ .text_editor_fonts(page)
+ .into_iter()
+ .find(|f| !before.contains(&f.resource) && !f.resource.starts_with("PCApproved"));
+ if let Some(f) = added {
+ out["resource"] = json!(f.resource);
+ out["font"] = json!(f.face);
+ }
+ out
+ }
+ "text_fonts" => {
+ let page = self.page(&a)?;
+ json!({"fonts": self.doc(&a)?.text_editor_fonts(page).into_iter().map(|f| json!({"resource":f.resource,"font":f.face,"full_face":f.resource.starts_with("PCFull"),"preview_only":f.resource.starts_with("PCApproved")})).collect::<Vec<_>>()})
+ }
+ "text_edit_layout" => {
+ let page = self.page(&a)?;
+ let doc = self.doc(&a)?;
+ let k = a.int("paragraph")?;
+ let blocks = doc.text_blocks(page);
+ let index = self.paragraph_index(doc.id, page, k, &blocks)?;
+ let source = blocks.get(index).ok_or_else(|| ToolError::InvalidArgs("paragraph is out of range".into()))?;
+ let text = a.opt_str("text")?.unwrap_or(&source.editor_text);
+ let style = pdfcraft_engine::BlockStyle {
+ size: a.opt_num("size")?,
+ width: a.opt_num("width")?,
+ resource: a.opt_str("font_resource")?.map(str::to_owned),
+ ranges: parse_style_ranges(a.get("ranges"))?,
+ ..Default::default()
+ };
+ let layout = doc.text_edit_layout(page, index, text, &style).map_err(failed)?;
+ let info = &doc.info.pages[page];
+ let view_rect = |r: [f64; 4]| {
+ let a = info.user_to_view(r[0] as f32, r[1] as f32);
+ let b = info.user_to_view(r[2] as f32, r[3] as f32);
+ [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])]
+ };
+ let fonts: Vec<_> = doc.text_editor_fonts(page).into_iter().map(|f| json!({"resource": f.resource, "face": f.face})).collect();
+ json!({ "page": page + 1, "paragraph": k, "source_rect": view_rect(layout.source_rect),
+ "draft_rect": layout.draft_rect.map(view_rect), "overflow": layout.overflow, "embedded_fonts": fonts })
+ }
+ "text_edit" if a.get("paragraph").is_some() => {
+ let page = self.page(&a)?;
+ let k = a.int("paragraph")?;
+ let (id, blocks) = {
+ let doc = self.doc(&a)?;
+ (doc.id, doc.text_blocks(page))
+ };
+ let index = self.paragraph_index(id, page, k, &blocks)?;
+ let block = blocks.get(index).cloned().ok_or_else(|| ToolError::InvalidArgs(format!("paragraph {k} is out of range")))?;
+ let text = a.opt_str("text")?.map(str::to_owned).unwrap_or(block.text);
+ let mut style = pdfcraft_engine::BlockStyle {
+ ranges: parse_style_ranges(a.get("ranges"))?,
+ resource: a.opt_str("font_resource")?.map(str::to_owned),
+ bold: a.opt_bool("bold")?,
+ size: a.opt_num("size")?,
+ underline: a.opt_bool("underline")?,
+ line_spacing: a.opt_num("line_spacing")?,
+ char_spacing: a.opt_num("char_spacing")?,
+ scale: a.opt_num("scale")?,
+ width: a.opt_num("width")?,
+ ..Default::default()
+ };
+ let (dx, dy) = (a.opt_num("dx")?, a.opt_num("dy")?);
+ if dx.is_some() || dy.is_some() {
+ style.offset = Some([dx.unwrap_or(0.0), dy.unwrap_or(0.0)]);
+ }
+ if let Some(f) = a.opt_str("font")? {
+ let family = match f {
+ "helvetica" => pdfcraft_engine::FontFamily::Helvetica,
+ "times" => pdfcraft_engine::FontFamily::Times,
+ "courier" => pdfcraft_engine::FontFamily::Courier,
+ other => return Err(ToolError::InvalidArgs(format!("unknown font {other:?} (helvetica, times, courier)"))),
+ };
+ style.family = Some((family, a.opt_bool("bold")?.unwrap_or(false), a.opt_bool("italic")?.unwrap_or(false)));
+ }
+ if let Some(c) = a.opt_str("color")? {
+ style.color = Some(comments::parse_color(c)?);
+ }
+ if let Some(al) = a.opt_str("align")? {
+ style.align = Some(match al {
+ "left" => pdfcraft_engine::TextAlign::Left,
+ "center" => pdfcraft_engine::TextAlign::Center,
+ "right" => pdfcraft_engine::TextAlign::Right,
+ "justify" => pdfcraft_engine::TextAlign::Justify,
+ other => return Err(ToolError::InvalidArgs(format!("unknown align {other:?}"))),
+ });
+ }
+ // Where the paragraph is drawn after the edit: moved by dx, dy (up is +dy).
+ let [dx, dy] = style.offset.unwrap_or([0.0, 0.0]);
+ let moved = [block.rect[0] + dx, block.rect[1] + dy, block.rect[2] + dx, block.rect[3] + dy];
+ let wanted: String = text.split_whitespace().collect();
+ let mut out = self.apply(&a, Edit::EditTextBlock { page, block: index, text, style })?;
+ let doc = self.doc(&a)?;
+ let after = doc.text_blocks(page);
+ // Without `text` the paragraph keeps the document's own words: not echoed when
+ // the document doesn't allow copying them.
+ let copy = doc.allows_copying();
+ // Only a paragraph that now shows exactly the requested text is the edited one. A
+ // neighbour that overlaps the old box (overlaid text, a text layer) must not take
+ // its number, and neither must a paragraph the edit merged it into: rewriting that
+ // one by this number would drop the neighbour's text.
+ let edited = block_overlapping(&after, moved)
+ .filter(|&i| !wanted.is_empty() && after.get(i).is_some_and(|b| b.text.split_whitespace().collect::<String>() == wanted));
+ if let Some(b) = edited.and_then(|i| after.get(i)) {
+ out["paragraph"] = json!({ "lines": b.lines.len(), "font": b.base_font });
+ if copy {
+ out["paragraph"]["text"] = json!(b.text);
+ }
+ }
+ let stale = self.follow_edit(id, page, k, edited.and_then(|i| after.get(i)), &after);
+ if !stale.is_empty() {
+ out["stale_paragraphs"] = json!(stale);
+ }
+ out
+ }
+ "text_edit" => {
+ let page = self.page(&a)?;
+ let n = self.doc(&a)?.text_lines(page).len();
+ let line = a.int("line")?;
+ if line < 1 || line as usize > n {
+ return Err(ToolError::InvalidArgs(format!("line {line} is out of range: page {} has {n} lines", page + 1)));
+ }
+ let text = a.str("text")?.to_owned();
+ let mut out = self.apply(&a, Edit::EditTextLine { page, line: line as usize - 1, text })?;
+ let after = self.doc(&a)?.text_lines(page);
+ if let Some(l) = after.get(line as usize - 1) {
+ out["line"] = json!({ "text": l.text, "font": l.base_font });
+ }
+ out
+ }
+ "doc_audit_space" => {
+ let rows: Vec<Value> = self
+ .doc(&a)?
+ .audit_space()
+ .iter()
+ .map(|u| json!({ "category": u.category.label(), "bytes": u.bytes, "percent": (u.percent * 100.0).round() / 100.0 }))
+ .collect();
+ json!({ "categories": rows })
+ }
+ "doc_open_revision" => {
+ let id = self.doc(&a)?.id;
+ let n = usize::try_from(a.opt_int("revision")?.ok_or_else(|| ToolError::InvalidArgs("revision is required".into()))?).unwrap_or(0);
+ let new = self.session.open_revision(id, n).map_err(failed)?;
+ summary(self.session.get(new).ok_or_else(|| failed("the document vanished"))?)
+ }
+ "doc_export_images" | "doc_export_text" | "doc_export_all_images" => self.export(name, &a)?,
+ "doc_header_footer" | "doc_watermark" | "doc_background" | "doc_remove_marks" => self.marks(name, &a)?,
++ "doc_backdrops" => self.backdrops(&a)?,
+ "doc_unprotect" => {
+ let mut out = self.apply(&a, Edit::RemoveProtection)?;
+ out["security"] = security(self.doc(&a)?);
+ out
+ }
+ "form_fields" => self.form_fields(&a)?,
+ "form_fill" => self.form_fill(&a)?,
+ "form_set_image" => {
+ let path = self.resolve(a.str("path")?, false)?;
+ let bytes = read_input(&path)?;
+ self.apply(&a, Edit::SetFieldImage { name: a.str("field")?.to_owned(), image: Arc::new(bytes) })?
+ }
+ "form_reset" => self.form_reset(&a)?,
+ "form_add_field" => self.form_add_field(&a)?,
+ "form_add_field_table" => self.form_add_field_table(&a)?,
+ "form_set_props" => self.form_set_props(&a)?,
+ "form_delete_field" => self.form_delete_field(&a)?,
+ "form_tab_order" => self.form_tab_order(&a)?,
+ "form_calculation_order" => self.form_calculation_order(&a)?,
+ "doc_export_data" => self.doc_export_data(&a)?,
+ "doc_import_data" => self.doc_import_data(&a)?,
+ "redact_mark" => self.redact_mark(&a)?,
+ "redact_apply" => self.redact_apply(&a)?,
+ "redact_clear" => self.redact_clear(&a)?,
+ "doc_hidden_info" => self.doc_hidden_info(&a)?,
+ "printers" => self.printers()?,
+ "printer_options" => self.printer_options(&a)?,
+ "link_list" => self.link_list(&a)?,
+ "link_open" => self.link_open(&a)?,
+ "link_add" => self.link_add(&a)?,
+ "link_edit" => self.link_edit(&a)?,
+ "link_delete" => self.link_delete(&a)?,
+ "links_from_urls" => self.links_from_urls(&a)?,
+ "links_remove" => self.links_remove(&a)?,
+ "object_list" => self.object_list(&a)?,
+ "object_move" => self.object_move(&a)?,
+ "content_list" => self.content_list(&a)?,
+ "page_add_text" => self.page_add_text(&a)?,
+ "page_add_image" => self.page_add_image(&a)?,
+ "content_update" => self.content_update(&a)?,
+ "content_delete" => self.content_delete(&a)?,
+ "content_copy" => self.content_copy(&a)?,
+ "doc_print" => self.doc_print(&a)?,
+ "attachment_add" => {
+ let path = self.resolve(a.str("path")?, false)?;
+ let bytes = read_input(&path)?;
+ let name = match a.opt_str("name")? {
+ Some(n) => n.to_string(),
+ None => path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
+ };
+ let mime = pdfcraft_engine::mime_for_name(&name).map(str::to_string);
+ let description = a.opt_str("description")?.map(str::to_string);
+ // Only the document-level keys: an annotation attachment of the same name is not the new one.
+ let before = document_attachment_keys(self.doc(&a)?);
+ let out = self.apply(&a, Edit::AddAttachment { name, bytes, description, mime })?;
+ let key = document_attachment_keys(self.doc(&a)?).into_iter().find(|n| !before.contains(n)).unwrap_or_default();
+ json!({ "name": key, "document": out })
+ }
+ "attachment_delete" => {
+ let edit = Edit::DeleteAttachment { key: a.str("name")?.into() };
+ self.apply(&a, edit)?
+ }
+ "doc_remove_hidden" => self.doc_remove_hidden(&a)?,
+ "doc_audit_redactions" => self.doc_audit_redactions(&a)?,
+ "fill_sign_add" => self.fill_sign_add(&a)?,
+ "fill_sign_date_format" => self.fill_sign_date_format(&a)?,
+ "measure_distance" => self.measurement_add(&a, pdfcraft_engine::measure::Kind::Distance)?,
+ "measure_perimeter" => self.measurement_add(&a, pdfcraft_engine::measure::Kind::Perimeter)?,
+ "measure_area" => self.measurement_add(&a, pdfcraft_engine::measure::Kind::Area)?,
+ "measure_info" => self.measurement_info(&a)?,
+ "measure_list" => self.measurement_list(&a)?,
+ "measure_scale" => self.measurement_scale(&a)?,
+ "measure_snap" => self.measurement_snap(&a)?,
+ "measure_export" => self.measurement_export(&a)?,
+ "comment_list" => self.comment_list(&a)?,
+ "comment_add" => self.comment_add(&a)?,
+ "stamp_custom" => self.stamp_custom(&a)?,
+ "comment_reply" => self.comment_reply(&a)?,
+ "comment_set_status" => self.comment_set_status(&a)?,
+ "sign_list" => self.sign_list(&a)?,
+ "accessibility_check" => self.a11y_check(&a)?,
+ "accessibility_find_untagged" => self.a11y_find_untagged(&a)?,
+ "accessibility_autotag_preview" => self.accessibility_autotag_preview(&a)?,
+ "accessibility_autotag_apply" => self.accessibility_autotag_apply(&a)?,
+ "accessibility_autotag_form_fields" => self.accessibility_autotag_form_fields(&a)?,
+ "ocr_recognize" => self.ocr_recognize(&a)?,
+ "js_run" => self.js_run(&a)?,
+ "js_document_scripts" => self.js_document_scripts(&a)?,
+ "js_set_document_script" => self.js_set_document_script(&a)?,
+ "js_enabled" => self.js_enabled(&a)?,
+ "form_set_script" => self.form_set_script(&a)?,
+ "form_merge_data" => self.form_merge_data(&a)?,
+ "form_actions" => self.form_actions(&a)?,
+ "form_detect_fields" => self.form_detect_fields(&a)?,
+ "doc_compare" => self.doc_compare(&a)?,
+ "action_list" => self.action_list()?,
+ "pdfa_verify" => self.pdfa_verify(&a)?,
+ "print_readiness" => self.print_readiness(&a)?,
+ "doc_export_office" => self.doc_export_office(&a)?,
+ "pdfa_convert" => self.pdfa_convert(&a)?,
+ "standards_remove_id" => {
+ let standard = match a.str("standard")? {
+ "pdfa" => pdfcraft_engine::Standard::PdfA,
+ "pdfx" => pdfcraft_engine::Standard::PdfX,
+ other => return Err(ToolError::InvalidArgs(format!("standard must be pdfa or pdfx, not {other}"))),
+ };
+ self.apply(&a, Edit::RemoveStandardId { standard })?
+ }
+ "action_run" => self.action_run(&a)?,
+ "doc_compare_report" => self.doc_compare_report(&a)?,
+ "doc_compare_mark" => self.doc_compare_mark(&a)?,
+ "form_set_actions" => self.form_set_actions(&a)?,
+ "ocr_status" => self.ocr_status()?,
+ "ocr_recognize_files" => self.ocr_recognize_files(&a)?,
+ "accessibility_report" => self.a11y_report(&a)?,
+ "accessibility_review_record" => self.a11y_review_record(&a)?,
+ "accessibility_review_save" => self.a11y_review_save(&a)?,
+ "accessibility_review_load" => self.a11y_review_load(&a)?,
+ "accessibility_review_html" => self.a11y_review_html(&a)?,
+ "accessibility_fix" => self.a11y_fix(&a)?,
+ "accessibility_figures" => self.accessibility_figures(&a)?,
+ "accessibility_set_alt" => self.accessibility_set_alt(&a)?,
+ "accessibility_tags" => self.accessibility_tags(&a)?,
+ "accessibility_tag_content" => self.accessibility_tag_content(&a)?,
+ "accessibility_set_tag_property" => self.accessibility_set_tag_property(&a)?,
+ "accessibility_mark_tag_artifact" => self.accessibility_mark_tag_artifact(&a)?,
+ "accessibility_move_tag" => self.accessibility_move_tag(&a)?,
+ "sign_id_create" => self.sign_id_create(&a)?,
+ "sign_document" => self.sign_document(&a)?,
+ "sign_keychain_ids" => {
+ #[cfg(target_os = "macos")]
+ let ids: Vec<Value> = pdfcraft_engine::sign::keychain::identities(None)
+ .map_err(failed)?
+ .iter()
+ .map(|id| json!({ "id": pdfcraft_engine::sign::keychain::reference(&id.certificate), "certificate": signing::cert_json(&id.certificate) }))
+ .collect();
+ #[cfg(not(target_os = "macos"))]
+ let ids: Vec<Value> = Vec::new();
+ json!({ "count": ids.len(), "ids": ids })
+ }
+ "sign_windows_ids" => {
+ #[cfg(target_os = "windows")]
+ let (ids, unusable): (Vec<Value>, Vec<Value>) = {
+ let listing = pdfcraft_engine::sign::windows::list().map_err(failed)?;
+ let ids = listing
+ .ids
+ .iter()
+ .map(|id| json!({ "id": pdfcraft_engine::sign::windows::reference(&id.certificate), "certificate": signing::cert_json(&id.certificate) }))
+ .collect();
+ let unusable = listing
+ .unusable
+ .iter()
+ .map(|u| json!({ "subject": u.subject, "sha256": u.fingerprint, "reason": u.reason, "no_private_key": u.no_private_key }))
+ .collect();
+ (ids, unusable)
+ };
+ #[cfg(not(target_os = "windows"))]
+ let (ids, unusable): (Vec<Value>, Vec<Value>) = (Vec::new(), Vec::new());
+ json!({ "count": ids.len(), "ids": ids, "unusable": unusable })
+ }
+ "sign_trust" => self.sign_trust(&a)?,
+ "comment_mark" => self.comment_mark(&a)?,
+ "comment_lock" => self.comment_lock(&a)?,
+ "comments_hide" => self.comments_hide(&a)?,
+ "layer_set" => self.layer_set(&a)?,
+ "view_reading_colors" => self.view_reading_colors(&a)?,
+ "comments_summarize" => self.comments_summarize(&a)?,
+ "comment_edit" => self.comment_edit(&a)?,
+ "comment_delete" => self.comment_delete(&a)?,
+ other => return Err(ToolError::UnknownTool(other.into())),
+ };
+ Ok(vec![Content::Json(out)])
+ }
+ }
diff --cc crates/automation/src/documents.rs
index 000000000,26addfd80..a3b9175d7
mode 000000,100644..100644
--- a/crates/automation/src/documents.rs
+++ b/crates/automation/src/documents.rs
@@@ -1,0 -1,606 +1,629 @@@
+ use super::error::{Result, ToolError, failed};
+ use super::json::{Args, nest_rows, security, summary};
+ use super::paths::{child, read_input, write_atomic};
+ use super::*;
+
+ /// How far a watermark may be moved from the page centre, in points (a page is at most 14,400).
+ const WATERMARK_MAX_OFFSET: f64 = 20_000.0;
+
+ /// Bookmarks in one page of the bookmark list, by default and at most.
+ const BOOKMARK_PAGE: usize = 100;
+
+ const MAX_BOOKMARK_PAGE: usize = 1000;
+
+ impl Automation {
+ // ---- documents ---------------------------------------------------------------------------
+
+ /// One page of a document's bookmarks: `offset` (from 0) and `limit` (1 to `MAX_BOOKMARK_PAGE`).
+ pub(crate) fn bookmark_listing(&self, a: &Args) -> Result<Value> {
+ let id = a.int("doc")?;
+ let id = DocId(u64::try_from(id).map_err(|_| ToolError::InvalidArgs("doc must be positive".into()))?);
+ let offset = a.opt_int("offset")?.unwrap_or(0);
+ let offset = usize::try_from(offset).map_err(|_| ToolError::InvalidArgs("offset must be 0 or more".into()))?;
+ let limit = a.opt_int("limit")?.unwrap_or(BOOKMARK_PAGE as i64);
+ let limit = usize::try_from(limit)
+ .ok()
+ .filter(|l| (1..=MAX_BOOKMARK_PAGE).contains(l))
+ .ok_or_else(|| ToolError::InvalidArgs(format!("limit must be from 1 to {MAX_BOOKMARK_PAGE}")))?;
+ let page = self
+ .session
+ .bookmark_page(id, offset, limit)
+ .ok_or_else(|| ToolError::Failed(format!("no open document with id {} (see doc_list)", id.0)))?;
+ let pages = &self.doc(a)?.info.pages;
+ Ok(json!({ "bookmarks": nest_rows(&page.rows, pages), "next": page.next, "truncated": page.truncated }))
+ }
+
+ pub(crate) fn doc(&self, a: &Args) -> Result<&Document> {
+ let id = a.int("doc")?;
+ let id = u64::try_from(id).map_err(|_| ToolError::InvalidArgs("doc must be positive".into()))?;
+ self.session.get(DocId(id)).ok_or_else(|| ToolError::Failed(format!("no open document with id {id} (see doc_list)")))
+ }
+
+ /// Most pages whose paragraph listing is remembered.
+ const MAX_LISTINGS: usize = 256;
+
+ /// Remember the paragraphs `text_paragraphs` just listed for `page`, so their numbers can be
+ /// resolved against that listing.
+ pub(crate) fn record_listing(&mut self, doc: DocId, page: usize, blocks: &[TextBlock]) {
+ if self.listed.len() >= Self::MAX_LISTINGS && !self.listed.contains_key(&(doc, page)) {
+ self.evicted.extend(self.listed.keys().map(|(d, _)| *d));
+ self.listed.clear();
+ }
+ self.listed.insert((doc, page), blocks.iter().map(BlockKey::of).collect());
+ }
+
+ /// The index in `blocks` (the page's paragraphs now) of paragraph number `k` (1-based).
+ ///
+ /// After `text_paragraphs` a number names the paragraph that listing showed, wherever it is
+ /// now. Without a listing it is a position in `blocks`. A paragraph an edit merged into a
+ /// neighbour (or changed) is refused: the number would otherwise rewrite another paragraph
+ /// and lose its text (#2516). So is any number on a page of a document whose listings were
+ /// dropped at the cap, until the page is listed again.
+ pub(crate) fn paragraph_index(&self, doc: DocId, page: usize, k: i64, blocks: &[TextBlock]) -> Result<usize> {
+ let keys = self.listed.get(&(doc, page));
+ if keys.is_none() && self.evicted.contains(&doc) {
+ return Err(ToolError::InvalidArgs(format!(
+ "page {} has no paragraph listing any more: too many pages were listed and the oldest listings were dropped. List the page again with text_paragraphs",
+ page + 1
+ )));
+ }
+ let n = keys.map_or(blocks.len(), Vec::len);
+ let i = usize::try_from(k)
+ .ok()
+ .and_then(|k| k.checked_sub(1))
+ .filter(|i| *i < n)
+ .ok_or_else(|| ToolError::InvalidArgs(format!("paragraph {k} is out of range: page {} has {n} paragraphs", page + 1)))?;
+ let Some(keys) = keys else { return Ok(i) };
+ keys.get(i).and_then(|key| key.find(blocks, i)).ok_or_else(|| {
+ ToolError::InvalidArgs(format!(
+ "paragraph {k} of page {} is no longer a paragraph of its own: an edit changed it or how the page is grouped. List the page again with text_paragraphs",
+ page + 1
+ ))
+ })
+ }
+
+ /// Update the listing after paragraph `k` was edited into `edited`, one of the page's
+ /// paragraphs `after`. Returns the numbers of the listed paragraphs that are gone.
+ pub(crate) fn follow_edit(&mut self, doc: DocId, page: usize, k: i64, edited: Option<&TextBlock>, after: &[TextBlock]) -> Vec<usize> {
+ let Some(keys) = self.listed.get_mut(&(doc, page)) else { return Vec::new() };
+ if let (Some(edited), Some(key)) = (edited, usize::try_from(k).ok().and_then(|k| k.checked_sub(1)).and_then(|i| keys.get_mut(i))) {
+ *key = BlockKey::of(edited);
+ }
+ keys.iter().enumerate().filter(|(i, key)| key.find(after, *i).is_none()).map(|(i, _)| i + 1).collect()
+ }
+
+ /// The document, if its security allows copying text and images out of it (Table 22, bit 5).
+ pub(crate) fn doc_to_copy(&self, a: &Args) -> Result<&Document> {
+ let doc = self.doc(a)?;
+ doc.check_copying().map_err(failed)?;
+ Ok(doc)
+ }
+
+ pub(crate) fn doc_open(&mut self, a: &Args) -> Result<Value> {
+ let path = self.resolve(a.str("path")?, false)?;
+ let bytes = read_input(&path)?;
+ let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
+ let id = self.session.open(name, Some(path.to_string_lossy().into_owned()), Arc::new(bytes), a.opt_str("password")?).map_err(failed)?;
+ let doc = self.session.get(id).ok_or_else(|| failed("the document vanished"))?;
+ Ok(summary(doc))
+ }
+
+ pub(crate) fn doc_close(&mut self, a: &Args) -> Result<Value> {
+ let doc = self.doc(a)?;
+ let id = doc.id;
+ let discard_changes = a.opt_bool("discard_changes")?.unwrap_or(false);
+ if doc.dirty && !discard_changes {
+ return Err(failed("the document has unsaved changes: save it with doc_save, or pass discard_changes: true"));
+ }
+ self.session.close(id);
+ self.renderers.remove(&id);
+ self.texts.remove(&id);
+ self.listed.retain(|(d, _), _| *d != id);
+ self.evicted.remove(&id);
+ Ok(json!({ "closed": id.0 }))
+ }
+
+ pub(crate) fn doc_save(&mut self, a: &Args) -> Result<Value> {
+ self.doc_save_with(a, write_atomic)
+ }
+
+ pub(crate) fn doc_save_with(&mut self, a: &Args, write: impl FnOnce(&Path, &[u8]) -> Result<()>) -> Result<Value> {
+ let doc = self.doc(a)?;
+ let id = doc.id;
+ let target = match a.opt_str("path")? {
+ Some(p) => self.resolve(p, true)?,
+ None => {
+ // Saving in place writes where the file was opened from, which the read root
+ // allows and the write root may not.
+ let own = doc.path.clone().ok_or_else(|| failed("the document has never been saved: pass a path"))?;
+ let own_path = PathBuf::from(&own);
+ self.check_roots(&own, &own_path, file_access::Access::Write)?;
+ own_path
+ }
+ };
+ let same_file = doc.path.as_deref().is_some_and(|p| Path::new(p) == target);
+ // Saving to a new file is a full rewrite unless asked otherwise, like Save As.
+ let full = a.opt_bool("full")?.unwrap_or(!same_file);
+ let flatten_fill_sign = a.opt_bool("flatten_fill_sign")?.unwrap_or(false);
+ if flatten_fill_sign {
+ self.apply(a, Edit::FlattenFillSign)?;
+ }
+ let bytes = if full { self.session.save_full_bytes(id) } else { self.session.save_bytes(id) }.map_err(failed)?;
+ // A save that adds or removes encryption, or must not keep the old revision (Sanitize,
+ // redaction), is rewritten in full even when an incremental save was asked for.
+ let incremental = !full && bytes.starts_with(&self.doc(a)?.saved_bytes());
+ self.publish_save(id, &target, bytes, incremental, write)
+ }
+
+ /// Validate the prepared bytes before publishing them or marking the document saved.
+ pub(crate) fn publish_save(
+ &mut self,
+ id: DocId,
+ target: &Path,
+ bytes: Arc<Vec<u8>>,
+ incremental: bool,
+ write: impl FnOnce(&Path, &[u8]) -> Result<()>,
+ ) -> Result<Value> {
+ self.session.check_save(id, &bytes).map_err(failed)?;
+ write(target, &bytes)?;
+ let path = target.to_string_lossy().into_owned();
+ self.session.mark_saved(id, bytes.clone(), Some(path.clone())).map_err(failed)?;
+ let doc = self.session.get(id).ok_or_else(|| failed("the saved document is no longer open"))?;
+ Ok(json!({ "path": path, "bytes": bytes.len(), "incremental": incremental, "document": summary(doc) }))
+ }
+
+ pub(crate) fn doc_revisions(&mut self, a: &Args) -> Result<Value> {
+ let doc = self.doc(a)?;
+ let ends = doc.revision_ends();
+ let sigs = doc.signatures.clone();
+ let list: Vec<Value> = ends
+ .iter()
+ .enumerate()
+ .map(|(i, end)| {
+ let start = if i == 0 { 0 } else { ends[i - 1] };
+ // A signature signs the revision its byte range ends in.
+ let signed: Vec<&str> =
+ sigs.iter().filter(|s| s.signed && s.signed_len > start && s.signed_len <= *end).map(|s| s.field.as_str()).collect();
+ json!({ "revision": i + 1, "end": end, "bytes": end - start, "signed_by": signed })
+ })
+ .collect();
+ Ok(json!({ "revisions": list, "unsaved_changes": doc.dirty }))
+ }
+
+ pub(crate) fn doc_initial_view(&mut self, a: &Args) -> Result<Value> {
+ use pdfcraft_engine::{InitialLayout as L, Magnification as M, Navigation as N};
+ let bad = |m: String| ToolError::InvalidArgs(m);
+ let mut v = self.doc(a)?.initial_view();
+ let before = v.clone();
+ if let Some(n) = a.opt_str("navigation")? {
+ v.navigation = match n {
+ "page" => N::PageOnly,
+ "bookmarks" => N::Bookmarks,
+ "pages" => N::Pages,
+ "attachments" => N::Attachments,
+ "layers" => N::Layers,
+ o => return Err(bad(format!("unknown navigation {o:?}"))),
+ };
+ }
+ if let Some(l) = a.opt_str("layout")? {
+ v.layout = match l {
+ "default" => L::Default,
+ "single" => L::SinglePage,
+ "continuous" => L::SinglePageContinuous,
+ "two_up" => L::TwoUp,
+ "two_up_continuous" => L::TwoUpContinuous,
+ "two_up_cover" => L::TwoUpCoverPage,
+ "two_up_continuous_cover" => L::TwoUpContinuousCoverPage,
+ o => return Err(bad(format!("unknown layout {o:?}"))),
+ };
+ }
+ match a.get("magnification") {
+ None => {}
+ Some(Value::Number(p)) => v.magnification = M::Percent(p.as_f64().unwrap_or(100.0).clamp(1.0, 6400.0)),
+ Some(Value::String(m)) => {
+ v.magnification = match m.as_str() {
+ "default" => M::Default,
+ "actual" => M::ActualSize,
+ "fit_page" => M::FitPage,
+ "fit_width" => M::FitWidth,
+ "fit_height" => M::FitHeight,
+ "fit_visible" => M::FitVisible,
+ o => return Err(bad(format!("unknown magnification {o:?}"))),
+ }
+ }
+ Some(_) => return Err(bad("magnification is a name or a percentage".into())),
+ }
+ if let Some(p) = a.opt_int("page")? {
+ v.page = (p.max(1) - 1) as usize;
+ }
+ for (k, f) in [
+ ("fit_window", &mut v.fit_window),
+ ("center_window", &mut v.center_window),
+ ("full_screen", &mut v.full_screen),
+ ("display_title", &mut v.display_title),
+ ("hide_menubar", &mut v.hide_menubar),
+ ("hide_toolbar", &mut v.hide_toolbar),
+ ("hide_window_ui", &mut v.hide_window_ui),
+ ] {
+ if let Some(b) = a.opt_bool(k)? {
+ *f = b;
+ }
+ }
+ if let Some(l) = a.opt_str("language")? {
+ v.language = (!l.trim().is_empty()).then(|| l.trim().to_string());
+ }
+ if let Some(b) = a.opt_str("binding")? {
+ v.right_to_left = match b {
+ "left" => false,
+ "right" => true,
+ o => return Err(bad(format!("binding is left or right, not {o:?}"))),
+ };
+ }
+ let mut out = if v != before { self.apply(a, Edit::SetInitialView(Box::new(v.clone())))? } else { json!({}) };
+ out["initial_view"] = json!({
+ "navigation": format!("{:?}", v.navigation),
+ "layout": format!("{:?}", v.layout),
+ "magnification": format!("{:?}", v.magnification),
+ "page": v.page + 1,
+ "fit_window": v.fit_window,
+ "center_window": v.center_window,
+ "full_screen": v.full_screen,
+ "display_title": v.display_title,
+ "hide_menubar": v.hide_menubar,
+ "hide_toolbar": v.hide_toolbar,
+ "hide_window_ui": v.hide_window_ui,
+ "language": v.language,
+ "binding": if v.right_to_left { "right" } else { "left" },
+ });
+ Ok(out)
+ }
+
+ pub(crate) fn doc_optimize(&mut self, a: &Args) -> Result<Value> {
+ use pdfcraft_engine::optimize::{Compatibility, Compression, ImageSettings, Preset};
+ let id = self.doc(a)?.id;
+ let before = self.doc(a)?.bytes.len();
+ let path = self.resolve(a.str("path")?, true)?;
+ let mut settings = match a.opt_str("preset")? {
+ None => Preset::Standard.settings(),
+ Some(p) => Preset::from_name(p).ok_or_else(|| ToolError::InvalidArgs(format!("unknown preset {p:?} (standard, mobile)")))?.settings(),
+ };
+ if let Some(c) = a.opt_str("compatibility")? {
+ settings.compatibility = Compatibility::from_name(c)
+ .ok_or_else(|| ToolError::InvalidArgs(format!("unknown compatibility {c:?} (retain, 1.4, 1.5, 1.6, 1.7, 2.0)")))?;
+ }
+ let images = |key: &str, base: ImageSettings| -> Result<ImageSettings> {
+ let Some(v) = a.get(key) else { return Ok(base) };
+ let mut s = base;
+ if let Some(d) = v.get("downsample").and_then(Value::as_bool) {
+ s.downsample = d;
+ }
+ if let Some(p) = v.get("ppi").and_then(Value::as_f64) {
+ s.target_ppi = p.clamp(9.0, 2400.0);
+ }
+ if let Some(p) = v.get("above_ppi").and_then(Value::as_f64) {
+ s.above_ppi = p.clamp(9.0, 2400.0);
+ }
+ s.above_ppi = s.above_ppi.max(s.target_ppi);
+ if let Some(c) = v.get("compression").and_then(Value::as_str) {
+ let q = v.get("quality").and_then(Value::as_u64).unwrap_or(60).clamp(1, 100) as u8;
+ s.compression = match c {
+ "jpeg" => Compression::Jpeg(q),
+ "zip" | "flate" => Compression::Flate,
+ "retain" => Compression::Retain,
+ other => return Err(ToolError::InvalidArgs(format!("unknown compression {other:?} (jpeg, zip, retain)"))),
+ };
+ }
+ Ok(s)
+ };
+ settings.color = images("color", settings.color)?;
+ settings.gray = images("gray", settings.gray)?;
+ for (key, flag) in [
+ ("merge_fragments", &mut settings.merge_fragments),
+ ("discard_thumbnails", &mut settings.discard_thumbnails),
+ ("discard_alternate_images", &mut settings.discard_alternate_images),
+ ("discard_tags", &mut settings.discard_tags),
+ ("discard_print_settings", &mut settings.discard_print_settings),
+ ("flate_unencoded", &mut settings.flate_unencoded),
+ ("object_streams", &mut settings.object_streams),
+ ("lzw_to_flate", &mut settings.lzw_to_flate),
+ ("remove_invalid_links", &mut settings.remove_invalid_links),
+ ("remove_unreferenced_dests", &mut settings.remove_unreferenced_dests),
+ ] {
+ if let Some(b) = a.opt_bool(key)? {
+ *flag = b;
+ }
+ }
+ let discard: Vec<pdfcraft_engine::Hidden> = match a.get("discard") {
+ None => Vec::new(),
+ Some(v) => v
+ .as_array()
+ .ok_or_else(|| ToolError::InvalidArgs("discard must be an array".into()))?
+ .iter()
+ .map(|x| {
+ x.as_str()
+ .and_then(pdfcraft_engine::Hidden::from_id)
+ .ok_or_else(|| ToolError::InvalidArgs(format!("unknown discard category {x}")))
+ })
+ .collect::<Result<_>>()?,
+ };
+ let (bytes, r) = self.session.optimized_bytes(id, &settings, &discard).map_err(failed)?;
+ write_atomic(&path, &bytes)?;
+ fn valid_version(v: &[u8]) -> Option<&str> {
+ if matches!(v, [b'1'..=b'9', b'.', b'0'..=b'9']) { std::str::from_utf8(v).ok() } else { None }
+ }
+ let catalog_version = (settings.compatibility == Compatibility::Retain)
+ .then(|| {
+ let pw = self.doc(a).ok().and_then(|d| d.password.as_deref());
+ let doc = pdfcraft_cos::Document::open_with_password(bytes.clone(), pw).ok()?;
+ let root = doc.root()?;
+ doc.get(root).as_dict()?.name(b"Version").and_then(valid_version).map(str::to_owned)
+ })
+ .flatten();
+ let header_version = bytes.strip_prefix(b"%PDF-").and_then(|b| b.get(..3)).and_then(valid_version);
+ // Viewers read the later of the two (object streams raise the header past a lower catalog
+ // entry). Both are "d.d", so text order is version order.
+ let pdf_version = catalog_version.as_deref().into_iter().chain(header_version).max();
+ let o = &r.optimize;
+ Ok(json!({
+ "path": path.to_string_lossy(),
+ "pdf_version": pdf_version,
+ "object_streams": settings.effective_object_streams(),
+ "bytes_before": before,
+ "bytes_after": bytes.len(),
+ "merged_images": o.merged_images,
+ "fragments_merged": o.fragments_merged,
+ "images": o.images,
+ "images_resampled": o.images_resampled,
+ "images_recompressed": o.images_recompressed,
+ "image_bytes_before": o.image_bytes_before,
+ "image_bytes_after": o.image_bytes_after,
+ "thumbnails": o.thumbnails,
+ "alternate_images": o.alternate_images,
+ "tags_removed": o.tags_removed,
+ "streams_compressed": o.streams_compressed,
+ "lzw_streams": o.lzw_streams,
+ "invalid_links": o.invalid_links,
+ "invalid_bookmarks": o.invalid_bookmarks,
+ "unreferenced_dests": o.unreferenced_dests,
+ "unused_xobjects": o.unused_xobjects,
+ "merged_objects": r.merged,
+ "discarded": r.discarded.iter().map(|(h, n)| json!({ "category": h.id(), "count": n })).collect::<Vec<_>>(),
+ }))
+ }
+
+ /// A watermark or background picture: `file` (an image or a PDF) and `file_page` (1-based).
+ fn mark_file(&self, a: &Args) -> Result<Option<pdfcraft_engine::MarkFile>> {
+ let Some(p) = a.opt_str("file")? else { return Ok(None) };
+ let path = self.resolve(p, false)?;
+ let bytes = read_input(&path)?;
+ let page = a.opt_int("file_page")?.unwrap_or(1).max(1) as usize - 1;
+ Ok(Some(pdfcraft_engine::MarkFile {
+ name: path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
+ bytes: Arc::new(bytes),
+ page,
+ }))
+ }
+
+ pub(crate) fn apply(&mut self, a: &Args, edit: Edit) -> Result<Value> {
+ let id = self.doc(a)?.id;
+ self.session.apply(id, edit).map_err(failed)?;
+ let doc = self.doc(a)?;
+ let mut out = summary(doc);
+ // Text the edit stored as typed but drew with `?` (its font can't draw it): said, not silent.
+ if !doc.edit_notices.is_empty() {
+ out["warnings"] = json!(doc.edit_notices.iter().map(ToString::to_string).collect::<Vec<_>>());
+ }
+ Ok(out)
+ }
+
++ /// Pages whose own backdrop hides a background (see `pdfcraft_edit::backdrop`).
++ pub(crate) fn backdrops(&mut self, a: &Args) -> Result<Value> {
++ let n = self.doc(a)?.info.pages.len();
++ let pages = match a.opt_ints("pages")? {
++ Some(_) => self.pages(a, "pages")?,
++ None => (0..n).collect(),
++ };
++ let doc = self.doc(a)?;
++ let found: Vec<Value> = pages
++ .iter()
++ .zip(doc.page_backdrops(&pages))
++ .filter_map(|(p, found)| {
++ let kind = match found? {
++ pdfcraft_engine::Backdrop::Fill => "fill",
++ pdfcraft_engine::Backdrop::Image => "image",
++ };
++ Some(json!({ "page": p + 1, "backdrop": kind }))
++ })
++ .collect();
++ Ok(json!({ "pages": found }))
++ }
++
+ pub(crate) fn marks(&mut self, tool: &str, a: &Args) -> Result<Value> {
+ use pdfcraft_engine::{Background, HeaderFooter, MarkKind, Watermark};
+ let n = self.doc(a)?.info.pages.len();
+ let pages = match a.opt_ints("pages")? {
+ Some(_) => self.pages(a, "pages")?,
+ None => (0..n).collect(),
+ };
+ let color =
+ |key: &str, default: [f64; 3]| -> Result<[f64; 3]> { Ok(a.opt_str(key)?.map(comments::parse_color).transpose()?.unwrap_or(default)) };
+ let replace = a.opt_bool("replace")?.unwrap_or(false);
+ let edit = match tool {
+ "doc_header_footer" => {
+ let mut hf = HeaderFooter::default();
+ for (k, key) in ["header_left", "header_center", "header_right", "footer_left", "footer_center", "footer_right"].iter().enumerate() {
+ hf.text[k] = a.opt_str(key)?.unwrap_or_default().to_string();
+ }
+ if let Some(s) = a.opt_num("font_size")? {
+ hf.font_size = s;
+ }
+ hf.font = match a.opt_str("font")? {
+ None | Some("Helvetica") => pdfcraft_engine::FontFamily::Helvetica,
+ Some("Times") => pdfcraft_engine::FontFamily::Times,
+ Some("Courier") => pdfcraft_engine::FontFamily::Courier,
+ Some(other) => {
+ return Err(ToolError::InvalidArgs(format!("font must be \"Helvetica\", \"Times\" or \"Courier\", not {other:?}")));
+ }
+ };
+ hf.color = color("color", hf.color)?;
+ if let Some(m) = a.get("margins").and_then(Value::as_array) {
+ let m: Vec<f64> = m.iter().filter_map(Value::as_f64).collect();
+ hf.margins = <[f64; 4]>::try_from(m).map_err(|_| ToolError::InvalidArgs("margins must be 4 numbers".into()))?;
+ }
+ if let Some(s) = a.opt_int("start_number")? {
+ hf.start_number = s.clamp(1, u32::MAX as i64) as u32;
+ }
+ hf.shrink = a.opt_bool("shrink")?.unwrap_or(false);
+ Edit::AddHeaderFooter { pages, settings: hf, replace }
+ }
+ "doc_watermark" => {
+ let d = Watermark::default();
+ let file = self.mark_file(a)?;
+ let text = match &file {
+ Some(_) => a.opt_str("text")?.unwrap_or_default().to_string(),
+ None => a.str("text")?.to_string(),
+ };
+ let wm = Watermark {
+ text,
+ source: None,
+ scale: a.opt_num("scale")?.unwrap_or(d.scale).clamp(0.01, 1.0),
+ font_size: a.opt_num("font_size")?.unwrap_or(0.0),
+ color: color("color", d.color)?,
+ opacity: a.opt_num("opacity")?.unwrap_or(d.opacity),
+ rotation: a.opt_num("rotation")?.unwrap_or(d.rotation),
+ behind: a.opt_bool("behind")?.unwrap_or(false),
+ offset: [
+ a.opt_num("offset_x")?.unwrap_or(0.0).clamp(-WATERMARK_MAX_OFFSET, WATERMARK_MAX_OFFSET),
+ a.opt_num("offset_y")?.unwrap_or(0.0).clamp(-WATERMARK_MAX_OFFSET, WATERMARK_MAX_OFFSET),
+ ],
+ };
+ Edit::AddWatermark { pages, settings: wm, replace, file }
+ }
+ "doc_background" => Edit::AddBackground {
+ pages,
+ settings: Background {
+ color: color("color", [1.0; 3])?,
+ opacity: a.opt_num("opacity")?.unwrap_or(1.0),
+ scale: a.opt_num("scale")?.unwrap_or(1.0).clamp(0.01, 1.0),
++ replace_backdrop: a.opt_bool("replace_backdrop")?.unwrap_or(true),
+ ..Background::default()
+ },
+ replace,
+ file: self.mark_file(a)?,
+ },
+ _ => {
+ let kind = match a.str("kind")? {
+ "header_footer" => MarkKind::HeaderFooter,
+ "watermark" => MarkKind::Watermark,
+ "background" => MarkKind::Background,
+ other => return Err(ToolError::InvalidArgs(format!("unknown kind {other:?}"))),
+ };
+ Edit::RemoveMarks { kind }
+ }
+ };
+ self.apply(a, edit)
+ }
+
+ pub(crate) fn export(&mut self, tool: &str, a: &Args) -> Result<Value> {
+ let doc = self.doc_to_copy(a)?;
+ let pages = match a.opt_ints("pages")? {
+ Some(_) => self.pages(a, "pages")?,
+ None => (0..doc.info.pages.len()).collect(),
+ };
+ let stem = doc.name.trim_end_matches(".pdf").trim_end_matches(".PDF").to_string();
+ let mut ex = pdfcraft_engine::export::Exporter::new(doc);
+ if tool == "doc_export_text" {
+ let path = self.resolve(a.str("path")?, true)?;
+ let text = ex.text_of(&pages).map_err(failed)?;
+ write_atomic(&path, text.as_bytes())?;
+ return Ok(json!({ "path": path.to_string_lossy(), "pages": pages.len(), "bytes": text.len() }));
+ }
+ let folder = self.resolve(a.str("folder")?, true)?;
+ std::fs::create_dir_all(&folder).map_err(|e| failed(format!("{}: {e}", folder.display())))?;
+ if tool == "doc_export_all_images" {
+ let min = u32::try_from(a.opt_int("min_size")?.unwrap_or(0).max(0)).unwrap_or(u32::MAX);
+ let out = pdfcraft_engine::export::extract_images(&doc.export_source(), &pages, min).map_err(failed)?;
+ let mut files = Vec::new();
+ for (k, img) in out.images.iter().enumerate() {
+ let path = child(&folder, &pdfcraft_engine::export::image_file_name(&stem, img, k + 1, doc.info.pages.len()));
+ write_atomic(&path, &img.data)?;
+ files.push(json!({ "path": path.to_string_lossy(), "page": img.page + 1, "width": img.width, "height": img.height }));
+ }
+ let skipped: Vec<Value> = out.skipped.iter().map(|(p, r, why)| json!({ "page": p + 1, "object": r.num, "reason": why })).collect();
+ return Ok(json!({ "count": files.len(), "files": files, "skipped": skipped }));
+ }
+ let dpi = a.opt_num("dpi")?.unwrap_or(150.0);
+ let quality = a.opt_int("quality")?.unwrap_or(85).clamp(1, 100) as u8;
+ let format = match a.opt_str("format")?.unwrap_or("png") {
+ "png" => pdfcraft_engine::export::ImageFormat::Png,
+ "jpeg" | "jpg" => pdfcraft_engine::export::ImageFormat::Jpeg { quality },
+ "tiff" | "tif" => pdfcraft_engine::export::ImageFormat::Tiff,
+ f => return Err(ToolError::InvalidArgs(format!("unknown format {f:?} (png, jpeg, tiff)"))),
+ };
+ let mut files = Vec::new();
+ let mut lowered = Vec::new();
+ for p in pages {
+ let img = ex.image(p, dpi, format).map_err(failed)?;
+ let path = child(&folder, &format!("{stem}_page_{}.{}", p + 1, format.extension()));
+ write_atomic(&path, &img)?;
+ files.push(path.to_string_lossy().into_owned());
+ // A page too large for the renderer at `dpi` is drawn at the most it allows.
+ let used = ex.dpi_used(p, dpi);
+ if used < dpi.clamp(18.0, 1200.0) - 0.5 {
+ lowered.push(json!({ "page": p + 1, "dpi": used.floor() }));
+ }
+ }
+ if lowered.is_empty() {
+ Ok(json!({ "count": files.len(), "files": files }))
+ } else {
+ Ok(json!({ "count": files.len(), "files": files, "lower_dpi": lowered }))
+ }
+ }
+
+ pub(crate) fn doc_protect(&mut self, a: &Args) -> Result<Value> {
+ use pdfcraft_engine::{Algorithm, Changes, Printing, Protection};
+ let d = Protection::default();
+ // Restrictions only exist behind a permissions password (ISO 32000-2 §7.6.4.4: /P is
+ // enforced against the owner password; without one everything stays allowed). Refuse a
+ // restriction that could not take effect instead of writing an unrestricted file (#134).
+ let restriction = ["printing", "changes", "copy", "accessibility"].into_iter().find(|k| a.get(k).is_some());
+ if let (None, Some(key)) = (a.opt_str("permissions_password")?, restriction) {
+ return Err(ToolError::InvalidArgs(format!(
+ "`{key}` needs `permissions_password`: with open_password alone the document is encrypted but nothing is restricted"
+ )));
+ }
+ let p = Protection {
+ open_password: a.opt_str("open_password")?.map(str::to_owned),
+ permissions_password: a.opt_str("permissions_password")?.map(str::to_owned),
+ printing: match a.opt_str("printing")? {
+ None => d.printing,
+ Some("none") => Printing::None,
+ Some("low") => Printing::Low,
+ Some("high") => Printing::High,
+ Some(o) => return Err(ToolError::InvalidArgs(format!("unknown printing {o:?}"))),
+ },
+ changes: match a.opt_str("changes")? {
+ None => d.changes,
+ Some("none") => Changes::None,
+ Some("pages") => Changes::Pages,
+ Some("fill-sign") => Changes::FillSign,
+ Some("comment-fill-sign") => Changes::CommentFillSign,
+ Some("any-except-extract") => Changes::AnyExceptExtract,
+ Some(o) => return Err(ToolError::InvalidArgs(format!("unknown changes {o:?}"))),
+ },
+ copy: a.opt_bool("copy")?.unwrap_or(d.copy),
+ accessibility: a.opt_bool("accessibility")?.unwrap_or(d.accessibility),
+ algorithm: match a.opt_str("compatibility")? {
+ None | Some("aes-256") => Algorithm::Aes256,
+ Some("aes-128") => Algorithm::Aes128,
+ Some("rc4-128") => Algorithm::Rc4_128,
+ Some("rc4-40") => Algorithm::Rc4_40,
+ Some(o) => return Err(ToolError::InvalidArgs(format!("unknown compatibility {o:?}"))),
+ },
+ encrypt_metadata: a.opt_bool("encrypt_metadata")?.unwrap_or(d.encrypt_metadata),
+ };
+ let mut out = self.apply(a, Edit::Protect(p))?;
+ out["security"] = security(self.doc(a)?);
+ Ok(out)
+ }
+ }
diff --cc crates/edit/src/apply.rs
index 000000000,1461dc78e..81ba9aa8d
mode 000000,100644..100644
--- a/crates/edit/src/apply.rs
+++ b/crates/edit/src/apply.rs
@@@ -1,0 -1,291 +1,301 @@@
+ use super::marks::{
+ Background, Context, HeaderFooter, MarkKind, Watermark, add_picture_resource, bates_start, expand, matrix_number, n, picture, rgb, shrink_matrix,
+ };
+ use super::place::{
+ END, Isolation, add_page_resources, add_resources, begin, check, check_on_top, contents, free_font_name, isolation, page_fonts, page_list, place,
+ place_inside_wrapper, stream_tag, text_op, undrawable, wrapper_role,
+ };
+ use super::*;
+
+ /// Add a header and footer to `pages` (0-based). With `replace`, existing headers and footers on
+ /// those pages are removed first (Acrobat's Replace Existing).
+ pub fn add_header_footer(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replace: bool, cx: &Context) -> Result<(), EditError> {
+ let all = page_list(doc);
+ check(pages, all.len())?;
+ if hf.text.iter().all(|t| t.trim().is_empty()) {
+ return Err(EditError::Invalid("type the header or footer text first".into()));
+ }
+ if let Some(c) = hf.first_undrawable() {
+ return Err(undrawable(c));
+ }
+ if !(hf.font_size.is_finite() && hf.font_size > 0.0 && hf.font_size <= 200.0 && hf.margins.iter().all(|m| m.is_finite() && *m >= 0.0)) {
+ return Err(EditError::Invalid("invalid font size or margins".into()));
+ }
+ // Page numbers count up from start_number, so the last selected page needs the most room.
+ // Refuse the whole run before drawing anything: headers applied to some pages and then a
+ // failed page number would leave the document half changed.
+ let last_number = u64::from(hf.start_number)
+ .checked_add(pages.len().saturating_sub(1) as u64)
+ .ok_or_else(|| EditError::Invalid("the header page numbers are too large".into()))?;
+ if last_number > u64::from(u32::MAX) {
+ return Err(EditError::Invalid(format!(
+ "the header start number {} leaves no room for {} pages (page numbers stop at {})",
+ hf.start_number,
+ pages.len(),
+ u32::MAX
+ )));
+ }
+ // The same goes for Bates numbers: the last selected page must still fit in a u64.
+ let bates0 = hf.text.iter().find_map(|t| bates_start(t)).unwrap_or(1);
+ if bates0.checked_add(pages.len().saturating_sub(1) as u64).is_none() {
+ return Err(EditError::Invalid(format!(
+ "the Bates start number {bates0} leaves no room for {} pages (Bates numbers stop at {})",
+ pages.len(),
+ u64::MAX
+ )));
+ }
+ // Shrinking needs room on every page: refuse before anything is drawn or replaced.
+ let shrinks = pages
+ .iter()
+ .map(|&i| hf.shrink.then(|| shrink_matrix(hf, all[i].display_size(doc), all[i].view_matrix(doc))).transpose())
+ .collect::<Result<Vec<_>, _>>()?;
+ for &i in pages {
+ check_on_top(doc, &all[i])?;
+ }
+ if replace {
+ remove_marks(doc, pages, MarkKind::HeaderFooter)?;
+ }
+ let all = page_list(doc);
+ let count = all.len();
+ for (k, &i) in pages.iter().enumerate() {
+ let page = &all[i];
+ let (w, h) = page.display_size(doc);
+ let number =
+ u32::try_from(u64::from(hf.start_number) + k as u64).map_err(|_| EditError::Invalid("the header page numbers are too large".into()))?;
+ let bates = bates0.checked_add(k as u64).ok_or_else(|| EditError::Invalid("the Bates numbers are too large".into()))?;
+ let size = hf.font_size;
+ let [top, bottom, left, right] = hf.margins;
+ // The page resource the face is added under: the usual name, unless the page already
+ // draws another font by it, which must not change under the header.
+ let preferred = match hf.font {
+ added::Family::Helvetica => "PCHelv",
+ added::Family::Times => "PCTimes",
+ added::Family::Courier => "PCCour",
+ };
+ let base = hf.font.base_font(false, false);
+ let resource = free_font_name(doc, &page_fonts(doc, page), preferred, base);
+ let mut body: Vec<u8> = format!("BT\n/{resource} {} Tf\n{}\n", n(size), rgb(hf.color)).into_bytes();
+ let mut underlines = String::new();
+ for (slot, template) in hf.text.iter().enumerate() {
+ if template.trim().is_empty() {
+ continue;
+ }
+ let lines: Vec<String> = expand(template, number, count, bates, cx).lines().map(str::to_owned).collect();
+ let header = slot < 3;
+ let line_h = size * 1.2;
+ for (li, line) in lines.iter().enumerate() {
+ // Centred and right-aligned text is placed by its width in the chosen face.
+ let tw = hf.font.width(line, size, false, false);
+ let x = match slot % 3 {
+ 0 => left,
+ 1 => (w - tw) / 2.0,
+ _ => w - right - tw,
+ };
+ // Headers hang below the top margin; footers sit on the bottom margin.
+ let y = if header { h - top - size * 0.8 - li as f64 * line_h } else { bottom + (lines.len() - 1 - li) as f64 * line_h };
+ body.extend(text_op(x, y, line));
+ if hf.underline {
+ underlines.push_str(&format!("{} {} {} {} re f\n", n(x), n(y - size * 0.15), n(tw), n((size * 0.06).max(0.4))));
+ }
+ }
+ }
+ body.extend_from_slice(b"ET\n");
+ if !underlines.is_empty() {
+ body.extend(format!("{}\n{underlines}", rgb(hf.color)).bytes());
+ }
+ let mut content = begin(MarkKind::HeaderFooter, "Header", page.view_matrix(doc)).into_bytes();
+ content.extend(body);
+ content.extend_from_slice(END.as_bytes());
+ // A name already there is that very font (see `free_font_name`): left as it is.
+ if !page_fonts(doc, page).contains(resource.as_bytes()) {
+ add_page_resources(doc, page, None, &[(resource.into_bytes(), base)])?;
+ }
+ let page = &page_list(doc)[i];
+ place(doc, page, MarkKind::HeaderFooter, content, false)?;
+ if let Some(Some(m)) = shrinks.get(k) {
+ let cm = format!("{} cm\n", m.map(matrix_number).join(" "));
+ let page = &page_list(doc)[i];
+ place_inside_wrapper(doc, page, MarkKind::HeaderFooter.tag(), cm.into_bytes())?;
+ }
+ }
+ Ok(())
+ }
+
+ /// Add a text watermark to `pages`.
+ pub fn add_watermark(doc: &mut Document, pages: &[usize], wm: &Watermark, replace: bool) -> Result<(), EditError> {
+ let all = page_list(doc);
+ check(pages, all.len())?;
+ let text = wm.text.trim();
+ if text.is_empty() && wm.source.is_none() {
+ return Err(EditError::Invalid("type the watermark text first".into()));
+ }
+ if let Some(c) = wm.first_undrawable() {
+ return Err(undrawable(c));
+ }
+ if !(wm.opacity.is_finite()
+ && wm.rotation.is_finite()
+ && wm.font_size.is_finite()
+ && wm.font_size >= 0.0
+ && wm.offset.iter().all(|o| o.is_finite()))
+ {
+ return Err(EditError::Invalid("invalid watermark settings".into()));
+ }
+ if !wm.behind {
+ for &i in pages {
+ check_on_top(doc, &all[i])?;
+ }
+ }
+ if replace {
+ remove_marks(doc, pages, MarkKind::Watermark)?;
+ }
+ let opacity = wm.opacity.clamp(0.0, 1.0);
+ let lines: Vec<&str> = text.lines().collect();
+ for &i in pages {
+ let page = page_list(doc)[i].clone();
+ let (w, h) = page.display_size(doc);
+ if let Some(src) = &wm.source {
+ let mut content = begin(MarkKind::Watermark, "Watermark", page.view_matrix(doc));
+ content.push_str(&format!("/PCGS{} gs\n", (opacity * 100.0).round() as i64));
+ content.push_str(&picture(src, (w, h), wm.scale, wm.rotation, wm.offset));
+ content.push_str(END);
+ add_resources(doc, &page, Some(opacity), None)?;
+ add_picture_resource(doc, &page_list(doc)[i].clone(), src)?;
+ let page = &page_list(doc)[i];
+ place(doc, page, MarkKind::Watermark, content.into_bytes(), wm.behind)?;
+ continue;
+ }
+ let widest = lines.iter().map(|l| helvetica_width(l, 1.0)).fold(0.0, f64::max).max(0.01);
+ let size = if wm.font_size > 0.0 { wm.font_size } else { ((w * w + h * h).sqrt() * 0.5 / widest).clamp(6.0, 300.0) };
+ let (s, c) = wm.rotation.to_radians().sin_cos();
+ let (cx, cy) = (w / 2.0 + wm.offset[0], h / 2.0 + wm.offset[1]);
+ let mut content = begin(MarkKind::Watermark, "Watermark", page.view_matrix(doc)).into_bytes();
+ content.extend(
+ format!(
+ "/PCGS{} gs\n{} {} {} {} {} {} cm\nBT\n/PCHelv {} Tf\n{}\n",
+ (opacity * 100.0).round() as i64,
+ n(c),
+ n(s),
+ n(-s),
+ n(c),
+ n(cx),
+ n(cy),
+ n(size),
+ rgb(wm.color)
+ )
+ .bytes(),
+ );
+ let line_h = size * 1.15;
+ let total = line_h * (lines.len() as f64 - 1.0);
+ for (li, line) in lines.iter().enumerate() {
+ let tw = helvetica_width(line, size);
+ content.extend(text_op(-tw / 2.0, total / 2.0 - li as f64 * line_h - size * 0.35, line));
+ }
+ content.extend_from_slice(b"ET\n");
+ content.extend_from_slice(END.as_bytes());
+ add_resources(doc, &page, Some(opacity), None)?;
+ let page = &page_list(doc)[i];
+ place(doc, page, MarkKind::Watermark, content, wm.behind)?;
+ }
+ Ok(())
+ }
+
-/// Add a solid-colour background behind the content of `pages`.
++/// Add a solid-colour background behind the content of `pages`. With `bg.replace_backdrop`, a
++/// white backdrop a page paints itself is replaced first, so the background shows (see
++/// [`backdrop`]); a picture backdrop (a scan) still hides it.
+ pub fn add_background(doc: &mut Document, pages: &[usize], bg: &Background, replace: bool) -> Result<(), EditError> {
+ let all = page_list(doc);
+ check(pages, all.len())?;
+ if replace {
+ remove_marks(doc, pages, MarkKind::Background)?;
+ }
+ let opacity = if bg.opacity.is_finite() { bg.opacity.clamp(0.0, 1.0) } else { 1.0 };
+ for &i in pages {
- let page = page_list(doc)[i].clone();
++ let mut page = page_list(doc)[i].clone();
++ if bg.replace_backdrop && backdrop::replace(doc, &page)? {
++ page = page_list(doc)[i].clone();
++ }
+ let (w, h) = page.display_size(doc);
+ let mut content = begin(MarkKind::Background, "Background", page.view_matrix(doc));
+ match &bg.source {
+ Some(src) => {
+ content.push_str(&format!("/PCGS{} gs\n", (opacity * 100.0).round() as i64));
+ content.push_str(&picture(src, (w, h), bg.scale, 0.0, [0.0; 2]));
+ }
+ None => content.push_str(&format!("/PCGS{} gs\n{}\n0 0 {} {} re f\n", (opacity * 100.0).round() as i64, rgb(bg.color), n(w), n(h))),
+ }
+ content.push_str(END);
+ add_resources(doc, &page, Some(opacity), None)?;
+ if let Some(src) = &bg.source {
+ add_picture_resource(doc, &page_list(doc)[i].clone(), src)?;
+ }
+ let page = &page_list(doc)[i];
+ place(doc, page, MarkKind::Background, content.into_bytes(), true)?;
+ }
+ Ok(())
+ }
+
+ /// Remove marks of `kind` from `pages`; returns how many were removed. Wrappers left with
+ /// nothing after them go too, restoring the original content list; a wrapper that content
-/// after it still relies on (another tool's appended stream) stays.
++/// after it still relies on (another tool's appended stream) stays. Removing backgrounds also
++/// turns a backdrop [`add_background`] replaced back on where that is still safe; the pages where
++/// it isn't are [`backdrops_left_off`].
+ pub fn remove_marks(doc: &mut Document, pages: &[usize], kind: MarkKind) -> Result<usize, EditError> {
+ let all = page_list(doc);
+ check(pages, all.len())?;
+ let mut removed = 0;
+ for &i in pages {
+ let page = &all[i];
++ if kind == MarkKind::Background {
++ backdrop::restore(doc, page)?;
++ }
+ let list = contents(doc, page)?;
+ let before = list.len();
+ let mut kept: Vec<Object> = list.into_iter().filter(|o| stream_tag(doc, o).as_deref() != Some(kind.tag())).collect();
+ removed += before - kept.len();
+ // Strip only wrapper pairs whose close ends the list (after stripping the pairs after
+ // it): nothing comes after them to need the state they restore. Pairs come from the
+ // operators; for content that can't be read that precisely, from the wrapper streams
+ // alone, so updating a mark there doesn't nest another wrapper each time.
+ if before != kept.len() {
+ let wrappers = match isolation(doc, &kept) {
+ Isolation::Clean { wrappers, .. } => wrappers,
+ Isolation::Unknown { .. } | Isolation::TooDeep => {
+ let mut opens = Vec::new();
+ let mut pairs = Vec::new();
+ for (i, o) in kept.iter().enumerate() {
+ match wrapper_role(doc, o) {
+ Some(true) => opens.push(i),
+ Some(false) => pairs.extend(opens.pop().map(|open| (open, i))),
+ None => {}
+ }
+ }
+ pairs
+ }
+ };
+ let pairs: std::collections::HashMap<usize, usize> = wrappers.into_iter().map(|(open, close)| (close, open)).collect();
+ let mut discarded = std::collections::HashSet::new();
+ let mut end = kept.len();
+ while let Some(close) = end.checked_sub(1) {
+ if discarded.contains(&close) {
+ end = close;
+ } else if let Some(&open) = pairs.get(&close) {
+ discarded.insert(open);
+ discarded.insert(close);
+ end = close;
+ } else {
+ break;
+ }
+ }
+ kept = kept.into_iter().enumerate().filter(|(i, _)| !discarded.contains(i)).map(|(_, o)| o).collect();
+ }
+ if before != kept.len() {
+ doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(kept)))?;
+ }
+ }
+ Ok(removed)
+ }
+
+ /// Which kinds of marks the document has (for enabling Update/Remove).
+ pub fn marks_present(doc: &Document) -> Vec<MarkKind> {
+ added::scan_markers(doc).marks
+ }
diff --cc crates/edit/src/backdrop.rs
index 72438deda,000000000..156501d95
mode 100644,000000..100644
--- a/crates/edit/src/backdrop.rs
+++ b/crates/edit/src/backdrop.rs
@@@ -1,563 -1,0 +1,563 @@@
+//! A page's own backdrop: an opaque white fill (or a picture) covering the whole visible page
+//! before anything else is drawn. Many writers paint one (browsers' Save as PDF, print drivers;
+//! scans are a page-sized picture), and it hides anything placed behind the content, so a
+//! background added behind such a page never shows.
+//!
+//! A white fill can be replaced: the one fill operator becomes `n` (end the path without
+//! painting), which looks the same on white paper. The page then gets a copy of the content
+//! stream that held it, tagged `/PCBackdrop << /Index n /Op (f) /Before <SHA-256> /Was [num gen] >>`:
+//! how many of the copy's operators come before the `n`, the operator it stands in for, a hash of
+//! those operators (their values, not their spacing: redaction writes a stream out again with
+//! other whitespace), and the number of the stream it was copied from. The stream itself is left
+//! alone (other pages may share it). [`restore`] turns the fill back on when the background is
+//! removed, even after the page was edited or redacted, as long as the operators before the fill
+//! are unchanged and the fill would again be the first thing painted, covering the page.
+//! Otherwise the fill stays off, and [`backdrops_left_off`] names those pages. A picture can't be
+//! replaced without losing it, so it is only reported.
+//!
+//! The tag holds no page content and no reference that keeps another object alive (`/Was` is two
+//! numbers, not a reference): a reference to the original stream would keep text in the file
+//! that a redaction, Remove Hidden Information or Edit Text removed from the copy.
+//!
+//! Detection is deliberately strict: only one rectangle (`re`), in DeviceGray, DeviceRGB or
+//! DeviceCMYK, opaque, unmasked, normally blended and with the identity transfer function as the
+//! graphics state stands after every `gs` so far (each sets only its own keys), with an
+//! axis-aligned transform, filled before any other painting, and covering the crop box.
+//! Anything else is real content and stays.
+
+use pdfcraft_content::{Matrix, Op, Pieces};
+use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString, Stream};
+use sha2::{Digest, Sha256};
+
+use crate::{EditError, MarkKind};
+
+/// The dictionary key of a backdrop copy's tag.
+const TAG: &[u8] = b"PCBackdrop";
+/// The fill operators a backdrop can be painted with, and so the only ones a tag may restore.
+const FILLS: [&[u8]; 3] = [b"f", b"F", b"f*"];
+
+/// How much of a page's content is read looking for a backdrop: it has to come first.
+const SCAN_BYTES: usize = 64 * 1024;
+/// How many operators are walked before giving up.
+const SCAN_OPS: usize = 4096;
+/// How far (in points) a backdrop may fall short of the crop box and still count as covering it.
+const COVER_EPS: f64 = 1.0;
+/// Components at least this close to white (per channel) count as white: a near-white fill
+/// (`0.99 g`) is a backdrop too, and replacing it changes the page by at most 2%.
+const WHITE: f64 = 0.98;
+
+/// What paints a page's backdrop.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Backdrop {
+ /// An opaque white fill: replaceable.
+ Fill,
+ /// A picture covering the page (a scan): a background behind it stays hidden.
+ Image,
+}
+
+/// Where a replaceable fill is: the content streams (references in `/Contents` order, untagged
+/// ones only), their joined bytes, where each starts in them, and the fill operator's joined
+/// byte range.
+struct Found {
+ refs: Vec<(usize, ObjRef)>,
+ pieces: Pieces,
+ starts: Vec<usize>,
+ op: std::ops::Range<usize>,
+}
+
+impl Found {
+ /// The piece holding the fill operator, and the operator's offset in it.
+ fn place(&self) -> Option<(usize, usize)> {
+ let piece = self.pieces.piece_of(self.op.start);
+ Some((piece, self.op.start.checked_sub(*self.starts.get(piece)?)?))
+ }
+}
+
+#[derive(Clone)]
+struct State {
+ ctm: Matrix,
+ /// Clip in default user space, when it is a known rectangle; `None` = unknown shape.
+ clip: Option<[f64; 4]>,
+ /// The fill colour is white.
+ white: bool,
+ /// Non-stroking colour space components (1, 3, 4), or 0 for a space we don't read.
+ space: usize,
+ paint: Paint,
+}
+
+/// The graphics-state parameters (ExtGState, ISO 32000-2 §8.4.5) that decide whether a fill
+/// paints its colour as given. A `gs` sets only the keys its dictionary has, so each is kept on
+/// its own: a later dictionary that leaves one out keeps the earlier value.
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct Paint {
+ /// Non-stroking alpha (`ca`) is 1.
+ full_alpha: bool,
+ /// No soft mask (`SMask` is `/None`).
+ no_soft_mask: bool,
+ /// The blend mode (`BM`) is Normal or Compatible.
+ normal_blend: bool,
+ /// The transfer function (`TR`, or `TR2`, which takes precedence) is the identity: a
+ /// function could turn white into any colour.
+ identity_transfer: bool,
+}
+
+impl Paint {
+ const INITIAL: Paint = Paint { full_alpha: true, no_soft_mask: true, normal_blend: true, identity_transfer: true };
+
+ /// A fill paints its colour exactly, opaque.
+ fn plain(self) -> bool {
+ self.full_alpha && self.no_soft_mask && self.normal_blend && self.identity_transfer
+ }
+}
+
+/// The backdrop `page` (0-based) paints, if any. Finding the page walks the page tree, so to
+/// check many pages use [`page_backdrops`], which walks it once.
+pub fn page_backdrop(doc: &Document, page: usize) -> Result<Option<Backdrop>, EditError> {
+ let all = pdfcraft_model::pages(doc);
+ let p = all.get(page).ok_or(EditError::NoSuchPage(page))?;
+ Ok(scan(doc, p, None).map(|(b, _)| b))
+}
+
+/// The backdrop each of `pages` (0-based) paints, in the same order, walking the page tree once.
+/// A page past the end has none, and doesn't hide what the others paint: a page count taken
+/// elsewhere (the viewer's) can disagree with the page tree's on a malformed document.
+pub fn page_backdrops(doc: &Document, pages: &[usize]) -> Vec<Option<Backdrop>> {
+ let all = pdfcraft_model::pages(doc);
+ pages.iter().map(|&p| all.get(p).and_then(|page| scan(doc, page, None)).map(|(b, _)| b)).collect()
+}
+
+/// Pages (0-based, ascending) whose own white backdrop [`replace`] turned off and [`restore`]
+/// couldn't turn back on: a tagged copy is still in their content, with no background over it.
+/// They look the same on white paper.
+pub fn backdrops_left_off(doc: &Document) -> Vec<usize> {
- let tag_of = |o: &Object| crate::stream_tag(doc, o);
++ let tag_of = |o: &Object| crate::place::stream_tag(doc, o);
+ let copy = |o: &Object| doc.resolve(o).as_dict().is_some_and(|d| d.get(TAG).is_some());
+ pdfcraft_model::pages(doc)
+ .iter()
+ .enumerate()
+ .filter(|(_, p)| {
+ let list: Vec<Object> = match p.dict.get(b"Contents").map(|c| doc.resolve(c)).as_deref() {
+ Some(Object::Array(a)) => a.clone(),
+ Some(_) => p.dict.get(b"Contents").cloned().into_iter().collect(),
+ None => Vec::new(),
+ };
+ list.iter().any(copy) && !list.iter().any(|o| tag_of(o).as_deref() == Some(MarkKind::Background.tag()))
+ })
+ .map(|(i, _)| i)
+ .collect()
+}
+
+/// Replace `page`'s white backdrop fill, if it has one (see the module doc). Returns whether it
+/// did; when it did, `page` no longer matches the document. A picture backdrop is left alone.
+pub(crate) fn replace(doc: &mut Document, page: &pdfcraft_model::Page) -> Result<bool, EditError> {
+ let Some((Backdrop::Fill, Some(found))) = scan(doc, page, None) else { return Ok(false) };
+ let Some((piece, at)) = found.place() else { return Ok(false) };
+ let op = found.pieces.data().get(found.op.clone()).unwrap_or_default().to_vec();
+ let edited = found.pieces.splice([(found.op.clone(), b"n".to_vec())]);
+ let (Some(&(_, original)), Some(bytes)) = (found.refs.get(piece), edited.get(piece)) else { return Ok(false) };
+ // The `n` among the copy's own operators. A copy whose fill can't be found that way again is
+ // not made: there would be no safe way back.
+ let parsed = pdfcraft_content::parse(head(bytes));
+ let Some(index) = parsed.ops.iter().position(|o| o.span.start == at && o.op == b"n") else { return Ok(false) };
+ let Some(before) = parsed.ops.get(..index) else { return Ok(false) };
+ let mut note = Dict::new();
+ note.set(b"Index".to_vec(), Object::Int(i64::try_from(index).unwrap_or(i64::MAX)));
+ note.set(b"Op".to_vec(), Object::String(PdfString::literal(op)));
+ note.set(b"Before".to_vec(), Object::String(PdfString { bytes: ops_hash(before), hex: true }));
+ note.set(b"Was".to_vec(), Object::Array(vec![Object::Int(original.num.into()), Object::Int(original.generation.into())]));
+ // The copy keeps the original's dictionary (unknown entries included) less what describes
+ // the old encoding; `scan` refused streams whose bytes live in an external file (`/F`).
+ let Object::Stream(source) = &*doc.get(original) else { return Ok(false) };
+ let mut dict = source.dict.clone();
+ for key in [&b"Length"[..], b"DL", TAG] {
+ dict.remove(key);
+ }
+ dict.set(TAG.to_vec(), Object::Dict(note));
+ let copy = doc.add(Object::Stream(Stream::flate(dict, bytes)));
+ // Every slot that draws the original: a page may list the same stream twice, and a second
+ // copy of the fill would cover the background again.
- let mut list = crate::contents(doc, page)?;
++ let mut list = crate::place::contents(doc, page)?;
+ let mut replaced = false;
+ for entry in list.iter_mut().filter(|o| matches!(o, Object::Ref(r) if *r == original)) {
+ *entry = Object::Ref(copy);
+ replaced = true;
+ }
+ if replaced {
+ doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(list)))?;
+ }
+ Ok(replaced)
+}
+
+/// Turn the fills [`replace`] turned off on `page` back on, where [`restored_copy`] finds that
+/// safe; a copy listed in several slots is restored in each. Returns how many slots it restored.
+/// A copy it can't restore stays as it is, tag and all, so [`backdrops_left_off`] names its page.
+pub(crate) fn restore(doc: &mut Document, page: &pdfcraft_model::Page) -> Result<usize, EditError> {
- let mut list = crate::contents(doc, page)?;
++ let mut list = crate::place::contents(doc, page)?;
+ // Per copy: the stream that takes its place, or `None` when it stays.
+ let mut done: Vec<(ObjRef, Option<ObjRef>)> = Vec::new();
+ let mut restored = 0;
+ for entry in list.iter_mut() {
+ let Object::Ref(copy) = *entry else { continue };
+ let with = match done.iter().find(|(c, _)| *c == copy) {
+ Some(&(_, with)) => with,
+ None => {
+ let with = restored_copy(doc, page, copy).map(|(bytes, dict, was)| {
+ // The stream it was copied from, while that is still here with these bytes
+ // (other pages may share it): the page is then exactly as it was. `/Was` is
+ // only a number, and a full save renumbers objects, so the bytes decide.
+ let same = |w: &ObjRef| match &*doc.get(*w) {
+ Object::Stream(s) => {
+ [TAG, &b"PCMark"[..], b"Subtype"].iter().all(|k| s.dict.get(k).is_none())
+ && s.decoded().ok().as_deref() == Some(bytes.as_slice())
+ }
+ _ => false,
+ };
+ match was.filter(same) {
+ Some(w) => w,
+ None => doc.add(Object::Stream(Stream::flate(dict, &bytes))),
+ }
+ });
+ done.push((copy, with));
+ with
+ }
+ };
+ if let Some(with) = with {
+ *entry = Object::Ref(with);
+ restored += 1;
+ }
+ }
+ if restored > 0 {
+ doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(list)))?;
+ }
+ Ok(restored)
+}
+
+/// `copy` (a stream [`replace`] wrote for `page`) with its fill turned back on: the bytes, its
+/// dictionary without the tag, and the stream it was copied from. `None` when it isn't such a
+/// copy, or when turning the fill on could paint over something: the operators before the fill
+/// changed since (their hash no longer matches), or the page would no longer paint the fill
+/// first, covering it. What comes after the fill (an edit, a redaction) is kept as it is.
+fn restored_copy(doc: &Document, page: &pdfcraft_model::Page, copy: ObjRef) -> Option<(Vec<u8>, Dict, Option<ObjRef>)> {
+ let obj = doc.get(copy);
+ let Object::Stream(s) = &*obj else { return None };
+ let note = s.dict.get(TAG).map(|n| doc.resolve(n))?;
+ let note = note.as_dict()?;
+ let index = usize::try_from(note.get(b"Index")?.as_int()?).ok()?;
+ let op = note.get(b"Op")?.as_string()?.bytes.as_slice();
+ if !FILLS.contains(&op) {
+ return None;
+ }
+ let hash = note.get(b"Before")?.as_string()?;
+ let bytes = s.decoded().ok()?;
+ let parsed = pdfcraft_content::parse(head(&bytes));
+ // The `n` standing in for the fill, after exactly the operators that came before it.
+ let fill = parsed.ops.get(index)?;
+ if fill.op != b"n" || !fill.operands.is_empty() || ops_hash(parsed.ops.get(..index)?) != hash.bytes {
+ return None;
+ }
+ let mut out = Vec::with_capacity(bytes.len().saturating_add(op.len()));
+ out.extend_from_slice(bytes.get(..fill.span.start)?);
+ out.extend_from_slice(op);
+ out.extend_from_slice(bytes.get(fill.span.end..)?);
+ let (Backdrop::Fill, Some(found)) = scan(doc, page, Some((copy, &out)))? else { return None };
+ let (piece, offset) = found.place()?;
+ if found.refs.get(piece).map(|&(_, r)| r) != Some(copy) || offset != fill.span.start || found.op.len() != op.len() {
+ return None;
+ }
+ let mut dict = s.dict.clone();
+ for key in [&b"Length"[..], b"DL", TAG] {
+ dict.remove(key);
+ }
+ let was = match note.get(b"Was").and_then(Object::as_array).map(Vec::as_slice) {
+ Some([num, generation]) => Some(ObjRef { num: u32::try_from(num.as_int()?).ok()?, generation: u16::try_from(generation.as_int()?).ok()? }),
+ _ => None,
+ };
+ Some((out, dict, was))
+}
+
+/// As much of a content stream as a backdrop could be in: it has to come first.
+fn head(bytes: &[u8]) -> &[u8] {
+ bytes.get(..bytes.len().min(SCAN_BYTES)).unwrap_or_default()
+}
+
+/// A SHA-256 of what `ops` are, not how they are written: keywords and operand values, with
+/// numbers in one form (`1`, `1.0` and `1.00000` are the same), so a stream written out again
+/// with other spacing or number formatting still matches.
+fn ops_hash(ops: &[Op]) -> Vec<u8> {
+ let mut h = Sha256::new();
+ for op in ops {
+ for o in &op.operands {
+ canonical(o, &mut h, 0);
+ }
+ if let Some((dict, data)) = &op.inline {
+ canonical_dict(dict, &mut h, 0);
+ bytes(b'i', data, &mut h);
+ }
+ bytes(b'k', &op.op, &mut h);
+ }
+ h.finalize().to_vec()
+}
+
+/// How deep [`canonical`] follows nested arrays and dictionaries; deeper ones count as equal.
+const CANONICAL_DEPTH: usize = 32;
+
+fn canonical(o: &Object, h: &mut Sha256, depth: usize) {
+ if depth > CANONICAL_DEPTH {
+ h.update(b"~");
+ return;
+ }
+ match o {
+ Object::Null => h.update(b"z"),
+ Object::Bool(b) => h.update(if *b { b"T" } else { b"F" }),
+ Object::Int(i) => number(&i.to_string(), h),
+ Object::Real(r) if *r == 0.0 => number("0", h),
+ Object::Real(r) => number(&format!("{r:.5}"), h),
+ Object::String(s) => bytes(b's', &s.bytes, h),
+ Object::Name(n) => bytes(b'/', n, h),
+ Object::Array(a) => {
+ h.update(b"[");
+ for x in a {
+ canonical(x, h, depth.saturating_add(1));
+ }
+ h.update(b"]");
+ }
+ Object::Dict(d) => canonical_dict(d, h, depth),
+ Object::Stream(_) | Object::Ref(_) => h.update(b"?"),
+ }
+}
+
+fn canonical_dict(d: &Dict, h: &mut Sha256, depth: usize) {
+ h.update(b"<");
+ for (k, v) in d.iter() {
+ bytes(b'/', k, h);
+ canonical(v, h, depth.saturating_add(1));
+ }
+ h.update(b">");
+}
+
+/// A number written with up to five decimals, without trailing zeros.
+fn number(text: &str, h: &mut Sha256) {
+ let t = if text.contains('.') { text.trim_end_matches('0').trim_end_matches('.') } else { text };
+ bytes(b'#', t.as_bytes(), h);
+}
+
+/// A typed, length-prefixed value, so no two different sequences hash the same way.
+fn bytes(kind: u8, b: &[u8], h: &mut Sha256) {
+ h.update([kind]);
+ h.update(u64::try_from(b.len()).unwrap_or(u64::MAX).to_le_bytes());
+ h.update(b);
+}
+
+/// Find the backdrop, and for a fill, where it is. With `swap`, that stream reads as those bytes
+/// instead of its own (to check a change before making it).
+fn scan(doc: &Document, p: &pdfcraft_model::Page, swap: Option<(ObjRef, &[u8])>) -> Option<(Backdrop, Option<Found>)> {
+ let crop = p.crop(doc);
+ let c = p.dict.get(b"Contents")?;
+ let list: Vec<Object> = match &*doc.resolve(c) {
+ Object::Array(a) => a.clone(),
+ _ => vec![c.clone()],
+ };
+ // The page's own content: untagged streams (marks and the q/Q wrapper carry /PCMark). Read
+ // only as far as a backdrop could be.
+ let mut refs = Vec::new();
+ let mut data = Vec::new();
+ let mut starts = Vec::new();
+ let mut total = 0usize;
+ for (slot, o) in list.iter().enumerate() {
+ if total >= SCAN_BYTES {
+ break;
+ }
+ let Object::Ref(r) = o else { return None };
+ let obj = doc.get(*r);
+ let Object::Stream(s) = &*obj else { continue };
+ if s.dict.get(b"PCMark").is_some() {
+ continue;
+ }
+ // Bytes in an external file (`/F`) replace the stream's own: what it draws is unknown here.
+ if s.dict.get(b"F").is_some() {
+ return None;
+ }
+ let bytes = match swap {
+ Some((with, b)) if with == *r => b.to_vec(),
+ _ => s.decoded().unwrap_or_default(),
+ };
+ starts.push(total);
+ total = total.saturating_add(bytes.len()).saturating_add(1);
+ refs.push((slot, *r));
+ data.push(bytes);
+ }
+ let pieces = Pieces::join(&data);
+ let parsed = pdfcraft_content::parse(head(pieces.data()));
+ let res = resources(doc, &p.dict);
+ let found = walk(doc, &res, crop, &parsed.ops);
+ found.map(|(b, op)| match (b, op) {
+ (Backdrop::Fill, Some(op)) => (b, Some(Found { refs, pieces, starts, op })),
+ _ => (b, None),
+ })
+}
+
+fn resources(doc: &Document, page: &Dict) -> Dict {
+ page.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default()
+}
+
+fn sub(doc: &Document, res: &Dict, kind: &[u8], name: &[u8]) -> Option<std::sync::Arc<Object>> {
+ let d = res.get(kind).map(|d| doc.resolve(d))?;
+ let o = d.as_dict()?.get(name)?.clone();
+ Some(doc.resolve(&o))
+}
+
+/// Walk the operators until the first one that paints; a backdrop is that one, or nothing.
+fn walk(doc: &Document, res: &Dict, crop: [f64; 4], ops: &[Op]) -> Option<(Backdrop, Option<std::ops::Range<usize>>)> {
+ let mut st = State { ctm: Matrix::IDENTITY, clip: Some([f64::MIN, f64::MIN, f64::MAX, f64::MAX]), white: false, space: 1, paint: Paint::INITIAL };
+ let mut saved: Vec<State> = Vec::new();
+ // Current path: its rectangles in user space, or `None` once it is anything else.
+ let mut path: Option<Vec<[f64; 4]>> = Some(Vec::new());
+ let mut clip_next = false;
+ for op in ops.iter().take(SCAN_OPS) {
+ match op.op.as_slice() {
+ b"q" => {
+ if saved.len() >= 64 {
+ return None;
+ }
+ saved.push(st.clone());
+ }
+ b"Q" => st = saved.pop()?,
+ b"cm" => {
+ let m = Matrix::from_operands(op.operands.get(op.operands.len().checked_sub(6)?..)?)?;
+ if !m.0.iter().all(|v| v.is_finite()) {
+ return None;
+ }
+ st.ctm = m.then(&st.ctm);
+ }
+ b"gs" => apply_state(doc, res, op.name(0)?, &mut st.paint)?,
+ b"g" => set_colour(&mut st, 1, op),
+ b"rg" => set_colour(&mut st, 3, op),
+ b"k" => set_colour(&mut st, 4, op),
+ b"cs" => {
+ st.space = match op.name(0)? {
+ b"DeviceGray" => 1,
+ b"DeviceRGB" => 3,
+ b"DeviceCMYK" => 4,
+ _ => 0,
+ };
+ // The initial colour of these spaces is black.
+ st.white = false;
+ }
+ b"sc" | b"scn" => {
+ let n = st.space;
+ set_colour(&mut st, n, op)
+ }
+ b"re" => {
+ let [x, y, w, h] = op.nums::<4>()?;
+ let finite = [x, y, w, h].iter().all(|v| v.is_finite());
+ match (&mut path, finite && axis_aligned(&st.ctm)) {
+ (Some(rects), true) => rects.push(st.ctm.bbox([x.min(x + w), y.min(y + h), x.max(x + w), y.max(y + h)])),
+ _ => path = None,
+ }
+ }
+ b"m" | b"l" | b"c" | b"v" | b"y" | b"h" => path = None,
+ b"W" | b"W*" => clip_next = true,
+ b"n" => {
+ if clip_next {
+ st.clip = clipped(st.clip, path.as_deref());
+ }
+ path = Some(Vec::new());
+ clip_next = false;
+ }
+ b"f" | b"F" | b"f*" => {
+ // One rectangle: with two, a fill rule can cut a hole where content shows.
+ let covers = match path.as_deref() {
+ Some([r]) => st.clip.and_then(|c| intersect(*r, c)).is_some_and(|r| pdfcraft_content::contains(r, crop, COVER_EPS)),
+ _ => false,
+ };
+ return (covers && st.white && st.paint.plain() && !clip_next).then(|| (Backdrop::Fill, Some(op.span.clone())));
+ }
+ b"Do" => {
+ let xo = sub(doc, res, b"XObject", op.name(0)?)?;
+ let Object::Stream(s) = &*xo else { return None };
+ // A stencil or masked picture lets what is behind it show.
+ let masked = [&b"SMask"[..], b"Mask"].iter().any(|k| s.dict.get(k).is_some())
+ || s.dict.get(b"ImageMask").is_some_and(|m| matches!(*doc.resolve(m), Object::Bool(true)));
+ let image = s.dict.name(b"Subtype") == Some(b"Image") && !masked;
+ return covers_unit_square(&st, crop, image).then_some((Backdrop::Image, None));
+ }
+ b"BI" => {
+ let masked = op
+ .inline
+ .as_ref()
+ .is_some_and(|(d, _)| [&b"IM"[..], b"ImageMask"].iter().any(|k| d.get(k).is_some_and(|m| matches!(m, Object::Bool(true)))));
+ return covers_unit_square(&st, crop, !masked).then_some((Backdrop::Image, None));
+ }
+ // Anything else that paints comes first: no backdrop.
+ b"S" | b"s" | b"B" | b"B*" | b"b" | b"b*" | b"sh" | b"Tj" | b"TJ" | b"'" | b"\"" | b"EI" | b"d0" | b"d1" => return None,
+ _ => {}
+ }
+ }
+ None
+}
+
+/// A picture placed by the CTM (onto the unit square) covering the crop box, opaque, unclipped.
+fn covers_unit_square(st: &State, crop: [f64; 4], image: bool) -> bool {
+ image
+ && st.paint.plain()
+ && axis_aligned(&st.ctm)
+ && st.clip.and_then(|c| intersect(st.ctm.bbox([0.0, 0.0, 1.0, 1.0]), c)).is_some_and(|r| pdfcraft_content::contains(r, crop, COVER_EPS))
+}
+
+fn set_colour(st: &mut State, components: usize, op: &Op) {
+ st.space = components;
+ let vals: Vec<f64> = op.operands.iter().filter_map(Object::as_f64).collect();
+ st.white = vals.len() == components
+ && match components {
+ 1 | 3 => vals.iter().all(|v| *v >= WHITE),
+ 4 => vals.iter().all(|v| *v <= 1.0 - WHITE),
+ _ => false,
+ };
+}
+
+/// Apply the named ExtGState's keys that [`Paint`] tracks; the keys it doesn't have leave
+/// `paint` as it was. `None` when the dictionary or one of those values can't be read.
+fn apply_state(doc: &Document, res: &Dict, name: &[u8], paint: &mut Paint) -> Option<()> {
+ let gs = sub(doc, res, b"ExtGState", name)?;
+ let gs = gs.as_dict()?;
+ if let Some(alpha) = gs.get(b"ca") {
+ paint.full_alpha = doc.resolve(alpha).as_f64()? >= 0.999;
+ }
+ if let Some(mask) = gs.get(b"SMask") {
+ paint.no_soft_mask = doc.resolve(mask).as_name() == Some(b"None");
+ }
+ if let Some(blend) = gs.get(b"BM") {
+ paint.normal_blend = matches!(doc.resolve(blend).as_name(), Some(b"Normal" | b"Compatible"));
+ }
+ // TR2 takes precedence over TR in the same dictionary (§8.4.5, Table 57). Only the names
+ // are read: a function (or one per colourant) is taken to change white.
+ if let Some(transfer) = gs.get(b"TR2") {
+ paint.identity_transfer = matches!(doc.resolve(transfer).as_name(), Some(b"Identity" | b"Default"));
+ } else if let Some(transfer) = gs.get(b"TR") {
+ paint.identity_transfer = doc.resolve(transfer).as_name() == Some(b"Identity");
+ }
+ Some(())
+}
+
+/// Rotations by multiples of 90° and scales only: rectangles stay rectangles.
+fn axis_aligned(m: &Matrix) -> bool {
+ let [a, b, c, d, ..] = m.0;
+ (b.abs() < 1e-9 && c.abs() < 1e-9) || (a.abs() < 1e-9 && d.abs() < 1e-9)
+}
+
+fn intersect(a: [f64; 4], b: [f64; 4]) -> Option<[f64; 4]> {
+ let r = [a[0].max(b[0]), a[1].max(b[1]), a[2].min(b[2]), a[3].min(b[3])];
+ (r.iter().all(|v| v.is_finite()) && r[2] > r[0] && r[3] > r[1]).then_some(r)
+}
+
+/// The clip after intersecting with a path: known only when the path is one rectangle.
+fn clipped(clip: Option<[f64; 4]>, path: Option<&[[f64; 4]]>) -> Option<[f64; 4]> {
+ match path {
+ Some([r]) => intersect(clip?, *r).or(Some([0.0, 0.0, 0.0, 0.0])),
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+#[path = "backdrop_tests.rs"]
+mod tests;
diff --cc crates/edit/src/lib.rs
index f5aa36754,7c8556332..5f615b435
--- a/crates/edit/src/lib.rs
+++ b/crates/edit/src/lib.rs
@@@ -31,1018 -31,8 +31,10 @@@ pub enum EditError
Cos(#[from] pdfcraft_cos::CosError),
}
- /// The kinds of page marks.
- #[derive(Clone, Copy, Debug, PartialEq, Eq)]
- pub enum MarkKind {
- HeaderFooter,
- Watermark,
- Background,
- }
-
- impl MarkKind {
- fn tag(self) -> &'static str {
- match self {
- MarkKind::HeaderFooter => "HeaderFooter",
- MarkKind::Watermark => "Watermark",
- MarkKind::Background => "Background",
- }
- }
- }
-
pub type Rgb = [f64; 3];
- /// Header and footer settings (Acrobat's Add Header and Footer dialog).
- #[derive(Clone, Debug, PartialEq)]
- pub struct HeaderFooter {
- /// Left, centre and right header text, then left, centre and right footer text. Tokens:
- /// `<<1>>` page number, `<<n>>` page count, `<<1 of n>>`, `<<1/n>>`, `<<Page 1>>`,
- /// `<<Page 1 of n>>`, dates `<<m/d/yyyy>>`, `<<mm/dd/yyyy>>`, `<<d/m/yyyy>>`, `<<yyyy-mm-dd>>`,
- /// `<<yyyy/mm/dd>>`, `<<yyyy/m/d>>`, `<<m/d/yy>>`, `<<mmmm d, yyyy>>`, the dotted day-first
- /// dates of German-speaking and much of Central and Eastern Europe `<<dd.mm.yyyy>>`,
- /// `<<d.m.yyyy>>`, `<<dd.mm.yy>>`, `<<d.m.yy>>`, and Bates numbers `<<Bates Number#6#1#PRE#SUF>>`
- /// (digits, start, prefix, suffix).
- pub text: [String; 6],
- /// The standard face the text is drawn in (#3754): Helvetica (the default), Times or Courier.
- pub font: added::Family,
- pub font_size: f64,
- pub color: Rgb,
- pub underline: bool,
- /// Margins in points: top, bottom, left, right (the text's distance from the page edges).
- pub margins: [f64; 4],
- /// The number `<<1>>` shows on the first page of the range.
- pub start_number: u32,
- /// Shrink the page content so the header and footer don't cover it (Acrobat's Appearance
- /// Options): the original content is scaled down evenly into the band the header and footer
- /// leave free, centred across the page. Remove and Update take the scaling away again.
- pub shrink: bool,
- }
-
- impl Default for HeaderFooter {
- /// Acrobat's defaults: 8 pt black, margins 0.5 in top and bottom, 1 in left and right.
- fn default() -> Self {
- Self {
- text: Default::default(),
- font: added::Family::Helvetica,
- font_size: 8.0,
- color: [0.0; 3],
- underline: false,
- margins: [36.0, 36.0, 72.0, 72.0],
- start_number: 1,
- shrink: false,
- }
- }
- }
-
- impl HeaderFooter {
- /// The first character [`add_header_footer`] would refuse, because the standard fonts can't
- /// draw it (#125). Tokens only add ASCII (Bates prefixes and suffixes are part of the
- /// template), so checking the templates, split as `expand`'s output is, covers every page
- /// (and a `\r` that would be drawn is refused too). The dialog asks this too, so its preview
- /// never offers text that applying refuses (#2013).
- pub fn first_undrawable(&self) -> Option<char> {
- self.text.iter().flat_map(|t| t.lines()).find_map(pdfcraft_fonts::first_non_win_ansi)
- }
-
- /// The room the header and the footer take at the top and the bottom of a page, in points:
- /// the margin, the lines of the tallest box, and a clearance of half the font size. A side
- /// without text takes none. This is the room [`HeaderFooter::shrink`] keeps free.
- pub fn bands(&self) -> (f64, f64) {
- let size = self.font_size;
- let line_h = size * 1.2;
- let lines = |boxes: &[String]| boxes.iter().filter(|t| !t.trim().is_empty()).map(|t| t.lines().count().max(1)).max();
- let (header, footer) = self.text.split_at(3);
- // Header lines hang below the top margin (a full line each); the footer's last line sits
- // on the bottom margin, so only its capitals (0.8 of the size) rise above it.
- let top = lines(header).map_or(0.0, |n| self.margins[0] + size + (n - 1) as f64 * line_h + size / 2.0);
- let bottom = lines(footer).map_or(0.0, |n| self.margins[1] + size * 0.8 + (n - 1) as f64 * line_h + size / 2.0);
- (top, bottom)
- }
- }
-
- /// The `cm` that shrinks a page's original content (user space) into the band `hf` leaves free,
- /// for a page shown `size` (display space) with view matrix `view` (display to user space): an
- /// even scale, centred across, the content's bottom on the footer's band.
- fn shrink_matrix(hf: &HeaderFooter, size: (f64, f64), view: [f64; 6]) -> Result<[f64; 6], EditError> {
- let (w, h) = size;
- let (top, bottom) = hf.bands();
- let free = h - top - bottom;
- if !(free.is_finite() && free >= 1.0 && w.is_finite() && w > 0.0) {
- return Err(EditError::Invalid("the header and footer margins leave no room for the page content to shrink into".into()));
- }
- let k = free / h;
- let v = kurbo::Affine::new(view);
- let det = v.determinant();
- if !(det.is_finite() && det.abs() > 1e-12) {
- return Err(EditError::Invalid("the page can't be shrunk: its view matrix is degenerate".into()));
- }
- let shrink = kurbo::Affine::new([k, 0.0, 0.0, k, (w - w * k) / 2.0, bottom]);
- // User space to display space, shrink there, and back.
- Ok((v * shrink * v.inverse()).as_coeffs())
- }
-
- /// A picture for a background or watermark (Acrobat: Source ▸ File): an XObject already in
- /// the document, an image (drawn into a unit square) or a form (a page of a PDF).
- #[derive(Clone, Copy, Debug, PartialEq)]
- pub struct MarkSource {
- pub xobject: pdfcraft_cos::ObjRef,
- /// Its natural size in points.
- pub size: (f64, f64),
- /// An image XObject (unit square); otherwise a form whose `/Matrix` maps it to `size`.
- pub image: bool,
- }
-
- /// A watermark: text, or a picture from a file (`source`; the text is then ignored).
- #[derive(Clone, Debug, PartialEq)]
- pub struct Watermark {
- pub text: String,
- pub source: Option<MarkSource>,
- /// Pictures: size relative to the page (1.0 fits the page).
- pub scale: f64,
- /// 0 = fit: about half the page diagonal.
- pub font_size: f64,
- pub color: Rgb,
- /// 0–1.
- pub opacity: f64,
- /// Degrees counter-clockwise (Acrobat's 45° runs from bottom-left to top-right).
- pub rotation: f64,
- /// Draw behind the page content instead of on top.
- pub behind: bool,
- /// Offset of the centre from the page centre, in points (right, up).
- pub offset: [f64; 2],
- }
-
- impl Watermark {
- /// The first character of a text watermark [`add_watermark`] would refuse, because the
- /// standard fonts can't draw it (#125). A picture watermark draws no text.
- pub fn first_undrawable(&self) -> Option<char> {
- match self.source {
- Some(_) => None,
- None => self.text.trim().lines().find_map(pdfcraft_fonts::first_non_win_ansi),
- }
- }
- }
-
- impl Default for Watermark {
- fn default() -> Self {
- Self {
- text: String::new(),
- source: None,
- scale: 0.5,
- font_size: 0.0,
- color: [0.6, 0.6, 0.6],
- opacity: 0.5,
- rotation: 45.0,
- behind: false,
- offset: [0.0; 2],
- }
- }
- }
-
- /// A background behind the page content: a solid colour, or a picture from a file.
- #[derive(Clone, Debug, PartialEq)]
- pub struct Background {
- pub color: Rgb,
- pub opacity: f64,
- pub source: Option<MarkSource>,
- /// Pictures: size relative to the page (1.0 fits the page).
- pub scale: f64,
- /// Replace a white backdrop the page paints itself, which would hide the background
- /// ([`backdrop`]). Removing the background turns it back on where that is still safe
- /// ([`backdrops_left_off`] are the pages where it isn't).
- pub replace_backdrop: bool,
- }
-
- impl Default for Background {
- /// A light yellow that still reads as a colour on screen (a near-white default looked as if
- /// nothing had happened).
- fn default() -> Self {
- Self { color: [1.0, 0.95, 0.7], opacity: 1.0, source: None, scale: 1.0, replace_backdrop: true }
- }
- }
-
- /// Drawing a picture mark: fitted to the page at `scale`, centred (plus `offset`), turned by
- /// `rotation` degrees. Returns the content and the resource name it uses.
- fn picture(src: &MarkSource, page: (f64, f64), scale: f64, rotation: f64, offset: [f64; 2]) -> String {
- let (w, h) = page;
- let (sw, sh) = (src.size.0.max(0.01), src.size.1.max(0.01));
- let k = (w / sw).min(h / sh) * if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
- let (dw, dh) = (sw * k, sh * k);
- let (s, c) = rotation.to_radians().sin_cos();
- let (cx, cy) = (w / 2.0 + offset[0], h / 2.0 + offset[1]);
- // Centre, rotate, then place the picture's box (unit square for images).
- let place = if src.image {
- format!("{} 0 0 {} {} {} cm", n(dw), n(dh), n(-dw / 2.0), n(-dh / 2.0))
- } else {
- format!("{} 0 0 {} {} {} cm", n(k), n(k), n(-dw / 2.0), n(-dh / 2.0))
- };
- format!("{} {} {} {} {} {} cm\n{place}\n/PCPic{} Do\n", n(c), n(s), n(-s), n(c), n(cx), n(cy), src.xobject.num)
- }
-
- /// Register a mark picture in the page's own resources (`/PCPic<num>`).
- fn add_picture_resource(doc: &mut Document, page: &pdfcraft_model::Page, src: &MarkSource) -> Result<(), EditError> {
- let p = doc.get(page.obj).as_dict().cloned().unwrap_or_default();
- let mut res = p.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
- let mut xo = res.get(b"XObject").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default();
- xo.set(format!("PCPic{}", src.xobject.num).into_bytes(), Object::Ref(src.xobject));
- res.set(b"XObject".to_vec(), Object::Dict(xo));
- doc.update_dict(page.obj, |d| d.set(b"Resources".to_vec(), Object::Dict(res)))?;
- Ok(())
- }
-
- /// Values tokens need that come from outside the document.
- #[derive(Clone, Debug, PartialEq, Default)]
- pub struct Context {
- /// Today's date: (year, month 1–12, day 1–31).
- pub date: (i64, u32, u32),
- }
-
- // Model-derived transforms can contain tiny scale factors; retain their PDF decimal precision.
- fn matrix_number(value: f64) -> String {
- let mut bytes = Vec::new();
- pdfcraft_cos::serialize(&Object::Real(value), &mut bytes);
- String::from_utf8_lossy(&bytes).into_owned()
- }
-
- fn n(v: f64) -> String {
- let s = format!("{:.3}", if v.abs() < 5e-4 { 0.0 } else { v });
- let s = s.trim_end_matches('0').trim_end_matches('.');
- if s == "-0" { "0".into() } else { s.into() }
- }
-
- fn rgb(c: Rgb) -> String {
- let c = c.map(|x| x.clamp(0.0, 1.0));
- format!("{} {} {} rg", n(c[0]), n(c[1]), n(c[2]))
- }
-
- const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
-
- /// Expand `<<…>>` tokens for page `index` (0-based within the range) of `count`.
- pub fn expand(template: &str, page_number: u32, count: usize, bates: u64, cx: &Context) -> String {
- let (y, m, d) = cx.date;
- let mut out = String::new();
- let mut rest = template;
- while let Some(start) = rest.find("<<") {
- out.push_str(&rest[..start]);
- let after = &rest[start + 2..];
- let Some(end) = after.find(">>") else {
- out.push_str(&rest[start..]);
- return out;
- };
- let token = &after[..end];
- let p = page_number;
- let value = match token {
- "1" => p.to_string(),
- "n" => count.to_string(),
- "1 of n" => format!("{p} of {count}"),
- "1/n" => format!("{p}/{count}"),
- "Page 1" => format!("Page {p}"),
- "Page 1 of n" => format!("Page {p} of {count}"),
- "m/d" => format!("{m}/{d}"),
- "m/d/yy" => format!("{m}/{d}/{:02}", y.rem_euclid(100)),
- "m/d/yyyy" => format!("{m}/{d}/{y}"),
- "mm/dd/yy" => format!("{m:02}/{d:02}/{:02}", y.rem_euclid(100)),
- "mm/dd/yyyy" => format!("{m:02}/{d:02}/{y}"),
- "d/m/yy" => format!("{d}/{m}/{:02}", y.rem_euclid(100)),
- "d/m/yyyy" => format!("{d}/{m}/{y}"),
- "dd/mm/yyyy" => format!("{d:02}/{m:02}/{y}"),
- "d.m.yy" => format!("{d}.{m}.{:02}", y.rem_euclid(100)),
- "d.m.yyyy" => format!("{d}.{m}.{y}"),
- "dd.mm.yy" => format!("{d:02}.{m:02}.{:02}", y.rem_euclid(100)),
- "dd.mm.yyyy" => format!("{d:02}.{m:02}.{y}"),
- "yyyy-mm-dd" => format!("{y}-{m:02}-{d:02}"),
- "yyyy/mm/dd" => format!("{y}/{m:02}/{d:02}"),
- "yyyy/m/d" => format!("{y}/{m}/{d}"),
- "mmmm d, yyyy" => format!("{} {d}, {y}", MONTHS[(m.clamp(1, 12) - 1) as usize]),
- t if t.starts_with("Bates Number") => {
- // Bates Number#digits#start#prefix#suffix (start is applied by the caller).
- let parts: Vec<&str> = t.split('#').collect();
- let digits = parts.get(1).and_then(|d| d.parse::<usize>().ok()).unwrap_or(6).clamp(1, 15);
- format!("{}{:0digits$}{}", parts.get(3).unwrap_or(&""), bates, parts.get(4).unwrap_or(&""))
- }
- _ => format!("<<{token}>>"),
- };
- out.push_str(&value);
- rest = &after[end + 2..];
- }
- out.push_str(rest);
- out
- }
-
- /// The Bates start number in a template (`<<Bates Number#digits#start#…>>`), if any.
- fn bates_start(template: &str) -> Option<u64> {
- let i = template.find("<<Bates Number")?;
- let t = &template[i + 2..];
- let t = &t[..t.find(">>")?];
- t.split('#').nth(2).and_then(|s| s.parse().ok()).or(Some(1))
- }
-
- fn page_list(doc: &Document) -> Vec<pdfcraft_model::Page> {
- pdfcraft_model::pages(doc)
- }
-
- fn check(pages: &[usize], count: usize) -> Result<(), EditError> {
- match pages.iter().find(|p| **p >= count) {
- Some(p) => Err(EditError::NoSuchPage(*p)),
- None => Ok(()),
- }
- }
-
- /// The page's `/Contents` as a list of stream references (inline content is promoted).
- fn contents(doc: &mut Document, page: &pdfcraft_model::Page) -> Result<Vec<Object>, EditError> {
- let obj = doc.get(page.obj);
- let d = obj.as_dict().cloned().unwrap_or_default();
- Ok(match d.get(b"Contents").cloned() {
- None => Vec::new(),
- Some(Object::Ref(r)) => match doc.get(r).as_array() {
- Some(a) => a.clone(),
- None => vec![Object::Ref(r)],
- },
- Some(Object::Array(a)) => a,
- Some(other) => vec![Object::Ref(doc.add(other))],
- })
- }
-
- /// Add the font (and an opacity state) to the page's own resources.
- fn add_resources(doc: &mut Document, page: &pdfcraft_model::Page, opacity: Option<f64>, content: Option<&[u8]>) -> Result<(), EditError> {
- let mut faces: Vec<(Vec<u8>, &str)> = Vec::new();
- for (name, base) in [(&b"PCHelv"[..], "Helvetica"), (b"PCTimes", "Times-Roman"), (b"PCCour", "Courier")] {
- // Helvetica always (marks use it); the others only when the content names them.
- if name != b"PCHelv" && !content.is_some_and(|c| c.windows(name.len() + 1).any(|w| w[0] == b'/' && &w[1..] == name)) {
- continue;
- }
- faces.push((name.to_vec(), base));
- }
- add_page_resources(doc, page, opacity, &faces)
- }
-
- /// The fonts a page draws with: its own resources' or the ones it inherits.
- fn page_fonts(doc: &Document, page: &pdfcraft_model::Page) -> Dict {
- let res = page.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
- res.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default()
- }
-
- /// A name in `fonts` for the standard face `base` that can't take over a font the page already
- /// draws with: `preferred` when it is free or already names exactly the dictionary
- /// [`add_page_resources`] writes for that face, otherwise the first such `preferred_1`,
- /// `preferred_2`… (one of the first `fonts.len() + 1` always is). A font with anything more
- /// (`/ToUnicode`, `/Widths`…) is someone else's, even in the same face.
- fn free_font_name(doc: &Document, fonts: &Dict, preferred: &str, base: &str) -> String {
- let usable = |name: &str| match fonts.get(name.as_bytes()) {
- None => true,
- Some(font) => doc.resolve(font).as_dict().is_some_and(|d| {
- d.len() == 4
- && d.name(b"Type") == Some(b"Font")
- && d.name(b"Subtype") == Some(b"Type1")
- && d.name(b"BaseFont") == Some(base.as_bytes())
- && d.name(b"Encoding") == Some(b"WinAnsiEncoding")
- }),
- };
- if usable(preferred) {
- return preferred.to_string();
- }
- (1..=fonts.len().saturating_add(1)).map(|k| format!("{preferred}_{k}")).find(|name| usable(name)).unwrap_or_else(|| preferred.to_string())
- }
-
- /// Add the standard `faces` (resource name, base font) and an opacity state to the page's own
- /// resources.
- fn add_page_resources(doc: &mut Document, page: &pdfcraft_model::Page, opacity: Option<f64>, faces: &[(Vec<u8>, &str)]) -> Result<(), EditError> {
- let mut res = page.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
- let mut fonts = res.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();
- for (name, base) in faces {
- let mut font = Dict::new();
- font.set(b"Type".to_vec(), Object::name("Font"));
- font.set(b"Subtype".to_vec(), Object::name("Type1"));
- font.set(b"BaseFont".to_vec(), Object::name(base));
- font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
- fonts.set(name.clone(), Object::Dict(font));
- }
- res.set(b"Font".to_vec(), Object::Dict(fonts));
- if let Some(o) = opacity {
- let mut gs = res.get(b"ExtGState").map(|g| doc.resolve(g)).and_then(|g| g.as_dict().cloned()).unwrap_or_default();
- let mut s = Dict::new();
- s.set(b"Type".to_vec(), Object::name("ExtGState"));
- s.set(b"CA".to_vec(), Object::Real(o));
- s.set(b"ca".to_vec(), Object::Real(o));
- let name = format!("PCGS{}", (o * 100.0).round() as i64);
- gs.set(name.into_bytes(), Object::Dict(s));
- res.set(b"ExtGState".to_vec(), Object::Dict(gs));
- }
- // The page gets its own (possibly copied) resources; shared dictionaries stay untouched.
- doc.update_dict(page.obj, |d| d.set(b"Resources".to_vec(), Object::Dict(res)))?;
- Ok(())
- }
-
- const WRAP_OPEN: &[u8] = b"q %PdfCraft\n";
- /// Starts with an end of line, so a comment left open at the end of the content before it
- /// can't swallow the `Q`. Older files have the close without it.
- const WRAP_CLOSE: &[u8] = b"\nQ %PdfCraft\n";
- const OLD_WRAP_CLOSE: &[u8] = b"Q %PdfCraft\n";
-
- /// Whether `bytes` are a wrapper's close: canonical `EMC` closures, then the existing
- /// graphics closures. Legacy closes without the leading newline remain valid on their own.
- fn is_wrap_close(bytes: &[u8]) -> bool {
- let mut rest = bytes;
- while let Some(shorter) = rest.strip_prefix(b"\nEMC".as_slice()) {
- rest = shorter;
- }
- let legacy = rest.len() == bytes.len();
- loop {
- if rest == WRAP_CLOSE || (legacy && rest == OLD_WRAP_CLOSE) {
- return true;
- }
- match rest.strip_prefix(b"\nQ".as_slice()) {
- Some(shorter) => rest = shorter,
- None => return false,
- }
- }
- }
-
- /// A `Wrap`-tagged stream's role from its exact bytes: `Some(true)` for an open, `Some(false)`
- /// for a close.
- fn wrapper_role(doc: &Document, o: &Object) -> Option<bool> {
- if stream_tag(doc, o).as_deref() != Some("Wrap") {
- return None;
- }
- let Object::Stream(stream) = &*doc.resolve(o) else { return None };
- // Wrappers are a few bytes; one that decodes to more isn't PdfCraft's.
- let bytes = stream.decoded_within(64 * 1024).ok()?;
- if bytes == WRAP_OPEN { Some(true) } else { is_wrap_close(&bytes).then_some(false) }
- }
-
- #[cfg(test)]
- fn stream_bytes(doc: &Document, o: &Object) -> Option<Vec<u8>> {
- match &*doc.resolve(o) {
- Object::Stream(s) => s.decoded().ok(),
- _ => None,
- }
- }
-
- /// The `/PCMark` tag in a content stream's dictionary: a mark kind, or `Wrap` for the q/Q
- /// wrapper. Read from the dictionary, so finding marks never decompresses page content.
- fn stream_tag(doc: &Document, o: &Object) -> Option<String> {
- let obj = doc.resolve(o);
- obj.as_dict()?.name(b"PCMark").map(|n| String::from_utf8_lossy(n).into_owned())
- }
-
- fn tagged(tag: &str) -> Dict {
- let mut d = Dict::new();
- d.set(b"PCMark".to_vec(), Object::name(tag));
- d
- }
-
- /// What placing a mark on top needs, from the page's actual operators (not the `/PCMark` tags,
- /// which another writer may keep, copy or forge).
- enum Isolation {
- /// The content parses cleanly with balanced `q`/`Q` and closed text objects and paths.
- /// `suffix`: the stream from which the content leaves graphics state set (or a comment open)
- /// that a mark on top must not inherit, so it needs a wrapper from there to the end.
- /// `wrappers`: PdfCraft wrapper pairs (open, close) as stream indexes.
- /// `marked`: unfinished marked-content sequences to close before a new mark.
- Clean { suffix: Option<usize>, wrappers: Vec<(usize, usize)>, marked: usize },
- /// The content could not be read that precisely (it doesn't decode, is too large, or has
- /// stray bytes, unbalanced `q`/`Q` or an unfinished text object or path). `unclosed` is
- /// the count of `q` left open at the end, when known. `marked` counts known unfinished
- /// marked-content sequences independently of graphics malformation, or zero when unknown.
- Unknown { unclosed: usize, marked: usize },
- /// Marked content nests past [`ISOLATION_MAX_DEPTH`]: how many sequences a mark on top would
- /// have to close (some may be hidden optional content) is unknown.
- TooDeep,
- }
-
- const ISOLATION_MAX_STREAMS: usize = 100_000;
- const ISOLATION_MAX_BYTES: usize = 128 * 1024 * 1024;
- const ISOLATION_MAX_OPS: usize = 1_000_000;
- const ISOLATION_MAX_DEPTH: usize = 10_000;
-
- fn isolation(doc: &Document, list: &[Object]) -> Isolation {
- let unknown = Isolation::Unknown { unclosed: 0, marked: 0 };
- if list.len() > ISOLATION_MAX_STREAMS {
- return unknown;
- }
- let mut remaining = ISOLATION_MAX_BYTES;
- let mut data = Vec::with_capacity(list.len());
- for object in list {
- let resolved = doc.resolve(object);
- let Object::Stream(stream) = &*resolved else { return unknown };
- let Ok(bytes) = stream.decoded_within(remaining) else { return unknown };
- let Some(left) = remaining.checked_sub(bytes.len().saturating_add(1)) else { return unknown };
- remaining = left;
- data.push(bytes);
- }
- let pieces = pdfcraft_content::Pieces::join(&data);
- let parsed = pieces.parse();
- if parsed.skipped != 0 || parsed.ops.len() > ISOLATION_MAX_OPS {
- return unknown;
- }
- let edges = pieces.comment_edges(&parsed);
- let (mut text_open, mut path_open, mut dirty, mut malformed) = (false, false, false, false);
- let mut stack: Vec<usize> = Vec::new();
- let (mut marked, mut marked_known) = (0usize, true);
- let mut split = 0;
- let mut previous_last = None;
- let mut wrappers = Vec::new();
- for op in &parsed.ops {
- let (first, last) = pieces.pieces_of(op);
- // A wrapper can only go in before a whole stream, outside graphics and marked-content
- // scopes, between operators, where no comment would swallow the wrapper's `q`.
- if stack.is_empty()
- && marked_known
- && marked == 0
- && !text_open
- && !path_open
- && !dirty
- && previous_last.is_none_or(|previous| first > previous)
- && !edges.get(first).is_some_and(|edge| edge.0)
- {
- split = first;
- }
- previous_last = Some(last);
- // Match the reader's tolerant operands: BMC uses the last name, BDC the last
- // name/object pair, and EMC ignores surplus operands. Invalid begins are ignored.
- let begin_marked = match op.op.as_slice() {
- b"BMC" => op.operands.last().is_some_and(|o| matches!(o, Object::Name(_))),
- b"BDC" => op.operands.len().checked_sub(2).and_then(|i| op.operands.get(i)).is_some_and(|o| matches!(o, Object::Name(_))),
- _ => false,
- };
- if marked_known {
- if begin_marked {
- if marked < ISOLATION_MAX_DEPTH {
- marked += 1;
- } else {
- // Once the budget is exceeded, later EMCs cannot restore a known depth.
- marked_known = false;
- marked = 0;
- }
- } else if op.is("EMC") {
- marked = marked.saturating_sub(1);
- }
- }
- match op.op.as_slice() {
- b"BT" if !text_open => text_open = true,
- b"ET" if text_open => text_open = false,
- b"BT" | b"ET" => malformed = true,
- b"m" | b"l" | b"c" | b"v" | b"y" | b"h" | b"re" | b"W" | b"W*" => path_open = true,
- b"n" | b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" => path_open = false,
- _ => {}
- }
- match op.op.as_slice() {
- b"q" if op.operands.is_empty() && stack.len() < ISOLATION_MAX_DEPTH => stack.push(first),
- b"Q" if op.operands.is_empty() => match stack.pop() {
- Some(open) => {
- // Only a standalone PdfCraft wrapper pair may later be removed again.
- let wrap = |i: usize| list.get(i).is_some_and(|o| stream_tag(doc, o).as_deref() == Some("Wrap"));
- if wrap(open)
- && wrap(first)
- && data.get(open).is_some_and(|d| d == WRAP_OPEN)
- && data.get(first).is_some_and(|d| is_wrap_close(d))
- {
- wrappers.push((open, first));
- }
- }
- None => malformed = true,
- },
- b"q" | b"Q" => malformed = true,
- _ if stack.is_empty() => dirty = true,
- _ => {}
- }
- }
- if !marked_known {
- return Isolation::TooDeep;
- }
- if malformed || text_open || path_open || !stack.is_empty() {
- return Isolation::Unknown { unclosed: if malformed { 0 } else { stack.len() }, marked };
- }
- let comment_open = edges.last().is_some_and(|edge| edge.1);
- Isolation::Clean { suffix: (dirty || comment_open || marked != 0).then_some(split), wrappers, marked }
- }
-
- /// Put a mark's content on a page: behind (with the behind-marks at the start) or on top
- /// (appended, after wrapping the original content in q/Q).
- fn place(doc: &mut Document, page: &pdfcraft_model::Page, kind: MarkKind, content: Vec<u8>, behind: bool) -> Result<(), EditError> {
- place_tagged(doc, page, kind.tag(), content, behind).map(drop)
- }
-
- /// Put content on a page, tagged `tag` (see [`place`]). On top, whatever graphics state the
- /// content before leaves set (a `cm`, a clip, text state…) must not reach the mark, including
- /// content appended after an earlier PdfCraft wrapper by another tool (#3084): the stretch of
- /// content that leaves state set is wrapped in q/Q, once. Any known unfinished marked-content
- /// sequences are closed at the end too, so hidden optional content cannot hide the new mark; when
- /// their number is unknown, nothing is placed on top. Returns the new content stream.
- fn place_tagged(doc: &mut Document, page: &pdfcraft_model::Page, tag: &str, content: Vec<u8>, behind: bool) -> Result<ObjRef, EditError> {
- let mut list = contents(doc, page)?;
- // The behind-marks at the start: backgrounds in the order added, then watermarks.
- let behind_kinds = [MarkKind::Background.tag(), MarkKind::Watermark.tag()];
- let behind_marks = list.iter().take_while(|o| stream_tag(doc, o).is_some_and(|t| behind_kinds.contains(&t.as_str()))).count();
- let wrap = if behind {
- None
- } else {
- match isolation(doc, &list) {
- Isolation::Clean { suffix, marked, .. } => suffix.map(|split| (split, 0, marked)),
- // Content that can't be read precisely is wrapped whole, as before: after the
- // behind-marks at the start. A `q` it leaves open is closed at its end, where
- // closing it changes nothing already drawn.
- Isolation::Unknown { unclosed, marked } => (behind_marks < list.len()).then_some((behind_marks, unclosed, marked)),
- // Content left inside an optional-content sequence it cannot close could be hidden.
- Isolation::TooDeep => return Err(too_deep_on_top()),
- }
- };
- let mark_ref = doc.add(Object::Stream(Stream::flate(tagged(tag), &content)));
- let mark = Object::Ref(mark_ref);
- if behind {
- // Right after the backgrounds already there, so a new background is painted over the
- // older ones (#3591) and a watermark over all of them. Not after the watermarks: on a
- // page with no content, one on top is at the start too and can't be told apart, so a
- // newer watermark behind goes under the older ones.
- let at = list.iter().take(behind_marks).rposition(|o| stream_tag(doc, o).as_deref() == Some(MarkKind::Background.tag())).map_or(0, |i| i + 1);
- list.insert(at, mark);
- } else {
- if let Some((split, unclosed, marked)) = wrap {
- let mut close_bytes = b"\nEMC".repeat(marked);
- close_bytes.extend_from_slice(&b"\nQ".repeat(unclosed));
- close_bytes.extend_from_slice(WRAP_CLOSE);
- let open = Object::Ref(doc.add(Object::Stream(Stream::from_raw(tagged("Wrap"), WRAP_OPEN.to_vec()))));
- let close = Object::Ref(doc.add(Object::Stream(Stream::from_raw(tagged("Wrap"), close_bytes))));
- list.insert(split.min(list.len()), open);
- list.push(close);
- }
- list.push(mark);
- }
- doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(list)))?;
- Ok(mark_ref)
- }
-
- fn too_deep_on_top() -> EditError {
- EditError::Invalid("the page's marked content is nested too deeply to add anything on top of it".into())
- }
-
- /// The refusal [`place_tagged`] gives for a mark on top of `page`, checked before an edit changes
- /// anything (removing old marks, adding resources) so a refused edit leaves the document as it was.
- fn check_on_top(doc: &Document, page: &pdfcraft_model::Page) -> Result<(), EditError> {
- let obj = doc.get(page.obj);
- let list = match obj.as_dict().and_then(|d| d.get(b"Contents")) {
- None => return Ok(()),
- Some(Object::Ref(r)) => doc.get(*r).as_array().cloned().unwrap_or_else(|| vec![Object::Ref(*r)]),
- Some(Object::Array(a)) => a.clone(),
- Some(other) => vec![other.clone()],
- };
- match isolation(doc, &list) {
- Isolation::TooDeep => Err(too_deep_on_top()),
- _ => Ok(()),
- }
- }
-
- /// Put content tagged `tag` first inside the q/Q wrapper, so it applies to the page's original
- /// content and nothing else (a header's shrink). A page without a wrapper has no original content
- /// on it and is left alone.
- fn place_inside_wrapper(doc: &mut Document, page: &pdfcraft_model::Page, tag: &str, content: Vec<u8>) -> Result<(), EditError> {
- let mut list = contents(doc, page)?;
- let Some(open) = list.iter().position(|o| stream_tag(doc, o).as_deref() == Some("Wrap")) else { return Ok(()) };
- let stream = Object::Ref(doc.add(Object::Stream(Stream::flate(tagged(tag), &content))));
- list.insert(open + 1, stream);
- doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(list)))?;
- Ok(())
- }
-
- /// Draw `content` on top of a page (0-based) as permanent page content, with standard Helvetica
- /// available as `/PCHelv`. The stream is tagged `tag` (not a mark kind, so Remove never takes
- /// it away); the original content is wrapped in q/Q first. Used for applied redaction boxes.
- /// Returns the new content stream.
- pub fn stamp(doc: &mut Document, page: usize, tag: &str, content: Vec<u8>) -> Result<ObjRef, EditError> {
- let all = page_list(doc);
- check(&[page], all.len())?;
- check_on_top(doc, &all[page])?;
- add_resources(doc, &all[page], None, Some(&content))?;
- let p = page_list(doc).swap_remove(page);
- place_tagged(doc, &p, tag, content, false)
- }
-
- fn begin(kind: MarkKind, subtype: &str, matrix: [f64; 6]) -> String {
- format!(
- "q\n/Artifact <</Type /Pagination /Subtype /{subtype} /PCMark /{}>> BDC\n{} {} {} {} {} {} cm\n",
- kind.tag(),
- matrix_number(matrix[0]),
- matrix_number(matrix[1]),
- matrix_number(matrix[2]),
- matrix_number(matrix[3]),
- matrix_number(matrix[4]),
- matrix_number(matrix[5])
- )
- }
-
- const END: &str = "EMC\nQ\n";
-
- /// The refusal for page text with `c`, which nothing here can draw.
- pub(crate) fn undrawable(c: char) -> EditError {
- EditError::Invalid(undrawable_message(c))
- }
-
- /// The wording of the refusal for text with `c`, which the standard fonts can't draw.
- pub fn undrawable_message(c: char) -> String {
- format!("the standard fonts can't draw \"{c}\" (U+{:04X}); only Western European characters can be added as text for now", u32::from(c))
- }
-
- fn text_op(x: f64, y: f64, text: &str) -> Vec<u8> {
- let mut v = format!("1 0 0 1 {} {} Tm ", n(x), n(y)).into_bytes();
- v.extend(literal(&win_ansi(text)));
- v.extend_from_slice(b" Tj\n");
- v
- }
-
- /// Add a header and footer to `pages` (0-based). With `replace`, existing headers and footers on
- /// those pages are removed first (Acrobat's Replace Existing).
- pub fn add_header_footer(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replace: bool, cx: &Context) -> Result<(), EditError> {
- let all = page_list(doc);
- check(pages, all.len())?;
- if hf.text.iter().all(|t| t.trim().is_empty()) {
- return Err(EditError::Invalid("type the header or footer text first".into()));
- }
- if let Some(c) = hf.first_undrawable() {
- return Err(undrawable(c));
- }
- if !(hf.font_size.is_finite() && hf.font_size > 0.0 && hf.font_size <= 200.0 && hf.margins.iter().all(|m| m.is_finite() && *m >= 0.0)) {
- return Err(EditError::Invalid("invalid font size or margins".into()));
- }
- // Page numbers count up from start_number, so the last selected page needs the most room.
- // Refuse the whole run before drawing anything: headers applied to some pages and then a
- // failed page number would leave the document half changed.
- let last_number = u64::from(hf.start_number)
- .checked_add(pages.len().saturating_sub(1) as u64)
- .ok_or_else(|| EditError::Invalid("the header page numbers are too large".into()))?;
- if last_number > u64::from(u32::MAX) {
- return Err(EditError::Invalid(format!(
- "the header start number {} leaves no room for {} pages (page numbers stop at {})",
- hf.start_number,
- pages.len(),
- u32::MAX
- )));
- }
- // The same goes for Bates numbers: the last selected page must still fit in a u64.
- let bates0 = hf.text.iter().find_map(|t| bates_start(t)).unwrap_or(1);
- if bates0.checked_add(pages.len().saturating_sub(1) as u64).is_none() {
- return Err(EditError::Invalid(format!(
- "the Bates start number {bates0} leaves no room for {} pages (Bates numbers stop at {})",
- pages.len(),
- u64::MAX
- )));
- }
- // Shrinking needs room on every page: refuse before anything is drawn or replaced.
- let shrinks = pages
- .iter()
- .map(|&i| hf.shrink.then(|| shrink_matrix(hf, all[i].display_size(doc), all[i].view_matrix(doc))).transpose())
- .collect::<Result<Vec<_>, _>>()?;
- for &i in pages {
- check_on_top(doc, &all[i])?;
- }
- if replace {
- remove_marks(doc, pages, MarkKind::HeaderFooter)?;
- }
- let all = page_list(doc);
- let count = all.len();
- for (k, &i) in pages.iter().enumerate() {
- let page = &all[i];
- let (w, h) = page.display_size(doc);
- let number =
- u32::try_from(u64::from(hf.start_number) + k as u64).map_err(|_| EditError::Invalid("the header page numbers are too large".into()))?;
- let bates = bates0.checked_add(k as u64).ok_or_else(|| EditError::Invalid("the Bates numbers are too large".into()))?;
- let size = hf.font_size;
- let [top, bottom, left, right] = hf.margins;
- // The page resource the face is added under: the usual name, unless the page already
- // draws another font by it, which must not change under the header.
- let preferred = match hf.font {
- added::Family::Helvetica => "PCHelv",
- added::Family::Times => "PCTimes",
- added::Family::Courier => "PCCour",
- };
- let base = hf.font.base_font(false, false);
- let resource = free_font_name(doc, &page_fonts(doc, page), preferred, base);
- let mut body: Vec<u8> = format!("BT\n/{resource} {} Tf\n{}\n", n(size), rgb(hf.color)).into_bytes();
- let mut underlines = String::new();
- for (slot, template) in hf.text.iter().enumerate() {
- if template.trim().is_empty() {
- continue;
- }
- let lines: Vec<String> = expand(template, number, count, bates, cx).lines().map(str::to_owned).collect();
- let header = slot < 3;
- let line_h = size * 1.2;
- for (li, line) in lines.iter().enumerate() {
- // Centred and right-aligned text is placed by its width in the chosen face.
- let tw = hf.font.width(line, size, false, false);
- let x = match slot % 3 {
- 0 => left,
- 1 => (w - tw) / 2.0,
- _ => w - right - tw,
- };
- // Headers hang below the top margin; footers sit on the bottom margin.
- let y = if header { h - top - size * 0.8 - li as f64 * line_h } else { bottom + (lines.len() - 1 - li) as f64 * line_h };
- body.extend(text_op(x, y, line));
- if hf.underline {
- underlines.push_str(&format!("{} {} {} {} re f\n", n(x), n(y - size * 0.15), n(tw), n((size * 0.06).max(0.4))));
- }
- }
- }
- body.extend_from_slice(b"ET\n");
- if !underlines.is_empty() {
- body.extend(format!("{}\n{underlines}", rgb(hf.color)).bytes());
- }
- let mut content = begin(MarkKind::HeaderFooter, "Header", page.view_matrix(doc)).into_bytes();
- content.extend(body);
- content.extend_from_slice(END.as_bytes());
- // A name already there is that very font (see `free_font_name`): left as it is.
- if !page_fonts(doc, page).contains(resource.as_bytes()) {
- add_page_resources(doc, page, None, &[(resource.into_bytes(), base)])?;
- }
- let page = &page_list(doc)[i];
- place(doc, page, MarkKind::HeaderFooter, content, false)?;
- if let Some(Some(m)) = shrinks.get(k) {
- let cm = format!("{} cm\n", m.map(matrix_number).join(" "));
- let page = &page_list(doc)[i];
- place_inside_wrapper(doc, page, MarkKind::HeaderFooter.tag(), cm.into_bytes())?;
- }
- }
- Ok(())
- }
-
- /// Add a text watermark to `pages`.
- pub fn add_watermark(doc: &mut Document, pages: &[usize], wm: &Watermark, replace: bool) -> Result<(), EditError> {
- let all = page_list(doc);
- check(pages, all.len())?;
- let text = wm.text.trim();
- if text.is_empty() && wm.source.is_none() {
- return Err(EditError::Invalid("type the watermark text first".into()));
- }
- if let Some(c) = wm.first_undrawable() {
- return Err(undrawable(c));
- }
- if !(wm.opacity.is_finite()
- && wm.rotation.is_finite()
- && wm.font_size.is_finite()
- && wm.font_size >= 0.0
- && wm.offset.iter().all(|o| o.is_finite()))
- {
- return Err(EditError::Invalid("invalid watermark settings".into()));
- }
- if !wm.behind {
- for &i in pages {
- check_on_top(doc, &all[i])?;
- }
- }
- if replace {
- remove_marks(doc, pages, MarkKind::Watermark)?;
- }
- let opacity = wm.opacity.clamp(0.0, 1.0);
- let lines: Vec<&str> = text.lines().collect();
- for &i in pages {
- let page = page_list(doc)[i].clone();
- let (w, h) = page.display_size(doc);
- if let Some(src) = &wm.source {
- let mut content = begin(MarkKind::Watermark, "Watermark", page.view_matrix(doc));
- content.push_str(&format!("/PCGS{} gs\n", (opacity * 100.0).round() as i64));
- content.push_str(&picture(src, (w, h), wm.scale, wm.rotation, wm.offset));
- content.push_str(END);
- add_resources(doc, &page, Some(opacity), None)?;
- add_picture_resource(doc, &page_list(doc)[i].clone(), src)?;
- let page = &page_list(doc)[i];
- place(doc, page, MarkKind::Watermark, content.into_bytes(), wm.behind)?;
- continue;
- }
- let widest = lines.iter().map(|l| helvetica_width(l, 1.0)).fold(0.0, f64::max).max(0.01);
- let size = if wm.font_size > 0.0 { wm.font_size } else { ((w * w + h * h).sqrt() * 0.5 / widest).clamp(6.0, 300.0) };
- let (s, c) = wm.rotation.to_radians().sin_cos();
- let (cx, cy) = (w / 2.0 + wm.offset[0], h / 2.0 + wm.offset[1]);
- let mut content = begin(MarkKind::Watermark, "Watermark", page.view_matrix(doc)).into_bytes();
- content.extend(
- format!(
- "/PCGS{} gs\n{} {} {} {} {} {} cm\nBT\n/PCHelv {} Tf\n{}\n",
- (opacity * 100.0).round() as i64,
- n(c),
- n(s),
- n(-s),
- n(c),
- n(cx),
- n(cy),
- n(size),
- rgb(wm.color)
- )
- .bytes(),
- );
- let line_h = size * 1.15;
- let total = line_h * (lines.len() as f64 - 1.0);
- for (li, line) in lines.iter().enumerate() {
- let tw = helvetica_width(line, size);
- content.extend(text_op(-tw / 2.0, total / 2.0 - li as f64 * line_h - size * 0.35, line));
- }
- content.extend_from_slice(b"ET\n");
- content.extend_from_slice(END.as_bytes());
- add_resources(doc, &page, Some(opacity), None)?;
- let page = &page_list(doc)[i];
- place(doc, page, MarkKind::Watermark, content, wm.behind)?;
- }
- Ok(())
- }
-
- /// Add a solid-colour background behind the content of `pages`. With `bg.replace_backdrop`, a
- /// white backdrop a page paints itself is replaced first, so the background shows (see
- /// [`backdrop`]); a picture backdrop (a scan) still hides it.
- pub fn add_background(doc: &mut Document, pages: &[usize], bg: &Background, replace: bool) -> Result<(), EditError> {
- let all = page_list(doc);
- check(pages, all.len())?;
- if replace {
- remove_marks(doc, pages, MarkKind::Background)?;
- }
- let opacity = if bg.opacity.is_finite() { bg.opacity.clamp(0.0, 1.0) } else { 1.0 };
- for &i in pages {
- let mut page = page_list(doc)[i].clone();
- if bg.replace_backdrop && backdrop::replace(doc, &page)? {
- page = page_list(doc)[i].clone();
- }
- let (w, h) = page.display_size(doc);
- let mut content = begin(MarkKind::Background, "Background", page.view_matrix(doc));
- match &bg.source {
- Some(src) => {
- content.push_str(&format!("/PCGS{} gs\n", (opacity * 100.0).round() as i64));
- content.push_str(&picture(src, (w, h), bg.scale, 0.0, [0.0; 2]));
- }
- None => content.push_str(&format!("/PCGS{} gs\n{}\n0 0 {} {} re f\n", (opacity * 100.0).round() as i64, rgb(bg.color), n(w), n(h))),
- }
- content.push_str(END);
- add_resources(doc, &page, Some(opacity), None)?;
- if let Some(src) = &bg.source {
- add_picture_resource(doc, &page_list(doc)[i].clone(), src)?;
- }
- let page = &page_list(doc)[i];
- place(doc, page, MarkKind::Background, content.into_bytes(), true)?;
- }
- Ok(())
- }
-
- /// Remove marks of `kind` from `pages`; returns how many were removed. Wrappers left with
- /// nothing after them go too, restoring the original content list; a wrapper that content
- /// after it still relies on (another tool's appended stream) stays. Removing backgrounds also
- /// turns a backdrop [`add_background`] replaced back on where that is still safe; the pages where
- /// it isn't are [`backdrops_left_off`].
- pub fn remove_marks(doc: &mut Document, pages: &[usize], kind: MarkKind) -> Result<usize, EditError> {
- let all = page_list(doc);
- check(pages, all.len())?;
- let mut removed = 0;
- for &i in pages {
- let page = &all[i];
- if kind == MarkKind::Background {
- backdrop::restore(doc, page)?;
- }
- let list = contents(doc, page)?;
- let before = list.len();
- let mut kept: Vec<Object> = list.into_iter().filter(|o| stream_tag(doc, o).as_deref() != Some(kind.tag())).collect();
- removed += before - kept.len();
- // Strip only wrapper pairs whose close ends the list (after stripping the pairs after
- // it): nothing comes after them to need the state they restore. Pairs come from the
- // operators; for content that can't be read that precisely, from the wrapper streams
- // alone, so updating a mark there doesn't nest another wrapper each time.
- if before != kept.len() {
- let wrappers = match isolation(doc, &kept) {
- Isolation::Clean { wrappers, .. } => wrappers,
- Isolation::Unknown { .. } | Isolation::TooDeep => {
- let mut opens = Vec::new();
- let mut pairs = Vec::new();
- for (i, o) in kept.iter().enumerate() {
- match wrapper_role(doc, o) {
- Some(true) => opens.push(i),
- Some(false) => pairs.extend(opens.pop().map(|open| (open, i))),
- None => {}
- }
- }
- pairs
- }
- };
- let pairs: std::collections::HashMap<usize, usize> = wrappers.into_iter().map(|(open, close)| (close, open)).collect();
- let mut discarded = std::collections::HashSet::new();
- let mut end = kept.len();
- while let Some(close) = end.checked_sub(1) {
- if discarded.contains(&close) {
- end = close;
- } else if let Some(&open) = pairs.get(&close) {
- discarded.insert(open);
- discarded.insert(close);
- end = close;
- } else {
- break;
- }
- }
- kept = kept.into_iter().enumerate().filter(|(i, _)| !discarded.contains(i)).map(|(_, o)| o).collect();
- }
- if before != kept.len() {
- doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(kept)))?;
- }
- }
- Ok(removed)
- }
-
- /// Which kinds of marks the document has (for enabling Update/Remove).
- pub fn marks_present(doc: &Document) -> Vec<MarkKind> {
- added::scan_markers(doc).marks
- }
-
+pub mod backdrop;
+pub use backdrop::{Backdrop, backdrops_left_off, page_backdrop, page_backdrops};
mod background;
pub use background::page_background;
pub mod objects;
diff --cc crates/edit/src/marks.rs
index 000000000,507e2afa8..defe5a207
mode 000000,100644..100644
--- a/crates/edit/src/marks.rs
+++ b/crates/edit/src/marks.rs
@@@ -1,0 -1,298 +1,304 @@@
+ use super::*;
+
+ /// The kinds of page marks.
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+ pub enum MarkKind {
+ HeaderFooter,
+ Watermark,
+ Background,
+ }
+
+ impl MarkKind {
+ pub(crate) fn tag(self) -> &'static str {
+ match self {
+ MarkKind::HeaderFooter => "HeaderFooter",
+ MarkKind::Watermark => "Watermark",
+ MarkKind::Background => "Background",
+ }
+ }
+ }
+
+ /// Header and footer settings (Acrobat's Add Header and Footer dialog).
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct HeaderFooter {
+ /// Left, centre and right header text, then left, centre and right footer text. Tokens:
+ /// `<<1>>` page number, `<<n>>` page count, `<<1 of n>>`, `<<1/n>>`, `<<Page 1>>`,
+ /// `<<Page 1 of n>>`, dates `<<m/d/yyyy>>`, `<<mm/dd/yyyy>>`, `<<d/m/yyyy>>`, `<<yyyy-mm-dd>>`,
+ /// `<<yyyy/mm/dd>>`, `<<yyyy/m/d>>`, `<<m/d/yy>>`, `<<mmmm d, yyyy>>`, the dotted day-first
+ /// dates of German-speaking and much of Central and Eastern Europe `<<dd.mm.yyyy>>`,
+ /// `<<d.m.yyyy>>`, `<<dd.mm.yy>>`, `<<d.m.yy>>`, and Bates numbers `<<Bates Number#6#1#PRE#SUF>>`
+ /// (digits, start, prefix, suffix).
+ pub text: [String; 6],
+ /// The standard face the text is drawn in (#3754): Helvetica (the default), Times or Courier.
+ pub font: added::Family,
+ pub font_size: f64,
+ pub color: Rgb,
+ pub underline: bool,
+ /// Margins in points: top, bottom, left, right (the text's distance from the page edges).
+ pub margins: [f64; 4],
+ /// The number `<<1>>` shows on the first page of the range.
+ pub start_number: u32,
+ /// Shrink the page content so the header and footer don't cover it (Acrobat's Appearance
+ /// Options): the original content is scaled down evenly into the band the header and footer
+ /// leave free, centred across the page. Remove and Update take the scaling away again.
+ pub shrink: bool,
+ }
+
+ impl Default for HeaderFooter {
+ /// Acrobat's defaults: 8 pt black, margins 0.5 in top and bottom, 1 in left and right.
+ fn default() -> Self {
+ Self {
+ text: Default::default(),
+ font: added::Family::Helvetica,
+ font_size: 8.0,
+ color: [0.0; 3],
+ underline: false,
+ margins: [36.0, 36.0, 72.0, 72.0],
+ start_number: 1,
+ shrink: false,
+ }
+ }
+ }
+
+ impl HeaderFooter {
+ /// The first character [`add_header_footer`] would refuse, because the standard fonts can't
+ /// draw it (#125). Tokens only add ASCII (Bates prefixes and suffixes are part of the
+ /// template), so checking the templates, split as `expand`'s output is, covers every page
+ /// (and a `\r` that would be drawn is refused too). The dialog asks this too, so its preview
+ /// never offers text that applying refuses (#2013).
+ pub fn first_undrawable(&self) -> Option<char> {
+ self.text.iter().flat_map(|t| t.lines()).find_map(pdfcraft_fonts::first_non_win_ansi)
+ }
+
+ /// The room the header and the footer take at the top and the bottom of a page, in points:
+ /// the margin, the lines of the tallest box, and a clearance of half the font size. A side
+ /// without text takes none. This is the room [`HeaderFooter::shrink`] keeps free.
+ pub fn bands(&self) -> (f64, f64) {
+ let size = self.font_size;
+ let line_h = size * 1.2;
+ let lines = |boxes: &[String]| boxes.iter().filter(|t| !t.trim().is_empty()).map(|t| t.lines().count().max(1)).max();
+ let (header, footer) = self.text.split_at(3);
+ // Header lines hang below the top margin (a full line each); the footer's last line sits
+ // on the bottom margin, so only its capitals (0.8 of the size) rise above it.
+ let top = lines(header).map_or(0.0, |n| self.margins[0] + size + (n - 1) as f64 * line_h + size / 2.0);
+ let bottom = lines(footer).map_or(0.0, |n| self.margins[1] + size * 0.8 + (n - 1) as f64 * line_h + size / 2.0);
+ (top, bottom)
+ }
+ }
+
+ /// The `cm` that shrinks a page's original content (user space) into the band `hf` leaves free,
+ /// for a page shown `size` (display space) with view matrix `view` (display to user space): an
+ /// even scale, centred across, the content's bottom on the footer's band.
+ pub(crate) fn shrink_matrix(hf: &HeaderFooter, size: (f64, f64), view: [f64; 6]) -> Result<[f64; 6], EditError> {
+ let (w, h) = size;
+ let (top, bottom) = hf.bands();
+ let free = h - top - bottom;
+ if !(free.is_finite() && free >= 1.0 && w.is_finite() && w > 0.0) {
+ return Err(EditError::Invalid("the header and footer margins leave no room for the page content to shrink into".into()));
+ }
+ let k = free / h;
+ let v = kurbo::Affine::new(view);
+ let det = v.determinant();
+ if !(det.is_finite() && det.abs() > 1e-12) {
+ return Err(EditError::Invalid("the page can't be shrunk: its view matrix is degenerate".into()));
+ }
+ let shrink = kurbo::Affine::new([k, 0.0, 0.0, k, (w - w * k) / 2.0, bottom]);
+ // User space to display space, shrink there, and back.
+ Ok((v * shrink * v.inverse()).as_coeffs())
+ }
+
+ /// A picture for a background or watermark (Acrobat: Source ▸ File): an XObject already in
+ /// the document, an image (drawn into a unit square) or a form (a page of a PDF).
+ #[derive(Clone, Copy, Debug, PartialEq)]
+ pub struct MarkSource {
+ pub xobject: pdfcraft_cos::ObjRef,
+ /// Its natural size in points.
+ pub size: (f64, f64),
+ /// An image XObject (unit square); otherwise a form whose `/Matrix` maps it to `size`.
+ pub image: bool,
+ }
+
+ /// A watermark: text, or a picture from a file (`source`; the text is then ignored).
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct Watermark {
+ pub text: String,
+ pub source: Option<MarkSource>,
+ /// Pictures: size relative to the page (1.0 fits the page).
+ pub scale: f64,
+ /// 0 = fit: about half the page diagonal.
+ pub font_size: f64,
+ pub color: Rgb,
+ /// 0–1.
+ pub opacity: f64,
+ /// Degrees counter-clockwise (Acrobat's 45° runs from bottom-left to top-right).
+ pub rotation: f64,
+ /// Draw behind the page content instead of on top.
+ pub behind: bool,
+ /// Offset of the centre from the page centre, in points (right, up).
+ pub offset: [f64; 2],
+ }
+
+ impl Watermark {
+ /// The first character of a text watermark [`add_watermark`] would refuse, because the
+ /// standard fonts can't draw it (#125). A picture watermark draws no text.
+ pub fn first_undrawable(&self) -> Option<char> {
+ match self.source {
+ Some(_) => None,
+ None => self.text.trim().lines().find_map(pdfcraft_fonts::first_non_win_ansi),
+ }
+ }
+ }
+
+ impl Default for Watermark {
+ fn default() -> Self {
+ Self {
+ text: String::new(),
+ source: None,
+ scale: 0.5,
+ font_size: 0.0,
+ color: [0.6, 0.6, 0.6],
+ opacity: 0.5,
+ rotation: 45.0,
+ behind: false,
+ offset: [0.0; 2],
+ }
+ }
+ }
+
+ /// A background behind the page content: a solid colour, or a picture from a file.
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct Background {
+ pub color: Rgb,
+ pub opacity: f64,
+ pub source: Option<MarkSource>,
+ /// Pictures: size relative to the page (1.0 fits the page).
+ pub scale: f64,
++ /// Replace a white backdrop the page paints itself, which would hide the background
++ /// ([`backdrop`](crate::backdrop)). Removing the background turns it back on where that is
++ /// still safe ([`backdrops_left_off`](crate::backdrops_left_off) are the pages where it isn't).
++ pub replace_backdrop: bool,
+ }
+
+ impl Default for Background {
++ /// A light yellow that still reads as a colour on screen (a near-white default looked as if
++ /// nothing had happened).
+ fn default() -> Self {
- Self { color: [1.0, 1.0, 0.85], opacity: 1.0, source: None, scale: 1.0 }
++ Self { color: [1.0, 0.95, 0.7], opacity: 1.0, source: None, scale: 1.0, replace_backdrop: true }
+ }
+ }
+
+ /// Drawing a picture mark: fitted to the page at `scale`, centred (plus `offset`), turned by
+ /// `rotation` degrees. Returns the content and the resource name it uses.
+ pub(crate) fn picture(src: &MarkSource, page: (f64, f64), scale: f64, rotation: f64, offset: [f64; 2]) -> String {
+ let (w, h) = page;
+ let (sw, sh) = (src.size.0.max(0.01), src.size.1.max(0.01));
+ let k = (w / sw).min(h / sh) * if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
+ let (dw, dh) = (sw * k, sh * k);
+ let (s, c) = rotation.to_radians().sin_cos();
+ let (cx, cy) = (w / 2.0 + offset[0], h / 2.0 + offset[1]);
+ // Centre, rotate, then place the picture's box (unit square for images).
+ let place = if src.image {
+ format!("{} 0 0 {} {} {} cm", n(dw), n(dh), n(-dw / 2.0), n(-dh / 2.0))
+ } else {
+ format!("{} 0 0 {} {} {} cm", n(k), n(k), n(-dw / 2.0), n(-dh / 2.0))
+ };
+ format!("{} {} {} {} {} {} cm\n{place}\n/PCPic{} Do\n", n(c), n(s), n(-s), n(c), n(cx), n(cy), src.xobject.num)
+ }
+
+ /// Register a mark picture in the page's own resources (`/PCPic<num>`).
+ pub(crate) fn add_picture_resource(doc: &mut Document, page: &pdfcraft_model::Page, src: &MarkSource) -> Result<(), EditError> {
+ let p = doc.get(page.obj).as_dict().cloned().unwrap_or_default();
+ let mut res = p.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
+ let mut xo = res.get(b"XObject").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default();
+ xo.set(format!("PCPic{}", src.xobject.num).into_bytes(), Object::Ref(src.xobject));
+ res.set(b"XObject".to_vec(), Object::Dict(xo));
+ doc.update_dict(page.obj, |d| d.set(b"Resources".to_vec(), Object::Dict(res)))?;
+ Ok(())
+ }
+
+ /// Values tokens need that come from outside the document.
+ #[derive(Clone, Debug, PartialEq, Default)]
+ pub struct Context {
+ /// Today's date: (year, month 1–12, day 1–31).
+ pub date: (i64, u32, u32),
+ }
+
+ // Model-derived transforms can contain tiny scale factors; retain their PDF decimal precision.
+ pub(crate) fn matrix_number(value: f64) -> String {
+ let mut bytes = Vec::new();
+ pdfcraft_cos::serialize(&Object::Real(value), &mut bytes);
+ String::from_utf8_lossy(&bytes).into_owned()
+ }
+
+ pub(crate) fn n(v: f64) -> String {
+ let s = format!("{:.3}", if v.abs() < 5e-4 { 0.0 } else { v });
+ let s = s.trim_end_matches('0').trim_end_matches('.');
+ if s == "-0" { "0".into() } else { s.into() }
+ }
+
+ pub(crate) fn rgb(c: Rgb) -> String {
+ let c = c.map(|x| x.clamp(0.0, 1.0));
+ format!("{} {} {} rg", n(c[0]), n(c[1]), n(c[2]))
+ }
+
+ const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
+
+ /// Expand `<<…>>` tokens for page `index` (0-based within the range) of `count`.
+ pub fn expand(template: &str, page_number: u32, count: usize, bates: u64, cx: &Context) -> String {
+ let (y, m, d) = cx.date;
+ let mut out = String::new();
+ let mut rest = template;
+ while let Some(start) = rest.find("<<") {
+ out.push_str(&rest[..start]);
+ let after = &rest[start + 2..];
+ let Some(end) = after.find(">>") else {
+ out.push_str(&rest[start..]);
+ return out;
+ };
+ let token = &after[..end];
+ let p = page_number;
+ let value = match token {
+ "1" => p.to_string(),
+ "n" => count.to_string(),
+ "1 of n" => format!("{p} of {count}"),
+ "1/n" => format!("{p}/{count}"),
+ "Page 1" => format!("Page {p}"),
+ "Page 1 of n" => format!("Page {p} of {count}"),
+ "m/d" => format!("{m}/{d}"),
+ "m/d/yy" => format!("{m}/{d}/{:02}", y.rem_euclid(100)),
+ "m/d/yyyy" => format!("{m}/{d}/{y}"),
+ "mm/dd/yy" => format!("{m:02}/{d:02}/{:02}", y.rem_euclid(100)),
+ "mm/dd/yyyy" => format!("{m:02}/{d:02}/{y}"),
+ "d/m/yy" => format!("{d}/{m}/{:02}", y.rem_euclid(100)),
+ "d/m/yyyy" => format!("{d}/{m}/{y}"),
+ "dd/mm/yyyy" => format!("{d:02}/{m:02}/{y}"),
+ "d.m.yy" => format!("{d}.{m}.{:02}", y.rem_euclid(100)),
+ "d.m.yyyy" => format!("{d}.{m}.{y}"),
+ "dd.mm.yy" => format!("{d:02}.{m:02}.{:02}", y.rem_euclid(100)),
+ "dd.mm.yyyy" => format!("{d:02}.{m:02}.{y}"),
+ "yyyy-mm-dd" => format!("{y}-{m:02}-{d:02}"),
+ "yyyy/mm/dd" => format!("{y}/{m:02}/{d:02}"),
+ "yyyy/m/d" => format!("{y}/{m}/{d}"),
+ "mmmm d, yyyy" => format!("{} {d}, {y}", MONTHS[(m.clamp(1, 12) - 1) as usize]),
+ t if t.starts_with("Bates Number") => {
+ // Bates Number#digits#start#prefix#suffix (start is applied by the caller).
+ let parts: Vec<&str> = t.split('#').collect();
+ let digits = parts.get(1).and_then(|d| d.parse::<usize>().ok()).unwrap_or(6).clamp(1, 15);
+ format!("{}{:0digits$}{}", parts.get(3).unwrap_or(&""), bates, parts.get(4).unwrap_or(&""))
+ }
+ _ => format!("<<{token}>>"),
+ };
+ out.push_str(&value);
+ rest = &after[end + 2..];
+ }
+ out.push_str(rest);
+ out
+ }
+
+ /// The Bates start number in a template (`<<Bates Number#digits#start#…>>`), if any.
+ pub(crate) fn bates_start(template: &str) -> Option<u64> {
+ let i = template.find("<<Bates Number")?;
+ let t = &template[i + 2..];
+ let t = &t[..t.find(">>")?];
+ t.split('#').nth(2).and_then(|s| s.parse().ok()).or(Some(1))
+ }
diff --cc crates/engine/src/lib.rs
index 75227e904,889b83936..270cdb75c
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@@ -69,7 -68,57 +68,57 @@@ pub use signature_scan::{PhotoRect, Sca
pub use stamp_preview::StampPreview;
pub use text_preview::TextEditPreview;
- pub use reexports::*;
+ pub use pdfcraft_organize::{BoxSpec, FieldConflicts, PageBox, SplitBy, Transition, TransitionSpec, mime_for_name, split_ranges};
+
+ pub use pdfcraft_organize::LabelStyle;
+ pub use pdfcraft_organize::Standard;
+ pub use pdfcraft_organize::check_custom_key;
+ pub use pdfcraft_organize::view::{InitialView, Layout as InitialLayout, Magnification, Navigation};
+
+ pub use pdfcraft_cos::Algorithm;
+ pub use pdfcraft_create::{CONVERTIBLE, CreateError, ImageResolution, SourceKind, decode_text, source_kind};
+ pub use pdfcraft_edit::added::{
+ CHAR_SPACING_LIMIT as ADDED_CHAR_SPACING_LIMIT, paste_place as added_paste_place, paste_rect as added_paste_rect, text_rect as added_text_rect,
+ text_width as added_text_width,
+ };
+ pub use pdfcraft_edit::{
+ Added, AddedImage, AddedText, Align as TextAlign, Background, Content as AddedContent, Family as FontFamily, HeaderFooter, MarkKind, Watermark,
+ };
+ pub use pdfcraft_forms::{
+ BorderStyle, CalculatedField, CalculationIssue, CalculationOrder, CheckStyle, Field as FormField, FieldAction, FieldChange, FieldFont,
+ FieldKind as FormFieldKind, FieldProps, FieldValue, Look as FieldLook, LookPatch as FieldLookPatch, NewField, TabOrder, Trigger as FieldTrigger,
+ Widget as FormWidget, af as form_scripts, appearance as form_appearance, appearance::auto_text_size_by as field_auto_text_size_by,
+ calculations_changed as form_calculations_changed, flags as field_flags,
+ };
+
+ pub use pdfcraft_a11y as a11y;
-pub use pdfcraft_edit::{BlockKey, BlockStyle, PageImage, RangeStyle, TextBlock, TextLine, block_overlapping, first_undrawable};
++pub use pdfcraft_edit::{Backdrop, BlockKey, BlockStyle, PageImage, RangeStyle, TextBlock, TextLine, block_overlapping, first_undrawable};
+ pub use pdfcraft_measure as measure;
+ pub use pdfcraft_xfa::Report as XfaLayout;
+
+ pub use pdfcraft_edit::{EditableObject, MAX_MOVE_OBJECTS, ObjectKind, ObjectTarget};
+
+ pub use pdfcraft_fonts::{MAX_SIGNATURE_CHARS, ScriptOutline, script_missing, script_outline, undrawable_message};
+
+ /// Comment geometry helpers (text-box line breaking) for frontends.
+ pub use pdfcraft_annot::appearance as annot_text;
+ pub use pdfcraft_annot::links::{Highlight as LinkHighlight, LinkAction, LinkItem, LinkStyle};
+ pub use pdfcraft_annot::{
+ AppearanceCache, AttachIcon, FillMark, LineEnding, Markup, NOTE_SIZE, NewAnnotation, NoteIcon, OverlayFont, OverlayLook, Props as CommentProps,
+ ReviewState, Rgb, Shape, StampGroup, StampKind, Style, rect_quad,
+ };
+ pub use pdfcraft_forms::detect;
+ pub use pdfcraft_optimize as optimize;
+ pub use pdfcraft_preflight as pdfa;
+ pub use pdfcraft_print as print;
+ pub use pdfcraft_redact::codes::{CODE_SETS as REDACTION_CODE_SETS, CodeSet as RedactionCodeSet};
+ pub use pdfcraft_redact::patterns::{
+ MAX_WORDS as REDACT_MAX_WORDS, PATTERNS as REDACT_PATTERNS, Pattern as RedactPattern, find as find_pattern, word_list as redact_word_list,
+ };
+ pub use pdfcraft_redact::sanitize::{HIDDEN, Hidden};
+ pub use pdfcraft_sign as sign;
+ pub use pdfcraft_sign::{SignOptions, SignatureInfo, Status as SignatureStatus, TrustStore};
+ pub use pdfcraft_xfdf::Format as DataFormat;
use bookmarks::outline_rows;
pub use bookmarks::{BookmarkPage, BookmarkRow};
diff --cc crates/engine/src/session.rs
index ab4d0345a,1051903ba..59c3f90f8
--- a/crates/engine/src/session.rs
+++ b/crates/engine/src/session.rs
@@@ -10,14 -10,19 +10,19 @@@ use crate::check_refresh_panic
use crate::edit::{EditCtx, check_permission, run_edit};
use crate::history::{Keys, MAX_UNDO, Scope, keys_after, scope_of, uses_scripts};
use crate::{
- BookmarkPage, BookmarkRow, CombineSource, Combined, DataFormat, DocId, Document, Edit, EditError, Hidden, ImageResolution,
- LOW_RESOLUTION_PRINT_DPI, Label, ObjectKind, OptimizeReport, RecoverySnapshot, SignOptions, SourceKind, SplitPart, SummarySort, TrustStore,
- XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, apply_layer_state, comment_list, comment_summary, decode_text, display_bytes, guard, info_fields, js,
- local_utc_offset, note_warnings, open_source, open_source_with, optimize, outline_rows, parse_ymd, print, print_raster, render_threads,
- scan_colours, set_default_layer_state, shown_under_redactions, signatures_of, source_kind, sync_xfa_state, undrawn_notices, use_layer_choices,
- writable, xfa, xfa_sync_datasets,
+ BookmarkPage, BookmarkRow, CombineSource, Combined, DataFormat, DocId, Document, Edit, EditError, EditNotice, Hidden, ImageResolution,
+ LOW_RESOLUTION_PRINT_DPI, Label, MarkKind, ObjectKind, OptimizeReport, RecoverySnapshot, SignOptions, SourceKind, SplitPart, SummarySort,
+ TrustStore, XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, apply_layer_state, comment_list, comment_summary, decode_text, display_bytes, guard,
+ info_fields, js, local_utc_offset, note_warnings, open_source, open_source_with, optimize, outline_rows, parse_ymd, print, print_raster,
+ render_threads, scan_colours, set_default_layer_state, shown_under_redactions, signatures_of, source_kind, sync_xfa_state, undrawn_notices,
+ use_layer_choices, writable, xfa, xfa_sync_datasets,
};
+ mod editing;
+ mod files;
+ mod save;
+ mod view;
+
#[derive(Default)]
pub struct Session {
pub(crate) docs: Vec<Document>,
diff --cc crates/engine/src/session/editing.rs
index 000000000,9b1a8340a..00f38a823
mode 000000,100644..100644
--- a/crates/engine/src/session/editing.rs
+++ b/crates/engine/src/session/editing.rs
@@@ -1,0 -1,521 +1,528 @@@
+ use super::*;
+
+ 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.
+ 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()));
+ }
+ // What this edit drew with `?` (a value or comment text its font can't draw, stored as
+ // typed): reported, never silent (AGENTS.md §4).
- let notices = if matches!(scope_of(&edit), Scope::Form | Scope::Comments | Scope::Full) {
- guard(|| undrawn_notices(&editor.cos, &next)).unwrap_or_default()
++ let mut notices: Vec<EditNotice> = if matches!(scope_of(&edit), Scope::Form | Scope::Comments | Scope::Full) {
++ guard(|| undrawn_notices(&editor.cos, &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: said, not silent.
++ 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 });
++ }
++ }
+ 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, &notes);
+ 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(), doc.config.clone());
+ 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(), doc.config.clone());
+ 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(), doc.config.clone());
+ }
+
+ /// 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(), doc.config.clone());
+ doc.bytes = bytes;
+ Ok(())
+ }
+ }
diff --cc crates/ui-egui/src/app/control.rs
index 000000000,bb5a65cb3..14f899de6
mode 000000,100644..100644
--- a/crates/ui-egui/src/app/control.rs
+++ b/crates/ui-egui/src/app/control.rs
@@@ -1,0 -1,392 +1,395 @@@
+ use super::*;
+ use crate::control;
+
+ impl PdfCraftApp {
+ /// Enable the UI control channel on `ctx` (opt-in; see [`control`]). Returns a client that
+ /// sends requests to this app; [`control::serve`] exposes it on loopback.
+ pub fn attach_control(&mut self, ctx: &egui::Context) -> control::ControlClient {
+ let (control, client) = control::attach(ctx);
+ self.control = Some(control);
+ client
+ }
+
+ /// Apply a named view option (`--page 3`, `--panel bookmarks`, `--theme dark`, …).
+ ///
+ /// This is the seed of the UI control channel (M3.9): the same verbs become `ui.set` calls.
+ pub fn set_option(&mut self, key: &str, value: &str) -> Result<(), String> {
+ let view = self.active.and_then(|i| self.views.get_mut(i));
+ match (key, view) {
+ ("language", _) => {
+ let language = i18n::normalize_pref(value).ok_or_else(|| {
+ let codes: Vec<&str> = std::iter::once(i18n::AUTO).chain(i18n::Lang::all().map(i18n::Lang::code)).collect();
+ format!("language must be one of {}", codes.join(", "))
+ })?;
+ self.language = language.to_string();
+ }
+ ("theme", _) => {
+ let preference = match value {
+ "system" => ThemePreference::System,
+ "light" => ThemePreference::Light,
+ "dark" => ThemePreference::Dark,
+ _ => return Err("theme must be light, dark, or system".into()),
+ };
+ self.set_theme_preference(preference);
+ }
+ ("scroll_speed", _) => {
+ self.scroll_speed = scroll_speed::ScrollSpeed::parse(value).ok_or("scroll_speed must be slow, normal, or fast")?;
+ }
+ ("animation_effects", _) => {
+ self.animation_effects = motion::AnimationEffects::parse(value).ok_or("animation_effects must be system, on, or off")?;
+ }
+ ("panel", _) => {
+ self.right = match value {
+ "comments" => Some(RightPanel::Comments),
+ "bookmarks" => Some(RightPanel::Bookmarks),
+ "pages" => Some(RightPanel::Pages),
+ "fields" => Some(RightPanel::Fields),
+ "layers" => Some(RightPanel::Layers),
+ "attachments" => Some(RightPanel::Attachments),
+ "signatures" => Some(RightPanel::Signatures),
+ "accessibility" => Some(RightPanel::Accessibility),
+ "tags" => Some(RightPanel::Tags),
+ "search" => Some(RightPanel::Search),
+ "compare" => Some(RightPanel::Compare),
+ "none" => None,
+ other => return Err(format!("unknown panel {other}")),
+ }
+ }
+ ("mode", _) => {
+ let mode = Mode::parse(value).unwrap_or(Mode::AllTools);
+ self.mode_override = Some(mode);
+ self.mode = mode;
+ // As switch_mode: another workspace puts the expanded All tools view away.
+ if mode != Mode::AllTools {
+ self.all_tools_full = false;
+ }
+ }
+ ("default-mode", _) => {
+ self.default_mode = Mode::parse(value).ok_or("default-mode must be all, read, edit, convert or sign")?;
+ }
+ ("date-format", _) => self.session.set_date_format(value)?,
+ ("date-language", _) => self.session.set_date_language(Some(value).filter(|v| *v != "auto"))?,
+ ("tool", _) => {
+ let g = pdfcraft_engine::catalog::group(value).ok_or_else(|| format!("unknown tool {value}"))?;
+ self.select_tool(g.id);
+ }
+ ("left", _) => self.left_open = value != "closed",
+ ("home", _) => {
+ self.active = None;
+ // With no document open the expanded All tools view covers Home itself, so no
+ // other tab comes forward to put it away.
+ self.all_tools_full = false;
+ }
+ ("dialog", _) => {
+ self.dialog = match value {
+ "properties" => Some(Dialog::Properties(PropsTab::Description)),
+ "security" => Some(Dialog::Properties(PropsTab::Security)),
+ "fonts" => Some(Dialog::Properties(PropsTab::Fonts)),
+ "custom" => Some(Dialog::Properties(PropsTab::Custom)),
+ "advanced" => Some(Dialog::Properties(PropsTab::Advanced)),
+ "space-audit" => Some(Dialog::Properties(PropsTab::SpaceAudit)),
+ "shortcuts" => Some(Dialog::Shortcuts),
+ "split" => Some(Dialog::Split),
+ "protect" => Some(Dialog::Protect),
+ "page-boxes" => Some(Dialog::PageBoxes),
+ "header-footer" => Some(Dialog::Marks(pdfcraft_engine::MarkKind::HeaderFooter)),
+ "watermark" => Some(Dialog::Marks(pdfcraft_engine::MarkKind::Watermark)),
+ "background" => Some(Dialog::Marks(pdfcraft_engine::MarkKind::Background)),
+ "export-image" => Some(Dialog::Export(export_ui::ExportKind::Image)),
+ "word-count" => Some(Dialog::WordCount),
+ "export-text" => Some(Dialog::Export(export_ui::ExportKind::Text)),
+ "export-all-images" => Some(Dialog::Export(export_ui::ExportKind::AllImages)),
+ "accessibility-options" => Some(Dialog::AccessibilityOptions),
+ "recognize-text" => Some(Dialog::RecognizeText),
+ "js-console" => Some(Dialog::JsConsole),
+ "document-js" => Some(Dialog::DocumentJs),
+ "preferences" => Some(Dialog::Preferences),
+ "compare-files" => Some(Dialog::CompareFiles),
+ "action-wizard" => Some(Dialog::ActionWizard),
+ "pdfa" => Some(Dialog::PdfA),
+ "signature" => Some(Dialog::Signature),
+ "optimize" => Some(Dialog::Optimize),
+ "sign" | "certify" => {
+ // Sign with a Digital ID for an invisible signature on the current page.
+ let page = self.active.map_or(0, |i| self.views[i].current);
+ self.start_signing(page, None, None, (value == "certify").then_some(2));
+ Some(Dialog::Sign)
+ }
+ "number-pages" => {
+ // Same path as the menu, so the page range is seeded.
+ self.execute("page.number");
+ Some(Dialog::NumberPages)
+ }
+ "none" => None,
+ _ => Some(Dialog::About),
++ };
++ if let Some(Dialog::Marks(kind)) = self.dialog {
++ self.marks_draft.opened(kind);
+ }
+ }
+ ("tools", _) if value == "full" => self.expand_all_tools(),
+ ("tools", _) => {
+ self.all_tools_full = false;
+ self.all_tools_expanded = value != "collapsed";
+ }
+ ("palette", _) => {
+ self.palette_open = true;
+ self.palette_query = value.to_string();
+ }
+ ("page", Some(v)) => v.go_to_page(value.parse::<usize>().map_err(|e| e.to_string())?.saturating_sub(1)),
+ ("zoom", Some(v)) => v.set_zoom(DocView::parse_zoom_percent(value).ok_or("zoom must be a percentage above 0")?),
+ ("layout", Some(v)) => {
+ let (layout, continuous) = canvas::parse_display_token(value).ok_or("layout must be single, continuous, two-up or two-page")?;
+ v.set_display(layout, continuous);
+ }
+ ("continuous", Some(v)) => match value {
+ "on" => v.set_continuous(true),
+ "off" => v.set_continuous(false),
+ _ => return Err("continuous must be on or off".into()),
+ },
+ ("page-gaps", Some(_)) => {
+ let show = match value {
+ "on" => true,
+ "off" => false,
+ _ => return Err("page-gaps must be on or off".into()),
+ };
+ self.set_active_page_gaps(show);
+ }
+ ("default-page-gaps", _) => {
+ self.view_defaults.show_page_gaps = match value {
+ "on" => true,
+ "off" => false,
+ _ => return Err("default-page-gaps must be on or off".into()),
+ };
+ }
+ ("cover", Some(v)) => {
+ let on = match value {
+ "on" => true,
+ "off" => false,
+ _ => return Err("cover must be on or off".into()),
+ };
+ if on && !v.cover_applies() {
+ return Err("switch to two-page view first to show the cover page".into());
+ }
+ v.set_cover(on);
+ }
+ ("default-layout", _) => {
+ let (layout, continuous) =
+ canvas::parse_display_token(value).ok_or("default-layout must be single, continuous, two-up or two-page")?;
+ (self.view_defaults.layout, self.view_defaults.continuous) = (layout, continuous);
+ }
+ ("default-continuous", _) => {
+ self.view_defaults.continuous = match value {
+ "on" => true,
+ "off" => false,
+ _ => return Err("default-continuous must be on or off".into()),
+ };
+ }
+ ("default-zoom", _) => {
+ self.view_defaults =
+ self.view_defaults.with_zoom(value).ok_or("default-zoom must be fit-width, fit-page or a percentage from 8 to 6400")?;
+ }
+ ("always-default-view", _) => {
+ self.always_default_view = match value {
+ "on" => true,
+ "off" => false,
+ _ => return Err("always-default-view must be on or off".into()),
+ };
+ }
+ ("tools-side", _) => {
+ self.side_panels.tools_side = match value {
+ "left" => side_panels::ToolsSide::Left,
+ "right" => side_panels::ToolsSide::Right,
+ _ => return Err("tools-side must be left or right".into()),
+ }
+ }
+ ("organize", Some(v)) => {
+ if value == "off" {
+ v.organize = false;
+ } else {
+ v.open_organize();
+ }
+ }
+ // Inspector thumbnail size, in percent, independent of document and grid zoom.
+ ("thumbnail-zoom", Some(v)) => {
+ let percent = value.trim_end_matches('%').parse::<f32>().map_err(|e| e.to_string())?;
+ if !percent.is_finite() || !canvas::THUMBNAIL_ZOOM_RANGE.contains(&(percent / 100.0)) {
+ return Err("thumbnail-zoom must be between 50 and 150".into());
+ }
+ v.set_thumbnail_zoom(percent / 100.0);
+ }
+ // `--grid-zoom 150`: the size of the pages in the organize grid, in percent.
+ ("grid-zoom", Some(v)) => {
+ let percent = value.trim_end_matches('%').parse::<f32>().map_err(|e| e.to_string())?;
+ if !percent.is_finite() || !canvas::GRID_ZOOM_RANGE.contains(&(percent / 100.0)) {
+ return Err("grid-zoom must be between 50 and 300".into());
+ }
+ v.set_grid_zoom(percent / 100.0);
+ // The grid's size is one for every document, as it is remembered.
+ self.organize_zoom = v.grid_zoom();
+ }
+ ("rotate", Some(v)) => {
+ let deg: u16 = value.parse().map_err(|_| "rotate: 0, 90, 180 or 270")?;
+ if !deg.is_multiple_of(90) {
+ return Err("rotate: 0, 90, 180 or 270".into());
+ }
+ v.rotation = deg % 360;
+ }
+ ("layer", _) => {
+ // `--layer "Name=off"` / `"Name=on"`
+ let (name, state) = value.rsplit_once('=').ok_or("expected NAME=on|off")?;
+ let (i, id) = self.active_ids().ok_or("`layer` needs an open document")?;
+ let idx = self
+ .session
+ .get(id)
+ .and_then(|d| d.info.layers.iter().position(|l| l.name == name))
+ .ok_or_else(|| format!("no layer named {name}"))?;
+ if self.session.set_layer_visible(id, idx, state != "off") {
+ self.views[i].invalidate_content();
+ }
+ }
+ ("find", Some(v)) => {
+ v.open_find();
+ if let Some(f) = v.find.as_mut() {
+ f.query = value.to_string();
+ }
+ v.rerun_find();
+ }
+ ("fields", Some(v)) => v.highlight_fields = value != "off",
+ ("select", Some(v)) => {
+ // The same physical page ranges as the Organize Pages selection field.
+ let pages = crate::page_selection_ui::parse(value, v.page_count()).map_err(|e| e.to_string())?;
+ v.select_pages(&pages);
+ }
+ ("notice", Some(v)) => v.notice_dismissed = value == "off",
+ ("quick", _) => {
+ // `--quick select|hand|note|freetext|highlight|underline|strikeout|ink|line|arrow|square|circle`
+ self.quick_tool = match value {
+ "select" => QuickTool::Select,
+ measure if measure.starts_with("measure-") => QuickTool::Measure(
+ measure_ui::Tool::from_name(measure.trim_start_matches("measure-")).ok_or_else(|| format!("unknown tool {measure}"))?,
+ ),
+ "hand" => QuickTool::Hand,
+ "crop" => QuickTool::Crop,
+ "enhance-camera" => QuickTool::EnhanceCamera,
+ "redact" => QuickTool::Redact,
+ "add-text" => QuickTool::AddText,
+ "edit-text" => QuickTool::EditText,
+ "link" => QuickTool::Link,
+ "sign" => QuickTool::SignArea { certify: false },
+ "marquee-zoom" => QuickTool::MarqueeZoom,
+ "snapshot" => QuickTool::Snapshot,
+ "column-select" => QuickTool::ColumnSelect,
+ "certify" => QuickTool::SignArea { certify: true },
+ custom if custom.starts_with("custom-stamp-") => {
+ let i: usize = custom[13..].parse().map_err(|_| format!("bad stamp {custom}"))?;
+ if i >= self.custom_stamps.len() {
+ return Err(format!("there are {} custom stamps", self.custom_stamps.len()));
+ }
+ QuickTool::CustomStamp(i)
+ }
+ stamp if stamp.starts_with("stamp-") => QuickTool::Stamp(
+ pdfcraft_engine::StampKind::ALL
+ .into_iter()
+ .find(|k| k.name().trim_start_matches("PC").eq_ignore_ascii_case(&stamp[6..]))
+ .ok_or_else(|| format!("unknown stamp {stamp}"))?,
+ ),
+ field if field.starts_with("field-") => QuickTool::Field(
+ prepare::FieldTool::from_command(&format!("form.add.{}", &field[6..])).ok_or_else(|| format!("unknown tool {field}"))?,
+ ),
+ fill if fill.starts_with("fill-") => QuickTool::Fill(
+ fill_sign::FillTool::from_command(&format!("sign.fill.{}", &fill[5..])).ok_or_else(|| format!("unknown tool {fill}"))?,
+ ),
+ other => {
+ let t = comments::CommentTool::from_command(&format!("comment.{other}")).ok_or_else(|| format!("unknown tool {other}"))?;
+ self.comment_prefs.group_tool[t.group()] = t;
+ QuickTool::Comment(t)
+ }
+ };
+ }
+ ("author", _) => self.comment_prefs.author = value.to_string(),
+ ("comment-tool-pinned", _) => {
+ self.comment_prefs.pinned = match value {
+ "true" => true,
+ "false" => false,
+ _ => return Err("comment-tool-pinned must be true or false".into()),
+ };
+ }
+ ("hide-empty-highlight-hover", _) => {
+ self.comment_prefs.hide_empty_highlight_hover = match value {
+ "true" => true,
+ "false" => false,
+ _ => return Err("hide-empty-highlight-hover must be true or false".into()),
+ };
+ }
+ ("ui-scale", _) => self.ui_scale = ui_scale::parse(value)?,
+ // `--secured-notice false`: no notice above the pages that a document is secured.
+ ("secured-notice", _) => {
+ self.show_secured_notice = match value {
+ "true" => true,
+ "false" => false,
+ _ => return Err("secured-notice must be true or false".into()),
+ };
+ }
+ ("system-title-bar", _) => {
+ self.system_title_bar = match value {
+ "true" => true,
+ "false" => false,
+ _ => return Err("system-title-bar must be true or false".into()),
+ };
+ }
+ ("flatten-fill-sign", _) => {
+ self.flatten_fill_sign_on_save = match value {
+ "true" => true,
+ "false" => false,
+ _ => return Err("flatten-fill-sign must be true or false".into()),
+ };
+ }
+ ("comment", Some(v)) => {
+ // `--comment 2:4` selects the 4th annotation of page 2 (1-based, as comment_list reports).
+ let (p, i) = value.split_once(':').ok_or("comment: PAGE:INDEX")?;
+ let (p, i): (usize, usize) =
+ (p.trim().parse().map_err(|_| "comment: PAGE:INDEX")?, i.trim().parse().map_err(|_| "comment: PAGE:INDEX")?);
+ v.comments.selected = Some((p.saturating_sub(1), i.saturating_sub(1)));
+ v.comments.reveal = true;
+ }
+ // `--combine-view list`: Combine files as thumbnails (grid) or as the table (list).
+ ("combine-view", _) => {
+ self.combine_view = combine_ui::CombineView::parse(value).ok_or("combine-view must be grid or list")?;
+ }
+ // `--combine-zoom 150`: the size of the cards in the Combine grid, in percent.
+ ("combine-zoom", _) => {
+ let percent = value.trim_end_matches('%').parse::<f32>().map_err(|e| e.to_string())?;
+ if !percent.is_finite() || !combine_grid::ZOOM_RANGE.contains(&(percent / 100.0)) {
+ let (lo, hi) = (combine_grid::ZOOM_RANGE.start(), combine_grid::ZOOM_RANGE.end());
+ return Err(format!("combine-zoom must be between {} and {}", lo * 100.0, hi * 100.0));
+ }
+ self.set_combine_zoom(percent / 100.0);
+ }
+ (k, None)
+ if [
+ "page",
+ "zoom",
+ "layout",
+ "continuous",
+ "page-gaps",
+ "cover",
+ "organize",
+ "grid-zoom",
+ "thumbnail-zoom",
+ "fields",
+ "find",
+ "rotate",
+ "select",
+ "notice",
+ "comment",
+ ]
+ .contains(&k) =>
+ {
+ return Err(format!("`{k}` needs an open document"));
+ }
+ (other, _) => return Err(format!("unknown option {other}")),
+ }
+ Ok(())
+ }
+ }