PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge remote-tracking branch 'upstream/main' into feat/bookmarks-from-text-styles
Claude65d838561678
diff --cc crates/automation/src/dispatch.rsindex 000000000,26e1f9536..5b9b96c8dmode 000000,100644..100644--- a/crates/automation/src/dispatch.rs+++ b/crates/automation/src/dispatch.rs@@@ -1,0 -1,784 +1,812 @@@+ use super::error::{Result, ToolError, failed};-use super::json::{Args, document_attachment_keys, info, one_based, parse_style_ranges, security, summary};++use super::json::{Args, document_attachment_keys, info, one_based, parse_style_ranges, security, summary, text_style_levels};+ 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+ }++ "text_styles" => {++ // The samples are the document's text, as text_lines is.++ let doc = self.doc_to_copy(&a)?;++ let styles: Vec<Value> = doc++ .text_styles()++ .into_iter()++ .map(|u| {++ json!({++ "font": u.style.font,++ "size": u.style.size,++ "bold": u.style.bold,++ "italic": u.style.italic,++ "lines": u.lines,++ "pages": u.pages,++ "sample": u.sample,++ })++ })++ .collect();++ json!({ "styles": styles })++ }++ "bookmark_from_text_styles" => {++ let levels = text_style_levels(&a)?;++ let mut out = self.apply(&a, Edit::BookmarksFromTextStyles { levels })?;++ 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, ¤t);+ 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_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/json.rsindex 000000000,c8710aa50..7a21654a3mode 000000,100644..100644--- a/crates/automation/src/json.rs+++ b/crates/automation/src/json.rs@@@ -1,0 -1,361 +1,391 @@@+ use super::error::{Result, ToolError};+ use super::*;++ /// How far from the page's corner a bookmark's position may be given, in points (a PDF page is at+ /// most 14 400 across).+ const MAX_BOOKMARK_POSITION: f64 = 1_000_000.0;++ // ---- JSON helpers ----------------------------------------------------------------------------+++/// The most bookmark levels `bookmark_from_text_styles` takes.++const MAX_STYLE_LEVELS: usize = 9;++++/// bookmark_from_text_styles' `levels`: one style per bookmark level, the first level 1, each++/// `{ font, size, bold, italic }` as text_styles lists them.++pub(crate) fn text_style_levels(a: &Args) -> Result<Vec<pdfcraft_engine::text_style_bookmarks::TextStyle>> {++ let levels =++ a.get("levels").and_then(Value::as_array).ok_or_else(|| ToolError::InvalidArgs("levels must list a style for each bookmark level".into()))?;++ if levels.is_empty() || levels.len() > MAX_STYLE_LEVELS {++ return Err(ToolError::InvalidArgs(format!("levels must list 1 to {MAX_STYLE_LEVELS} styles")));++ }++ levels++ .iter()++ .enumerate()++ .map(|(i, v)| {++ let bad = |what: &str| ToolError::InvalidArgs(format!("levels[{i}]: {what}"));++ let font =++ v.get("font").and_then(Value::as_str).filter(|f| !f.is_empty()).ok_or_else(|| bad("font must be a font name from text_styles"))?;++ let size =++ v.get("size").and_then(Value::as_f64).filter(|s| s.is_finite() && *s > 0.0).ok_or_else(|| bad("size must be a positive number"))?;++ let flag = |key: &str| match v.get(key) {++ None | Some(Value::Null) => Ok(false),++ Some(Value::Bool(b)) => Ok(*b),++ Some(_) => Err(bad(&format!("{key} must be true or false"))),++ };++ Ok(pdfcraft_engine::text_style_bookmarks::TextStyle { font: font.to_string(), size, bold: flag("bold")?, italic: flag("italic")? })++ })++ .collect()++}+++ pub(crate) fn parse_style_ranges(value: Option<&Value>) -> Result<Vec<pdfcraft_engine::RangeStyle>> {+ let Some(value) = value else { return Ok(Vec::new()) };+ let values = value.as_array().filter(|v| v.len() <= 1024).ok_or_else(|| Args::wrong("ranges", "an array of at most 1024 style objects"))?;+ values+ .iter()+ .map(|v| {+ let a = Args(v);+ let bounds = a+ .get("range")+ .and_then(Value::as_array)+ .filter(|v| v.len() == 2)+ .ok_or_else(|| Args::wrong("range", "[start,end] UTF-8 byte offsets"))?;+ let start = bounds+ .first()+ .and_then(Value::as_u64)+ .and_then(|n| usize::try_from(n).ok())+ .ok_or_else(|| Args::wrong("range", "nonnegative byte offsets"))?;+ let end = bounds+ .get(1)+ .and_then(Value::as_u64)+ .and_then(|n| usize::try_from(n).ok())+ .ok_or_else(|| Args::wrong("range", "nonnegative byte offsets"))?;+ let family = a+ .opt_str("font")?+ .map(|f| match f {+ "helvetica" => Ok(pdfcraft_engine::FontFamily::Helvetica),+ "times" => Ok(pdfcraft_engine::FontFamily::Times),+ "courier" => Ok(pdfcraft_engine::FontFamily::Courier),+ _ => Err(Args::wrong("font", "helvetica, times or courier")),+ })+ .transpose()?+ .map(|f| -> Result<_> { Ok((f, a.opt_bool("bold")?.unwrap_or(false), a.opt_bool("italic")?.unwrap_or(false))) })+ .transpose()?;+ Ok(pdfcraft_engine::RangeStyle {+ range: start..end,+ family,+ resource: a.opt_str("font_resource")?.map(str::to_owned),+ size: a.opt_num("size")?,+ color: a.opt_str("color")?.map(comments::parse_color).transpose()?,+ underline: a.opt_bool("underline")?,+ char_spacing: a.opt_num("char_spacing")?,+ scale: a.opt_num("scale")?,+ })+ })+ .collect()+ }++ /// Typed access to validated arguments.+ pub(crate) struct Args<'a>(pub(crate) &'a Value);++ impl Args<'_> {+ pub(crate) fn get(&self, key: &str) -> Option<&Value> {+ self.0.get(key).filter(|v| !v.is_null())+ }+ pub(crate) fn missing(key: &str) -> ToolError {+ ToolError::InvalidArgs(format!("missing argument {key}"))+ }+ pub(crate) fn wrong(key: &str, what: &str) -> ToolError {+ ToolError::InvalidArgs(format!("{key} must be {what}"))+ }+ pub(crate) fn str(&self, key: &str) -> Result<&str> {+ self.opt_str(key)?.ok_or_else(|| Self::missing(key))+ }+ pub(crate) fn opt_str(&self, key: &str) -> Result<Option<&str>> {+ self.get(key).map(|v| v.as_str().ok_or_else(|| Self::wrong(key, "a string"))).transpose()+ }+ pub(crate) fn int(&self, key: &str) -> Result<i64> {+ self.opt_int(key)?.ok_or_else(|| Self::missing(key))+ }+ pub(crate) fn opt_int(&self, key: &str) -> Result<Option<i64>> {+ self.get(key).map(|v| v.as_i64().ok_or_else(|| Self::wrong(key, "an integer"))).transpose()+ }+ pub(crate) fn opt_num(&self, key: &str) -> Result<Option<f64>> {+ self.get(key).map(|v| v.as_f64().filter(|f| f.is_finite()).ok_or_else(|| Self::wrong(key, "a number"))).transpose()+ }+ pub(crate) fn opt_bool(&self, key: &str) -> Result<Option<bool>> {+ self.get(key).map(|v| v.as_bool().ok_or_else(|| Self::wrong(key, "true or false"))).transpose()+ }+ pub(crate) fn ints(&self, key: &str) -> Result<Vec<i64>> {+ self.opt_ints(key)?.ok_or_else(|| Self::missing(key))+ }+ pub(crate) fn opt_ints(&self, key: &str) -> Result<Option<Vec<i64>>> {+ let Some(v) = self.get(key) else { return Ok(None) };+ let arr = v.as_array().ok_or_else(|| Self::wrong(key, "an array of integers"))?;+ arr.iter().map(|x| x.as_i64().ok_or_else(|| Self::wrong(key, "an array of integers"))).collect::<Result<Vec<_>>>().map(Some)+ }+ /// A 1-based bookmark path → 0-based indices.+ pub(crate) fn path(&self, key: &str) -> Result<Vec<usize>> {+ let p = self.opt_path(key)?.ok_or_else(|| Self::missing(key))?;+ if p.is_empty() {+ return Err(ToolError::InvalidArgs(format!("{key} must not be empty")));+ }+ Ok(p)+ }+ pub(crate) fn opt_path(&self, key: &str) -> Result<Option<Vec<usize>>> {+ let Some(v) = self.opt_ints(key)? else { return Ok(None) };+ v.iter().map(|i| if *i >= 1 { Ok(*i as usize - 1) } else { Err(Self::wrong(key, "1-based positions")) }).collect::<Result<Vec<_>>>().map(Some)+ }+ /// A bookmark's `left` or `top`: points on the displayed page, `None` when left out, an error+ /// when it is not a number or lies absurdly far off the page.+ pub(crate) fn bookmark_coordinate(&self, key: &str) -> Result<Option<f32>> {+ match self.opt_num(key)? {+ None => Ok(None),+ Some(v) if v.is_finite() && v.abs() <= MAX_BOOKMARK_POSITION => Ok(Some(v as f32)),+ Some(_) => Err(ToolError::InvalidArgs(format!("{key} must be between -{MAX_BOOKMARK_POSITION} and {MAX_BOOKMARK_POSITION} points"))),+ }+ }+ pub(crate) fn strs(&self, key: &str) -> Result<Vec<&str>> {+ let v = self.get(key).ok_or_else(|| Self::missing(key))?;+ let arr = v.as_array().ok_or_else(|| Self::wrong(key, "an array of strings"))?;+ arr.iter().map(|x| x.as_str().ok_or_else(|| Self::wrong(key, "an array of strings"))).collect()+ }+ }++ /// The name-tree keys of a document's own attachments, leaving out the files attached to pages as comments.+ pub(crate) fn document_attachment_keys(doc: &Document) -> Vec<String> {+ doc.info+ .attachments+ .iter()+ .filter_map(|x| match &x.source {+ pdfcraft_render::AttachmentSource::Document { key } => Some(key.clone()),+ pdfcraft_render::AttachmentSource::Annotation { .. } => None,+ })+ .collect()+ }++ /// Bookmark rows in listing order as JSON: a row holds the rows that follow it on the page at the+ /// next level down in `children`, and paths and pages are 1-based.+ pub(crate) fn nest_rows(rows: &[pdfcraft_engine::BookmarkRow], pages: &[pdfcraft_render::PageInfo]) -> Vec<Value> {+ // The open rows, outermost first, with their depth and the children gathered so far.+ let mut open: Vec<(usize, Value, Vec<Value>)> = Vec::new();+ let mut roots = Vec::new();+ for row in rows {+ let depth = row.path.len().saturating_sub(1);+ while open.last().is_some_and(|(d, _, _)| *d >= depth) {+ close_row(&mut open, &mut roots);+ }+ let path: Vec<usize> = row.path.iter().map(|p| p.saturating_add(1)).collect();+ let mut fields = json!({ "path": path, "title": row.title, "page": row.page.map(|p| p.saturating_add(1)), "open": row.open });+ // Only what differs from the defaults (black, regular), as the PDF itself stores it.+ if let Some(color) = row.color {+ fields["color"] = json!(color);+ }+ if row.bold {+ fields["bold"] = json!(true);+ }+ if row.italic {+ fields["italic"] = json!(true);+ }+ if let Some(destination) = row.page.and_then(|p| pages.get(p)).and_then(|p| destination(&row.view, p)) {+ fields["destination"] = destination;+ }+ open.push((depth, fields, Vec::new()));+ }+ while !open.is_empty() {+ close_row(&mut open, &mut roots);+ }+ roots+ }++ /// Where on its page a bookmark or link goes, in points from the top-left of the displayed page+ /// like every `rect`: the destination type (`XYZ`, `Fit`, `FitH`, `FitV`, `FitR`) and its+ /// position, `null` where the destination leaves it unspecified (`/XYZ null null null` keeps the+ /// reader's position and zoom). `None` for a destination without a type.+ pub(crate) fn destination(view: &pdfcraft_render::DestView, page: &pdfcraft_render::PageInfo) -> Option<Value> {+ use pdfcraft_render::DestView;+ let points = |left: Option<f32>, top: Option<f32>| {+ let [x, y] = page.dest_fraction(left, top, 0);+ let round = |v: f32| f64::from((v * 100.0).round() / 100.0);+ (x.map(|x| round(x * page.width)), y.map(|y| round(y * page.height)))+ };+ Some(match view {+ DestView::Top => return None,+ DestView::Xyz { left, top, zoom } => {+ let (x, y) = points(*left, *top);+ json!({ "fit": "XYZ", "left": x, "top": y, "zoom": zoom.map(f64::from) })+ }+ DestView::Fit => json!({ "fit": "Fit" }),+ DestView::FitH { top } => {+ let (x, y) = points(None, *top);+ json!({ "fit": "FitH", "left": x, "top": y })+ }+ DestView::FitV { left } => {+ let (x, y) = points(*left, None);+ json!({ "fit": "FitV", "left": x, "top": y })+ }+ DestView::FitR { rect } => json!({ "fit": "FitR", "rect": comments::rect_to_view(page, *rect) }),+ })+ }++ /// Closes the innermost open row: it joins the row above it as a child, or the top level.+ fn close_row(open: &mut Vec<(usize, Value, Vec<Value>)>, roots: &mut Vec<Value>) {+ if let Some((_, mut fields, children)) = open.pop() {+ fields["children"] = Value::Array(children);+ match open.last_mut() {+ Some((_, _, siblings)) => siblings.push(fields),+ None => roots.push(fields),+ }+ }+ }++ pub(crate) fn one_based(pages: &[i64]) -> Result<Vec<usize>> {+ pages+ .iter()+ .map(|p| if *p >= 1 { Ok(*p as usize - 1) } else { Err(ToolError::InvalidArgs(format!("page numbers start at 1 (got {p})"))) })+ .collect()+ }++ /// The document's security as the next save writes it (never includes passwords).+ pub(crate) fn security(d: &Document) -> Value {+ match d.security_summary() {+ None => json!({ "protected": false }),+ Some(s) => {+ let p = s.permissions;+ json!({+ "protected": true,+ "method": s.method,+ "pending": s.pending,+ "printing": if !p.print() { "none" } else if p.print_high_quality() { "high" } else { "low" },+ "modify": p.modify(), "assemble": p.assemble(), "copy": p.copy(), "annotate": p.annotate(),+ "fill_forms": p.fill_forms(), "accessibility": p.extract_for_accessibility(),+ })+ }+ }+ }++ /// What every tool that changes a document returns.+ pub(crate) fn summary(d: &Document) -> Value {+ json!({+ "doc": d.id.0,+ "name": d.name,+ "path": d.path,+ "pages": d.info.pages.len(),+ "dirty": d.dirty,+ "editable": d.read_only_reason.is_none(),+ "read_only_reason": d.read_only_reason,+ "encrypted": d.info.encrypted,+ "undo": d.can_undo(),+ "redo": d.can_redo(),+ })+ }++ pub(crate) fn info(d: &Document) -> Value {+ let i = &d.info;+ let page1 = |p: usize| p + 1;+ let mut security = security(d);+ if let Some(s) = d.security_summary() {+ security["opened_as_owner"] = json!(s.owner);+ }+ json!({+ "document": summary(d),+ "pdf_version": i.pdf_version,+ "file_size": i.file_size,+ "title": i.title, "author": i.author, "subject": i.subject, "keywords": i.keywords,+ // Custom document properties (Document Properties ▸ Custom): /Info entries beyond the+ // ones the spec names, set and cleared with doc_set_info.+ "custom": i.custom.iter().map(|(name, value)| json!({ "name": name, "value": value })).collect::<Vec<_>>(),+ "creator": i.creator, "producer": i.producer,+ "tagged": i.tagged,+ "has_javascript": i.has_javascript,+ // Where the document opens (/OpenAction, named destinations resolved): 1-based page and+ // destination, null without one.+ "open_destination": i.open_dest.as_ref().map(|(p, view)| json!({ "page": page1(*p), "destination": i.pages.get(*p).and_then(|pg| destination(view, pg)) })),+ // XFA forms: "static" (the PDF's own fields work; the XFA data is ignored) or "dynamic"+ // (laid out from the template by PdfCraft, see xfa_layout; placeholder pages when that failed).+ "xfa": i.xfa.map(|x| match x { pdfcraft_render::Xfa::Static => "static", pdfcraft_render::Xfa::Dynamic => "dynamic" }),+ "xfa_layout": d.xfa.as_ref().map(|x| json!({ "pages": x.pages, "fields": x.fields, "warnings": x.warnings })),+ // A script of the form ran too long and was abandoned: its scripts no longer run in this+ // document (calculations, buttons) until it is opened again.+ "xfa_scripts_off": d.xfa_scripts_off(),+ // What was rewritten from, or could not be written to, the XFA data.+ "xfa_warnings": d.xfa_warnings,+ "security": security,+ "pages": i.pages.iter().enumerate().map(|(n, p)| json!({+ "page": n + 1, "label": p.label, "width": p.width, "height": p.height, "rotation": p.rotation,+ })).collect::<Vec<_>>(),+ "outline": outline(&i.outline),+ "outline_more": i.outline_more,+ // Rectangles use the tools' convention (top-left of the displayed page, like+ // comment_list and link_list), not raw PDF user space, so they can be fed back to+ // geometry-taking tools (#129).+ "annotations": i.annotations.iter().map(|a| json!({+ "page": page1(a.page), "type": a.subtype, "author": a.author, "contents": a.contents,+ "modified": a.modified, "name": a.name, "in_reply_to": a.in_reply_to,+ "rect": view_rect(i, a.page, a.shown_rect(i.pages.get(a.page).map_or(0, |p| p.rotation))),+ })).collect::<Vec<_>>(),+ "fields": i.fields.iter().map(|f| json!({+ "name": f.name, "kind": format!("{:?}", f.kind), "value": f.value, "page": f.page.map(page1),+ "tooltip": f.tooltip, "has_actions": f.has_actions,+ })).collect::<Vec<_>>(),+ "links": i.links.iter().map(|l| json!({+ "page": page1(l.page), "rect": view_rect(i, l.page, l.rect),+ "target": match &l.target {+ pdfcraft_render::LinkTarget::Page(p, _) => json!({ "page": page1(*p) }),+ pdfcraft_render::LinkTarget::Uri(u) => json!({ "uri": u }),+ pdfcraft_render::LinkTarget::SetLayers { changes, preserve_rb } => json!({+ "layers": changes.iter().map(|(op, ocg)| json!({+ "layer": i.layers.iter().find(|l| l.id == *ocg).map(|l| l.name.as_str()),+ "state": match op {+ pdfcraft_render::LayerOp::On => "on",+ pdfcraft_render::LayerOp::Off => "off",+ pdfcraft_render::LayerOp::Toggle => "toggle",+ },+ })).collect::<Vec<_>>(),+ "preserve_rb": preserve_rb,+ }),+ pdfcraft_render::LinkTarget::RemoteGoTo { launch, file, destination, new_window } => json!({+ "action": if *launch { "Launch" } else { "GoToR" },+ "remote_document": file,+ "destination": match destination {+ pdfcraft_render::RemoteDestination::Default => json!({ "kind": "default" }),+ pdfcraft_render::RemoteDestination::Page { page, view } => json!({ "kind": "page", "page": page1(*page), "view": format!("{view:?}") }),+ pdfcraft_render::RemoteDestination::Named(name) => json!({ "kind": "named", "name": name }),+ },+ "new_window": new_window,+ }),+ pdfcraft_render::LinkTarget::Other(o) => json!({ "other": o }),+ },+ })).collect::<Vec<_>>(),+ "layers": i.layers.iter().map(|l| json!({ "name": l.name, "visible": l.visible, "initial": l.initial })).collect::<Vec<_>>(),+ // Full-screen presentation settings a page carries (ISO 32000-2 §12.4.4): only pages with+ // a `/Trans` or `/Dur` appear; `style` is null for a display time alone.+ "transitions": i.transitions.iter().map(|t| json!({+ "page": page1(t.page), "style": t.style.map(pdfcraft_render::TransitionStyle::name), "duration": t.duration,+ "horizontal": t.horizontal, "inward": t.inward, "direction": t.direction, "scale": t.scale, "opaque": t.opaque,+ "display": t.display,+ })).collect::<Vec<_>>(),+ "attachments": i.attachments.iter().map(|a| json!({ "name": a.name, "description": a.description, "size": a.size })).collect::<Vec<_>>(),+ // `substitute` names the face standing in for a program the document does not embed, and+ // `substitution` says why. Both are null for an embedded font: nothing stands in. A null+ // `substitute` with a non-null `substitution` means no face was available at all, so+ // nothing is drawn for that font -- which is the answer to "why is my text missing?".+ "fonts": i.fonts.iter().map(|f| json!({+ "name": f.name, "kind": f.kind, "embedded": f.embedded, "subset": f.subset, "encoding": f.encoding,+ "substitute": f.substitute, "substitution": f.substitution,+ })).collect::<Vec<_>>(),+ "warnings": i.warnings,+ "repairs": d.repair_log(),+ })+ }++ /// A user-space rectangle on 0-based `page` in displayed-page coordinates (points from the+ /// top-left of the page as displayed, y down, after `/Rotate`), the way every tool reports+ /// rectangles; unchanged when the page is unknown (a malformed annotation that points at no page).+ /// Public so `pdfcraft-cli` reports the same rectangles as the tools.+ pub fn view_rect(i: &pdfcraft_render::DocInfo, page: usize, rect: [f32; 4]) -> [f32; 4] {+ i.pages.get(page).map_or(rect, |p| comments::rect_to_view(p, rect))+ }++ fn outline(items: &[pdfcraft_render::OutlineItem]) -> Value {+ Value::Array(items.iter().map(|o| json!({ "title": o.title, "page": o.page.map(|p| p + 1), "children": outline(&o.children) })).collect())+ }diff --cc crates/engine/src/document.rsindex 000000000,7023caa55..23d625e6cmode 000000,100644..100644--- a/crates/engine/src/document.rs+++ b/crates/engine/src/document.rs@@@ -1,0 -1,713 +1,723 @@@+ //! An open document: its working file, view data and edit state.++ use std::sync::{Arc, OnceLock};++ use pdfcraft_cos::{SaveOptions, write_incremental};+ use pdfcraft_render::{DocInfo, RenderConfig, RenderPool};++ use crate::history::Editor;+ use crate::{+ CalculationOrder, CheckStyle, DocId, Edit, EditError, EditableObject, FormFieldKind, Hidden, InitialView, Label, MarkKind, SecuritySummary,+ SignatureInfo, TabOrder, TrustStore, XfaLayout, a11y, form_appearance, guard, js, measure, optimize, renderer_password, unrestricted,+ };+ #[cfg(test)]+ use crate::{record_link_scan, record_marker_scan};++ pub struct Document {+ pub id: DocId,+ pub name: String,+ pub path: Option<String>,+ /// The working file: what Save writes.+ pub bytes: Arc<Vec<u8>>,+ /// What is displayed (the page view, `page_render`, page images): `bytes`, plus appearances+ /// drawn for display only for comments that have none ([`display_bytes`]). Never saved.+ pub display: Arc<Vec<u8>>,+ pub info: DocInfo,+ pub renderer: RenderPool,+ /// The password the document was opened with (needed to read attachments, etc.).+ pub password: Option<String>,+ /// `true` when there are edits that have not been saved.+ pub dirty: bool,+ /// Bumped on every change to the working file (edit, undo, redo, save); autosave compares it.+ pub(crate) generation: u64,+ /// The generation last handed out by `autosave_snapshots`.+ pub(crate) snapshot_generation: u64,+ /// Why the document cannot be edited (e.g. encryption), if so.+ pub read_only_reason: Option<String>,+ /// Interactive form fields of the current state (empty without a form).+ pub form: Arc<Vec<pdfcraft_forms::Field>>,+ pub(crate) marker_scan: OnceLock<pdfcraft_edit::MarkerScan>,+ pub(crate) links: OnceLock<Vec<pdfcraft_annot::links::LinkItem>>,+ /// Signature fields, validated against the session's trust store (Signatures panel).+ pub signatures: Arc<Vec<SignatureInfo>>,+ pub(crate) trust: Arc<TrustStore>,+ pub(crate) sig_cache: Arc<pdfcraft_sign::DigestCache>,+ pub(crate) editor: Option<Editor>,+ pub(crate) config: RenderConfig,+ /// What field scripts printed or asked for (see [`Session::take_js_output`]).+ pub(crate) js_output: js::JsOutput,+ /// Dynamic XFA forms: what laying the template out produced (pages and fields are+ /// PdfCraft's; Adobe's viewers draw the form from the XFA packets themselves).+ pub xfa: Option<XfaLayout>,+ /// The parsed template of a laid-out XFA form, for its scripts.+ pub(crate) xfa_template: Option<Arc<pdfcraft_xfa::model::Template>>,+ /// A script of the XFA form ran away, so its scripts are off (see [`Document::xfa_scripts_off`]).+ pub(crate) xfa_scripts_off: bool,+ /// A content-only refresh keeps `info` from before the edit; an edit may have added or+ /// embedded fonts, so the font list is read again on demand ([`Session::refresh_fonts`]).+ pub(crate) fonts_stale: bool,+ /// XFA forms: what was approximated, rewritten or could not be written to the XFA data+ /// (also in `info.warnings`, kept there when the document is re-read).+ pub xfa_warnings: Vec<String>,+ /// What the last successful [`Session::apply`](crate::Session::apply) wrote that its fonts can't draw: kept as typed,+ /// drawn with `?` in its place (see [`TextNotice`]). The interface shows it; tools return it.+ pub edit_notices: Vec<TextNotice>,+ }++ /// Text an edit stored as typed but drew with `?` in place of `ch`, because the font it is drawn+ /// with (a form field's, or the standard fonts for comments) can't draw that character. Acrobat+ /// keeps such text too, drawing it with fonts PdfCraft can't embed yet.+ #[derive(Clone, Debug, PartialEq, Eq)]+ pub struct TextNotice {+ /// The form field's full name, or `None` for a comment.+ pub field: Option<String>,+ /// The page (0-based) of the comment or of the field's widget.+ pub page: usize,+ pub ch: char,+ /// Other PDF viewers redraw it from the stored text (a form field, with `/NeedAppearances`+ /// set); otherwise the `?` shows in every viewer.+ pub redrawn_elsewhere: bool,+ }++ impl std::fmt::Display for TextNotice {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ let ch = format!("\"{}\" (U+{:04X})", self.ch.escape_debug(), u32::from(self.ch));+ let page = self.page + 1;+ match (&self.field, self.redrawn_elsewhere) {+ (Some(name), true) => write!(+ f,+ "form field {name:?} (page {page}) holds {ch}, which its font can't draw: the value is saved, PdfCraft shows ? in its place, and other PDF viewers redraw the field from the value"+ ),+ (Some(name), false) => write!(+ f,+ "form field {name:?} (page {page}) holds {ch}, which its font can't draw: the value is saved, but this PDF/A document can't ask other viewers to redraw it, so ? shows in its place everywhere"+ ),+ (None, _) => write!(+ f,+ "a comment on page {page} has {ch}, which the standard fonts can't draw: its text is saved, but its appearance shows ? in its place in every viewer"+ ),+ }+ }+ }++ /// What `next` drew with `?` that `prev` didn't (a new or redrawn appearance carrying+ /// `pdfcraft_fonts::UNDRAWN_MARK`), one notice per field or comment, in page order.+ pub(crate) fn undrawn_notices(prev: &pdfcraft_cos::Document, next: &pdfcraft_cos::Document) -> Vec<TextNotice> {+ let Ok(pages) = pdfcraft_annot::page_refs(next) else { return Vec::new() };+ let redrawn_elsewhere = pdfcraft_forms::need_appearances(next);+ let mut names: Option<std::collections::HashMap<pdfcraft_cos::ObjRef, String>> = None;+ let mut out: Vec<TextNotice> = Vec::new();+ for (page, p) in pages.iter().enumerate() {+ let annots = next.get(*p).as_dict().and_then(|d| d.get(b"Annots").cloned()).map(|a| next.resolve(&a));+ for r in annots.as_deref().and_then(pdfcraft_cos::Object::as_array).into_iter().flatten().filter_map(pdfcraft_cos::Object::as_ref) {+ let now = next.get(r);+ let Some(d) = now.as_dict() else { continue };+ let Some(ch) = pdfcraft_fonts::undrawn_mark(d) else { continue };+ // Only what this edit drew: a new annotation, or a new appearance.+ let was = prev.get(r);+ if was.as_dict().is_some_and(|w| w.get(b"AP") == d.get(b"AP") && pdfcraft_fonts::undrawn_mark(w) == Some(ch)) {+ continue;+ }+ let field = (d.name(b"Subtype") == Some(b"Widget")).then(|| {+ let names = names.get_or_insert_with(|| {+ pdfcraft_forms::fields(next)+ .into_iter()+ .flat_map(|f| f.widgets.iter().map(|w| (w.obj, f.name.clone())).collect::<Vec<_>>())+ .collect()+ });+ names.get(&r).cloned().unwrap_or_default()+ });+ if field.is_some() && out.iter().any(|n| n.field == field) {+ continue;+ }+ out.push(TextNotice { redrawn_elsewhere: redrawn_elsewhere && field.is_some(), field, page, ch });+ }+ }+ out+ }++ impl Document {+ /// How the document opens (Document Properties ▸ Initial View).+ /// Accessibility ▸ Check for accessibility: the full check (`None` if the document can't be+ /// read for editing).+ pub fn accessibility_check(&self, options: &a11y::Options) -> Option<a11y::Report> {+ self.editor.as_ref().map(|e| a11y::check(&e.cos, options))+ }++ /// A script of this XFA form ran past its time limit and was abandoned, so the form's+ /// scripts no longer run in this document (reopening it runs them again). The script's+ /// error is in the JavaScript output; this is the state, for a viewer to show.+ pub fn xfa_scripts_off(&self) -> bool {+ self.xfa_scripts_off+ }++ /// PDF Optimizer ▸ Audit space usage.+ pub fn audit_space(&self) -> Vec<optimize::SpaceUse> {+ self.editor.as_ref().map(|e| optimize::audit_space(&e.cos, self.bytes.len() as u64)).unwrap_or_default()+ }++ /// Edit a PDF: the images `page` draws (0-based).+ pub fn page_images(&self, page: usize) -> Vec<pdfcraft_edit::PageImage> {+ self.editor.as_ref().and_then(|e| pdfcraft_edit::page_images(&e.cos, page).ok()).unwrap_or_default()+ }++ /// Mixed editable objects on one page. Source inventories are zero-based and added items+ /// appear once. Rectangles are user-space points, independent of the viewer's zoom.+ pub fn editable_objects(&self, page: usize) -> Result<Vec<EditableObject>, String> {+ let editor = self.editor.as_ref().ok_or("the document can't be read")?;+ pdfcraft_edit::editable_objects(&editor.cos, page).map_err(|e| e.to_string())+ }++ /// Displayed top-left-origin motion to a user-space vector. Use the linear map only,+ /// so even a large crop-box origin cannot erase a small drag by cancellation.+ pub fn object_move_offset(&self, page: usize, delta: [f64; 2]) -> Result<[f64; 2], String> {+ let p = self.info.pages.get(page).ok_or("the page no longer exists")?;+ let [x0, y0, x1, y1] = p.crop.map(f64::from);+ let (a, b) = (delta[0] / f64::from(p.width.max(1e-3)), delta[1] / f64::from(p.height.max(1e-3)));+ let (u, v) = match p.rotation {+ 90 => (b, -a),+ 180 => (-a, -b),+ 270 => (-b, a),+ _ => (a, b),+ };+ let offset = [u * (x1 - x0), -v * (y1 - y0)];+ if !offset.iter().all(|v| v.is_finite()) {+ return Err("the move must be finite and non-zero".into());+ }+ Ok(offset)+ }++ /// Save image as: image `index` on `page` as a file (extension, bytes).+ pub fn page_image_file(&self, page: usize, index: usize) -> Result<(&'static str, Vec<u8>), String> {+ self.check_copying().map_err(|e| e.to_string())?;+ let editor = self.editor.as_ref().ok_or("the document can't be read")?;+ let img = self.page_images(page).into_iter().nth(index).ok_or_else(|| format!("page {} has no image {}", page + 1, index + 1))?;+ if img.is_form {+ return Err("grouped Form artwork is not a bitmap; Save Image As is only available for raster images".into());+ }+ pdfcraft_create::image_file(&editor.cos, img.object.ok_or("the image has no object")?)+ }++ /// Edit a PDF ▸ Edit text: the paragraphs on `page` (0-based).+ pub fn text_blocks(&self, page: usize) -> Vec<pdfcraft_edit::TextBlock> {+ self.editor.as_ref().and_then(|e| e.text_blocks(page).ok()).map(|b| b.as_ref().clone()).unwrap_or_default()+ }++ /// Saved measurement annotations, calculated from their geometry and PDF scales, plus+ /// the ones that couldn't be read (unsupported formats are skipped, not fatal).+ pub fn measurements(&self) -> Result<measure::Listing, String> {+ let e = self.editor.as_ref().ok_or("the document can't be read")?;+ Ok(measure::list(&e.cos))+ }+ pub fn measurement_scale(&self, page: usize, at: measure::Point) -> Result<measure::Scale, String> {+ let e = self.editor.as_ref().ok_or("the document can't be read")?;+ measure::scale_at(&e.cos, page, at).map_err(|e| e.to_string())+ }+ /// [`Self::measurement_scale`], measuring true size in `unit` (`per_point` of them in a+ /// point) where the page sets no scale.+ pub fn measurement_scale_or(&self, page: usize, at: measure::Point, per_point: f64, unit: &str) -> Result<measure::Scale, String> {+ let e = self.editor.as_ref().ok_or("the document can't be read")?;+ measure::scale_at_or(&e.cos, page, at, per_point, unit).map_err(|e| e.to_string())+ }+ pub fn measurement_to_user(&self, page: usize, point: measure::Point) -> Result<measure::Point, String> {+ let e = self.editor.as_ref().ok_or("the document can't be read")?;+ measure::view_to_user(&e.cos, page, point).map_err(|e| e.to_string())+ }+ pub fn measurement_to_view(&self, page: usize, point: measure::Point) -> Result<measure::Point, String> {+ let e = self.editor.as_ref().ok_or("the document can't be read")?;+ measure::user_to_view(&e.cos, page, point).map_err(|e| e.to_string())+ }+ pub fn measurement_paths(&self, page: usize) -> Result<measure::snap::Geometry, String> {+ let e = self.editor.as_ref().ok_or("the document can't be read")?;+ measure::snap::geometry(&e.cos, page).map_err(|e| e.to_string())+ }++ /// A counter that changes with every edit (for caches of derived data).+ pub fn edit_generation(&self) -> u64 {+ self.generation+ }+++ /// The styles the document's text is set in, the largest first, for bookmarks from text++ /// styles (#1693).++ /// Empty when the document doesn't allow copying: the samples are its text.++ pub fn text_styles(&self) -> Vec<crate::text_style_bookmarks::TextStyleUse> {++ if !self.allows_copying() {++ return Vec::new();++ }++ self.editor.as_ref().map(|e| crate::text_style_bookmarks::styles(&e.cos)).unwrap_or_default()++ }+++ /// Edit a PDF ▸ Edit text: the lines of existing text on `page` (0-based).+ pub fn text_lines(&self, page: usize) -> Vec<pdfcraft_edit::TextLine> {+ self.editor.as_ref().and_then(|e| pdfcraft_edit::text_lines(&e.cos, page).ok()).unwrap_or_default()+ }++ /// The form's calculation order: its calculated fields in the order they calculate, what each+ /// formula reads, what is wrong with the order, and the order Fix order writes.+ pub fn calculation_order(&self) -> CalculationOrder {+ self.editor.as_ref().map(|e| pdfcraft_forms::calculation_order(&e.cos, &self.form)).unwrap_or_default()+ }++ /// Add alternate text: the figures, in document order.+ pub fn figures(&self) -> Vec<a11y::Figure> {+ self.editor.as_ref().map(|e| a11y::figures(&e.cos)).unwrap_or_default()+ }++ /// Reachable indirect structure tags, in document order.+ pub fn tags(&self) -> Vec<a11y::TagInfo> {+ self.editor.as_ref().map(|e| a11y::tags(&e.cos)).unwrap_or_default()+ }++ /// Marked-content items directly owned by one reachable indirect structure tag.+ pub fn tag_content(&self, object: pdfcraft_cos::ObjRef) -> Result<Vec<a11y::TagContentItem>, a11y::TagError> {+ self.editor.as_ref().map(|e| a11y::tag_content(&e.cos, object)).unwrap_or_else(|| Ok(Vec::new()))+ }++ /// The edit that fixes `rule`, for the rules with an automatic fix: the document language+ /// (`value` is the language), the title (`value` replaces it; else the current title or the+ /// file name) and the tab order.+ pub fn accessibility_fix(&self, rule: a11y::Rule, value: Option<&str>) -> Result<Edit, String> {+ let value = value.map(str::trim).filter(|v| !v.is_empty());+ match rule {+ a11y::Rule::PrimaryLanguage => {+ let mut v = self.initial_view();+ v.language = Some(value.ok_or("give the document language (for example en-US)")?.to_owned());+ Ok(Edit::SetInitialView(Box::new(v)))+ }+ a11y::Rule::Title => {+ let title = value+ .map(str::to_owned)+ .or_else(|| self.info_value("Title").filter(|t| !t.trim().is_empty()))+ .unwrap_or_else(|| self.name.trim_end_matches(".pdf").trim_end_matches(".PDF").to_owned());+ let mut v = self.initial_view();+ v.display_title = true;+ Ok(Edit::Batch {+ label: "Set document title".into(),+ edits: vec![Edit::SetInfo { key: "Title".into(), value: title }, Edit::SetInitialView(Box::new(v))],+ })+ }+ a11y::Rule::TabOrder => Ok(Edit::SetTabOrder { pages: (0..self.info.pages.len()).collect(), order: TabOrder::Structure }),+ other => Err(format!("\"{}\" has no automatic fix", other.name())),+ }+ }++ pub fn initial_view(&self) -> InitialView {+ self.editor.as_ref().map(|e| pdfcraft_organize::initial_view(&e.cos)).unwrap_or_default()+ }++ /// Signed: at least one signature field holds a signature.+ pub fn is_signed(&self) -> bool {+ self.signatures.iter().any(|s| s.signed)+ }++ /// Whether comments are hidden (Comments ▸ Hide all comments).+ pub fn comments_hidden(&self) -> bool {+ self.config.hide_comments+ }++ pub fn can_undo(&self) -> Option<&str> {+ self.undo_label().map(Label::as_str)+ }++ pub fn can_redo(&self) -> Option<&str> {+ self.redo_label().map(Label::as_str)+ }++ /// What Undo would undo, in parts, for an interface that says it in another language.+ pub fn undo_label(&self) -> Option<&Label> {+ self.editor.as_ref().and_then(|e| e.undo.last()).map(|(l, ..)| l)+ }++ /// What Redo would redo, in parts.+ pub fn redo_label(&self) -> Option<&Label> {+ self.editor.as_ref().and_then(|e| e.redo.last()).map(|(l, ..)| l)+ }++ pub fn editable(&self) -> bool {+ self.editor.is_some()+ }++ /// What the opening password allows; `None` when the document is not encrypted.+ pub fn permissions(&self) -> Option<pdfcraft_cos::Permissions> {+ self.editor.as_ref().and_then(|e| e.cos.permissions())+ }++ /// Printing is allowed (Table 22, bit 3).+ pub fn allows_printing(&self) -> bool {+ self.permissions().is_none_or(|p| p.print())+ }++ /// Copying or otherwise extracting text and images is allowed (Table 22, bit 5): copying+ /// selected text, snapshots, Save Image As, exporting. Assistive technology may read the+ /// content regardless (§7.6.4.2), so reading aloud and accessibility tools don't ask.+ pub fn allows_copying(&self) -> bool {+ self.permissions().is_none_or(|p| p.copy())+ }++ /// [`Self::allows_copying`], as the error to report when it isn't.+ pub fn check_copying(&self) -> Result<(), EditError> {+ if self.allows_copying() { Ok(()) } else { Err(EditError::NotPermitted("copying text and images")) }+ }++ /// Page changes (insert, delete, rotate, move, extract) are allowed.+ pub fn allows_assembly(&self) -> bool {+ self.editable() && self.permissions().is_none_or(|p| p.assemble())+ }++ /// Redaction marks waiting to be applied.+ pub fn redaction_marks(&self) -> usize {+ self.info.annotations.iter().filter(|a| a.subtype == "Redact").count()+ }++ /// Page marks present (headers and footers, watermarks, backgrounds), for Update/Remove.+ pub fn marks(&self) -> &[MarkKind] {+ &self+ .marker_scan+ .get_or_init(|| {+ self.editor+ .as_ref()+ .map(|e| {+ #[cfg(test)]+ record_marker_scan();+ pdfcraft_edit::scan_markers(&e.cos)+ })+ .unwrap_or_default()+ })+ .marks+ }++ /// Text and images added with Edit a PDF ▸ Add content (still editable).+ pub fn added(&self) -> &[pdfcraft_edit::Added] {+ &self+ .marker_scan+ .get_or_init(|| {+ self.editor+ .as_ref()+ .map(|e| {+ #[cfg(test)]+ record_marker_scan();+ pdfcraft_edit::scan_markers(&e.cos)+ })+ .unwrap_or_default()+ })+ .added+ }++ /// Link annotations, for Edit a PDF ▸ Link.+ pub fn links(&self) -> &[pdfcraft_annot::links::LinkItem] {+ self.links.get_or_init(|| {+ self.editor+ .as_ref()+ .map(|e| {+ #[cfg(test)]+ record_link_scan();+ pdfcraft_annot::links::list(&e.cos)+ })+ .unwrap_or_default()+ })+ }++ /// Changes to content and document information are allowed.+ pub fn allows_modification(&self) -> bool {+ self.editable() && self.permissions().is_none_or(|p| p.modify())+ }++ /// How widget `widget` of text field `name` lays its value out, for asking whether a typed+ /// value fits it ([`form_appearance::TextBox::fits`]): a field that doesn't scroll takes no+ /// more than fits. `None` without such a field or widget, or when the document can't be+ /// edited.+ pub fn field_text_box(&self, name: &str, widget: usize) -> Option<form_appearance::TextBox> {+ let cos = &self.editor.as_ref()?.cos;+ let f = self.form.iter().find(|f| f.name == name)?;+ let w = f.widgets.get(widget)?;+ Some(form_appearance::text_box(cos, f, w))+ }++ /// Filling in form fields is allowed (Table 22, bits 6 and 9).+ pub fn allows_form_filling(&self) -> bool {+ self.editable() && self.permissions().is_none_or(|p| p.fill_forms())+ }++ /// Adding and changing comments is allowed (Table 22, bit 6).+ pub fn allows_annotation(&self) -> bool {+ self.editable() && self.permissions().is_none_or(|p| p.annotate())+ }++ /// The document's security may be changed (Protect, Remove security): it is editable and,+ /// if encrypted, was opened with the owner password.+ pub fn allows_security_change(&self) -> bool {+ self.editable() && self.permissions().is_none_or(|p| unrestricted(&p))+ }++ /// A password restricts the document and it wasn't opened with the owner password: entering+ /// that password ([`Session::unlock`](crate::Session::unlock)) lifts the restrictions.+ pub fn can_unlock(&self) -> bool {+ self.editable() && self.permissions().is_some_and(|p| !unrestricted(&p))+ }++ /// A summary of the document's security for Document Properties ▸ Security, including+ /// protection applied in this session (written by the next save).+ pub fn security_summary(&self) -> Option<SecuritySummary> {+ let editor = self.editor.as_ref()?;+ let h = editor.cos.output_handler()?;+ let d = h.dict();+ let stream = d.crypt_filters.iter().find(|(name, _)| *name == d.stm_f).map(|(_, m)| *m);+ let method = match (d.v, stream) {+ (1..=3, _) if d.length_bits <= 40 => "RC4, 40-bit",+ (1..=3, _) | (_, Some(pdfcraft_cos::CryptMethod::Rc4)) => "RC4, 128-bit",+ (_, Some(pdfcraft_cos::CryptMethod::Aes128)) => "AES, 128-bit",+ (_, Some(pdfcraft_cos::CryptMethod::Aes256)) => "AES, 256-bit",+ _ => "Attachments only",+ };+ let pending = editor.cos.encryption_changed();+ let permissions = if pending { pdfcraft_cos::Permissions { bits: h.permissions().bits, owner: false } } else { h.permissions() };+ Some(SecuritySummary { method: method.into(), owner: h.auth() == pdfcraft_cos::Auth::Owner && !pending, permissions, pending })+ }++ /// Comment properties of the comment at `(page, index)` (Comment Properties dialog).+ pub fn comment_props(&self, page: usize, index: usize) -> Option<pdfcraft_annot::Props> {+ self.editor.as_ref().and_then(|e| pdfcraft_annot::props(&e.cos, page, index))+ }++ /// A form field's Appearance-tab look (borders, colours, font).+ pub fn field_look(&self, name: &str) -> Option<pdfcraft_forms::Look> {+ let e = self.editor.as_ref()?;+ let f = self.form.iter().find(|f| f.name == name)?;+ Some(pdfcraft_forms::look(&e.cos, f))+ }++ /// A check box's or radio button's mark (Field Properties ▸ Options), `None` for other fields.+ pub fn field_check_style(&self, name: &str) -> Option<CheckStyle> {+ let e = self.editor.as_ref()?;+ let f = self.form.iter().find(|f| f.name == name)?;+ matches!(f.kind, FormFieldKind::CheckBox | FormFieldKind::Radio).then(|| pdfcraft_forms::check_style(&e.cos, f))+ }++ /// Whether text field `name`'s value is cut off by its box at the field's font size (#4018):+ /// the page (0-based) of the first widget that cuts it, and how.+ pub fn field_overflow(&self, name: &str) -> Option<(Option<usize>, pdfcraft_forms::appearance::Overflow)> {+ let e = self.editor.as_ref()?;+ let f = self.form.iter().find(|f| f.name == name)?;+ f.widgets.iter().find_map(|w| pdfcraft_forms::appearance::value_overflow(&e.cos, f, w).map(|o| (w.page, o)))+ }++ /// Remove Hidden Information: what each category would remove.+ pub fn hidden_info(&self) -> Vec<(Hidden, usize)> {+ self.editor.as_ref().map(|e| pdfcraft_redact::sanitize::scan(&e.cos)).unwrap_or_default()+ }++ /// Verification: faux redactions (opaque covers over extractable text) and redaction+ /// marks that were never applied. Fails closed: any read error is returned, never an+ /// empty list.+ pub fn audit_redactions(&self) -> Result<Vec<pdfcraft_audit::AuditFinding>, String> {+ let editor = self.editor.as_ref().ok_or("the document can't be read")?;+ pdfcraft_audit::audit_redactions(&editor.cos).map_err(|e| e.to_string())+ }++ /// Every page's media, crop, bleed, trim and art boxes (user space), for Set Page Boxes.+ pub fn page_boxes(&self) -> Vec<[[f64; 4]; 5]> {+ self.editor.as_ref().and_then(|e| pdfcraft_organize::page_boxes(&e.cos).ok()).unwrap_or_default()+ }++ /// Current value of a document-information entry (Title, Author, …).+ pub fn info_value(&self, key: &str) -> Option<String> {+ self.editor.as_ref().and_then(|e| pdfcraft_organize::info(&e.cos, key))+ }++ /// Whether the document information has an entry `key`, of any type, listed or not.+ pub fn has_info(&self, key: &str) -> bool {+ self.editor.as_ref().is_some_and(|e| pdfcraft_organize::has_info(&e.cos, key))+ }++ /// The custom document properties as they are now (name, text), Document Properties ▸ Custom.+ pub fn custom_info(&self) -> Vec<(String, String)> {+ self.editor.as_ref().map(|e| pdfcraft_organize::custom_info(&e.cos)).unwrap_or_default()+ }++ /// The name shown on the tab and window: the document title when the document asks for it+ /// (Initial View ▸ Show: Document Title) and has a real one, else the file name.+ pub fn display_name(&self) -> String {+ self.editor+ .as_ref()+ .filter(|e| pdfcraft_organize::displays_doc_title(&e.cos))+ .and_then(|e| pdfcraft_organize::info(&e.cos, "Title"))+ .map(|t| t.trim().to_owned())+ .filter(|t| !t.is_empty() && !is_placeholder_title(t))+ .unwrap_or_else(|| self.name.clone())+ }++ /// Where each saved revision of the file ends (oldest first; `bytes[..end]` is that+ /// revision). Unsaved edits aren't a revision yet.+ pub fn revision_ends(&self) -> Vec<usize> {+ self.editor.as_ref().map(|e| e.cos.revision_ends()).unwrap_or_default()+ }++ /// The file as last opened or saved, without unsaved edits: what an incremental save appends+ /// to. This stays that file when undo has restored an older snapshot.+ pub fn saved_bytes(&self) -> Arc<Vec<u8>> {+ self.editor.as_ref().map_or_else(|| self.bytes.clone(), |e| e.saved.clone())+ }++ /// Notes about damage repaired while opening (Document Properties ▸ Advanced, notices).+ pub fn repair_log(&self) -> Vec<String> {+ self.editor.as_ref().map(|e| e.cos.repair_log().to_vec()).unwrap_or_default()+ }+ }++ /// A title that names no document: what a web browser writes when it saves a blank page or a+ /// pop-up as PDF (`about:blank`), another browser-internal address, or a bare "Untitled". Such a+ /// title says less than the file name, so the file name is shown instead. An address is one+ /// word: "About: our company" is a real title.+ pub(crate) fn is_placeholder_title(title: &str) -> bool {+ let t = title.trim().to_lowercase();+ let address = !t.contains(char::is_whitespace) && ["about:", "blob:", "data:"].iter().any(|p| t.starts_with(p));+ address || t == "untitled"+ }++ /// The working file plus appearances for comments that have none, and for form fields the file+ /// leaves to the viewer (#3470). Signature artwork is preserved; validation badges belong to the+ /// viewer and never enter these bytes, which image/text exports and Print as Image also consume.+ pub(crate) fn display_bytes(editor: Option<&mut Editor>, bytes: &Arc<Vec<u8>>) -> Arc<Vec<u8>> {+ let Some(e) = editor else { return bytes.clone() };+ let comments = pdfcraft_annot::with_missing_appearances_cached(&e.cos, &mut e.appearances);+ let fields = pdfcraft_forms::with_field_appearances_cached(comments.as_ref().unwrap_or(&e.cos), &mut e.field_appearances);+ let Some(display) = fields.or(comments) else {+ return bytes.clone();+ };+ match write_incremental(&display, &SaveOptions::default()) {+ Ok(written) => Arc::new(written),+ Err(err) => {+ e.cos.note_repair(format!("missing comment or field appearances could not be drawn ({err})"));+ bytes.clone()+ }+ }+ }++ /// `comments` (the display copy with comment appearances, if it needed any; else the document+ /// itself) with its form fields drawn from their values where the file leaves that to the viewer.+ fn with_field_appearances(comments: Option<pdfcraft_cos::Document>, doc: &pdfcraft_cos::Document) -> Option<pdfcraft_cos::Document> {+ pdfcraft_forms::with_field_appearances(comments.as_ref().unwrap_or(doc)).or(comments)+ }++ /// The reader shows the same pages in `a` and `b`: count, displayed size and rotation.+ pub(crate) fn same_pages(a: &[pdfcraft_render::PageInfo], b: &[pdfcraft_render::PageInfo]) -> bool {+ a.len() == b.len()+ && a.iter().zip(b).all(|(x, y)| (x.width - y.width).abs() < 0.01 && (x.height - y.height).abs() < 0.01 && x.rotation == y.rotation)+ }++ /// Each document-information field of `info` with its value in `cos` (`/Info`, else XMP), read+ /// the way the full inspection reads them: NULs and spaces trimmed, empty is none.+ pub(crate) fn info_fields<'a>(info: &'a mut DocInfo, cos: &pdfcraft_cos::Document) -> [(&'a mut Option<String>, Option<String>); 6] {+ let read = |key| pdfcraft_organize::info(cos, key).map(|v| v.trim_matches('\0').trim().to_string()).filter(|v| !v.is_empty());+ [+ (&mut info.title, read("Title")),+ (&mut info.author, read("Author")),+ (&mut info.subject, read("Subject")),+ (&mut info.keywords, read("Keywords")),+ (&mut info.creator, read("Creator")),+ (&mut info.producer, read("Producer")),+ ]+ }++ /// The copy PDFCraft displays when opening `bytes`: with appearances drawn, in memory only, for+ /// comments that have none and form fields the file leaves to the viewer. Render paths outside the app, such as the CLI, use this so their page+ /// images agree with the app and independent viewers. It never changes the source document, and an+ /// unparseable file, a write failure or a parser panic falls back to the original bytes.+ pub fn display_bytes_for(bytes: Arc<Vec<u8>>, password: Option<&str>) -> Arc<Vec<u8>> {+ guard(|| {+ pdfcraft_cos::Document::open_with_password(bytes.clone(), password)+ .ok()+ .and_then(|cos| with_field_appearances(pdfcraft_annot::with_missing_appearances(&cos), &cos))+ .and_then(|display| write_incremental(&display, &SaveOptions::default()).ok())+ .map(Arc::new)+ })+ .ok()+ .flatten()+ .unwrap_or(bytes)+ }++ /// The password to give the renderer (`inspect`, `PageRenderer`) for `bytes` opened with+ /// `password`. The renderer authenticates only the user password of R2–R4 files, so for their+ /// owner password this is the user password that owner authentication recovers; otherwise it is+ /// `password` itself. Render paths outside a [`Session`](crate::Session), such as the CLI, use this so the owner+ /// password works there as it does in `doc_open`. A file that doesn't open with `password` keeps+ /// it, so the renderer reports the same error it always did.+ pub fn render_password_for(bytes: Arc<Vec<u8>>, password: Option<&str>) -> Option<String> {+ let password = password?;+ let recovered =+ guard(|| pdfcraft_cos::Document::open_with_password(bytes, Some(password)).ok().and_then(|d| recovered_render_password(&d))).ok().flatten();+ Some(recovered.unwrap_or_else(|| password.to_owned()))+ }++ /// The user password owner authentication recovered from an R2–R4 `cos`, as the renderer takes it.+ pub(crate) fn recovered_render_password(cos: &pdfcraft_cos::Document) -> Option<String> {+ cos.security().and_then(|s| s.recovered_user_password()).map(|user| renderer_password(&user))+ }++ /// Fails when the renderer still draws text under an applied redaction mark.+ ///+ /// Redaction decides what lies under a mark from the positions its own interpreter computes, and+ /// its verify pass reuses them. Where they differ from the renderer's (a standard font without+ /// /Widths, whose advances the interpreter approximates; a CMap+ /// that it reads differently), a mark drawn over the text as displayed lies over glyphs the+ /// interpreter believes are elsewhere: they stay in the file and nothing notices. The renderer is+ /// what the user saw when placing the marks, so it is asked. `after` is written as a save would+ /// write it, without the marks' own `overlays` (the box and its label are drawn on purpose), its+ /// text is extracted, and a glyph still mostly inside a mark fails the edit: the caller keeps+ /// the document as it was.+ pub(crate) fn shown_under_redactions(+ after: &pdfcraft_cos::Document,+ marks: &[pdfcraft_redact::Mark],+ overlays: &[pdfcraft_cos::ObjRef],+ pages: &[pdfcraft_render::PageInfo],+ password: Option<&str>,+ ) -> Result<(), EditError> {+ use pdfcraft_cos::Object;+ use pdfcraft_redact::RedactError;+ let mut marked: Vec<usize> = marks.iter().map(|m| m.page).collect();+ marked.sort_unstable();+ marked.dedup();+ if marked.is_empty() {+ return Ok(());+ }+ let mut shown = after.clone();+ let model = pdfcraft_model::pages(&shown);+ for &pi in &marked {+ let Some(page) = model.get(pi) else { continue };+ let Some(Object::Array(list)) = page.dict.get(b"Contents").map(|c| (*shown.resolve(c)).clone()) else { continue };+ let kept: Vec<Object> = list.into_iter().filter(|o| !o.as_ref().is_some_and(|r| overlays.contains(&r))).collect();+ shown.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(kept))).map_err(|e| EditError::Write(e.to_string()))?;+ }+ let bytes = write_incremental(&shown, &SaveOptions::default()).map_err(|e| EditError::Write(e.to_string()))?;+ let config = RenderConfig { password: password.map(Arc::from), ..Default::default() };+ let mut renderer = pdfcraft_render::PageRenderer::new(Arc::new(bytes), config);+ let mut residue = 0;+ for &pi in &marked {+ let request = pdfcraft_render::RenderRequest { page: pi, kind: pdfcraft_render::RequestKind::Text, scale: 1.0, ..Default::default() };+ // A page that cannot be read back cannot be confirmed clean.+ let (Some(info), Some(text)) = (pages.get(pi), renderer.render(request).text) else { return Err(RedactError::Unreadable(pi + 1).into()) };+ let rects: Vec<[f64; 4]> = marks+ .iter()+ .filter(|m| m.page == pi)+ .flat_map(|m| m.rects.iter())+ .map(|r| [r[0].min(r[2]), r[1].min(r[3]), r[0].max(r[2]), r[1].max(r[3])])+ .collect();+ for glyph in text.glyphs.iter().filter(|g| !g.text.trim().is_empty()) {+ let [x0, y0, x1, y1] = info.view_rect_to_user(glyph.rect).map(f64::from);+ let area = (x1 - x0) * (y1 - y0);+ if area.is_nan() || area <= 0.0 {+ continue;+ }+ // Redaction itself takes any glyph a fifth under a mark; one that is half under it+ // and still drawn was not where redaction thought it was.+ let under = |r: &[f64; 4]| (x1.min(r[2]) - x0.max(r[0])).max(0.0) * (y1.min(r[3]) - y0.max(r[1])).max(0.0) >= 0.5 * area;+ if rects.iter().any(under) {+ residue += 1;+ }+ }+ }+ if residue > 0 {+ return Err(RedactError::Residue(residue).into());+ }+ Ok(())+ }diff --cc crates/engine/src/edit.rsindex 000000000,c31984ca1..2c64f7bcdmode 000000,100644..100644--- a/crates/engine/src/edit.rs+++ b/crates/engine/src/edit.rs@@@ -1,0 -1,553 +1,558 @@@+ //! The edits a document takes: what each is called, whether its permissions allow it, and running it.++ use std::sync::Arc;++ use crate::{+ AddedContent, AddedText, Background, BoxSpec, EditError, FieldProps, FieldValue, FillMark, HeaderFooter, Hidden, ImageEdit, InitialView, Label,+ LineEnding, LinkAction, LinkStyle, MarkFile, MarkKind, Markup, NewAnnotation, NewField, NoteIcon, ObjectTarget, PageBox, Protection, ReviewState,+ Rgb, Shape, Standard, Style, TabOrder, TransitionSpec, Watermark, a11y, copy_image, decode_data_file, embed_image, field_table, fit_picture,+ image_content_type, is_xfa_data_file, js, mark_source, measure, open_source, strip_xfa, unrestricted, xfa, xfa_after_data_change,+ };++ mod labels;+ mod run;++ pub use labels::{BATCH_LABELS, EDIT_LABELS};+ pub(crate) use run::{EditCtx, check_permission, run_edit};++ /// Edits that can be applied to a document. Page indices are 0-based.+ #[derive(Clone, Debug, PartialEq)]+ pub enum Edit {+ RotatePages {+ pages: Vec<usize>,+ degrees: i64,+ },+ DeletePages {+ pages: Vec<usize>,+ },+ MovePages {+ pages: Vec<usize>,+ to: usize,+ },+ /// `pages` reversed among the positions they occupy.+ ReversePages {+ pages: Vec<usize>,+ },+ InsertBlankPage {+ at: usize,+ width: f64,+ height: f64,+ },+ /// Copies of `pages` inserted at `at` (an index in the page order as it is now), or after+ /// the last of them when `at` is `None`.+ DuplicatePages {+ pages: Vec<usize>,+ at: Option<usize>,+ },+ /// Replace Pages: the content of `pages` is replaced by `src_pages` of another PDF; the+ /// pages' links, comments and bookmarks stay.+ ReplacePages {+ pages: Vec<usize>,+ name: String,+ bytes: Arc<Vec<u8>>,+ src_pages: Vec<usize>,+ },+ /// Set Page Boxes / Crop: set (or reset) one box on `pages`.+ SetPageBox {+ pages: Vec<usize>,+ which: PageBox,+ spec: BoxSpec,+ },+ /// Set or remove the page transition and display time of pages (ISO 32000-2 §12.4.4),+ /// Organize ▸ Page Transitions.+ SetTransition {+ pages: Vec<usize>,+ spec: TransitionSpec,+ },+ SetInfo {+ key: String,+ value: String,+ },+ /// Insert pages from another PDF (all pages when `pages` is `None`) at position `at`.+ InsertPagesFrom {+ name: String,+ bytes: Arc<Vec<u8>>,+ pages: Option<Vec<usize>>,+ at: usize,+ /// How a form field whose name the document already uses is kept separate.+ field_conflicts: pdfcraft_organize::FieldConflicts,+ },+ /// Add a bookmark to `page` as child `index` of the bookmark at `parent` (`[]` = top level).+ /// It goes to the user-space point (`left`, `top`) of the page at the reader's zoom, and+ /// either may be `None` to keep the reader's position that way (both `None` is the page top).+ /// A coordinate that is not finite fails the edit.+ AddBookmark {+ parent: Vec<usize>,+ index: usize,+ title: String,+ page: usize,+ left: Option<f64>,+ top: Option<f64>,+ },+ RenameBookmark {+ path: Vec<usize>,+ title: String,+ },+ /// Delete a bookmark and the bookmarks under it.+ DeleteBookmark {+ path: Vec<usize>,+ },+ /// Move a bookmark to child `index` of `to_parent` (indices after removing it).+ MoveBookmark {+ from: Vec<usize>,+ to_parent: Vec<usize>,+ index: usize,+ },+ /// Point a bookmark at another page.+ SetBookmarkPage {+ path: Vec<usize>,+ page: usize,+ },+ /// Colour a bookmark's title (`/C`); `None` or black is the default black.+ SetBookmarkColor {+ path: Vec<usize>,+ color: Option<[f64; 3]>,+ },+ /// Make a bookmark's title bold or italic or not (`/F`); `None` keeps that one.+ SetBookmarkStyle {+ path: Vec<usize>,+ bold: Option<bool>,+ italic: Option<bool>,+ },+ /// Bookmarks for the tagged headings (H, H1–H6), nested by level under a new first+ /// "Untitled" bookmark (New Bookmarks from Structure).+ BookmarksFromStructure,++ /// Bookmarks for the lines set in `levels`' styles (the first is level 1, the next nests++ /// under it, …), under a new first "Untitled" bookmark (#1693; see [`crate::text_style_bookmarks`]).++ BookmarksFromTextStyles {++ levels: Vec<crate::text_style_bookmarks::TextStyle>,++ },+ /// Label pages `from..=to` (0-based) as Acrobat's "Number pages" does; later pages keep their labels.+ NumberPages {+ from: usize,+ to: usize,+ style: pdfcraft_organize::LabelStyle,+ prefix: String,+ first: u32,+ },+ /// Add a calibrated distance, perimeter or area annotation.+ AddMeasurement(measure::NewMeasurement),+ /// Store a drawing scale for a rectangular viewport (PDF user space).+ SetMeasurementScale {+ page: usize,+ bbox: [f64; 4],+ name: String,+ scale: measure::Scale,+ },+ /// Add a comment (sticky note, highlight, shape, drawing, text box…).+ AddAnnotation(NewAnnotation),+ /// A custom stamp from a picture file (a PDF page or an image) on `page`. A zero-size+ /// `rect` is a point: the stamp is centred there at its natural size (at most 200 pt).+ /// Any other `rect` is a box: the picture is scaled to fit inside it, keeping its shape,+ /// and centred in it (#4077).+ AddCustomStamp {+ page: usize,+ rect: [f64; 4],+ name: String,+ file: MarkFile,+ author: String,+ },+ /// Delete the comment at `index` in the page's `/Annots`, with its pop-up and replies.+ DeleteAnnotation {+ page: usize,+ index: usize,+ },+ SetAnnotationContents {+ page: usize,+ index: usize,+ text: String,+ },+ ReplyToAnnotation {+ page: usize,+ index: usize,+ text: String,+ author: String,+ },+ /// Acrobat's "Set status" (a state reply by `author`).+ SetAnnotationStatus {+ page: usize,+ index: usize,+ state: ReviewState,+ author: String,+ },+ /// The Eraser: rub out the parts of drawing `(page, index)` near `path` (user space).+ EraseInk {+ page: usize,+ index: usize,+ path: Vec<[f64; 2]>,+ radius: f64,+ },+ /// Replace Text: strike out `quads` and add a grouped caret holding `text`.+ ReplaceText {+ page: usize,+ quads: Vec<[f64; 8]>,+ text: String,+ author: String,+ strike: Style,+ caret: Style,+ },+ /// Acrobat's "Mark with checkmark" (a hidden `/StateModel /Marked` reply by `author`).+ MarkAnnotation {+ page: usize,+ index: usize,+ marked: bool,+ author: String,+ },+ /// Properties ▸ Locked.+ LockAnnotation {+ page: usize,+ index: usize,+ locked: bool,+ },+ MoveAnnotation {+ page: usize,+ index: usize,+ dx: f64,+ dy: f64,+ },+ /// Reshape a line, connected lines, a polygon or a cloud: its points in user space (a line's+ /// two ends, the others' corners).+ ReshapeAnnotation {+ page: usize,+ index: usize,+ points: Vec<[f64; 2]>,+ },+ /// Resize a rectangle, oval or text box.+ ResizeAnnotation {+ page: usize,+ index: usize,+ rect: [f64; 4],+ },+ StyleAnnotation {+ page: usize,+ index: usize,+ color: Option<Rgb>,+ opacity: Option<f64>,+ width: Option<f64>,+ /// Line or polyline: two endings. Callout: one. `None` leaves `/LE` unchanged.+ endings: Option<Vec<pdfcraft_annot::LineEnding>>,+ },+ /// Fill a rectangle, oval or polygon comment, or remove its fill (`None`).+ FillAnnotation {+ page: usize,+ index: usize,+ fill: Option<Rgb>,+ },+ /// Change the font size (pt) of a text box, typewriter text or callout.+ FontSizeAnnotation {+ page: usize,+ index: usize,+ size: f64,+ },+ /// Comment properties ▸ General / note icon.+ SetAnnotationInfo {+ page: usize,+ index: usize,+ author: Option<String>,+ subject: Option<String>,+ icon: Option<NoteIcon>,+ },+ /// Fill in a form field.+ SetFieldValue {+ name: String,+ value: FieldValue,+ },+ /// Clear form: the named fields (all when `None`) back to their defaults.+ ResetForm {+ names: Option<Vec<String>>,+ },+ /// Prepare a form: add a field on a page (`rect` in PDF user space); `name` defaults to+ /// Acrobat's next free name ("Text1", "Check Box2", …).+ AddField {+ page: usize,+ rect: [f64; 4],+ kind: NewField,+ name: Option<String>,+ },+ /// Field Properties ▸ General / Options.+ SetFieldProps {+ name: String,+ props: Box<FieldProps>,+ },+ /// An image field (or any button): show this image file (PNG, JPEG, TIFF, GIF, BMP).+ SetFieldImage {+ name: String,+ image: Arc<Vec<u8>>,+ },+ /// Duplicate a field onto other pages (same field, shared value).+ DuplicateField {+ name: String,+ pages: Vec<usize>,+ },+ DeleteField {+ name: String,+ },+ /// Page properties ▸ Tab order, for pages (0-based).+ SetTabOrder {+ pages: Vec<usize>,+ order: TabOrder,+ },+ /// Document Properties ▸ Initial View (and the language and binding).+ SetInitialView(Box<InitialView>),+ /// Edit ▸ Attach a file: a document-level attachment (`/Names /EmbeddedFiles`) under+ /// `name`, made unique; `mime` is the embedded file's `/Subtype` when known.+ AddAttachment {+ name: String,+ bytes: Vec<u8>,+ description: Option<String>,+ mime: Option<String>,+ },+ /// Remove the document-level attachment whose name-tree key is `key`.+ DeleteAttachment {+ key: String,+ },+ /// Build a tagged structure tree for an untagged, text-only document.+ AutoTagText,+ /// Add alternate text: set (or clear, with `None`) a figure's alternate text. `figure` is+ /// the figure element's object number (from `Document::figures`).+ SetAltText {+ figure: u32,+ alt: Option<String>,+ },+ /// Add `/Form` tags and object references for all widgets in an untagged AcroForm.+ AutoTagFormFields,+ /// Change one property on a reachable indirect structure tag.+ SetTagProperty {+ object: pdfcraft_cos::ObjRef,+ property: a11y::TagProperty,+ value: Option<String>,+ },+ /// Move a structure tag before or after a direct sibling in reading order.+ MoveTag {+ object: pdfcraft_cos::ObjRef,+ anchor: pdfcraft_cos::ObjRef,+ placement: a11y::TagPlacement,+ },+ /// Add alternate text ▸ Decorative figure: the figure's content becomes an artifact.+ MarkDecorative {+ figure: u32,+ },+ /// Tags panel ▸ Mark as artifact: retire a leaf tag and mark its content as an artifact.+ MarkTagArtifact {+ object: pdfcraft_cos::ObjRef,+ },+ /// Document JavaScripts: add, replace (`script`) or remove (`None`) the document-level+ /// script `name`.+ SetDocumentScript {+ name: String,+ script: Option<String>,+ },+ /// Field Properties ▸ a custom script: set or remove field `name`'s JavaScript for `event`+ /// (keystroke, format, validate, calculate or mouse_up).+ SetFieldScript {+ name: String,+ event: String,+ script: Option<String>,+ },+ /// Standards ▸ Save as PDF/A: fix what can be fixed for `level` (metadata, output intent,+ /// forbidden actions, annotation flags, …).+ ConvertPdfA {+ level: pdfcraft_preflight::Level,+ },+ /// Remove what identifies the document as meeting `standard` (PDF/A or PDF/X).+ RemoveStandardId {+ standard: Standard,+ },+ /// What a script (button or console) changed in form fields: values, read-only, required+ /// and visibility.+ ApplyScriptChanges {+ changes: Vec<pdfcraft_forms::FieldChange>,+ },+ /// An XFA form's scripted event (a button's `click`, say) on the object at `som`: what the+ /// script changes (values, rows, visibility) is applied and the form laid out again.+ XfaEvent {+ som: String,+ activity: String,+ },+ /// Scan & OCR ▸ Recognize text: put recognised words on `page` as invisible text over the+ /// image (from [`ocr::OcrJob::run`](crate::ocr::OcrJob::run)).+ AddOcrText {+ page: usize,+ words: Vec<pdfcraft_ocr::PlacedWord>,+ },+ /// Edit a PDF ▸ Edit text: replace the text of line `line` (from `Document::text_lines`) on+ /// `page`, in its own font when it can show it, else in Helvetica.+ EditTextLine {+ page: usize,+ line: usize,+ text: String,+ },+ /// Edit a PDF ▸ an existing image on `page` (index from `Document::page_images`).+ EditPageImage {+ page: usize,+ index: usize,+ change: ImageEdit,+ },+ /// Move mixed existing and added objects together. References resolve before any change;+ /// offset is a user-space vector. No retyping, reflow or font substitution is involved.+ MoveObjects {+ page: usize,+ objects: Vec<ObjectTarget>,+ offset: [f64; 2],+ },+ /// Edit text in a paragraph box: replace paragraph `block` (from `Document::text_blocks`),+ /// rewrapped to the box's width.+ EditTextBlock {+ page: usize,+ block: usize,+ text: String,+ /// Formatting changes (font, size, colour, alignment); default keeps the paragraph's.+ style: pdfcraft_edit::BlockStyle,+ },+ /// An explicit open-licensed full font program, completing subsets or selected by a user.+ RegisterTextFont {+ page: usize,+ bytes: Arc<Vec<u8>>,+ },+ /// Order tabs manually: move a field one place earlier or later on its page.+ MoveInTabOrder {+ name: String,+ earlier: bool,+ },+ /// Set the calculation order: these calculated fields first, in this order, then the others+ /// in their current order (see [`Document::calculation_order`](crate::Document::calculation_order)). The form recalculates.+ SetCalculationOrder {+ names: Vec<String>,+ },+ /// Add a header and footer (with `replace`, existing ones on those pages go first).+ AddHeaderFooter {+ pages: Vec<usize>,+ settings: HeaderFooter,+ replace: bool,+ },+ /// `file`: a picture from a file (an image, or a page of a PDF) instead of text.+ AddWatermark {+ pages: Vec<usize>,+ settings: Watermark,+ replace: bool,+ file: Option<MarkFile>,+ },+ /// `file`: a picture from a file instead of a colour.+ AddBackground {+ pages: Vec<usize>,+ settings: Background,+ replace: bool,+ file: Option<MarkFile>,+ },+ /// Remove every mark of a kind from every page.+ RemoveMarks {+ kind: MarkKind,+ },+ /// Edit a PDF ▸ Add content ▸ Text (`text.rect` in display space).+ AddText {+ page: usize,+ text: AddedText,+ },+ /// Edit a PDF ▸ Add content ▸ Image: an image file placed at `rect` (display space), or at+ /// its natural size centred on the page (shrunk to fit).+ AddImage {+ page: usize,+ rect: Option<[f64; 4]>,+ name: String,+ bytes: Arc<Vec<u8>>,+ },+ /// Move, resize, retype or reformat an added item (`index` among the page's added items).+ UpdateContent {+ page: usize,+ index: usize,+ content: AddedContent,+ },+ DeleteContent {+ page: usize,+ index: usize,+ },+ /// Replace an added image with another file (keeping its box and transforms).+ ReplaceImage {+ page: usize,+ index: usize,+ name: String,+ bytes: Arc<Vec<u8>>,+ },+ /// Edit ▸ Paste: an added item copied in this document or another, as it was: text with its+ /// style, an image in its box (display space) with its turns, flips and crop. An image's+ /// picture is `file` (from [`Document::added_image_file`](crate::Document::added_image_file)): the copied image object is reused+ /// while it is still that picture in this document, else one an added image here already draws+ /// it from, else the file is embedded.+ PasteContent {+ page: usize,+ content: AddedContent,+ file: Option<(String, Arc<Vec<u8>>)>,+ },+ /// Apply redaction marks (all, or those on `pages`): remove what they cover for good.+ ApplyRedactions {+ pages: Option<Vec<usize>>,+ },+ /// Remove redaction marks without applying them.+ ClearRedactions,+ /// Edit a PDF ▸ Link: a new link over `rect` (user space).+ AddLink {+ page: usize,+ rect: [f64; 4],+ action: LinkAction,+ style: LinkStyle,+ },+ /// Link Properties (`index` in the page's `/Annots`).+ SetLink {+ page: usize,+ index: usize,+ rect: Option<[f64; 4]>,+ action: Option<LinkAction>,+ style: Option<LinkStyle>,+ },+ DeleteLink {+ page: usize,+ index: usize,+ },+ /// Remove all links (on `pages`, or everywhere).+ RemoveLinks {+ pages: Option<Vec<usize>>,+ },+ /// Create links from URLs in the text: (page, line rects in user space, URI).+ AddLinks {+ links: Vec<(usize, Vec<[f64; 4]>, String)>,+ style: LinkStyle,+ },+ /// Import comments and/or form data (XFDF, FDF, XML, CSV, tab-delimited text).+ ImportData {+ name: String,+ bytes: Arc<Vec<u8>>,+ },+ /// Remove Hidden Information: the chosen categories.+ RemoveHidden {+ which: Vec<Hidden>,+ },+ /// Sanitize Document: every category, then a full rewrite on save.+ Sanitize,+ /// An XFA form made an ordinary (static) PDF form: the XFA packets, `/NeedsRendering` and+ /// PdfCraft's private keys go, the pages as laid out and the fields with their values+ /// stay, so every viewer shows the same form and none lays it out again. Its scripts no+ /// longer run.+ XfaToStatic,+ /// Flatten comments and/or form fields on every page into page content.+ Flatten {+ comments: bool,+ fields: bool,+ },+ /// Bake Fill & Sign text, marks and signatures into the page. Other comments and fields stay.+ /// A no-op (no undo step) when the document has none.+ FlattenFillSign,+ /// Protect with passwords and permissions (written by the next save, which is a full rewrite).+ Protect(Protection),+ /// Remove password security (needs the owner password).+ RemoveProtection,+ /// Several edits applied as one undoable step (all or nothing).+ Batch {+ label: String,+ edits: Vec<Edit>,+ },+ }diff --cc crates/engine/src/edit/labels.rsindex 000000000,5e25ae465..f850840edmode 000000,100644..100644--- a/crates/engine/src/edit/labels.rs+++ b/crates/engine/src/edit/labels.rs@@@ -1,0 -1,336 +1,338 @@@+ use super::*;++ /// Every wording [`Edit::label`] can produce, for an interface to translate. `Edit::Batch` is not+ /// here: its wording is only the hole, because a batch carries its name as text (see+ /// [`BATCH_LABELS`]).+ pub const EDIT_LABELS: &[&str] = &[+ "Rotate page",+ "Change tag properties",+ "Rotate pages",+ "Delete page",+ "Delete pages",+ "Move page",+ "Move pages",+ "Reverse pages",+ "Insert blank page",+ "Duplicate page",+ "Duplicate pages",+ "Replace page",+ "Replace pages",+ "Crop page",+ "Crop pages",+ "Set page boxes",+ "Set page transitions",+ "Change Title",+ "Change Author",+ "Change Subject",+ "Change Keywords",+ "Change {key}",+ "Insert pages from {name}",+ "Insert pages from {name} — 1 field renamed",+ "Insert pages from {name} — fields renamed",+ "Attach {name}",+ "Delete attachment {key}",+ "Add bookmark",+ "Rename bookmark",+ "Delete bookmark",+ "Move bookmark",+ "Set bookmark destination",+ "Colour",+ "Style",+ "New bookmarks from structure",++ "New bookmarks from text styles",+ "Number pages",+ "Measure distance",+ "Measure perimeter",+ "Measure area",+ "Set measurement scale",+ "Add sticky note",+ "Add highlight",+ "Add underline",+ "Add strikethrough",+ "Add squiggly underline",+ "Add rectangle",+ "Add oval",+ "Add arrow",+ "Add line",+ "Add drawing",+ "Add text box",+ "Add checkmark",+ "Add cross",+ "Add dot",+ "Add signature",+ "Add redaction mark",+ "Add cloud",+ "Add polygon",+ "Add connected lines",+ "Add callout",+ "Add inserted text",+ "Add file attachment",+ "Add stamp",+ "Delete comment",+ "Edit comment",+ "Reply",+ "Set status None",+ "Set status Accepted",+ "Set status Rejected",+ "Set status Cancelled",+ "Set status Completed",+ "Replace text",+ "Erase",+ "Mark with checkmark",+ "Remove checkmark",+ "Lock comment",+ "Unlock comment",+ "Move comment",+ "Reshape comment",+ "Resize comment",+ "Change comment properties",+ "Fill in {name}",+ "Set the image of {name}",+ "Clear form",+ "Add field",+ "Change field properties",+ "Delete field",+ "Duplicate field",+ "Set tab order",+ "Set calculation order",+ "Change initial view",+ "Set alternate text",+ "Mark figure as decorative",+ "Recognize text",+ "Run JavaScript",+ "Run form script",+ "Save as {level}",+ "Remove {standard} identification",+ "Edit script of {name}",+ "Delete document JavaScript",+ "Edit document JavaScript",+ "Edit text",+ "Load document font",+ "Move object",+ "Move objects",+ "Move image",+ "Rotate image",+ "Flip image",+ "Replace image",+ "Delete image",+ "Add header & footer",+ "Update header & footer",+ "Add watermark",+ "Update watermark",+ "Add background",+ "Update background",+ "Remove header & footer",+ "Remove watermark",+ "Remove background",+ "Add text",+ "Add image",+ "Edit content",+ "Delete content",+ "Paste",+ "Apply redactions",+ "Remove redaction marks",+ "Remove hidden information",+ "Import {name}",+ "Add link",+ "Change link properties",+ "Delete link",+ "Remove all links",+ "Create link",+ "Create links",+ "Sanitize document",+ "Flatten comments",+ "Flatten form fields",+ "Flatten",+ "Flatten Fill & Sign",+ "Protect with password",+ "Remove security",+ ];++ /// The names of the batches built below L7, which an interface shows in the same places as+ /// [`EDIT_LABELS`] and so translates the same way. A batch built in the interface itself arrives+ /// already worded in the interface's language.+ pub const BATCH_LABELS: &[&str] =+ &["Set document title", "Mark differences", "Detect form fields", "Run JavaScript", "Recognize text", field_table::LABEL, "Style"];++ impl Edit {+ /// Label for the Edit menu and history ("Undo Rotate pages").+ pub fn label(&self) -> Label {+ match self {+ Edit::RotatePages { pages, .. } => plural("Rotate page", "Rotate pages", pages.len()),+ Edit::DeletePages { pages } => plural("Delete page", "Delete pages", pages.len()),+ Edit::MovePages { pages, .. } => plural("Move page", "Move pages", pages.len()),+ Edit::ReversePages { .. } => Label::of("Reverse pages"),+ Edit::InsertBlankPage { .. } => Label::of("Insert blank page"),+ Edit::DuplicatePages { pages, .. } => plural("Duplicate page", "Duplicate pages", pages.len()),+ Edit::ReplacePages { pages, .. } => plural("Replace page", "Replace pages", pages.len()),+ Edit::SetPageBox { pages, which: PageBox::Crop, .. } => plural("Crop page", "Crop pages", pages.len()),+ Edit::SetPageBox { .. } => Label::of("Set page boxes"),+ Edit::SetTransition { .. } => Label::of("Set page transitions"),+ // The four `/Info` keys PdfCraft itself offers get a wording of their own, so each can+ // be said in another language; any other key is the document's and goes in as it stands.+ Edit::SetInfo { key, .. } => match key.as_str() {+ "Title" => Label::of("Change Title"),+ "Author" => Label::of("Change Author"),+ "Subject" => Label::of("Change Subject"),+ "Keywords" => Label::of("Change Keywords"),+ _ => Label::with("Change {key}", key.as_str()),+ },+ Edit::InsertPagesFrom { name, .. } => Label::with("Insert pages from {name}", name.as_str()),+ Edit::AddBookmark { .. } => Label::of("Add bookmark"),+ Edit::RenameBookmark { .. } => Label::of("Rename bookmark"),+ Edit::DeleteBookmark { .. } => Label::of("Delete bookmark"),+ Edit::MoveBookmark { .. } => Label::of("Move bookmark"),+ Edit::SetBookmarkPage { .. } => Label::of("Set bookmark destination"),+ // The bookmark Style and Colour menus' own names, already said in every language.+ Edit::SetBookmarkColor { .. } => Label::of("Colour"),+ Edit::SetBookmarkStyle { .. } => Label::of("Style"),+ Edit::BookmarksFromStructure => Label::of("New bookmarks from structure"),++ Edit::BookmarksFromTextStyles { .. } => Label::of("New bookmarks from text styles"),+ Edit::NumberPages { .. } => Label::of("Number pages"),+ // What was measured is part of the wording too, for the same reason.+ Edit::AddMeasurement(m) => Label::of(match m.kind {+ pdfcraft_measure::Kind::Distance => "Measure distance",+ pdfcraft_measure::Kind::Perimeter => "Measure perimeter",+ pdfcraft_measure::Kind::Area => "Measure area",+ }),+ Edit::SetMeasurementScale { .. } => Label::of("Set measurement scale"),+ Edit::AddAnnotation(a) => Label::of(add_annotation(&a.shape)),+ Edit::AddCustomStamp { .. } => Label::of("Add stamp"),+ Edit::DeleteAnnotation { .. } => Label::of("Delete comment"),+ Edit::SetAnnotationContents { .. } => Label::of("Edit comment"),+ Edit::ReplyToAnnotation { .. } => Label::of("Reply"),+ // The state's name is part of the wording: a language may need to agree it with the rest.+ Edit::SetAnnotationStatus { state, .. } => Label::of(match state {+ ReviewState::None => "Set status None",+ ReviewState::Accepted => "Set status Accepted",+ ReviewState::Rejected => "Set status Rejected",+ ReviewState::Cancelled => "Set status Cancelled",+ ReviewState::Completed => "Set status Completed",+ }),+ Edit::ReplaceText { .. } => Label::of("Replace text"),+ Edit::EraseInk { .. } => Label::of("Erase"),+ Edit::MarkAnnotation { marked: true, .. } => Label::of("Mark with checkmark"),+ Edit::MarkAnnotation { .. } => Label::of("Remove checkmark"),+ Edit::LockAnnotation { locked: true, .. } => Label::of("Lock comment"),+ Edit::LockAnnotation { .. } => Label::of("Unlock comment"),+ Edit::MoveAnnotation { .. } => Label::of("Move comment"),+ Edit::ReshapeAnnotation { .. } => Label::of("Reshape comment"),+ Edit::ResizeAnnotation { .. } => Label::of("Resize comment"),+ Edit::StyleAnnotation { .. } | Edit::FillAnnotation { .. } | Edit::FontSizeAnnotation { .. } | Edit::SetAnnotationInfo { .. } => {+ Label::of("Change comment properties")+ }+ Edit::SetFieldValue { name, .. } => Label::with("Fill in {name}", name.as_str()),+ Edit::SetFieldImage { name, .. } => Label::with("Set the image of {name}", name.as_str()),+ Edit::ResetForm { .. } => Label::of("Clear form"),+ Edit::AddField { .. } => Label::of("Add field"),+ Edit::SetFieldProps { .. } => Label::of("Change field properties"),+ Edit::DeleteField { .. } => Label::of("Delete field"),+ Edit::DuplicateField { .. } => Label::of("Duplicate field"),+ Edit::SetTabOrder { .. } | Edit::MoveInTabOrder { .. } => Label::of("Set tab order"),+ Edit::SetCalculationOrder { .. } => Label::of("Set calculation order"),+ Edit::SetInitialView(_) => Label::of("Change initial view"),+ Edit::AddAttachment { name, .. } => Label::with("Attach {name}", name.as_str()),+ Edit::DeleteAttachment { key } => Label::with("Delete attachment {key}", key.as_str()),+ Edit::AutoTagText => Label::of("Automatically tag text"),+ Edit::SetAltText { .. } => Label::of("Set alternate text"),+ Edit::AutoTagFormFields => Label::of("Tag form fields"),+ Edit::SetTagProperty { .. } => Label::of("Change tag properties"),+ Edit::MoveTag { .. } => Label::of("Move object"),+ Edit::MarkDecorative { .. } => Label::of("Mark figure as decorative"),+ Edit::MarkTagArtifact { .. } => Label::of("Mark content as artifact"),+ Edit::AddOcrText { .. } => Label::of("Recognize text"),+ Edit::ApplyScriptChanges { .. } => Label::of("Run JavaScript"),+ Edit::XfaEvent { .. } => Label::of("Run form script"),+ // The level is the standard's own name ("PDF/A-2b"), so it goes in as it stands.+ Edit::ConvertPdfA { level } => Label::with("Save as {level}", level.label()),+ Edit::RemoveStandardId { standard } => Label::with("Remove {standard} identification", standard.label()),+ Edit::SetFieldScript { name, .. } => Label::with("Edit script of {name}", name.as_str()),+ Edit::SetDocumentScript { script: None, .. } => Label::of("Delete document JavaScript"),+ Edit::SetDocumentScript { .. } => Label::of("Edit document JavaScript"),+ Edit::EditTextLine { .. } | Edit::EditTextBlock { .. } => Label::of("Edit text"),+ Edit::RegisterTextFont { .. } => Label::of("Load document font"),+ Edit::MoveObjects { objects, .. } => plural("Move object", "Move objects", objects.len()),+ Edit::EditPageImage { change, .. } => Label::of(match change {+ ImageEdit::Move(_) => "Move image",+ ImageEdit::Rotate(_) | ImageEdit::RotateBy(_) => "Rotate image",+ ImageEdit::Crop(_) => "Crop image",+ ImageEdit::Flip { .. } => "Flip image",+ ImageEdit::Replace { .. } => "Replace image",+ ImageEdit::Delete => "Delete image",+ }),+ Edit::AddHeaderFooter { replace: false, .. } => Label::of("Add header & footer"),+ Edit::AddHeaderFooter { .. } => Label::of("Update header & footer"),+ Edit::AddWatermark { replace: false, .. } => Label::of("Add watermark"),+ Edit::AddWatermark { .. } => Label::of("Update watermark"),+ Edit::AddBackground { replace: false, .. } => Label::of("Add background"),+ Edit::AddBackground { .. } => Label::of("Update background"),+ Edit::RemoveMarks { kind: MarkKind::HeaderFooter } => Label::of("Remove header & footer"),+ Edit::RemoveMarks { kind: MarkKind::Watermark } => Label::of("Remove watermark"),+ Edit::RemoveMarks { kind: MarkKind::Background } => Label::of("Remove background"),+ Edit::AddText { .. } => Label::of("Add text"),+ Edit::AddImage { .. } => Label::of("Add image"),+ Edit::UpdateContent { .. } => Label::of("Edit content"),+ Edit::DeleteContent { .. } => Label::of("Delete content"),+ Edit::ReplaceImage { .. } => Label::of("Replace image"),+ Edit::PasteContent { .. } => Label::of("Paste"),+ Edit::ApplyRedactions { .. } => Label::of("Apply redactions"),+ Edit::ClearRedactions => Label::of("Remove redaction marks"),+ Edit::RemoveHidden { .. } => Label::of("Remove hidden information"),+ Edit::ImportData { name, .. } => Label::with("Import {name}", name.as_str()),+ Edit::AddLink { .. } => Label::of("Add link"),+ Edit::SetLink { .. } => Label::of("Change link properties"),+ Edit::DeleteLink { .. } => Label::of("Delete link"),+ Edit::RemoveLinks { .. } => Label::of("Remove all links"),+ Edit::AddLinks { links, .. } => plural("Create link", "Create links", links.len()),+ Edit::Sanitize => Label::of("Sanitize document"),+ Edit::XfaToStatic => Label::of("Convert to a static form"),+ Edit::Flatten { comments: true, fields: false } => Label::of("Flatten comments"),+ Edit::Flatten { comments: false, fields: true } => Label::of("Flatten form fields"),+ Edit::Flatten { .. } => Label::of("Flatten"),+ Edit::FlattenFillSign => Label::of("Flatten Fill & Sign"),+ Edit::Protect(_) => Label::of("Protect with password"),+ Edit::RemoveProtection => Label::of("Remove security"),+ // A batch carries its own name, already worded by whoever built it.+ // A batch carries its name as text, so the wording is only the hole (see `BATCH_LABELS`).+ Edit::Batch { label, .. } => Label::with("{batch}", label.as_str()),+ }+ }+ }++ /// What the Edit menu calls a new comment ("Undo Add highlight"). A whole wording for each kind,+ /// so a language can give the noun the article and the gender its own grammar asks for.+ fn add_annotation(s: &Shape) -> &'static str {+ match s {+ Shape::Note { .. } => "Add sticky note",+ Shape::TextMarkup { kind: Markup::Highlight, .. } => "Add highlight",+ Shape::TextMarkup { kind: Markup::Underline, .. } => "Add underline",+ Shape::TextMarkup { kind: Markup::StrikeOut, .. } => "Add strikethrough",+ Shape::TextMarkup { kind: Markup::Squiggly, .. } => "Add squiggly underline",+ Shape::Rectangle { .. } => "Add rectangle",+ Shape::Oval { .. } => "Add oval",+ Shape::Line { start: LineEnding::None, end: LineEnding::OpenArrow, .. } => "Add arrow",+ Shape::Line { .. } => "Add line",+ Shape::Ink { .. } => "Add drawing",+ Shape::TextBox { .. } => "Add text box",+ Shape::Typewriter { .. } => "Add text",+ Shape::Mark { mark: FillMark::Check, .. } => "Add checkmark",+ Shape::Mark { mark: FillMark::Cross, .. } => "Add cross",+ Shape::Mark { mark: FillMark::Dot, .. } => "Add dot",+ Shape::Mark { mark: FillMark::Line, .. } => "Add line",+ Shape::Signature { .. } | Shape::TypedSignature { .. } => "Add signature",+ Shape::Redact { .. } => "Add redaction mark",+ Shape::Stamp { .. } | Shape::CustomStamp { .. } => "Add stamp",+ Shape::Polygon { cloud: true, .. } => "Add cloud",+ Shape::Polygon { .. } => "Add polygon",+ Shape::PolyLine { .. } => "Add connected lines",+ Shape::Callout { .. } => "Add callout",+ Shape::Caret { .. } => "Add inserted text",+ Shape::Attachment { .. } => "Add file attachment",+ }+ }++ /// The singular or the plural wording, by count. Both are written out: a language forms its plural+ /// its own way, and `one` and `many` may differ in more than an "s".+ fn plural(one: &'static str, many: &'static str, n: usize) -> Label {+ Label::of(if n == 1 { one } else { many })+ }diff --cc crates/engine/src/edit/run.rsindex 000000000,7901a3b7d..8734c372bmode 000000,100644..100644--- a/crates/engine/src/edit/run.rs+++ b/crates/engine/src/edit/run.rs@@@ -1,0 -1,696 +1,717 @@@+ use super::*;++ /// Whether the opening password allows an edit (§7.6.4.2, Table 22).+ pub(crate) fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Result<(), EditError> {+ match edit {+ Edit::RotatePages { .. }+ | Edit::DeletePages { .. }+ | Edit::MovePages { .. }+ | Edit::ReversePages { .. }+ | Edit::InsertBlankPage { .. }+ | Edit::DuplicatePages { .. }+ | Edit::ReplacePages { .. }+ | Edit::SetPageBox { .. }+ | Edit::SetTransition { .. }+ | Edit::InsertPagesFrom { .. }+ // "Assemble the document: insert, rotate or delete pages and create bookmarks" (Table 22).+ | Edit::AddBookmark { .. }+ | Edit::RenameBookmark { .. }+ | Edit::DeleteBookmark { .. }+ | Edit::MoveBookmark { .. }+ | Edit::SetBookmarkPage { .. }+ | Edit::SetBookmarkColor { .. }+ | Edit::SetBookmarkStyle { .. }+ | Edit::BookmarksFromStructure+ | Edit::NumberPages { .. } => {+ if p.assemble() {+ Ok(())+ } else {+ Err(EditError::NotPermitted("page changes"))+ }+ }++ // Creates bookmarks (assembly), and their titles are the document's text, copied out of it++ // (Table 22, bit 5), as an export of it would be.++ Edit::BookmarksFromTextStyles { .. } => {++ if !p.assemble() {++ Err(EditError::NotPermitted("page changes"))++ } else if !p.copy() {++ Err(EditError::NotPermitted("copying text and images"))++ } else {++ Ok(())++ }++ }+ Edit::AddMeasurement(_)+ | Edit::AddAnnotation(_)+ | Edit::AddCustomStamp { .. }+ | Edit::DeleteAnnotation { .. }+ | Edit::SetAnnotationContents { .. }+ | Edit::ReplyToAnnotation { .. }+ | Edit::SetAnnotationStatus { .. }+ | Edit::MarkAnnotation { .. }+ | Edit::ReplaceText { .. }+ | Edit::EraseInk { .. }+ | Edit::LockAnnotation { .. }+ | Edit::MoveAnnotation { .. }+ | Edit::ReshapeAnnotation { .. }+ | Edit::ResizeAnnotation { .. }+ | Edit::StyleAnnotation { .. }+ | Edit::FillAnnotation { .. }+ | Edit::FontSizeAnnotation { .. }+ | Edit::SetAnnotationInfo { .. }+ | Edit::SetMeasurementScale { .. } => {+ if p.annotate() {+ Ok(())+ } else {+ Err(EditError::NotPermitted("comments"))+ }+ }+ Edit::SetFieldValue { .. } | Edit::ResetForm { .. } | Edit::SetFieldImage { .. } | Edit::ApplyScriptChanges { .. } | Edit::XfaEvent { .. } => {+ if p.fill_forms() {+ Ok(())+ } else {+ Err(EditError::NotPermitted("filling in form fields"))+ }+ }+ Edit::Protect(_) | Edit::RemoveProtection => {+ if unrestricted(p) {+ Ok(())+ } else {+ Err(EditError::NotPermitted("changing security"))+ }+ }+ // Converting to PDF/A takes the encryption off (PDF/A forbids it), so on an encrypted+ // document it is a change of security (#3921).+ Edit::ConvertPdfA { .. } => {+ if unrestricted(p) {+ Ok(())+ } else {+ Err(EditError::NotPermitted("removing the encryption, which PDF/A forbids"))+ }+ }+ Edit::SetInfo { .. }+ | Edit::AddHeaderFooter { .. }+ | Edit::AddWatermark { .. }+ | Edit::AddBackground { .. }+ | Edit::RemoveMarks { .. }+ | Edit::AddField { .. }+ | Edit::ApplyRedactions { .. }+ | Edit::AddText { .. }+ | Edit::AddImage { .. }+ | Edit::UpdateContent { .. }+ | Edit::MoveObjects { .. }+ | Edit::DeleteContent { .. }+ | Edit::ReplaceImage { .. }+ | Edit::PasteContent { .. }+ | Edit::ClearRedactions+ | Edit::RemoveHidden { .. }+ | Edit::ImportData { .. }+ | Edit::AddLink { .. }+ | Edit::SetLink { .. }+ | Edit::DeleteLink { .. }+ | Edit::RemoveLinks { .. }+ | Edit::AddLinks { .. }+ | Edit::Sanitize+ | Edit::XfaToStatic+ | Edit::SetFieldProps { .. }+ | Edit::DeleteField { .. }+ | Edit::DuplicateField { .. }+ | Edit::SetTabOrder { .. }+ | Edit::MoveInTabOrder { .. }+ | Edit::SetCalculationOrder { .. }+ | Edit::SetInitialView(_)+ | Edit::AddAttachment { .. }+ | Edit::DeleteAttachment { .. }+ | Edit::AutoTagText+ | Edit::SetAltText { .. }+ | Edit::AutoTagFormFields+ | Edit::SetTagProperty { .. }+ | Edit::MoveTag { .. }+ | Edit::MarkDecorative { .. }+ | Edit::MarkTagArtifact { .. }+ | Edit::AddOcrText { .. }+ | Edit::SetDocumentScript { .. }+ | Edit::SetFieldScript { .. }+ | Edit::RemoveStandardId { .. }+ | Edit::EditTextLine { .. }+ | Edit::EditTextBlock { .. }+ | Edit::RegisterTextFont { .. }+ | Edit::EditPageImage { .. }+ | Edit::Flatten { .. }+ | Edit::FlattenFillSign => {+ if p.modify() {+ Ok(())+ } else {+ Err(EditError::NotPermitted("changes to the document"))+ }+ }+ Edit::Batch { edits, .. } => edits.iter().try_for_each(|e| check_permission(e, p)),+ }+ }++ /// Dates and unique ids stamped onto what an edit creates.+ pub(crate) struct EditCtx {+ /// Field scripts run (`None`: JavaScript is off) and what they produced.+ pub(crate) js: Option<js::JsRunner>,+ /// A laid-out XFA form's template (`None`: not an XFA form, or JavaScript is off) and what+ /// its scripts produced.+ pub(crate) xfa: Option<Arc<pdfcraft_xfa::model::Template>>,+ pub(crate) xfa_out: js::JsOutput,+ /// The datasets stream this edit wrote (later writes in the edit replace it in place).+ pub(crate) xfa_datasets: Option<pdfcraft_cos::ObjRef>,+ /// A form script ran too long and was abandoned: the document's scripts go off.+ pub(crate) xfa_ran_away: bool,+ /// What the XFA scripts' time limits are multiplied by ([`Session::with_xfa_time_scale`]).+ pub(crate) xfa_time_scale: u32,+ /// The edit took the XFA out of the form: what went with it, for the document's warnings.+ pub(crate) xfa_removed: Vec<String>,+ /// Pages in the document, for `xfa.layout.pageCount()`.+ pub(crate) pages: usize,+ pub(crate) date: Option<String>,+ /// Today in local time, for date tokens.+ pub(crate) today: (i64, u32, u32),+ pub(crate) seed: u64,+ pub(crate) count: u64,+ /// Fields the edit renamed to keep imported names separate (old → new), for the repair+ /// log and the undo label.+ pub(crate) renamed_fields: Vec<(String, String)>,+ /// The overlay streams the edit's applied redactions added, which alone the renderer's check+ /// leaves out.+ pub(crate) redaction_overlays: Vec<pdfcraft_cos::ObjRef>,+ }++ impl EditCtx {+ pub(crate) fn new(now: Option<i64>, salt: u64) -> Self {+ let mut seed = 0x9E37_79B9_7F4A_7C15u64 ^ salt;+ if let Some(t) = now {+ seed ^= (t as u64).rotate_left(17);+ }+ #[cfg(not(target_arch = "wasm32"))]+ if now.is_some() {+ // Real clock: mix in sub-second time so ids from two sessions don't collide.+ seed ^= std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos() as u64).unwrap_or(0) << 32;+ }+ Self {+ js: None,+ xfa: None,+ xfa_out: Default::default(),+ xfa_datasets: None,+ xfa_ran_away: false,+ xfa_time_scale: 1,+ xfa_removed: Vec::new(),+ pages: 0,+ date: now.map(pdfcraft_cos::pdf_date),+ today: (1970, 1, 1),+ seed,+ count: 0,+ renamed_fields: Vec::new(),+ redaction_overlays: Vec::new(),+ }+ }++ /// 32 bytes of entropy for new encryption keys and salts. `RandomState` is seeded by the+ /// operating system, so no extra dependency is needed.+ fn entropy(&mut self) -> [u8; 32] {+ use std::hash::{BuildHasher, Hasher};+ let mut out = [0u8; 32];+ for (i, chunk) in out.chunks_mut(8).enumerate() {+ let mut h = std::collections::hash_map::RandomState::new().build_hasher();+ h.write_u64(self.seed ^ i as u64);+ h.write_u64(self.count);+ self.count += 1;+ chunk.copy_from_slice(&h.finish().to_le_bytes());+ }+ out+ }++ /// A fresh `/NM`: a random-looking UUID (version 4 layout) from a splitmix64 stream.+ fn meta(&mut self) -> pdfcraft_annot::Meta {+ let mut next = || {+ self.count += 1;+ let mut z = self.seed.wrapping_add(self.count.wrapping_mul(0x9E37_79B9_7F4A_7C15));+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);+ z ^ (z >> 31)+ };+ let (a, b) = (next(), next());+ let id = format!(+ "{:08x}-{:04x}-4{:03x}-{:04x}-{:012x}",+ a >> 32,+ (a >> 16) & 0xffff,+ a & 0xfff,+ 0x8000 | (b >> 48) & 0x3fff,+ b & 0xffff_ffff_ffff+ );+ pdfcraft_annot::Meta { date: self.date.clone(), id }+ }+ }++ /// Perform an edit on a working copy (the caller discards it on error).+ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) -> Result<(), EditError> {+ match edit {+ Edit::RotatePages { pages, degrees } => pdfcraft_organize::rotate_pages(doc, pages, *degrees)?,+ Edit::DeletePages { pages } => pdfcraft_organize::delete_pages(doc, pages)?,+ Edit::MovePages { pages, to } => pdfcraft_organize::move_pages(doc, pages, *to)?,+ Edit::ReversePages { pages } => pdfcraft_organize::reverse_pages(doc, pages)?,+ Edit::InsertBlankPage { at, width, height } => {+ pdfcraft_organize::insert_blank_page(doc, *at, *width, *height)?;+ }+ Edit::SetInfo { key, value } => pdfcraft_organize::set_info(doc, key, value)?,+ Edit::DuplicatePages { pages, at } => pdfcraft_organize::duplicate_pages(doc, pages, *at)?,+ Edit::ReplacePages { pages, name, bytes, src_pages } => {+ let src = open_source(name, bytes)?;+ pdfcraft_organize::replace_pages(doc, pages, &src, src_pages)?;+ }+ Edit::SetPageBox { pages, which, spec } => pdfcraft_organize::set_page_box(doc, pages, *which, *spec)?,+ Edit::SetTransition { pages, spec } => pdfcraft_organize::set_transition(doc, pages, spec)?,+ Edit::InsertPagesFrom { name, bytes, pages, at, field_conflicts } => {+ let src = open_source(name, bytes)?;+ let pages = match pages {+ Some(p) => p.clone(),+ None => (0..pdfcraft_organize::page_count(&src)?).collect(),+ };+ // The file's bookmarks come along under one named after it, as in Combine Files.+ let title = std::path::Path::new(name).file_stem().map_or_else(|| name.clone(), |s| s.to_string_lossy().into_owned());+ let outcome = pdfcraft_organize::insert_file_pages(doc, &src, &title, &pages, *at, *field_conflicts)?;+ cx.renamed_fields = outcome.renamed_fields;+ }+ Edit::AddBookmark { parent, index, title, page, left, top } => {+ pdfcraft_organize::add_bookmark_at(doc, parent, *index, title, *page, *left, *top)?;+ }+ Edit::RenameBookmark { path, title } => pdfcraft_organize::rename_bookmark(doc, path, title)?,+ Edit::DeleteBookmark { path } => pdfcraft_organize::delete_bookmark(doc, path)?,+ Edit::MoveBookmark { from, to_parent, index } => {+ pdfcraft_organize::move_bookmark(doc, from, to_parent, *index)?;+ }+ Edit::SetBookmarkPage { path, page } => pdfcraft_organize::set_bookmark_page(doc, path, *page)?,+ Edit::SetBookmarkColor { path, color } => pdfcraft_organize::set_bookmark_color(doc, path, *color)?,+ Edit::SetBookmarkStyle { path, bold, italic } => pdfcraft_organize::set_bookmark_style(doc, path, *bold, *italic)?,+ Edit::BookmarksFromStructure => {+ let entries: Vec<_> = pdfcraft_a11y::headings(doc)+ .into_iter()- .map(|h| pdfcraft_organize::OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj })++ .map(|h| pdfcraft_organize::OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj, top: None })+ .collect();+ pdfcraft_organize::add_bookmark_tree(doc, "Untitled", &entries)?;+ }++ Edit::BookmarksFromTextStyles { levels } => {++ if levels.is_empty() {++ return Err(EditError::Invalid("choose a text style for at least one bookmark level".into()));++ }++ let entries = crate::text_style_bookmarks::headings(doc, levels);++ if entries.is_empty() {++ return Err(EditError::Invalid("no text is set in the chosen styles".into()));++ }++ pdfcraft_organize::add_bookmark_tree(doc, "Untitled", &entries)?;++ }+ Edit::NumberPages { from, to, style, prefix, first } => pdfcraft_organize::number_pages(doc, *from, *to, *style, prefix, *first)?,+ Edit::AddMeasurement(m) => {+ measure::add(doc, m, &cx.meta())?;+ }+ Edit::SetMeasurementScale { page, bbox, name, scale } => measure::set_scale(doc, *page, *bbox, name, scale)?,+ Edit::AddAnnotation(a) => {+ pdfcraft_annot::add_annotation(doc, a, &cx.meta())?;+ }+ Edit::AddCustomStamp { page, rect, name, file, author } => {+ let src = mark_source(doc, file)?;+ let (sw, sh) = (src.size.0.max(1.0), src.size.1.max(1.0));+ let natural = rect[2] == rect[0] && rect[3] == rect[1];+ let rotation = pdfcraft_organize::page_rotation(doc, *page)?;+ // The picture as displayed: a quarter turn swaps its sides in user space.+ let (dw, dh) = if matches!(rotation, 90 | 270) { (sh, sw) } else { (sw, sh) };+ let rect = if natural {+ let k = (200.0 / sw.max(sh)).min(1.0);+ let (w, h) = (dw * k, dh * k);+ [rect[0] - w / 2.0, rect[1] - h / 2.0, rect[0] + w / 2.0, rect[1] + h / 2.0]+ } else {+ fit_picture(*rect, dw, dh)+ };+ let shape = Shape::CustomStamp { rect, name: name.clone(), picture: src.xobject, image: src.image, size: (sw, sh) };+ let style = pdfcraft_annot::Style::default_for(&shape);+ let new = NewAnnotation { page: *page, shape, style, contents: name.clone(), author: author.clone() };+ let index = pdfcraft_annot::add_annotation(doc, &new, &cx.meta())?;+ pdfcraft_annot::orient_image_stamp(doc, *page, index, rotation)?;+ }+ Edit::DeleteAnnotation { page, index } => pdfcraft_annot::delete_annotation(doc, *page, *index)?,+ Edit::SetAnnotationContents { page, index, text } => pdfcraft_annot::set_contents(doc, *page, *index, text, &cx.meta())?,+ Edit::ReplyToAnnotation { page, index, text, author } => {+ pdfcraft_annot::add_reply(doc, *page, *index, text, author, &cx.meta())?;+ }+ Edit::SetAnnotationStatus { page, index, state, author } => {+ pdfcraft_annot::set_review_state(doc, *page, *index, *state, author, &cx.meta())?;+ }+ Edit::EraseInk { page, index, path, radius } => {+ pdfcraft_annot::erase_ink(doc, *page, *index, path, *radius, &cx.meta())?;+ }+ Edit::AddAttachment { name, bytes, description, mime } => {+ pdfcraft_organize::add_attachment(doc, name, bytes, description.as_deref(), mime.as_deref(), cx.date.as_deref())?;+ }+ Edit::DeleteAttachment { key } => pdfcraft_organize::delete_attachment(doc, key)?,+ Edit::ReplaceText { page, quads, text, author, strike, caret } => {+ // One `/NM` each: the caret replies to the strikeout, and XFDF names that reply by+ // the strikeout's `/NM` (#2666).+ let (strike_meta, caret_meta) = (cx.meta(), cx.meta());+ pdfcraft_annot::add_text_replacement(doc, *page, quads, text, author, strike, caret, &strike_meta, &caret_meta)?;+ }+ Edit::MarkAnnotation { page, index, marked, author } => {+ pdfcraft_annot::set_marked(doc, *page, *index, *marked, author, &cx.meta())?;+ }+ Edit::LockAnnotation { page, index, locked } => pdfcraft_annot::set_locked(doc, *page, *index, *locked)?,+ Edit::MoveAnnotation { page, index, dx, dy } => pdfcraft_annot::move_annotation(doc, *page, *index, *dx, *dy, &cx.meta())?,+ Edit::ReshapeAnnotation { page, index, points } => pdfcraft_annot::set_points(doc, *page, *index, points, &cx.meta())?,+ Edit::ResizeAnnotation { page, index, rect } => pdfcraft_annot::set_rect(doc, *page, *index, *rect, &cx.meta())?,+ Edit::StyleAnnotation { page, index, color, opacity, width, endings } => {+ pdfcraft_annot::set_style(doc, *page, *index, *color, *opacity, *width, endings.as_deref(), &cx.meta())?;+ }+ Edit::FillAnnotation { page, index, fill } => pdfcraft_annot::set_fill(doc, *page, *index, *fill, &cx.meta())?,+ Edit::FontSizeAnnotation { page, index, size } => pdfcraft_annot::set_font_size(doc, *page, *index, *size, &cx.meta())?,+ Edit::SetAnnotationInfo { page, index, author, subject, icon } => {+ pdfcraft_annot::set_info(doc, *page, *index, author.as_deref(), subject.as_deref(), *icon, &cx.meta())?;+ }+ Edit::SetFieldValue { name, value } => {+ let mut set = |doc: &mut pdfcraft_cos::Document, value: &FieldValue| match cx.js.as_mut() {+ Some(js) => pdfcraft_forms::set_value_with(doc, name, value, js),+ None => pdfcraft_forms::set_value(doc, name, value),+ };+ match set(doc, value) {+ Ok(()) => {}+ // A date the field's format doesn't read may be typed by another of an XFA date+ // field's patterns: it is kept in the first. Only a format refusal is tried+ // again: it comes before any of the field's scripts run, so they run once.+ Err(refused @ pdfcraft_forms::FormError::Format(_)) => match xfa::typed_date(doc, cx.xfa.as_deref(), name, value) {+ Some(typed) => set(doc, &typed)?,+ None => return Err(refused.into()),+ },+ Err(refused) => return Err(refused.into()),+ }+ }+ Edit::ApplyScriptChanges { changes } => match cx.js.as_mut() {+ Some(js) => pdfcraft_forms::apply_script_changes(doc, changes, js)?,+ None => pdfcraft_forms::apply_script_changes(doc, changes, &mut pdfcraft_forms::NoScripts)?,+ },+ Edit::XfaEvent { som, activity } => {+ let tpl = cx.xfa.clone().ok_or_else(|| EditError::Invalid("this is not a laid-out XFA form, or JavaScript is off".into()))?;+ 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 };+ let ran = xfa::on_event(doc, &tpl, som, activity, &mut run);+ cx.xfa_datasets = run.datasets;+ cx.xfa_ran_away |= run.ran_away;+ ran.map_err(EditError::Invalid)?;+ }+ Edit::SetFieldImage { name, image } => {+ let (img, _) = embed_image(doc, name, image)?;+ let px = match &*doc.get(img) {+ pdfcraft_cos::Object::Stream(s) => (s.dict.int(b"Width").unwrap_or(1) as u32, s.dict.int(b"Height").unwrap_or(1) as u32),+ _ => (1, 1),+ };+ // An XFA image field keeps the picture in the data too (as Designer saves it), and a+ // laid-out form shows it from there: so only pictures the layout can show, and only+ // for image fields (a laid-out one carries its SOM path; a static form's field name+ // is its path).+ let is_xfa = pdfcraft_xfa::read_packets(doc).ok().flatten().is_some();+ let image_field = is_xfa+ && pdfcraft_forms::fields(doc).iter().any(|f| f.name == *name && f.button == Some(pdfcraft_forms::af::ButtonAction::ImportIcon));+ if image_field {+ let Some(content_type) = image_content_type(image) else {+ return Err(EditError::Invalid(format!("{name}: an XFA form keeps a PNG, JPEG, GIF, BMP or TIFF picture; choose one of those")));+ };+ pdfcraft_forms::set_button_icon(doc, name, img, px)?;+ let som = pdfcraft_xfa::fields_by_som(doc).into_iter().find(|(_, n)| n == name).map(|(s, _)| s).unwrap_or_else(|| name.clone());+ let path = match cx.xfa.as_deref() {+ Some(tpl) => pdfcraft_xfa::data_path(tpl, &som),+ None => pdfcraft_xfa::som_to_path(&som),+ };+ let r =+ pdfcraft_xfa::write_data_image(doc, &path, content_type, image, cx.xfa_datasets).map_err(|e| EditError::Write(e.to_string()))?;+ if !r.written && r.warnings.is_empty() {+ return Err(EditError::Write(format!("{name}: the picture could not be written into the form's data")));+ }+ cx.xfa_datasets = r.stream.or(cx.xfa_datasets);+ cx.xfa_out.errors.extend(r.warnings);+ xfa_after_data_change(doc, cx, false)?;+ } else {+ pdfcraft_forms::set_button_icon(doc, name, img, px)?;+ }+ }+ Edit::ResetForm { names } => {+ pdfcraft_forms::reset(doc, names.as_deref())?;+ }+ Edit::AddField { page, rect, kind, name } => {+ pdfcraft_forms::add_field(doc, *page, *rect, kind, name.as_deref())?;+ }+ Edit::SetFieldProps { name, props } => {+ pdfcraft_forms::set_props(doc, name, props)?;+ }+ Edit::DuplicateField { name, pages } => {+ if pdfcraft_forms::duplicate_field(doc, name, pages)? == 0 {+ return Err(EditError::Form(pdfcraft_forms::FormError::Invalid(format!("{name} is already on those pages"))));+ }+ }+ Edit::DeleteField { name } => pdfcraft_forms::delete_field(doc, name)?,+ Edit::SetTabOrder { pages, order } => pdfcraft_forms::set_tab_order(doc, pages, *order)?,+ Edit::MoveInTabOrder { name, earlier } => pdfcraft_forms::move_in_tab_order(doc, name, *earlier)?,+ // As after a script edit: the values the new order gives show at once.+ Edit::SetCalculationOrder { names } => {+ pdfcraft_forms::set_calculation_order(doc, names)?;+ match cx.js.as_mut() {+ Some(js) => pdfcraft_forms::recalculate_with(doc, js)?,+ None => pdfcraft_forms::recalculate(doc)?,+ };+ }+ Edit::SetInitialView(v) => pdfcraft_organize::set_initial_view(doc, v)?,+ Edit::AutoTagText => {+ a11y::autotag_text(doc).map_err(|e| EditError::Accessibility(e.to_string()))?;+ }+ Edit::SetAltText { figure, alt } => {+ let r = pdfcraft_cos::ObjRef::new(*figure, doc.generation(*figure));+ a11y::set_alt(doc, r, alt.as_deref()).map_err(|e| EditError::Accessibility(e.to_string()))?;+ }+ Edit::AutoTagFormFields => {+ a11y::tag_form_fields(doc).map_err(EditError::Accessibility)?;+ }+ Edit::SetTagProperty { object, property, value } => {+ a11y::set_tag_property(doc, *object, *property, value.as_deref()).map_err(|e| EditError::Accessibility(e.to_string()))?;+ }+ Edit::MoveTag { object, anchor, placement } => {+ a11y::move_tag(doc, *object, *anchor, *placement).map_err(|e| EditError::Accessibility(e.to_string()))?;+ }+ Edit::EditTextLine { page, line, text } => {+ pdfcraft_edit::replace_line(doc, *page, *line, text)?;+ }+ Edit::SetFieldScript { name, event, script } => {+ pdfcraft_forms::set_field_script(doc, name, event, script.as_deref())?;+ match cx.js.as_mut() {+ Some(js) => pdfcraft_forms::recalculate_with(doc, js)?,+ None => pdfcraft_forms::recalculate(doc)?,+ };+ }+ Edit::ConvertPdfA { level } => {+ pdfcraft_preflight::convert(doc, *level).map_err(|e| EditError::Invalid(e.to_string()))?;+ }+ Edit::RemoveStandardId { standard } => pdfcraft_organize::remove_standard_id(doc, *standard)?,+ Edit::SetDocumentScript { name, script } => pdfcraft_forms::set_document_script(doc, name, script.as_deref())?,+ Edit::AddOcrText { page, words } => {+ pdfcraft_edit::stamp(doc, *page, "OCR", pdfcraft_ocr::text_layer(words))?;+ }+ Edit::EditPageImage { page, index, change } => {+ let img = pdfcraft_edit::page_images(doc, *page)?+ .into_iter()+ .nth(*index)+ .ok_or_else(|| EditError::Edit(pdfcraft_edit::EditError::Invalid(format!("page {} has no image {}", page + 1, index + 1))))?;+ let c = match change {+ ImageEdit::Move(to) => pdfcraft_edit::ImageChange::Transform(pdfcraft_edit::rect_to_rect(img.rect, *to)),+ ImageEdit::Rotate(q) => {+ pdfcraft_edit::ImageChange::Transform(pdfcraft_edit::turn_about_centre(img.visible_rect.unwrap_or(img.rect), *q, false, false))+ }+ ImageEdit::RotateBy(degrees) => {+ let t = pdfcraft_edit::turn_by_degrees(img.visible_rect.unwrap_or(img.rect), *degrees)+ .ok_or_else(|| EditError::Edit(pdfcraft_edit::EditError::Invalid("the rotation angle must be a finite number".into())))?;+ pdfcraft_edit::ImageChange::Transform(t)+ }+ ImageEdit::Flip { horizontal } => pdfcraft_edit::ImageChange::Transform(pdfcraft_edit::turn_about_centre(+ img.visible_rect.unwrap_or(img.rect),+ 0,+ *horizontal,+ !*horizontal,+ )),+ ImageEdit::Replace { name, bytes } => {+ if img.is_form {+ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid(+ "grouped Form artwork cannot be replaced with a bitmap".into(),+ )));+ }+ pdfcraft_edit::ImageChange::Replace(embed_image(doc, name, bytes)?.0)+ }+ ImageEdit::Crop(keep) => pdfcraft_edit::ImageChange::Crop(*keep),+ ImageEdit::Delete => pdfcraft_edit::ImageChange::Delete,+ };+ pdfcraft_edit::change_image(doc, *page, *index, &c)?;+ }+ Edit::MoveObjects { page, objects, offset } => pdfcraft_edit::move_objects(doc, *page, objects, *offset)?,+ Edit::EditTextBlock { page, block, text, style } => {+ pdfcraft_edit::rewrite_block(doc, *page, *block, Some(text), style)?;+ }+ Edit::RegisterTextFont { page, bytes } => {+ pdfcraft_edit::text::register_text_font(doc, *page, bytes)?;+ }+ Edit::MarkDecorative { figure } => {+ let r = pdfcraft_cos::ObjRef::new(*figure, doc.generation(*figure));+ a11y::mark_decorative(doc, r).map_err(|e| EditError::Accessibility(e.to_string()))?;+ }+ Edit::MarkTagArtifact { object } => {+ a11y::mark_tag_artifact(doc, *object).map_err(|e| EditError::Accessibility(e.to_string()))?;+ }+ Edit::AddHeaderFooter { pages, settings, replace } => {+ let date = cx.today;+ pdfcraft_edit::add_header_footer(doc, pages, settings, *replace, &pdfcraft_edit::Context { date })?;+ }+ Edit::AddWatermark { pages, settings, replace, file } => {+ let mut s = settings.clone();+ if let Some(f) = file {+ s.source = Some(mark_source(doc, f)?);+ }+ pdfcraft_edit::add_watermark(doc, pages, &s, *replace)?+ }+ Edit::AddBackground { pages, settings, replace, file } => {+ let mut s = settings.clone();+ if let Some(f) = file {+ s.source = Some(mark_source(doc, f)?);+ }+ pdfcraft_edit::add_background(doc, pages, &s, *replace)?+ }+ Edit::RemoveMarks { kind } => {+ let n = pdfcraft_model::pages(doc).len();+ if pdfcraft_edit::remove_marks(doc, &(0..n).collect::<Vec<_>>(), *kind)? == 0 {+ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("there is nothing to remove".into())));+ }+ }+ Edit::AddText { page, text } => {+ pdfcraft_edit::add_content(doc, *page, &AddedContent::Text(text.clone()))?;+ }+ Edit::AddImage { page, rect, name, bytes } => {+ let (image, natural) = embed_image(doc, name, bytes)?;+ let rect = match rect {+ Some(r) => *r,+ None => {+ let p = pdfcraft_model::pages(doc).swap_remove(*page);+ let (pw, ph) = p.display_size(doc);+ let k = ((pw * 0.8) / natural.0).min((ph * 0.8) / natural.1).min(1.0);+ let (w, h) = (natural.0 * k, natural.1 * k);+ [(pw - w) / 2.0, (ph - h) / 2.0, (pw + w) / 2.0, (ph + h) / 2.0]+ }+ };+ pdfcraft_edit::add_content(doc, *page, &AddedContent::Image(pdfcraft_edit::AddedImage::new(rect, image)))?;+ }+ Edit::UpdateContent { page, index, content } => pdfcraft_edit::update_content(doc, *page, *index, content)?,+ Edit::DeleteContent { page, index } => pdfcraft_edit::delete_content(doc, *page, *index)?,+ Edit::ReplaceImage { page, index, name, bytes } => {+ let item = pdfcraft_edit::list_added(doc).into_iter().filter(|a| a.page == *page).nth(*index);+ let Some(AddedContent::Image(old)) = item.map(|a| a.content) else {+ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("that item is not an image".into())));+ };+ let (image, _) = embed_image(doc, name, bytes)?;+ pdfcraft_edit::update_content(doc, *page, *index, &AddedContent::Image(pdfcraft_edit::AddedImage { image, ..old }))?;+ }+ Edit::PasteContent { page, content, file } => {+ let content = match content {+ AddedContent::Text(_) => content.clone(),+ AddedContent::Image(img) => {+ let Some((name, bytes)) = file else {+ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("a pasted image needs its picture".into())));+ };+ // The same picture in this document (copied here, pasted here before, or an+ // identical file): drawn again from the one image object rather than stored twice.+ let image = if copy_image::is_picture(doc, img.image, bytes) {+ img.image+ } else {+ match copy_image::added_picture(doc, bytes) {+ Some(image) => image,+ None => embed_image(doc, name, bytes)?.0,+ }+ };+ AddedContent::Image(pdfcraft_edit::AddedImage { image, ..img.clone() })+ }+ };+ pdfcraft_edit::add_content(doc, *page, &content)?;+ }+ Edit::ApplyRedactions { pages } => {+ cx.redaction_overlays = pdfcraft_redact::apply(doc, pages.as_deref())?.overlays;+ }+ Edit::ClearRedactions => {+ pdfcraft_redact::clear_marks(doc, None)?;+ }+ Edit::AddLink { page, rect, action, style } => {+ pdfcraft_annot::links::add(doc, *page, *rect, action, style)?;+ }+ Edit::SetLink { page, index, rect, action, style } => pdfcraft_annot::links::set(doc, *page, *index, *rect, action.as_ref(), style.as_ref())?,+ Edit::DeleteLink { page, index } => pdfcraft_annot::links::delete(doc, *page, *index)?,+ Edit::RemoveLinks { pages } => {+ if pdfcraft_annot::links::remove_all(doc, pages.as_deref())? == 0 {+ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("there are no links to remove".into())));+ }+ }+ Edit::AddLinks { links, style } => {+ if pdfcraft_annot::links::add_many(doc, links, style)? == 0 {+ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("no web addresses were found".into())));+ }+ }+ Edit::ImportData { bytes, .. } => {+ // An XFA form takes XFA data files (XDP, datasets, or a data document) as its data;+ // XFDF, FDF, Acrobat's XML and tables go the usual way.+ let text = (pdfcraft_xfa::read_packets(doc).ok().flatten().is_some()).then(|| decode_data_file(bytes)).flatten();+ match text {+ Some(Ok(text)) if is_xfa_data_file(&text) => {+ let expect_root = cx.xfa.as_ref().and_then(|t| t.root.common.name.clone());+ let r = pdfcraft_xfa::import_data(doc, &text, expect_root.as_deref(), cx.xfa_datasets)+ .map_err(|e| EditError::Write(e.to_string()))?;+ cx.xfa_datasets = r.stream.or(cx.xfa_datasets);+ cx.xfa_out.errors.extend(r.warnings);+ cx.xfa_out.console.push(format!("Imported XFA data: {} node(s)", r.nodes));+ xfa_after_data_change(doc, cx, true)?;+ }+ Some(Err(why)) => return Err(EditError::Invalid(why)),+ _ => {+ pdfcraft_xfdf::import(doc, bytes)?;+ }+ }+ }+ Edit::RemoveHidden { which } => {+ pdfcraft_redact::sanitize::remove_hidden(doc, which)?;+ }+ Edit::Sanitize => {+ pdfcraft_redact::sanitize::sanitize(doc)?;+ }+ Edit::Flatten { comments, fields } => {+ // An XFA form's fields baked into the pages: the XFA goes too, or Adobe's viewers+ // would lay the form out again from its template over the baked pages. A dynamic+ // form that was never laid out keeps its XFA: without it only placeholders remain.+ let shape = (*fields).then(|| pdfcraft_xfa::xfa_shape(doc)).flatten();+ let n = pdfcraft_model::pages(doc).len();+ pdfcraft_edit::flatten(doc, &(0..n).collect::<Vec<_>>(), *comments, *fields)?;+ match shape {+ Some(shape) if shape.strippable() => strip_xfa(doc, cx)?,+ Some(_) => cx.xfa_removed.push("The XFA was kept: this dynamic form was not laid out, so its fields were not baked in".into()),+ None => {}+ }+ }+ Edit::XfaToStatic => {+ let Some(shape) = pdfcraft_xfa::xfa_shape(doc) else {+ return Err(EditError::Invalid("this document is not an XFA form".into()));+ };+ if !shape.strippable() {+ return Err(EditError::Invalid("this dynamic XFA form was not laid out, so there is no static form to keep".into()));+ }+ strip_xfa(doc, cx)?;+ }+ Edit::FlattenFillSign => {+ let n = pdfcraft_model::pages(doc).len();+ pdfcraft_edit::flatten_fill_sign(doc, &(0..n).collect::<Vec<_>>())?;+ }+ Edit::Protect(p) => {+ p.validate()?;+ let seed = cx.entropy();+ // Without a permissions password nothing is restricted, so the owner password is a+ // random one nobody needs.+ let random_owner: String = cx.entropy().iter().map(|b| format!("{b:02x}")).collect();+ let params = pdfcraft_cos::NewEncryption {+ algorithm: p.algorithm,+ user_password: p.open_password.as_deref().unwrap_or(""),+ owner_password: p.permissions_password.as_deref().unwrap_or(&random_owner),+ permissions: p.permission_bits(),+ encrypt_metadata: p.encrypt_metadata,+ seed,+ };+ doc.set_encryption(¶ms).map_err(|e| EditError::Protection(e.to_string()))?;+ }+ Edit::RemoveProtection => {+ if doc.output_handler().is_none() {+ return Err(EditError::Protection("the document isn't protected".into()));+ }+ doc.remove_encryption();+ }+ Edit::Batch { edits, .. } => {+ for e in edits {+ run_edit(doc, e, cx)?;+ }+ }+ }+ Ok(())+ }diff --cc crates/engine/src/lib.rsindex af4ba5913,889b83936..024058ecc--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@@ -23,25 -25,44 +25,45 @@@ mod commentspub mod compare;mod copy_image;pub mod dates;+ mod document;+ mod edit;+ mod error;pub mod export;pub mod field_table;+ mod fill_sign;+ mod history;pub mod js;+ mod layers;pub mod links;pub mod ocr;+ mod open;pub mod optimizer;+ mod page_filter;+ mod pictures;pub mod print_raster;pub mod printcheck;+ mod protection;mod scan_colours;mod scan_fields;+ mod session;pub mod signature_image;pub mod signature_scan;+ mod sources;mod stamp_preview;+ #[cfg(test)]+ mod test_hooks;pub mod text_fonts;mod text_preview;+pub mod text_style_bookmarks;pub mod word_count;pub mod xfa;+ mod xfa_form;++ use std::sync::Arc;+ pub use links::{+ MAX_REMOTE_DOCUMENT_BYTES, RemoteDocumentPathError, read_remote_document, remote_document_path_is_absolute, resolve_remote_document_path,+ };pub use signature_image::{ImageSignaturePreview, SignatureImage};pub use signature_scan::{PhotoRect, ScanError, SignaturePhoto, Turn};pub use stamp_preview::StampPreview;diff --cc crates/ui-egui/src/app.rsindex 000000000,8925a0dca..b824e73b8mode 000000,100644..100644--- a/crates/ui-egui/src/app.rs+++ b/crates/ui-egui/src/app.rs@@@ -1,0 -1,610 +1,611 @@@+ use super::hooks::OsEvent;+ use super::state::{+ Dialog, DocumentCopyJob, GridFile, LeftPanel, LinkOrigin, Mode, NumberDraft, PasswordPrompt, PendingLink, PropsTab, QuickTool, RecentFile,+ RightPanel, UnlockPrompt,+ };+ #[cfg(not(target_arch = "wasm32"))]+ use super::state::{OpenOutcome, OpenRequest, PendingRemoteLink};+ use super::*;++ mod clipboard;+ mod commands;+ mod control;+ mod files;+ mod frame;+ mod input;+ mod keys;+ mod links;+ mod prefs;+ mod window;++ pub(crate) use clipboard::{copy_refused, print_refused};+ #[cfg(not(target_arch = "wasm32"))]+ pub(crate) use files::same_file;+ use frame::migrate_panel_state;+ pub(crate) use prefs::{MAX_AUTHOR_CHARS, date_text_for_pdf};++ impl Default for PdfCraftApp {+ fn default() -> Self {+ Self::new()+ }+ }++ impl PdfCraftApp {+ /// Construct an application with the default session, panels, theme and control state.+ pub fn new() -> Self {+ Self {+ session: Session::new(),+ views: Vec::new(),+ closed_tabs: Vec::new(),+ active: None,+ mode: Mode::AllTools,+ default_mode: Mode::AllTools,+ view_defaults: Default::default(),+ units: Default::default(),+ date_format_draft: None,+ mode_override: None,+ left: LeftPanel::AllTools,+ side_panels: Default::default(),+ left_open: true,+ right: None,+ last_right: RightPanel::Comments,+ right_before_read: None,+ comments_panel_closed: false,+ right_panel_closed: false,+ quick_tool: QuickTool::Select,+ space_hand: None,+ full_screen_tool: None,+ comment_prefs: Default::default(),+ theme: ThemeKind::Light,+ // A fresh install follows the desktop's appearance (#1248); saved settings override.+ theme_preference: ThemePreference::System,+ reading_colors: Default::default(),+ #[cfg(target_os = "linux")]+ desktop_theme: None,+ #[cfg(target_os = "linux")]+ desktop_theme_enabled: false,+ scroll_speed: scroll_speed::ScrollSpeed::default(),+ animation_effects: motion::AnimationEffects::default(),+ motion: motion::Motion::default(),+ language: i18n::AUTO.to_string(),+ ui_scale: None,+ system_text_scale: 1.0,+ ui_scale_applied: None,+ flatten_fill_sign_on_save: false,+ fill_text_size: fill_sign::TEXT_SIZE,+ dialog: None,+ updates: updates::Updates::default(),+ printer_source: None,+ options_source: None,+ print_tasks: print_ui::PrintTasks::default(),+ palette_open: false,+ palette_query: String::new(),+ all_tools_expanded: false,+ all_tools_full: false,+ all_tools_query: String::new(),+ all_tools_tab: (None, false),+ recent: Vec::new(),+ reopen_last_session: false,+ restore_last_view: true,+ last_views: Vec::new(),+ last_session: Default::default(),+ quit_session: None,+ reload_changed_files: true,+ show_secured_notice: true,+ always_default_view: false,+ #[cfg(not(target_arch = "wasm32"))]+ watch: Default::default(),+ #[cfg(not(target_arch = "wasm32"))]+ open_worker: None,+ #[cfg(not(target_arch = "wasm32"))]+ pending_opens: Vec::new(),+ #[cfg(not(target_arch = "wasm32"))]+ next_open_token: 0,+ #[cfg(all(test, not(target_arch = "wasm32")))]+ open_prepare_gate: None,+ pinned: Default::default(),+ toast: None,+ integrated_titlebar: false,+ window_controls: None,+ system_title_bar: false,+ app_frame_shown: None,+ password_prompt: None,+ document_copy: None,+ unlock_prompt: None,+ full_screen: false,+ inbox: Default::default(),+ startup_inbox: Default::default(),+ startup_superseded: false,+ failed_inbox: Default::default(),+ unsaved_flag: Default::default(),+ os_events: None,+ host_save: None,+ host_dirty: None,+ close_request: None,+ save_prompt_button: Default::default(),+ save_prompt_seen: false,+ save_prompt_attention: false,+ #[cfg(not(target_arch = "wasm32"))]+ pending_overwrite: None,+ save_override: None,+ props_draft: None,+ view_draft: None,+ custom_draft: None,+ requests: Default::default(),+ #[cfg(not(target_arch = "wasm32"))]+ pickers: Default::default(),+ #[cfg(not(target_arch = "wasm32"))]+ pick_override: None,+ export_dir_override: None,+ split_draft: SplitDraft::default(),+ extract_draft: ExtractDraft::default(),+ rotate_draft: RotateDraft::default(),+ summary_sort: Default::default(),+ sign_draft: None,+ digital_ids: Vec::new(),+ sig_expanded: Vec::new(),+ a11y_options: a11y_ui::A11yOptions::default(),+ ocr_draft: ocr_ui::OcrDraft::default(),+ ocr_run: None,+ ocr_batch: None,+ run_inline: false,+ custom_actions: Vec::new(),+ wizard: Default::default(),+ action_run: None,+ action_files_override: None,+ pdfa: Default::default(),+ compare_old: None,+ compare: None,+ js_console: Default::default(),+ doc_js: Default::default(),+ a11y: a11y_ui::A11yState::default(),+ tags_state: Default::default(),+ a11y_skipped: Default::default(),+ alt_draft: Default::default(),+ os_key_store_ids: false,+ cert_viewer: None,+ space_audit: Vec::new(),+ space_audit_of: None,+ combine_draft: Vec::new(),+ combine_conflicts: Default::default(),+ combine_tab: Default::default(),+ combine_columns: Default::default(),+ combine_view: Default::default(),+ combine_zoom: 1.0,+ organize_zoom: 1.0,+ combine_thumbs: Default::default(),+ image_import: None,+ custom_stamps: Vec::new(),+ stamp_draft: Default::default(),+ optimize_draft: OptimizeDraft::default(),+ optimize_run: None,+ progress_notice: None,+ page_clipboard: None,+ grid_drop: None,+ last_snapshot: None,+ last_copied_image: None,+ last_copied_file: None,+ system_clipboard: true,+ clipboard_override: None,+ v_pressed: false,+ attach_override: None,+ duplicate_draft: None,+ field_table_draft: None,+ form_preview: false,+ window_title: String::new(),+ recovery: None,+ recoverable: Vec::new(),+ recovery_keys: Default::default(),+ last_autosave: None,+ allow_quit: false,+ deferred_commands: Vec::new(),+ native_menu: None,+ menu_input: Vec::new(),+ dialog_seen: None,+ dialog_epoch: 0,+ ctx: None,+ #[cfg(not(target_arch = "wasm32"))]+ window_state: Default::default(),+ styled: false,+ fonts_ready: false,+ fonts_cjk: theme::CjkPreference::Default,+ control: None,+ bookmark_rename: None,+ last_opened_url: None,+ community_card_closed: false,+ pending_link: None,+ pending_full_screen: None,+ pending_remote_link: None,+ protect_draft: Default::default(),++ text_style_draft: Default::default(),+ boxes_draft: Default::default(),+ marks_draft: Default::default(),+ export_draft: Default::default(),+ export_status: None,+ signature: None,+ initials: None,+ signature_draft: Default::default(),+ signature_preview: None,+ signature_photo: None,+ saved_signature_previews: [None, None],+ sign_graphic: sign_ui::SignGraphic::Name,+ sign_graphic_preview: None,+ #[cfg(target_arch = "wasm32")]+ signature_images: Default::default(),+ comment_props: None,+ field_props: None,+ bulk_field_props: None,+ redact_prefs: RedactPrefs::default(),+ redact_defaults: RedactPrefs::default(),+ redact_before: None,+ redact_pages_draft: RedactPagesDraft::default(),+ redact_search: RedactSearchDraft::default(),+ hidden_draft: HiddenDraft::default(),+ print_draft: PrintDraft::default(),+ link_draft: None,+ text_style: content_ui::default_style(),+ replace_draft: None,+ number_draft: NumberDraft { from: 1, to: 1, style: pdfcraft_engine::LabelStyle::Decimal, prefix: String::new(), start: 1 },+ word_count_draft: word_count_ui::Draft::default(),+ }+ }++ /// Fields are being edited (Prepare a form or its Calculation order is open, or a field tool+ /// is picked), unless the form is being previewed.+ pub fn is_preparing(&self) -> bool {+ ((self.left_open && matches!(self.left, LeftPanel::Tool("form") | LeftPanel::CalculationOrder))+ || matches!(self.quick_tool, QuickTool::Field(_)))+ && !self.form_preview+ }++ /// A number that changes whenever the open dialog changes (opened, closed or replaced by+ /// another), checked every frame. A picker started from a dialog's Browse… button answers+ /// only into the same showing of that dialog.+ pub(crate) fn dialog_epoch(&mut self) -> u64 {+ if self.dialog != self.dialog_seen {+ self.dialog_seen = self.dialog;+ self.dialog_epoch = self.dialog_epoch.wrapping_add(1);+ }+ self.dialog_epoch+ }++ pub fn active_ids(&self) -> Option<(usize, DocId)> {+ self.active.and_then(|i| self.views.get(i).map(|v| (i, v.id)))+ }++ /// A dialog or prompt is open over the window: the keyboard is its own, and nothing may act+ /// on the document underneath it.+ pub(crate) fn modal_open(&self) -> bool {+ self.dialog.is_some()+ || self.close_request.is_some()+ || self.password_prompt.is_some()+ || self.unlock_prompt.is_some()+ || self.pending_link.is_some()+ || self.pending_remote_link.is_some()+ || self.updates.open+ }++ pub fn notify(&mut self, msg: impl Into<String>) {+ self.toast = Some((msg.into(), 0.0));+ }++ /// Notify with a static message in the UI language.+ pub fn notify_tr(&mut self, text: &str) {+ self.notify(tl!(text).to_string());+ }++ /// Notify with an error's own text. Engine and OS messages are not translated: matching their+ /// English wording would break silently whenever it changes.+ pub fn notify_error(&mut self, error: impl std::fmt::Display) {+ self.notify(error.to_string());+ }++ /// Notify with a `{name}`-style template in the UI language (placeholders filled once).+ pub fn notify_fmt(&mut self, template: &str, args: &[(&str, &str)]) {+ self.notify(i18n::fmt(tl!(template), args));+ }++ /// `true` while any open document still waits for page renders (used by headless capture).+ pub fn render_pending(&self) -> bool {+ self.views.iter().any(|v| v.render_pending())+ }+ }++ impl eframe::App for PdfCraftApp {+ /// While files are dragged over the window the system sends no pointer moves, so egui+ /// would keep the place the pointer entered at: tell it where the pointer really is, so the+ /// page grid can show (and use) the gap under it.+ fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {+ // The button's release a window move or resize kept from egui.+ window_controls::release_after_desktop_grab(ctx, raw);+ self.prepare_raw_input(ctx, raw);+ if raw.hovered_files.is_empty() && raw.dropped_files.is_empty() {+ return;+ }+ if let Some(pos) = drag_pointer::in_window(ctx) {+ raw.events.push(egui::Event::PointerMoved(pos));+ }+ ctx.request_repaint();+ }++ fn save(&mut self, storage: &mut dyn eframe::Storage) {+ // eframe has just stored the window as it is now: not while it is minimized.+ #[cfg(not(target_arch = "wasm32"))]+ {+ let minimized = self.ctx.as_ref().is_some_and(|c| c.input(|i| i.viewport().minimized == Some(true)));+ self.window_state.keep(storage, minimized);+ }+ storage.set_string("pdfcraft", self.persist());+ }++ /// Each frame's work before drawing: opens, operating-system and control-channel requests,+ /// the quit guard, shortcuts, and the background jobs' results.+ fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {+ self.ctx = Some(ctx.clone());+ #[cfg(not(target_arch = "wasm32"))]+ self.window_state.repair(ctx);+ self.dialog_epoch();+ // Notices raised outside `ui` (opened files, OS events, the control channel) translate too.+ let lang = i18n::Lang::from_pref(&self.language);+ i18n::set_current(lang);+ #[cfg(not(target_arch = "wasm32"))]+ {+ if let Some(worker) = &self.open_worker {+ worker.set_context(ctx);+ }+ self.poll_pending_opens();+ }+ // Chinese wants its own faces before the Japanese ones (one baseline per line).+ let cjk = theme::CjkPreference::for_language(lang.code());+ if !self.styled {+ egui_extras::install_image_loaders(ctx);+ theme::install_fonts_for(ctx, cjk);+ self.fonts_cjk = cjk;+ theme::apply(ctx, self.theme);+ self.styled = true;+ } else {+ self.fonts_ready = true;+ if cjk != self.fonts_cjk {+ // Same family names as before, so named fonts stay valid while the new set loads.+ theme::install_fonts_for(ctx, cjk);+ self.fonts_cjk = cjk;+ }+ }+ self.sync_theme(ctx);+ let native = ctx.native_pixels_per_point().unwrap_or(1.0);+ ui_scale::sync(ctx, ui_scale::zoom(self.ui_scale, self.system_text_scale, native), &mut self.ui_scale_applied);+ // Remember user work even if its tab is subsequently closed or Home is selected.+ self.startup_superseded |= !self.views.is_empty() || self.combine_showing() || self.dialog.is_some() || self.password_prompt.is_some();+ // Also done in `raw_input_hook`, before input; here for hosts that don't call the hook.+ self.scroll_speed.set_line_speed(ctx);+ // Motion reads this frame's wheel input, so it begins in `ui`, in a known UI phase:+ // `logic` also runs alone while hidden, where the input events and time are stale.+ // Before taking this frame's drop: the grid must be drawn once with the pointer where+ // the files were let go before the gap is read.+ self.finish_grid_drop(ctx);+ // Showing a document hides the Combine files tab.+ if self.active.is_some() {+ self.combine_tab.focused = false;+ }+ #[cfg(target_arch = "wasm32")]+ self.process_signature_images();+ let dropped = ctx.input(|i| i.raw.dropped_files.clone());+ #[cfg(not(target_arch = "wasm32"))]+ let dropped = self.drop_on_signature_pad(dropped);+ #[cfg(not(target_arch = "wasm32"))]+ let dropped = self.drop_on_grid(dropped, ctx);+ for f in dropped {+ // Files dropped on the Combine files tab join its list instead of opening.+ if self.combine_showing() {+ self.drop_into_combine(f, ctx);+ } else {+ self.open_dropped(f, ctx);+ }+ }+ let arrived: Vec<(String, Vec<u8>)> = self.inbox.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default();+ for (name, bytes) in arrived {+ if let Err(e) = self.open_bytes(&name, None, bytes) {+ self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &e.to_string())]);+ }+ }+ // Don't replace a pending prompt or import. A startup file may need its own password+ // prompt, so its bytes stay queued until the current interaction finishes.+ #[cfg(not(target_arch = "wasm32"))]+ let opening = !self.pending_opens.is_empty();+ #[cfg(target_arch = "wasm32")]+ let opening = false;+ if !opening+ && self.password_prompt.is_none()+ && self.image_import.is_none()+ && self.dialog.is_none()+ && self.close_request.is_none()+ && self.pending_link.is_none()+ && self.pending_remote_link.is_none()+ {+ let startup = self.startup_inbox.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default();+ for (name, bytes) in startup {+ let activate = !self.startup_superseded;+ if let Err(e) = self.open_bytes_with_focus(&name, None, bytes, activate) {+ self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &e)]);+ }+ }+ }+ let failed: Vec<(String, String)> = self.failed_inbox.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default();+ for (name, e) in failed {+ self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &e)]);+ }+ let os_events = self.os_events.as_mut().map(|poll| poll()).unwrap_or_default();+ for e in os_events {+ match e {+ #[cfg(not(target_arch = "wasm32"))]+ OsEvent::Open(paths) => {+ paths.iter().for_each(|p| {+ self.open_path(p);+ });+ // Files handed to the running app (Finder, or another launch): bring its+ // window to the front, also when minimized or full screen on another Space.+ ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));+ ctx.send_viewport_cmd(egui::ViewportCommand::Focus);+ }+ #[cfg(target_arch = "wasm32")]+ OsEvent::Open(_) => {}+ // Like closing the window: `guard_quit` asks about unsaved changes.+ OsEvent::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close),+ }+ }+ if let Some((_, id)) = self.active_ids() {+ let out = self.session.take_js_output(id);+ self.handle_js(id, out);+ }+ if let Some(mut control) = self.control.take() {+ control.tick(ctx, self);+ self.control = Some(control);+ }+ self.guard_quit(ctx);+ // macOS: quit through `terminate:` instead of dropping the window (Touch Bar crash, #1136).+ #[cfg(target_os = "macos")]+ craft_quit::on_close_request(ctx);+ self.autosave_tick(ctx, web_time::Instant::now());+ // Reload documents whose files a build rewrote (#431).+ #[cfg(not(target_arch = "wasm32"))]+ self.watch_files();+ if self.host_dirty.is_some() {+ let dirty = self.first_dirty().is_some();+ if let Some(report) = self.host_dirty.as_mut() {+ report(dirty);+ }+ }+ self.poll_updates();+ self.poll_print();+ // Shortcuts deferred last frame: the text field has taken that frame's typing since.+ let deferred = std::mem::take(&mut self.deferred_commands);+ self.native_menu_clicks(ctx);+ // The keys a menu click stands for (⌘C, Delete…), before anything reads this frame's keys.+ if !self.menu_input.is_empty() {+ let events = std::mem::take(&mut self.menu_input);+ ctx.input_mut(|i| i.events.extend(events));+ }+ self.shortcuts(ctx);+ // Scrolling and group-drag previews are transient: never resume after changing tabs,+ // opening a modal/palette, or returning to a window that lost focus.+ let blocked = self.modal_open() || self.palette_open || !ctx.input(|i| i.focused);+ for (index, view) in self.views.iter_mut().enumerate() {+ view.objects.set_input_blocked(blocked || self.active != Some(index));+ if blocked || self.active != Some(index) {+ view.auto_scroll.cancel();+ }+ }+ // A field that refused its value this frame keeps the shortcut from saving or printing+ // behind the user's back; so does a save prompt opened since.+ if self.process_pending_edits() && self.close_request.is_none() {+ for (id, doc) in deferred {+ // Only in the document the shortcut was pressed in.+ if self.active_ids().map(|(_, active)| active) == doc {+ self.execute(id);+ }+ }+ }+ self.poll_export();+ self.auto_ocr_scanned_page();+ self.poll_ocr();+ self.poll_optimize();+ self.poll_action();+ self.process_file_requests();+ #[cfg(not(target_arch = "wasm32"))]+ self.process_picked();+ // Last, after everything that can open or answer the "save changes?" question.+ self.attend_save_prompt(ctx);+ self.sync_native_menu(ctx);+ }++ fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {+ let ctx = ui.ctx().clone();+ i18n::set_current(i18n::Lang::from_pref(&self.language));+ // A language change switches stock chrome between LTR and RTL before anything is drawn.+ theme::sync_direction(&ctx);+ // Fonts registered via set_fonts only take effect next frame; named families would panic now.+ if !self.fonts_ready {+ ctx.request_repaint();+ return;+ }+ // Before any widget reads this frame's wheel input or draws.+ self.motion.begin_pass(&ctx, self.animation_effects);+ // One-time 0.36 -> 0.37 panel persistence migration, before any panel stores or reads state.+ migrate_panel_state(ui);+ for view in &mut self.views {+ view.begin_render_frame();+ }+ // The window shows the active document's name (or title, if it asks for that).+ let title = self+ .active+ .and_then(|i| crate::canvas::tab_label(self, i))+ .or_else(|| self.combine_showing().then(|| tl!("Combine files").to_owned()))+ .map_or_else(|| "PdfCraft".to_owned(), |name| format!("{name} — PdfCraft"));+ if title != self.window_title {+ ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.clone()));+ self.window_title = title;+ }+ // The accessible window takes the same name, so a screen reader (AT-SPI on Linux, UIA on+ // Windows) can tell it apart (#4614). egui builds the root node afresh every pass.+ ctx.accesskit_node_builder(egui::accesskit_root_id(), |root| root.set_label(self.window_title.as_str()));+ if self.full_screen && self.active.is_some() {+ // Full screen: the page on black, nothing else, as Acrobat's Full Screen Mode (Esc+ // or ⌘L to leave).+ egui::CentralPanel::default().frame(egui::Frame::NONE.fill(egui::Color32::BLACK)).show(ui, |ui| {+ if let Some(i) = self.active {+ match compare_ui::side_by_side(self, i) {+ Some((old, new)) => compare_ui::compare_area(self, old, new, ui),+ None => canvas::document_area(self, i, ui),+ }+ }+ });+ dialogs::show(self, &ctx);+ // Notices too: a refused field value or a failed save must be seen in full screen.+ self.show_progress(&ctx);+ widgets::toast(self, &ctx);+ self.finish_render_frame(&ctx);+ if let Some(mut control) = self.control.take() {+ control.finish_frame(&ctx, self);+ self.control = Some(control);+ }+ return;+ }+ self.sync_window_frame(&ctx);+ if self.draws_window_frame() {+ window_controls::resize_edges(&ctx);+ }+ chrome::tab_strip(self, ui);+ chrome::mode_bar(self, ui);+ // Whichever way another tab came to the front, it shows instead of the expanded view.+ if self.all_tools_full && self.all_tools_tab != self.shown_tab() {+ self.all_tools_full = false;+ }+ side_panels::show(self, ui);+ let t = theme::Tokens::get(&ctx);+ egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.pasteboard)).show(ui, |ui| {+ if self.mode == Mode::AllTools && self.all_tools_full {+ all_tools_ui::show(self, ui);+ } else {+ match self.active {+ None if self.combine_showing() => combine_ui::page(self, ui),+ None => home::show(self, ui),+ Some(index) => match compare_ui::side_by_side(self, index) {+ Some((old, new)) => compare_ui::compare_area(self, old, new, ui),+ None => canvas::document_area(self, index, ui),+ },+ }+ }+ });+ self.process_pending_edits();+ palette::show(self, &ctx);+ dialogs::show(self, &ctx);+ self.show_progress(&ctx);+ widgets::toast(self, &ctx);+ self.finish_render_frame(&ctx);+ // Screenshots are issued only after a settled pass that really drew the window.+ if let Some(mut control) = self.control.take() {+ control.finish_frame(&ctx, self);+ self.control = Some(control);+ }+ }+ }diff --cc crates/ui-egui/src/dialogs.rsindex f4100f2f0,d0e9482d0..c90d91773--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@@ -7,6 -7,20 +7,21 @@@ use pdfcraft_engine::Edituse crate::{CloseRequest, Dialog, PdfCraftApp, PropsTab, panels::human_size, widgets};+ pub(super) mod appearance;++pub mod bookmark_styles_ui;+ pub(super) mod comment_props;+ pub(super) mod credits;+ pub(super) mod marks_ui;+ pub(super) mod pageboxes;+ pub(super) mod palette;+ mod prompts;+ pub(super) mod protect;+ pub(super) mod standards_ui;+ pub(super) mod word_count_ui;++ pub(crate) use prompts::{PromptButton, save_prompt_key};+ use prompts::{full_screen_prompt, link_prompt, password, remote_link_prompt, save_prompt, unlock};+const INFO_KEYS: [&str; 4] = ["Title", "Author", "Subject", "Keywords"];pub fn show(app: &mut PdfCraftApp, ctx: &egui::Context) {diff --cc crates/ui-egui/src/dialogs/bookmark_styles_ui.rsindex 890a5f2ef,000000000..890a5f2efmode 100644,000000..100644--- a/crates/ui-egui/src/dialogs/bookmark_styles_ui.rs+++ b/crates/ui-egui/src/dialogs/bookmark_styles_ui.rsdiff --cc crates/ui-egui/src/lib.rsindex ec2b596ed,65bc7e4b1..0ca6dd4a6--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -166,113 -60,109 +60,110 @@@ pub use files::{ExtractDraft, FilePurpopub use recovery::{AUTOSAVE_SECS, RecoveryMeta, RecoveryStore};use theme::{ThemeKind, ThemePreference};- /// Top-level workspace modes (Acrobat's mode bar).- #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]- #[serde(rename_all = "lowercase")]- pub enum Mode {- #[serde(rename = "all")]- AllTools,- Read,- Edit,- Convert,- Sign,- }-- impl Mode {- fn parse(value: &str) -> Option<Self> {- match value {- "all" => Some(Self::AllTools),- "read" => Some(Self::Read),- "edit" => Some(Self::Edit),- "convert" => Some(Self::Convert),- "sign" => Some(Self::Sign),- _ => None,- }- }- }-- /// What the left panel shows.- #[derive(Clone, Copy, Debug, PartialEq, Eq)]- pub enum LeftPanel {- AllTools,- Tool(&'static str),- /// Prepare a form ▸ Calculation order, a page of its own; Back returns to Prepare a form.- CalculationOrder,- }-- /// Right-hand panels, opened from the rail.- #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]- pub enum RightPanel {- Comments,- Bookmarks,- Pages,- Fields,- Layers,- Attachments,- Signatures,- /// Accessibility Checker results.- Accessibility,- /// Reachable PDF structure tags and their properties.- Tags,- /// Advanced Search results.- Search,- /// Compare files: the differences.- Compare,- }-- /// Quick-action bar tools (the vertical floating strip).- #[derive(Clone, Copy, Debug, PartialEq, Eq)]- pub enum QuickTool {- Select,- Hand,- /// A commenting tool (Add comments).- Comment(comments::CommentTool),- Measure(measure_ui::Tool),- /// Crop pages by dragging a rectangle.- Crop,- /// Scan & OCR ▸ Enhance ▸ Camera image: drag four corners, then Enhance page.- EnhanceCamera,- /// A Fill & Sign tool.- Fill(fill_sign::FillTool),- /// A Prepare a form field tool.- Field(prepare::FieldTool),- /// Redact text and images (drag across text or draw a box).- Redact,- /// Edit a PDF ▸ Add content ▸ Text.- AddText,- /// Edit a PDF ▸ Edit text: click a line of existing text to edit it.- EditText,- /// Add a stamp: click to place this stamp.- Stamp(pdfcraft_engine::StampKind),- /// A custom stamp from the library (its index).- CustomStamp(usize),- /// Edit a PDF ▸ Link: draw link areas, select and edit links.- Link,- /// Use a certificate ▸ Digitally sign / Certify (visible): drag the signature's rectangle.- SignArea {- certify: bool,- },- /// View ▸ Zoom ▸ Marquee Zoom.- MarqueeZoom,- /// Edit ▸ Take a Snapshot.- Snapshot,- /// Edit ▸ Column Select: drag a rectangle to select only the text inside it (#740). The- /// Select tool does the same while Alt/Option is held at the start of a drag.- ColumnSelect,- }-- /// A file dropped on a page grid: its name, and its bytes or, for a file on disk, the path they are- /// read from when the file's turn to be inserted comes (so a long drop holds one file at a time).- type GridFile = (String, Result<Vec<u8>, std::path::PathBuf>);+ mod app;+ mod hooks;+ mod persist;+ mod platform;+ mod state;+ mod tools;+ mod workflows;- /// Read a file dropped on a page grid (see [`GridFile`]).- fn read_grid_file((name, source): GridFile) -> Result<(String, Vec<u8>), (String, String)> {- let bytes = match source {- Ok(bytes) => bytes,- Err(path) => std::fs::read(&path).map_err(|e| (name.clone(), e.to_string()))?,- };- Ok((name, bytes))- }+ #[cfg(not(target_arch = "wasm32"))]+ pub(crate) use app::same_file;+ pub(crate) use app::{MAX_AUTHOR_CHARS, copy_refused, date_text_for_pdf, print_refused};+ use canvas::autoscroll;+ use canvas::crop;+ use canvas::fling;+ use canvas::image_pick;+ use canvas::page_pointer;+ pub use canvas::scroll_speed;+ use canvas::signature_drag;+ use canvas::wheel_boost;+ use canvas::wheel_pager;+ use canvas::zoom_snap;+ use dialogs::appearance;++pub use dialogs::bookmark_styles_ui;+ use dialogs::comment_props;+ use dialogs::credits;+ use dialogs::marks_ui;+ use dialogs::pageboxes;+ use dialogs::palette;+ use dialogs::protect;+ use dialogs::standards_ui;+ use dialogs::word_count_ui;+ pub use home::folders_ui;+ pub use hooks::{FailedInbox, HostDirtyFn, HostSaveFn, Inbox, OsEvent, OsEventsFn};+ use menus::tab_context;+ use panels::all_tools_ui;+ use panels::comments_panel;+ use panels::format_text_ui;+ use panels::organize_panel;+ use panels::page_selection_ui;+ use panels::search_ui;+ pub use panels::side_panels;+ pub use persist::last_session;+ pub use persist::last_view;+ use persist::recovery;+ pub use persist::units;+ #[cfg(not(target_arch = "wasm32"))]+ pub use persist::window_state;+ use platform::drag_pointer;+ #[cfg(not(target_arch = "wasm32"))]+ pub use platform::file_watch;+ #[cfg(target_os = "macos")]+ use platform::macos_association;+ pub use platform::motion;+ #[cfg(not(target_arch = "wasm32"))]+ use platform::open_worker;+ #[cfg(not(target_arch = "wasm32"))]+ use platform::pickers;+ pub use platform::portable;+ #[cfg(not(target_arch = "wasm32"))]+ use platform::system_fonts;+ pub use platform::ui_scale;+ pub use platform::updates;+ pub use platform::window_controls;+ #[cfg(test)]+ use state::CopyPage;+ #[cfg(not(target_arch = "wasm32"))]+ use state::OpenRequest;+ pub use state::{+ CustomDraft, Dialog, DuplicateDraft, LeftPanel, LinkOrigin, Mode, NumberDraft, OpenOutcome, PageClip, PasswordPrompt, PendingLink,+ PendingRemoteLink, PropsTab, QuickTool, RecentFile, RightPanel, UnlockPrompt,+ };+ use state::{DocumentCopyJob, GridFile};+ pub use tools::bulk_fields;+ use tools::calc_order_ui;+ use tools::camera_ui;+ pub use tools::comments;+ use tools::content_ui;+ use tools::edit_text_ui;+ pub use tools::field_table_ui;+ pub use tools::fill_sign;+ pub use tools::forms_ui;+ use tools::link_ui;+ use tools::measure_ui;+ use tools::object_ui;+ pub use tools::prepare;+ use tools::redact_ui;+ use tools::sign_ui;+ use tools::stamps_ui;+ use tools::tags_ui;+ use widgets::icon_data;+ pub use widgets::icons;+ use workflows::a11y_ui;+ use workflows::actions_ui;+ use workflows::combine_grid;+ use workflows::combine_ui;+ use workflows::compare_ui;+ use workflows::create_ui;+ use workflows::export_ui;+ use workflows::files;+ use workflows::js_ui;+ use workflows::ocr_ui;+ use workflows::optimize_ui;+ use workflows::print_ui;+ use workflows::web_print;/// Files dropped on a document's page grid or its Pages panel.struct GridDrop {diff --cc crates/ui-egui/src/menus.rsindex 000000000,d7c8bef1c..a42e70ab3mode 000000,100644..100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@@ -1,0 -1,793 +1,794 @@@+ //! The menus: one definition ([`PdfCraftApp::menu_bar`]) for the native macOS menu bar and the+ //! in-window bar on Windows, Linux and the web, laid out for each platform by craft-menu.+ //!+ //! Items run registry commands (`pdfcraft_engine::commands`) by id, with the registry's label and+ //! shortcut, so a menu click and its shortcut run the same command. A few items have menu-only+ //! ids: the zoom keys the document view handles itself, the side panel choices, the clipboard+ //! keys, the recent files and the open documents. [`PdfCraftApp::run_menu_command`] runs every+ //! one of them, once per click, whichever bar it came from.++ use craft_keymap::{Key, Mods};+ use craft_menu::{+ Builtin, Chord, CommandRef, Document, Gate, Item, ItemRole, ItemState, Labeled, LayoutOptions, Menu, MenuBar, MenuRole, Node, Target,+ };+ use pdfcraft_engine::catalog::{Availability, TOOL_GROUPS};+ use pdfcraft_engine::commands::{self, Shortcut};++ use crate::canvas::{Fit, PageLayout};+ use crate::theme::ThemePreference;+ use crate::{PdfCraftApp, RightPanel};++ pub(super) mod tab_context;++ /// The app's name in the menus the layouts write (About, Hide, Quit).+ pub(crate) const APP_NAME: &str = "PdfCraft";++ /// The top bar's width after the menus: the mode tabs, the search box and the buttons.+ const ROW_AFTER_MENUS: f32 = 720.0;+ /// The narrowest the menu bar gets: one "Menu" title.+ const MIN_MENUS_WIDTH: f32 = 80.0;++ /// Menu-only commands. The registry's commands keep their own ids.+ pub(crate) const CUT: &str = "edit.cut";+ pub(crate) const PASTE: &str = "edit.paste";+ pub(crate) const DELETE: &str = "edit.delete";+ pub(crate) const SELECT_ALL: &str = "edit.select_all";+ pub(crate) const NO_RECENT: &str = "file.no_recent";+ /// An open document in the Window menu, `{"index": n}` in the tab strip.+ pub(crate) const DOCUMENT: &str = "window.document";+ /// A side panel, `{"panel": name}` ([`PANELS`]).+ pub(crate) const PANEL: &str = "view.panel";+ const ACTUAL_SIZE: &str = "view.zoom.actual_size";+ const PAGE_LEVEL: &str = "view.zoom.page_level";+ const FIT_WIDTH: &str = "view.zoom.fit_width";+ const FIT_HEIGHT: &str = "view.zoom.fit_height";+ const ZOOM_IN: &str = "view.zoom.in";+ const ZOOM_OUT: &str = "view.zoom.out";+ const ROTATE_CW: &str = "view.rotate.cw";+ const ROTATE_CCW: &str = "view.rotate.ccw";++ /// The menu-only items: id, English label and the shortcut shown (the keys stay with the view).+ const EXTRA: &[(&str, &str, Option<Shortcut>)] = &[+ (CUT, "Cut", Some(Shortcut::cmd("X"))),+ (PASTE, "Paste", Some(Shortcut::cmd("V"))),+ (DELETE, "Delete", Some(Shortcut { command: false, shift: false, mac_ctrl: false, key: "Delete" })),+ (SELECT_ALL, "Select all", Some(crate::commands::SELECT_ALL)),+ (NO_RECENT, "No recent files", None),+ (ACTUAL_SIZE, "Actual size", Some(crate::commands::ACTUAL_SIZE)),+ (PAGE_LEVEL, "Zoom to page level", Some(crate::commands::PAGE_LEVEL)),+ (FIT_WIDTH, "Fit to width", Some(crate::commands::FIT_WIDTH)),+ (FIT_HEIGHT, "Fit to height", None),+ (ZOOM_IN, "Zoom in", Some(crate::commands::ZOOM_IN)),+ (ZOOM_OUT, "Zoom out", Some(crate::commands::ZOOM_OUT)),+ (ROTATE_CW, "Rotate view clockwise", Some(crate::commands::ROTATE_CW)),+ (ROTATE_CCW, "Rotate view counterclockwise", Some(crate::commands::ROTATE_CCW)),+ ];++ /// View ▸ Side panels: the panel, its id in [`PANEL`] commands and its English label.+ const PANELS: &[(RightPanel, &str, &str)] = &[+ (RightPanel::Comments, "comments", "Comments"),+ (RightPanel::Bookmarks, "bookmarks", "Bookmarks"),+ (RightPanel::Pages, "pages", "Pages"),+ (RightPanel::Fields, "fields", "Fields"),+ (RightPanel::Layers, "layers", "Layers"),+ (RightPanel::Attachments, "attachments", "Attachments"),+ (RightPanel::Signatures, "signatures", "Signatures"),+ (RightPanel::Accessibility, "accessibility", "Accessibility Checker"),+ (RightPanel::Tags, "tags", "Tags"),+ (RightPanel::Search, "search", "Search"),+ (RightPanel::Compare, "compare", "Compare"),+ ];++ /// The English titles of the menus and submenus, for the bar's mnemonics in languages whose+ /// labels have no ASCII letter.+ const TITLES: &[&str] = &[+ "File",+ "Edit",+ "View",+ "Pages",+ "Sign",+ "Window",+ "Help",+ "Open Recent",+ "Create",+ "Export",+ "Protect",+ "Zoom",+ "Rotate view",+ "Page navigation",+ "Page display",+ "Side panels",+ "Display theme",+ "Tools",+ "Fill & Sign",+ ];++ /// Separator.+ const SEP: &str = "---";++ const FILE: &[&str] = &[+ "create.blank",+ "file.open",+ "file.open_recent",+ "file.pin_folder",+ SEP,+ "page.combine",+ SEP,+ "file.save",+ "file.save_as",+ "file.revert",+ SEP,+ "file.close",+ "file.close_all",+ SEP,+ "optimize.reduce",+ "optimize.advanced",+ SEP,+ "file.properties",+ "file.word_count",+ SEP,+ "print.dialog",+ ];+ const CREATE: &[&str] = &["create.file", "create.multiple", "create.multiple_separate", "create.images", "create.clipboard"];+ const EXPORT: &[&str] = &["export.docx", "export.pptx", "export.rtf", "export.html", "export.text", SEP, "export.image", "export.all_images"];+ const PROTECT: &[&str] = &["protect.password", "protect.remove", "protect.unlock", SEP, "protect.properties"];+ const EDIT: &[&str] = &[+ "edit.undo",+ "edit.redo",+ SEP,+ CUT,+ "edit.copy",+ PASTE,+ DELETE,+ SEP,+ SELECT_ALL,+ SEP,+ "edit.find",+ "edit.advanced_search",+ SEP,+ "edit.column_select",+ "edit.snapshot",+ SEP,+ "edit.attach",+ "form.clear",+ SEP,+ "app.preferences",+ ];+ const ZOOM: &[&str] = &[ACTUAL_SIZE, PAGE_LEVEL, FIT_WIDTH, FIT_HEIGHT, "view.fit_visible", SEP, ZOOM_IN, ZOOM_OUT, SEP, "view.marquee_zoom"];+ const NAVIGATION: &[&str] = &["view.focus_page_input", SEP, "view.previous_view", "view.next_view"];+ const DISPLAY: &[&str] = &[+ "view.layout.single",+ "view.layout.two_up",+ SEP,+ "view.continuous",+ "view.page_gaps",+ "view.layout.cover",+ SEP,+ "view.fit_width_scrolling",+ "view.fit_one_page",+ ];+ const THEMES: &[&str] = &["view.theme.system", "view.theme.light", "view.theme.dark"];+ const PANES: &[&str] = &["view.side_panel", "view.tools_pane"];+ const PANE_COMMANDS: &[&str] = &["comment.list", "form.fields", "ui.dock.reset"];+ const MODES: &[&str] = &["view.full_screen", "view.read_mode"];+ const PAGES: &[&str] = &[+ "page.organize",+ SEP,+ "page.insert_blank",+ "page.insert",+ "page.replace",+ "page.extract",+ "page.split",+ "page.duplicate",+ "page.delete",+ SEP,+ "page.rotate",+ "page.rotate_ccw",+ "page.rotate_dialog",+ "page.reverse",+ SEP,+ "page.crop",+ "page.boxes",+ "page.number",+ SEP,+ "bookmark.add",+ "bookmark.from_structure",++ "bookmark.from_text_styles",+ ];+ /// Sign ▸ Fill & Sign, with the short labels of the Fill & Sign toolbar.+ const FILL: &[(&str, &str)] = &[+ ("sign.fill.text", "Add text"),+ ("sign.fill.check", "Checkmark"),+ ("sign.fill.cross", "Cross"),+ ("sign.fill.dot", "Dot"),+ ("sign.fill.line", "Line"),+ ("sign.fill.date", "Date"),+ ("sign.fill.signature", "Signature"),+ ("sign.fill.initials", "Initials"),+ ];+ const SIGN: &[&str] = &[+ SEP,+ "sign.fill.signature.change",+ "sign.fill.initials.change",+ "sign.fill.signature.remove",+ "sign.fill.initials.remove",+ SEP,+ "sign.digital",+ "sign.certify",+ "sign.certify_invisible",+ "form.add.signature",+ SEP,+ "sign.validate",+ "sign.panel",+ ];+ const WINDOW: &[&str] = &["view.next_tab", "view.previous_tab"];+ const HELP: &[&str] =+ &["help.shortcuts", SEP, "help.app_page", "help.github", "help.website", "help.discord", SEP, "help.check_updates", SEP, "help.about"];++ /// A registry shortcut as a craft-keymap chord: `command` is ⌘ (Ctrl elsewhere) and `mac_ctrl`+ /// the Control key on macOS. `None` for a key craft-keymap doesn't name.+ pub(crate) fn chord(s: Shortcut) -> Option<Chord> {+ let key = Key::parse(s.key)?;+ Some(Chord::new(Mods { cmd: s.command, ctrl: s.mac_ctrl, alt: false, shift: s.shift }, key))+ }++ fn extra(id: &str) -> Option<&'static (&'static str, &'static str, Option<Shortcut>)> {+ EXTRA.iter().find(|(e, ..)| *e == id)+ }++ /// The English label of an item's command, for the bar's mnemonics.+ fn english_label(command: &CommandRef) -> Option<String> {+ if let Some(spec) = commands::command(&command.id) {+ return Some(spec.label.to_owned());+ }+ if let Some((_, label, _)) = extra(&command.id) {+ return Some((*label).to_owned());+ }+ FILL.iter().find(|(id, _)| *id == command.id).map(|(_, label)| (*label).to_owned())+ }++ fn english(labeled: Labeled<'_>) -> Option<String> {+ match labeled {+ Labeled::Command(command) => english_label(command),+ Labeled::Title(shown) => TITLES.iter().find(|t| tl!(t) == shown).map(|t| (*t).to_owned()),+ }+ }++ fn translate(english: &'static str) -> String {+ tl!(english).to_owned()+ }++ /// The layouts' own labels (About, Quit, Window…) through the app's translations.+ pub(crate) fn layout_options() -> LayoutOptions<'static> {+ LayoutOptions { label: &translate, ..LayoutOptions::new(APP_NAME) }+ }++ impl PdfCraftApp {+ /// The app's menus for this frame, before the platform layout: every item's label, shortcut,+ /// enabled and checked state as the app is now. A modal dialog doesn't grey anything here;+ /// that is the [`Gate`]'s job ([`PdfCraftApp::menu_gate`]).+ pub fn menu_bar(&self, ctx: &egui::Context) -> MenuBar {+ let mut used: Vec<&str> = Vec::new();+ let list = |ids: &[&'static str], used: &mut Vec<&'static str>| -> Vec<Node> {+ ids.iter()+ .map(|&id| {+ if id == SEP {+ return Node::Separator;+ }+ used.push(id);+ self.menu_item(id, None)+ })+ .collect()+ };+ let file = {+ let mut nodes = Vec::new();+ for node in list(FILE, &mut used) {+ // Open Recent is the live recent list; Create, Export and Protect follow Combine,+ // Optimize and Close.+ let recent = matches!(&node, Node::Item(it) if it.command.id == "file.open_recent");+ if recent {+ nodes.push(self.recent_menu());+ continue;+ }+ let after = match &node {+ Node::Item(it) => it.command.id.clone(),+ _ => String::new(),+ };+ nodes.push(node);+ match after.as_str() {+ "page.combine" => nodes.push(Node::submenu(tl!("Create"), list(CREATE, &mut used))),+ "optimize.advanced" => {+ nodes.push(Node::submenu(tl!("Export"), list(EXPORT, &mut used)));+ nodes.push(Node::Separator);+ nodes.push(Node::submenu(tl!("Protect"), list(PROTECT, &mut used)));+ }+ _ => {}+ }+ }+ nodes+ };+ // Edit ▸ Pages follows Select All.+ let mut edit = Vec::new();+ for node in list(EDIT, &mut used) {+ let select_all = matches!(&node, Node::Item(it) if it.command.id == SELECT_ALL);+ edit.push(node);+ if select_all {+ edit.push(Node::submenu(tl!("Pages"), list(PAGES, &mut used)));+ }+ }+ let mut sign = vec![Node::submenu(+ tl!("Fill & Sign"),+ FILL.iter()+ .map(|&(id, label)| {+ used.push(id);+ self.menu_item(id, Some(tl!(label)))+ })+ .collect(),+ )];+ sign.extend(list(SIGN, &mut used));+ let window = list(WINDOW, &mut used);+ let help = list(HELP, &mut used);+ let mut view = vec![+ Node::submenu(tl!("Zoom"), list(ZOOM, &mut used)),+ Node::submenu(tl!("Rotate view"), list(&[ROTATE_CW, ROTATE_CCW], &mut used)),+ Node::submenu(tl!("Page navigation"), list(NAVIGATION, &mut used)),+ Node::submenu(tl!("Page display"), list(DISPLAY, &mut used)),+ Node::Separator,+ ];+ view.extend(list(PANES, &mut used));+ view.push(Node::submenu(+ tl!("Side panels"),+ PANELS+ .iter()+ .map(|(_, name, label)| {+ Item::new(CommandRef::with_params(PANEL, serde_json::json!({ "panel": name })), tl!(label)).radio(false).into()+ })+ .collect(),+ ));+ view.extend(list(PANE_COMMANDS, &mut used));+ view.push(Node::Separator);+ view.extend(list(MODES, &mut used));+ view.push(Node::submenu(tl!("Display theme"), list(THEMES, &mut used)));+ view.push(Node::Separator);+ view.push(Node::submenu(tl!("Tools"), self.tools_menu(&used)));+ view.extend(list(&["view.palette"], &mut used));+ let mut bar = MenuBar {+ menus: vec![+ Menu::new(tl!("File"), craft_menu::tidy(file)).role(MenuRole::File),+ Menu::new(tl!("Edit"), craft_menu::tidy(edit)).role(MenuRole::Edit),+ Menu::new(tl!("View"), craft_menu::tidy(view)).role(MenuRole::View),+ Menu::new(tl!("Sign"), craft_menu::tidy(sign)),+ Menu::new(tl!("Window"), window).role(MenuRole::Window),+ Menu::new(tl!("Help"), craft_menu::tidy(help)).role(MenuRole::Help),+ ],+ documents: self.menu_documents(),+ };+ bar.tag_item(&CommandRef::new("help.about"), ItemRole::About);+ bar.tag_item(&CommandRef::new("app.preferences"), ItemRole::Settings);+ craft_menu::apply_state(&mut bar, |command| self.menu_state(ctx, command));+ bar+ }++ /// One item: a registry command with its live label (Undo names the edit) and shortcut, or a+ /// menu-only one. Radio and check items get their kind here, their state from+ /// [`PdfCraftApp::menu_state`].+ fn menu_item(&self, id: &'static str, label: Option<&str>) -> Node {+ let (english, shortcut) = match commands::command(id) {+ Some(spec) => {+ let current = commands::current_label(spec, &self.session, self.active_ids().map(|(_, doc)| doc));+ (crate::i18n::menu_label(id, ¤t), spec.shortcut.or((id == "edit.copy").then_some(crate::commands::COPY)))+ }+ None => match extra(id) {+ Some((_, label, shortcut)) => (tl!(label).to_owned(), *shortcut),+ None => (id.to_owned(), None),+ },+ };+ let mut item = Item::new(id, label.map_or(english, str::to_owned));+ if let Some(c) = shortcut.and_then(chord) {+ item = item.shortcut(c);+ }+ if matches!(id, "view.layout.single" | "view.layout.two_up") || THEMES.contains(&id) {+ item = item.radio(false);+ }+ item.into()+ }++ /// File ▸ Open Recent: the recent files, newest first, then Clear Recent Files.+ fn recent_menu(&self) -> Node {+ let mut items: Vec<Node> = self+ .recent+ .iter()+ .enumerate()+ .map(|(index, r)| Item::new(CommandRef::with_params("file.open_recent", serde_json::json!({ "index": index })), r.name.clone()).into())+ .collect();+ if items.is_empty() {+ items.push(self.menu_item(NO_RECENT, None));+ } else {+ items.push(Node::Separator);+ items.push(self.menu_item("file.clear_recent", Some(tl!("Clear Recent Files"))));+ }+ let label = commands::command("file.open_recent").map_or("Open Recent", |c| c.label);+ Node::submenu(crate::i18n::menu_label("file.open_recent", label), items)+ }++ /// View ▸ Tools: the All tools groups, each a submenu of its ready tools that no other menu+ /// lists, sections apart.+ fn tools_menu(&self, used: &[&str]) -> Vec<Node> {+ TOOL_GROUPS+ .iter()+ .filter(|g| g.availability == Availability::Ready)+ .map(|group| {+ let mut nodes = Vec::new();+ let mut seen: Vec<&str> = Vec::new();+ for section in group.sections {+ nodes.push(Node::Separator);+ for tool in section.items.iter().filter(|t| t.availability == Availability::Ready) {+ let actions: &[&'static str] = if tool.actions.is_empty() { std::slice::from_ref(&tool.command) } else { tool.actions };+ for &id in actions {+ if commands::command(id).is_none() || used.contains(&id) || seen.contains(&id) {+ continue;+ }+ seen.push(id);+ let label = if tool.actions.is_empty() { Some(tl!(tool.label)) } else { None };+ nodes.push(self.menu_item(id, label));+ }+ }+ }+ Node::submenu(tl!(group.label), nodes)+ })+ .collect()+ }++ /// The open documents, in tab order, for the Window menu.+ fn menu_documents(&self) -> Vec<Document> {+ (0..self.views.len())+ .filter_map(|index| {+ let name = crate::canvas::tab_label(self, index)?;+ Some(Document::new(CommandRef::with_params(DOCUMENT, serde_json::json!({ "index": index })), name).active(self.active == Some(index)))+ })+ .collect()+ }++ /// What may run from the menus now: a dialog, a prompt or the command palette holds the+ /// window. Edit's text items stay with a focused text field (craft-menu's gate).+ pub fn menu_gate(&self, ctx: &egui::Context) -> Gate {+ Gate { modal: self.modal_open() || self.palette_open, recording_shortcut: false, text_editing: ctx.text_edit_focused() }+ }++ /// Whether a menu item's command can run now, and its checked or selected state.+ pub fn menu_state(&self, ctx: &egui::Context, command: &CommandRef) -> ItemState {+ let view = self.active.and_then(|i| self.views.get(i));+ let organize = view.is_some_and(|v| v.organize);+ let has_doc = view.is_some();+ let enabled_id = |id: &str| commands::command(id).is_some_and(|s| self.command_enabled(s));+ let index = param_index(command);+ let text = ctx.text_edit_focused() && matches!(command.id.as_str(), "edit.undo" | "edit.redo" | "edit.copy" | CUT | PASTE | SELECT_ALL);+ let enabled = text+ || match command.id.as_str() {+ NO_RECENT => false,+ "file.open_recent" => index.is_none_or(|i| i < self.recent.len()),+ "file.clear_recent" => !self.recent.is_empty(),+ DOCUMENT => index.is_some_and(|i| i < self.views.len()),+ // macOS ⌘W closes the window when no document is open (#869).+ "file.close" if !has_doc && crate::commands::mac_shortcuts(ctx) && !cfg!(target_arch = "wasm32") => true,+ "edit.copy" if organize => enabled_id("page.copy"),+ "edit.copy" if view.is_some_and(|v| v.picked_image.is_some()) => {+ self.active_ids().and_then(|(_, id)| self.session.get(id)).is_some_and(|d| d.allows_copying())+ }+ CUT => organize && enabled_id("page.cut"),+ PASTE => organize && self.page_clipboard.is_some() && enabled_id("page.paste"),+ SELECT_ALL | DELETE => has_doc,+ ACTUAL_SIZE | PAGE_LEVEL | FIT_WIDTH | FIT_HEIGHT | ZOOM_IN | ZOOM_OUT | ROTATE_CW | ROTATE_CCW => has_doc,+ PANEL => panel(command).is_some(),+ id => enabled_id(id),+ };+ let checked = match command.id.as_str() {+ "view.layout.single" => Some(view.is_some_and(|v| v.layout == PageLayout::Single)),+ "view.layout.two_up" => Some(view.is_some_and(|v| v.layout == PageLayout::TwoUp)),+ "view.continuous" => Some(view.is_some_and(|v| v.continuous())),+ "view.page_gaps" => Some(view.is_some_and(|v| v.show_page_gaps)),+ "view.layout.cover" => Some(view.is_some_and(|v| v.cover)),+ "view.full_screen" => Some(self.full_screen),+ "view.read_mode" => Some(self.mode == crate::Mode::Read),+ "view.side_panel" => Some(self.right.is_some()),+ "view.tools_pane" => Some(self.left_open),+ "view.theme.system" => Some(self.theme_preference == ThemePreference::System),+ "view.theme.light" => Some(self.theme_preference == ThemePreference::Light),+ "view.theme.dark" => Some(self.theme_preference == ThemePreference::Dark),+ PANEL => Some(panel(command).is_some_and(|p| self.right == Some(p))),+ _ => None,+ };+ ItemState { enabled, checked }+ }++ /// Run a command chosen in either menu bar. Registry commands go through+ /// [`PdfCraftApp::dispatch_command`], as their shortcuts do; the clipboard items act as+ /// their keys would (⌘C is a Copy event, Delete a key press), so every place that handles the+ /// key handles the click. A command that can't run now (a dialog opened since the menu was+ /// drawn) does nothing.+ pub fn run_menu_command(&mut self, ctx: &egui::Context, command: &CommandRef) {+ // Both menu bars run Quit and Minimize themselves; Hide and Hide Others are AppKit's.+ if Builtin::of(command).is_some() {+ return;+ }+ if !self.menu_gate(ctx).allows_command(command) || !self.menu_state(ctx, command).enabled {+ return;+ }+ let index = param_index(command);+ let key = |key: egui::Key, modifiers: egui::Modifiers| {+ [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers })+ };+ match command.id.as_str() {+ "file.open_recent" if index.is_some() => {+ if let Some(path) = index.and_then(|i| self.recent.get(i)).map(|r| r.path.clone()) {+ self.open_recent(&path);+ }+ }+ DOCUMENT => {+ if let Some(i) = index.filter(|&i| i < self.views.len()) {+ self.active = Some(i);+ }+ }+ "edit.copy" => self.menu_input.push(egui::Event::Copy),+ CUT => self.menu_input.push(egui::Event::Cut),+ PASTE => ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaste),+ SELECT_ALL => self.menu_input.extend(key(egui::Key::A, egui::Modifiers::COMMAND)),+ DELETE => self.menu_input.extend(key(egui::Key::Delete, egui::Modifiers::NONE)),+ PANEL => self.choose_right_panel(panel(command)),+ ACTUAL_SIZE | PAGE_LEVEL | FIT_WIDTH | FIT_HEIGHT | ZOOM_IN | ZOOM_OUT | ROTATE_CW | ROTATE_CCW => {+ let Some(v) = self.active.and_then(|i| self.views.get_mut(i)) else { return };+ match command.id.as_str() {+ ACTUAL_SIZE => v.set_zoom(1.0),+ PAGE_LEVEL => v.fit = Fit::Page,+ FIT_WIDTH => v.fit = Fit::Width,+ FIT_HEIGHT => {+ v.fit = Fit::Height;+ v.goto = Some((v.current, 0.0));+ }+ ZOOM_IN => v.zoom_step(true),+ ZOOM_OUT => v.zoom_step(false),+ ROTATE_CW => v.rotate_view(true),+ _ => v.rotate_view(false),+ }+ }+ id => {+ if let Some(spec) = commands::command(id) {+ self.dispatch_command(ctx, spec.id);+ }+ }+ }+ ctx.request_repaint();+ }++ /// The menu bar drawn in the window (Windows, Linux, the web, and macOS when the native one+ /// couldn't be installed), where the top bar starts. Runs the commands chosen.+ pub(crate) fn menu_bar_ui(&mut self, ui: &mut egui::Ui) {+ let ctx = ui.ctx().clone();+ let bar = craft_menu::layout(&self.menu_bar(&ctx), Target::current(), &layout_options()).bar;+ let gate = self.menu_gate(&ctx);+ // The mode tabs, search and buttons follow the bar in the same row: it takes its titles'+ // width, less when the row is short, where the menus that don't fit move into its "⋯".+ let fit = (ui.available_width() - ROW_AFTER_MENUS).max(MIN_MENUS_WIDTH);+ let chosen = craft_menu::MenuBarUi::new(&bar)+ .gate(gate)+ .label(&translate)+ .english(&english)+ .id(egui::Id::unique("pdfcraft-menu-bar"))+ .shrink_to_fit(fit)+ .show(ui);+ for command in chosen {+ self.run_menu_command(&ctx, &command);+ }+ }++ /// Install the native menu bar (macOS), once, from the eframe app creator. `false` when+ /// AppKit refused it: the in-window bar stays.+ #[cfg(target_os = "macos")]+ pub fn install_native_menu(&mut self, ctx: &egui::Context) -> bool {+ crate::i18n::set_current(crate::i18n::Lang::from_pref(&self.language));+ let bar = craft_menu::mac_layout(&self.menu_bar(ctx), &layout_options()).bar;+ // The Window menu lists the open documents itself, so AppKit's window list stays off.+ self.native_menu = craft_menu::mac::install_with(ctx, &bar, craft_menu::mac::MacOptions::default().window_list(false));+ self.native_menu.is_some()+ }++ /// The native menu's clicks since the last frame, run like in-window ones.+ pub(crate) fn native_menu_clicks(&mut self, ctx: &egui::Context) {+ let gate = self.menu_gate(ctx);+ let Some(native) = self.native_menu.as_mut() else { return };+ native.set_gate(gate);+ for command in native.take_clicks(ctx) {+ self.run_menu_command(ctx, &command);+ }+ }++ /// Bring the native menu in step with the app, after this frame's changes.+ pub(crate) fn sync_native_menu(&mut self, ctx: &egui::Context) {+ if self.native_menu.is_none() {+ return;+ }+ let layout = craft_menu::mac_layout(&self.menu_bar(ctx), &layout_options());+ let gate = self.menu_gate(ctx);+ if let Some(native) = self.native_menu.as_mut() {+ native.set_gate(gate);+ for clash in native.sync(layout) {+ log::info!("menu shortcut {:?} kept by {} over {} ({})", clash.shortcut, clash.command.id, clash.system, clash.resolution);+ }+ }+ }+ }++ /// A command's `{"index": n}` parameter.+ fn param_index(command: &CommandRef) -> Option<usize> {+ command.params.get("index").and_then(serde_json::Value::as_u64).and_then(|i| usize::try_from(i).ok())+ }++ /// The side panel a [`PANEL`] command names.+ fn panel(command: &CommandRef) -> Option<RightPanel> {+ let name = command.params.get("panel").and_then(serde_json::Value::as_str)?;+ PANELS.iter().find(|(_, n, _)| *n == name).map(|(p, ..)| *p)+ }++ #[cfg(test)]+ mod tests {+ use std::cell::RefCell;+ use std::rc::Rc;++ use craft_menu::{Backend, Dispatch, Event, ItemKind, NativeMenu};++ use super::*;++ const PDF: &[u8] = include_bytes!("../tests/data/form.pdf");++ fn app(docs: &[&str]) -> (PdfCraftApp, egui::Context) {+ let mut app = PdfCraftApp::new();+ app.set_option("language", "en").unwrap();+ for name in docs {+ app.open_bytes(name, None, PDF.to_vec()).unwrap();+ }+ (app, egui::Context::default())+ }++ fn linux(app: &PdfCraftApp, ctx: &egui::Context) -> MenuBar {+ craft_menu::layout(&app.menu_bar(ctx), Target::Linux, &layout_options()).bar+ }++ fn item<'b>(bar: &'b MenuBar, command: &CommandRef) -> &'b Item {+ bar.find(command).unwrap_or_else(|| panic!("{} is in the menus", command.key()))+ }++ #[test]+ fn every_menu_command_is_listed_once_with_its_shortcut() {+ let (app, ctx) = app(&["a.pdf"]);+ let bar = linux(&app, &ctx);+ let items = bar.items();+ let mut keys: Vec<String> = items.iter().map(|it| it.command.key()).collect();+ keys.sort();+ let count = keys.len();+ keys.dedup();+ assert_eq!(keys.len(), count, "no command is listed twice");+ for spec in commands::COMMANDS.iter().filter(|s| s.menu.is_some()) {+ if spec.id == "file.open_recent" {+ continue; // A submenu of the recent files.+ }+ let it = item(&bar, &CommandRef::new(spec.id));+ let shortcut = spec.shortcut.or((spec.id == "edit.copy").then_some(crate::commands::COPY));+ assert_eq!(it.shortcut, shortcut.and_then(chord), "{} has its registry shortcut", spec.id);+ }+ // Every item runs a registry command or one of the menu's own.+ for it in items {+ let id = it.command.id.as_str();+ assert!(+ commands::command(id).is_some() || extra(id).is_some() || [PANEL, DOCUMENT].contains(&id) || Builtin::of(&it.command).is_some(),+ "{id} runs something"+ );+ }+ }++ #[test]+ fn check_and_radio_items_follow_the_app() {+ let (mut app, ctx) = app(&["a.pdf"]);+ let kind = |app: &PdfCraftApp, id: &str| item(&linux(app, &ctx), &CommandRef::new(id)).kind;+ assert_eq!(kind(&app, "view.layout.single"), ItemKind::Radio(true));+ assert_eq!(kind(&app, "view.layout.two_up"), ItemKind::Radio(false));+ let continuous = app.views[0].continuous();+ assert_eq!(kind(&app, "view.continuous"), ItemKind::Check(continuous));+ app.run_menu_command(&ctx, &CommandRef::new("view.layout.two_up"));+ app.run_menu_command(&ctx, &CommandRef::new("view.continuous"));+ assert_eq!(kind(&app, "view.layout.single"), ItemKind::Radio(false));+ assert_eq!(kind(&app, "view.layout.two_up"), ItemKind::Radio(true));+ assert_eq!(kind(&app, "view.continuous"), ItemKind::Check(!continuous));+ let left = app.left_open;+ assert_eq!(kind(&app, "view.tools_pane"), ItemKind::Check(left));+ app.run_menu_command(&ctx, &CommandRef::new("view.tools_pane"));+ assert_eq!(kind(&app, "view.tools_pane"), ItemKind::Check(!left));+ let bookmarks = CommandRef::with_params(PANEL, serde_json::json!({ "panel": "bookmarks" }));+ app.run_menu_command(&ctx, &bookmarks);+ assert_eq!(app.right, Some(RightPanel::Bookmarks));+ assert_eq!(item(&linux(&app, &ctx), &bookmarks).kind, ItemKind::Radio(true));+ assert_eq!(kind(&app, "view.side_panel"), ItemKind::Check(true));+ }++ #[test]+ fn a_dialog_greys_document_commands_and_drops_their_clicks() {+ let (mut app, ctx) = app(&["a.pdf"]);+ let rotate = CommandRef::new("page.rotate");+ assert!(app.menu_gate(&ctx).allows_command(&rotate));+ app.dialog = Some(crate::Dialog::About);+ assert!(!app.menu_gate(&ctx).allows_command(&rotate), "the gate greys the menus under a dialog");+ let doc = app.views[0].id;+ let before = app.session.get(doc).unwrap().info.pages[0].rotation;+ app.run_menu_command(&ctx, &rotate);+ assert_eq!(app.session.get(doc).unwrap().info.pages[0].rotation, before, "a click that arrives anyway does nothing");+ // Quit still asks the window to close, which asks about unsaved changes.+ assert!(app.menu_gate(&ctx).allows_command(&Builtin::Quit.command()));+ }++ #[test]+ fn recent_files_and_open_documents_are_listed_once_each() {+ let (mut app, ctx) = app(&["a.pdf", "b.pdf"]);+ app.recent = ["one.pdf", "two.pdf"].map(|n| crate::RecentFile { name: n.into(), path: format!("/nowhere/{n}"), pages: 1, size: 0 }).into();+ let bar = linux(&app, &ctx);+ for (i, name) in ["one.pdf", "two.pdf"].into_iter().enumerate() {+ assert_eq!(item(&bar, &CommandRef::with_params("file.open_recent", serde_json::json!({ "index": i }))).label, name);+ }+ let window = bar.menu(MenuRole::Window).unwrap();+ let documents: Vec<&str> = window+ .children+ .iter()+ .filter_map(|n| match n {+ Node::Item(it) if it.command.id == DOCUMENT => Some(it.label.as_str()),+ _ => None,+ })+ .collect();+ assert_eq!(documents, ["a.pdf", "b.pdf"], "each open document once, in tab order");+ app.run_menu_command(&ctx, &CommandRef::with_params(DOCUMENT, serde_json::json!({ "index": 0 })));+ assert_eq!(app.active, Some(0));+ // The macOS layout lists them once too.+ let mac = craft_menu::mac_layout(&app.menu_bar(&ctx), &layout_options()).bar;+ let listed = mac.items().iter().filter(|it| it.command.id == DOCUMENT).count();+ assert_eq!(listed, 2);+ app.recent.clear();+ let bar = linux(&app, &ctx);+ assert!(!item(&bar, &CommandRef::new(NO_RECENT)).enabled, "an empty list shows a greyed placeholder");+ assert!(bar.find(&CommandRef::new("file.clear_recent")).is_none());+ }++ /// A native backend that reports what the test queues, through the driver's dispatch as the+ /// macOS backend does.+ #[derive(Clone, Default)]+ struct FakeMenu(Rc<RefCell<(Option<Dispatch>, Vec<Event>)>>);++ impl FakeMenu {+ fn click(&self, command: &CommandRef) {+ let mut state = self.0.borrow_mut();+ let event = state.0.as_ref().map(|d| d.chosen(command, None, false, None));+ state.1.extend(event);+ }+ }++ impl Backend for FakeMenu {+ fn sync(&mut self, _bar: &MenuBar) {}+ fn drain(&mut self) -> Vec<Event> {+ std::mem::take(&mut self.0.borrow_mut().1)+ }+ fn attach(&mut self, dispatch: Dispatch) {+ self.0.borrow_mut().0 = Some(dispatch);+ }+ }++ #[test]+ fn a_native_menu_click_runs_its_command_once() {+ let (mut app, ctx) = app(&["a.pdf"]);+ let fake = FakeMenu::default();+ app.native_menu = Some(NativeMenu::new(Box::new(fake.clone())));+ let doc = app.views[0].id;+ let before = app.session.get(doc).unwrap().info.pages[0].rotation;+ fake.click(&CommandRef::new("page.rotate"));+ let mut raw = egui::RawInput::default();+ app.prepare_raw_input(&ctx, &mut raw);+ app.native_menu_clicks(&ctx);+ app.native_menu_clicks(&ctx);+ assert_eq!(app.session.get(doc).unwrap().info.pages[0].rotation, (before + 90) % 360, "rotated once");+ }+ }diff --cc crates/ui-egui/src/panels/bookmarks.rsindex 000000000,3753c8494..5a293005cmode 000000,100644..100644--- a/crates/ui-egui/src/panels/bookmarks.rs+++ b/crates/ui-egui/src/panels/bookmarks.rs@@@ -1,0 -1,360 +1,362 @@@+ use super::*;++ /// What the user asked to do with a bookmark (applied after the panel is drawn).+ #[derive(Clone, Debug, PartialEq)]+ pub enum BmAction {+ /// New "Untitled" bookmark for the current page, after the selected one (⌘B).+ New,+ StartRename(Vec<usize>),+ Rename(Vec<usize>, String),+ SetToCurrentPage(Vec<usize>),+ /// Make the title bold or italic or not (`None` keeps that one).+ SetStyle(Vec<usize>, Option<bool>, Option<bool>),+ /// Colour the title; black is the default.+ SetColor(Vec<usize>, [f64; 3]),+ Delete(Vec<usize>),+ MoveUp(Vec<usize>),+ MoveDown(Vec<usize>),+ /// Make it the last child of the bookmark above it.+ Indent(Vec<usize>),+ /// Move it out to follow its parent.+ Outdent(Vec<usize>),+ /// Bookmarks from the tagged headings, under a new first "Untitled" bookmark.+ FromStructure,++ /// Open New bookmarks from text styles, to choose a style per bookmark level (#1693).++ FromTextStyles,+ }++ /// Matching titles plus their ancestors, keeping document paths rather than filtered indexes.+ /// `query` is folded with [`pdfcraft_render::text::fold_case`], as titles are here.+ pub(super) fn outline_matches(items: &[OutlineItem], query: &str) -> std::collections::HashSet<Vec<usize>> {+ let mut matches = std::collections::HashSet::new();+ if query.is_empty() {+ return matches;+ }+ let mut pending: Vec<_> = items.iter().enumerate().map(|(i, item)| (vec![i], item)).collect();+ while let Some((path, item)) = pending.pop() {+ if pdfcraft_render::text::fold_case(&item.title).contains(query) {+ let mut ancestor = path.clone();+ while !ancestor.is_empty() {+ matches.insert(ancestor.clone());+ ancestor.pop();+ }+ }+ for (i, child) in item.children.iter().enumerate() {+ let mut child_path = path.clone();+ child_path.push(i);+ pending.push((child_path, child));+ }+ }+ matches+ }++ pub(super) struct OutlineCtx<'a> {+ pub(super) nav: &'a mut Option<Nav>,+ pub(super) action: &'a mut Option<BmAction>,+ pub(super) rename: &'a mut Option<(Vec<usize>, String)>,+ pub(super) editable: bool,+ pub(super) current: usize,+ /// Expand all (`Some(usize::MAX)`), collapse all (`Some(0)`) or expand to a depth, this frame.+ pub(super) expand: Option<usize>,+ pub(super) matches: &'a std::collections::HashSet<Vec<usize>>,+ pub(super) searching: bool,+ }++ /// The destination page label gets its own right-aligned column in a bookmark row; drawing+ /// tools put whole section titles in /PageLabels, so the column is bounded (#124).+ const LABEL_COLUMN_MAX: f32 = 72.0;++ /// More characters than ever fit [`LABEL_COLUMN_MAX`] at the label size.+ const LABEL_MEASURE_CHARS: usize = 64;++ /// The longest head of `text` that `fits`, plus an ellipsis when the whole string doesn't.+ /// Whole characters are dropped from the end, so the string is only ever cut at a char+ /// boundary, and the loop always ends (at the ellipsis alone). A label is document text: only+ /// its first [`LABEL_MEASURE_CHARS`] characters are measured, so a huge one can't make each+ /// frame lay out thousands of candidates.+ pub(crate) fn ellipsized_prefix(text: &str, mut fits: impl FnMut(&str) -> bool) -> String {+ let mut s: String = text.chars().take(LABEL_MEASURE_CHARS).collect();+ if s.len() == text.len() && fits(text) {+ return text.to_owned();+ }+ loop {+ s.pop();+ let candidate = format!("{s}\u{2026}");+ if s.is_empty() || fits(&candidate) {+ return candidate;+ }+ }+ }++ /// How a bookmark's title is drawn: in its own style and colour (ISO 32000-2 §12.3.3, Tables 151+ /// and 152), bold in the heavier face and italic slanted, its colour kept readable on the panel.+ /// Top-level bookmarks without a style keep the medium face.+ fn title_format(item: &OutlineItem, depth: usize, t: &Tokens) -> egui::TextFormat {+ let font_id = match (item.bold, depth) {+ (true, _) => theme::semibold(13.0),+ (false, 0) => theme::medium(13.0),+ (false, _) => theme::regular(13.0),+ };+ let color = item.color.map_or(t.text, |rgb| {+ // Each component is within 0–1, so the rounded value fits a byte.+ let [r, g, b] = rgb.map(|c| (c * 255.0).round() as u8);+ theme::readable(egui::Color32::from_rgb(r, g, b), t.panel, t.text)+ });+ egui::TextFormat { font_id, color, italics: item.italic, ..Default::default() }+ }++ /// Draw one bookmark row with expansion, inline rename and the editable context menu.+ pub(super) fn outline_item(+ ui: &mut egui::Ui,+ t: &Tokens,+ info: &DocInfo,+ item: &OutlineItem,+ path: &[usize],+ siblings: usize,+ cx: &mut OutlineCtx<'_>,+ ) {+ if cx.searching && !cx.matches.contains(path) {+ return;+ }+ let depth = path.len() - 1;+ let indent = depth as f32 * 16.0;+ let id = ui.scope_id().with(("outline", path));+ if let Some(levels) = cx.expand {+ ui.data_mut(|d| d.insert_temp(id, depth < levels));+ }+ // A bookmark opens as the file says at every level: a positive /Count is open, a negative+ // one (or none) closed (ISO 32000-2 §12.3.3, Table 151). The reader's own toggles and a+ // search override it.+ let mut open = cx.searching || ui.data(|d| d.get_temp::<bool>(id)).unwrap_or(item.open);+ let x_text = indent + 20.0;+ if let Some((rpath, text)) = cx.rename.as_mut()+ && rpath.as_slice() == path+ {+ // Inline rename: Enter commits, Escape cancels.+ let mut commit = None;+ let mut cancel = false;+ ui.horizontal(|ui| {+ ui.add_space(x_text);+ crate::widgets::begin_dialog(ui);+ let edit = crate::widgets::line(text).desired_width(ui.available_width() - 8.0).id(id.with("rename"));+ let resp = ui.add(edit);+ if !resp.has_focus() && !resp.lost_focus() {+ resp.request_focus();+ }+ if ui.input(|i| i.key_pressed(egui::Key::Escape)) {+ cancel = true;+ } else if resp.lost_focus() {+ commit = Some(text.trim().to_string());+ }+ });+ if cancel {+ *cx.rename = None;+ } else if let Some(title) = commit {+ *cx.rename = None;+ if !title.is_empty() && title != item.title {+ *cx.action = Some(BmAction::Rename(path.to_vec(), title));+ }+ }+ } else {+ // The page label sits right-aligned in its own bounded column, and the title wraps to+ // what is really left of it — a long label painted over a long title was the overlap+ // of #124.+ let label_font = theme::regular(11.0);+ let label_galley = item.page.and_then(|p| info.pages.get(p)).map(|page| {+ ui.fonts_mut(|f| {+ let text =+ ellipsized_prefix(&page.label, |s| f.layout_no_wrap(s.to_owned(), label_font.clone(), t.text_faint).size().x <= LABEL_COLUMN_MAX);+ f.layout_no_wrap(text, label_font, t.text_faint)+ })+ });+ let label_w = label_galley.as_ref().map_or(0.0, |g| g.size().x);+ let wrap_w = (ui.available_width() - indent - 20.0 - label_w - 12.0).max(60.0);+ let mut job = egui::text::LayoutJob::single_section(item.title.clone(), title_format(item, depth, t));+ job.wrap.max_width = wrap_w;+ let galley = ui.fonts_mut(|f| f.layout_job(job));+ let h = (galley.size().y + 12.0).max(28.0);+ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &item.title));+ theme::Press::track(ui, &resp).wash(ui, rect, 6, false);+ let x0 = rect.left() + indent;+ if !item.children.is_empty() {+ let tri = Rect::from_min_size(pos2(x0, rect.top() + 6.0), vec2(16.0, 16.0));+ icons::paint(ui, tri, if open { "chevron-down" } else { "chevron-right" }, 14.0, t.text_muted);+ if !cx.searching && ui.interact(tri, id.with("tri"), Sense::click()).clicked() {+ open = !open;+ ui.data_mut(|d| d.insert_temp(id, open));+ }+ }+ ui.painter().galley(pos2(x0 + 20.0, rect.top() + 6.0), galley, t.text);+ if let Some(g) = label_galley {+ // Right-aligned, vertically centred at the first line, inside the column the title+ // wrapped around.+ let pos = pos2(rect.right() - 6.0 - g.size().x, rect.top() + 14.0 - g.size().y / 2.0);+ ui.painter().galley(pos, g, t.text_faint);+ }+ if theme::hand(resp.clone()).clicked()+ && let Some(p) = item.page+ {+ *cx.nav = Some(Nav::Dest(p, item.view));+ }+ if resp.double_clicked() && cx.editable {+ *cx.action = Some(BmAction::StartRename(path.to_vec()));+ }+ if cx.editable+ && let Some(&i) = path.last()+ {+ let current = cx.current;+ resp.context_menu(|ui| {+ let mut pick = |ui: &mut egui::Ui, label: &str, enabled: bool, a: BmAction| {+ if ui.add_enabled(enabled, egui::Button::new(tl!(label))).clicked() {+ *cx.action = Some(a);+ ui.close();+ }+ };+ pick(ui, tl!("Rename"), true, BmAction::StartRename(path.to_vec()));+ let set_page = crate::i18n::fmt(tl!("Set to current page ({n})"), &[("n", &(current + 1).to_string())]);+ pick(ui, &set_page, true, BmAction::SetToCurrentPage(path.to_vec()));+ // The title's style and colour (ISO 32000-2 §12.3.3, Tables 151 and 152).+ let mut styled = None;+ ui.menu_button(tl!("Style"), |ui| {+ let (mut bold, mut italic) = (item.bold, item.italic);+ if ui.add(crate::widgets::checkbox(&mut bold, tl!("Bold"))).clicked() {+ styled = Some(BmAction::SetStyle(path.to_vec(), Some(bold), None));+ }+ if ui.add(crate::widgets::checkbox(&mut italic, tl!("Italic"))).clicked() {+ styled = Some(BmAction::SetStyle(path.to_vec(), None, Some(italic)));+ }+ });+ ui.menu_button(tl!("Colour"), |ui| {+ let current = item.color.map_or([0.0; 3], |c| c.map(f64::from));+ if let Some(c) = crate::comments::swatch_grid(ui, Some(current)) {+ styled = Some(BmAction::SetColor(path.to_vec(), c));+ }+ });+ if styled.is_some() {+ ui.close();+ }+ ui.separator();+ pick(ui, tl!("Move up"), i > 0, BmAction::MoveUp(path.to_vec()));+ pick(ui, tl!("Move down"), i + 1 < siblings, BmAction::MoveDown(path.to_vec()));+ pick(ui, tl!("Indent"), i > 0, BmAction::Indent(path.to_vec()));+ pick(ui, tl!("Outdent"), depth > 0, BmAction::Outdent(path.to_vec()));+ ui.separator();+ pick(ui, tl!("Delete"), true, BmAction::Delete(path.to_vec()));+ if let Some(a) = styled {+ *cx.action = Some(a);+ }+ });+ }+ }+ if open {+ for (ci, c) in item.children.iter().enumerate() {+ let mut p = path.to_vec();+ p.push(ci);+ outline_item(ui, t, info, c, &p, item.children.len(), cx);+ }+ }+ }++ #[cfg(test)]+ mod label_column {+ use super::ellipsized_prefix;++ /// A short page label (the usual "3", "iv", "1-1") is shown unchanged.+ #[test]+ fn short_labels_are_not_touched() {+ for label in ["3", "iv", "1-1", "A-201"] {+ assert_eq!(ellipsized_prefix(label, |s| s.len() <= 10), label);+ }+ }++ /// A label wider than its column (#124: whole section titles in /PageLabels) keeps only+ /// the head that fits, with an ellipsis, and that head is a prefix of the real label.+ #[test]+ fn long_labels_are_cut_to_their_column_with_an_ellipsis() {+ let label = "Floor Plans (001 Floor Plans): GROUND FLOOR PLAN";+ let shown = ellipsized_prefix(label, |s| s.len() <= 20);+ assert!(shown.ends_with('\u{2026}'), "{shown:?}");+ assert!(shown.len() <= 20, "{shown:?}");+ assert!(label.starts_with(shown.trim_end_matches('\u{2026}')), "{shown:?}");+ }++ /// CJK labels (three bytes per character) are cut on character boundaries too.+ #[test]+ fn multibyte_labels_are_cut_on_char_boundaries() {+ let label = "図面(一階平面図):配置図";+ let shown = ellipsized_prefix(label, |s| s.len() <= 12);+ assert!(shown.ends_with('\u{2026}'), "{shown:?}");+ assert!(shown.len() <= 12, "{shown:?}");+ assert!(label.starts_with(shown.trim_end_matches('\u{2026}')), "{shown:?}");+ }++ /// The pathological floor: nothing fits, the loop still ends with the lone ellipsis.+ #[test]+ fn the_loop_ends_when_nothing_fits() {+ assert_eq!(ellipsized_prefix("Floor Plans", |_| false), "\u{2026}");+ }++ /// A huge label from a hostile file is measured a bounded number of times per frame.+ #[test]+ fn a_huge_label_is_measured_a_bounded_number_of_times() {+ let label = "x".repeat(1_000_000);+ let mut calls = 0;+ let shown = ellipsized_prefix(&label, |s| {+ calls += 1;+ s.len() <= 12+ });+ assert!(calls <= super::LABEL_MEASURE_CHARS + 1, "{calls} measurements");+ assert!(shown.ends_with('\u{2026}') && label.starts_with(shown.trim_end_matches('\u{2026}')), "{shown:?}");+ }+ }++ #[cfg(test)]+ mod bookmark_filter {+ use super::{outline_matches, title_format};+ use crate::theme::{self, Tokens};+ use pdfcraft_render::OutlineItem;++ /// #3193: a bookmark's title is drawn in its own style and colour.+ #[test]+ fn bookmark_titles_take_their_style_and_colour() {+ let t = Tokens::for_kind(crate::theme::ThemeKind::Light);+ let plain = item("Plain", Vec::new());+ assert_eq!(title_format(&plain, 0, &t).font_id, theme::medium(13.0));+ assert_eq!(title_format(&plain, 1, &t).font_id, theme::regular(13.0));+ assert_eq!(title_format(&plain, 1, &t).color, t.text);+ assert!(!title_format(&plain, 1, &t).italics);+ let styled = OutlineItem { color: Some([1.0, 0.0, 0.0]), italic: true, bold: true, ..item("Styled", Vec::new()) };+ let f = title_format(&styled, 1, &t);+ assert_eq!(f.font_id, theme::semibold(13.0));+ assert!(f.italics);+ assert_eq!(f.color, egui::Color32::from_rgb(255, 0, 0));+ let half = OutlineItem { color: Some([0.0, 0.5, 0.0]), ..item("Green", Vec::new()) };+ assert_eq!(title_format(&half, 1, &t).color, egui::Color32::from_rgb(0, 128, 0));+ }++ fn item(title: &str, children: Vec<OutlineItem>) -> OutlineItem {+ OutlineItem {+ title: title.into(),+ page: Some(0),+ view: pdfcraft_render::DestView::Top,+ children,+ open: true,+ color: None,+ italic: false,+ bold: false,+ }+ }++ /// Turkish dotted and dotless i match in any case, as in Find (#892).+ #[test]+ fn titles_match_in_any_case_with_turkish_i() {+ let outline = [item("İSTANBUL ŞUBESİ", vec![item("Kış dönemi", vec![])]), item("Ankara", vec![])];+ let fold = pdfcraft_render::text::fold_case;+ assert_eq!(outline_matches(&outline, &fold("istanbul")).len(), 1);+ assert_eq!(outline_matches(&outline, &fold("şubesi")).len(), 1);+ // A child match keeps its parent: [0] and [0, 0].+ assert_eq!(outline_matches(&outline, &fold("KIŞ")).len(), 2);+ assert!(outline_matches(&outline, &fold("izmir")).is_empty());+ }+ }diff --cc crates/ui-egui/src/panels/right.rsindex 000000000,4f6c150c4..81b59e40dmode 000000,100644..100644--- a/crates/ui-egui/src/panels/right.rs+++ b/crates/ui-egui/src/panels/right.rs@@@ -1,0 -1,711 +1,715 @@@+ use super::bookmarks::{BmAction, OutlineCtx, outline_item, outline_matches};+ use super::pages::{page_tools, pages, thumbnail_size};+ use super::*;++ /// Draw the selected right-hand panel and apply its navigation, layer, bookmark or edit actions.+ pub fn right_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) {+ let t = Tokens::get(ui.ctx());+ let Some((index, id)) = app.active_ids() else { return };+ let Some(panel) = app.right else { return };+ let mut nav: Option<Nav> = None;+ let mut close = false;+ let mut toggle_layer: Option<(usize, bool)> = None;+ let mut reset_layers = false;+ let mut attachment_action: Option<(usize, bool)> = None; // (index, open instead of save)+ let mut bm_action: Option<BmAction> = None;+ let mut bm_expand: Option<usize> = None;+ let mut panel_edit: Option<pdfcraft_engine::Edit> = None;+ let mut field_properties = None;+ let mut panel_command: Option<&'static str> = None;+ let mut sig_action: Option<crate::sign_ui::PanelAction> = None;+ let mut a11y_action: Option<crate::a11y_ui::PanelAction> = None;+ let mut compare_action: Option<crate::compare_ui::PanelAction> = None;+ let mut bm_rename = app.bookmark_rename.clone();+ let bm_editable = app.session.get(id).is_some_and(|d| d.allows_assembly() && d.read_only_reason.is_none());+ // Prepare a form is open: the Fields panel orders tabs.+ let preparing = app.is_preparing();+ {+ let Some(doc) = app.session.get(id) else { return };+ let info = &doc.info;+ let view = &mut app.views[index];+ let prefs = &app.comment_prefs;+ let sig_expanded = &mut app.sig_expanded;+ let a11y = &mut app.a11y;+ let tags_state = &mut app.tags_state;+ let compare = &app.compare;+ let comment_allowed = doc.allows_annotation();+ // A dialog or the palette owns the keyboard: the panel leaves Escape to it.+ let modal = app.dialog.is_some() || app.palette_open;+ egui::Frame::NONE+ .fill(t.panel)+ .inner_margin(egui::Margin { left: 14, right: 12, top: 12, bottom: 8 })+ .stroke(Stroke::new(1.0, t.divider))+ .show(ui, |ui| {+ let (title, count) = match panel {+ RightPanel::Comments => ("Comments", Some(crate::comments_panel::count(info))),+ RightPanel::Bookmarks => ("Bookmarks", None),+ RightPanel::Pages => ("Pages", Some(info.pages.len())),+ RightPanel::Fields => ("Fields", Some(info.fields.len())),+ RightPanel::Layers => ("Layers", Some(info.layers.len())),+ RightPanel::Attachments => ("Attachments", Some(info.attachments.len())),+ RightPanel::Signatures => ("Signatures", Some(doc.signatures.iter().filter(|s| s.signed).count())),+ RightPanel::Accessibility => ("Accessibility Checker", None),+ RightPanel::Tags => ("Tags", None),+ RightPanel::Search => ("Search", None),+ RightPanel::Compare => ("Compare", compare.as_ref().filter(|c| c.new == id).map(|c| c.result.changes.len())),+ };+ // Comments count like Acrobat (no replies); the replies go in small text below.+ let replies = if panel == RightPanel::Comments { crate::comments_panel::reply_count(info) } else { 0 };+ ui.horizontal(|ui| {+ ui.vertical(|ui| {+ ui.spacing_mut().item_spacing.y = 0.0;+ ui.horizontal(|ui| {+ ui.label(egui::RichText::new(tl!(title)).font(theme::semibold(15.5)));+ if let Some(c) = count {+ ui.label(egui::RichText::new(c.to_string()).font(theme::medium(13.0)).color(t.text_faint));+ }+ });+ if replies > 0 {+ let text = crate::i18n::trn(crate::i18n::current(), replies as u64, "{n} reply", "{n} replies");+ ui.label(egui::RichText::new(text).font(theme::regular(11.0)).color(t.text_faint));+ }+ });+ if panel == RightPanel::Pages && view.selected.len() > 1 {+ let n = view.selected.len().to_string();+ let picked = crate::i18n::fmt(tl!("{n} pages selected"), &[("n", &n)]);+ ui.label(egui::RichText::new(picked).font(theme::medium(12.0)).color(t.accent_text));+ }+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {+ if icons::button(ui, "x", 26.0, false, tl!("Close")).clicked() {+ close = true;+ }+ if panel == RightPanel::Pages+ && let Some(c) = page_tools(ui, !modal && view.panel_drag.is_none() && bm_editable)+ {+ panel_command = Some(c);+ }+ // Right to left: close, "…", filter, search (Acrobat's order left to right).+ if panel == RightPanel::Comments {+ panel_command = crate::comments_panel::header_controls(ui, info, view, doc.comments_hidden());+ }+ if panel == RightPanel::Comments+ && icons::button(ui, "search", 26.0, view.comments.search.is_some(), tl!("Search comments")).clicked()+ {+ view.comments.search = match view.comments.search {+ Some(_) => None,+ None => Some(String::new()),+ };+ view.comments.search_focus = true;+ }+ if panel == RightPanel::Bookmarks && (bm_editable || !info.outline.is_empty()) {+ let more = icons::button(ui, "ellipsis", 26.0, false, tl!("Bookmark options"));+ egui::Popup::menu(&more).show(|ui| {+ ui.set_min_width(200.0);+ if bm_editable && ui.button(tl!("New bookmarks from structure")).clicked() {+ bm_action = Some(BmAction::FromStructure);+ ui.close();+ }++ if bm_editable && ui.button(tl!("New bookmarks from text styles…")).clicked() {++ bm_action = Some(BmAction::FromTextStyles);++ ui.close();++ }+ if !info.outline.is_empty() {+ for (levels, label) in [+ (usize::MAX, tl!("Expand all bookmarks")),+ (1, tl!("Expand top-level bookmarks")),+ (0, tl!("Collapse all bookmarks")),+ ] {+ if ui.button(label).clicked() {+ bm_expand = Some(levels);+ ui.close();+ }+ }+ }+ });+ }+ if panel == RightPanel::Layers && !info.layers.is_empty() {+ let more = icons::button(ui, "ellipsis", 26.0, false, tl!("Layer options"));+ egui::Popup::menu(&more).show(|ui| {+ ui.set_min_width(200.0);+ if ui.button(tl!("Reset to Initial Visibility")).clicked() {+ reset_layers = true;+ ui.close();+ }+ });+ }+ let new_tip = crate::commands::command_tip(ui.ctx(), tl!("New bookmark ({key})"), "bookmark.add");+ if panel == RightPanel::Bookmarks && bm_editable && icons::button(ui, "bookmark-plus", 26.0, false, &new_tip).clicked() {+ bm_action = Some(BmAction::New);+ }+ });+ });+ ui.add_space(6.0);+ let search_id = egui::Id::unique(("bookmark_search", id.0));+ let mut bookmark_query = ui.data(|d| d.get_temp::<String>(search_id)).unwrap_or_default();+ if panel == RightPanel::Bookmarks && !info.outline.is_empty() {+ ui.horizontal(|ui| {+ const CLEAR: f32 = 26.0;+ let label = ui.label(tl!("Search"));+ let previous = bookmark_query.clone();+ // The panel keeps whatever width its content used, so this row must fit+ // exactly: any overflow would widen the panel again on every repaint.+ let width = ui.available_width() - CLEAR - ui.spacing().item_spacing.x;+ let response = ui.add(egui::TextEdit::singleline(&mut bookmark_query).desired_width(width)).labelled_by(label.id);+ response.widget_info(|| {+ let mut info = egui::WidgetInfo::text_edit(ui.is_enabled(), &previous, &bookmark_query, "");+ info.label = Some(tl!("Search").to_string());+ info+ });+ if icons::button(ui, "x", CLEAR, false, tl!("Clear")).clicked() {+ bookmark_query.clear();+ }+ });+ ui.data_mut(|d| d.insert_temp(search_id, bookmark_query.clone()));+ ui.add_space(6.0);+ }+ let bookmark_query = pdfcraft_render::text::fold_case(bookmark_query.trim());+ let mut bookmark_matches =+ if panel == RightPanel::Bookmarks { outline_matches(&info.outline, &bookmark_query) } else { std::collections::HashSet::new() };+ // A new bookmark must stay nameable even when its initial title doesn't match.+ if let Some((path, _)) = &bm_rename {+ let mut ancestor = path.clone();+ while !ancestor.is_empty() {+ bookmark_matches.insert(ancestor.clone());+ ancestor.pop();+ }+ }+ if panel == RightPanel::Pages {+ let enabled = !modal && view.panel_drag.is_none();+ thumbnail_size(ui, &t, view, enabled);+ }+ egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| match panel {+ RightPanel::Comments => {+ if let Some(e) = crate::comments_panel::show(ui, &t, info, view, prefs, comment_allowed, &mut nav) {+ panel_edit = Some(e);+ }+ }+ RightPanel::Bookmarks => {+ if info.outline.is_empty() {+ empty(ui, &t, "bookmark", "This document has no bookmarks.");+ }+ let mut ctx = OutlineCtx {+ nav: &mut nav,+ action: &mut bm_action,+ rename: &mut bm_rename,+ editable: bm_editable,+ current: view.current,+ expand: bm_expand,+ matches: &bookmark_matches,+ searching: !bookmark_query.is_empty(),+ };+ if ctx.searching && bookmark_matches.is_empty() && !info.outline.is_empty() {+ ui.label(tl!("No matches."));+ }+ for (i, item) in info.outline.iter().enumerate() {+ outline_item(ui, &t, info, item, &[i], info.outline.len(), &mut ctx);+ }+ if info.outline_more {+ ui.label(tl!("Some bookmarks are not shown here: the panel lists a limited number, nested a limited depth."));+ }+ }+ RightPanel::Pages => pages(ui, &t, info, view, modal, bm_editable, &mut nav),+ RightPanel::Fields => field_properties = fields(ui, &t, info, &doc.form, preparing, &mut view.prepare, &mut nav, &mut panel_edit),+ RightPanel::Layers => {+ if info.layers.is_empty() {+ empty(ui, &t, "layers", "This document has no layers.");+ }+ for (li, l) in info.layers.iter().enumerate() {+ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 32.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, l.visible, &l.name));+ let press = theme::Press::track(ui, &resp);+ press.wash(ui, rect, 6, false);+ let body = rect.translate(press.offset());+ icons::paint(+ ui,+ Rect::from_min_size(body.min + vec2(4.0, 7.0), vec2(18.0, 18.0)),+ if l.visible { "eye" } else { "eye-off" },+ 16.0,+ t.icon,+ );+ let fg = if l.visible { t.text } else { t.text_faint };+ crate::widgets::paint_left(+ ui,+ body.left_center() + vec2(32.0, 0.0),+ &l.name,+ theme::regular(13.0),+ fg,+ (rect.width() - 40.0).max(0.0),+ );+ if theme::hand(resp).on_hover_text(if l.visible { tl!("Hide layer") } else { tl!("Show layer") }).clicked() {+ toggle_layer = Some((li, !l.visible));+ }+ }+ }+ RightPanel::Signatures => {+ sig_action = crate::sign_ui::panel(ui, &t, &doc.signatures, sig_expanded);+ }+ RightPanel::Accessibility => {+ a11y_action = crate::a11y_ui::panel(ui, &t, a11y, id);+ }+ RightPanel::Tags => {+ let tags = tags_state.tags(doc);+ let content = tags_state.content(doc);+ let (page, edit) = crate::tags_ui::panel(ui, &t, id, &tags, &content, tags_state, doc.allows_modification());+ if let Some(page) = page {+ nav = Some(Nav::Page(page));+ }+ panel_edit = edit;+ }+ RightPanel::Search => crate::search_ui::panel(ui, &t, view, info.pages.len()),+ RightPanel::Compare => compare_action = crate::compare_ui::panel(ui, &t, compare, id),+ RightPanel::Attachments => {+ let attachable = doc.allows_modification() && doc.read_only_reason.is_none();+ if attachable {+ egui::Frame::NONE.inner_margin(egui::Margin::symmetric(4, 6)).show(ui, |ui| {+ if ui.add(egui::Button::new(tl!("Attach a file…"))).clicked() {+ panel_command = Some("edit.attach");+ }+ });+ }+ if info.attachments.is_empty() {+ empty(ui, &t, "paperclip", "This document has no attachments.");+ }+ for (ai, a) in info.attachments.iter().enumerate() {+ let is_pdf = a.name.to_lowercase().ends_with(".pdf");+ // Only an attachment of the document itself can be deleted here.+ let deletable = match &a.source {+ pdfcraft_render::AttachmentSource::Document { key } if attachable => Some(key),+ _ => None,+ };+ // The whole row answers a double-click and a right-click (#3466), below+ // its buttons, which still take their own clicks.+ let mut buttons: Vec<egui::Response> = Vec::new();+ let row = ui.scope_builder(egui::UiBuilder::new().sense(Sense::click()), |ui| {+ egui::Frame::NONE.inner_margin(egui::Margin::symmetric(4, 6)).show(ui, |ui| {+ ui.horizontal(|ui| {+ ui.add(icons::image("paperclip", 16.0, t.icon));+ ui.vertical(|ui| {+ ui.set_width(ui.available_width() - 70.0);+ // Not selectable, so a click on the name or the details reaches the row.+ ui.add(+ egui::Label::new(egui::RichText::new(&a.name).font(theme::medium(13.0))).truncate().selectable(false),+ );+ let mut meta = a.size.map(human_size).unwrap_or_default();+ if let pdfcraft_render::AttachmentSource::Annotation { page, .. } = a.source {+ let on_page = crate::i18n::fmt(+ tl!("on page {label}"),+ &[("label", info.pages.get(page).map(|p| p.label.as_str()).unwrap_or("?"))],+ );+ meta = format!("{meta} · {on_page}");+ }+ if let Some(d) = &a.description {+ meta = format!("{meta} · {d}");+ }+ ui.add(+ egui::Label::new(egui::RichText::new(meta).color(t.text_faint).small()).truncate().selectable(false),+ );+ });+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {+ let save = icons::button(ui, "file-down", 28.0, false, tl!("Save attachment…"));+ if save.clicked() {+ attachment_action = Some((ai, false));+ }+ buttons.push(save);+ if is_pdf {+ let open = icons::button(ui, "file-input", 28.0, false, tl!("Open in a new tab"));+ if open.clicked() {+ attachment_action = Some((ai, true));+ }+ buttons.push(open);+ }+ if let Some(key) = deletable {+ let delete = icons::button(ui, "trash-2", 28.0, false, tl!("Delete attachment"));+ if delete.clicked() {+ panel_edit = Some(pdfcraft_engine::Edit::DeleteAttachment { key: key.clone() });+ }+ buttons.push(delete);+ }+ });+ });+ })+ });+ // A double-click opens a PDF in a new tab, as Acrobat opens an attachment;+ // any other file is saved, since PdfCraft opens only PDFs.+ if row.response.double_clicked() {+ attachment_action = Some((ai, is_pdf));+ }+ // A right-click on one of the row's buttons is a right-click on the row:+ // the union keeps the row's id, so it is one menu either way.+ let menu = buttons.into_iter().fold(row.response.clone(), |row, button| row | button);+ menu.context_menu(|ui| {+ if is_pdf && ui.button(tl!("Open in a new tab")).clicked() {+ attachment_action = Some((ai, true));+ ui.close();+ }+ if ui.button(tl!("Save attachment…")).clicked() {+ attachment_action = Some((ai, false));+ ui.close();+ }+ if let Some(key) = deletable+ && ui.button(tl!("Delete attachment")).clicked()+ {+ panel_edit = Some(pdfcraft_engine::Edit::DeleteAttachment { key: key.clone() });+ ui.close();+ }+ });+ }+ }+ });+ });+ }+ if close {+ app.choose_right_panel(None);+ }+ if let Some(e) = panel_edit {+ app.apply_edit(e);+ }+ if let Some((name, widget)) = field_properties {+ app.open_field_props(&name, widget);+ }+ if let Some(c) = panel_command {+ app.run_command(c);+ }+ if let Some(a) = a11y_action {+ app.a11y_action(index, a);+ }+ if let Some(a) = compare_action {+ app.compare_action(index, a);+ }+ match sig_action {+ Some(crate::sign_ui::PanelAction::Validate) => app.run_command("sign.validate"),+ Some(crate::sign_ui::PanelAction::GoTo(p)) => app.views[index].go_to_page(p),+ Some(crate::sign_ui::PanelAction::Trust(c)) => app.trust_certificate(*c),+ Some(crate::sign_ui::PanelAction::ViewCertificate(chain)) => {+ app.cert_viewer = Some(crate::sign_ui::CertViewer { chain, selected: 0, tab: crate::sign_ui::CertTab::Summary });+ app.dialog = Some(crate::Dialog::CertificateViewer);+ }+ Some(crate::sign_ui::PanelAction::ViewSigned { len, revision }) => app.view_signed_version(len, revision),+ Some(crate::sign_ui::PanelAction::Sign(field)) => {+ let page = app.views[index].current;+ app.start_signing(page, None, Some(field), None);+ }+ Some(crate::sign_ui::PanelAction::ExportCertificate(c)) => {+ app.export_certificate(&c);+ }+ None => {}+ }+ if let Some((p, i)) = app.views.get_mut(index).and_then(|v| v.comments.default_request.take()) {+ app.make_comment_default(p, i);+ }+ if let Some((p, i, open)) = app.views.get_mut(index).and_then(|v| v.comments.attachment_request.take()) {+ app.comment_attachment_action(id, p, i, open);+ }+ if let Some((p, i)) = app.views.get_mut(index).and_then(|v| v.comments.props_request.take()) {+ app.open_comment_props(p, i);+ }+ app.bookmark_rename = bm_rename;+ if let Some(a) = bm_action {+ app.bookmark_action(a);+ }+ if let Some((ai, open)) = attachment_action {+ app.attachment_action(id, ai, open);+ }+ if let Some((layer, visible)) = toggle_layer+ && app.session.set_layer_visible(id, layer, visible)+ {+ app.views[index].invalidate_content();+ }+ if reset_layers && app.session.reset_layers(id) {+ app.views[index].invalidate_content();+ }+ match nav {+ Some(Nav::Page(p)) => app.views[index].go_to_page(p),+ Some(Nav::Dest(p, dest)) => match app.session.get(id) {+ Some(doc) => app.views[index].go_to_dest(p, dest, &doc.info),+ None => app.views[index].go_to_page(p),+ },+ Some(Nav::Flash(p, r)) => {+ let v = &mut app.views[index];+ if let Some(doc) = app.session.get(id) {+ v.reveal_rect(p, r, &doc.info);+ } else {+ v.go_to_page(p);+ }+ v.flash = Some((p, r, 0.0));+ }+ None => {}+ }+ }++ fn empty(ui: &mut egui::Ui, t: &Tokens, icon: &str, text: &str) {+ ui.add_space(40.0);+ ui.vertical_centered(|ui| {+ ui.add(icons::image(icon, 36.0, t.text_faint));+ ui.add_space(8.0);+ // Every empty-panel message goes through here.+ ui.label(egui::RichText::new(tl!(text)).color(t.text_muted));+ });+ }++ /// The Fields panel: fields by page, in tab order. While preparing a form, each field can move+ /// earlier or later in its page's tab order (Acrobat: Order Tabs Manually).+ #[allow(clippy::too_many_arguments)]+ fn fields(+ ui: &mut egui::Ui,+ t: &Tokens,+ info: &DocInfo,+ form: &[pdfcraft_engine::FormField],+ preparing: bool,+ selection: &mut crate::prepare::PrepareView,+ nav: &mut Option<Nav>,+ edit: &mut Option<pdfcraft_engine::Edit>,+ ) -> Option<(String, usize)> {+ let mut properties = None;+ if info.fields.is_empty() {+ empty(ui, t, "text-cursor-input", "This document has no form fields.");+ return None;+ }+ let rows = field_rows(&info.fields, form);+ if preparing {+ ui.label(egui::RichText::new(tl!("Tab order: move a field with its arrows.")).small().color(t.text_muted));+ ui.label(egui::RichText::new(tl!("Shift- or Ctrl/Command-click to select several fields.")).small().color(t.text_muted));+ let names = selection.names();+ // Keep the field rows in place when the first click selects a field, so the+ // second click of a double-click still lands on the same row.+ ui.horizontal(|ui| {+ ui.label(crate::i18n::fmt(tl!("{n} selected"), &[("n", &names.len().to_string())]));+ if ui.add_enabled(!names.is_empty(), egui::Button::new(tl!("Properties…"))).clicked() {+ properties = selection.selected.clone();+ }+ });+ }+ for (p, page_rows) in rows {+ // A field's /P can name a page the document doesn't have (#1307); it reads as unplaced.+ let label = p+ .and_then(|p| info.pages.get(p))+ .map(|page| crate::i18n::fmt(tl!("Page {label}"), &[("label", &page.label)]))+ .unwrap_or_else(|| tl!("Unplaced").to_string());+ ui.add_space(4.0);+ ui.label(egui::RichText::new(label).font(theme::semibold(12.5)).color(t.text_muted));+ for (f, key) in page_rows {+ let selected = key.as_ref().is_some_and(|key| selection.selected.as_ref() == Some(key) || selection.also.contains(key));+ let icon = match f.kind {+ FieldKind::Text => "text-cursor-input",+ FieldKind::CheckBox => "check-circle-2",+ FieldKind::Radio => "circle",+ FieldKind::PushButton => "square",+ FieldKind::Combo => "chevron-down",+ FieldKind::List => "list",+ FieldKind::Signature => "signature",+ FieldKind::Unknown => "square",+ };+ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 30.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &f.name));+ // A row scrolled out of view still takes clicks and keyboard focus, but isn't drawn:+ // laying out every row of a large form each frame took a tenth of a second a frame.+ let visible = ui.is_rect_visible(rect);+ if visible {+ let press = theme::Press::track(ui, &resp);+ press.wash(ui, rect, 6, selected);+ let body = rect.translate(press.offset());+ icons::paint(ui, Rect::from_min_size(body.min + vec2(8.0, 7.0), vec2(16.0, 16.0)), icon, 15.0, Color32::from_rgb(0x8E, 0x4E, 0xE6));+ let value =+ f.value.as_ref().map(|v| if v.chars().count() > 18 { format!("{}…", v.chars().take(17).collect::<String>()) } else { v.clone() });+ let value_font = theme::regular(11.5);+ let value_w = value.as_ref().map(|v| crate::widgets::text_width(ui, v, &value_font)).unwrap_or(0.0);+ let arrows = if preparing && f.page.is_some() { 56.0 } else { 0.0 };+ let max_w = (rect.width() - 32.0 - value_w - arrows - 16.0).max(0.0);+ crate::widgets::paint_left(ui, body.left_center() + vec2(32.0, 0.0), &f.name, theme::regular(13.0), t.text, max_w);+ if let Some(v) = value {+ let x = if arrows > 0.0 { 64.0 } else { 8.0 };+ ui.painter().text(body.right_center() - vec2(x, 0.0), Align2::RIGHT_CENTER, v, value_font, t.text_faint);+ }+ }+ if preparing && f.page.is_some() {+ let up = Rect::from_center_size(rect.right_center() - vec2(44.0, 0.0), vec2(22.0, 22.0));+ let down = Rect::from_center_size(rect.right_center() - vec2(20.0, 0.0), vec2(22.0, 22.0));+ for (r, icon, earlier, tip) in+ [(up, "chevron-up", true, tl!("Earlier in tab order")), (down, "chevron-down", false, tl!("Later in tab order"))]+ {+ let b = ui.interact(r, ui.scope_id().with((&f.name, earlier)), Sense::click());+ b.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("{tip}: {}", f.name)));+ if visible {+ let bpress = theme::Press::track(ui, &b);+ bpress.wash(ui, r, 4, false);+ icons::paint(ui, r.shrink(3.0).translate(bpress.offset()), icon, 15.0, t.icon);+ }+ if theme::hand(b).on_hover_text(tip).clicked() {+ *edit = Some(pdfcraft_engine::Edit::MoveInTabOrder { name: f.name.clone(), earlier });+ }+ }+ }+ if preparing && resp.double_clicked() && !ui.input(|i| i.modifiers.shift || i.modifiers.command) {+ if let Some(key) = key {+ if !selected {+ selection.select(key.clone(), false);+ }+ properties = Some(key);+ }+ } else if preparing+ && resp.clicked()+ && let Some(key) = key+ {+ selection.select(key, ui.input(|i| i.modifiers.shift || i.modifiers.command));+ }+ let resp = theme::hand(resp);+ // Only a row in view can be hovered: its tip isn't built for the others.+ let resp = if visible { resp.on_hover_text(field_tip(f)) } else { resp };+ if resp.clicked()+ && let (Some(p), Some(r)) = (f.page, f.rect)+ {+ *nav = Some(Nav::Flash(p, r));+ }+ }+ }+ properties+ }++ /// A Fields panel row's tooltip: the field's kind, its own tooltip and whether it has scripts.+ fn field_tip(f: &pdfcraft_render::Field) -> String {+ let kind = format!("{:?}", f.kind);+ let mut tip = crate::i18n::fmt(tl!("{kind} field"), &[("kind", tl!(&kind))]);+ if let Some(tt) = &f.tooltip {+ tip.push_str(&format!(" — {tt}"));+ }+ if f.has_actions {+ tip.push_str(&format!("\n{}", tl!("Has JavaScript actions (run in M6)")));+ }+ tip+ }++ /// One page's rows of the Fields panel: each field, with the form field and widget a click on+ /// it selects (`None` when the form has no widget of it on that page).+ type FieldRows<'a> = Vec<(&'a pdfcraft_render::Field, Option<(String, usize)>)>;++ /// The Fields panel's rows: by page ("Unplaced" first), each page's in tab order. A row is paired+ /// with the first form field of its name, as the engine pairs them: one map, built once a frame.+ /// Searching the form for each row, and again inside the sort, was O(fields²) every frame.+ fn field_rows<'a>(fields: &'a [pdfcraft_render::Field], form: &[pdfcraft_engine::FormField]) -> Vec<(Option<usize>, FieldRows<'a>)> {+ let mut by_name: std::collections::HashMap<&str, &pdfcraft_engine::FormField> = std::collections::HashMap::with_capacity(form.len());+ for field in form {+ by_name.entry(field.name.as_str()).or_insert(field);+ }+ let rank = |name: &str| by_name.get(name).and_then(|f| f.widgets.iter().map(|w| w.tab).min()).unwrap_or(usize::MAX);+ let mut ordered: Vec<&pdfcraft_render::Field> = fields.iter().collect();+ ordered.sort_by_cached_key(|f| (f.page, rank(&f.name)));+ let mut rows: Vec<(Option<usize>, FieldRows<'a>)> = Vec::new();+ for f in ordered {+ let key =+ by_name.get(f.name.as_str()).and_then(|field| field.widgets.iter().position(|w| w.page == f.page).map(|wi| (field.name.clone(), wi)));+ match rows.last_mut() {+ Some((page, page_rows)) if *page == f.page => page_rows.push((f, key)),+ _ => rows.push((f.page, vec![(f, key)])),+ }+ }+ rows+ }++ #[cfg(test)]+ mod field_rows {+ use super::field_rows;+ use std::sync::Arc;++ /// A PDF of `objects` (numbered from 1; object 1 the catalog) with a valid xref table.+ fn pdf(objects: &[String]) -> Vec<u8> {+ let mut out = b"%PDF-1.7\n".to_vec();+ let mut offsets = Vec::new();+ for (i, o) in objects.iter().enumerate() {+ offsets.push(out.len());+ out.extend(format!("{} 0 obj\n{o}\nendobj\n", i + 1).bytes());+ }+ let xref = out.len();+ out.extend(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).bytes());+ for o in offsets {+ out.extend(format!("{o:010} 00000 n \n").bytes());+ }+ out.extend(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).bytes());+ out+ }++ /// The fields the engine reads from `bytes`: the inspector's list and the form.+ fn open(bytes: Vec<u8>) -> (Vec<pdfcraft_render::Field>, Arc<Vec<pdfcraft_engine::FormField>>) {+ let mut session = pdfcraft_engine::Session::new();+ let id = session.open("form.pdf", None, Arc::new(bytes), None).expect("opens");+ let doc = session.get(id).expect("open");+ (doc.info.fields.clone(), doc.form.clone())+ }++ /// Rows go by page, the unplaced first, each page's in tab order (here its annotation order,+ /// not the `/Fields` order), and a row selects the first form field of its name.+ #[test]+ fn rows_follow_pages_and_tab_order() {+ let widget = |name: &str, page: Option<usize>| match page {+ Some(p) => format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T ({name}) /Rect [10 10 90 30] /P {} 0 R >>", 3 + p),+ None => format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T ({name}) /Rect [10 10 90 30] >>"),+ };+ let bytes = pdf(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 7 0 R 8 0 R 9 0 R 10 0 R 6 0 R] >> >>".into(),+ "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>".into(),+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [6 0 R 5 0 R] >>".into(),+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [7 0 R 8 0 R 9 0 R] >>".into(),+ widget("a1", Some(0)),+ widget("a2", Some(0)),+ widget("b", Some(1)),+ widget("twin", Some(1)),+ widget("twin", Some(1)),+ widget("loose", None),+ ]);+ let (fields, form) = open(bytes);+ // A page's rows as (field name, the form field and widget a click selects).+ type Named<'a> = Vec<(&'a str, Option<(String, usize)>)>;+ let rows: Vec<(Option<usize>, Named)> = field_rows(&fields, &form)+ .into_iter()+ .map(|(page, rows)| (page, rows.into_iter().map(|(f, key)| (f.name.as_str(), key)).collect()))+ .collect();+ let key = |name: &str| Some((name.to_string(), 0));+ assert_eq!(+ rows,+ [+ (None, vec![("loose", key("loose"))]),+ (Some(0), vec![("a2", key("a2")), ("a1", key("a1"))]),+ (Some(1), vec![("b", key("b")), ("twin", key("twin")), ("twin", key("twin"))]),+ ]+ );+ }++ /// The panel's rows for a large form take milliseconds: looking each row's field up in the+ /// form, there and inside the sort, was O(fields²) every frame.+ #[test]+ fn rows_for_a_large_form_are_quick() {+ const PAGES: usize = 150;+ const PER_PAGE: usize = 100;+ let mut objects = vec![String::new(), String::new()];+ let page = |p: usize| 3 + p;+ let field = |p: usize, k: usize| 3 + PAGES + p * PER_PAGE + k;+ let mut all = Vec::new();+ for p in 0..PAGES {+ let annots: Vec<String> = (0..PER_PAGE).map(|k| format!("{} 0 R", field(p, k))).collect();+ all.extend(annots.iter().cloned());+ objects.push(format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [{}] >>", annots.join(" ")));+ }+ for p in 0..PAGES {+ for k in 0..PER_PAGE {+ objects.push(format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T (field{p}_{k}) /Rect [10 10 90 30] /P {} 0 R >>", page(p)));+ }+ }+ // `/Fields` in no particular order, so the rows must be sorted.+ let mut seed = 12345u64;+ for i in (1..all.len()).rev() {+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);+ all.swap(i, (seed >> 33) as usize % (i + 1));+ }+ objects[0] = format!("<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [{}] >> >>", all.join(" "));+ let kids: Vec<String> = (0..PAGES).map(|p| format!("{} 0 R", page(p))).collect();+ objects[1] = format!("<< /Type /Pages /Kids [{}] /Count {PAGES} >>", kids.join(" "));+ let (fields, form) = open(pdf(&objects));+ assert_eq!(fields.len(), PAGES * PER_PAGE);+ let (tx, rx) = std::sync::mpsc::channel();+ std::thread::spawn(move || {+ let rows = field_rows(&fields, &form);+ let _ = tx.send((rows.len(), rows.iter().map(|(_, r)| r.len()).sum::<usize>()));+ });+ let counted = rx.recv_timeout(std::time::Duration::from_secs(3)).expect("the Fields panel's rows must not take seconds a frame");+ assert_eq!(counted, (PAGES, PAGES * PER_PAGE));+ }+ }diff --cc crates/ui-egui/src/state.rsindex 000000000,dd3b3e90a..3bbe8301amode 000000,100644..100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@@ -1,0 -1,417 +1,419 @@@+ use super::*;++ /// Top-level workspace modes (Acrobat's mode bar).+ #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+ #[serde(rename_all = "lowercase")]+ pub enum Mode {+ #[serde(rename = "all")]+ AllTools,+ Read,+ Edit,+ Convert,+ Sign,+ }++ impl Mode {+ pub(crate) fn parse(value: &str) -> Option<Self> {+ match value {+ "all" => Some(Self::AllTools),+ "read" => Some(Self::Read),+ "edit" => Some(Self::Edit),+ "convert" => Some(Self::Convert),+ "sign" => Some(Self::Sign),+ _ => None,+ }+ }+ }++ /// What the left panel shows.+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]+ pub enum LeftPanel {+ AllTools,+ Tool(&'static str),+ /// Prepare a form ▸ Calculation order, a page of its own; Back returns to Prepare a form.+ CalculationOrder,+ }++ /// Right-hand panels, opened from the rail.+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]+ pub enum RightPanel {+ Comments,+ Bookmarks,+ Pages,+ Fields,+ Layers,+ Attachments,+ Signatures,+ /// Accessibility Checker results.+ Accessibility,+ /// Reachable PDF structure tags and their properties.+ Tags,+ /// Advanced Search results.+ Search,+ /// Compare files: the differences.+ Compare,+ }++ /// Quick-action bar tools (the vertical floating strip).+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]+ pub enum QuickTool {+ Select,+ Hand,+ /// A commenting tool (Add comments).+ Comment(comments::CommentTool),+ Measure(measure_ui::Tool),+ /// Crop pages by dragging a rectangle.+ Crop,+ /// Scan & OCR ▸ Enhance ▸ Camera image: drag four corners, then Enhance page.+ EnhanceCamera,+ /// A Fill & Sign tool.+ Fill(fill_sign::FillTool),+ /// A Prepare a form field tool.+ Field(prepare::FieldTool),+ /// Redact text and images (drag across text or draw a box).+ Redact,+ /// Edit a PDF ▸ Add content ▸ Text.+ AddText,+ /// Edit a PDF ▸ Edit text: click a line of existing text to edit it.+ EditText,+ /// Add a stamp: click to place this stamp.+ Stamp(pdfcraft_engine::StampKind),+ /// A custom stamp from the library (its index).+ CustomStamp(usize),+ /// Edit a PDF ▸ Link: draw link areas, select and edit links.+ Link,+ /// Use a certificate ▸ Digitally sign / Certify (visible): drag the signature's rectangle.+ SignArea {+ certify: bool,+ },+ /// View ▸ Zoom ▸ Marquee Zoom.+ MarqueeZoom,+ /// Edit ▸ Take a Snapshot.+ Snapshot,+ /// Edit ▸ Column Select: drag a rectangle to select only the text inside it (#740). The+ /// Select tool does the same while Alt/Option is held at the start of a drag.+ ColumnSelect,+ }++ /// A file dropped on a page grid: its name, and its bytes or, for a file on disk, the path they are+ /// read from when the file's turn to be inserted comes (so a long drop holds one file at a time).+ pub(crate) type GridFile = (String, Result<Vec<u8>, std::path::PathBuf>);++ #[derive(Clone, Copy, Debug, PartialEq, Eq)]+ pub enum Dialog {+ WordCount,+ CreateImages,+ Properties(PropsTab),+ About,+ Shortcuts,+ Split,+ /// Pages ▸ Number pages… (page labels).+ NumberPages,+ /// Protect Using Password.+ Protect,++ /// Bookmarks ▸ New bookmarks from text styles (#1693).++ BookmarksFromTextStyles,+ /// Set Page Boxes (crop, trim, bleed, art, media).+ PageBoxes,+ /// Add / Update Header and Footer, Watermark, Background.+ Marks(pdfcraft_engine::MarkKind),+ /// Export a PDF ▸ Image / Text.+ Export(export_ui::ExportKind),+ /// Fill & Sign ▸ Create signature (the drawing pad).+ Signature,+ /// Comment Properties.+ CommentProps,+ /// Replace Pages (after choosing the file).+ ReplacePages,+ /// Prepare a form ▸ Field Properties.+ FieldProps,+ /// Shared properties of several selected form fields.+ BulkFieldProps,+ /// Redact a PDF ▸ Redact pages, Find text and redact, Set properties, apply confirmation.+ RedactPages,+ RedactSearch,+ RedactProps,+ RedactApply,+ /// File ▸ Print.+ Print,+ /// File ▸ Revert confirmation.+ Revert,+ /// Save over a file that changed on disk since the document came from it (#2166).+ OverwriteChanged,+ /// Link Properties.+ LinkProps,+ /// Organize ▸ Extract (options), Rotate Pages.+ Extract,+ RotatePages,+ /// Remove Hidden Information and Sanitize Document.+ RemoveHidden,+ Sanitize,+ /// Documents from a session that ended unexpectedly.+ Recovery,+ /// Comments ▸ Summarize comments (options).+ SummarizeComments,+ /// Sign with a Digital ID ▸ Configure ▸ Sign as.+ Sign,+ /// Optimize PDF ▸ Advanced optimization.+ Optimize,+ /// Prepare a form ▸ right-click a field ▸ Duplicate.+ DuplicateField,+ /// Prepare a form ▸ Text field table: a movable window rather than a modal (`field_table_ui`).+ FieldTable,+ /// Check for accessibility ▸ Accessibility Checker Options.+ AccessibilityOptions,+ /// Scan & OCR ▸ Recognize text.+ RecognizeText,+ /// The JavaScript console (⌘J).+ JsConsole,+ /// Document JavaScripts.+ DocumentJs,+ /// Preferences.+ Preferences,+ /// Compare files: choose the older version.+ CompareFiles,+ /// Action Wizard.+ ActionWizard,+ /// Standards ▸ PDF/A.+ PdfA,+ /// Custom stamps ▸ Create.+ CreateStamp,+ /// Prepare for accessibility ▸ Add alternate text.+ AltText,+ /// PDF Optimizer ▸ Audit space usage (then back to the optimizer).+ AuditSpace,+ /// Signatures ▸ Show certificate.+ CertificateViewer,+ }++ #[derive(Clone, Copy, Debug, PartialEq, Eq)]+ pub enum PropsTab {+ Description,+ InitialView,+ Security,+ Fonts,+ Custom,+ Advanced,+ SpaceAudit,+ }++ /// Document Properties ▸ Custom being edited: the properties as they will be after OK, in order,+ /// and the Name and Value fields.+ #[derive(Clone, Debug, Default, PartialEq)]+ pub struct CustomDraft {+ pub props: Vec<(String, String)>,+ pub name: String,+ pub value: String,+ }++ /// Duplicate Field: the field and the pages (all, or a range, 1-based).+ #[derive(Clone, Debug, PartialEq)]+ pub struct DuplicateDraft {+ pub name: String,+ pub all: bool,+ pub from: usize,+ pub to: usize,+ }++ /// Copied pages: their document's name and bytes (as it was when copied) and the pages.+ #[derive(Clone, Debug)]+ pub struct PageClip {+ /// The document the pages were copied from: pasting back into it keeps field names.+ pub from: DocId,+ pub name: String,+ pub bytes: std::sync::Arc<Vec<u8>>,+ pub pages: Vec<usize>,+ }++ /// One page of a whole-document copy: its text as read for display, to read, or not to try+ /// (reading it failed before).+ pub(crate) enum CopyPage {+ Read(std::sync::Arc<pdfcraft_render::PageText>),+ ToRead,+ Skip,+ }++ /// What a whole-document copy needs, taken from the view on the UI thread: each page's text+ /// layer as far as it was read, and the document to read the others from.+ pub(crate) struct DocumentCopyJob {+ pub(crate) pages: Vec<CopyPage>,+ bytes: std::sync::Arc<Vec<u8>>,+ password: Option<std::sync::Arc<str>>,+ }++ impl DocumentCopyJob {+ pub(crate) fn of(v: &DocView, doc: &pdfcraft_engine::Document) -> DocumentCopyJob {+ let pages = (0..v.page_count())+ .map(|p| match v.texts.get(&p) {+ Some(t) => CopyPage::Read(t.clone()),+ None if v.text_failed.contains(&p) => CopyPage::Skip,+ None => CopyPage::ToRead,+ })+ .collect();+ DocumentCopyJob { pages, bytes: doc.bytes.clone(), password: doc.password.as_deref().map(std::sync::Arc::from) }+ }++ /// The document's text in page order, a page per line run. Each page read here is let go+ /// once its text is taken, so a large document never holds every page's text layer at once.+ /// `None` when `cancel` was set.+ pub(crate) fn text(self, cancel: &std::sync::atomic::AtomicBool) -> Option<String> {+ let mut renderer: Option<pdfcraft_render::PageRenderer> = None;+ let mut out = String::new();+ let mut push = |text: String| {+ if !text.is_empty() {+ if !out.is_empty() {+ out.push('\n');+ }+ out.push_str(&text);+ }+ };+ for (page, p) in self.pages.into_iter().enumerate() {+ if cancel.load(std::sync::atomic::Ordering::Relaxed) {+ return None;+ }+ match p {+ CopyPage::Read(t) => push(t.text_of(0..t.glyphs.len())),+ CopyPage::ToRead => {+ let r = renderer.get_or_insert_with(|| {+ let config = pdfcraft_render::RenderConfig { password: self.password.clone(), ..Default::default() };+ pdfcraft_render::PageRenderer::new(self.bytes.clone(), config)+ });+ let req = pdfcraft_render::RenderRequest {+ page,+ kind: pdfcraft_render::RequestKind::Text,+ tile: None,+ scale: 1.0,+ tag: 0,+ preview: false,+ };+ if let Some(t) = r.render(req).text {+ push(t.text_of(0..t.glyphs.len()));+ }+ }+ CopyPage::Skip => {}+ }+ }+ Some(out)+ }+ }++ pub struct PasswordPrompt {+ pub name: String,+ pub path: Option<String>,+ pub bytes: std::sync::Arc<Vec<u8>>,+ #[cfg(not(target_arch = "wasm32"))]+ pub(crate) stamp: Option<file_watch::Stamp>,+ pub input: String,+ pub error: Option<String>,+ /// A late startup file must stay in the background even after it is unlocked.+ pub(crate) activate: bool,+ /// The bytes are a recovery snapshot: once the document is open it takes the snapshot's+ /// path and recovery entry. Cancelling the prompt drops the association with it (#813).+ pub(crate) recovered: Option<RecoveryMeta>,+ /// The tool that asked for this file (a tool chosen with no document open): it runs once+ /// the document is unlocked.+ pub(crate) then: Option<&'static str>,+ /// A link destination to apply after the linked PDF is unlocked.+ pub(crate) after_open: Option<pdfcraft_render::RemoteDestination>,+ }++ #[cfg(not(target_arch = "wasm32"))]+ pub(crate) struct OpenRequest {+ pub(crate) name: String,+ pub(crate) path: Option<String>,+ pub(crate) stamp: Option<file_watch::Stamp>,+ pub(crate) input: open_worker::Input,+ pub(crate) password: Option<String>,+ pub(crate) activate: bool,+ pub(crate) after_open: Option<pdfcraft_render::RemoteDestination>,+ pub(crate) recovered: Option<RecoveryMeta>,+ pub(crate) then: Option<&'static str>,+ }++ /// Asks for the permissions password of an open document whose security restricts it, which+ /// lifts the restrictions (#995). Acrobat asks for it when such a document's security is changed.+ pub struct UnlockPrompt {+ pub doc: DocId,+ pub name: String,+ pub input: String,+ pub error: Option<String>,+ /// The command to run once unlocked (Protect using password, Remove security), if any.+ pub then: Option<&'static str>,+ }++ impl UnlockPrompt {+ pub(crate) fn new(doc: &pdfcraft_engine::Document, then: Option<&'static str>) -> Self {+ Self { doc: doc.id, name: doc.name.clone(), input: String::new(), error: None, then }+ }+ }++ #[derive(serde::Serialize, serde::Deserialize)]+ pub struct RecentFile {+ pub name: String,+ pub path: String,+ pub pages: usize,+ pub size: usize,+ }++ /// Where in a document a request to open an address came from.+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]+ pub enum LinkOrigin {+ /// A link on the page.+ Link,+ /// A push button's URI action.+ Button,+ /// A script (`app.launchURL`).+ Script,+ }++ impl LinkOrigin {+ pub(crate) fn noun(self) -> &'static str {+ match self {+ Self::Link => "A link",+ Self::Button => "A button",+ Self::Script => "A script",+ }+ }+ }++ /// An address a document asked to open, waiting for the user to allow or cancel it.+ #[derive(Clone, Debug, PartialEq, Eq)]+ pub struct PendingLink {+ pub url: String,+ pub origin: LinkOrigin,+ }++ /// A resolved local target and its original source/destination, independent of the active tab.+ #[derive(Clone, Debug)]+ pub struct PendingRemoteLink {+ pub source: DocId,+ pub path: std::path::PathBuf,+ pub destination: pdfcraft_render::RemoteDestination,+ }++ /// Settings for the Number pages dialog.+ #[derive(Clone, Debug, PartialEq)]+ pub struct NumberDraft {+ pub from: usize,+ pub to: usize,+ pub style: pdfcraft_engine::LabelStyle,+ pub prefix: String,+ pub start: u32,+ }++ /// What [`PdfCraftApp::open_path`] did: opened the file in a new tab, focused the tab already+ /// showing it, handed it to the background open worker, or failed. Failures tell the user+ /// through a toast; this is the programmatic contract for callers that must know (the control+ /// channel, tools that wait for a file) (#1620).+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]+ pub enum OpenOutcome {+ /// The file opened in a new tab (or raised its password prompt).+ Opened,+ /// A tab already showed the file; it was focused and no tab was added.+ Focused,+ /// The file was accepted for opening in the background; its tab appears when the open+ /// completes (`ui.state.pending_opens` lists the files on the way).+ Pending,+ /// The file could not be read or opened; the user was told.+ Failed,+ }