Skip to content

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

Merge main into feat/align-selected-lines

RiceDee6733d9eaee7e
diff --cc crates/automation/src/dispatch.rs
index 000000000,26e1f9536..4e907478d
mode 000000,100644..100644
--- a/crates/automation/src/dispatch.rs
+++ b/crates/automation/src/dispatch.rs
@@@ -1,0 -1,784 +1,784 @@@
+ use super::error::{Result, ToolError, failed};
+ use super::json::{Args, document_attachment_keys, info, one_based, parse_style_ranges, security, summary};
+ use super::paths::{read_input, write_atomic};
+ use super::*;
+
+ /// One piece of a tool's result.
+ #[derive(Clone, Debug, PartialEq)]
+ pub enum Content {
+ /// Structured data (MCP: a text block with the JSON plus `structuredContent`).
+ Json(Value),
+ /// A PNG image.
+ Png { data: Vec<u8>, width: u32, height: u32 },
+ }
+
+ impl Automation {
+ /// Run the tool `name` with JSON `args` (an object; `null` means no arguments).
+ pub fn call(&mut self, name: &str, args: &Value) -> Result<Vec<Content>> {
+ let empty = json!({});
+ let args = if args.is_null() { &empty } else { args };
+ if !args.is_object() {
+ return Err(ToolError::InvalidArgs("arguments must be a JSON object".into()));
+ }
+ let def = tools::find(name).ok_or_else(|| ToolError::UnknownTool(name.into()))?;
+ tools::check_args(def, args)?;
+ let a = Args(args);
+ let out = match name {
+ "doc_open" => self.doc_open(&a)?,
+ "doc_batch" => self.doc_batch(&a)?,
+ "doc_list" => json!({ "documents": self.session.docs().iter().map(summary).collect::<Vec<_>>() }),
+ "doc_info" => {
+ let id = self.doc(&a)?.id;
+ self.session.refresh_fonts(id);
+ info(self.doc(&a)?)
+ }
+ "doc_close" => self.doc_close(&a)?,
+ "doc_save" => self.doc_save(&a)?,
+ "doc_set_info" => {
+ let edit = Edit::SetInfo { key: a.str("key")?.into(), value: a.str("value")?.into() };
+ self.apply(&a, edit)?
+ }
+ "page_render" => return self.page_render(&a).map(|c| vec![c]),
+ "comment_image_preview" => return self.comment_image_preview(&a),
+ "text_extract" => self.text_extract(&a)?,
+ "text_word_count" => self.text_word_count(&a)?,
+ "text_find" => self.text_find(&a)?,
+ "page_rotate" => {
+ let degrees = a.int("degrees")?;
+ if degrees % 90 != 0 {
+ return Err(ToolError::InvalidArgs("degrees must be a multiple of 90".into()));
+ }
+ let doc = self.doc(&a)?;
+ let base = match a.opt_ints("pages")? {
+ Some(_) => self.pages(&a, "pages")?,
+ None => (0..doc.info.pages.len()).collect(),
+ };
+ let parity = match a.opt_str("subset")?.unwrap_or("all") {
+ "all" => pdfcraft_engine::PageParity::Both,
+ "even" => pdfcraft_engine::PageParity::Even,
+ "odd" => pdfcraft_engine::PageParity::Odd,
+ s => return Err(ToolError::InvalidArgs(format!("unknown subset {s:?} (all, even, odd)"))),
+ };
+ let orientation = match a.opt_str("orientation")?.unwrap_or("all") {
+ "all" => pdfcraft_engine::PageOrientation::Both,
+ "landscape" => pdfcraft_engine::PageOrientation::Landscape,
+ "portrait" => pdfcraft_engine::PageOrientation::Portrait,
+ o => return Err(ToolError::InvalidArgs(format!("unknown orientation {o:?} (all, landscape, portrait)"))),
+ };
+ let pages = pdfcraft_engine::filter_pages(&self.doc(&a)?.info, &base, parity, orientation);
+ if pages.is_empty() {
+ return Err(failed("no pages match the filters"));
+ }
+ let n = pages.len();
+ let mut out = self.apply(&a, Edit::RotatePages { pages, degrees })?;
+ out["rotated"] = json!(n);
+ out
+ }
+ "page_enhance_camera" => {
+ let page = self.page(&a)?;
+ let given = a.nums::<8>("corners")?;
+ let doc = self.doc(&a)?;
+ let (id, info) = (doc.id, doc.info.pages.get(page).cloned().ok_or_else(|| failed("no such page"))?);
+ let corners = match given {
+ Some(c) => [0, 1, 2, 3].map(|i| {
+ let [x, y] = info.view_to_user(c[2 * i] as f32, c[2 * i + 1] as f32);
+ [x as f64, y as f64]
+ }),
+ None => self.session.detect_camera_corners(id, page).ok_or_else(|| {
+ failed("the document's edges could not be found on this page: pass `corners` [x1, y1, x2, y2, x3, y3, x4, y4]")
+ })?,
+ };
+ let level = match a.opt_int("level")? {
+ None => 0,
+ Some(l @ 0..=100) => l as u8,
+ Some(l) => return Err(ToolError::InvalidArgs(format!("level must be between 0 and 100, not {l}"))),
+ };
+ let look = match a.opt_str("mode")? {
+ None => pdfcraft_engine::camera_clean::Look::Colour,
+ Some(m) => pdfcraft_engine::camera_clean::Look::from_name(m)
+ .ok_or_else(|| ToolError::InvalidArgs(format!("unknown mode {m:?} (original, colour, greyscale, bw)")))?,
+ };
+ self.session.enhance_camera_page_at(id, page, corners, look, level).map_err(failed)?;
+ let r = |v: f32| (v * 100.0).round() / 100.0;
+ let used: Vec<f32> = corners.iter().flat_map(|&[x, y]| info.user_to_view(x as f32, y as f32)).map(r).collect();
+ let mut out = summary(self.doc(&a)?);
+ out["corners"] = json!(used);
+ out["detected"] = json!(given.is_none());
+ out
+ }
+ "page_delete" => {
+ let pages = self.pages(&a, "pages")?;
+ self.apply(&a, Edit::DeletePages { pages })?
+ }
+ "page_move" => {
+ let pages = self.pages(&a, "pages")?;
+ let to = self.position(&a, "to")?;
+ self.apply(&a, Edit::MovePages { pages, to })?
+ }
+ "page_reverse" => {
+ let pages = match a.opt_ints("pages")? {
+ Some(_) => self.pages(&a, "pages")?,
+ None => (0..self.doc(&a)?.info.pages.len()).collect(),
+ };
+ self.apply(&a, Edit::ReversePages { pages })?
+ }
+ "page_insert_blank" => self.insert_blank(&a)?,
+ "page_insert_file" => self.insert_file(&a)?,
+ "page_extract" => self.page_extract(&a)?,
+ "doc_combine" => self.doc_combine(&a)?,
+ "doc_create_multiple" => self.doc_create_multiple(&a)?,
+ "doc_split" => self.doc_split(&a)?,
+ "edit_undo" => {
+ let id = self.doc(&a)?.id;
+ let label = self.session.undo(id).map_err(failed)?.to_string();
+ json!({ "undone": label, "document": summary(self.doc(&a)?) })
+ }
+ "edit_redo" => {
+ let id = self.doc(&a)?.id;
+ let label = self.session.redo(id).map_err(failed)?.to_string();
+ json!({ "redone": label, "document": summary(self.doc(&a)?) })
+ }
+ "command_list" => self.command_list(&a)?,
+ "command_run" => return self.command_run(&a),
+ "command_batch" => self.command_batch(&a)?,
+ "doc_inspect" => self.doc_inspect(&a)?,
+ "render_preview" => return self.render_preview(&a).map(|c| vec![c]),
+ "page_number" => {
+ use pdfcraft_organize::LabelStyle as L;
+ let n = self.doc(&a)?.info.pages.len();
+ let (from, to) = (a.int("from")?, a.int("to")?);
+ if from < 1 || to < from || to as usize > n {
+ return Err(ToolError::InvalidArgs(format!("from and to must satisfy 1 ≤ from ≤ to ≤ {n}")));
+ }
+ let style = match a.opt_str("style")?.unwrap_or("decimal") {
+ "decimal" => L::Decimal,
+ "upper-roman" => L::UpperRoman,
+ "lower-roman" => L::LowerRoman,
+ "upper-alpha" => L::UpperAlpha,
+ "lower-alpha" => L::LowerAlpha,
+ "none" => L::None,
+ other => return Err(ToolError::InvalidArgs(format!("unknown style {other:?}"))),
+ };
+ let prefix = a.opt_str("prefix")?.unwrap_or_default().to_string();
+ let first = a.opt_int("start")?.unwrap_or(1).clamp(1, u32::MAX as i64) as u32;
+ let mut out = self.apply(&a, Edit::NumberPages { from: from as usize - 1, to: to as usize - 1, style, prefix, first })?;
+ out["labels"] = json!(self.doc(&a)?.info.pages.iter().map(|p| p.label.clone()).collect::<Vec<_>>());
+ out
+ }
+ "bookmark_list" => self.bookmark_listing(&a)?,
+ "bookmark_add" => {
+ let page = self.page(&a)?;
+ let parent = a.opt_path("parent")?.unwrap_or_default();
+ let index = a.opt_int("position")?.map_or(usize::MAX, |p| (p.max(1) - 1) as usize);
+ let title = a.str("title")?.to_string();
+ let (left, top) = (a.bookmark_coordinate("left")?, a.bookmark_coordinate("top")?);
+ let [left, top] = match self.doc(&a)?.info.pages.get(page) {
+ Some(p) => p.xyz_for_view(left, top),
+ None => [None, None],
+ };
+ let (left, top) = (left.map(f64::from), top.map(f64::from));
+ self.apply(&a, Edit::AddBookmark { parent, index, title, page, left, top })?
+ }
+ "bookmark_rename" => {
+ let (path, title) = (a.path("path")?, a.str("title")?.to_string());
+ self.apply(&a, Edit::RenameBookmark { path, title })?
+ }
+ "bookmark_delete" => {
+ let path = a.path("path")?;
+ self.apply(&a, Edit::DeleteBookmark { path })?
+ }
+ "bookmark_move" => {
+ let from = a.path("path")?;
+ let to_parent = a.opt_path("parent")?.unwrap_or_default();
+ let index = a.opt_int("position")?.map_or(usize::MAX, |p| (p.max(1) - 1) as usize);
+ self.apply(&a, Edit::MoveBookmark { from, to_parent, index })?
+ }
+ "bookmark_set_page" => {
+ let (path, page) = (a.path("path")?, self.page(&a)?);
+ self.apply(&a, Edit::SetBookmarkPage { path, page })?
+ }
+ "bookmark_set_style" => {
+ let path = a.path("path")?;
+ // Left out keeps the colour; [0, 0, 0] is the default black.
+ let color = match a.get("color") {
+ None => None,
+ Some(v) => {
+ let rgb: Option<Vec<f64>> = v.as_array().and_then(|c| c.iter().map(Value::as_f64).collect());
+ match rgb.as_deref() {
+ Some(&[r, g, b]) if [r, g, b].iter().all(|c| (0.0..=1.0).contains(c)) => Some([r, g, b]),
+ _ => return Err(ToolError::InvalidArgs("color must be [r, g, b], each from 0 to 1".into())),
+ }
+ }
+ };
+ let (bold, italic) = (a.opt_bool("bold")?, a.opt_bool("italic")?);
+ if color.is_none() && bold.is_none() && italic.is_none() {
+ return Err(ToolError::InvalidArgs("give color, bold or italic".into()));
+ }
+ let mut edits = Vec::new();
+ if let Some(color) = color {
+ edits.push(Edit::SetBookmarkColor { path: path.clone(), color: Some(color) });
+ }
+ if bold.is_some() || italic.is_some() {
+ edits.push(Edit::SetBookmarkStyle { path, bold, italic });
+ }
+ // A colour and a style given together are one step to undo, applied all or nothing.
+ match edits.len() {
+ 1 => self.apply(&a, edits.remove(0))?,
+ _ => self.apply(&a, Edit::Batch { label: "Style".into(), edits })?,
+ }
+ }
+ "bookmark_from_structure" => {
+ let mut out = self.apply(&a, Edit::BookmarksFromStructure)?;
+ let listing = self.bookmark_listing(&a)?;
+ out["bookmarks"] = listing["bookmarks"].clone();
+ out["next"] = listing["next"].clone();
+ out
+ }
+ "doc_protect" => self.doc_protect(&a)?,
+ "page_replace" => {
+ let pages = self.pages(&a, "pages")?;
+ let path = self.resolve(a.str("path")?, false)?;
+ let bytes = Arc::new(read_input(&path)?);
+ let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
+ let src_pages = match a.opt_ints("from_pages")? {
+ Some(p) => one_based(&p)?,
+ None => (0..pages.len()).collect(),
+ };
+ self.apply(&a, Edit::ReplacePages { pages, name, bytes, src_pages })?
+ }
+ "page_duplicate" => {
+ let pages = self.pages(&a, "pages")?;
+ let at = self.opt_position(&a, "at")?;
+ self.apply(&a, Edit::DuplicatePages { pages, at })?
+ }
+ "page_set_box" => self.page_set_box(&a)?,
+ "page_transition_set" => self.page_transition_set(&a)?,
+ "doc_create" => self.doc_create(&a)?,
+ "xfa_to_static" => self.apply(&a, Edit::XfaToStatic)?,
+ "doc_flatten" => {
+ let (comments, fields) = (a.opt_bool("comments")?.unwrap_or(true), a.opt_bool("fields")?.unwrap_or(true));
+ if !comments && !fields {
+ return Err(ToolError::InvalidArgs("nothing to flatten".into()));
+ }
+ self.apply(&a, Edit::Flatten { comments, fields })?
+ }
+ "doc_reduce" => {
+ let id = self.doc(&a)?.id;
+ let before = self.doc(&a)?.bytes.len();
+ let path = self.resolve(a.str("path")?, true)?;
+ let (bytes, merged) = self.session.reduced_bytes(id).map_err(failed)?;
+ // As in the app, a copy that isn't smaller is not written (#490).
+ let written = bytes.len() < before;
+ if written {
+ write_atomic(&path, &bytes)?;
+ }
+ json!({ "path": path.to_string_lossy(), "written": written, "bytes_before": before, "bytes_after": bytes.len(), "merged_objects": merged })
+ }
+ "doc_optimize" => self.doc_optimize(&a)?,
+ "doc_initial_view" => self.doc_initial_view(&a)?,
+ "doc_revisions" => self.doc_revisions(&a)?,
+ "text_lines" => {
+ let page = self.page(&a)?;
+ let doc = self.doc_to_copy(&a)?;
+ let info = &doc.info.pages[page];
+ let r = |x: f32| (x as f64 * 100.0).round() / 100.0;
+ let lines: Vec<Value> = doc
+ .text_lines(page)
+ .iter()
+ .enumerate()
+ .map(|(i, l)| {
+ let (u, v) = (info.user_to_view(l.rect[0] as f32, l.rect[1] as f32), info.user_to_view(l.rect[2] as f32, l.rect[3] as f32));
+ json!({
+ "line": i + 1,
+ "text": l.text,
+ "rect": [r(u[0].min(v[0])), r(u[1].min(v[1])), r(u[0].max(v[0])), r(u[1].max(v[1]))],
+ "font": l.base_font,
+ "size": (l.size * 100.0).round() / 100.0,
+ })
+ })
+ .collect();
+ json!({ "page": page + 1, "count": lines.len(), "lines": lines })
+ }
+ "image_hit" => {
+ let page = self.page(&a)?;
+ let point = a
+ .get("point")
+ .and_then(Value::as_array)
+ .filter(|p| p.len() == 2)
+ .and_then(|p| Some([p.first()?.as_f64()?, p.get(1)?.as_f64()?]))
+ .filter(|p| p.iter().all(|v| v.is_finite() && v.abs() <= 1e9))
+ .ok_or_else(|| ToolError::InvalidArgs("point must contain two finite coordinates".into()))?;
+ let doc = self.doc(&a)?;
+ let p = &doc.info.pages[page];
+ let user = p.view_to_user(point[0] as f32, point[1] as f32).map(f64::from);
+ let images: Vec<_> = doc.page_images(page).iter().enumerate().filter(|(_, im)| im.contains(user)).map(|(i, _)| i + 1).collect();
+ json!({"page":page+1,"images":images})
+ }
+ "page_images" => {
+ let page = self.page(&a)?;
+ let doc = self.doc(&a)?;
+ let info = &doc.info.pages[page];
+ let r = |x: f32| (x as f64 * 100.0).round() / 100.0;
+ let list: Vec<Value> = doc
+ .page_images(page)
+ .iter()
+ .enumerate()
+ .map(|(i, im)| {
+ let (u, v) = (info.user_to_view(im.rect[0] as f32, im.rect[1] as f32), info.user_to_view(im.rect[2] as f32, im.rect[3] as f32));
+ let visible = im.visible_rect.map(|rect| {
+ let (u, v) = (info.user_to_view(rect[0] as f32, rect[1] as f32), info.user_to_view(rect[2] as f32, rect[3] as f32));
+ [r(u[0].min(v[0])), r(u[1].min(v[1])), r(u[0].max(v[0])), r(u[1].max(v[1]))]
+ });
+ json!({ "visible_rect": visible, "image": i + 1, "rect": [r(u[0].min(v[0])), r(u[1].min(v[1])), r(u[0].max(v[0])), r(u[1].max(v[1]))], "pixels": [im.width, im.height], "name": im.name, "kind": if im.is_form { "form" } else { "image" } })
+ })
+ .collect();
+ json!({ "page": page + 1, "count": list.len(), "images": list })
+ }
+ "image_edit" | "image_save" => {
+ let page = self.page(&a)?;
+ let n = self.doc(&a)?.page_images(page).len();
+ let k = a.int("image")?;
+ if k < 1 || k as usize > n {
+ return Err(ToolError::InvalidArgs(format!("image {k} is out of range: page {} has {n} images", page + 1)));
+ }
+ let index = k as usize - 1;
+ if name == "image_save" {
+ let (ext, bytes) = self.doc(&a)?.page_image_file(page, index).map_err(failed)?;
+ let mut path = self.resolve(a.str("path")?, true)?;
+ if path.is_dir() {
+ // Adding the extension to a folder's name would write beside it: "." is the
+ // root, so that would land outside it.
+ return Err(failed(format!("{}: is a folder, not a file", path.display())));
+ }
+ if path.extension().is_none() {
+ path.set_extension(ext);
+ }
+ write_atomic(&path, &bytes)?;
+ json!({ "path": path.to_string_lossy(), "format": ext, "bytes": bytes.len() })
+ } else {
+ use pdfcraft_engine::ImageEdit;
+ let change = match a.str("action")? {
+ "move" => {
+ let r: Vec<f64> =
+ a.get("rect").and_then(Value::as_array).map(|x| x.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
+ let r = <[f64; 4]>::try_from(r).map_err(|_| ToolError::InvalidArgs("move needs rect: 4 numbers".into()))?;
+ // Top-left-origin points → user space.
+ let info = &self.doc(&a)?.info.pages[page];
+ let (u0, u1) = (info.view_to_user(r[0] as f32, r[1] as f32), info.view_to_user(r[2] as f32, r[3] as f32));
+ ImageEdit::Move([u0[0].min(u1[0]) as f64, u0[1].min(u1[1]) as f64, u0[0].max(u1[0]) as f64, u0[1].max(u1[1]) as f64])
+ }
+ "rotate_by" => ImageEdit::RotateBy(
+ a.get("degrees")
+ .and_then(Value::as_f64)
+ .ok_or_else(|| ToolError::InvalidArgs("rotate_by needs degrees: a number (clockwise)".into()))?,
+ ),
+ "rotate" => ImageEdit::Rotate(a.opt_int("quarters")?.unwrap_or(1) as i32),
+ "crop" => {
+ let r: Vec<f64> =
+ a.get("rect").and_then(Value::as_array).map(|x| x.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
+ let r =
+ <[f64; 4]>::try_from(r).map_err(|_| ToolError::InvalidArgs("crop needs rect: 4 numbers, the part to keep".into()))?;
+ let info = &self.doc(&a)?.info.pages[page];
+ let (u0, u1) = (info.view_to_user(r[0] as f32, r[1] as f32), info.view_to_user(r[2] as f32, r[3] as f32));
+ ImageEdit::Crop([u0[0].min(u1[0]) as f64, u0[1].min(u1[1]) as f64, u0[0].max(u1[0]) as f64, u0[1].max(u1[1]) as f64])
+ }
+ "flip_horizontal" => ImageEdit::Flip { horizontal: true },
+ "flip_vertical" => ImageEdit::Flip { horizontal: false },
+ "delete" => ImageEdit::Delete,
+ "replace" => {
+ let path = self.resolve(a.str("path")?, false)?;
+ let bytes = read_input(&path)?;
+ ImageEdit::Replace {
+ name: path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
+ bytes: Arc::new(bytes),
+ }
+ }
+ other => return Err(ToolError::InvalidArgs(format!("unknown action {other:?}"))),
+ };
+ self.apply(&a, Edit::EditPageImage { page, index, change })?
+ }
+ }
+ "text_paragraphs" => {
+ let page = self.page(&a)?;
+ let doc = self.doc_to_copy(&a)?;
+ let info = &doc.info.pages[page];
+ let r = |x: f32| (x as f64 * 100.0).round() / 100.0;
+ let current = doc.text_blocks(page);
+ let id = doc.id;
+ let blocks: Vec<Value> = current
+ .iter()
+ .enumerate()
+ .map(|(i, b)| {
+ let (u, v) = (info.user_to_view(b.rect[0] as f32, b.rect[1] as f32), info.user_to_view(b.rect[2] as f32, b.rect[3] as f32));
+ json!({
+ "paragraph": i + 1,
+ "text": b.text,
+ "editor_text": b.editor_text,
+ "rows": b.rows.iter().map(|row| row.iter().map(|i| i + 1).collect::<Vec<_>>()).collect::<Vec<_>>(),
+ "lines": b.lines.iter().map(|l| l + 1).collect::<Vec<_>>(),
+ "rect": [r(u[0].min(v[0])), r(u[1].min(v[1])), r(u[0].max(v[0])), r(u[1].max(v[1]))],
+ "font": b.base_font,
+ "size": (b.size * 100.0).round() / 100.0,
+ })
+ })
+ .collect();
+ self.record_listing(id, page, &current);
+ json!({ "page": page + 1, "count": blocks.len(), "paragraphs": blocks })
+ }
+ "text_font_files" => {
+ let roots = if let Some(paths) = a.get("directories") {
+ let paths = paths
+ .as_array()
+ .filter(|p| p.len() <= 16)
+ .ok_or_else(|| ToolError::InvalidArgs("directories must be at most 16 paths".into()))?;
+ paths
+ .iter()
+ .map(|p| self.resolve(p.as_str().ok_or_else(|| ToolError::InvalidArgs("directory must be a path".into()))?, false))
+ .collect::<Result<Vec<_>>>()?
+ } else if let Some(roots) = &self.roots {
+ // The installed fonts are outside the roots: look in the read root instead.
+ let read = roots
+ .read_root()
+ .ok_or_else(|| failed("automation filesystem access is not granted: read authority is absent: installed fonts"))?;
+ vec![self.resolve(&read.to_string_lossy(), false)?]
+ } else if let Some(root) = &self.root {
+ vec![root.clone()]
+ } else {
+ pdfcraft_engine::text_fonts::installed_directories()
+ };
+ json!({"fonts": pdfcraft_engine::text_fonts::discover(&roots).into_iter().map(|f| json!({"path":f.path,"family":f.family,"font":f.face})).collect::<Vec<_>>()})
+ }
+ "text_font_import" => {
+ let page = self.page(&a)?;
+ let path = self.resolve(a.str("path")?, false)?;
+ let file = std::fs::File::open(&path).map_err(failed)?;
+ use std::io::Read;
+ let mut bytes = Vec::new();
+ file.take((16 << 20) + 1).read_to_end(&mut bytes).map_err(failed)?;
+ if bytes.len() > 16 << 20 {
+ return Err(ToolError::InvalidArgs("font input exceeds 16 MiB".into()));
+ }
+ let before: Vec<_> = self.doc(&a)?.text_editor_fonts(page).into_iter().map(|f| f.resource).collect();
+ let mut out = self.apply(&a, Edit::RegisterTextFont { page, bytes: Arc::new(bytes) })?;
+ let added = self
+ .doc(&a)?
+ .text_editor_fonts(page)
+ .into_iter()
+ .find(|f| !before.contains(&f.resource) && !f.resource.starts_with("PCApproved"));
+ if let Some(f) = added {
+ out["resource"] = json!(f.resource);
+ out["font"] = json!(f.face);
+ }
+ out
+ }
+ "text_fonts" => {
+ let page = self.page(&a)?;
+ json!({"fonts": self.doc(&a)?.text_editor_fonts(page).into_iter().map(|f| json!({"resource":f.resource,"font":f.face,"full_face":f.resource.starts_with("PCFull"),"preview_only":f.resource.starts_with("PCApproved")})).collect::<Vec<_>>()})
+ }
+ "text_edit_layout" => {
+ let page = self.page(&a)?;
+ let doc = self.doc(&a)?;
+ let k = a.int("paragraph")?;
+ let blocks = doc.text_blocks(page);
+ let index = self.paragraph_index(doc.id, page, k, &blocks)?;
+ let source = blocks.get(index).ok_or_else(|| ToolError::InvalidArgs("paragraph is out of range".into()))?;
+ let text = a.opt_str("text")?.unwrap_or(&source.editor_text);
+ let style = pdfcraft_engine::BlockStyle {
+ size: a.opt_num("size")?,
+ width: a.opt_num("width")?,
+ resource: a.opt_str("font_resource")?.map(str::to_owned),
+ ranges: parse_style_ranges(a.get("ranges"))?,
+ ..Default::default()
+ };
+ let layout = doc.text_edit_layout(page, index, text, &style).map_err(failed)?;
+ let info = &doc.info.pages[page];
+ let view_rect = |r: [f64; 4]| {
+ let a = info.user_to_view(r[0] as f32, r[1] as f32);
+ let b = info.user_to_view(r[2] as f32, r[3] as f32);
+ [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])]
+ };
+ let fonts: Vec<_> = doc.text_editor_fonts(page).into_iter().map(|f| json!({"resource": f.resource, "face": f.face})).collect();
+ json!({ "page": page + 1, "paragraph": k, "source_rect": view_rect(layout.source_rect),
+ "draft_rect": layout.draft_rect.map(view_rect), "overflow": layout.overflow, "embedded_fonts": fonts })
+ }
+ "text_edit" if a.get("paragraph").is_some() => {
+ let page = self.page(&a)?;
+ let k = a.int("paragraph")?;
+ let (id, blocks) = {
+ let doc = self.doc(&a)?;
+ (doc.id, doc.text_blocks(page))
+ };
+ let index = self.paragraph_index(id, page, k, &blocks)?;
+ let block = blocks.get(index).cloned().ok_or_else(|| ToolError::InvalidArgs(format!("paragraph {k} is out of range")))?;
- let text = a.opt_str("text")?.map(str::to_owned).unwrap_or(block.text);
++ // `aligns` counts rows, so without new text the paragraph keeps its rows (the
++ // editor text); otherwise its text joined with spaces is rewrapped.
++ let own = if a.get("aligns").is_some() { block.editor_text } else { block.text };
++ let text = a.opt_str("text")?.map(str::to_owned).unwrap_or(own);
+ 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:?}"))),
- });
++ style.align = Some(content::parse_align(al)?);
++ }
++ if let Some(aligns) = content::opt_aligns(&a)? {
++ style.aligns = aligns;
+ }
+ // 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/edit/src/added.rs
index 36e1c3bc0,40e540fb0..a603a3706
--- a/crates/edit/src/added.rs
+++ b/crates/edit/src/added.rs
@@@ -257,1077 -67,5 +67,23 @@@ impl Content
}
}
- /// An added item on a page.
- #[derive(Clone, Debug, PartialEq)]
- pub struct Added {
- pub page: usize,
- /// The item's content stream.
- pub obj: ObjRef,
- pub content: Content,
- }
-
- /// PdfCraft-owned page content discovered in one page/content traversal.
- #[derive(Clone, Debug, Default, PartialEq)]
- pub struct MarkerScan {
- pub marks: Vec<MarkKind>,
- pub added: Vec<Added>,
- }
-
- fn nums(doc: &Document, o: Option<&Object>) -> Vec<f64> {
- o.map(|o| doc.resolve(o)).and_then(|a| a.as_array().map(|a| a.iter().filter_map(Object::as_f64).collect())).unwrap_or_default()
- }
-
- fn norm(r: [f64; 4]) -> [f64; 4] {
- [r[0].min(r[2]), r[1].min(r[3]), r[0].max(r[2]), r[1].max(r[3])]
- }
-
- /// The advance of `s` in the item's standard font: its glyphs' widths and the character spacing
- /// after each of them, as `Tc` moves the pen (ISO 32000-2 §9.3.2).
- fn latin_width(t: &AddedText, s: &str) -> f64 {
- t.family.width(s, t.size, t.bold, t.italic) + t.char_spacing * s.chars().count() as f64
- }
-
- /// The lines of a text item after wrapping to its box width.
- pub fn lines(t: &AddedText) -> Vec<String> {
- wrapped(t).into_iter().map(|(line, ..)| line).collect()
- }
-
- #[cfg(test)]
- thread_local! {
- /// How often [`wrapped`] laid a text out on this thread, for the test that keeps it out of per-line loops.
- pub(crate) static WRAP_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
- }
-
- /// [`lines`], each with whether its paragraph runs right to left (its first strong character
- /// does) and which paragraph it is in.
- fn wrapped(t: &AddedText) -> Vec<(String, bool, usize)> {
- #[cfg(test)]
- WRAP_CALLS.with(|c| c.set(c.get().saturating_add(1)));
- let width = (t.rect[2] - t.rect[0]).max(t.size);
- let mut out = Vec::new();
- for (index, para) in t.text.split('\n').enumerate() {
- // Arabic or Hebrew: laid out with the bidirectional algorithm and shaped.
- let rtl_script = para.chars().any(|c| is_arabic(c) || is_hebrew(c));
- let thai = para.chars().any(is_thai);
- if thai
- && !rtl_script
- && let Ok(lines) = thai_lines(t, para, width)
- {
- out.extend(lines.into_iter().map(|line| (line, false, index)));
- continue;
- }
- let rtl = rtl_script && unicode_bidi::get_base_direction(para) == unicode_bidi::Direction::Rtl;
- // Arabic words are shaped one by one (joining stops at spaces), so a line's width is the
- // sum of its words' and shaping stays linear in the paragraph's length. The space is the
- // paragraph's; a space between Latin words is drawn in the item's font, a few hundredths
- // of an em apart.
- let measure = |s: &str| if rtl_script || thai { shaped_width(t, s, rtl) } else { latin_width(t, s) };
- let space = measure(" ");
- let (mut line, mut line_w) = (String::new(), 0.0);
- for word in para.split(' ') {
- let candidate = if line.is_empty() { word.to_string() } else { format!("{line} {word}") };
- let candidate_w =
- if rtl_script || thai { if line.is_empty() { measure(word) } else { line_w + space + measure(word) } } else { measure(&candidate) };
- if !line.is_empty() && candidate_w > width {
- out.push((std::mem::take(&mut line), rtl, index));
- line = word.to_string();
- line_w = measure(word);
- } else {
- line = candidate;
- line_w = candidate_w;
- }
- }
- out.push((line, rtl, index));
- }
- out
- }
-
- /// Thai wrapping at shaped cluster boundaries never detaches a tone/vowel mark from its base.
- /// This is glyph-safe wrapping, not dictionary-based Thai word segmentation.
- fn thai_lines(t: &AddedText, para: &str, width: f64) -> Result<Vec<String>, EditError> {
- let (pieces, _) = shaped_layout(t, para, false)?;
- let mut atoms = Vec::new();
- for piece in pieces {
- match piece {
- Piece::Shaped(clusters) => atoms.extend(clusters.into_iter().map(|c| (c.text, c.advance * t.size + t.char_spacing))),
- Piece::Latin(s) => atoms.extend(s.chars().map(|c| {
- let text = c.to_string();
- let w = latin_width(t, &text);
- (text, w)
- })),
- }
- }
- let mut lines = Vec::new();
- let (mut line, mut used) = (String::new(), 0.0);
- for (text, advance) in atoms {
- if !line.is_empty() && used + advance > width {
- lines.push(std::mem::take(&mut line));
- used = 0.0;
- }
- line.push_str(&text);
- used += advance;
- }
- lines.push(line);
- Ok(lines)
- }
-
- fn is_thai(c: char) -> bool {
- matches!(u32::from(c), 0x0E00..=0x0E7F)
- }
-
- /// Arabic letters, marks, digits and punctuation: an item with any of them is shaped with the
- /// craft-fonts Arabic face.
- fn is_arabic(c: char) -> bool {
- matches!(u32::from(c), 0x0600..=0x06FF | 0x0750..=0x077F | 0x0870..=0x08FF | 0xFB50..=0xFDFF | 0xFE70..=0xFEFC)
- }
-
- /// Hebrew letters, points, cantillation marks and punctuation (and the presentation forms): an
- /// item with any of them is drawn with the craft-fonts Hebrew face.
- fn is_hebrew(c: char) -> bool {
- matches!(u32::from(c), 0x0591..=0x05F4 | 0xFB1D..=0xFB4F)
- }
-
- /// The first character of `t` that would be drawn as `?`: outside WinAnsiEncoding and not drawn
- /// with the craft-fonts Arabic (#125) or Hebrew (#128) face, or Arabic or Hebrew that the face can't
- /// draw (or that has no face to draw it). Page-content tools refuse such text; the Add-text editor
- /// keeps it open.
- pub fn first_undrawable(t: &AddedText) -> Option<char> {
- if t.text.chars().any(is_thai) {
- if let Some(c) = t.text.chars().find(|c| is_thai(*c) && !pdfcraft_fonts::thai_has(*c)) {
- return Some(c);
- }
- let rest = AddedText { text: t.text.chars().filter(|c| !is_thai(*c)).collect(), ..t.clone() };
- return first_undrawable(&rest);
- }
- // Arabic or Hebrew that nothing can draw: there's no face, or the face lacks it.
- if let Some(c) =
- t.text.chars().find(|c| (shaped_arabic(*c) && !pdfcraft_fonts::arabic_has(*c)) || (is_hebrew(*c) && !pdfcraft_fonts::hebrew_has(*c)))
- {
- return Some(c);
- }
- if !shaped_by_a_face(t) {
- // Drawn line by line in the item's standard font (`\n` splits lines). Without the face
- // that is also how `draw` redraws an existing item, so it's checked that way.
- return t.text.split('\n').find_map(pdfcraft_fonts::first_non_win_ansi);
- }
- // What `shaped_layout` leaves to the standard font, exactly as `draw_shaped` splits it.
- wrapped(t).into_iter().find_map(|(line, rtl, _)| {
- let (pieces, _) = shaped_layout(t, &line, rtl).ok()?;
- pieces.iter().find_map(|p| match p {
- Piece::Latin(s) => pdfcraft_fonts::first_non_win_ansi(s),
- Piece::Shaped(_) => None,
- })
- })
- }
-
- /// Whether `t` has Arabic or Hebrew that its craft-fonts face draws (so `draw` lays it out with
- /// [`draw_shaped`]).
- fn shaped_by_a_face(t: &AddedText) -> bool {
- (pdfcraft_fonts::document_arabic_font().is_some() && t.text.chars().any(is_arabic))
- || (pdfcraft_fonts::document_hebrew_font(false).is_some() && t.text.chars().any(is_hebrew))
- }
-
- /// An Arabic character the face shapes and draws (U+061C, a direction mark, is dropped).
- fn shaped_arabic(c: char) -> bool {
- is_arabic(c) && !is_bidi_control(c)
- }
-
- /// Direction marks, embeddings, overrides and isolates: they steer the order and are not drawn.
- fn is_bidi_control(c: char) -> bool {
- matches!(c, '\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
- }
-
- fn mirrored(c: char) -> char {
- match c {
- '(' => ')',
- ')' => '(',
- '[' => ']',
- ']' => '[',
- '{' => '}',
- '}' => '{',
- '<' => '>',
- '>' => '<',
- '«' => '»',
- '»' => '«',
- other => other,
- }
- }
-
- /// A piece of a line with shaped text, in drawing order.
- enum Piece {
- /// Shown in the item's own standard font.
- Latin(String),
- Shaped(Vec<ShapedCluster>),
- }
-
- /// A line of a shaped-text item in drawing order (the Unicode bidirectional algorithm, UAX #9), and
- /// its width at the item's size. `rtl` is its paragraph's direction.
- fn shaped_layout(t: &AddedText, line: &str, rtl: bool) -> Result<(Vec<Piece>, f64), EditError> {
- // unicode-bidi indexes the first level of a line, so an empty one would panic.
- if line.is_empty() {
- return Ok((Vec::new(), 0.0));
- }
- let base = if rtl { Level::rtl() } else { Level::ltr() };
- let info = ParagraphBidiInfo::new(line, Some(base));
- let (levels, runs) = info.visual_runs(0..line.len());
- let mut pieces = Vec::new();
- for run in runs {
- let run_rtl = levels.get(run.start).is_some_and(Level::is_rtl);
- // Runs lie on character boundaries; a missing slice is skipped, never a panic.
- let Some(text) = line.get(run) else { continue };
- // Arabic and Hebrew letters take their face; so do spaces and punctuation between them
- // (Hebrew's when they follow Hebrew), which the shaper then mirrors. Latin text (and what
- // the faces lack) keeps the item's font.
- let mut segments: Vec<(Option<ShapedScript>, String)> = Vec::new();
- for c in text.chars().filter(|c| !is_bidi_control(*c)) {
- let after_hebrew = segments.last().is_some_and(|(kind, _)| *kind == Some(ShapedScript::Hebrew));
- let script = if is_thai(c) {
- Some(ShapedScript::Thai)
- } else if is_hebrew(c) || (run_rtl && after_hebrew && !c.is_alphanumeric() && pdfcraft_fonts::hebrew_has(c)) {
- Some(ShapedScript::Hebrew)
- } else if is_arabic(c) || (run_rtl && !c.is_alphanumeric() && pdfcraft_fonts::arabic_has(c)) {
- Some(ShapedScript::Arabic)
- } else {
- None
- };
- match segments.last_mut() {
- Some((kind, s)) if *kind == script => s.push(c),
- _ => segments.push((script, c.to_string())),
- }
- }
- if run_rtl {
- segments.reverse();
- }
- for (script, s) in segments {
- pieces.push(if let Some(script) = script {
- let shaped = match script {
- ShapedScript::Arabic => shape_arabic(&s, run_rtl).map_err(|e| arabic_error(e, &s))?,
- ShapedScript::Hebrew => shape_hebrew(&s, run_rtl).map_err(|e| hebrew_error(e, &s))?,
- ShapedScript::Thai => shape_thai(&s).map_err(|e| thai_error(e, &s))?,
- };
- Piece::Shaped(shaped)
- } else if run_rtl {
- Piece::Latin(s.chars().rev().map(mirrored).collect())
- } else {
- Piece::Latin(s)
- });
- }
- }
- let width = pieces
- .iter()
- .map(|p| match p {
- Piece::Latin(s) => latin_width(t, s),
- // Each cluster is shown on its own, so the spacing follows each once.
- Piece::Shaped(clusters) => clusters.iter().map(|c| c.advance * t.size + t.char_spacing).sum::<f64>(),
- })
- .sum();
- Ok((pieces, width))
- }
-
- /// The width of `s` in a shaped-text item; the item's font's estimate if it can't be shaped (drawing
- /// then reports why).
- fn shaped_width(t: &AddedText, s: &str, rtl: bool) -> f64 {
- shaped_layout(t, s, rtl).map(|(_, w)| w).unwrap_or_else(|_| latin_width(t, s))
- }
-
- fn arabic_error(e: GlyphError, text: &str) -> EditError {
- EditError::Invalid(match e {
- GlyphError::NoFont => "Arabic text needs PdfCraft's Arabic font, which this build doesn't include \
- (to build it in, set CRAFT_FONTS_DIR to a craft-fonts checkout that has an Arab face)"
- .into(),
- GlyphError::Missing => format!("the Arabic font can't show \"{text}\""),
- GlyphError::TooComplex => format!("the Arabic font's glyphs for \"{text}\" are too complex"),
- })
- }
-
- fn hebrew_error(e: GlyphError, text: &str) -> EditError {
- EditError::Invalid(match e {
- GlyphError::NoFont => "Hebrew text needs PdfCraft's Hebrew font, which this build doesn't include \
- (to build it in, set CRAFT_FONTS_DIR to a craft-fonts checkout that has a Hebr face)"
- .into(),
- GlyphError::Missing => format!("the Hebrew font can't show \"{text}\""),
- GlyphError::TooComplex => format!("the Hebrew font's glyphs for \"{text}\" are too complex"),
- })
- }
-
- fn thai_error(e: GlyphError, text: &str) -> EditError {
- EditError::Invalid(match e {
- GlyphError::NoFont => {
- "Thai text needs a Thai font in this build; rebuild with CRAFT_FONTS_DIR pointing to craft-fonts with a Thai face".into()
- }
- GlyphError::Missing => format!("the Thai font can't show \"{text}\""),
- GlyphError::TooComplex => "the Thai glyphs are too complex; use a shorter text box".into(),
- })
- }
-
- /// The box a text item occupies (height from its lines).
- pub fn text_rect(t: &AddedText) -> [f64; 4] {
- let r = norm(t.rect);
- let h = lines(t).len().max(1) as f64 * t.size * 1.2;
- [r[0], r[3] - h, r[2], r[3]]
- }
-
- /// How far each paste onto a page already holding the copy is offset, down and to the right, so a
- /// copy doesn't hide what it was copied from (points).
- pub const PASTE_STEP: f64 = 18.0;
-
- /// Where a pasted item of box `rect` goes on a page of `size` (display space): with its top-left
- /// corner at `at`, else where it was, `steps` paste steps ([`PASTE_STEP`]) down and to the right.
- /// It is kept on the page; one larger than the page keeps its left and top edges on it. A page
- /// or point that isn't a number leaves the box where it was.
- pub fn paste_rect(rect: [f64; 4], size: [f64; 2], steps: u32, at: Option<[f64; 2]>) -> [f64; 4] {
- let [x0, y0, x1, y1] = norm(rect);
- let (w, h) = (x1 - x0, y1 - y0);
- let (left, top) = match at {
- Some([x, y]) => (x, y),
- None => {
- let d = PASTE_STEP * f64::from(steps);
- (x0 + d, y1 - d)
- }
- };
- if !size.iter().chain(&[left, top, w, h]).all(|v| v.is_finite()) {
- return rect;
- }
- let left = left.min(size[0] - w).max(0.0);
- let top = top.max(h).min(size[1]);
- [left, top - h, left + w, top]
- }
-
- /// Most paste steps [`paste_place`] tries before giving up on finding a free place.
- const MAX_PASTE_STEPS: u32 = 64;
-
- /// Where Edit ▸ Paste puts `content` on a page of `size` already holding `items` (display space):
- /// where it was, or as many paste steps down and to the right as it takes not to land exactly on
- /// a copy of it (the original it was copied from, or an earlier paste).
- pub fn paste_place<'a>(items: impl IntoIterator<Item = &'a Content>, content: &Content, size: [f64; 2]) -> [f64; 4] {
- let same = copy_key(content);
- let copies: Vec<[f64; 4]> = items.into_iter().filter(|i| copy_key(i) == same).map(Content::rect).collect();
- let taken = |rect: [f64; 4]| copies.iter().any(|c| c.iter().zip(rect).all(|(a, b)| (a - b).abs() < 0.5));
- let mut rect = paste_rect(content.rect(), size, 0, None);
- for steps in 1..=MAX_PASTE_STEPS {
- if !taken(rect) {
- break;
- }
- rect = paste_rect(content.rect(), size, steps, None);
- }
- rect
- }
-
- /// What makes two items copies of each other for [`paste_place`]: all but the box, and for an
- /// image all but the object holding its picture, which a paste into another document stores anew.
- fn copy_key(c: &Content) -> Content {
- match c.with_rect([0.0; 4]) {
- Content::Image(img) => Content::Image(AddedImage { image: ObjRef::new(0, 0), ..img }),
- text => text,
- }
- }
-
- /// The widest explicit line before wrapping, measured with the PDF writing fonts.
- pub fn text_width(t: &AddedText) -> f64 {
- t.text.split('\n').map(|line| shaped_width(t, line, unicode_bidi::get_base_direction(line) == unicode_bidi::Direction::Rtl)).fold(0.0, f64::max)
- }
-
- fn font_name(base: &str) -> String {
- format!("PCF{}", base.replace('-', ""))
- }
-
- /// Most glyphs in one Type 3 font: its codes are single bytes, 1–240. An item gets one such font
- /// per 240 distinct glyphs it needs.
- const GLYPHS_PER_FONT: usize = 240;
-
- /// A line of a shaped-text item after layout: its text, whether its paragraph runs right to left,
- /// its paragraph, its pieces in drawing order and its width at the item's size.
- type LaidLine = (String, bool, usize, Vec<Piece>, f64);
-
- /// Where line `i` (`w` wide unstretched, with `spaces` spaces) starts in the box `r`, and its word
- /// spacing. `paragraphs` holds each line's paragraph: a line takes its paragraph's alignment, and
- /// every line of a justified paragraph but its last is stretched to the box's width.
- fn placed(t: &AddedText, r: [f64; 4], paragraphs: &[usize], i: usize, w: f64, spaces: usize, rtl: bool) -> (f64, f64) {
- let paragraph = paragraphs.get(i).copied().unwrap_or(0);
- let align = t.paragraph_align(paragraph);
- let ends_paragraph = paragraphs.get(i + 1) != Some(&paragraph);
- let tw = if align == Align::Justify && !ends_paragraph && spaces > 0 { ((r[2] - r[0]) - w).max(0.0) / spaces as f64 } else { 0.0 };
- let x = match align {
- // A right-to-left paragraph's unstretched last line ends at the right edge.
- Align::Justify if rtl => r[2] - w - tw * spaces as f64,
- Align::Left | Align::Justify => r[0],
- Align::Center => r[0] + ((r[2] - r[0]) - w) / 2.0,
- Align::Right => r[2] - w,
- };
- (x, tw)
- }
-
- /// Draw a text item that has Arabic, Hebrew or Thai in it. Each line is laid out in display order; their glyphs
- /// come from Type 3 fonts drawn from the craft-fonts face's outlines (no font file is embedded),
- /// with a ToUnicode map for copy and search. Other text uses the item's standard font.
- fn draw_shaped(doc: &mut Document, t: &AddedText, taken: &Dict, fonts: &mut Dict, out: &mut Vec<u8>) -> Result<(), EditError> {
- let laid = wrapped(t)
- .into_iter()
- .map(|(line, rtl, paragraph)| shaped_layout(t, &line, rtl).map(|(pieces, w)| (line, rtl, paragraph, pieces, w)))
- .collect::<Result<Vec<_>, _>>()?;
- draw_laid_shaped(doc, t, &laid, taken, fonts, out, shaped_glyph)
- }
-
- /// [`draw_shaped`] for lines that are already laid out. `outline` is the source of glyph outlines
- /// for a script's face (the craft-fonts faces, or a stand-in in tests).
- fn draw_laid_shaped(
- doc: &mut Document,
- t: &AddedText,
- laid: &[LaidLine],
- taken: &Dict,
- fonts: &mut Dict,
- out: &mut Vec<u8>,
- outline: impl Fn(ShapedScript, u32) -> Result<GlyphOutline, GlyphError>,
- ) -> Result<(), EditError> {
- let r = text_rect(t);
- let latin = font_name(t.family.base_font(t.bold, t.italic));
- // Every distinct cluster (a letter with its dots and the text it stands for) is one glyph of
- // one of the fonts, so copy and search get each character exactly once.
- let mut keys: Vec<&ShapedCluster> = Vec::new();
- let mut index: HashMap<ClusterKey, usize> = HashMap::new();
- for c in laid.iter().flat_map(|(_, _, _, pieces, _)| pieces).flat_map(|p| match p {
- Piece::Shaped(clusters) => clusters.as_slice(),
- Piece::Latin(_) => &[],
- }) {
- index.entry(cluster_key(c)).or_insert_with(|| {
- keys.push(c);
- keys.len() - 1
- });
- }
-
- // Every outline is read before anything is written, so a failure leaves the document as it was.
- let mut outlines = HashMap::new();
- for c in &keys {
- for (id, _) in &c.glyphs {
- if let std::collections::hash_map::Entry::Vacant(entry) = outlines.entry((c.script, *id)) {
- entry.insert(outline(c.script, *id).map_err(|e| match c.script {
- ShapedScript::Arabic => arabic_error(e, &c.text),
- ShapedScript::Hebrew => hebrew_error(e, &c.text),
- ShapedScript::Thai => thai_error(e, &c.text),
- })?);
- }
- }
- }
- // The names the page and this item already use: a new font never takes one of them.
- let mut taken_names: HashSet<Vec<u8>> = taken.iter().chain(fonts.iter()).map(|(name, _)| name.clone()).collect();
- let mut names = Vec::new();
- for chunk in keys.chunks(GLYPHS_PER_FONT) {
- let font = type3_shaped(doc, chunk, &outlines);
- // A name no font on the page has, so items never replace each other's fonts (object
- // numbers alone don't do: a full save renumbers objects but keeps resource names).
- let mut name = format!("PCAr{}", font.num);
- let mut suffix = 0usize;
- while taken_names.contains(name.as_bytes()) {
- suffix = suffix.saturating_add(1);
- name = format!("PCAr{}_{suffix}", font.num);
- }
- taken_names.insert(name.clone().into_bytes());
- fonts.set(name.clone().into_bytes(), Object::Ref(font));
- names.push(name);
- }
- let [cr, cg, cb] = t.color.map(|v| v.clamp(0.0, 1.0));
- out.extend(format!("BT {} {} {} rg\n", n(cr), n(cg), n(cb)).bytes());
- if t.char_spacing != 0.0 {
- out.extend(format!("{} Tc\n", n(t.char_spacing)).bytes());
- }
- let paragraphs: Vec<usize> = laid.iter().map(|(_, _, p, ..)| *p).collect();
- for (i, (line, rtl, _, pieces, w)) in laid.iter().enumerate() {
- // Shaped glyphs are painted in visual order. Keep the original line's typing order
- // explicitly, including marks, ligatures, digits and mixed-script punctuation.
- let logical: String = line.encode_utf16().map(|u| format!("{u:04X}")).collect();
- out.extend(format!("/Span <</ActualText <FEFF{logical}>>> BDC\n").bytes());
- let spaces = line.matches(' ').count();
- let (x, tw) = placed(t, r, &paragraphs, i, *w, spaces, *rtl);
- let y = r[3] - (i as f64 * 1.2 + 0.95) * t.size;
- let mut pen = x;
- let mut current: Option<&str> = None;
- for piece in pieces {
- match piece {
- Piece::Latin(s) => {
- out.extend(format!("/{latin} {} Tf {} Tw 1 0 0 1 {} {} Tm ", n(t.size), n(tw), n(pen), n(y)).bytes());
- out.extend(literal(&win_ansi(s)));
- out.extend_from_slice(b" Tj\n");
- current = Some(latin.as_str());
- pen += latin_width(t, s) + tw * s.matches(' ').count() as f64;
- }
- Piece::Shaped(clusters) => {
- for c in clusters {
- let Some(&k) = index.get(&cluster_key(c)) else { continue };
- let Some(name) = names.get(k / GLYPHS_PER_FONT) else { continue };
- // Codes start at 1; k % 240 + 1 is at most 240.
- let code = u8::try_from(k % GLYPHS_PER_FONT + 1).unwrap_or(1);
- if current != Some(name.as_str()) {
- out.extend(format!("/{name} {} Tf ", n(t.size)).bytes());
- current = Some(name.as_str());
- }
- out.extend(format!("1 0 0 1 {} {} Tm ", n(pen), n(y)).bytes());
- out.extend(literal(&[code]));
- out.extend_from_slice(b" Tj\n");
- pen += c.advance * t.size + t.char_spacing + if c.text == " " { tw } else { 0.0 };
- }
- }
- }
- }
- out.extend_from_slice(b"EMC\n");
- }
- out.extend_from_slice(b"ET\n");
- Ok(())
- }
-
- /// What makes two clusters the same Type 3 glyph: text, glyphs, offsets and advance (bit for bit;
- /// equal clusters come from the same font units).
- type ClusterKey<'a> = (ShapedScript, &'a str, Vec<(u32, u64, u64)>, u64);
-
- fn cluster_key(c: &ShapedCluster) -> ClusterKey<'_> {
- (c.script, c.text.as_str(), c.glyphs.iter().map(|(id, [x, y])| (*id, x.to_bits(), y.to_bits())).collect(), c.advance.to_bits())
- }
-
- /// A Type 3 font with `clusters` as codes 1…, each drawn from its script face's glyph `outlines`.
- fn type3_shaped(doc: &mut Document, clusters: &[&ShapedCluster], outlines: &HashMap<(ShapedScript, u32), GlyphOutline>) -> ObjRef {
- let mut charprocs = Dict::new();
- let mut differences = vec![Object::Int(1)];
- let mut widths = Vec::with_capacity(clusters.len());
- let mut bbox = [0.0f64; 4];
- let mut to_unicode = Vec::new();
- for (i, c) in clusters.iter().enumerate() {
- let code = i + 1;
- // Glyph space is 1000 units per em.
- let mut paths = Vec::new();
- let mut ink: Option<[f64; 4]> = None;
- for (id, [dx, dy]) in &c.glyphs {
- let Some(g) = outlines.get(&(c.script, *id)) else { continue };
- for contour in &g.contours {
- for (j, p) in contour.iter().enumerate() {
- paths.extend(format!("{} {} {}\n", n((p[0] + dx) * 1000.0), n((p[1] + dy) * 1000.0), if j == 0 { "m" } else { "l" }).bytes());
- }
- paths.extend_from_slice(b"h\n");
- let b = [g.bbox[0] + dx, g.bbox[1] + dy, g.bbox[2] + dx, g.bbox[3] + dy];
- ink = Some(ink.map_or(b, |a| [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])]));
- }
- }
- // Rounded outwards so no ink is clipped.
- let [x0, y0, x1, y1] =
- ink.map_or([0.0; 4], |b| [(b[0] * 1000.0).floor(), (b[1] * 1000.0).floor(), (b[2] * 1000.0).ceil(), (b[3] * 1000.0).ceil()]);
- bbox = [bbox[0].min(x0), bbox[1].min(y0), bbox[2].max(x1), bbox[3].max(y1)];
- let mut proc = format!("{} 0 {} {} {} {} d1\n", n(c.advance * 1000.0), n(x0), n(y0), n(x1), n(y1)).into_bytes();
- if !paths.is_empty() {
- proc.extend(paths);
- proc.extend_from_slice(b"f\n");
- }
- let glyph = format!("g{code:02X}");
- charprocs.set(glyph.clone().into_bytes(), Object::Ref(doc.add(Object::Stream(Stream::flate(Dict::new(), &proc)))));
- differences.push(Object::name(&glyph));
- widths.push(Object::Real((c.advance * 1000.0).round()));
- if !c.text.is_empty() {
- let hex: String = c.text.encode_utf16().map(|u| format!("{u:04X}")).collect();
- to_unicode.push(format!("<{code:02X}> <{hex}>\n"));
- }
- }
- let mut cmap = String::from(
- "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CMapType 2 def\n1 begincodespacerange\n<01> <FF>\nendcodespacerange\n",
- );
- // A CMap block holds at most 100 entries.
- for block in to_unicode.chunks(100) {
- cmap.push_str(&format!("{} beginbfchar\n{}endbfchar\n", block.len(), block.concat()));
- }
- cmap.push_str("endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n");
- let cmap = doc.add(Object::Stream(Stream::flate(Dict::new(), cmap.as_bytes())));
- // The face's family when every glyph comes from one script; without the face, the script's
- // name (as Arabic items were always named).
- let family = match clusters.first().map(|c| c.script).filter(|s| clusters.iter().all(|c| c.script == *s)) {
- Some(script) => script.font().map_or(
- match script {
- ShapedScript::Arabic => "Arabic",
- ShapedScript::Hebrew => "Hebrew",
- ShapedScript::Thai => "Thai",
- },
- |f| f.family,
- ),
- None => "PdfCraft Shaped Text",
- };
- let mut descriptor = Dict::new();
- descriptor.set(b"Type".to_vec(), Object::name("FontDescriptor"));
- descriptor.set(b"FontName".to_vec(), Object::name(&family.replace(' ', "")));
- descriptor.set(b"FontFamily".to_vec(), Object::String(PdfString::literal(family.as_bytes().to_vec())));
- descriptor.set(b"Flags".to_vec(), Object::Int(4));
- descriptor.set(b"ItalicAngle".to_vec(), Object::Int(0));
- let mut encoding = Dict::new();
- encoding.set(b"Type".to_vec(), Object::name("Encoding"));
- encoding.set(b"Differences".to_vec(), Object::Array(differences));
- let mut font = Dict::new();
- font.set(b"Type".to_vec(), Object::name("Font"));
- font.set(b"Subtype".to_vec(), Object::name("Type3"));
- font.set(b"FontDescriptor".to_vec(), Object::Ref(doc.add(Object::Dict(descriptor))));
- font.set(b"FontBBox".to_vec(), Object::Array(bbox.iter().map(|v| Object::Real(*v)).collect()));
- font.set(
- b"FontMatrix".to_vec(),
- Object::Array(vec![Object::Real(0.001), Object::Int(0), Object::Int(0), Object::Real(0.001), Object::Int(0), Object::Int(0)]),
- );
- font.set(b"FirstChar".to_vec(), Object::Int(1));
- font.set(b"LastChar".to_vec(), Object::Int(clusters.len() as i64));
- font.set(b"Widths".to_vec(), Object::Array(widths));
- font.set(b"Encoding".to_vec(), Object::Dict(encoding));
- font.set(b"CharProcs".to_vec(), Object::Dict(charprocs));
- font.set(b"ToUnicode".to_vec(), Object::Ref(cmap));
- doc.add(Object::Dict(font))
- }
-
- /// Content and resources for an item; `view` maps display space to user space. `taken` holds the
- /// page's font names. `existing`: the item is being replaced, so a build without the Arabic or
- /// Hebrew face keeps drawing that text as `?`, as before it was supported, rather than refusing to
- /// move it.
- fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict, existing: bool) -> Result<(Vec<u8>, Dict), EditError> {
- let mut res = Dict::new();
- let mut out = format!(
- "q {} {} {} {} {} {} cm\n",
- matrix_number(view[0]),
- matrix_number(view[1]),
- matrix_number(view[2]),
- matrix_number(view[3]),
- matrix_number(view[4]),
- matrix_number(view[5])
- )
- .into_bytes();
- match c {
- Content::Text(t) => {
- let base = t.family.base_font(t.bold, t.italic);
- let name = font_name(base);
- let mut font = Dict::new();
- font.set(b"Type".to_vec(), Object::name("Font"));
- font.set(b"Subtype".to_vec(), Object::name("Type1"));
- font.set(b"BaseFont".to_vec(), Object::name(base));
- if t.family != Family::Courier || !t.text.is_ascii() {
- font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
- }
- let mut fonts = Dict::new();
- fonts.set(name.clone().into_bytes(), Object::Dict(font));
- let face_or_new = |has: fn(char) -> bool, face: bool| t.text.chars().any(has) && (face || !existing);
- if t.text.chars().any(is_thai)
- || face_or_new(is_arabic, pdfcraft_fonts::document_arabic_font().is_some())
- || face_or_new(is_hebrew, pdfcraft_fonts::document_hebrew_font(false).is_some())
- {
- draw_shaped(doc, t, taken, &mut fonts, &mut out)?;
- res.set(b"Font".to_vec(), Object::Dict(fonts));
- out.extend_from_slice(b"Q\n");
- return Ok((out, res));
- }
- res.set(b"Font".to_vec(), Object::Dict(fonts));
- let r = text_rect(t);
- let [cr, cg, cb] = t.color.map(|v| v.clamp(0.0, 1.0));
- out.extend(format!("BT /{name} {} Tf {} {} {} rg\n", n(t.size), n(cr), n(cg), n(cb)).bytes());
- if t.char_spacing != 0.0 {
- out.extend(format!("{} Tc\n", n(t.char_spacing)).bytes());
- }
- let all = wrapped(t);
- let paragraphs: Vec<usize> = all.iter().map(|(_, _, p)| *p).collect();
- for (i, (line, ..)) in all.iter().enumerate() {
- let w = latin_width(t, line);
- // Baseline: 0.8 em below the line top.
- let y = r[3] - (i as f64 * 1.2 + 0.95) * t.size;
- // Justified: word spacing makes every line of a paragraph but its last fill the box.
- let (x, tw) = placed(t, r, &paragraphs, i, w, line.matches(' ').count(), false);
- out.extend(format!("1 0 0 1 {} {} Tm {} Tw ", n(x), n(y), n(tw)).bytes());
- out.extend(literal(&win_ansi(line)));
- out.extend_from_slice(b" Tj\n");
- }
- out.extend_from_slice(b"ET\n");
- }
- Content::Image(i) => {
- if !matches!(&*doc.get(i.image), Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image")) {
- return Err(EditError::Invalid("not an image".into()));
- }
- let r = norm(i.rect);
- let name = format!("PCImg{}", i.image.num);
- let mut xo = Dict::new();
- xo.set(name.clone().into_bytes(), Object::Ref(i.image));
- res.set(b"XObject".to_vec(), Object::Dict(xo));
- let [a, b, c, d, e, f] = i.matrix().0;
- // Clip to the box: the cropped-away parts stay hidden.
- out.extend(
- format!(
- "{} {} {} {} re W n {} {} {} {} {} {} cm /{name} Do\n",
- n(r[0]),
- n(r[1]),
- n(r[2] - r[0]),
- n(r[3] - r[1]),
- n(a),
- n(b),
- n(c),
- n(d),
- n(e),
- n(f)
- )
- .bytes(),
- );
- }
- }
- out.extend_from_slice(b"Q\n");
- Ok((out, res))
- }
-
- fn params(c: &Content) -> Dict {
- let mut d = Dict::new();
- let arr = |v: &[f64]| Object::Array(v.iter().map(|x| Object::Real(*x)).collect());
- match c {
- Content::Text(t) => {
- d.set(b"Kind".to_vec(), Object::name("Text"));
- d.set(b"Text".to_vec(), PdfString::text(&t.text));
- d.set(b"Font".to_vec(), Object::name(t.family.base_font(t.bold, t.italic)));
- d.set(b"Size".to_vec(), Object::Real(t.size));
- d.set(b"Color".to_vec(), arr(&t.color));
- d.set(b"Align".to_vec(), Object::Int(align_code(t.align)));
- // Each paragraph's own alignment, or null where it follows /Align.
- let aligns = crate::paragraph_align::tidy(t.aligns.clone(), t.align);
- if !aligns.is_empty() {
- d.set(b"Aligns".to_vec(), Object::Array(aligns.iter().map(|a| a.map_or(Object::Null, |a| Object::Int(align_code(a)))).collect()));
- }
- d.set(b"Rect".to_vec(), arr(&text_rect(t)));
- if t.char_spacing != 0.0 {
- d.set(b"CharSpacing".to_vec(), Object::Real(t.char_spacing));
- }
- }
- Content::Image(i) => {
- d.set(b"Kind".to_vec(), Object::name("Image"));
- d.set(b"Image".to_vec(), Object::Ref(i.image));
- d.set(b"Rect".to_vec(), arr(&norm(i.rect)));
- if i.rotation % 4 != 0 {
- d.set(b"Rotate".to_vec(), Object::Int(i64::from(i.rotation % 4) * 90));
- }
- if i.flip_h {
- d.set(b"FlipH".to_vec(), Object::Bool(true));
- }
- if i.flip_v {
- d.set(b"FlipV".to_vec(), Object::Bool(true));
- }
- if i.crop != [0.0; 4] {
- d.set(b"Crop".to_vec(), arr(&i.crop));
- }
- }
- }
- d
- }
-
+fn align_code(a: Align) -> i64 {
+ match a {
+ Align::Left => 0,
+ Align::Center => 1,
+ Align::Right => 2,
+ Align::Justify => 3,
+ }
+}
+
+fn align_from(code: Option<i64>) -> Align {
+ match code {
+ Some(1) => Align::Center,
+ Some(2) => Align::Right,
+ Some(3) => Align::Justify,
+ _ => Align::Left,
+ }
+}
+
- fn parse(doc: &Document, d: &Dict) -> Option<Content> {
- let r = nums(doc, d.get(b"Rect"));
- let rect: [f64; 4] = r.try_into().ok()?;
- match d.name(b"Kind")? {
- b"Text" => {
- let (family, bold, italic) = Family::from_base(d.name(b"Font").unwrap_or(b"Helvetica"));
- let c = nums(doc, d.get(b"Color"));
- let text = d.get(b"Text").and_then(|t| doc.resolve(t).as_string().map(|s| s.to_text())).unwrap_or_default();
- let align = align_from(d.int(b"Align"));
- // At most one entry per paragraph, whatever the file says.
- let aligns = d
- .get(b"Aligns")
- .and_then(|a| {
- doc.resolve(a)
- .as_array()
- .map(|a| a.iter().take(crate::paragraph_align::count(&text)).map(|v| v.as_int().map(|c| align_from(Some(c)))).collect())
- })
- .unwrap_or_default();
- Some(Content::Text(AddedText {
- rect,
- text,
- family,
- bold,
- italic,
- size: d.get(b"Size").and_then(Object::as_f64).unwrap_or(12.0),
- color: if c.len() == 3 { [c[0], c[1], c[2]] } else { [0.0; 3] },
- align,
- aligns: crate::paragraph_align::tidy(aligns, align),
- // Items written before character spacing have none.
- char_spacing: d.get(b"CharSpacing").and_then(Object::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0),
- }))
- }
- b"Image" => {
- let crop = nums(doc, d.get(b"Crop"));
- Some(Content::Image(AddedImage {
- rect,
- image: d.get(b"Image")?.as_ref()?,
- rotation: (d.int(b"Rotate").unwrap_or(0).rem_euclid(360) / 90) as u8,
- flip_h: matches!(d.get(b"FlipH"), Some(Object::Bool(true))),
- flip_v: matches!(d.get(b"FlipV"), Some(Object::Bool(true))),
- crop: crop.try_into().unwrap_or([0.0; 4]),
- }))
- }
- _ => None,
- }
- }
-
- fn with_resolved<T>(doc: &Document, object: &Object, f: impl FnOnce(&Object) -> T) -> T {
- match object {
- Object::Ref(reference) => {
- let resolved = doc.get(*reference);
- f(&resolved)
- }
- direct => f(direct),
- }
- }
-
- fn for_each_content_entry(doc: &Document, page: &pdfcraft_model::Page, mut visit: impl FnMut(&Object)) {
- let Some(contents) = page.dict.get(b"Contents") else { return };
- with_resolved(doc, contents, |resolved| match resolved {
- Object::Array(entries) => {
- for entry in entries {
- visit(entry);
- }
- }
- _ => visit(contents),
- });
- }
-
- /// Finds page marks and editable added content in one pass over the page content entries.
- pub fn scan_markers(doc: &Document) -> MarkerScan {
- let mut scan = MarkerScan::default();
- for (pi, page) in page_list(doc).iter().enumerate() {
- for_each_content_entry(doc, page, |entry| {
- with_resolved(doc, entry, |resolved| {
- let Some(dict) = resolved.as_dict() else { return };
- let tag = dict.name(b"PCMark");
- let kind = if tag == Some(&b"HeaderFooter"[..]) {
- Some(MarkKind::HeaderFooter)
- } else if tag == Some(&b"Watermark"[..]) {
- Some(MarkKind::Watermark)
- } else if tag == Some(&b"Background"[..]) {
- Some(MarkKind::Background)
- } else {
- None
- };
- if let Some(kind) = kind
- && !scan.marks.contains(&kind)
- {
- scan.marks.push(kind);
- }
-
- let Some(obj) = Object::as_ref(entry) else { return };
- if tag != Some(TAG.as_bytes()) {
- return;
- }
- let Some(params_object) = dict.get(b"PCAdded") else { return };
- with_resolved(doc, params_object, |resolved_params| {
- let Some(params) = resolved_params.as_dict() else { return };
- if let Some(content) = parse(doc, params) {
- // Display points depend on the page's /UserUnit. An item records the one it was
- // written for; none means 1, as for items written before display space followed
- // /UserUnit.
- let written = params
- .get(b"UserUnit")
- .and_then(Object::as_f64)
- .filter(|u| u.is_finite() && *u >= 1.0)
- .map_or(1.0, |u| u.min(pdfcraft_model::MAX_USER_UNIT));
- scan.added.push(Added { page: pi, obj, content: content.scaled(page.user_unit(doc) / written) });
- }
- });
- });
- });
- }
- scan
- }
-
- fn validate(c: &Content) -> Result<(), EditError> {
- let r = c.rect();
- if !r.iter().all(|v| v.is_finite()) {
- return Err(EditError::Invalid("invalid position".into()));
- }
- match c {
- Content::Text(t) => {
- if t.text.trim().is_empty() {
- return Err(EditError::Invalid("type some text first".into()));
- }
- if !(t.size.is_finite() && (1.0..=500.0).contains(&t.size)) {
- return Err(EditError::Invalid("the font size must be between 1 and 500 points".into()));
- }
- if !(t.char_spacing.is_finite() && (-CHAR_SPACING_LIMIT..=CHAR_SPACING_LIMIT).contains(&t.char_spacing)) {
- return Err(EditError::Invalid(format!(
- "the character spacing must be between -{CHAR_SPACING_LIMIT} and {CHAR_SPACING_LIMIT} points"
- )));
- }
- if (r[2] - r[0]).abs() < 1.0 {
- return Err(EditError::Invalid("the text box is too narrow".into()));
- }
- if t.text.chars().any(is_thai) && pdfcraft_fonts::document_thai_font().is_none() {
- return Err(thai_error(GlyphError::NoFont, &t.text));
- }
- // Without the Arabic face, `draw` decides for the Arabic letters themselves (#403): a new
- // item is refused with what's missing, and one that already holds Arabic stays movable.
- // Everything else in it is drawn in the standard font, so it still has to fit.
- let undrawable = if t.text.chars().any(shaped_arabic) && pdfcraft_fonts::document_arabic_font().is_none() {
- t.text.split('\n').find_map(|line| {
- line.chars()
- .find(|c| !(shaped_arabic(*c) || is_thai(*c) && pdfcraft_fonts::thai_has(*c) || pdfcraft_fonts::win_ansi_encodable(*c)))
- })
- } else {
- first_undrawable(t)
- };
- if let Some(c) = undrawable {
- return Err(crate::undrawable(c));
- }
- }
- Content::Image(_) => {
- if (r[2] - r[0]).abs() < 1.0 || (r[3] - r[1]).abs() < 1.0 {
- return Err(EditError::Invalid("the image is too small".into()));
- }
- }
- }
- Ok(())
- }
-
- /// Write an item's stream (new, or replacing `obj`) and make its resources available to the page.
- fn write(doc: &mut Document, page: usize, c: &Content, obj: Option<ObjRef>) -> Result<ObjRef, EditError> {
- validate(c)?;
- let all = page_list(doc);
- check(&[page], all.len())?;
- let p = &all[page];
- let view = p.view_matrix(doc);
- let user_unit = p.user_unit(doc);
- // The page gets its own copy of its resources with the item's fonts and images added, and
- // without the Arabic fonts of the version it replaces.
- let mut pres = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
- if let Some(r) = obj {
- drop_fonts(doc, &mut pres, &own_fonts(doc, r));
- }
- let taken = pres.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();
- let (content, res) = draw(doc, c, view, &taken, obj.is_some())?;
- if obj.is_none() {
- crate::check_on_top(doc, p)?;
- }
- for (k, v) in res.iter() {
- let mut sub = pres.get(k).map(|s| doc.resolve(s)).and_then(|s| s.as_dict().cloned()).unwrap_or_default();
- for (n2, o) in v.as_dict().into_iter().flat_map(|d| d.iter()) {
- sub.set(n2.clone(), o.clone());
- }
- pres.set(k.clone(), Object::Dict(sub));
- }
- doc.update_dict(p.obj, |d| d.set(b"Resources".to_vec(), Object::Dict(pres)))?;
- let mut sd = Dict::new();
- sd.set(b"PCMark".to_vec(), Object::name(TAG));
- let mut added = params(c);
- if user_unit != 1.0 {
- added.set(b"UserUnit".to_vec(), Object::Real(user_unit));
- }
- sd.set(b"PCAdded".to_vec(), Object::Dict(added));
- let stream = Stream::flate(sd, &content);
- match obj {
- Some(r) => {
- doc.set(r, Object::Stream(stream));
- Ok(r)
- }
- None => {
- // place_tagged appends a new stream; recover its reference.
- let p = page_list(doc).swap_remove(page);
- place_tagged(doc, &p, TAG, content.clone(), false)?;
- let p = page_list(doc).swap_remove(page);
- let r = contents(doc, &p)?.last().and_then(Object::as_ref).ok_or_else(|| EditError::Invalid("could not add the content".into()))?;
- doc.set(r, Object::Stream(stream));
- Ok(r)
- }
- }
- }
-
- /// Every added item, page by page, in drawing order.
- pub fn list_added(doc: &Document) -> Vec<Added> {
- scan_markers(doc).added
- }
-
- /// Add an item to a page (0-based). Returns its index among the page's added items.
- pub fn add_content(doc: &mut Document, page: usize, c: &Content) -> Result<usize, EditError> {
- write(doc, page, c, None)?;
- Ok(list_added(doc).iter().filter(|a| a.page == page).count() - 1)
- }
-
- fn find(doc: &Document, page: usize, index: usize) -> Result<Added, EditError> {
- list_added(doc)
- .into_iter()
- .filter(|a| a.page == page)
- .nth(index)
- .ok_or_else(|| EditError::Invalid(format!("page {} has no added item {}", page + 1, index + 1)))
- }
-
- /// Replace item `index` of `page` (moved, resized, retyped or reformatted).
- pub fn update_content(doc: &mut Document, page: usize, index: usize, c: &Content) -> Result<(), EditError> {
- let a = find(doc, page, index)?;
- if std::mem::discriminant(&a.content) != std::mem::discriminant(c) {
- return Err(EditError::Invalid("an item can't change between text and image".into()));
- }
- write(doc, page, c, Some(a.obj))?;
- Ok(())
- }
-
- /// Remove item `index` of `page`.
- pub fn delete_content(doc: &mut Document, page: usize, index: usize) -> Result<(), EditError> {
- let a = find(doc, page, index)?;
- let p = page_list(doc).swap_remove(page);
- let list: Vec<Object> = contents(doc, &p)?.into_iter().filter(|o| o.as_ref() != Some(a.obj)).collect();
- let fonts = own_fonts(doc, a.obj);
- // Only the page's own resources carry an item's fonts (`write` gives the page a copy).
- let res = match p.dict.get(b"Resources") {
- Some(Object::Dict(d)) if !fonts.is_empty() => Some(d.clone()),
- _ => None,
- };
- let res = res.map(|mut r| {
- drop_fonts(doc, &mut r, &fonts);
- r
- });
- doc.update_dict(p.obj, |d| {
- d.set(b"Contents".to_vec(), Object::Array(list));
- if let Some(r) = res {
- d.set(b"Resources".to_vec(), Object::Dict(r));
- }
- })?;
- Ok(())
- }
-
- /// Leave only item `index` on `page`: its contents become the item's own stream and its
- /// annotations go, so a render of the page (on a transparent backdrop) is the item's pixels
- /// alone. For previews on a copy of the document; the page's resources stay as they are.
- pub fn isolate_content(doc: &mut Document, page: usize, index: usize) -> Result<(), EditError> {
- let a = find(doc, page, index)?;
- let p = page_list(doc).swap_remove(page);
- // An item's stream starts from the page's initial graphics state: `place_tagged` closes
- // everything drawn before it, so it draws the same on its own.
- doc.update_dict(p.obj, |d| {
- d.set(b"Contents".to_vec(), Object::Array(vec![Object::Ref(a.obj)]));
- d.remove(b"Annots");
- })?;
- Ok(())
- }
-
- /// The Type 3 fonts an Arabic item's stream shows text with. Each item has its own (`draw_shaped`
- /// names them so), so they go when the item is replaced or deleted.
- fn own_fonts(doc: &Document, obj: ObjRef) -> Vec<Vec<u8>> {
- let Object::Stream(s) = &*doc.get(obj) else { return Vec::new() };
- let Ok(data) = s.decoded() else { return Vec::new() };
- data.split(u8::is_ascii_whitespace).filter_map(|w| w.strip_prefix(b"/")).filter(|w| w.starts_with(b"PCAr")).map(<[u8]>::to_vec).collect()
- }
-
- fn drop_fonts(doc: &Document, res: &mut Dict, names: &[Vec<u8>]) {
- if names.is_empty() {
- return;
- }
- let Some(mut fonts) = res.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()) else { return };
- for name in names {
- fonts.remove(name);
- }
- res.set(b"Font".to_vec(), Object::Dict(fonts));
- }
-
#[cfg(test)]
mod arabic_tests;
diff --cc crates/edit/src/added/draw.rs
index 000000000,0fc7aa510..0ad024b92
mode 000000,100644..100644
--- a/crates/edit/src/added/draw.rs
+++ b/crates/edit/src/added/draw.rs
@@@ -1,0 -1,383 +1,385 @@@
+ use super::layout::{
- Piece, arabic_error, hebrew_error, is_arabic, is_hebrew, is_thai, latin_width, lines, norm, shaped_layout, text_rect, thai_error, wrapped,
++ Piece, arabic_error, hebrew_error, is_arabic, is_hebrew, is_thai, latin_width, norm, shaped_layout, text_rect, thai_error, wrapped,
+ };
+ use super::types::{AddedText, Align, Family};
+ use super::*;
+
+ fn font_name(base: &str) -> String {
+ format!("PCF{}", base.replace('-', ""))
+ }
+
+ /// Most glyphs in one Type 3 font: its codes are single bytes, 1–240. An item gets one such font
+ /// per 240 distinct glyphs it needs.
+ pub(super) const GLYPHS_PER_FONT: usize = 240;
+
+ /// A line of a shaped-text item after layout: its text, whether its paragraph runs right to left,
-/// its pieces in drawing order and its width at the item's size.
-pub(super) type LaidLine = (String, bool, Vec<Piece>, f64);
++/// its paragraph, its pieces in drawing order and its width at the item's size.
++pub(super) type LaidLine = (String, bool, usize, Vec<Piece>, f64);
++
++/// Where line `i` (`w` wide unstretched, with `spaces` spaces) starts in the box `r`, and its word
++/// spacing. `paragraphs` holds each line's paragraph: a line takes its paragraph's alignment, and
++/// every line of a justified paragraph but its last is stretched to the box's width.
++fn placed(t: &AddedText, r: [f64; 4], paragraphs: &[usize], i: usize, w: f64, spaces: usize, rtl: bool) -> (f64, f64) {
++ let paragraph = paragraphs.get(i).copied().unwrap_or(0);
++ let align = t.paragraph_align(paragraph);
++ let ends_paragraph = paragraphs.get(i + 1) != Some(&paragraph);
++ let tw = if align == Align::Justify && !ends_paragraph && spaces > 0 { ((r[2] - r[0]) - w).max(0.0) / spaces as f64 } else { 0.0 };
++ let x = match align {
++ // A right-to-left paragraph's unstretched last line ends at the right edge.
++ Align::Justify if rtl => r[2] - w - tw * spaces as f64,
++ Align::Left | Align::Justify => r[0],
++ Align::Center => r[0] + ((r[2] - r[0]) - w) / 2.0,
++ Align::Right => r[2] - w,
++ };
++ (x, tw)
++}
+
+ /// Draw a text item that has Arabic, Hebrew or Thai in it. Each line is laid out in display order; their glyphs
+ /// come from Type 3 fonts drawn from the craft-fonts face's outlines (no font file is embedded),
+ /// with a ToUnicode map for copy and search. Other text uses the item's standard font.
+ fn draw_shaped(doc: &mut Document, t: &AddedText, taken: &Dict, fonts: &mut Dict, out: &mut Vec<u8>) -> Result<(), EditError> {
+ let laid = wrapped(t)
+ .into_iter()
- .map(|(line, rtl)| shaped_layout(t, &line, rtl).map(|(pieces, w)| (line, rtl, pieces, w)))
++ .map(|(line, rtl, paragraph)| shaped_layout(t, &line, rtl).map(|(pieces, w)| (line, rtl, paragraph, pieces, w)))
+ .collect::<Result<Vec<_>, _>>()?;
+ draw_laid_shaped(doc, t, &laid, taken, fonts, out, shaped_glyph)
+ }
+
+ /// [`draw_shaped`] for lines that are already laid out. `outline` is the source of glyph outlines
+ /// for a script's face (the craft-fonts faces, or a stand-in in tests).
+ pub(super) fn draw_laid_shaped(
+ doc: &mut Document,
+ t: &AddedText,
+ laid: &[LaidLine],
+ taken: &Dict,
+ fonts: &mut Dict,
+ out: &mut Vec<u8>,
+ outline: impl Fn(ShapedScript, u32) -> Result<GlyphOutline, GlyphError>,
+ ) -> Result<(), EditError> {
+ let r = text_rect(t);
+ let latin = font_name(t.family.base_font(t.bold, t.italic));
+ // Every distinct cluster (a letter with its dots and the text it stands for) is one glyph of
+ // one of the fonts, so copy and search get each character exactly once.
+ let mut keys: Vec<&ShapedCluster> = Vec::new();
+ let mut index: HashMap<ClusterKey, usize> = HashMap::new();
- for c in laid.iter().flat_map(|(_, _, pieces, _)| pieces).flat_map(|p| match p {
++ for c in laid.iter().flat_map(|(_, _, _, pieces, _)| pieces).flat_map(|p| match p {
+ Piece::Shaped(clusters) => clusters.as_slice(),
+ Piece::Latin(_) => &[],
+ }) {
+ index.entry(cluster_key(c)).or_insert_with(|| {
+ keys.push(c);
+ keys.len() - 1
+ });
+ }
+
+ // Every outline is read before anything is written, so a failure leaves the document as it was.
+ let mut outlines = HashMap::new();
+ for c in &keys {
+ for (id, _) in &c.glyphs {
+ if let std::collections::hash_map::Entry::Vacant(entry) = outlines.entry((c.script, *id)) {
+ entry.insert(outline(c.script, *id).map_err(|e| match c.script {
+ ShapedScript::Arabic => arabic_error(e, &c.text),
+ ShapedScript::Hebrew => hebrew_error(e, &c.text),
+ ShapedScript::Thai => thai_error(e, &c.text),
+ })?);
+ }
+ }
+ }
+ // The names the page and this item already use: a new font never takes one of them.
+ let mut taken_names: HashSet<Vec<u8>> = taken.iter().chain(fonts.iter()).map(|(name, _)| name.clone()).collect();
+ let mut names = Vec::new();
+ for chunk in keys.chunks(GLYPHS_PER_FONT) {
+ let font = type3_shaped(doc, chunk, &outlines);
+ // A name no font on the page has, so items never replace each other's fonts (object
+ // numbers alone don't do: a full save renumbers objects but keeps resource names).
+ let mut name = format!("PCAr{}", font.num);
+ let mut suffix = 0usize;
+ while taken_names.contains(name.as_bytes()) {
+ suffix = suffix.saturating_add(1);
+ name = format!("PCAr{}_{suffix}", font.num);
+ }
+ taken_names.insert(name.clone().into_bytes());
+ fonts.set(name.clone().into_bytes(), Object::Ref(font));
+ names.push(name);
+ }
+ let [cr, cg, cb] = t.color.map(|v| v.clamp(0.0, 1.0));
+ out.extend(format!("BT {} {} {} rg\n", n(cr), n(cg), n(cb)).bytes());
+ if t.char_spacing != 0.0 {
+ out.extend(format!("{} Tc\n", n(t.char_spacing)).bytes());
+ }
- for (i, (line, rtl, pieces, w)) in laid.iter().enumerate() {
++ let paragraphs: Vec<usize> = laid.iter().map(|(_, _, p, ..)| *p).collect();
++ for (i, (line, rtl, _, pieces, w)) in laid.iter().enumerate() {
+ // Shaped glyphs are painted in visual order. Keep the original line's typing order
+ // explicitly, including marks, ligatures, digits and mixed-script punctuation.
+ let logical: String = line.encode_utf16().map(|u| format!("{u:04X}")).collect();
+ out.extend(format!("/Span <</ActualText <FEFF{logical}>>> BDC\n").bytes());
+ let spaces = line.matches(' ').count();
- // Justified: the spaces of every line but the last stretch to fill the box.
- let tw = if t.align == Align::Justify && i + 1 < laid.len() && spaces > 0 { ((r[2] - r[0]) - w).max(0.0) / spaces as f64 } else { 0.0 };
- let x = match t.align {
- // A right-to-left paragraph's unstretched last line ends at the right edge.
- Align::Justify if *rtl => r[2] - w - tw * spaces as f64,
- Align::Left | Align::Justify => r[0],
- Align::Center => r[0] + ((r[2] - r[0]) - w) / 2.0,
- Align::Right => r[2] - w,
- };
++ let (x, tw) = placed(t, r, &paragraphs, i, *w, spaces, *rtl);
+ let y = r[3] - (i as f64 * 1.2 + 0.95) * t.size;
+ let mut pen = x;
+ let mut current: Option<&str> = None;
+ for piece in pieces {
+ match piece {
+ Piece::Latin(s) => {
+ out.extend(format!("/{latin} {} Tf {} Tw 1 0 0 1 {} {} Tm ", n(t.size), n(tw), n(pen), n(y)).bytes());
+ out.extend(literal(&win_ansi(s)));
+ out.extend_from_slice(b" Tj\n");
+ current = Some(latin.as_str());
+ pen += latin_width(t, s) + tw * s.matches(' ').count() as f64;
+ }
+ Piece::Shaped(clusters) => {
+ for c in clusters {
+ let Some(&k) = index.get(&cluster_key(c)) else { continue };
+ let Some(name) = names.get(k / GLYPHS_PER_FONT) else { continue };
+ // Codes start at 1; k % 240 + 1 is at most 240.
+ let code = u8::try_from(k % GLYPHS_PER_FONT + 1).unwrap_or(1);
+ if current != Some(name.as_str()) {
+ out.extend(format!("/{name} {} Tf ", n(t.size)).bytes());
+ current = Some(name.as_str());
+ }
+ out.extend(format!("1 0 0 1 {} {} Tm ", n(pen), n(y)).bytes());
+ out.extend(literal(&[code]));
+ out.extend_from_slice(b" Tj\n");
+ pen += c.advance * t.size + t.char_spacing + if c.text == " " { tw } else { 0.0 };
+ }
+ }
+ }
+ }
+ out.extend_from_slice(b"EMC\n");
+ }
+ out.extend_from_slice(b"ET\n");
+ Ok(())
+ }
+
+ /// What makes two clusters the same Type 3 glyph: text, glyphs, offsets and advance (bit for bit;
+ /// equal clusters come from the same font units).
+ type ClusterKey<'a> = (ShapedScript, &'a str, Vec<(u32, u64, u64)>, u64);
+
+ fn cluster_key(c: &ShapedCluster) -> ClusterKey<'_> {
+ (c.script, c.text.as_str(), c.glyphs.iter().map(|(id, [x, y])| (*id, x.to_bits(), y.to_bits())).collect(), c.advance.to_bits())
+ }
+
+ /// A Type 3 font with `clusters` as codes 1…, each drawn from its script face's glyph `outlines`.
+ fn type3_shaped(doc: &mut Document, clusters: &[&ShapedCluster], outlines: &HashMap<(ShapedScript, u32), GlyphOutline>) -> ObjRef {
+ let mut charprocs = Dict::new();
+ let mut differences = vec![Object::Int(1)];
+ let mut widths = Vec::with_capacity(clusters.len());
+ let mut bbox = [0.0f64; 4];
+ let mut to_unicode = Vec::new();
+ for (i, c) in clusters.iter().enumerate() {
+ let code = i + 1;
+ // Glyph space is 1000 units per em.
+ let mut paths = Vec::new();
+ let mut ink: Option<[f64; 4]> = None;
+ for (id, [dx, dy]) in &c.glyphs {
+ let Some(g) = outlines.get(&(c.script, *id)) else { continue };
+ for contour in &g.contours {
+ for (j, p) in contour.iter().enumerate() {
+ paths.extend(format!("{} {} {}\n", n((p[0] + dx) * 1000.0), n((p[1] + dy) * 1000.0), if j == 0 { "m" } else { "l" }).bytes());
+ }
+ paths.extend_from_slice(b"h\n");
+ let b = [g.bbox[0] + dx, g.bbox[1] + dy, g.bbox[2] + dx, g.bbox[3] + dy];
+ ink = Some(ink.map_or(b, |a| [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])]));
+ }
+ }
+ // Rounded outwards so no ink is clipped.
+ let [x0, y0, x1, y1] =
+ ink.map_or([0.0; 4], |b| [(b[0] * 1000.0).floor(), (b[1] * 1000.0).floor(), (b[2] * 1000.0).ceil(), (b[3] * 1000.0).ceil()]);
+ bbox = [bbox[0].min(x0), bbox[1].min(y0), bbox[2].max(x1), bbox[3].max(y1)];
+ let mut proc = format!("{} 0 {} {} {} {} d1\n", n(c.advance * 1000.0), n(x0), n(y0), n(x1), n(y1)).into_bytes();
+ if !paths.is_empty() {
+ proc.extend(paths);
+ proc.extend_from_slice(b"f\n");
+ }
+ let glyph = format!("g{code:02X}");
+ charprocs.set(glyph.clone().into_bytes(), Object::Ref(doc.add(Object::Stream(Stream::flate(Dict::new(), &proc)))));
+ differences.push(Object::name(&glyph));
+ widths.push(Object::Real((c.advance * 1000.0).round()));
+ if !c.text.is_empty() {
+ let hex: String = c.text.encode_utf16().map(|u| format!("{u:04X}")).collect();
+ to_unicode.push(format!("<{code:02X}> <{hex}>\n"));
+ }
+ }
+ let mut cmap = String::from(
+ "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CMapType 2 def\n1 begincodespacerange\n<01> <FF>\nendcodespacerange\n",
+ );
+ // A CMap block holds at most 100 entries.
+ for block in to_unicode.chunks(100) {
+ cmap.push_str(&format!("{} beginbfchar\n{}endbfchar\n", block.len(), block.concat()));
+ }
+ cmap.push_str("endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n");
+ let cmap = doc.add(Object::Stream(Stream::flate(Dict::new(), cmap.as_bytes())));
+ // The face's family when every glyph comes from one script; without the face, the script's
+ // name (as Arabic items were always named).
+ let family = match clusters.first().map(|c| c.script).filter(|s| clusters.iter().all(|c| c.script == *s)) {
+ Some(script) => script.font().map_or(
+ match script {
+ ShapedScript::Arabic => "Arabic",
+ ShapedScript::Hebrew => "Hebrew",
+ ShapedScript::Thai => "Thai",
+ },
+ |f| f.family,
+ ),
+ None => "PdfCraft Shaped Text",
+ };
+ let mut descriptor = Dict::new();
+ descriptor.set(b"Type".to_vec(), Object::name("FontDescriptor"));
+ descriptor.set(b"FontName".to_vec(), Object::name(&family.replace(' ', "")));
+ descriptor.set(b"FontFamily".to_vec(), Object::String(PdfString::literal(family.as_bytes().to_vec())));
+ descriptor.set(b"Flags".to_vec(), Object::Int(4));
+ descriptor.set(b"ItalicAngle".to_vec(), Object::Int(0));
+ let mut encoding = Dict::new();
+ encoding.set(b"Type".to_vec(), Object::name("Encoding"));
+ encoding.set(b"Differences".to_vec(), Object::Array(differences));
+ let mut font = Dict::new();
+ font.set(b"Type".to_vec(), Object::name("Font"));
+ font.set(b"Subtype".to_vec(), Object::name("Type3"));
+ font.set(b"FontDescriptor".to_vec(), Object::Ref(doc.add(Object::Dict(descriptor))));
+ font.set(b"FontBBox".to_vec(), Object::Array(bbox.iter().map(|v| Object::Real(*v)).collect()));
+ font.set(
+ b"FontMatrix".to_vec(),
+ Object::Array(vec![Object::Real(0.001), Object::Int(0), Object::Int(0), Object::Real(0.001), Object::Int(0), Object::Int(0)]),
+ );
+ font.set(b"FirstChar".to_vec(), Object::Int(1));
+ font.set(b"LastChar".to_vec(), Object::Int(clusters.len() as i64));
+ font.set(b"Widths".to_vec(), Object::Array(widths));
+ font.set(b"Encoding".to_vec(), Object::Dict(encoding));
+ font.set(b"CharProcs".to_vec(), Object::Dict(charprocs));
+ font.set(b"ToUnicode".to_vec(), Object::Ref(cmap));
+ doc.add(Object::Dict(font))
+ }
+
+ /// Content and resources for an item; `view` maps display space to user space. `taken` holds the
+ /// page's font names. `existing`: the item is being replaced, so a build without the Arabic or
+ /// Hebrew face keeps drawing that text as `?`, as before it was supported, rather than refusing to
+ /// move it.
+ pub(super) fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict, existing: bool) -> Result<(Vec<u8>, Dict), EditError> {
+ let mut res = Dict::new();
+ let mut out = format!(
+ "q {} {} {} {} {} {} cm\n",
+ matrix_number(view[0]),
+ matrix_number(view[1]),
+ matrix_number(view[2]),
+ matrix_number(view[3]),
+ matrix_number(view[4]),
+ matrix_number(view[5])
+ )
+ .into_bytes();
+ match c {
+ Content::Text(t) => {
+ let base = t.family.base_font(t.bold, t.italic);
+ let name = font_name(base);
+ let mut font = Dict::new();
+ font.set(b"Type".to_vec(), Object::name("Font"));
+ font.set(b"Subtype".to_vec(), Object::name("Type1"));
+ font.set(b"BaseFont".to_vec(), Object::name(base));
+ if t.family != Family::Courier || !t.text.is_ascii() {
+ font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
+ }
+ let mut fonts = Dict::new();
+ fonts.set(name.clone().into_bytes(), Object::Dict(font));
+ let face_or_new = |has: fn(char) -> bool, face: bool| t.text.chars().any(has) && (face || !existing);
+ if t.text.chars().any(is_thai)
+ || face_or_new(is_arabic, pdfcraft_fonts::document_arabic_font().is_some())
+ || face_or_new(is_hebrew, pdfcraft_fonts::document_hebrew_font(false).is_some())
+ {
+ draw_shaped(doc, t, taken, &mut fonts, &mut out)?;
+ res.set(b"Font".to_vec(), Object::Dict(fonts));
+ out.extend_from_slice(b"Q\n");
+ return Ok((out, res));
+ }
+ res.set(b"Font".to_vec(), Object::Dict(fonts));
+ let r = text_rect(t);
+ let [cr, cg, cb] = t.color.map(|v| v.clamp(0.0, 1.0));
+ out.extend(format!("BT /{name} {} Tf {} {} {} rg\n", n(t.size), n(cr), n(cg), n(cb)).bytes());
+ if t.char_spacing != 0.0 {
+ out.extend(format!("{} Tc\n", n(t.char_spacing)).bytes());
+ }
- let all = lines(t);
- for (i, line) in all.iter().enumerate() {
++ let all = wrapped(t);
++ let paragraphs: Vec<usize> = all.iter().map(|(_, _, p)| *p).collect();
++ for (i, (line, ..)) in all.iter().enumerate() {
+ let w = latin_width(t, line);
- let x = match t.align {
- Align::Left | Align::Justify => r[0],
- Align::Center => r[0] + ((r[2] - r[0]) - w) / 2.0,
- Align::Right => r[2] - w,
- };
+ // Baseline: 0.8 em below the line top.
+ let y = r[3] - (i as f64 * 1.2 + 0.95) * t.size;
- // Justified: word spacing makes every line but the last fill the box.
- let spaces = line.matches(' ').count();
- let tw =
- if t.align == Align::Justify && i + 1 < all.len() && spaces > 0 { ((r[2] - r[0]) - w).max(0.0) / spaces as f64 } else { 0.0 };
++ // Justified: word spacing makes every line of a paragraph but its last fill the box.
++ let (x, tw) = placed(t, r, &paragraphs, i, w, line.matches(' ').count(), false);
+ out.extend(format!("1 0 0 1 {} {} Tm {} Tw ", n(x), n(y), n(tw)).bytes());
+ out.extend(literal(&win_ansi(line)));
+ out.extend_from_slice(b" Tj\n");
+ }
+ out.extend_from_slice(b"ET\n");
+ }
+ Content::Image(i) => {
+ if !matches!(&*doc.get(i.image), Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image")) {
+ return Err(EditError::Invalid("not an image".into()));
+ }
+ let r = norm(i.rect);
+ let name = format!("PCImg{}", i.image.num);
+ let mut xo = Dict::new();
+ xo.set(name.clone().into_bytes(), Object::Ref(i.image));
+ res.set(b"XObject".to_vec(), Object::Dict(xo));
+ let [a, b, c, d, e, f] = i.matrix().0;
+ // Clip to the box: the cropped-away parts stay hidden.
+ out.extend(
+ format!(
+ "{} {} {} {} re W n {} {} {} {} {} {} cm /{name} Do\n",
+ n(r[0]),
+ n(r[1]),
+ n(r[2] - r[0]),
+ n(r[3] - r[1]),
+ n(a),
+ n(b),
+ n(c),
+ n(d),
+ n(e),
+ n(f)
+ )
+ .bytes(),
+ );
+ }
+ }
+ out.extend_from_slice(b"Q\n");
+ Ok((out, res))
+ }
+
+ pub(super) fn params(c: &Content) -> Dict {
+ let mut d = Dict::new();
+ let arr = |v: &[f64]| Object::Array(v.iter().map(|x| Object::Real(*x)).collect());
+ match c {
+ Content::Text(t) => {
+ d.set(b"Kind".to_vec(), Object::name("Text"));
+ d.set(b"Text".to_vec(), PdfString::text(&t.text));
+ d.set(b"Font".to_vec(), Object::name(t.family.base_font(t.bold, t.italic)));
+ d.set(b"Size".to_vec(), Object::Real(t.size));
+ d.set(b"Color".to_vec(), arr(&t.color));
- d.set(
- b"Align".to_vec(),
- Object::Int(match t.align {
- Align::Left => 0,
- Align::Center => 1,
- Align::Right => 2,
- Align::Justify => 3,
- }),
- );
++ d.set(b"Align".to_vec(), Object::Int(align_code(t.align)));
++ // Each paragraph's own alignment, or null where it follows /Align.
++ let aligns = crate::paragraph_align::tidy(t.aligns.clone(), t.align);
++ if !aligns.is_empty() {
++ d.set(b"Aligns".to_vec(), Object::Array(aligns.iter().map(|a| a.map_or(Object::Null, |a| Object::Int(align_code(a)))).collect()));
++ }
+ d.set(b"Rect".to_vec(), arr(&text_rect(t)));
+ if t.char_spacing != 0.0 {
+ d.set(b"CharSpacing".to_vec(), Object::Real(t.char_spacing));
+ }
+ }
+ Content::Image(i) => {
+ d.set(b"Kind".to_vec(), Object::name("Image"));
+ d.set(b"Image".to_vec(), Object::Ref(i.image));
+ d.set(b"Rect".to_vec(), arr(&norm(i.rect)));
+ if i.rotation % 4 != 0 {
+ d.set(b"Rotate".to_vec(), Object::Int(i64::from(i.rotation % 4) * 90));
+ }
+ if i.flip_h {
+ d.set(b"FlipH".to_vec(), Object::Bool(true));
+ }
+ if i.flip_v {
+ d.set(b"FlipV".to_vec(), Object::Bool(true));
+ }
+ if i.crop != [0.0; 4] {
+ d.set(b"Crop".to_vec(), arr(&i.crop));
+ }
+ }
+ }
+ d
+ }
diff --cc crates/edit/src/added/layout.rs
index 000000000,0e971b92c..dc9f658bd
mode 000000,100644..100644
--- a/crates/edit/src/added/layout.rs
+++ b/crates/edit/src/added/layout.rs
@@@ -1,0 -1,356 +1,356 @@@
+ use super::types::{AddedImage, AddedText};
+ use super::*;
+
+ pub(super) fn nums(doc: &Document, o: Option<&Object>) -> Vec<f64> {
+ o.map(|o| doc.resolve(o)).and_then(|a| a.as_array().map(|a| a.iter().filter_map(Object::as_f64).collect())).unwrap_or_default()
+ }
+
+ pub(super) fn norm(r: [f64; 4]) -> [f64; 4] {
+ [r[0].min(r[2]), r[1].min(r[3]), r[0].max(r[2]), r[1].max(r[3])]
+ }
+
+ /// The advance of `s` in the item's standard font: its glyphs' widths and the character spacing
+ /// after each of them, as `Tc` moves the pen (ISO 32000-2 §9.3.2).
+ pub(super) fn latin_width(t: &AddedText, s: &str) -> f64 {
+ t.family.width(s, t.size, t.bold, t.italic) + t.char_spacing * s.chars().count() as f64
+ }
+
+ /// The lines of a text item after wrapping to its box width.
+ pub fn lines(t: &AddedText) -> Vec<String> {
- wrapped(t).into_iter().map(|(line, _)| line).collect()
++ wrapped(t).into_iter().map(|(line, ..)| line).collect()
+ }
+
+ #[cfg(test)]
+ thread_local! {
+ /// How often [`wrapped`] laid a text out on this thread, for the test that keeps it out of per-line loops.
+ pub(crate) static WRAP_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
+ }
+
+ /// [`lines`], each with whether its paragraph runs right to left (its first strong character
-/// does).
-pub(super) fn wrapped(t: &AddedText) -> Vec<(String, bool)> {
++/// does) and which paragraph it is in.
++pub(super) fn wrapped(t: &AddedText) -> Vec<(String, bool, usize)> {
+ #[cfg(test)]
+ WRAP_CALLS.with(|c| c.set(c.get().saturating_add(1)));
+ let width = (t.rect[2] - t.rect[0]).max(t.size);
+ let mut out = Vec::new();
- for para in t.text.split('\n') {
++ for (index, para) in t.text.split('\n').enumerate() {
+ // Arabic or Hebrew: laid out with the bidirectional algorithm and shaped.
+ let rtl_script = para.chars().any(|c| is_arabic(c) || is_hebrew(c));
+ let thai = para.chars().any(is_thai);
+ if thai
+ && !rtl_script
+ && let Ok(lines) = thai_lines(t, para, width)
+ {
- out.extend(lines.into_iter().map(|line| (line, false)));
++ out.extend(lines.into_iter().map(|line| (line, false, index)));
+ continue;
+ }
+ let rtl = rtl_script && unicode_bidi::get_base_direction(para) == unicode_bidi::Direction::Rtl;
+ // Arabic words are shaped one by one (joining stops at spaces), so a line's width is the
+ // sum of its words' and shaping stays linear in the paragraph's length. The space is the
+ // paragraph's; a space between Latin words is drawn in the item's font, a few hundredths
+ // of an em apart.
+ let measure = |s: &str| if rtl_script || thai { shaped_width(t, s, rtl) } else { latin_width(t, s) };
+ let space = measure(" ");
+ let (mut line, mut line_w) = (String::new(), 0.0);
+ for word in para.split(' ') {
+ let candidate = if line.is_empty() { word.to_string() } else { format!("{line} {word}") };
+ let candidate_w =
+ if rtl_script || thai { if line.is_empty() { measure(word) } else { line_w + space + measure(word) } } else { measure(&candidate) };
+ if !line.is_empty() && candidate_w > width {
- out.push((std::mem::take(&mut line), rtl));
++ out.push((std::mem::take(&mut line), rtl, index));
+ line = word.to_string();
+ line_w = measure(word);
+ } else {
+ line = candidate;
+ line_w = candidate_w;
+ }
+ }
- out.push((line, rtl));
++ out.push((line, rtl, index));
+ }
+ out
+ }
+
+ /// Thai wrapping at shaped cluster boundaries never detaches a tone/vowel mark from its base.
+ /// This is glyph-safe wrapping, not dictionary-based Thai word segmentation.
+ fn thai_lines(t: &AddedText, para: &str, width: f64) -> Result<Vec<String>, EditError> {
+ let (pieces, _) = shaped_layout(t, para, false)?;
+ let mut atoms = Vec::new();
+ for piece in pieces {
+ match piece {
+ Piece::Shaped(clusters) => atoms.extend(clusters.into_iter().map(|c| (c.text, c.advance * t.size + t.char_spacing))),
+ Piece::Latin(s) => atoms.extend(s.chars().map(|c| {
+ let text = c.to_string();
+ let w = latin_width(t, &text);
+ (text, w)
+ })),
+ }
+ }
+ let mut lines = Vec::new();
+ let (mut line, mut used) = (String::new(), 0.0);
+ for (text, advance) in atoms {
+ if !line.is_empty() && used + advance > width {
+ lines.push(std::mem::take(&mut line));
+ used = 0.0;
+ }
+ line.push_str(&text);
+ used += advance;
+ }
+ lines.push(line);
+ Ok(lines)
+ }
+
+ pub(super) fn is_thai(c: char) -> bool {
+ matches!(u32::from(c), 0x0E00..=0x0E7F)
+ }
+
+ /// Arabic letters, marks, digits and punctuation: an item with any of them is shaped with the
+ /// craft-fonts Arabic face.
+ pub(super) fn is_arabic(c: char) -> bool {
+ matches!(u32::from(c), 0x0600..=0x06FF | 0x0750..=0x077F | 0x0870..=0x08FF | 0xFB50..=0xFDFF | 0xFE70..=0xFEFC)
+ }
+
+ /// Hebrew letters, points, cantillation marks and punctuation (and the presentation forms): an
+ /// item with any of them is drawn with the craft-fonts Hebrew face.
+ pub(super) fn is_hebrew(c: char) -> bool {
+ matches!(u32::from(c), 0x0591..=0x05F4 | 0xFB1D..=0xFB4F)
+ }
+
+ /// The first character of `t` that would be drawn as `?`: outside WinAnsiEncoding and not drawn
+ /// with the craft-fonts Arabic (#125) or Hebrew (#128) face, or Arabic or Hebrew that the face can't
+ /// draw (or that has no face to draw it). Page-content tools refuse such text; the Add-text editor
+ /// keeps it open.
+ pub fn first_undrawable(t: &AddedText) -> Option<char> {
+ if t.text.chars().any(is_thai) {
+ if let Some(c) = t.text.chars().find(|c| is_thai(*c) && !pdfcraft_fonts::thai_has(*c)) {
+ return Some(c);
+ }
+ let rest = AddedText { text: t.text.chars().filter(|c| !is_thai(*c)).collect(), ..t.clone() };
+ return first_undrawable(&rest);
+ }
+ // Arabic or Hebrew that nothing can draw: there's no face, or the face lacks it.
+ if let Some(c) =
+ t.text.chars().find(|c| (shaped_arabic(*c) && !pdfcraft_fonts::arabic_has(*c)) || (is_hebrew(*c) && !pdfcraft_fonts::hebrew_has(*c)))
+ {
+ return Some(c);
+ }
+ if !shaped_by_a_face(t) {
+ // Drawn line by line in the item's standard font (`\n` splits lines). Without the face
+ // that is also how `draw` redraws an existing item, so it's checked that way.
+ return t.text.split('\n').find_map(pdfcraft_fonts::first_non_win_ansi);
+ }
+ // What `shaped_layout` leaves to the standard font, exactly as `draw_shaped` splits it.
- wrapped(t).into_iter().find_map(|(line, rtl)| {
++ wrapped(t).into_iter().find_map(|(line, rtl, _)| {
+ let (pieces, _) = shaped_layout(t, &line, rtl).ok()?;
+ pieces.iter().find_map(|p| match p {
+ Piece::Latin(s) => pdfcraft_fonts::first_non_win_ansi(s),
+ Piece::Shaped(_) => None,
+ })
+ })
+ }
+
+ /// Whether `t` has Arabic or Hebrew that its craft-fonts face draws (so `draw` lays it out with
+ /// [`draw_shaped`]).
+ fn shaped_by_a_face(t: &AddedText) -> bool {
+ (pdfcraft_fonts::document_arabic_font().is_some() && t.text.chars().any(is_arabic))
+ || (pdfcraft_fonts::document_hebrew_font(false).is_some() && t.text.chars().any(is_hebrew))
+ }
+
+ /// An Arabic character the face shapes and draws (U+061C, a direction mark, is dropped).
+ pub(super) fn shaped_arabic(c: char) -> bool {
+ is_arabic(c) && !is_bidi_control(c)
+ }
+
+ /// Direction marks, embeddings, overrides and isolates: they steer the order and are not drawn.
+ fn is_bidi_control(c: char) -> bool {
+ matches!(c, '\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
+ }
+
+ fn mirrored(c: char) -> char {
+ match c {
+ '(' => ')',
+ ')' => '(',
+ '[' => ']',
+ ']' => '[',
+ '{' => '}',
+ '}' => '{',
+ '<' => '>',
+ '>' => '<',
+ '«' => '»',
+ '»' => '«',
+ other => other,
+ }
+ }
+
+ /// A piece of a line with shaped text, in drawing order.
+ pub(super) enum Piece {
+ /// Shown in the item's own standard font.
+ Latin(String),
+ Shaped(Vec<ShapedCluster>),
+ }
+
+ /// A line of a shaped-text item in drawing order (the Unicode bidirectional algorithm, UAX #9), and
+ /// its width at the item's size. `rtl` is its paragraph's direction.
+ pub(super) fn shaped_layout(t: &AddedText, line: &str, rtl: bool) -> Result<(Vec<Piece>, f64), EditError> {
+ // unicode-bidi indexes the first level of a line, so an empty one would panic.
+ if line.is_empty() {
+ return Ok((Vec::new(), 0.0));
+ }
+ let base = if rtl { Level::rtl() } else { Level::ltr() };
+ let info = ParagraphBidiInfo::new(line, Some(base));
+ let (levels, runs) = info.visual_runs(0..line.len());
+ let mut pieces = Vec::new();
+ for run in runs {
+ let run_rtl = levels.get(run.start).is_some_and(Level::is_rtl);
+ // Runs lie on character boundaries; a missing slice is skipped, never a panic.
+ let Some(text) = line.get(run) else { continue };
+ // Arabic and Hebrew letters take their face; so do spaces and punctuation between them
+ // (Hebrew's when they follow Hebrew), which the shaper then mirrors. Latin text (and what
+ // the faces lack) keeps the item's font.
+ let mut segments: Vec<(Option<ShapedScript>, String)> = Vec::new();
+ for c in text.chars().filter(|c| !is_bidi_control(*c)) {
+ let after_hebrew = segments.last().is_some_and(|(kind, _)| *kind == Some(ShapedScript::Hebrew));
+ let script = if is_thai(c) {
+ Some(ShapedScript::Thai)
+ } else if is_hebrew(c) || (run_rtl && after_hebrew && !c.is_alphanumeric() && pdfcraft_fonts::hebrew_has(c)) {
+ Some(ShapedScript::Hebrew)
+ } else if is_arabic(c) || (run_rtl && !c.is_alphanumeric() && pdfcraft_fonts::arabic_has(c)) {
+ Some(ShapedScript::Arabic)
+ } else {
+ None
+ };
+ match segments.last_mut() {
+ Some((kind, s)) if *kind == script => s.push(c),
+ _ => segments.push((script, c.to_string())),
+ }
+ }
+ if run_rtl {
+ segments.reverse();
+ }
+ for (script, s) in segments {
+ pieces.push(if let Some(script) = script {
+ let shaped = match script {
+ ShapedScript::Arabic => shape_arabic(&s, run_rtl).map_err(|e| arabic_error(e, &s))?,
+ ShapedScript::Hebrew => shape_hebrew(&s, run_rtl).map_err(|e| hebrew_error(e, &s))?,
+ ShapedScript::Thai => shape_thai(&s).map_err(|e| thai_error(e, &s))?,
+ };
+ Piece::Shaped(shaped)
+ } else if run_rtl {
+ Piece::Latin(s.chars().rev().map(mirrored).collect())
+ } else {
+ Piece::Latin(s)
+ });
+ }
+ }
+ let width = pieces
+ .iter()
+ .map(|p| match p {
+ Piece::Latin(s) => latin_width(t, s),
+ // Each cluster is shown on its own, so the spacing follows each once.
+ Piece::Shaped(clusters) => clusters.iter().map(|c| c.advance * t.size + t.char_spacing).sum::<f64>(),
+ })
+ .sum();
+ Ok((pieces, width))
+ }
+
+ /// The width of `s` in a shaped-text item; the item's font's estimate if it can't be shaped (drawing
+ /// then reports why).
+ fn shaped_width(t: &AddedText, s: &str, rtl: bool) -> f64 {
+ shaped_layout(t, s, rtl).map(|(_, w)| w).unwrap_or_else(|_| latin_width(t, s))
+ }
+
+ pub(super) fn arabic_error(e: GlyphError, text: &str) -> EditError {
+ EditError::Invalid(match e {
+ GlyphError::NoFont => "Arabic text needs PdfCraft's Arabic font, which this build doesn't include \
+ (to build it in, set CRAFT_FONTS_DIR to a craft-fonts checkout that has an Arab face)"
+ .into(),
+ GlyphError::Missing => format!("the Arabic font can't show \"{text}\""),
+ GlyphError::TooComplex => format!("the Arabic font's glyphs for \"{text}\" are too complex"),
+ })
+ }
+
+ pub(super) fn hebrew_error(e: GlyphError, text: &str) -> EditError {
+ EditError::Invalid(match e {
+ GlyphError::NoFont => "Hebrew text needs PdfCraft's Hebrew font, which this build doesn't include \
+ (to build it in, set CRAFT_FONTS_DIR to a craft-fonts checkout that has a Hebr face)"
+ .into(),
+ GlyphError::Missing => format!("the Hebrew font can't show \"{text}\""),
+ GlyphError::TooComplex => format!("the Hebrew font's glyphs for \"{text}\" are too complex"),
+ })
+ }
+
+ pub(super) fn thai_error(e: GlyphError, text: &str) -> EditError {
+ EditError::Invalid(match e {
+ GlyphError::NoFont => {
+ "Thai text needs a Thai font in this build; rebuild with CRAFT_FONTS_DIR pointing to craft-fonts with a Thai face".into()
+ }
+ GlyphError::Missing => format!("the Thai font can't show \"{text}\""),
+ GlyphError::TooComplex => "the Thai glyphs are too complex; use a shorter text box".into(),
+ })
+ }
+
+ /// The box a text item occupies (height from its lines).
+ pub fn text_rect(t: &AddedText) -> [f64; 4] {
+ let r = norm(t.rect);
+ let h = lines(t).len().max(1) as f64 * t.size * 1.2;
+ [r[0], r[3] - h, r[2], r[3]]
+ }
+
+ /// How far each paste onto a page already holding the copy is offset, down and to the right, so a
+ /// copy doesn't hide what it was copied from (points).
+ pub const PASTE_STEP: f64 = 18.0;
+
+ /// Where a pasted item of box `rect` goes on a page of `size` (display space): with its top-left
+ /// corner at `at`, else where it was, `steps` paste steps ([`PASTE_STEP`]) down and to the right.
+ /// It is kept on the page; one larger than the page keeps its left and top edges on it. A page
+ /// or point that isn't a number leaves the box where it was.
+ pub fn paste_rect(rect: [f64; 4], size: [f64; 2], steps: u32, at: Option<[f64; 2]>) -> [f64; 4] {
+ let [x0, y0, x1, y1] = norm(rect);
+ let (w, h) = (x1 - x0, y1 - y0);
+ let (left, top) = match at {
+ Some([x, y]) => (x, y),
+ None => {
+ let d = PASTE_STEP * f64::from(steps);
+ (x0 + d, y1 - d)
+ }
+ };
+ if !size.iter().chain(&[left, top, w, h]).all(|v| v.is_finite()) {
+ return rect;
+ }
+ let left = left.min(size[0] - w).max(0.0);
+ let top = top.max(h).min(size[1]);
+ [left, top - h, left + w, top]
+ }
+
+ /// Most paste steps [`paste_place`] tries before giving up on finding a free place.
+ const MAX_PASTE_STEPS: u32 = 64;
+
+ /// Where Edit ▸ Paste puts `content` on a page of `size` already holding `items` (display space):
+ /// where it was, or as many paste steps down and to the right as it takes not to land exactly on
+ /// a copy of it (the original it was copied from, or an earlier paste).
+ pub fn paste_place<'a>(items: impl IntoIterator<Item = &'a Content>, content: &Content, size: [f64; 2]) -> [f64; 4] {
+ let same = copy_key(content);
+ let copies: Vec<[f64; 4]> = items.into_iter().filter(|i| copy_key(i) == same).map(Content::rect).collect();
+ let taken = |rect: [f64; 4]| copies.iter().any(|c| c.iter().zip(rect).all(|(a, b)| (a - b).abs() < 0.5));
+ let mut rect = paste_rect(content.rect(), size, 0, None);
+ for steps in 1..=MAX_PASTE_STEPS {
+ if !taken(rect) {
+ break;
+ }
+ rect = paste_rect(content.rect(), size, steps, None);
+ }
+ rect
+ }
+
+ /// What makes two items copies of each other for [`paste_place`]: all but the box, and for an
+ /// image all but the object holding its picture, which a paste into another document stores anew.
+ fn copy_key(c: &Content) -> Content {
+ match c.with_rect([0.0; 4]) {
+ Content::Image(img) => Content::Image(AddedImage { image: ObjRef::new(0, 0), ..img }),
+ text => text,
+ }
+ }
+
+ /// The widest explicit line before wrapping, measured with the PDF writing fonts.
+ pub fn text_width(t: &AddedText) -> f64 {
+ t.text.split('\n').map(|line| shaped_width(t, line, unicode_bidi::get_base_direction(line) == unicode_bidi::Direction::Rtl)).fold(0.0, f64::max)
+ }
diff --cc crates/edit/src/added/store.rs
index 000000000,b89d42900..cbafd0f66
mode 000000,100644..100644
--- a/crates/edit/src/added/store.rs
+++ b/crates/edit/src/added/store.rs
@@@ -1,0 -1,301 +1,308 @@@
+ use super::draw::{draw, params};
+ use super::layout::{first_undrawable, is_thai, nums, shaped_arabic, thai_error};
-use super::types::{Added, AddedImage, AddedText, Align, CHAR_SPACING_LIMIT, Family, MarkerScan, TAG};
++use super::types::{Added, AddedImage, AddedText, CHAR_SPACING_LIMIT, Family, MarkerScan, TAG};
+ use super::*;
+
+ fn parse(doc: &Document, d: &Dict) -> Option<Content> {
+ let r = nums(doc, d.get(b"Rect"));
+ let rect: [f64; 4] = r.try_into().ok()?;
+ match d.name(b"Kind")? {
+ b"Text" => {
+ let (family, bold, italic) = Family::from_base(d.name(b"Font").unwrap_or(b"Helvetica"));
+ let c = nums(doc, d.get(b"Color"));
++ let text = d.get(b"Text").and_then(|t| doc.resolve(t).as_string().map(|s| s.to_text())).unwrap_or_default();
++ let align = align_from(d.int(b"Align"));
++ // At most one entry per paragraph, whatever the file says.
++ let aligns = d
++ .get(b"Aligns")
++ .and_then(|a| {
++ doc.resolve(a)
++ .as_array()
++ .map(|a| a.iter().take(crate::paragraph_align::count(&text)).map(|v| v.as_int().map(|c| align_from(Some(c)))).collect())
++ })
++ .unwrap_or_default();
+ Some(Content::Text(AddedText {
+ rect,
- text: d.get(b"Text").and_then(|t| doc.resolve(t).as_string().map(|s| s.to_text())).unwrap_or_default(),
++ text,
+ family,
+ bold,
+ italic,
+ size: d.get(b"Size").and_then(Object::as_f64).unwrap_or(12.0),
+ color: if c.len() == 3 { [c[0], c[1], c[2]] } else { [0.0; 3] },
- align: match d.int(b"Align") {
- Some(1) => Align::Center,
- Some(2) => Align::Right,
- Some(3) => Align::Justify,
- _ => Align::Left,
- },
++ align,
++ aligns: crate::paragraph_align::tidy(aligns, align),
+ // Items written before character spacing have none.
+ char_spacing: d.get(b"CharSpacing").and_then(Object::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0),
+ }))
+ }
+ b"Image" => {
+ let crop = nums(doc, d.get(b"Crop"));
+ Some(Content::Image(AddedImage {
+ rect,
+ image: d.get(b"Image")?.as_ref()?,
+ rotation: (d.int(b"Rotate").unwrap_or(0).rem_euclid(360) / 90) as u8,
+ flip_h: matches!(d.get(b"FlipH"), Some(Object::Bool(true))),
+ flip_v: matches!(d.get(b"FlipV"), Some(Object::Bool(true))),
+ crop: crop.try_into().unwrap_or([0.0; 4]),
+ }))
+ }
+ _ => None,
+ }
+ }
+
+ fn with_resolved<T>(doc: &Document, object: &Object, f: impl FnOnce(&Object) -> T) -> T {
+ match object {
+ Object::Ref(reference) => {
+ let resolved = doc.get(*reference);
+ f(&resolved)
+ }
+ direct => f(direct),
+ }
+ }
+
+ fn for_each_content_entry(doc: &Document, page: &pdfcraft_model::Page, mut visit: impl FnMut(&Object)) {
+ let Some(contents) = page.dict.get(b"Contents") else { return };
+ with_resolved(doc, contents, |resolved| match resolved {
+ Object::Array(entries) => {
+ for entry in entries {
+ visit(entry);
+ }
+ }
+ _ => visit(contents),
+ });
+ }
+
+ /// Finds page marks and editable added content in one pass over the page content entries.
+ pub fn scan_markers(doc: &Document) -> MarkerScan {
+ let mut scan = MarkerScan::default();
+ for (pi, page) in page_list(doc).iter().enumerate() {
+ for_each_content_entry(doc, page, |entry| {
+ with_resolved(doc, entry, |resolved| {
+ let Some(dict) = resolved.as_dict() else { return };
+ let tag = dict.name(b"PCMark");
+ let kind = if tag == Some(&b"HeaderFooter"[..]) {
+ Some(MarkKind::HeaderFooter)
+ } else if tag == Some(&b"Watermark"[..]) {
+ Some(MarkKind::Watermark)
+ } else if tag == Some(&b"Background"[..]) {
+ Some(MarkKind::Background)
+ } else {
+ None
+ };
+ if let Some(kind) = kind
+ && !scan.marks.contains(&kind)
+ {
+ scan.marks.push(kind);
+ }
+
+ let Some(obj) = Object::as_ref(entry) else { return };
+ if tag != Some(TAG.as_bytes()) {
+ return;
+ }
+ let Some(params_object) = dict.get(b"PCAdded") else { return };
+ with_resolved(doc, params_object, |resolved_params| {
+ let Some(params) = resolved_params.as_dict() else { return };
+ if let Some(content) = parse(doc, params) {
+ // Display points depend on the page's /UserUnit. An item records the one it was
+ // written for; none means 1, as for items written before display space followed
+ // /UserUnit.
+ let written = params
+ .get(b"UserUnit")
+ .and_then(Object::as_f64)
+ .filter(|u| u.is_finite() && *u >= 1.0)
+ .map_or(1.0, |u| u.min(pdfcraft_model::MAX_USER_UNIT));
+ scan.added.push(Added { page: pi, obj, content: content.scaled(page.user_unit(doc) / written) });
+ }
+ });
+ });
+ });
+ }
+ scan
+ }
+
+ fn validate(c: &Content) -> Result<(), EditError> {
+ let r = c.rect();
+ if !r.iter().all(|v| v.is_finite()) {
+ return Err(EditError::Invalid("invalid position".into()));
+ }
+ match c {
+ Content::Text(t) => {
+ if t.text.trim().is_empty() {
+ return Err(EditError::Invalid("type some text first".into()));
+ }
+ if !(t.size.is_finite() && (1.0..=500.0).contains(&t.size)) {
+ return Err(EditError::Invalid("the font size must be between 1 and 500 points".into()));
+ }
+ if !(t.char_spacing.is_finite() && (-CHAR_SPACING_LIMIT..=CHAR_SPACING_LIMIT).contains(&t.char_spacing)) {
+ return Err(EditError::Invalid(format!(
+ "the character spacing must be between -{CHAR_SPACING_LIMIT} and {CHAR_SPACING_LIMIT} points"
+ )));
+ }
+ if (r[2] - r[0]).abs() < 1.0 {
+ return Err(EditError::Invalid("the text box is too narrow".into()));
+ }
+ if t.text.chars().any(is_thai) && pdfcraft_fonts::document_thai_font().is_none() {
+ return Err(thai_error(GlyphError::NoFont, &t.text));
+ }
+ // Without the Arabic face, `draw` decides for the Arabic letters themselves (#403): a new
+ // item is refused with what's missing, and one that already holds Arabic stays movable.
+ // Everything else in it is drawn in the standard font, so it still has to fit.
+ let undrawable = if t.text.chars().any(shaped_arabic) && pdfcraft_fonts::document_arabic_font().is_none() {
+ t.text.split('\n').find_map(|line| {
+ line.chars()
+ .find(|c| !(shaped_arabic(*c) || is_thai(*c) && pdfcraft_fonts::thai_has(*c) || pdfcraft_fonts::win_ansi_encodable(*c)))
+ })
+ } else {
+ first_undrawable(t)
+ };
+ if let Some(c) = undrawable {
+ return Err(crate::undrawable(c));
+ }
+ }
+ Content::Image(_) => {
+ if (r[2] - r[0]).abs() < 1.0 || (r[3] - r[1]).abs() < 1.0 {
+ return Err(EditError::Invalid("the image is too small".into()));
+ }
+ }
+ }
+ Ok(())
+ }
+
+ /// Write an item's stream (new, or replacing `obj`) and make its resources available to the page.
+ fn write(doc: &mut Document, page: usize, c: &Content, obj: Option<ObjRef>) -> Result<ObjRef, EditError> {
+ validate(c)?;
+ let all = page_list(doc);
+ check(&[page], all.len())?;
+ let p = &all[page];
+ let view = p.view_matrix(doc);
+ let user_unit = p.user_unit(doc);
+ // The page gets its own copy of its resources with the item's fonts and images added, and
+ // without the Arabic fonts of the version it replaces.
+ let mut pres = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
+ if let Some(r) = obj {
+ drop_fonts(doc, &mut pres, &own_fonts(doc, r));
+ }
+ let taken = pres.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();
+ let (content, res) = draw(doc, c, view, &taken, obj.is_some())?;
+ if obj.is_none() {
+ crate::check_on_top(doc, p)?;
+ }
+ for (k, v) in res.iter() {
+ let mut sub = pres.get(k).map(|s| doc.resolve(s)).and_then(|s| s.as_dict().cloned()).unwrap_or_default();
+ for (n2, o) in v.as_dict().into_iter().flat_map(|d| d.iter()) {
+ sub.set(n2.clone(), o.clone());
+ }
+ pres.set(k.clone(), Object::Dict(sub));
+ }
+ doc.update_dict(p.obj, |d| d.set(b"Resources".to_vec(), Object::Dict(pres)))?;
+ let mut sd = Dict::new();
+ sd.set(b"PCMark".to_vec(), Object::name(TAG));
+ let mut added = params(c);
+ if user_unit != 1.0 {
+ added.set(b"UserUnit".to_vec(), Object::Real(user_unit));
+ }
+ sd.set(b"PCAdded".to_vec(), Object::Dict(added));
+ let stream = Stream::flate(sd, &content);
+ match obj {
+ Some(r) => {
+ doc.set(r, Object::Stream(stream));
+ Ok(r)
+ }
+ None => {
+ // place_tagged appends a new stream; recover its reference.
+ let p = page_list(doc).swap_remove(page);
+ place_tagged(doc, &p, TAG, content.clone(), false)?;
+ let p = page_list(doc).swap_remove(page);
+ let r = contents(doc, &p)?.last().and_then(Object::as_ref).ok_or_else(|| EditError::Invalid("could not add the content".into()))?;
+ doc.set(r, Object::Stream(stream));
+ Ok(r)
+ }
+ }
+ }
+
+ /// Every added item, page by page, in drawing order.
+ pub fn list_added(doc: &Document) -> Vec<Added> {
+ scan_markers(doc).added
+ }
+
+ /// Add an item to a page (0-based). Returns its index among the page's added items.
+ pub fn add_content(doc: &mut Document, page: usize, c: &Content) -> Result<usize, EditError> {
+ write(doc, page, c, None)?;
+ Ok(list_added(doc).iter().filter(|a| a.page == page).count() - 1)
+ }
+
+ fn find(doc: &Document, page: usize, index: usize) -> Result<Added, EditError> {
+ list_added(doc)
+ .into_iter()
+ .filter(|a| a.page == page)
+ .nth(index)
+ .ok_or_else(|| EditError::Invalid(format!("page {} has no added item {}", page + 1, index + 1)))
+ }
+
+ /// Replace item `index` of `page` (moved, resized, retyped or reformatted).
+ pub fn update_content(doc: &mut Document, page: usize, index: usize, c: &Content) -> Result<(), EditError> {
+ let a = find(doc, page, index)?;
+ if std::mem::discriminant(&a.content) != std::mem::discriminant(c) {
+ return Err(EditError::Invalid("an item can't change between text and image".into()));
+ }
+ write(doc, page, c, Some(a.obj))?;
+ Ok(())
+ }
+
+ /// Remove item `index` of `page`.
+ pub fn delete_content(doc: &mut Document, page: usize, index: usize) -> Result<(), EditError> {
+ let a = find(doc, page, index)?;
+ let p = page_list(doc).swap_remove(page);
+ let list: Vec<Object> = contents(doc, &p)?.into_iter().filter(|o| o.as_ref() != Some(a.obj)).collect();
+ let fonts = own_fonts(doc, a.obj);
+ // Only the page's own resources carry an item's fonts (`write` gives the page a copy).
+ let res = match p.dict.get(b"Resources") {
+ Some(Object::Dict(d)) if !fonts.is_empty() => Some(d.clone()),
+ _ => None,
+ };
+ let res = res.map(|mut r| {
+ drop_fonts(doc, &mut r, &fonts);
+ r
+ });
+ doc.update_dict(p.obj, |d| {
+ d.set(b"Contents".to_vec(), Object::Array(list));
+ if let Some(r) = res {
+ d.set(b"Resources".to_vec(), Object::Dict(r));
+ }
+ })?;
+ Ok(())
+ }
+
+ /// Leave only item `index` on `page`: its contents become the item's own stream and its
+ /// annotations go, so a render of the page (on a transparent backdrop) is the item's pixels
+ /// alone. For previews on a copy of the document; the page's resources stay as they are.
+ pub fn isolate_content(doc: &mut Document, page: usize, index: usize) -> Result<(), EditError> {
+ let a = find(doc, page, index)?;
+ let p = page_list(doc).swap_remove(page);
+ // An item's stream starts from the page's initial graphics state: `place_tagged` closes
+ // everything drawn before it, so it draws the same on its own.
+ doc.update_dict(p.obj, |d| {
+ d.set(b"Contents".to_vec(), Object::Array(vec![Object::Ref(a.obj)]));
+ d.remove(b"Annots");
+ })?;
+ Ok(())
+ }
+
+ /// The Type 3 fonts an Arabic item's stream shows text with. Each item has its own (`draw_shaped`
+ /// names them so), so they go when the item is replaced or deleted.
+ fn own_fonts(doc: &Document, obj: ObjRef) -> Vec<Vec<u8>> {
+ let Object::Stream(s) = &*doc.get(obj) else { return Vec::new() };
+ let Ok(data) = s.decoded() else { return Vec::new() };
+ data.split(u8::is_ascii_whitespace).filter_map(|w| w.strip_prefix(b"/")).filter(|w| w.starts_with(b"PCAr")).map(<[u8]>::to_vec).collect()
+ }
+
+ fn drop_fonts(doc: &Document, res: &mut Dict, names: &[Vec<u8>]) {
+ if names.is_empty() {
+ return;
+ }
+ let Some(mut fonts) = res.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()) else { return };
+ for name in names {
+ fonts.remove(name);
+ }
+ res.set(b"Font".to_vec(), Object::Dict(fonts));
+ }
diff --cc crates/edit/src/added/types.rs
index 000000000,0a9f92f92..c3e651a05
mode 000000,100644..100644
--- a/crates/edit/src/added/types.rs
+++ b/crates/edit/src/added/types.rs
@@@ -1,0 -1,212 +1,223 @@@
+ use super::layout::norm;
+ use super::*;
+
+ pub(super) const TAG: &str = "Added";
+
+ /// The most character spacing an added text takes either way, in points: as far as the font size goes.
+ pub const CHAR_SPACING_LIMIT: f64 = 500.0;
+
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
+ pub enum Family {
+ #[default]
+ Helvetica,
+ Times,
+ Courier,
+ }
+
+ impl Family {
+ pub fn label(self) -> &'static str {
+ match self {
+ Family::Helvetica => "Helvetica",
+ Family::Times => "Times",
+ Family::Courier => "Courier",
+ }
+ }
+
+ /// The standard-14 font name for this family and style.
+ pub fn base_font(self, bold: bool, italic: bool) -> &'static str {
+ match (self, bold, italic) {
+ (Family::Helvetica, false, false) => "Helvetica",
+ (Family::Helvetica, true, false) => "Helvetica-Bold",
+ (Family::Helvetica, false, true) => "Helvetica-Oblique",
+ (Family::Helvetica, true, true) => "Helvetica-BoldOblique",
+ (Family::Times, false, false) => "Times-Roman",
+ (Family::Times, true, false) => "Times-Bold",
+ (Family::Times, false, true) => "Times-Italic",
+ (Family::Times, true, true) => "Times-BoldItalic",
+ (Family::Courier, false, false) => "Courier",
+ (Family::Courier, true, false) => "Courier-Bold",
+ (Family::Courier, false, true) => "Courier-Oblique",
+ (Family::Courier, true, true) => "Courier-BoldOblique",
+ }
+ }
+
+ pub(super) fn from_base(base: &[u8]) -> (Family, bool, bool) {
+ let s = String::from_utf8_lossy(base);
+ let family = if s.starts_with("Times") {
+ Family::Times
+ } else if s.starts_with("Courier") {
+ Family::Courier
+ } else {
+ Family::Helvetica
+ };
+ (family, s.contains("Bold"), s.contains("Italic") || s.contains("Oblique"))
+ }
+
+ /// Advance width of `s` at `size` points, from the published standard-14 metrics.
+ ///
+ /// `italic` matters: the item is written out as the oblique/italic face (see [`Family::base_font`]),
+ /// whose published widths differ from the upright face (Times-Italic `A` is 611, Times-Roman 722).
+ pub fn width(self, s: &str, size: f64, bold: bool, italic: bool) -> f64 {
+ self.std14(bold, italic).text_width(s, size)
+ }
+
+ /// The standard-14 face this family means at the given style.
+ pub fn std14(self, bold: bool, italic: bool) -> Std14 {
+ match (self, bold, italic) {
+ (Family::Courier, false, false) => Std14::Courier,
+ (Family::Courier, true, false) => Std14::CourierBold,
+ (Family::Courier, false, true) => Std14::CourierOblique,
+ (Family::Courier, true, true) => Std14::CourierBoldOblique,
+ (Family::Times, false, false) => Std14::TimesRoman,
+ (Family::Times, true, false) => Std14::TimesBold,
+ (Family::Times, false, true) => Std14::TimesItalic,
+ (Family::Times, true, true) => Std14::TimesBoldItalic,
+ (Family::Helvetica, false, false) => Std14::Helvetica,
+ (Family::Helvetica, true, false) => Std14::HelveticaBold,
+ (Family::Helvetica, false, true) => Std14::HelveticaOblique,
+ (Family::Helvetica, true, true) => Std14::HelveticaBoldOblique,
+ }
+ }
+ }
+
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
+ pub enum Align {
+ #[default]
+ Left,
+ Center,
+ Right,
+ /// Lines (but the last) stretched to the box's width.
+ Justify,
+ }
+
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct AddedText {
+ /// The text box in display space; its width wraps the text and its top is the first line's
+ /// top. The height follows the text.
+ pub rect: [f64; 4],
+ pub text: String,
+ pub family: Family,
+ pub bold: bool,
+ pub italic: bool,
+ pub size: f64,
+ pub color: [f64; 3],
+ pub align: Align,
+ /// Extra space after every character, in points: the PDF's character spacing (`Tc`).
+ pub char_spacing: f64,
++ /// Paragraphs (lines typed with Enter) aligned other than [`AddedText::align`], by index;
++ /// `None` and paragraphs past the end follow `align` ([`crate::paragraph_align`]).
++ pub aligns: Vec<Option<Align>>,
++}
++
++impl AddedText {
++ /// Paragraph `i`'s alignment.
++ pub fn paragraph_align(&self, i: usize) -> Align {
++ crate::paragraph_align::align_of(&self.aligns, i, self.align)
++ }
+ }
+
+ impl Default for AddedText {
+ fn default() -> Self {
+ AddedText {
+ rect: [0.0; 4],
+ text: String::new(),
+ family: Family::Helvetica,
+ bold: false,
+ italic: false,
+ size: 12.0,
+ color: [0.0; 3],
+ align: Align::Left,
++ aligns: Vec::new(),
+ char_spacing: 0.0,
+ }
+ }
+ }
+
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct AddedImage {
+ /// Display space.
+ pub rect: [f64; 4],
+ /// The image XObject.
+ pub image: ObjRef,
+ /// Quarter turns counter-clockwise (0–3).
+ pub rotation: u8,
+ pub flip_h: bool,
+ pub flip_v: bool,
+ /// The fraction trimmed from each side of the image: left, bottom, right, top (see
+ /// [`AddedImage::crop_valid`]).
+ pub crop: [f64; 4],
+ }
+
+ impl AddedImage {
+ pub fn new(rect: [f64; 4], image: ObjRef) -> Self {
+ AddedImage { rect, image, rotation: 0, flip_h: false, flip_v: false, crop: [0.0; 4] }
+ }
+
+ /// The least of the image's width and of its height that a crop keeps.
+ pub const MIN_CROP_KEEP: f64 = 0.05;
+
+ /// How far a sum of two sides may pass the most a crop trims: `0.05 + 0.9` is
+ /// `0.9500000000000001` in floating point and still keeps 5 %.
+ const CROP_ROUNDING: f64 = 1e-9;
+
+ /// Whether `crop` trims every side by a fraction from 0 to under 1 and keeps at least
+ /// [`AddedImage::MIN_CROP_KEEP`] across each axis: one side may trim 95 % when its opposite
+ /// trims nothing.
+ pub fn crop_valid(crop: [f64; 4]) -> bool {
+ let [l, b, r, t] = crop;
+ let most = 1.0 - Self::MIN_CROP_KEEP;
+ crop.iter().all(|v| v.is_finite() && (0.0..1.0).contains(v)) && l + r <= most + Self::CROP_ROUNDING && b + t <= most + Self::CROP_ROUNDING
+ }
+
+ /// `crop` brought into [`AddedImage::crop_valid`] range, for one read from a file: each side
+ /// in range, and an axis that trims too much keeps its two sides' proportion.
+ pub fn clamp_crop(crop: [f64; 4]) -> [f64; 4] {
+ let most = 1.0 - Self::MIN_CROP_KEEP;
+ let [l, b, r, t] = crop.map(|v| if v.is_finite() { v.max(0.0) } else { 0.0 });
+ // Scaled from the halves, whose sum can't overflow, so the pair keeps its proportion;
+ // a pair within the limit keeps each side within it too.
+ let fit = |a: f64, c: f64| {
+ let half = a / 2.0 + c / 2.0;
+ if half > (most + Self::CROP_ROUNDING) / 2.0 { (a / 2.0 / half * most, c / 2.0 / half * most) } else { (a, c) }
+ };
+ let ((l, r), (b, t)) = (fit(l, r), fit(b, t));
+ [l, b, r, t]
+ }
+
+ /// The matrix from image space (the unit square) to display space: crop, flip, rotate,
+ /// then fill the box.
+ pub(super) fn matrix(&self) -> pdfcraft_content::Matrix {
+ use pdfcraft_content::Matrix as M;
+ let [l, b, r, t] = Self::clamp_crop(self.crop);
+ let (cw, ch) = (1.0 - l - r, 1.0 - b - t);
+ let mut m = M([1.0 / cw, 0.0, 0.0, 1.0 / ch, -l / cw, -b / ch]);
+ if self.flip_h {
+ m = m.then(&M([-1.0, 0.0, 0.0, 1.0, 1.0, 0.0]));
+ }
+ if self.flip_v {
+ m = m.then(&M([1.0, 0.0, 0.0, -1.0, 0.0, 1.0]));
+ }
+ for _ in 0..self.rotation % 4 {
+ // A quarter turn counter-clockwise within the unit square.
+ m = m.then(&M([0.0, 1.0, -1.0, 0.0, 1.0, 0.0]));
+ }
+ let [x0, y0, x1, y1] = norm(self.rect);
+ m.then(&M([x1 - x0, 0.0, 0.0, y1 - y0, x0, y0]))
+ }
+ }
+
+ /// An added item on a page.
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct Added {
+ pub page: usize,
+ /// The item's content stream.
+ pub obj: ObjRef,
+ pub content: Content,
+ }
+
+ /// PdfCraft-owned page content discovered in one page/content traversal.
+ #[derive(Clone, Debug, Default, PartialEq)]
+ pub struct MarkerScan {
+ pub marks: Vec<MarkKind>,
+ pub added: Vec<Added>,
+ }
diff --cc crates/edit/src/text.rs
index df0067ff3,eb4520935..ece164c79
--- a/crates/edit/src/text.rs
+++ b/crates/edit/src/text.rs
@@@ -24,9 -24,43 +24,43 @@@ use crate::EditError
mod regions;
#[path = "text_session.rs"]
mod session;
-use regions::{group_blocks, is_centred, rewrite_styled_block};
+use regions::{alignment_frame, group_blocks, is_centred, rewrite_styled_block};
pub use session::TextSession;
+ mod blocks;
+ mod editor;
+ mod fallback;
+ mod interp;
+ mod lines;
+ mod rewrite;
+
+ use blocks::paragraph_separator;
+ #[cfg(test)]
+ use blocks::wrap;
+ pub use blocks::{
+ BlockKey, BlockStyle, RangeStyle, ReadingBlocks, TextBlock, block_overlapping, clear_block, reading_blocks, reading_blocks_checked,
+ replace_block, text_blocks,
+ };
+ use editor::layout_draft;
+ pub use editor::{TextEditLayout, TextEditorFont, register_text_font, text_edit_layout, text_editor_fonts};
+ #[cfg(test)]
+ pub(crate) use fallback::SOURCE_SPACE_CALLS;
+ use fallback::{
+ MAX_TYPE3_GLYPHS, Type3Glyph, fallback_face, needs_type3, no_fallback_font, no_glyph_for, same_base_font, same_font, source_encodes,
+ source_family, source_program, source_show, source_space, source_width, strip_subset_tag, type3_faces, type3_glyph, write_type3_glyphs,
+ };
+ #[cfg(test)]
+ use fallback::{add_type3_font, is_type3_fallback};
+ use interp::{Origin, Paint, union};
+ use lines::page_dict;
+ pub(crate) use lines::{FormBudget, content_streams, content_streams_within, form_call, rewritten_contents, splice};
+ pub use lines::{MAX_FORM_DEPTH, MAX_FORM_VISITS, glyph_text_lines, text_lines};
+ pub use rewrite::{LineEdit, replace_line, rewrite_block};
+ use rewrite::{coincident_ops, rewrite_block_from};
+ #[cfg(test)]
+ pub(crate) use rewrite::{replace_line_with_limit, rewrite_block_with_limit};
+ pub(crate) use rewrite::{reveal_ops, selectable_blocks, translate_blocks};
+
/// One line of existing text.
#[derive(Clone, Debug, PartialEq)]
pub struct TextLine {
diff --cc crates/edit/src/text/blocks.rs
index 000000000,8d3d224da..1228cb865
mode 000000,100644..100644
--- a/crates/edit/src/text/blocks.rs
+++ b/crates/edit/src/text/blocks.rs
@@@ -1,0 -1,424 +1,427 @@@
+ use super::interp::{Carry, interpret};
+ use super::lines::{content_streams, page_dict, reading_lines, rewritten_contents, splice, text_lines};
+ use super::rewrite::{LineEdit, coincident_ops, rewrite_block};
+ use super::*;
+
+ /// An editable text region: adjacent runs on visual rows, followed by aligned rows.
+ /// A region may contain several source fonts, sizes, colours and weights.
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct TextBlock {
+ /// The lines' text joined with spaces (lines that ended in a hyphen are joined directly).
+ pub text: String,
+ pub rect: [f64; 4],
+ pub base_font: String,
+ pub size: f64,
+ pub bold: bool,
+ pub italic: bool,
+ /// The text fill colour as RGB, used by the visual editor and preserved when no colour
+ /// override is requested.
+ pub color: [f64; 3],
+ /// Counterclockwise baseline angle in page user space, in degrees.
+ pub rotation: f64,
+ /// Indexes into [`text_lines`].
+ pub lines: Vec<usize>,
+ /// Visual rows; each contains indexes into [`text_lines`], including mixed-style runs.
+ pub rows: Vec<Vec<usize>>,
+ /// Text for the inline editor, with a newline only between visual rows.
+ pub editor_text: String,
+ /// Byte ranges in `editor_text` and their source line indexes.
+ pub spans: Vec<(std::ops::Range<usize>, usize)>,
+ /// Every line is invisible text (rendering mode 3): an OCR layer over a scanned image, whose
+ /// pixels show the words. A rewrite draws the new text visibly (see [`BlockStyle::cover`]).
+ pub invisible: bool,
+ }
+
+ impl TextBlock {
+ /// Preserve styles outside the changed ranges; inserted characters inherit the surrounding
+ /// source run. The texts are aligned word by word, so words left untouched between two edits
+ /// keep their own runs (#2198); past [`MAX_CHANGED_WORDS`] the draft counts as one change.
+ /// Byte ranges are always UTF-8 boundaries. Linear time, including large edits.
+ pub fn edited_spans(&self, draft: &str) -> Vec<(std::ops::Range<usize>, usize)> {
+ if self.editor_text.len() > 4_000_000 || draft.len() > 4_000_000 {
+ return vec![(0..draft.len(), self.lines.first().copied().unwrap_or(0))];
+ }
+ let old: Vec<_> = self.editor_text.chars().collect();
+ let new: Vec<_> = draft.char_indices().collect();
+ let chars: Vec<_> = new.iter().map(|(_, c)| *c).collect();
+ let mut original = Vec::with_capacity(old.len());
+ let mut span = 0;
+ for (byte, _) in self.editor_text.char_indices() {
+ while self.spans.get(span).is_some_and(|(r, _)| byte >= r.end) {
+ span += 1;
+ }
+ original.push(self.spans.get(span).or_else(|| self.spans.last()).map_or(0, |(_, i)| *i));
+ }
+ let mut sources = Vec::with_capacity(new.len());
+ let slices = |text: &[char]| words(text).into_iter().map(|w| text.get(w).unwrap_or_default().to_vec()).collect::<Vec<_>>();
+ let (old_words, new_words) = (slices(&old), slices(&chars));
+ match edit_script(&old_words, &new_words, MAX_CHANGED_WORDS) {
+ Some(script) => {
+ // `(o, n)`: where the current change starts in the old and new text; `(x, y)`: where it ends.
+ let ((mut o, mut n), (mut x, mut y)) = ((0, 0), (0, 0));
+ let (mut a, mut b) = (old_words.iter(), new_words.iter());
+ for step in script {
+ match step {
+ Step::Keep => {
+ replaced(&original, o, old.get(o..x).unwrap_or_default(), chars.get(n..y).unwrap_or_default(), &mut sources);
+ let len = a.next().map_or(0, Vec::len);
+ b.next();
+ sources.extend(original.get(x..x.saturating_add(len)).unwrap_or_default());
+ (x, y) = (x.saturating_add(len), y.saturating_add(len));
+ (o, n) = (x, y);
+ }
+ Step::Delete => x = x.saturating_add(a.next().map_or(0, Vec::len)),
+ Step::Insert => y = y.saturating_add(b.next().map_or(0, Vec::len)),
+ }
+ }
+ replaced(&original, o, old.get(o..x).unwrap_or_default(), chars.get(n..y).unwrap_or_default(), &mut sources);
+ }
+ None => replaced(&original, 0, &old, &chars, &mut sources),
+ }
+ let fallback = original.first().copied().unwrap_or(0);
+ let mut result: Vec<(std::ops::Range<usize>, usize)> = Vec::new();
+ for (i, (byte, ch)) in new.iter().enumerate() {
+ let source = sources.get(i).copied().unwrap_or(fallback);
+ let end = byte.saturating_add(ch.len_utf8());
+ if let Some((range, _)) = result.last_mut().filter(|(_, prev)| *prev == source) {
+ range.end = end;
+ } else {
+ result.push((*byte..end, source));
+ }
+ }
+ result
+ }
+ }
+
+ /// Changed words [`TextBlock::edited_spans`] aligns before it treats the draft as one change.
+ /// Myers' diff costs O((N + M) · D), so bounding D keeps it linear.
+ const MAX_CHANGED_WORDS: usize = 64;
+
+ /// `text` split into words, each with the whitespace after it, as char ranges.
+ fn words(text: &[char]) -> Vec<std::ops::Range<usize>> {
+ let mut out = Vec::new();
+ let mut start = 0;
+ for (i, pair) in text.windows(2).enumerate() {
+ if let [a, b] = pair
+ && a.is_whitespace()
+ && !b.is_whitespace()
+ {
+ out.push(start..i + 1);
+ start = i + 1;
+ }
+ }
+ if start < text.len() {
+ out.push(start..text.len());
+ }
+ out
+ }
+
+ #[derive(Clone, Copy, Debug, PartialEq)]
+ enum Step {
+ Keep,
+ Delete,
+ Insert,
+ }
+
+ /// Myers' shortest edit script from `a` to `b`, or `None` when it takes more than `max` steps.
+ fn edit_script<T: PartialEq>(a: &[T], b: &[T], max: usize) -> Option<Vec<Step>> {
+ let (n, m) = (a.len() as isize, b.len() as isize);
+ let max = max.min(a.len().saturating_add(b.len())) as isize;
+ // Furthest x reached on each diagonal k = x - y, stored at k + max + 1.
+ let at = |v: &[isize], k: isize| usize::try_from(k + max + 1).ok().and_then(|i| v.get(i).copied()).unwrap_or(0);
+ let mut v = vec![0isize; (2 * max + 3) as usize];
+ let mut trace = Vec::new();
+ for d in 0..=max {
+ trace.push(v.clone());
+ for k in (-d..=d).step_by(2) {
+ let down = k == -d || (k != d && at(&v, k - 1) < at(&v, k + 1));
+ let mut x = if down { at(&v, k + 1) } else { at(&v, k - 1) + 1 };
+ let mut y = x - k;
+ while x < n && y < m && a.get(x as usize) == b.get(y as usize) {
+ x += 1;
+ y += 1;
+ }
+ if let Some(slot) = usize::try_from(k + max + 1).ok().and_then(|i| v.get_mut(i)) {
+ *slot = x;
+ }
+ if x >= n && y >= m {
+ return Some(backtrack(&trace, n, m, max));
+ }
+ }
+ }
+ None
+ }
+
+ /// Walk Myers' saved frontiers back from the end to the edit script.
+ fn backtrack(trace: &[Vec<isize>], n: isize, m: isize, max: isize) -> Vec<Step> {
+ let at = |v: &[isize], k: isize| usize::try_from(k + max + 1).ok().and_then(|i| v.get(i).copied()).unwrap_or(0);
+ let mut steps = Vec::new();
+ let (mut x, mut y) = (n, m);
+ for (d, v) in trace.iter().enumerate().rev() {
+ let (d, k) = (d as isize, x - y);
+ let prev_k = if k == -d || (k != d && at(v, k - 1) < at(v, k + 1)) { k + 1 } else { k - 1 };
+ let prev_x = at(v, prev_k);
+ let prev_y = prev_x - prev_k;
+ while x > prev_x && y > prev_y {
+ steps.push(Step::Keep);
+ x -= 1;
+ y -= 1;
+ }
+ if d > 0 {
+ steps.push(if x == prev_x { Step::Insert } else { Step::Delete });
+ }
+ (x, y) = (prev_x, prev_y);
+ }
+ steps.reverse();
+ steps
+ }
+
+ /// `old`, at char `at` of the source, became `new`: characters kept at either end keep their
+ /// runs, and the rest inherit the run just before the change (or the first one it replaces).
+ fn replaced(original: &[usize], at: usize, old: &[char], new: &[char], out: &mut Vec<usize>) {
+ let prefix = old.iter().zip(new).take_while(|(a, b)| a == b).count();
+ let suffix = old.iter().rev().zip(new.iter().rev()).take(old.len().min(new.len()).saturating_sub(prefix)).take_while(|(a, b)| a == b).count();
+ let start = at.saturating_add(prefix);
+ let inherited = start.checked_sub(1).and_then(|i| original.get(i)).or_else(|| original.get(start)).copied().unwrap_or(0);
+ for i in 0..new.len() {
+ let source = if i < prefix {
+ original.get(at.saturating_add(i)).copied()
+ } else if i >= new.len().saturating_sub(suffix) {
+ original.get(at.saturating_add(old.len()).saturating_sub(new.len() - i)).copied()
+ } else {
+ Some(inherited)
+ };
+ out.push(source.unwrap_or(inherited));
+ }
+ }
+
+ /// How a listing of [`text_blocks`] records a paragraph so that it can be found again.
+ ///
+ /// The index of a paragraph is its position in a list regrouped from geometry on every read, so
+ /// an edit that merges or splits paragraphs makes the same index name another one (#2516). A key
+ /// names the paragraph by what it says and where it is; a paragraph that no longer exists as
+ /// such has no match, instead of a neighbour taking its place.
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct BlockKey {
+ text: String,
+ rect: [f64; 4],
+ }
+
+ impl BlockKey {
+ /// Two boxes are the same box within this many points.
+ const TOLERANCE: f64 = 0.01;
+
+ pub fn of(block: &TextBlock) -> Self {
+ Self { text: block.text.clone(), rect: block.rect }
+ }
+
+ /// The paragraph's box when it was recorded (user space).
+ pub fn rect(&self) -> [f64; 4] {
+ self.rect
+ }
+
+ /// The paragraph in `blocks` with this text and box. `hint` is tried first, so two
+ /// paragraphs drawn on top of one another are told apart by their order.
+ pub fn find(&self, blocks: &[TextBlock], hint: usize) -> Option<usize> {
+ let matches = |b: &TextBlock| b.text == self.text && b.rect.iter().zip(&self.rect).all(|(a, b)| (a - b).abs() <= Self::TOLERANCE);
+ match blocks.get(hint) {
+ Some(b) if matches(b) => Some(hint),
+ _ => blocks.iter().position(matches),
+ }
+ }
+ }
+
+ /// The paragraph in `blocks` whose box overlaps `rect` the most, if any overlaps it at all. An
+ /// edit rewrites a paragraph in place, so this is the paragraph it became.
+ pub fn block_overlapping(blocks: &[TextBlock], rect: [f64; 4]) -> Option<usize> {
+ // `f64::min` and `max` skip a NaN, which would make a box that isn't a number overlap anything.
+ let area = |b: &TextBlock| {
+ if !rect.iter().chain(&b.rect).all(|v| v.is_finite()) {
+ return 0.0;
+ }
+ let w = b.rect[2].min(rect[2]) - b.rect[0].max(rect[0]);
+ let h = b.rect[3].min(rect[3]) - b.rect[1].max(rect[1]);
+ if w > 0.0 && h > 0.0 { w * h } else { 0.0 }
+ };
+ blocks.iter().enumerate().map(|(i, b)| (i, area(b))).filter(|(_, a)| *a > 0.0).max_by(|(_, a), (_, b)| a.total_cmp(b)).map(|(i, _)| i)
+ }
+
+ /// The paragraphs on a page (0-based).
+ pub fn text_blocks(doc: &Document, page: usize) -> Result<Vec<TextBlock>, EditError> {
+ let lines = text_lines(doc, page)?;
+ Ok(group_blocks(&lines))
+ }
+
+ /// Remove a paragraph's glyphs for a temporary editor background. Numeric TJ adjustments
+ /// preserve the text matrix, so unselected text positioned relative to it stays in place.
+ /// Call this on a clone: it is a preview operation, not a document edit.
+ pub fn clear_block(doc: &mut Document, page: usize, block: usize) -> Result<(), EditError> {
+ let lines = text_lines(doc, page)?;
+ let blocks = group_blocks(&lines);
+ let target = blocks.get(block).ok_or_else(|| EditError::Invalid("the paragraph no longer exists".into()))?;
+ let targets: Vec<&TextLine> = target.lines.iter().filter_map(|i| lines.get(*i)).collect();
+ targets.iter().try_for_each(|line| line.ensure_editable())?;
+ let mut drops = coincident_ops(&lines, &targets);
+ drops.extend(target.lines.iter().filter_map(|i| lines.get(*i)).flat_map(|l| l.ops.iter().copied()));
+ let p = page_dict(doc, page)?;
+ let res = p.dict.get(b"Resources").and_then(|r| doc.resolve(r).as_dict().cloned()).unwrap_or_default();
+ let streams = content_streams(doc, &p.dict)?;
+ let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
+ let ops = pieces.parse().ops;
+ let shown = interpret(doc, &ops, &res, &mut HashMap::new(), &mut Carry::new(), None, None)?;
+ let mut patches = HashMap::new();
+ for s in shown.into_iter().filter(|s| drops.contains(&s.op)) {
+ if s.state.render_mode >= 4 {
+ return Err(EditError::Invalid("text used as a clipping path cannot be previewed for editing".into()));
+ }
+ let denominator = s.state.size * s.state.scale;
+ let adjustment = if denominator != 0.0 { -1000.0 * s.advance / denominator } else { 0.0 };
+ if !adjustment.is_finite() || (denominator == 0.0 && s.advance != 0.0) {
+ return Err(EditError::Invalid("the paragraph's text advance cannot be previewed".into()));
+ }
+ let mut replacement = Vec::new();
+ if let Some(op) = ops.get(s.op) {
+ if op.is("\"") {
+ replacement.push(Op::new("Tw", vec![op.operands.first().cloned().unwrap_or(Object::Int(0))]));
+ replacement.push(Op::new("Tc", vec![op.operands.get(1).cloned().unwrap_or(Object::Int(0))]));
+ }
+ if op.is("'") || op.is("\"") {
+ replacement.push(Op::new("T*", vec![]));
+ }
+ }
+ replacement.push(Op::new("TJ", vec![Object::Array(vec![pdfcraft_content::num(adjustment)])]));
+ patches.insert(s.op, replacement);
+ }
+ let data = splice(&pieces, &ops, |i| patches.remove(&i).map_or((Vec::new(), true), |v| (v, false)));
+ let contents = rewritten_contents(doc, &streams, data);
+ doc.update_dict(p.obj, |d| d.set(b"Contents".to_vec(), contents))?;
+ Ok(())
+ }
+
+ /// The paragraphs on a page as a reader sees them, including text drawn by form XObjects
+ /// (Export to Word, HTML and RTF). Read-only: indexes into this list are not
+ /// [`text_blocks`] indexes, so they can't be passed to [`replace_block`] or [`rewrite_block`].
+ /// [`reading_blocks_checked`] also says whether text was left out.
+ pub fn reading_blocks(doc: &Document, page: usize) -> Result<Vec<TextBlock>, EditError> {
+ reading_blocks_checked(doc, page).map(|r| r.blocks)
+ }
+
+ /// A page's paragraphs as a reader sees them ([`reading_blocks_checked`]).
+ #[derive(Clone, Debug, Default, PartialEq)]
+ pub struct ReadingBlocks {
+ /// The paragraphs, as [`reading_blocks`] returns them.
+ pub blocks: Vec<TextBlock>,
+ /// The page draws forms nested deeper than [`MAX_FORM_DEPTH`], more of them than
+ /// [`MAX_FORM_VISITS`], or forms that run past what the page's content left of its decode
+ /// budget. Reading leaves those forms out to stay bounded on hostile files, so their text
+ /// is missing from `blocks`; [`crate::reading_images`] walks the same forms and misses
+ /// their images too.
+ pub truncated: bool,
+ }
+
+ /// [`reading_blocks`], saying whether the limits that bound reading left text out. A page
+ /// whose `/Contents` alone runs past its decode budget is an [`EditError::Invalid`], not a
+ /// truncated result.
+ pub fn reading_blocks_checked(doc: &Document, page: usize) -> Result<ReadingBlocks, EditError> {
+ let (lines, truncated) = reading_lines(doc, page)?;
+ Ok(ReadingBlocks { blocks: regions::group_reading_blocks(&lines), truncated })
+ }
+
+ // An ideographic space carries intentional Japanese spacing, including paragraph indentation.
+ // Keep other whitespace normalization unchanged.
+ pub(crate) fn paragraph_separator(c: char) -> bool {
+ c.is_whitespace() && c != '\u{3000}'
+ }
+
+ /// Greedy word wrapping to `width` with `advance` giving a string's width. Each `\n` starts a
+ /// new line. A row may also end inside a word of Chinese or Japanese text ([`crate::linebreak`]);
+ /// those pieces join without a space. Every white-space character is written as one space, so
+ /// a run of spaces typed between, before or after words stays (#4199); only the spaces where a
-/// row wraps are dropped.
-pub(super) fn wrap(text: &str, width: f64, advance: impl Fn(&str) -> f64) -> Vec<String> {
++/// row wraps are dropped. Each line comes with the `\n`-separated row it is from.
++pub(super) fn wrap(text: &str, width: f64, advance: impl Fn(&str) -> f64) -> Vec<(String, usize)> {
+ let mut out = Vec::new();
- for row in text.split('\n') {
++ for (index, row) in text.split('\n').enumerate() {
+ let mut line = String::new();
+ let start = out.len();
+ // The separators read since the last word: each one boundary between `split` pieces.
+ let mut gap = 0usize;
+ for (k, word) in row.split(paragraph_separator).enumerate() {
+ if k > 0 {
+ gap = gap.saturating_add(1);
+ }
+ if word.is_empty() {
+ continue;
+ }
+ let spaces = " ".repeat(std::mem::take(&mut gap));
+ for (i, piece) in crate::linebreak::pieces(word).into_iter().enumerate() {
+ let candidate = if i == 0 { format!("{line}{spaces}{piece}") } else { format!("{line}{piece}") };
+ // A row holding only the spaces that indent it doesn't wrap before its first word.
+ if line.chars().any(|c| c != ' ') && advance(&candidate) > width {
- out.push(std::mem::take(&mut line));
++ out.push((std::mem::take(&mut line), index));
+ line = piece.to_string();
+ } else {
+ line = candidate;
+ }
+ }
+ }
+ line.push_str(&" ".repeat(gap));
+ if !line.is_empty() || out.len() == start {
- out.push(line);
++ out.push((line, index));
+ }
+ }
+ out
+ }
+
+ /// Replace paragraph `block` (an index into [`text_blocks`]) with `text`, rewrapped to the
+ /// paragraph's width with its line spacing. The paragraph keeps its first line's position, font
+ /// (or Helvetica when the font can't show the text), size and colour.
+ pub fn replace_block(doc: &mut Document, page: usize, block: usize, text: &str) -> Result<LineEdit, EditError> {
+ rewrite_block(doc, page, block, Some(text), &BlockStyle::default())
+ }
+
+ /// Formatting for a rewritten paragraph (`None` keeps the paragraph's own).
+ #[derive(Clone, Debug, Default, PartialEq)]
+ pub struct BlockStyle {
+ /// Disjoint UTF-8 ranges in the replacement, each preserving unspecified source style.
+ pub ranges: Vec<RangeStyle>,
+ /// Explicit page font resource (from register_text_font or the page font inventory).
+ pub resource: Option<String>,
+ /// A standard font family, bold, italic.
+ pub family: Option<(crate::added::Family, bool, bool)>,
+ /// Override weight without choosing a different family (`None` keeps the source weight).
+ pub bold: Option<bool>,
+ /// Font size in points (user space).
+ pub size: Option<f64>,
+ /// Fill colour (RGB 0–1).
+ pub color: Option<[f64; 3]>,
+ pub align: Option<crate::added::Align>,
++ /// Rows (the text's lines between `\n`s) aligned other than the paragraph, by index; `None`
++ /// and rows past the end follow `align` ([`crate::paragraph_align`]).
++ pub aligns: Vec<Option<crate::added::Align>>,
+ /// Draw a line under each line of text.
+ pub underline: Option<bool>,
+ /// Line spacing as a multiple of the font size (1.2 is ordinary).
+ pub line_spacing: Option<f64>,
+ /// Character spacing (points) and horizontal scaling (percent).
+ pub char_spacing: Option<f64>,
+ pub scale: Option<f64>,
+ /// Move the paragraph by `[dx, dy]` in user space (dragging its box).
+ pub offset: Option<[f64; 2]>,
+ /// Rewrap to this width in user space (dragging the box's edge).
+ pub width: Option<f64>,
+ /// For an invisible paragraph ([`TextBlock::invisible`]): fill its old area with this colour
+ /// (RGB 0–1) before the new text, hiding the scanned word beneath it.
+ pub cover: Option<[f64; 3]>,
+ }
+
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct RangeStyle {
+ pub range: std::ops::Range<usize>,
+ pub family: Option<(crate::added::Family, bool, bool)>,
+ pub resource: Option<String>,
+ pub size: Option<f64>,
+ pub color: Option<[f64; 3]>,
+ pub underline: Option<bool>,
+ pub char_spacing: Option<f64>,
+ pub scale: Option<f64>,
+ }
diff --cc crates/edit/src/text/rewrite.rs
index 000000000,dd58c7289..77d3d8b2a
mode 000000,100644..100644
--- a/crates/edit/src/text/rewrite.rs
+++ b/crates/edit/src/text/rewrite.rs
@@@ -1,0 -1,857 +1,870 @@@
+ use super::blocks::{BlockStyle, TextBlock, paragraph_separator, wrap};
+ use super::fallback::{
+ Encoder, MAX_TYPE3_GLYPHS, drop_unused_fallback_fonts, needs_type3, no_japanese_font, source_encodes, source_family, source_program_completes,
+ source_show, source_space, source_width, type3_encode, type3_font,
+ };
+ use super::interp::{Carry, interpret};
+ use super::lines::{content_streams, page_dict, rewritten_contents, splice, text_lines};
+ use super::*;
+
+ /// What replacing a line did.
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct LineEdit {
+ /// `Some(font)` when the line's font couldn't show the new text and Helvetica was used.
+ pub substituted: Option<String>,
+ }
+
+ /// Replace the text of line `line` (an index into [`text_lines`]) on `page` with `text`.
+ pub fn replace_line(doc: &mut Document, page: usize, line: usize, text: &str) -> Result<LineEdit, EditError> {
+ let edit = replace_line_with_limit(doc, page, line, text, MAX_TYPE3_GLYPHS)?;
+ drop_unused_fallback_fonts(doc, page);
+ Ok(edit)
+ }
+
+ /// Refuses a rewrite that would remove text drawn as a clipping path (`4 Tr` to `7 Tr`). Such
+ /// glyphs are not ink but a mask, and whatever is painted through them takes their shape.
+ /// Removing the glyphs removes the mask, and the fill or image behind floods its own rectangle
+ /// instead -- the artwork is destroyed, in a file that still opens without a warning (#3429).
+ /// `clear_block` already refuses these for the same reason.
+ ///
+ /// Every line the rewrite drops is checked, not only the one being replaced: a line's runs need
+ /// not share a rendering mode (see [`TextLine::clips`]), and [`coincident_ops`] drops a whole
+ /// overlapping line without regard to its mode -- so a mask could go with text that is ink.
+ fn refuse_clipping_text(lines: &[TextLine], dropped: &std::collections::HashSet<usize>) -> Result<(), EditError> {
+ if lines.iter().any(|l| l.clips && l.ops.iter().any(|op| dropped.contains(op))) {
+ return Err(EditError::Invalid("text used as a clipping path cannot be edited: its glyphs mask the artwork behind them".into()));
+ }
+ Ok(())
+ }
+
+ /// [`replace_line`] with the most unique characters one generated font may hold (tests lower it).
+ pub(crate) fn replace_line_with_limit(doc: &mut Document, page: usize, line: usize, text: &str, max_glyphs: usize) -> Result<LineEdit, EditError> {
+ let text = text.replace(['\n', '\r'], " ");
+ let lines = text_lines(doc, page)?;
+ let target = lines.get(line).cloned().ok_or_else(|| EditError::Invalid(format!("page {} has no line {}", page + 1, line + 1)))?;
+ target.ensure_editable()?;
+ // Copies of the line drawn on the same baseline go with it, so the replacement is all that
+ // shows. Which operators go is settled here, before any font is generated, so that a refusal
+ // leaves the document untouched.
+ let mut drops = coincident_ops(&lines, &[&target]);
+ drops.extend(target.ops.iter().copied());
+ refuse_clipping_text(&lines, &drops)?;
+ let p = page_dict(doc, page)?;
+ let mut res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
+ let mut fonts_res = res.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();
+ let streams = content_streams(doc, &p.dict)?;
+ let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
+ let ops = pieces.parse().ops;
+ let first = target.ops.first().copied().filter(|i| *i < ops.len()).ok_or_else(|| EditError::Invalid("the page's content changed".into()))?;
+ // The line's own font, when it can show every character.
+ let font = fonts_res.get(target.font.as_bytes()).and_then(|f| doc.resolve(f).as_dict().cloned()).map(|d| Metrics::from_dict(doc, &d));
+ let visual_indic = font.as_ref().is_some_and(|m| m.visual_order) || target.visual_order;
+ let indic_text = if visual_indic { crate::indic::to_visual(&text) } else { text.clone() };
+ // Typed in logical order; drawn left to right (right-to-left runs reversed).
+ let shown = crate::bidi::to_visual(&indic_text);
+ let reused = font.as_ref().filter(|m| source_encodes(m, &shown));
+ let mut substituted = None;
+ let mut replacement: Vec<Op> = Vec::new();
+ // ' and " also move to the next line; keep that.
+ match ops[first].op.as_slice() {
+ b"'" => replacement.push(Op::new("T*", vec![])),
+ b"\"" => {
+ replacement.push(Op::new("Tw", vec![ops[first].operands.first().cloned().unwrap_or(Object::Int(0))]));
+ replacement.push(Op::new("Tc", vec![ops[first].operands.get(1).cloned().unwrap_or(Object::Int(0))]));
+ replacement.push(Op::new("T*", vec![]));
+ }
+ _ => {}
+ }
+ match reused {
+ Some(metrics) => replacement.extend(source_show(
+ metrics,
+ &shown,
+ target.origin.state.font.as_ref().map_or(target.size, |(_, size)| *size),
+ source_space(doc, &fonts_res, metrics),
+ target.origin.state.char_spacing,
+ target.origin.state.word_spacing,
+ )?),
+ None => {
+ let fallback_shown = crate::bidi::to_visual(&text);
+ if needs_type3(&text) {
+ let fallback = type3_font(doc, &mut fonts_res, &text, source_family(&target.base_font), target.bold, max_glyphs)?;
+ let runs = type3_encode(&fallback, &fallback_shown)
+ .ok_or_else(|| EditError::Invalid(format!("\"{text}\" can't be shown by the {} fallback", fallback.family)))?;
+ let size = font_size_before(&ops, first).unwrap_or(target.size);
+ for (name, bytes) in runs {
+ replacement.push(Op::new("Tf", vec![Object::name(&name), pdfcraft_content::num(size)]));
+ replacement.push(Op::new("Tj", vec![Object::String(PdfString::literal(bytes))]));
+ }
+ replacement.push(Op::new("Tf", vec![Object::name(&target.font), pdfcraft_content::num(size)]));
+ substituted = Some(format!("{} Type3", fallback.family));
+ } else {
+ let win = pdfcraft_fonts::win_ansi(&fallback_shown);
+ // WinAnsi turns what it can't show into '?'; refuse rather than print the wrong thing.
+ let back: String = win.iter().map(|b| char::from_u32(u32::from(*b)).unwrap_or('?')).collect();
+ if fallback_shown.chars().zip(back.chars()).any(|(a, b)| b == '?' && a != '?') {
+ return Err(EditError::Invalid(format!("\"{text}\" has characters neither {} nor Helvetica can show", target.base_font)));
+ }
+ // The size in text space: the current Tf's size.
+ let size = font_size_before(&ops, first).unwrap_or(target.size);
+ let family = source_family(&target.base_font);
+ let base = family.base_font(target.bold, target.italic);
+ let substitute_name = format!("PCEd{}", base.replace('-', ""));
+ replacement.push(Op::new("Tf", vec![Object::name(&substitute_name), pdfcraft_content::num(size)]));
+ replacement.push(Op::new("Tj", vec![Object::String(PdfString::literal(win))]));
+ replacement.push(Op::new("Tf", vec![Object::name(&target.font), pdfcraft_content::num(size)]));
+ substituted = Some(base.to_string());
+ let mut f = Dict::new();
+ f.set(b"Type".to_vec(), Object::name("Font"));
+ f.set(b"Subtype".to_vec(), Object::name("Type1"));
+ f.set(b"BaseFont".to_vec(), Object::name(base));
+ f.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
+ fonts_res.set(substitute_name.into_bytes(), Object::Dict(f));
+ }
+ }
+ }
+ // Rebuild: the line's first operator becomes the replacement, its others go.
+ let new_data = splice(&pieces, &ops, |i| if i == first { (std::mem::take(&mut replacement), false) } else { (Vec::new(), !drops.contains(&i)) });
+ let contents = rewritten_contents(doc, &streams, new_data);
+ let page_ref = p.obj;
+ if substituted.is_some() {
+ res.set(b"Font".to_vec(), Object::Dict(fonts_res));
+ }
+ doc.update_dict(page_ref, |d| {
+ d.set(b"Contents".to_vec(), contents);
+ if substituted.is_some() {
+ d.set(b"Resources".to_vec(), Object::Dict(res));
+ }
+ })?;
+ Ok(LineEdit { substituted })
+ }
+
+ /// The size of the last `Tf` before operator `at`.
+ fn font_size_before(ops: &[Op], at: usize) -> Option<f64> {
+ ops[..at].iter().rev().find(|o| o.is("Tf")).and_then(|o| o.num(1))
+ }
+
+ /// Operators of every line that is another drawing of one of `targets` (fake bold, an invisible
+ /// text layer). A surviving copy would show the old text under the replacement.
+ ///
+ /// A copy overlaps a target by more than half the smaller box and sits on the same baseline
+ /// (within the tolerance that joins showing operators onto one line). A neighbouring line can
+ /// share box area when the leading is tighter than the font's ascent plus descent; its baseline
+ /// is farther away, so it stays.
+ pub(crate) fn coincident_ops(lines: &[TextLine], targets: &[&TextLine]) -> std::collections::HashSet<usize> {
+ let area = |r: [f64; 4]| ((r[2] - r[0]) * (r[3] - r[1])).max(0.0);
+ let mut drop = std::collections::HashSet::new();
+ for line in lines {
+ let copy = targets.iter().any(|target| {
+ let same_text = line.text.trim() == target.text.trim() || (line.origin.state.render_mode == 3) != (target.origin.state.render_mode == 3);
+ same_text && overlaps_half(line.rect, target.rect, area) && on_same_baseline(line, target)
+ });
+ if copy {
+ drop.extend(line.ops.iter().copied());
+ }
+ }
+ drop
+ }
+
+ fn overlaps_half(a: [f64; 4], b: [f64; 4], area: impl Fn([f64; 4]) -> f64) -> bool {
+ let ix = (b[2].min(a[2]) - b[0].max(a[0])).max(0.0);
+ let iy = (b[3].min(a[3]) - b[1].max(a[1])).max(0.0);
+ let small = area(b).min(area(a));
+ small > 0.0 && ix * iy / small > 0.5
+ }
+
+ /// Perpendicular distance between baselines, in user space. Horizontal text compares height;
+ /// turned text compares the distance across the writing direction.
+ fn on_same_baseline(line: &TextLine, target: &TextLine) -> bool {
+ let (dir, target_dir) = (line.direction(), target.direction());
+ let same_dir = (dir.0 - target_dir.0).abs() < 1e-3 && (dir.1 - target_dir.1).abs() < 1e-3;
+ let same_size = line.size.min(target.size) >= line.size.max(target.size) * 0.8;
+ let angle = target.rotation().to_radians();
+ let (sin, cos) = if angle.is_finite() { angle.sin_cos() } else { (0.0, 1.0) };
+ let dx = line.origin.x - target.origin.x;
+ let dy = line.origin.baseline - target.origin.baseline;
+ let offset = dx.mul_add(-sin, dy * cos).abs();
+ let size = line.size.min(target.size).max(1.0);
+ same_dir && same_size && offset.is_finite() && offset < size * 0.3
+ }
+
+ /// Rewrite paragraph `block` with new text (or its own) and formatting, rewrapped to its width.
+ pub fn rewrite_block(doc: &mut Document, page: usize, block: usize, text: Option<&str>, style: &BlockStyle) -> Result<LineEdit, EditError> {
+ let edit = rewrite_block_with_limit(doc, page, block, text, style, MAX_TYPE3_GLYPHS)?;
+ drop_unused_fallback_fonts(doc, page);
+ Ok(edit)
+ }
+
+ /// [`rewrite_block`] with the most unique characters one generated font may hold (tests lower it).
+ pub(crate) fn rewrite_block_with_limit(
+ doc: &mut Document,
+ page: usize,
+ block: usize,
+ text: Option<&str>,
+ style: &BlockStyle,
+ max_glyphs: usize,
+ ) -> Result<LineEdit, EditError> {
+ TextSession::open(doc, page, block)?.commit_with_limit(doc, text, style, max_glyphs)
+ }
+
+ /// [`rewrite_block_with_limit`] with the page's [`text_lines`], read from `doc` as it is now.
+ pub(crate) fn rewrite_block_from(
+ doc: &mut Document,
+ page: usize,
+ lines: Vec<TextLine>,
+ block: usize,
+ text: Option<&str>,
+ style: &BlockStyle,
+ max_glyphs: usize,
+ ) -> Result<LineEdit, EditError> {
+ let blocks = group_blocks(&lines);
+ let b = blocks.get(block).cloned().ok_or_else(|| EditError::Invalid(format!("page {} has no paragraph {}", page + 1, block + 1)))?;
++ // An alignment for a one-row paragraph is laid out across the column it sits in, as a
++ // paragraph of that width moved to its left edge.
++ let framed;
++ let style = match alignment_frame(&lines, &b, style) {
++ Some([left, right]) => {
++ framed = BlockStyle { width: Some(right - left), offset: Some([left - b.rect[0], 0.0]), ..style.clone() };
++ &framed
++ }
++ None => style,
++ };
+ let members: Vec<&TextLine> = b.lines.iter().map(|i| &lines[*i]).collect();
+ // One clipping run is enough: rewriting the paragraph would drop its mask with the rest.
+ let mut dropped = coincident_ops(&lines, &members);
+ dropped.extend(members.iter().flat_map(|l| l.ops.iter().copied()));
+ refuse_clipping_text(&lines, &dropped)?;
+ let first = members.first().copied().ok_or_else(|| EditError::Invalid("the paragraph has no source runs".into()))?;
+ members.iter().try_for_each(|line| line.ensure_editable())?;
+ let p = page_dict(doc, page)?;
+ let mut res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
+ let mut fonts_res = res.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();
+ let registered_face = fonts_res.iter().any(|(name, _)| name.starts_with(b"PCFull"));
+ // Hebrew is written back in drawing order (and with the Hebrew fallback face) by the
+ // single-style path below; the styled region path does not reorder right-to-left runs.
+ let hebrew = text.unwrap_or(&b.text).chars().any(crate::bidi::is_hebrew);
+ if hebrew && (!style.ranges.is_empty() || style.resource.is_some()) {
+ return Err(EditError::Invalid(
+ "formatting part of right-to-left (Hebrew) text, or choosing a document font for it, isn't supported yet".into(),
+ ));
+ }
+ // Text turned on the page (a landscape page drawn a quarter turn round) is rewritten in its
+ // own text space below; the styled region path lays rows out along the page's x axis.
+ let upright = members.iter().all(|line| line.upright());
+ if !upright && (!style.ranges.is_empty() || style.resource.is_some()) {
+ return Err(EditError::Invalid("formatting part of turned text, or choosing a document font for it, isn't supported yet".into()));
+ }
+ let visual_indic = members.iter().any(|line| line.visual_order);
+ if upright
+ && !hebrew
+ && !visual_indic
+ && (!style.ranges.is_empty()
+ || style.resource.is_some()
+ || (text.is_some_and(|draft| {
+ // A row break, `\n` or a carriage return, takes the path that keeps untouched rows.
+ draft.contains(['\n', '\r'])
+ || pdfcraft_fonts::source_shaping::required(draft)
+ || !pdfcraft_fonts::embedding::matching_faces(&b.base_font).is_empty()
+ }) || registered_face
+ || text.is_some_and(|draft| source_program_completes(doc, &fonts_res, first, draft))
+ || b.rows.iter().any(|row| row.len() > 1)
+ || members.iter().any(|line| line.font != first.font || line.size != first.size || line.color != first.color))
+ && style.family.is_none()
+ && style.bold.is_none())
+ {
+ return rewrite_styled_block(doc, page, &b, &lines, text, style, max_glyphs);
+ }
+ let streams = content_streams(doc, &p.dict)?;
+ let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
+ let ops = pieces.parse().ops;
+ // Explicit line breaks stay (#1443), and so does each typed U+0020 space: a run of them is
+ // not folded into one (#4199, #3797). `\r\n` and a lone `\r` are breaks too; other white
+ // space is written as one space.
+ let text: String = text
+ .unwrap_or(&b.text)
+ .replace("\r\n", "\n")
+ .chars()
+ .map(|c| match c {
+ '\r' => '\n',
+ c if c != '\n' && paragraph_separator(c) => ' ',
+ c => c,
+ })
+ .collect();
+ // The characters to show, for choosing fonts: the breaks are moves, not glyphs.
+ let flat = text.replace('\n', " ");
+ let o = &first.origin;
+ let last = members.last().copied().unwrap_or(first);
+ let emit = &last.origin;
+ let (font_name, old_size) = o.state.font.clone().ok_or_else(|| EditError::Invalid("the paragraph has no font".into()))?;
+ let k = o.k.max(1e-6);
+ // The size in text space: points ÷ the text-to-user scale.
+ let size = style.size.map_or(old_size, |pt| (pt / k).max(0.1));
+ // Spacing and scaling (text state), with the chosen values.
+ let mut ts_state = o.state.clone();
+ if let Some(c) = style.char_spacing {
+ ts_state.char_spacing = c / k;
+ }
+ if let Some(sc) = style.scale {
+ ts_state.scale = (sc / 100.0).clamp(0.1, 10.0);
+ }
+ let o_state = ts_state.clone();
+ let metrics = fonts_res.get(font_name.as_bytes()).and_then(|f| doc.resolve(f).as_dict().cloned()).map(|d| Metrics::from_dict(doc, &d));
+ let visual_indic = metrics.as_ref().is_some_and(|m| m.visual_order) || first.visual_order;
+ let indic_text = if visual_indic { crate::indic::to_visual(&flat) } else { flat.clone() };
+ let reuse = style.family.is_none() && style.bold.is_none() && metrics.as_ref().is_some_and(|m| source_encodes(m, &indic_text));
+ let space = metrics.as_ref().map_or(0.33, |m| source_space(doc, &fonts_res, m));
+ // The chosen style also determines the real Japanese fallback outlines and advances.
+ let (family, bold, italic) = style.family.unwrap_or((source_family(&b.base_font), b.bold, b.italic));
+ let bold = style.bold.unwrap_or(bold);
+ // The face is chosen after `bold` settles, so a bold request measures with the bold metrics.
+ let face = family.std14(bold, italic);
+ let std_width = move |s: &str, size: f64| -> f64 { face.text_width(s, size) };
+ let [dx, dy] = style.offset.unwrap_or([0.0, 0.0]);
+ if !(dx.is_finite() && dy.is_finite()) {
+ return Err(EditError::Invalid("the paragraph can't be moved that far".into()));
+ }
+ // Right-to-left text (more Hebrew or Arabic letters than Latin) is right-aligned unless an
+ // alignment is asked for, and a single right-to-left line keeps its right edge as it grows.
+ let rtl = crate::bidi::rtl_base(&flat);
+ let anchored_right = rtl && upright && style.width.is_none() && members.len() == 1;
+ // The paragraph's width along its lines: in user space unless it is turned.
+ let frame = if upright {
+ b.rect
+ } else {
+ members.iter().map(|l| l.frame_rect()).reduce(|a, f| [a[0].min(f[0]), a[1].min(f[1]), a[2].max(f[2]), a[3].max(f[3])]).unwrap_or(b.rect)
+ };
+ // A centred title is laid out in the box it already sits in, so it keeps its centre as it
+ // grows or wraps, rather than being grown to the right up to the page's margin (#2581).
+ // Turned text is left alone: its centre lives along its own baseline, not in page space.
+ let crop = p.crop(doc);
+ let centred = upright && !rtl && style.width.is_none() && style.align.is_none() && is_centred(&b, &lines, (crop[0] + crop[2]) / 2.0, first.size);
+ // A paragraph keeps its width (or takes the one asked for); a single line grows to the right
+ // (to the left when right-to-left), up to the page's margin.
+ let width = match style.width {
+ // Capped at the largest page PDF allows (14 400 pt), even for text set larger than that
+ // (`clamp` panics when its minimum is the larger, or NaN).
+ Some(w) if w.is_finite() => w.clamp((size * k).min(14_400.0), 14_400.0),
+ Some(_) => return Err(EditError::Invalid("the paragraph's width must be a number".into())),
+ // Turned text: the page's margins are along another axis. A single line grows (below).
+ None if !upright => (frame[2] - frame[0]).max(size * k),
+ None if anchored_right => (b.rect[2] - b.rect[0]).max(size * k).max(b.rect[2] + dx - (crop[0] + 36.0)),
+ // A centred line is not stretched to the margin: its own box is the frame it is centred in.
+ None if members.len() == 1 && !centred => (b.rect[2] - b.rect[0]).max(size * k).max(crop[2] - 36.0 - (b.rect[0] + dx)),
+ None => (b.rect[2] - b.rect[0]).max(size * k),
+ };
+ if !width.is_finite() {
+ return Err(EditError::Invalid("the paragraph's width must be a number".into()));
+ }
+ let align = if centred { Some(crate::added::Align::Center) } else { style.align.or(rtl.then_some(crate::added::Align::Right)) };
+ // Where a right-aligned line ends, from the paragraph's left edge (user space).
+ let right_edge = if anchored_right { (b.rect[2] - b.rect[0]).max(0.0) } else { width };
+ // The move and the width are checked here, before the fallback fonts are written: a refused
+ // paragraph leaves the document as it was. The move is in page space, so it is taken back through
+ // the CTM's linear part into the space the paragraph is drawn in.
+ let movement = if dx != 0.0 || dy != 0.0 {
+ let c = emit.ctm;
+ let back = Matrix([c[0], c[1], c[2], c[3], 0.0, 0.0])
+ .invert()
+ .ok_or_else(|| EditError::Invalid("the paragraph is drawn in a space it can't be moved in".into()))?;
+ Some(back.apply(dx, dy))
+ } else {
+ None
+ };
+ let tm = if o.ctm == emit.ctm {
+ o.tm
+ } else {
+ let emit_inv = Matrix(emit.ctm).invert().ok_or_else(|| EditError::Invalid("the paragraph has a singular transform".into()))?;
+ Matrix(o.tm).then(&Matrix(o.ctm)).then(&emit_inv).0
+ };
+ let type3 = if !reuse && needs_type3(&flat) { Some(type3_font(doc, &mut fonts_res, &flat, family, bold, max_glyphs)?) } else { None };
+ let advance = |s: &str| -> f64 {
+ let t = match (&metrics, reuse) {
+ (Some(m), true) => {
+ let visual_s = if m.visual_order { crate::indic::to_visual(s) } else { s.to_owned() };
+ source_width(m, &visual_s, size, space, o_state.char_spacing, o_state.word_spacing)
+ }
+ _ if let Some(fallback) = &type3 => {
+ // Each character's count in `s`, from one pass over `s`.
+ let mut counts: HashMap<char, usize> = HashMap::new();
+ for c in s.chars() {
+ let count = counts.entry(c).or_insert(0);
+ *count = count.saturating_add(1);
+ }
+ fallback.widths.iter().map(|(ch, width)| counts.get(ch).copied().unwrap_or(0) as f64 * width * size).sum::<f64>()
+ + s.chars().count() as f64 * o_state.char_spacing
+ }
+ _ => std_width(s, size) + s.chars().count() as f64 * o_state.char_spacing,
+ };
+ t * o_state.scale * k
+ };
+ // A turned single line grows to fit, up to where its baseline reaches the page's margin.
+ let width = if !upright && style.width.is_none() && members.len() == 1 {
+ let crop = p.crop(doc);
+ let (x0, y0) = (first.origin.x + dx, first.origin.baseline + dy);
+ let (ux, uy) = first.direction();
+ let tx = if ux > 1e-6 {
+ (crop[2] - 36.0 - x0) / ux
+ } else if ux < -1e-6 {
+ (crop[0] + 36.0 - x0) / ux
+ } else {
+ f64::INFINITY
+ };
+ let ty = if uy > 1e-6 {
+ (crop[3] - 36.0 - y0) / uy
+ } else if uy < -1e-6 {
+ (crop[1] + 36.0 - y0) / uy
+ } else {
+ f64::INFINITY
+ };
+ let cap = width.max(tx.min(ty)).min(14_400.0);
+ text.split('\n').map(&advance).fold(width, f64::max).min(cap)
+ } else {
+ width
+ };
+ let right_edge = if anchored_right { right_edge } else { width };
+ let wrapped = wrap(&text, width + 0.5, advance);
+ let mut substituted = None;
+ let new_font = !reuse;
+ let (show_font, encode): (String, Encoder) = if let Some(m) = metrics.clone().filter(|_| reuse) {
+ let name = font_name.clone();
+ (font_name.clone(), Box::new(move |s: &str| m.encode(s).map(|bytes| vec![(name.clone(), bytes)])))
+ } else if let Some(fallback) = type3.clone() {
+ substituted = Some(format!("{} Type3", fallback.family));
+ let first = fallback.names.first().cloned().ok_or_else(no_japanese_font)?;
+ (first, Box::new(move |s: &str| type3_encode(&fallback, s)))
+ } else {
+ let win = pdfcraft_fonts::win_ansi(&flat);
+ let back: String = win.iter().map(|c| char::from_u32(u32::from(*c)).unwrap_or('?')).collect();
+ let base = family.base_font(bold, italic);
+ if flat.chars().zip(back.chars()).any(|(a, c)| c == '?' && a != '?') {
+ return Err(EditError::Invalid(format!("\"{flat}\" has characters neither {} nor {base} can show", b.base_font)));
+ }
+ let mut f = Dict::new();
+ f.set(b"Type".to_vec(), Object::name("Font"));
+ f.set(b"Subtype".to_vec(), Object::name("Type1"));
+ f.set(b"BaseFont".to_vec(), Object::name(base));
+ f.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
+ // Named after its face, as the line and region rewrites name theirs: one name for every
+ // stand-in would repoint the paragraphs set in an earlier one at this face (#4280).
+ let name = format!("PCEd{}", base.replace('-', ""));
+ fonts_res.set(name.clone().into_bytes(), Object::Dict(f));
+ if style.family.is_none() {
+ substituted = Some(base.to_string());
+ }
+ let shown = name.clone();
+ (name, Box::new(move |s: &str| Some(vec![(shown.clone(), pdfcraft_fonts::win_ansi(s))])))
+ };
+ // Line spacing in text space: the paragraph's own (scaled with the size), or 1.2 × the size.
+ let lead = match style.line_spacing {
+ Some(m) => size * m.clamp(0.5, 5.0),
+ // From the first two rows (a row may hold several runs).
+ None if let Some((upper, lower)) = b
+ .rows
+ .first()
+ .zip(b.rows.get(1))
+ .and_then(|(upper, lower)| upper.first().zip(lower.first()))
+ .and_then(|(upper, lower)| lines.get(*upper).zip(lines.get(*lower))) =>
+ {
+ (upper.frame_origin().1 - lower.frame_origin().1) / k * size / old_size
+ }
+ None if o_state.leading > 0.0 => o_state.leading,
+ None => size * 1.2,
+ };
+ let n = pdfcraft_content::num;
+ // The paragraph's operators go, and so does another drawing on the same baseline (a fake-bold
+ // second copy, an invisible text layer): the new text is all that may show.
+ let drop = dropped;
+ // Text shown earlier in the same text object stays first: the paragraph then goes where its
+ // last row was, after any backgrounds between the rows, or between two halves of the text object.
+ let start = last.ops.first().copied().unwrap_or(emit.bt_op);
+ let split = ops
+ .get(emit.bt_op..start)
+ .unwrap_or_default()
+ .iter()
+ .enumerate()
+ .any(|(i, op)| matches!(op.op.as_slice(), b"Tj" | b"TJ" | b"'" | b"\"") && !drop.contains(&(emit.bt_op + i)));
+ // What the text after the paragraph expects, and what is in force where the paragraph is
+ // drawn: the state at its BT (or where it was split).
+ let after = if split { &emit.state } else { &emit.bt_state };
+ // In its own graphics state, so a new colour (or anything else) stops at the paragraph.
+ let mut block_ops = vec![Op::new("q", vec![])];
+ block_ops.extend(reveal_ops(&b, &lines, style, emit.ctm)?);
+ // Moved: a translation inside that state.
+ if let Some((ax, ay)) = movement {
+ block_ops.push(Op::new("cm", vec![n(1.0), n(0.0), n(0.0), n(1.0), n(ax), n(ay)]));
+ }
+ // Painted as the paragraph was, including what its text object set before the first show.
+ block_ops.extend(o_state.paint_ops(after));
+ block_ops.push(Op::new("BT", vec![]));
+ let mut state = o_state.clone();
+ state.word_spacing = 0.0;
+ // The font the next run is shown in: the one the BT sets, until a run of another fallback subset.
+ let mut shown_font = show_font.clone();
+ state.font = Some((show_font, size));
+ if let Some([r, g, bl]) = style.color {
+ state.fill = vec![Op::new("rg", vec![n(r), n(g), n(bl)])];
+ }
+ block_ops.extend(state.ops());
+ block_ops.push(Op::new("Tm", tm.iter().map(|v| n(*v)).collect()));
++ // Each row's alignment: its own, or the paragraph's.
++ let align_of = |row: usize| style.aligns.get(row).copied().flatten().or(align);
+ // Alignment: each line's offset from the left edge, in text space.
- // `visible` is the width the line is aligned on (see the loop below).
- let offset = |visible: f64| -> f64 {
++ // `visible` is the width the line is aligned on (see the loop below); `align` is its row's.
++ let offset = |visible: f64, align: Option<crate::added::Align>| -> f64 {
+ let free = (width - visible).max(0.0) / k;
+ match align {
+ Some(crate::added::Align::Center) => free / 2.0,
+ // A right-to-left line anchored at its right edge may start left of the old box.
+ Some(crate::added::Align::Right) if anchored_right => (right_edge - visible) / k,
+ Some(crate::added::Align::Right) => free,
+ // A justified right-to-left paragraph ends its last line at the right edge.
+ Some(crate::added::Align::Justify) if rtl => free,
+ _ => 0.0,
+ }
+ };
+ // Justify: each line but the last fills the width. Word spacing reaches only single-byte code 32
+ // (ISO 32000-1 §9.3.3), so where a space is shown with another code (a composite font, a
+ // generated Type 3 font, a subset without a space) the extra space follows each space as a
+ // TJ adjustment instead, and code 32, which may then be a letter, gets none.
- let justify = align == Some(crate::added::Align::Justify);
+ let word_spacing_reaches_spaces = match metrics.as_ref().filter(|_| reuse) {
+ Some(m) => m.encode(" ").is_some_and(|b| m.codes(&b).iter().all(|(c, len)| m.is_space(*c, *len))),
+ None => type3.is_none(),
+ };
+ let mut x = 0.0;
+ let mut tw_set = 0.0;
+ let mut underlines: Vec<(f64, f64, f64)> = Vec::new(); // (x0, x1, y) in text space
- for (i, line) in wrapped.iter().enumerate() {
++ for (i, (line, row)) in wrapped.iter().enumerate() {
++ let line_align = align_of(*row);
++ let justify = line_align == Some(crate::added::Align::Justify);
+ // A stretched (justified) line shows only its words, as before #4199: word spacing would
+ // reach the spaces before its first word and after its last, so they are left out, and
+ // the line fills the width from the left edge. Nothing to stretch over, or a paragraph
+ // drawn at `0 Tz`, isn't justified.
+ let body = line.trim_matches(' ');
+ let interior = body.matches(' ').count();
+ let tw = if justify && i + 1 < wrapped.len() && interior > 0 && o_state.scale.abs() > 1e-6 {
+ Some((width - advance(body)).max(0.0) / k / o_state.scale / interior as f64).filter(|tw| tw.is_finite())
+ } else {
+ None
+ }
+ .unwrap_or(0.0);
+ // Other lines show every space typed. A left-to-right one is aligned on its width up to
+ // its last word; a right-to-left one on its whole width, since the spaces typed after its
+ // last word are drawn on its left and the ones before its first on its right.
+ let (shown, visible) = if tw > 0.0 {
+ (body, advance(body))
+ } else if crate::bidi::rtl_base(line) {
+ (line.as_str(), advance(line))
+ } else {
+ (line.as_str(), advance(line.trim_end_matches(' ')))
+ };
- let dx = if tw > 0.0 { 0.0 } else { offset(visible) };
++ let dx = if tw > 0.0 { 0.0 } else { offset(visible, line_align) };
+ if i > 0 || dx != 0.0 {
+ block_ops.push(Op::new("Td", vec![n(dx - x), n(if i > 0 { -lead } else { 0.0 })]));
+ }
+ x = dx;
+ let stretch = if word_spacing_reaches_spaces { 0.0 } else { tw };
+ let tw = tw - stretch;
+ if tw != tw_set {
+ block_ops.push(Op::new("Tw", vec![n(tw)]));
+ tw_set = tw;
+ }
+ // Each wrapped line in typing order; drawn left to right (right-to-left runs reversed).
+ let visual = crate::bidi::to_visual(shown);
+ // Stretched without word spacing: shown up to and including each space, then moved on.
+ let pieces = if stretch > 0.0 { visual.split_inclusive(' ').collect() } else { vec![visual.as_str()] };
+ for piece in pieces {
+ if let Some(metrics) = metrics.as_ref().filter(|_| reuse) {
+ let indic_piece = if metrics.visual_order { crate::indic::to_visual(piece) } else { piece.to_owned() };
+ block_ops.extend(source_show(metrics, &indic_piece, size, space, o_state.char_spacing, tw)?);
+ } else {
+ for (font, bytes) in encode(piece).ok_or_else(|| EditError::Invalid(format!("\"{line}\" can't be shown")))? {
+ if font != shown_font {
+ block_ops.push(Op::new("Tf", vec![Object::name(&font), n(size)]));
+ shown_font = font;
+ }
+ block_ops.push(Op::new("Tj", vec![Object::String(PdfString::literal(bytes))]));
+ }
+ }
+ if stretch > 0.0 && piece.ends_with(' ') {
+ block_ops.push(Op::new("TJ", vec![Object::Array(vec![n(-1000.0 * stretch / size)])]));
+ }
+ }
+ let tw = tw + stretch;
+ // Underlined to the line's last word, over its stretched gaps.
+ let w = (visible + tw * interior as f64 * o_state.scale * k) / k;
+ underlines.push((dx, dx + w, -(i as f64) * lead - size * 0.12));
+ }
+ block_ops.push(Op::new("ET", vec![]));
+ if style.underline == Some(true) {
+ // In text space (the paragraph's text matrix), in its fill colour.
+ let colour: Vec<Op> = state
+ .fill
+ .iter()
+ .map(|f| match f.op.as_slice() {
+ b"g" => Op::new("G", f.operands.clone()),
+ b"rg" => Op::new("RG", f.operands.clone()),
+ b"k" => Op::new("K", f.operands.clone()),
+ b"cs" => Op::new("CS", f.operands.clone()),
+ b"sc" => Op::new("SC", f.operands.clone()),
+ _ => Op::new("SCN", f.operands.clone()),
+ })
+ .collect();
+ block_ops.push(Op::new("q", vec![]));
+ block_ops.push(Op::new("cm", tm.iter().map(|v| n(*v)).collect()));
+ block_ops.extend(colour);
+ block_ops.push(Op::new("w", vec![n(size * 0.06)]));
+ for (x0, x1, y) in underlines {
+ block_ops.push(Op::new("m", vec![n(x0), n(y)]));
+ block_ops.push(Op::new("l", vec![n(x1), n(y)]));
+ }
+ block_ops.push(Op::new("S", vec![]));
+ block_ops.push(Op::new("Q", vec![]));
+ }
+ block_ops.push(Op::new("Q", vec![]));
+ block_ops.extend(after.ops().into_iter().filter(|op| !op.is("Tf") || after.font.is_some()));
+ if split {
+ block_ops.insert(0, Op::new("ET", vec![]));
+ block_ops.push(Op::new("BT", vec![]));
+ block_ops.push(Op::new("Tm", emit.tlm.iter().map(|v| n(*v)).collect()));
+ }
+ let at = if split { start } else { emit.bt_op };
+ let new_data = splice(&pieces, &ops, |i| {
+ let insert = if i == at { std::mem::take(&mut block_ops) } else { Vec::new() };
+ (insert, !drop.contains(&i))
+ });
+ let contents = rewritten_contents(doc, &streams, new_data);
+ if new_font {
+ res.set(b"Font".to_vec(), Object::Dict(fonts_res));
+ }
+ let page_ref = p.obj;
+ doc.update_dict(page_ref, |d| {
+ d.set(b"Contents".to_vec(), contents);
+ if new_font {
+ d.set(b"Resources".to_vec(), Object::Dict(res));
+ }
+ })?;
+ Ok(LineEdit { substituted })
+ }
+
+ /// The cover (when [`BlockStyle::cover`] asks for one) and visible rendering that start a
+ /// rewritten invisible paragraph, drawn in the space whose CTM is `ctm`. Nothing for visible text.
+ /// The paragraph's `q`/`Q` restores the rendering mode for the invisible text after it.
+ pub(crate) fn reveal_ops(block: &TextBlock, lines: &[TextLine], style: &BlockStyle, ctm: [f64; 6]) -> Result<Vec<Op>, EditError> {
+ if !block.invisible {
+ return Ok(Vec::new());
+ }
+ let n = pdfcraft_content::num;
+ let mut ops = Vec::new();
+ if let Some(colour) = style.cover {
+ if colour.iter().any(|c| !c.is_finite() || !(0.0..=1.0).contains(c)) {
+ return Err(EditError::Invalid("the cover colour must be RGB values from 0 to 1".into()));
+ }
+ let back = Matrix(ctm).invert().ok_or_else(|| EditError::Invalid("the paragraph is drawn in a space it can't be covered in".into()))?;
+ ops.push(Op::new("q", vec![]));
+ ops.push(Op::new("rg", colour.map(n).to_vec()));
+ for rect in block.lines.iter().filter_map(|i| lines.get(*i)).map(|l| l.rect) {
+ // Scanned ink reaches a little past the recognised box.
+ let pad = ((rect[3] - rect[1]).abs() * 0.1).clamp(0.5, 2.0);
+ let corners =
+ [[rect[0] - pad, rect[1] - pad], [rect[2] + pad, rect[1] - pad], [rect[2] + pad, rect[3] + pad], [rect[0] - pad, rect[3] + pad]];
+ for (i, [x, y]) in corners.into_iter().enumerate() {
+ let (x, y) = back.apply(x, y);
+ if !(x.is_finite() && y.is_finite()) {
+ return Err(EditError::Invalid("the paragraph's area can't be covered".into()));
+ }
+ ops.push(Op::new(if i == 0 { "m" } else { "l" }, vec![n(x), n(y)]));
+ }
+ ops.push(Op::new("h", vec![]));
+ }
+ ops.push(Op::new("f", vec![]));
+ ops.push(Op::new("Q", vec![]));
+ }
+ ops.push(Op::new("Tr", vec![Object::Int(0)]));
+ Ok(ops)
+ }
+
+ /// Existing paragraph indexes, excluding streams owned by an added-content item.
+ pub(crate) fn selectable_blocks(
+ doc: &Document,
+ page: usize,
+ excluded: &std::collections::BTreeSet<pdfcraft_cos::ObjRef>,
+ ) -> Result<Vec<(usize, TextBlock)>, EditError> {
+ let p = page_dict(doc, page)?;
+ let streams = content_streams(doc, &p.dict)?;
+ let lines = text_lines(doc, page)?;
+ Ok(group_blocks(&lines)
+ .into_iter()
+ .enumerate()
+ .filter(|(_, b)| {
+ !b.lines
+ .iter()
+ .filter_map(|i| lines.get(*i))
+ .any(|l| streams.get(l.stream).and_then(|(o, _)| o.as_ref()).is_some_and(|r| excluded.contains(&r)))
+ })
+ .collect())
+ }
+
+ /// The vertical advance per unit of font size of a font that writes vertically: `/DW2`'s w1
+ /// (default −1000, §9.7.4.3), or `None` for horizontal text. Per-glyph `/W2` entries are not
+ /// read. An encoding whose writing mode can't be read is an error, as in [`vertical_encoding`];
+ /// listing text treats it as horizontal and records the error (see [`Ts::unreadable`]).
+ pub(super) fn vertical_advance(doc: &Document, font: &Dict) -> Result<Option<f64>, EditError> {
+ if !vertical_encoding(doc, font)? {
+ return Ok(None);
+ }
+ let descendant = font.get(b"DescendantFonts").and_then(|d| doc.resolve(d).as_array().and_then(|a| a.first().cloned()));
+ let w1 = descendant
+ .and_then(|d| doc.resolve(&d).as_dict().and_then(|d| d.get(b"DW2").cloned()))
+ .and_then(|a| doc.resolve(&a).as_array().and_then(|a| a.get(1).cloned()))
+ .and_then(|w| doc.resolve(&w).as_f64())
+ .filter(|w| w.is_finite())
+ .unwrap_or(-1000.0);
+ Ok(Some(w1 / 1000.0))
+ }
+
+ /// Detect vertical CMaps before moving horizontal text. A broken/cyclic embedded CMap is
+ /// refused rather than guessing which direction TJ advances its text matrix.
+ fn vertical_encoding(doc: &Document, font: &Dict) -> Result<bool, EditError> {
+ if font.name(b"Subtype") != Some(b"Type0") {
+ return Ok(false);
+ }
+ let mut next = font.get(b"Encoding").cloned();
+ let mut seen = std::collections::BTreeSet::new();
+ for _ in 0..8 {
+ let Some(o) = next.take() else { return Ok(false) };
+ if let Some(r) = o.as_ref()
+ && !seen.insert(r)
+ {
+ return Err(EditError::Invalid("the text encoding is cyclic".into()));
+ }
+ match &*doc.resolve(&o) {
+ Object::Name(n) => return Ok(n.ends_with(b"-V")),
+ Object::Stream(stream) => {
+ if let Some(mode) = stream.dict.get(b"WMode") {
+ match mode.as_int() {
+ Some(1) => return Ok(true),
+ Some(0) => {}
+ _ => return Err(EditError::Invalid("the text writing mode is invalid".into())),
+ }
+ }
+ let bytes = stream
+ .decoded_within(8 * 1024 * 1024)
+ .map_err(|_| EditError::Invalid("the text encoding cannot be decoded within its size limit".into()))?;
+ let ops = parse(&bytes).ops;
+ if let Some(mode) = ops.iter().rev().find(|op| op.is("def") && op.name(0) == Some(b"WMode")) {
+ return match mode.num(1) {
+ Some(0.0) => Ok(false),
+ Some(1.0) => Ok(true),
+ _ => Err(EditError::Invalid("the text writing mode is invalid".into())),
+ };
+ }
+ next = stream
+ .dict
+ .get(b"UseCMap")
+ .cloned()
+ .or_else(|| ops.iter().rev().find(|op| op.is("usecmap")).and_then(|op| op.operands.first().cloned()));
+ }
+ _ => return Err(EditError::Invalid("the text encoding is invalid".into())),
+ }
+ }
+ Err(EditError::Invalid("the text encoding is nested too deeply".into()))
+ }
+
+ /// Translate paragraphs together without re-encoding glyphs, changing fonts or reflowing.
+ /// Numeric TJ offsets and text rise temporarily move each selected show operation, then
+ /// restore both advances and rise. The PDF reader advances the original glyph bytes itself:
+ /// no approximate font metrics are used to position following, unselected text (§9.4.4).
+ pub(crate) fn translate_blocks(doc: &mut Document, page: usize, indexes: &[usize], offset: [f64; 2]) -> Result<(), EditError> {
+ if indexes.is_empty() {
+ return Ok(());
+ }
+ let p = page_dict(doc, page)?;
+ let streams = content_streams(doc, &p.dict)?;
+ let lines = text_lines(doc, page)?;
+ let blocks = group_blocks(&lines);
+ let mut selected = std::collections::BTreeSet::new();
+ for index in indexes {
+ let b = blocks.get(*index).ok_or_else(|| EditError::Invalid("a selected paragraph no longer exists".into()))?;
+ for line in &b.lines {
+ let l = lines.get(*line).ok_or_else(|| EditError::Invalid("a selected text line no longer exists".into()))?;
+ l.ensure_editable()?;
+ selected.extend(l.ops.iter().copied());
+ }
+ }
+ let res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
+ let fonts = res.get(b"Font").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
+ let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
+ let ops = pieces.parse().ops;
+ let shown = interpret(doc, &ops, &res, &mut HashMap::new(), &mut Carry::new(), None, None)?;
+ let mut patches = HashMap::new();
+ // Keep full precision: a tiny rounded text-space change can be magnified by a CTM,
+ // and restoring rise/spacing must not alter following unselected text.
+ let n = Object::Real;
+ for s in shown.into_iter().filter(|s| selected.contains(&s.op)) {
+ if !(0..=3).contains(&s.state.render_mode) {
+ return Err(EditError::Invalid("text used as a clipping path cannot be moved in a group".into()));
+ }
+ let font = fonts
+ .get(&s.font)
+ .map(|f| doc.resolve(f))
+ .and_then(|f| f.as_dict().cloned())
+ .ok_or_else(|| EditError::Invalid("a selected paragraph has no font".into()))?;
+ if vertical_encoding(doc, &font)? {
+ return Err(EditError::Invalid("vertical text cannot be moved in a group".into()));
+ }
+ let inverse = s.tm.then(&s.state.ctm).invert().ok_or_else(|| EditError::Invalid("a selected paragraph has no area".into()))?;
+ let [a, b, c, d, _, _] = inverse.0;
+ let (dx, dy) = (a * offset[0] + c * offset[1], b * offset[0] + d * offset[1]);
+ let denominator = s.state.size * s.state.scale;
+ let shift = if dx == 0.0 {
+ 0.0
+ } else if denominator.abs() > 1e-12 {
+ -1000.0 * dx / denominator
+ } else {
+ return Err(EditError::Invalid("a selected paragraph has no horizontal advance".into()));
+ };
+ let rise = s.state.rise + dy;
+ if ![shift, rise, dx, dy].iter().all(|v| v.is_finite() && v.abs() <= 1e12) {
+ return Err(EditError::Invalid("the paragraph move is too large".into()));
+ }
+ let original = ops.get(s.op).ok_or_else(|| EditError::Invalid("a selected text operation is missing".into()))?;
+ let mut replacement = Vec::new();
+ let show = if original.is("'") || original.is("\"") {
+ if original.is("\"") {
+ let spacing = original
+ .operands
+ .get(..2)
+ .filter(|a| a.iter().all(|o| o.as_f64().is_some()))
+ .ok_or_else(|| EditError::Invalid("a text operation has invalid spacing".into()))?;
+ for (operator, operand) in ["Tw", "Tc"].into_iter().zip(spacing) {
+ replacement.push(Op::new(operator, vec![operand.clone()]));
+ }
+ }
+ replacement.push(Op::new("T*", vec![]));
+ Op::new("Tj", vec![original.operands.last().cloned().ok_or_else(|| EditError::Invalid("a text operation has no string".into()))?])
+ } else {
+ original.clone()
+ };
+ if dy != 0.0 {
+ replacement.push(Op::new("Ts", vec![n(rise)]));
+ }
+ if shift != 0.0 {
+ replacement.push(Op::new("TJ", vec![Object::Array(vec![n(shift)])]));
+ }
+ replacement.push(show);
+ if shift != 0.0 {
+ replacement.push(Op::new("TJ", vec![Object::Array(vec![n(-shift)])]));
+ }
+ if dy != 0.0 {
+ replacement.push(Op::new("Ts", vec![n(s.state.rise)]));
+ }
+ patches.insert(s.op, replacement);
+ }
+ if patches.len() != selected.len() {
+ return Err(EditError::Invalid("a selected text operation cannot be moved".into()));
+ }
+ let data = splice(&pieces, &ops, |i| patches.remove(&i).map_or((Vec::new(), true), |v| (v, false)));
+ let contents = rewritten_contents(doc, &streams, data);
+ doc.update_dict(p.obj, |d| d.set(b"Contents".to_vec(), contents))?;
+ Ok(())
+ }
diff --cc crates/edit/src/text_regions.rs
index 965792908,7516cb793..c43c9154e
--- a/crates/edit/src/text_regions.rs
+++ b/crates/edit/src/text_regions.rs
@@@ -2,1146 -2,10 +2,10 @@@
use super::*;
- // The draft is capped at 4 MiB; also bound the outline data prepared across all fallback faces.
- // A glyph budget worth 64 full batches (15,360 glyphs with the production batch size).
- // Lowering the internal batch size for tests lowers the budget by the same ratio.
- const MAX_STYLED_FALLBACK_BATCHES: usize = 64;
+ #[path = "text_regions/grouping.rs"]
+ mod grouping;
+ #[path = "text_regions/styled.rs"]
+ mod styled;
- struct FallbackGroup {
- face: &'static CraftFont,
- seen: std::collections::HashSet<char>,
- glyphs: Vec<Type3Glyph>,
- positions: Vec<usize>,
- }
-
- fn same_plane(a: &TextLine, b: &TextLine) -> bool {
- let at = Matrix(a.origin.tm).then(&Matrix(a.origin.ctm));
- let bt = Matrix(b.origin.tm).then(&Matrix(b.origin.ctm));
- a.scope == b.scope
- && a.paint == b.paint
- && [0, 2].iter().all(|axis| {
- let ax = at.0.get(*axis).copied().unwrap_or(0.0);
- let ay = at.0.get(axis + 1).copied().unwrap_or(0.0);
- let bx = bt.0.get(*axis).copied().unwrap_or(0.0);
- let by = bt.0.get(axis + 1).copied().unwrap_or(0.0);
- let al = ax.hypot(ay);
- let bl = bx.hypot(by);
- al > 0.0 && bl > 0.0 && (ax / al - bx / bl).abs() < 0.001 && (ay / al - by / bl).abs() < 0.001
- })
- }
-
- fn row_rect(row: &[usize], lines: &[TextLine]) -> Option<[f64; 4]> {
- row.iter().filter_map(|i| lines.get(*i)).map(|l| l.rect).reduce(union)
- }
-
- /// [`row_rect`] in its text's own frame ([`TextLine::frame_rect`]), so rows of turned text
- /// compare along and across their baselines.
- fn frame_row_rect(row: &[usize], lines: &[TextLine]) -> Option<[f64; 4]> {
- row.iter().filter_map(|i| lines.get(*i)).map(TextLine::frame_rect).reduce(union)
- }
-
- /// The left edge the rest of the page's text sits on, ignoring the rows of `block`. A single row
- /// that does not share it is not merely an indented or full-width left-aligned line, so its own
- /// centre is the only remaining explanation for where it sits. With `over`, only rows reaching
- /// across that span count: the edge of the column under it, however many rows another column has.
- fn neighbour_left(lines: &[TextLine], block: &TextBlock, over: Option<[f64; 2]>) -> Option<f64> {
- let mut edges: HashMap<i64, usize> = HashMap::new();
- for (i, line) in lines.iter().enumerate() {
- if block.lines.contains(&i) || over.is_some_and(|[left, right]| line.rect[2] <= left || line.rect[0] >= right) {
- continue;
- }
- // Quarter-point buckets: equal edges found through different runs still agree.
- *edges.entry((line.rect[0] * 4.0).round() as i64).or_insert(0) += 1;
- }
- let (best, _) = edges.into_iter().max_by_key(|(_, count)| *count)?;
- Some(best as f64 / 4.0)
- }
-
- /// Where an alignment picked for a one-row paragraph is measured, as `[left, right]`: the column of
- /// text it sits in (the left edge the text under or over it uses, to the furthest right those rows
- /// reach) when that column holds it, otherwise its own box. A lone row's own box is no frame
- /// to align in: left-aligning a title centred on the page left it where it was, and since a single
- /// row grows to the page's margin, centring it again moved it right each time. `None` when no
- /// alignment is asked for, or when the paragraph is several rows, turned, or given a width or a
- /// move of its own.
- pub(super) fn alignment_frame(lines: &[TextLine], block: &TextBlock, style: &BlockStyle) -> Option<[f64; 2]> {
- let asked = style.align.is_some() || style.aligns.iter().any(Option::is_some);
- if !asked || style.width.is_some() || style.offset.is_some() || block.rows.len() != 1 || block.rotation.abs() > 0.01 {
- return None;
- }
- let own = [block.rect[0], block.rect[2]];
- let tolerance = block.size.max(1.0) * 0.5;
- let Some(left) = neighbour_left(lines, block, Some(own)) else { return Some(own) };
- let right = lines
- .iter()
- .enumerate()
- .filter(|(i, line)| !block.lines.contains(i) && (line.rect[0] - left).abs() < tolerance)
- .map(|(_, line)| line.rect[2])
- .fold(f64::NEG_INFINITY, f64::max);
- let holds = right.is_finite() && right - left > own[1] - own[0] && own[0] >= left - tolerance && own[1] <= right + tolerance;
- Some(if holds { [left, right] } else { own })
- }
-
- /// Whether a block reads as centred, and so must keep its centre when it grows or wraps.
- ///
- /// Several ragged rows whose left edges disagree while their centres agree are centred. A one row
- /// block cannot say that: all of its left edges are the same, so the ragged test never fires and a
- /// centred title would be taken for left-aligned and grow to the right (#2581). Fall back to the
- /// page instead — a lone row sitting on the page's own centre, and not on the edge the rest of the
- /// text uses, is a centred title. A full-width left-aligned line still lines up with that edge, so
- /// it is not mistaken for one.
- pub(super) fn is_centred(block: &TextBlock, lines: &[TextLine], page_centre: f64, size: f64) -> bool {
- let centre = (block.rect[0] + block.rect[2]) / 2.0;
- let lefts: Vec<_> = block.rows.iter().filter_map(|r| row_rect(r, lines).map(|r| r[0])).collect();
- if block.rows.len() > 1 {
- let left_span = lefts.iter().copied().fold(f64::NEG_INFINITY, f64::max) - lefts.iter().copied().fold(f64::INFINITY, f64::min);
- return left_span > size * 0.5
- && block.rows.iter().all(|row| row_rect(row, lines).is_some_and(|r| ((r[0] + r[2]) / 2.0 - centre).abs() < size));
- }
- lefts.first().is_some_and(|left| {
- (centre - page_centre).abs() < size && neighbour_left(lines, block, None).is_none_or(|edge| (*left - edge).abs() > size * 0.5)
- })
- }
-
- pub(super) fn group_blocks(lines: &[TextLine]) -> Vec<TextBlock> {
- group_layout(lines, true)
- }
-
- /// Exporters currently represent a block with one style. Keep their style boundaries until
- /// they support rich runs, while edit selection may encompass the complete visual region.
- /// Dotted-leader entries stay on one row and use the title run's style.
- pub(super) fn group_reading_blocks(lines: &[TextLine]) -> Vec<TextBlock> {
- let mut blocks = Vec::new();
- let mut start = 0;
- let mut offset = 0;
- for row in lines.chunk_by(|a, b| same_plane(a, b) && (a.origin.baseline - b.origin.baseline).abs() < a.size.min(b.size) * 0.2) {
- let mut text = String::new();
- for (i, line) in row.iter().enumerate() {
- if !text.ends_with(char::is_whitespace)
- && !line.text.starts_with(char::is_whitespace)
- && i.checked_sub(1).and_then(|i| row.get(i)).is_some_and(|prev| line.rect[0] - prev.rect[2] > line.size * 0.12)
- {
- text.push(' ');
- }
- text.push_str(&line.text);
- }
- if leader_entry(&text)
- && let Some(first) = row.first()
- {
- // Tab leaders are a single reading row, even when the title, dots and page
- // number are separate text objects far apart. Do not merge neighbouring entries.
- blocks.extend(group_layout(lines.get(start..offset).unwrap_or_default(), false));
- let mut line = first.clone();
- line.text = text;
- line.rect = row.iter().map(|line| line.rect).reduce(union).unwrap_or(first.rect);
- blocks.extend(group_layout(std::slice::from_ref(&line), false));
- start = offset + row.len();
- }
- offset += row.len();
- }
- blocks.extend(group_layout(lines.get(start..).unwrap_or_default(), false));
- blocks
- }
-
- /// Dotted leaders end in a page number, with a title before the dots. A dot in an article
- /// number, or an ellipsis in ordinary prose, is not enough to make a contents entry.
- fn leader_entry(text: &str) -> bool {
- let text = text.trim_end();
- let prefix = text.trim_end_matches(|c: char| {
- c.is_ascii_digit() || matches!(c, 'i' | 'v' | 'x' | 'l' | 'c' | 'd' | 'm' | 'I' | 'V' | 'X' | 'L' | 'C' | 'D' | 'M')
- });
- if prefix.len() == text.len() {
- return false;
- }
- let title = prefix.trim_end_matches(|c: char| c.is_whitespace() || matches!(c, '.' | '…'));
- let dots = prefix
- .get(title.len()..)
- .unwrap_or_default()
- .chars()
- .map(|c| match c {
- '.' => 1,
- '…' => 3,
- _ => 0,
- })
- .sum::<usize>();
- dots >= 3 && title.chars().any(char::is_alphabetic)
- }
-
- /// Text-space units → user space along the baseline. It is the vertical scale ([`Origin::k`])
- /// unless the text matrix stretches the glyphs, as an OCR layer fitting each word to the scan does.
- fn across(line: &TextLine) -> f64 {
- let m = Matrix(line.origin.tm).then(&Matrix(line.origin.ctm)).0;
- let h = m[0].hypot(m[1]);
- if h.is_finite() && h > 1e-9 { h } else { line.origin.k }
- }
-
- /// Invisible text (rendering mode 3), as in an OCR layer over a scanned image.
- fn invisible(line: &TextLine) -> bool {
- line.origin.state.render_mode == 3
- }
-
- fn same_style(a: &TextLine, b: &TextLine) -> bool {
- same_font(a, b.font.as_bytes(), &b.base_font, b.face.as_deref())
- // With no `/BaseFont` (or only a subset tag) there is no name to compare: the resource or
- // fallback face `same_font` matched is the whole identity, so keep the lines together.
- && (same_base_font(&a.base_font, &b.base_font)
- || (strip_subset_tag(&a.base_font).is_empty() && strip_subset_tag(&b.base_font).is_empty()))
- && a.bold == b.bold
- && a.italic == b.italic
- && a.color == b.color
- && (a.rotation() - b.rotation()).abs() < 0.01
- && (a.size - b.size).abs() < 0.01
- }
-
- /// Does a row open with a list marker? A bullet or a dash, or an ordered marker — digits (or a
- /// single letter) followed by `.` or `)` and then a space or the row's end, so prose such as
- /// `1.5` or `Dr. Smith` is left alone.
- fn opens_with_marker(text: &str) -> bool {
- let Some(first) = text.chars().next() else { return false };
- if matches!(first, '•' | '◦' | '▪' | '‣' | '⁃' | '*' | '-' | '–' | '—') {
- return true;
- }
- if !first.is_ascii_digit() && !first.is_ascii_alphabetic() {
- return false;
- }
- let digits = text.chars().take_while(char::is_ascii_digit).count();
- let letters = text.chars().take_while(char::is_ascii_alphabetic).count();
- // Both runs are ASCII characters, so their length in characters is their length in bytes:
- // the slice below starts on a character boundary.
- let rest = if digits > 0 {
- &text[digits..]
- } else if letters == 1 {
- &text[1..]
- } else {
- return false;
- };
- let mut after = rest.chars();
- matches!(after.next(), Some('.' | ')')) && after.next().is_none_or(char::is_whitespace)
- }
-
- /// A row that opens with a list marker opens its own item: joining it to the row above is what
- /// let an edit of one paragraph delete every item after it (#2564). The other error, splitting
- /// an ordinary paragraph, costs one more paragraph to click and never any text — so err this way.
- fn starts_list_item(row: &[usize], lines: &[TextLine]) -> bool {
- row.iter().filter_map(|i| lines.get(*i)).map(|l| l.text.trim_start()).find(|t| !t.is_empty()).is_some_and(opens_with_marker)
- }
-
- fn group_layout(lines: &[TextLine], mixed: bool) -> Vec<TextBlock> {
- let mut rows: Vec<Vec<usize>> = Vec::new();
- for (i, line) in lines.iter().enumerate() {
- let joins = rows.last().and_then(|r| r.last()).and_then(|i| lines.get(*i)).is_some_and(|prev| {
- let gap = line.frame_rect()[0] - prev.frame_rect()[2];
- // OCR words (invisible text over a scan) join only across a word space: a wider gap
- // is a table cell or a tab stop, which a rewrite would close up.
- let scanned = !mixed || (invisible(prev) == invisible(line) && (!invisible(line) || gap < prev.size.max(line.size) * 0.6));
- scanned
- && (mixed || same_style(prev, line))
- && same_plane(prev, line)
- // A superscript or subscript run (a footnote marker, say) sits on the same visual
- // row as the text around it, raised or lowered by `Ts` from the body baseline
- // (#3252). That shift is typically up to half the body size, not the marker's own
- // smaller size — but the wider tolerance only applies between a run and a
- // distinctly smaller or larger one, with no horizontal overlap (`gap >= 0.0`):
- // two equal-size runs can land within it too, at a baseline shift tight columns
- // or compressed text (`Tz`) can produce between genuinely separate rows, and the
- // original 20% tolerance is what keeps those apart.
- && ((prev.frame_origin().1 - line.frame_origin().1).abs() < prev.size.min(line.size) * 0.2
- || (gap >= 0.0
- && prev.size.min(line.size) < prev.size.max(line.size) * 0.9
- && (prev.frame_origin().1 - line.frame_origin().1).abs() < prev.size.max(line.size) * 0.5))
- && gap >= -prev.size.min(line.size) * 0.2
- && gap < prev.size.max(line.size) * 1.5
- // Separate same-style text objects that merely touch or overlap, with no space
- // between them, are separate labels (for example a paragraph dragged against
- // another, #594). Style runs and words separated by a space or gap still join.
- && (prev.origin.bt_op == line.origin.bt_op
- || gap > prev.size.min(line.size) * 0.01
- || !same_style(prev, line)
- || prev.text.ends_with(char::is_whitespace)
- || line.text.starts_with(char::is_whitespace))
- });
- if joins && let Some(row) = rows.last_mut() {
- row.push(i);
- } else {
- rows.push(vec![i]);
- }
- }
- let mut blocks: Vec<TextBlock> = Vec::new();
- for row in rows {
- let Some(first) = row.first().and_then(|i| lines.get(*i)) else { continue };
- let (Some(rect), Some(frame)) = (row_rect(&row, lines), frame_row_rect(&row, lines)) else { continue };
- let joins = blocks.last().is_some_and(|block| {
- // A bullet of its own opens a list item (#2564): such a row is a new paragraph, and
- // letting it join is what made an edit of the row above delete this item and the ones
- // after it.
- if starts_list_item(&row, lines) {
- return false;
- }
- let Some(prev_row) = block.rows.last() else { return false };
- let Some(prev) = prev_row.first().and_then(|i| lines.get(*i)) else { return false };
- let Some(pr) = frame_row_rect(prev_row, lines) else { return false };
- let gap = prev.frame_origin().1 - first.frame_origin().1;
- let tol = prev.size.max(first.size).max(1.0);
- // The block opens with a list marker and this row sits further right: the item's text
- // is at a hanging indent, so the row it wrapped onto continues it (#2564). A row at
- // the block's own left edge is already covered by the match on `pr[0]`. Both boxes are
- // in the frame, as the rest of this comparison is, so turned text matches too.
- let hanging = frame[0] > pr[0]
- && frame[0] - pr[0] <= tol * 3.0
- && block.lines.first().and_then(|&i| lines.get(i)).is_some_and(|l| opens_with_marker(l.text.trim_start()));
- let aligned = (pr[0] - frame[0]).abs() < tol
- || ((pr[0] + pr[2] - frame[0] - frame[2]) / 2.0).abs() < tol
- || (pr[2] - frame[2]).abs() < tol
- || hanging;
- // OCR lines stay apart: the scan fixes where each one is, so they never rewrap together.
- (!mixed || !(invisible(prev) || invisible(first)))
- && (mixed || same_style(prev, first))
- && same_plane(prev, first)
- // The rewrite sets every row in the first one's horizontal scale.
- && (prev.origin.state.scale - first.origin.state.scale).abs() < 1e-6
- && aligned
- && first.size.min(prev.size) >= first.size.max(prev.size) * 0.4
- && gap > first.size.min(prev.size) * 0.8
- && gap < first.size.max(prev.size) * 2.5
- });
- if !joins {
- blocks.push(TextBlock {
- text: String::new(),
- editor_text: String::new(),
- spans: Vec::new(),
- rect,
- base_font: first.base_font.clone(),
- size: first.size,
- bold: first.bold,
- italic: first.italic,
- color: first.color,
- rotation: first.rotation(),
- lines: Vec::new(),
- rows: Vec::new(),
- invisible: true,
- });
- }
- let Some(block) = blocks.last_mut() else { continue };
- let mut row_text = String::new();
- if !block.rows.is_empty() {
- block.editor_text.push('\n');
- }
- for &index in &row {
- let Some(line) = lines.get(index) else { continue };
- // Some producers position separate words without encoding a space.
- if let Some(prev) = block.lines.last().filter(|i| row.contains(i)).and_then(|i| lines.get(*i))
- && !row_text.ends_with(char::is_whitespace)
- && !line.text.starts_with(char::is_whitespace)
- && line.frame_rect()[0] - prev.frame_rect()[2] > line.size * 0.12
- {
- row_text.push(' ');
- block.editor_text.push(' ');
- }
- let start = block.editor_text.len();
- block.editor_text.push_str(&line.text);
- block.spans.push((start..block.editor_text.len(), index));
- row_text.push_str(&line.text);
- block.invisible &= line.origin.state.render_mode == 3;
- block.lines.push(index);
- }
- if !block.text.is_empty() {
- if block.text.ends_with('-') {
- block.text.pop();
- } else {
- block.text.push(' ');
- }
- }
- block.text.push_str(row_text.trim_matches(paragraph_separator));
- block.rect = union(block.rect, rect);
- block.rows.push(row);
- }
- blocks
- }
-
- /// Shape in the source or an explicitly registered matching full face. Never use interface fonts.
- fn shape_source(
- doc: &Document,
- fonts: &Dict,
- name: &str,
- text: &str,
- ) -> Result<Option<(Vec<u8>, pdfcraft_fonts::source_shaping::ShapedRun, String)>, EditError> {
- if !pdfcraft_fonts::source_shaping::required(text) {
- return Ok(None);
- }
- let source =
- fonts.get(name.as_bytes()).and_then(|f| doc.dict(f)).ok_or_else(|| EditError::Invalid("the shaped text has no font resource".into()))?;
- let family = Metrics::from_dict(doc, &source).base_font;
- let mut candidates = vec![source];
- candidates.extend(
- fonts
- .iter()
- .filter_map(|(_, f)| doc.dict(f))
- .filter(|f| pdfcraft_fonts::embedding::face_key(&Metrics::from_dict(doc, f).base_font) == pdfcraft_fonts::embedding::face_key(&family)),
- );
- for font in candidates {
- if let Some(bytes) = pdfcraft_fonts::pdf::embedded_sfnt(doc, &font)
- && pdfcraft_fonts::embedding::covers(&bytes, text)
- && let Ok(shaped) = pdfcraft_fonts::source_shaping::shape(&bytes, text)
- {
- return Ok(Some((bytes, shaped, family)));
- }
- }
- Err(EditError::Invalid("complex text needs the complete source TrueType/OpenType face; load that font before editing".into()))
- }
-
- /// For each output row (a range of the draft's characters), whether it is exactly the source row
- /// at the same position: the same characters, none of them inserted or changed by the edit.
- fn untouched_rows(block: &TextBlock, draft: &str, rows: &[std::ops::Range<usize>]) -> Vec<bool> {
- let old: Vec<char> = block.editor_text.chars().collect();
- let new: Vec<char> = draft.chars().collect();
- let prefix = old.iter().zip(&new).take_while(|(a, b)| a == b).count();
- let suffix = old.iter().rev().zip(new.iter().rev()).take(old.len().min(new.len()).saturating_sub(prefix)).take_while(|(a, b)| a == b).count();
- // The source character a draft character is, if the edit left it alone.
- let origin = |i: usize| {
- if i < prefix {
- Some(i)
- } else if i >= new.len().saturating_sub(suffix) {
- (old.len() + i).checked_sub(new.len())
- } else {
- None
- }
- };
- let mut source_rows = Vec::new();
- let mut start = 0;
- for (i, ch) in old.iter().enumerate() {
- if *ch == '\n' {
- source_rows.push(start..i);
- start = i + 1;
- }
- }
- source_rows.push(start..old.len());
- // A line break inside a source run would pair editor rows with the wrong visual rows.
- if source_rows.len() != block.rows.len() {
- return vec![false; rows.len()];
- }
- rows.iter()
- .enumerate()
- .map(|(r, range)| {
- source_rows.get(r).is_some_and(|source| {
- !range.is_empty() && range.len() == source.len() && range.clone().zip(source.clone()).all(|(i, j)| origin(i) == Some(j))
- })
- })
- .collect()
- }
-
- /// Rewrite visual rows while keeping the source style on each surviving character. Resource
- /// names may differ between Unicode subsets of the same face; encoding searches those subsets.
- pub(super) fn rewrite_styled_block(
- doc: &mut Document,
- page: usize,
- block: &TextBlock,
- lines: &[TextLine],
- text: Option<&str>,
- style: &BlockStyle,
- max_glyphs: usize,
- ) -> Result<LineEdit, EditError> {
- let first = block.lines.first().and_then(|i| lines.get(*i)).ok_or_else(|| EditError::Invalid("the paragraph has no source runs".into()))?;
- let draft = match text {
- Some(t) if t != block.text => t,
- _ => &block.editor_text,
- };
- if draft.len() > 4_000_000 {
- return Err(EditError::Invalid("the replacement text is too large".into()));
- }
- if draft == block.editor_text && *style == BlockStyle::default() {
- return Ok(LineEdit { substituted: None });
- }
- let mut ranges: Vec<_> = style.ranges.iter().collect();
- ranges.sort_by_key(|r| r.range.start);
- if ranges.len() > 1024
- || ranges.iter().any(|r| {
- r.range.start >= r.range.end
- || draft.get(r.range.clone()).is_none()
- || [r.size, r.char_spacing, r.scale].iter().flatten().any(|n| !n.is_finite())
- || r.size.is_some_and(|n| n <= 0.0 || n > 14400.0)
- || r.color.is_some_and(|c| c.iter().any(|n| !n.is_finite() || !(0.0..=1.0).contains(n)))
- })
- || ranges.windows(2).any(|r| r[0].range.end > r[1].range.start)
- {
- return Err(EditError::Invalid("text style ranges must be disjoint UTF-8 boundaries with finite formatting (at most 1024 ranges)".into()));
- }
- let source_count = lines.len();
- let mut styled_lines = lines.to_vec();
- let mut styled_spans = Vec::new();
- let mut underlines = HashMap::new();
- let mut overrides = HashMap::new();
- for (span, source) in block.edited_spans(draft) {
- let mut edges = vec![span.start, span.end];
- for r in &ranges {
- for edge in [r.range.start, r.range.end] {
- if span.contains(&edge) {
- edges.push(edge);
- }
- }
- }
- edges.sort_unstable();
- edges.dedup();
- for bounds in edges.windows(2) {
- let (Some(start), Some(end)) = (bounds.first().copied(), bounds.get(1).copied()) else { continue };
- let mut index = source;
- let selected = ranges.iter().find(|r| r.range.contains(&start)).copied();
- if selected.is_some() || style.family.is_some() || style.bold.is_some() {
- let default_range = RangeStyle {
- range: start..end,
- family: None,
- resource: None,
- size: None,
- color: None,
- underline: None,
- char_spacing: None,
- scale: None,
- };
- let r = selected.unwrap_or(&default_range);
- let mut line = lines.get(source).unwrap_or(first).clone();
- if let Some((family, bold, italic)) =
- r.family.or(style.family).or_else(|| style.bold.map(|b| (source_family(&line.base_font), b, line.italic)))
- {
- let base = family.base_font(bold, italic);
- line.font = format!("PCRange{}", base.replace('-', ""));
- line.base_font = base.to_owned();
- line.bold = bold;
- line.italic = italic;
- }
- if let Some(resource) = &r.resource {
- line.font = resource.clone();
- }
- if let Some(size) = r.size {
- line.size = size;
- }
- if let Some(color) = r.color {
- line.color = color;
- line.origin.state.fill = vec![Op::new("rg", color.map(Object::Real).to_vec())];
- }
- if let Some(spacing) = r.char_spacing {
- line.origin.state.char_spacing = spacing / line.origin.k.max(1e-6);
- }
- if let Some(scale) = r.scale {
- line.origin.state.scale = (scale / 100.0).clamp(0.1, 10.0);
- }
- index = styled_lines.len();
- styled_lines.push(line);
- if let Some(r) = selected {
- overrides.insert(index, r);
- }
- if let Some(underline) = r.underline {
- underlines.insert(index, underline);
- }
- }
- styled_spans.push((start..end, index));
- }
- }
- let lines = styled_lines.as_slice();
- let p = page_dict(doc, page)?;
- let mut res = p.dict.get(b"Resources").and_then(|r| doc.resolve(r).as_dict().cloned()).unwrap_or_default();
- let mut fonts = res.get(b"Font").and_then(|r| doc.resolve(r).as_dict().cloned()).unwrap_or_default();
- for line in lines.iter().filter(|line| line.font.starts_with("PCRange")) {
- let mut f = Dict::new();
- f.set(b"Type".to_vec(), Object::name("Font"));
- f.set(b"Subtype".to_vec(), Object::name("Type1"));
- f.set(b"BaseFont".to_vec(), Object::name(&line.base_font));
- f.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
- fonts.set(line.font.as_bytes().to_vec(), Object::Dict(f));
- }
- let mut metrics = std::collections::BTreeMap::new();
- for (name, object) in fonts.iter().take(256) {
- if let Some(font) = doc.resolve(object).as_dict() {
- metrics.insert(String::from_utf8_lossy(name).into_owned(), Metrics::from_dict(doc, font));
- }
- }
- for index in &block.lines {
- if let Some(line) = lines.get(*index)
- && !metrics.contains_key(&line.font)
- && let Some(font) = fonts.get(line.font.as_bytes()).and_then(|f| doc.resolve(f).as_dict().cloned())
- {
- metrics.insert(line.font.clone(), Metrics::from_dict(doc, &font));
- }
- }
- if [style.size, style.line_spacing, style.char_spacing, style.scale, style.width].iter().flatten().any(|v| !v.is_finite())
- || style.color.is_some_and(|c| c.iter().any(|v| !v.is_finite()))
- {
- return Err(EditError::Invalid("the paragraph's formatting must use finite numbers".into()));
- }
- let [dx, dy] = style.offset.unwrap_or([0.0, 0.0]);
- if !dx.is_finite() || !dy.is_finite() || style.width.is_some_and(|w| !w.is_finite()) {
- return Err(EditError::Invalid("the paragraph's position and width must be finite".into()));
- }
- // A visual row grows even when it contains several source/font runs. Multi-row
- // paragraphs retain their container width; an explicit width always wins.
- let natural = if block.invisible || block.rows.len() == 1 {
- (p.crop(doc)[2] - 36.0 - (block.rect[0] + dx)).max(block.rect[2] - block.rect[0])
- } else {
- block.rect[2] - block.rect[0]
- };
- let width = style.width.unwrap_or(natural).clamp(1.0, 14_400.0);
- // Each tuple is a character, its source style and an encodable resource name.
- let mut chars = Vec::new();
- let mut substituted = None;
- let mut fallback_groups: Vec<FallbackGroup> = Vec::new();
- let mut fallback_names: std::collections::BTreeMap<(String, bool, char), usize> = std::collections::BTreeMap::new();
- let mut fallback_glyphs = 0_usize;
- let per_font = max_glyphs.clamp(1, MAX_TYPE3_GLYPHS);
- let fallback_budget = per_font.saturating_mul(MAX_STYLED_FALLBACK_BATCHES);
- let mut full_faces: HashMap<String, String> = HashMap::new();
- let mut programs: HashMap<String, Option<std::sync::Arc<Vec<u8>>>> = HashMap::new();
- for (range, index) in styled_spans {
- let source = lines.get(index).unwrap_or(first);
- let start = range.start;
- for (offset, ch) in draft.get(range).unwrap_or_default().char_indices() {
- if ch == '\n' {
- chars.push((ch, index, source.font.clone()));
- continue;
- }
- // A carriage return breaks the row too. Before `\n` the pair is one break, so the
- // CR stays a `\r` the rows skip. Either way it keeps its place among the draft's
- // characters, which rows are counted in.
- if ch == '\r' {
- let crlf = start.checked_add(offset).and_then(|at| draft.get(at.saturating_add(1)..)).is_some_and(|rest| rest.starts_with('\n'));
- chars.push((if crlf { '\r' } else { '\n' }, index, source.font.clone()));
- continue;
- }
- let s = ch.to_string();
- let name = if let Some(resource) = overrides.get(&index).and_then(|r| r.resource.as_ref()).or(style.resource.as_ref()) {
- if !metrics.get(resource).is_some_and(|m| source_encodes(m, &s)) {
- return Err(EditError::Invalid(format!("the selected font resource {resource} cannot show U+{:04X}", u32::from(ch))));
- }
- resource.clone()
- } else if metrics.get(&source.font).is_some_and(|m| source_encodes(m, &s)) {
- source.font.clone()
- } else if let Some((name, _)) = metrics.iter().find(|(_, m)| {
- pdfcraft_fonts::embedding::face_key(&m.base_font) == pdfcraft_fonts::embedding::face_key(&source.base_font) && source_encodes(m, &s)
- }) {
- name.clone()
- } else if let Some(face) =
- pdfcraft_fonts::embedding::matching_faces(&source.base_font).into_iter().find(|f| pdfcraft_fonts::embedding::covers(f.bytes, &s))
- {
- let key = face.name();
- if let Some(name) = full_faces.get(&key) {
- name.clone()
- } else {
- let name = pdfcraft_fonts::embedding::embed(doc, &mut fonts, face.bytes, face.family).map_err(EditError::Invalid)?;
- let font = fonts
- .get(name.as_bytes())
- .and_then(|f| doc.dict(f))
- .ok_or_else(|| EditError::Invalid("the full source font could not be loaded".into()))?;
- metrics.insert(name.clone(), Metrics::from_dict(doc, &font));
- full_faces.insert(key, name.clone());
- name
- }
- } else if let Some(bytes) = programs
- .entry(source.font.clone())
- .or_insert_with(|| source_program(doc, &fonts, &source.font).map(std::sync::Arc::new))
- .clone()
- .filter(|bytes| pdfcraft_fonts::embedding::covers(bytes, &s))
- {
- // The document's own complete program of this font has the glyph: draw it with
- // that face rather than another family's fallback.
- let key = format!("source {}", source.font);
- if let Some(name) = full_faces.get(&key) {
- name.clone()
- } else {
- let family = pdfcraft_fonts::embedding::names(&bytes).map_or_else(|_| source.base_font.clone(), |(family, _)| family);
- let name = pdfcraft_fonts::embedding::embed(doc, &mut fonts, &bytes, &family).map_err(EditError::Invalid)?;
- let font = fonts
- .get(name.as_bytes())
- .and_then(|f| doc.dict(f))
- .ok_or_else(|| EditError::Invalid("the source font could not be loaded".into()))?;
- metrics.insert(name.clone(), Metrics::from_dict(doc, &font));
- full_faces.insert(key, name.clone());
- name
- }
- } else {
- let family = source_family(&source.base_font);
- if needs_type3(&s) {
- let key = (source.base_font.clone(), source.bold, ch);
- let group_index = if let Some(index) = fallback_names.get(&key) {
- *index
- } else {
- // Keep the old per-character face choice: a serif Japanese character
- // and a Cyrillic character may need different faces even in one style.
- // Hebrew uses the separate RTL path before reaching this writer.
- let (faces, _) = type3_faces(&s, family, source.bold)?;
- let face =
- fallback_face(&faces, &[ch], |face, ch| japanese_glyph_from(face, ch).is_ok()).ok_or_else(|| no_fallback_font(&s))?;
- let index = fallback_groups.iter().position(|group| std::ptr::eq(group.face, face)).unwrap_or_else(|| {
- let index = fallback_groups.len();
- fallback_groups.push(FallbackGroup { face, seen: Default::default(), glyphs: Vec::new(), positions: Vec::new() });
- index
- });
- fallback_names.insert(key, index);
- index
- };
- let group = fallback_groups.get_mut(group_index).ok_or_else(|| EditError::Invalid("the fallback face is missing".into()))?;
- if group.seen.insert(ch) {
- if fallback_glyphs >= fallback_budget {
- return Err(EditError::Invalid(format!(
- "the replacement needs more than {fallback_budget} fallback glyphs; edit a smaller paragraph or load a complete font"
- )));
- }
- let (path, width) = type3_glyph(group.face, ch)?.ok_or_else(|| no_glyph_for(group.face, ch))?;
- let code = u8::try_from((group.glyphs.len() % per_font).saturating_add(1))
- .map_err(|_| EditError::Invalid("replacement text has too many unique characters".into()))?;
- group.glyphs.push(Type3Glyph { code, ch, path, width });
- fallback_glyphs = fallback_glyphs.saturating_add(1);
- }
- group.positions.push(chars.len());
- // Filled from the prepared font/code map before measuring or drawing.
- String::new()
- } else {
- let base = family.base_font(source.bold, source.italic);
- let name = format!("PCEd{}", base.replace('-', ""));
- let mut f = Dict::new();
- f.set(b"Type".to_vec(), Object::name("Font"));
- f.set(b"Subtype".to_vec(), Object::name("Type1"));
- f.set(b"BaseFont".to_vec(), Object::name(base));
- f.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
- metrics.entry(name.clone()).or_insert_with(|| Metrics::from_dict(doc, &f));
- fonts.set(name.clone().into_bytes(), Object::Dict(f));
- substituted = Some(base.to_string());
- name
- }
- };
- chars.push((ch, index, name));
- }
- }
- // All fallback outlines have now succeeded. Batch by actual face, preserving source
- // style indices; the existing writer then coalesces adjacent equal-font/style characters.
- for group in fallback_groups {
- let fallback = write_type3_glyphs(doc, &mut fonts, group.face, false, group.glyphs, per_font);
- for name in &fallback.names {
- let font = fonts
- .get(name.as_bytes())
- .and_then(|f| doc.dict(f))
- .ok_or_else(|| EditError::Invalid("the fallback font could not be loaded".into()))?;
- metrics.insert(name.clone(), Metrics::from_dict(doc, &font));
- }
- for position in group.positions {
- let item = chars.get_mut(position).ok_or_else(|| EditError::Invalid("the fallback character is missing".into()))?;
- let (font, _) = fallback.codes.get(&item.0).ok_or_else(|| EditError::Invalid("the fallback glyph is missing".into()))?;
- item.2 = fallback.names.get(*font).cloned().ok_or_else(|| EditError::Invalid("the fallback font is missing".into()))?;
- }
- substituted = Some(fallback.family.to_owned());
- }
- let size_of = |source: &TextLine, index: usize| {
- overrides.get(&index).and_then(|r| r.size).or(style.size).unwrap_or(source.size).max(0.1) / source.origin.k.max(1e-6)
- };
- // A source run may carry TJ kerning/justification that is absent from its text state.
- // Keep its measured advance when rebuilding the run instead of making it wrap on entry.
- // Each font's space width, worked out once: when a font can't show a space, finding one
- // reads every font on the page, and doing that for every character of a paragraph made each
- // keystroke in a long paragraph take half a second (#2616).
- // Only for the fonts the paragraph uses, when first asked: working out every page font's width
- // up front would scan the page once per font for a short edit on a page of many fonts.
- let spaces: std::cell::RefCell<HashMap<String, f64>> = std::cell::RefCell::new(HashMap::new());
- let space_of = |name: &str, m: &Metrics| {
- if let Some(w) = spaces.borrow().get(name) {
- return *w;
- }
- let w = source_space(doc, &fonts, m);
- spaces.borrow_mut().insert(name.to_owned(), w);
- w
- };
- let mut calibration = HashMap::new();
- for (index, source) in lines.iter().enumerate() {
- if let Some(m) = metrics.get(&source.font) {
- let nominal = source_width(
- m,
- &source.text,
- source.origin.state.font.as_ref().map_or(1.0, |(_, s)| *s),
- space_of(&source.font, m),
- source.origin.state.char_spacing,
- source.origin.state.word_spacing,
- ) * source.origin.state.scale
- * across(source);
- let changed_face = style.resource.is_some() || overrides.get(&index).is_some_and(|r| r.family.is_some() || r.resource.is_some());
- let factor = if nominal > 0.0 && !changed_face { ((source.rect[2] - source.rect[0]) / nominal).clamp(0.5, 2.0) } else { 1.0 };
- calibration.insert(index, factor);
- }
- }
- let advance = |item: &(char, usize, String)| -> f64 {
- let source = lines.get(item.1).unwrap_or(first);
- let Some(m) = metrics.get(&item.2) else { return 0.0 };
- source_width(
- m,
- &item.0.to_string(),
- size_of(source, item.1),
- space_of(&item.2, m),
- overrides
- .get(&item.1)
- .and_then(|r| r.char_spacing)
- .or(style.char_spacing)
- .map_or(source.origin.state.char_spacing, |c| c / source.origin.k.max(1e-6)),
- source.origin.state.word_spacing,
- ) * overrides.get(&item.1).and_then(|r| r.scale).or(style.scale).map_or(source.origin.state.scale, |s| (s / 100.0).clamp(0.1, 10.0))
- * across(source)
- * calibration.get(&item.1).copied().unwrap_or(1.0)
- };
- let measure = |items: &[(char, usize, String)]| -> Result<f64, EditError> {
- let mut width = 0.0;
- let mut at = 0;
- while let Some(item) = items.get(at) {
- let mut end = at + 1;
- while items.get(end).is_some_and(|v| v.1 == item.1 && v.2 == item.2) {
- end += 1;
- }
- let segment = items.get(at..end).unwrap_or_default();
- let string: String = segment.iter().map(|v| v.0).collect();
- if let Some((_, shaped, _)) = shape_source(doc, &fonts, &item.2, &string)? {
- let source = lines.get(item.1).unwrap_or(first);
- let scale =
- overrides.get(&item.1).and_then(|r| r.scale).or(style.scale).map_or(source.origin.state.scale, |s| (s / 100.0).clamp(0.1, 10.0));
- let spacing = overrides
- .get(&item.1)
- .and_then(|r| r.char_spacing)
- .or(style.char_spacing)
- .map_or(source.origin.state.char_spacing, |s| s / source.origin.k.max(1e-6));
- width += (shaped.advance * size_of(source, item.1)
- + spacing * string.chars().count() as f64
- + source.origin.state.word_spacing * string.matches(' ').count() as f64)
- * scale
- * source.origin.k;
- } else {
- width += segment.iter().map(&advance).sum::<f64>();
- }
- at = end;
- }
- Ok(width)
- };
- let mut rows: Vec<Vec<(char, usize, String)>> = Vec::new();
- // Each row's characters, as indexes into the draft's characters (`chars` holds all of them).
- let mut row_ranges = Vec::new();
- // Each row's line in the draft (its `\n`-separated part), which [`BlockStyle::aligns`] counts.
- let mut row_lines: Vec<usize> = Vec::new();
- let mut draft_line = 0usize;
- let mut row_start = 0;
- let mut row = Vec::new();
- let mut row_width = 0.0;
- // Wrap at word boundaries, retaining explicit source row breaks and whitespace.
- let mut at = 0;
- while at < chars.len() {
- let Some(item) = chars.get(at) else { break };
- // The CR of a CRLF: the `\n` after it breaks the row.
- if item.0 == '\r' {
- at += 1;
- continue;
- }
- if item.0 == '\n' {
- row_ranges.push(row_start..row_start + row.len());
- row_lines.push(draft_line);
- draft_line = draft_line.saturating_add(1);
- rows.push(std::mem::take(&mut row));
- row_width = 0.0;
- at += 1;
- row_start = at;
- continue;
- }
- let mut end = at + 1;
- if !item.0.is_whitespace() {
- // A word ends at a space, or where Chinese or Japanese text may break between characters.
- while let (Some(before), Some(c)) = (chars.get(end - 1), chars.get(end))
- && !c.0.is_whitespace()
- && !crate::linebreak::between(before.0, c.0)
- {
- end += 1;
- }
- }
- let word = chars.get(at..end).unwrap_or_default();
- let w = measure(word)?;
- if !row.is_empty() && !item.0.is_whitespace() && row_width + w > width + 0.5 {
- while row.last().is_some_and(|c: &(char, usize, String)| c.0.is_whitespace()) {
- row.pop();
- }
- row_ranges.push(row_start..row_start + row.len());
- row_lines.push(draft_line);
- rows.push(std::mem::take(&mut row));
- row_width = 0.0;
- row_start = at;
- }
- row.extend_from_slice(word);
- row_width += w;
- at = end;
- }
- if !row.is_empty() {
- row_ranges.push(row_start..row_start + row.len());
- row_lines.push(draft_line);
- rows.push(row);
- }
- let streams = content_streams(doc, &p.dict)?;
- let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
- let ops = pieces.parse().ops;
- // A row the edit doesn't reach keeps its source operators, so its kerning, TJ word gaps and
- // glyph widths stay exactly as they were instead of being rebuilt from the text state. A row
- // aligned on its own is reached; the rows around it are not.
- let plain = BlockStyle { ranges: Vec::new(), aligns: Vec::new(), ..style.clone() } == BlockStyle::default();
- let mut kept = if plain {
- untouched_rows(block, draft, &row_ranges)
- .into_iter()
- .zip(&rows)
- .zip(&row_lines)
- .map(|((same, row), line)| same && row.iter().all(|c| c.1 < source_count) && style.aligns.get(*line).copied().flatten().is_none())
- .collect()
- } else {
- vec![false; rows.len()]
- };
- let kept_lines: std::collections::HashSet<usize> =
- kept.iter().enumerate().filter(|(_, k)| **k).filter_map(|(r, _)| block.rows.get(r)).flatten().copied().collect();
- let rewritten: Vec<&TextLine> = block.lines.iter().filter(|i| !kept_lines.contains(i)).filter_map(|i| lines.get(*i)).collect();
- // The rewrite goes where the last rewritten row was drawn, after any backgrounds painted
- // between the rows. A dropped `'` or `"` also moved to the next line, which a kept row relies on.
- let lead =
- rewritten.last().copied().filter(|_| !rewritten.iter().flat_map(|l| &l.ops).any(|i| ops.get(*i).is_some_and(|op| op.is("'") || op.is("\""))));
- let (members, lead) = match lead {
- Some(lead) if !kept_lines.is_empty() => (rewritten, lead),
- _ => {
- kept.iter_mut().for_each(|k| *k = false);
- let all: Vec<&TextLine> = block.lines.iter().filter_map(|i| lines.get(*i)).collect();
- let last = all.last().copied().unwrap_or(first);
- (all, last)
- }
- };
- let o = &lead.origin;
- let mut drop = coincident_ops(lines, &members);
- drop.extend(members.iter().flat_map(|l| l.ops.iter().copied()));
- let start = lead.ops.first().copied().unwrap_or(o.bt_op);
- let split = ops
- .get(o.bt_op..start)
- .unwrap_or_default()
- .iter()
- .enumerate()
- .any(|(i, op)| matches!(op.op.as_slice(), b"Tj" | b"TJ" | b"'" | b"\"") && !drop.contains(&(o.bt_op + i)));
- // What is in force where the rewrite is drawn, and what the text after it expects.
- let after = if split { &o.state } else { &o.bt_state };
- for (row, _) in rows.iter().zip(&kept).filter(|(_, k)| !**k) {
- let text: String = row.iter().map(|v| v.0).collect();
- if pdfcraft_fonts::source_shaping::required(&text) && row.first().is_some_and(|first| row.iter().any(|v| v.1 != first.1 || v.2 != first.2)) {
- return Err(EditError::Invalid(
- "contextual/bidi text across font or style boundaries needs a uniform full-face row; mixed contextual runs are not yet supported"
- .into(),
- ));
- }
- }
- let measured: Vec<_> = rows.iter().map(|r| measure(r)).collect::<Result<_, _>>()?;
- let mut shaped_runs = HashMap::new();
- let mut segment_advances = HashMap::new();
- for (row_index, row) in rows.iter().enumerate().filter(|(r, _)| !kept.get(*r).copied().unwrap_or(false)) {
- let mut at = 0;
- while let Some(item) = row.get(at) {
- let mut end = at + 1;
- while row.get(end).is_some_and(|v| v.1 == item.1 && v.2 == item.2) {
- end += 1;
- }
- segment_advances.insert((row_index, at), row.get(at..end).unwrap_or_default().iter().map(&advance).sum::<f64>());
- let string: String = row.get(at..end).unwrap_or_default().iter().map(|v| v.0).collect();
- if let Some((bytes, shaped, family)) = shape_source(doc, &fonts, &item.2, &string)? {
- shaped_runs.insert((row_index, at), (bytes, shaped, family));
- }
- at = end;
- }
- }
- let mut glyph_resources = HashMap::new();
- for (key, (bytes, shaped, family)) in &shaped_runs {
- let mappings: Vec<_> = shaped.glyphs.iter().map(|g| (g.text.clone(), g.id)).collect();
- let resource = pdfcraft_fonts::embedding::embed_mapping(doc, &mut fonts, bytes, family, &mappings).map_err(EditError::Invalid)?;
- glyph_resources.insert(*key, resource);
- }
- let n = pdfcraft_content::num;
- let mut block_ops = vec![Op::new("q", vec![])];
- block_ops.extend(reveal_ops(block, lines, style, o.ctm)?);
- let back = Matrix([o.ctm[0], o.ctm[1], o.ctm[2], o.ctm[3], 0.0, 0.0])
- .invert()
- .ok_or_else(|| EditError::Invalid("the paragraph is drawn in a space it cannot be edited in".into()))?;
- let (tx, ty) = back.apply(dx, dy);
- block_ops.push(Op::new("cm", vec![n(1.0), n(0.0), n(0.0), n(1.0), n(tx), n(ty)]));
- let crop = p.crop(doc);
- let centered = is_centred(block, lines, (crop[0] + crop[2]) / 2.0, first.size);
- let source_leading = block
- .rows
- .windows(2)
- .filter_map(|rows| {
- let a = rows[0].first().and_then(|i| lines.get(*i))?;
- let b = rows[1].first().and_then(|i| lines.get(*i))?;
- Some((a.origin.baseline - b.origin.baseline).abs())
- })
- .rfind(|v| *v > 0.0)
- .unwrap_or(first.size * 1.5);
- let mut baseline = first.origin.baseline;
- for (row_index, row) in rows.iter().enumerate() {
- let anchor = block.rows.get(row_index).and_then(|r| r.first()).and_then(|i| lines.get(*i));
- if style.line_spacing.is_none()
- && style.size.is_none()
- && let Some(anchor) = anchor
- {
- baseline = anchor.origin.baseline;
- }
- let anchor = anchor.unwrap_or(first);
- if kept.get(row_index).copied().unwrap_or(false) {
- // Kept rows only occur without spacing or size changes, so this is the step below.
- baseline -= source_leading;
- continue;
- }
- let w = measured.get(row_index).copied().unwrap_or(0.0);
- // The row's own alignment, or the paragraph's.
- let asked = row_lines.get(row_index).and_then(|l| style.aligns.get(*l)).copied().flatten().or(style.align);
- let align = asked.unwrap_or(if centered { crate::added::Align::Center } else { crate::added::Align::Left });
- let original_rect = block.rows.get(row_index).and_then(|row| row_rect(row, lines)).unwrap_or(block.rect);
- let left = if style.width.is_none() && asked.is_none() { original_rect[0] } else { block.rect[0] };
- let available = if style.width.is_none() && asked.is_none() { original_rect[2] - original_rect[0] } else { width };
- let mut x = left
- + match align {
- crate::added::Align::Center => (available - w) / 2.0,
- crate::added::Align::Right => available - w,
- _ => 0.0,
- };
- let mut pos = 0;
- while pos < row.len() {
- let Some(item) = row.get(pos) else { break };
- let source = lines.get(item.1).unwrap_or(first);
- let mut end = pos + 1;
- while row.get(end).is_some_and(|other| other.1 == item.1 && other.2 == item.2) {
- end += 1;
- }
- let segment = row.get(pos..end).unwrap_or_default();
- let string: String = segment.iter().map(|c| c.0).collect();
- let m = metrics.get(&item.2).ok_or_else(|| EditError::Invalid("the paragraph font is missing".into()))?;
- let mut state = source.origin.state.clone();
- state.font = Some((item.2.clone(), size_of(source, item.1)));
- if let Some(c) = overrides.get(&item.1).and_then(|r| r.char_spacing).or(style.char_spacing) {
- state.char_spacing = c / source.origin.k.max(1e-6);
- }
- if let Some(s) = overrides.get(&item.1).and_then(|r| r.scale).or(style.scale) {
- state.scale = (s / 100.0).clamp(0.1, 10.0);
- }
- if !shaped_runs.contains_key(&(row_index, pos)) {
- state.scale *= calibration.get(&item.1).copied().unwrap_or(1.0);
- }
- if let Some([r, g, b]) = overrides.get(&item.1).and_then(|r| r.color).or(style.color) {
- state.fill = vec![Op::new("rg", vec![n(r), n(g), n(b)])];
- }
- let inverse = Matrix(o.ctm).invert().ok_or_else(|| EditError::Invalid("the paragraph has a singular transform".into()))?;
- let mut tm = Matrix(source.origin.tm).then(&Matrix(source.origin.ctm)).then(&inverse).0;
- let (ax, ay) = back.apply(x - source.origin.x, baseline - source.origin.baseline);
- tm[4] += ax;
- tm[5] += ay;
- let mut segment_width = segment_advances.get(&(row_index, pos)).copied().unwrap_or(0.0);
- // Each run in its own graphics state, restating what its source set inside its text
- // object (`gs`, stroke, line width, `Tr`; #3508/#3509) from the state the rewrite is
- // drawn in: a `gs` has no inverse, so one run's ExtGState would stay for the next.
- block_ops.push(Op::new("q", vec![]));
- block_ops.extend(state.paint_ops(after));
- if let Some((_, shaped, _)) = shaped_runs.get(&(row_index, pos)) {
- let resource = glyph_resources.get(&(row_index, pos)).ok_or_else(|| EditError::Invalid("shaped font is missing".into()))?;
- let mut properties = Dict::new();
- properties.set(b"ActualText".to_vec(), Object::String(PdfString::text(&string)));
- block_ops.push(Op::new("BDC", vec![Object::name("Span"), Object::Dict(properties)]));
- state.font = Some((resource.clone(), size_of(source, item.1)));
- // One text object for the run: each glyph is placed where shaping put it by a TJ
- // adjustment from where the glyph before it ends (its advance in the embedded
- // font's widths), and raised by the text rise for a mark set above or below
- // (ISO 32000-1 §9.4.3, §9.3.7). Font-program codes are separate from Unicode;
- // ToUnicode and ActualText keep the logical text.
- let size = size_of(source, item.1);
- let per_unit = 1000.0 / size;
- if !per_unit.is_finite() {
- return Err(EditError::Invalid("the shaped text has no size".into()));
- }
- let shown = fonts
- .get(resource.as_bytes())
- .and_then(|f| doc.resolve(f).as_dict().cloned())
- .map(|d| Metrics::from_dict(doc, &d))
- .ok_or_else(|| EditError::Invalid("shaped font is missing".into()))?;
- // Spacing is part of each glyph's position, so the run itself has none.
- let (char_spacing, word_spacing, rise) = (state.char_spacing, state.word_spacing, state.rise);
- state.char_spacing = 0.0;
- state.word_spacing = 0.0;
- block_ops.push(Op::new("BT", vec![]));
- block_ops.extend(state.ops());
- block_ops.push(Op::new("Tm", tm.iter().map(|v| n(*v)).collect()));
- // `pen`: where the next glyph would start, in thousandths of the font size.
- let (mut pen, mut extra, mut raised) = (0.0, 0.0, rise);
- let mut shown_glyphs: Vec<Object> = Vec::new();
- for (i, glyph) in shaped.glyphs.iter().enumerate() {
- let target = (glyph.position[0] * size + extra) * per_unit;
- let glyph_rise = rise + glyph.position[1] * size;
- if (glyph_rise - raised).abs() > 1e-9 || shown_glyphs.len() >= 4096 {
- if !shown_glyphs.is_empty() {
- block_ops.push(Op::new("TJ", vec![Object::Array(std::mem::take(&mut shown_glyphs))]));
- }
- if (glyph_rise - raised).abs() > 1e-9 {
- block_ops.push(Op::new("Ts", vec![n(glyph_rise)]));
- raised = glyph_rise;
- }
- }
- if (target - pen).abs() > 1e-6 {
- shown_glyphs.push(n(pen - target));
- }
- let code = u16::try_from(i + 1).map_err(|_| EditError::Invalid("shaped glyph limit".into()))?;
- shown_glyphs.push(Object::String(PdfString::literal(code.to_be_bytes().to_vec())));
- pen = target + shown.width(u32::from(code)) * 1000.0;
- extra += char_spacing * glyph.text.chars().count() as f64 + word_spacing * glyph.text.matches(' ').count() as f64;
- }
- if !shown_glyphs.is_empty() {
- block_ops.push(Op::new("TJ", vec![Object::Array(shown_glyphs)]));
- }
- if (raised - rise).abs() > 1e-9 {
- block_ops.push(Op::new("Ts", vec![n(rise)]));
- }
- block_ops.push(Op::new("ET", vec![]));
- (state.char_spacing, state.word_spacing) = (char_spacing, word_spacing);
- block_ops.push(Op::new("EMC", vec![]));
- segment_width = (shaped.advance * size + extra) * state.scale * source.origin.k;
- } else {
- block_ops.push(Op::new("BT", vec![]));
- block_ops.extend(state.ops());
- block_ops.push(Op::new("Tm", tm.iter().map(|v| n(*v)).collect()));
- block_ops.extend(source_show(
- m,
- &string,
- size_of(source, item.1),
- spaces.borrow().get(&item.2).copied().unwrap_or_else(|| source_space(doc, &fonts, m)),
- state.char_spacing,
- state.word_spacing,
- )?);
- block_ops.push(Op::new("ET", vec![]));
- }
- if underlines.get(&item.1).copied().or(style.underline) == Some(true) {
- let [r, g, b] = overrides.get(&item.1).and_then(|r| r.color).or(style.color).unwrap_or(source.color);
- let underline_size = size_of(source, item.1) * source.origin.k;
- let (x0, y0) = back.apply(x - o.ctm[4], baseline - o.ctm[5] - underline_size * 0.12);
- let (x1, y1) = back.apply(x + segment_width - o.ctm[4], baseline - o.ctm[5] - underline_size * 0.12);
- block_ops.push(Op::new("RG", vec![n(r), n(g), n(b)]));
- block_ops.push(Op::new("w", vec![n(underline_size * 0.06 / o.ctm[2].hypot(o.ctm[3]).max(1e-6))]));
- block_ops.push(Op::new("m", vec![n(x0), n(y0)]));
- block_ops.push(Op::new("l", vec![n(x1), n(y1)]));
- block_ops.push(Op::new("S", vec![]));
- }
- block_ops.push(Op::new("Q", vec![]));
- x += segment_width;
- pos = end;
- }
- baseline -= if style.line_spacing.is_none() && style.size.is_none() {
- source_leading
- } else {
- style.line_spacing.unwrap_or(1.5).clamp(0.5, 5.0) * style.size.unwrap_or(anchor.size)
- };
- }
- block_ops.push(Op::new("Q", vec![]));
- block_ops.extend(after.ops());
- if split {
- block_ops.insert(0, Op::new("ET", vec![]));
- block_ops.push(Op::new("BT", vec![]));
- block_ops.push(Op::new("Tm", o.tlm.iter().map(|v| n(*v)).collect()));
- }
- let at = if split { start } else { o.bt_op };
- let data = splice(&pieces, &ops, |i| (if i == at { std::mem::take(&mut block_ops) } else { Vec::new() }, !drop.contains(&i)));
- let contents = rewritten_contents(doc, &streams, data);
- res.set(b"Font".to_vec(), Object::Dict(fonts));
- doc.update_dict(p.obj, |d| {
- d.set(b"Contents".to_vec(), contents);
- d.set(b"Resources".to_vec(), Object::Dict(res));
- })?;
- Ok(LineEdit { substituted })
- }
-pub(super) use grouping::{group_blocks, group_reading_blocks, is_centred};
++pub(super) use grouping::{alignment_frame, group_blocks, group_reading_blocks, is_centred};
+ pub(super) use styled::rewrite_styled_block;
diff --cc crates/edit/src/text_regions/grouping.rs
index 000000000,29004b8e3..fce75880d
mode 000000,100644..100644
--- a/crates/edit/src/text_regions/grouping.rs
+++ b/crates/edit/src/text_regions/grouping.rs
@@@ -1,0 -1,319 +1,345 @@@
+ use super::*;
+
+ fn same_plane(a: &TextLine, b: &TextLine) -> bool {
+ let at = Matrix(a.origin.tm).then(&Matrix(a.origin.ctm));
+ let bt = Matrix(b.origin.tm).then(&Matrix(b.origin.ctm));
+ a.scope == b.scope
+ && a.paint == b.paint
+ && [0, 2].iter().all(|axis| {
+ let ax = at.0.get(*axis).copied().unwrap_or(0.0);
+ let ay = at.0.get(axis + 1).copied().unwrap_or(0.0);
+ let bx = bt.0.get(*axis).copied().unwrap_or(0.0);
+ let by = bt.0.get(axis + 1).copied().unwrap_or(0.0);
+ let al = ax.hypot(ay);
+ let bl = bx.hypot(by);
+ al > 0.0 && bl > 0.0 && (ax / al - bx / bl).abs() < 0.001 && (ay / al - by / bl).abs() < 0.001
+ })
+ }
+
+ pub(super) fn row_rect(row: &[usize], lines: &[TextLine]) -> Option<[f64; 4]> {
+ row.iter().filter_map(|i| lines.get(*i)).map(|l| l.rect).reduce(union)
+ }
+
+ /// [`row_rect`] in its text's own frame ([`TextLine::frame_rect`]), so rows of turned text
+ /// compare along and across their baselines.
+ fn frame_row_rect(row: &[usize], lines: &[TextLine]) -> Option<[f64; 4]> {
+ row.iter().filter_map(|i| lines.get(*i)).map(TextLine::frame_rect).reduce(union)
+ }
+
+ /// The left edge the rest of the page's text sits on, ignoring the rows of `block`. A single row
+ /// that does not share it is not merely an indented or full-width left-aligned line, so its own
-/// centre is the only remaining explanation for where it sits.
-fn neighbour_left(lines: &[TextLine], block: &TextBlock) -> Option<f64> {
++/// centre is the only remaining explanation for where it sits. With `over`, only rows reaching
++/// across that span count: the edge of the column under it, however many rows another column has.
++fn neighbour_left(lines: &[TextLine], block: &TextBlock, over: Option<[f64; 2]>) -> Option<f64> {
+ let mut edges: HashMap<i64, usize> = HashMap::new();
+ for (i, line) in lines.iter().enumerate() {
- if block.lines.contains(&i) {
++ if block.lines.contains(&i) || over.is_some_and(|[left, right]| line.rect[2] <= left || line.rect[0] >= right) {
+ continue;
+ }
+ // Quarter-point buckets: equal edges found through different runs still agree.
+ *edges.entry((line.rect[0] * 4.0).round() as i64).or_insert(0) += 1;
+ }
+ let (best, _) = edges.into_iter().max_by_key(|(_, count)| *count)?;
+ Some(best as f64 / 4.0)
+ }
+
++/// Where an alignment picked for a one-row paragraph is measured, as `[left, right]`: the column of
++/// text it sits in (the left edge the text under or over it uses, to the furthest right those rows
++/// reach) when that column holds it, otherwise its own box. A lone row's own box is no frame
++/// to align in: left-aligning a title centred on the page left it where it was, and since a single
++/// row grows to the page's margin, centring it again moved it right each time. `None` when no
++/// alignment is asked for, or when the paragraph is several rows, turned, or given a width or a
++/// move of its own.
++pub(crate) fn alignment_frame(lines: &[TextLine], block: &TextBlock, style: &BlockStyle) -> Option<[f64; 2]> {
++ let asked = style.align.is_some() || style.aligns.iter().any(Option::is_some);
++ if !asked || style.width.is_some() || style.offset.is_some() || block.rows.len() != 1 || block.rotation.abs() > 0.01 {
++ return None;
++ }
++ let own = [block.rect[0], block.rect[2]];
++ let tolerance = block.size.max(1.0) * 0.5;
++ let Some(left) = neighbour_left(lines, block, Some(own)) else { return Some(own) };
++ let right = lines
++ .iter()
++ .enumerate()
++ .filter(|(i, line)| !block.lines.contains(i) && (line.rect[0] - left).abs() < tolerance)
++ .map(|(_, line)| line.rect[2])
++ .fold(f64::NEG_INFINITY, f64::max);
++ let holds = right.is_finite() && right - left > own[1] - own[0] && own[0] >= left - tolerance && own[1] <= right + tolerance;
++ Some(if holds { [left, right] } else { own })
++}
++
+ /// Whether a block reads as centred, and so must keep its centre when it grows or wraps.
+ ///
+ /// Several ragged rows whose left edges disagree while their centres agree are centred. A one row
+ /// block cannot say that: all of its left edges are the same, so the ragged test never fires and a
+ /// centred title would be taken for left-aligned and grow to the right (#2581). Fall back to the
+ /// page instead — a lone row sitting on the page's own centre, and not on the edge the rest of the
+ /// text uses, is a centred title. A full-width left-aligned line still lines up with that edge, so
+ /// it is not mistaken for one.
+ pub(crate) fn is_centred(block: &TextBlock, lines: &[TextLine], page_centre: f64, size: f64) -> bool {
+ let centre = (block.rect[0] + block.rect[2]) / 2.0;
+ let lefts: Vec<_> = block.rows.iter().filter_map(|r| row_rect(r, lines).map(|r| r[0])).collect();
+ if block.rows.len() > 1 {
+ let left_span = lefts.iter().copied().fold(f64::NEG_INFINITY, f64::max) - lefts.iter().copied().fold(f64::INFINITY, f64::min);
+ return left_span > size * 0.5
+ && block.rows.iter().all(|row| row_rect(row, lines).is_some_and(|r| ((r[0] + r[2]) / 2.0 - centre).abs() < size));
+ }
- lefts
- .first()
- .is_some_and(|left| (centre - page_centre).abs() < size && neighbour_left(lines, block).is_none_or(|edge| (*left - edge).abs() > size * 0.5))
++ lefts.first().is_some_and(|left| {
++ (centre - page_centre).abs() < size && neighbour_left(lines, block, None).is_none_or(|edge| (*left - edge).abs() > size * 0.5)
++ })
+ }
+
+ pub(crate) fn group_blocks(lines: &[TextLine]) -> Vec<TextBlock> {
+ group_layout(lines, true)
+ }
+
+ /// Exporters currently represent a block with one style. Keep their style boundaries until
+ /// they support rich runs, while edit selection may encompass the complete visual region.
+ /// Dotted-leader entries stay on one row and use the title run's style.
+ pub(crate) fn group_reading_blocks(lines: &[TextLine]) -> Vec<TextBlock> {
+ let mut blocks = Vec::new();
+ let mut start = 0;
+ let mut offset = 0;
+ for row in lines.chunk_by(|a, b| same_plane(a, b) && (a.origin.baseline - b.origin.baseline).abs() < a.size.min(b.size) * 0.2) {
+ let mut text = String::new();
+ for (i, line) in row.iter().enumerate() {
+ if !text.ends_with(char::is_whitespace)
+ && !line.text.starts_with(char::is_whitespace)
+ && i.checked_sub(1).and_then(|i| row.get(i)).is_some_and(|prev| line.rect[0] - prev.rect[2] > line.size * 0.12)
+ {
+ text.push(' ');
+ }
+ text.push_str(&line.text);
+ }
+ if leader_entry(&text)
+ && let Some(first) = row.first()
+ {
+ // Tab leaders are a single reading row, even when the title, dots and page
+ // number are separate text objects far apart. Do not merge neighbouring entries.
+ blocks.extend(group_layout(lines.get(start..offset).unwrap_or_default(), false));
+ let mut line = first.clone();
+ line.text = text;
+ line.rect = row.iter().map(|line| line.rect).reduce(union).unwrap_or(first.rect);
+ blocks.extend(group_layout(std::slice::from_ref(&line), false));
+ start = offset + row.len();
+ }
+ offset += row.len();
+ }
+ blocks.extend(group_layout(lines.get(start..).unwrap_or_default(), false));
+ blocks
+ }
+
+ /// Dotted leaders end in a page number, with a title before the dots. A dot in an article
+ /// number, or an ellipsis in ordinary prose, is not enough to make a contents entry.
+ fn leader_entry(text: &str) -> bool {
+ let text = text.trim_end();
+ let prefix = text.trim_end_matches(|c: char| {
+ c.is_ascii_digit() || matches!(c, 'i' | 'v' | 'x' | 'l' | 'c' | 'd' | 'm' | 'I' | 'V' | 'X' | 'L' | 'C' | 'D' | 'M')
+ });
+ if prefix.len() == text.len() {
+ return false;
+ }
+ let title = prefix.trim_end_matches(|c: char| c.is_whitespace() || matches!(c, '.' | '…'));
+ let dots = prefix
+ .get(title.len()..)
+ .unwrap_or_default()
+ .chars()
+ .map(|c| match c {
+ '.' => 1,
+ '…' => 3,
+ _ => 0,
+ })
+ .sum::<usize>();
+ dots >= 3 && title.chars().any(char::is_alphabetic)
+ }
+
+ /// Text-space units → user space along the baseline. It is the vertical scale ([`Origin::k`])
+ /// unless the text matrix stretches the glyphs, as an OCR layer fitting each word to the scan does.
+ pub(super) fn across(line: &TextLine) -> f64 {
+ let m = Matrix(line.origin.tm).then(&Matrix(line.origin.ctm)).0;
+ let h = m[0].hypot(m[1]);
+ if h.is_finite() && h > 1e-9 { h } else { line.origin.k }
+ }
+
+ /// Invisible text (rendering mode 3), as in an OCR layer over a scanned image.
+ fn invisible(line: &TextLine) -> bool {
+ line.origin.state.render_mode == 3
+ }
+
+ fn same_style(a: &TextLine, b: &TextLine) -> bool {
+ same_font(a, b.font.as_bytes(), &b.base_font, b.face.as_deref())
+ // With no `/BaseFont` (or only a subset tag) there is no name to compare: the resource or
+ // fallback face `same_font` matched is the whole identity, so keep the lines together.
+ && (same_base_font(&a.base_font, &b.base_font)
+ || (strip_subset_tag(&a.base_font).is_empty() && strip_subset_tag(&b.base_font).is_empty()))
+ && a.bold == b.bold
+ && a.italic == b.italic
+ && a.color == b.color
+ && (a.rotation() - b.rotation()).abs() < 0.01
+ && (a.size - b.size).abs() < 0.01
+ }
+
+ /// Does a row open with a list marker? A bullet or a dash, or an ordered marker — digits (or a
+ /// single letter) followed by `.` or `)` and then a space or the row's end, so prose such as
+ /// `1.5` or `Dr. Smith` is left alone.
+ fn opens_with_marker(text: &str) -> bool {
+ let Some(first) = text.chars().next() else { return false };
+ if matches!(first, '•' | '◦' | '▪' | '‣' | '⁃' | '*' | '-' | '–' | '—') {
+ return true;
+ }
+ if !first.is_ascii_digit() && !first.is_ascii_alphabetic() {
+ return false;
+ }
+ let digits = text.chars().take_while(char::is_ascii_digit).count();
+ let letters = text.chars().take_while(char::is_ascii_alphabetic).count();
+ // Both runs are ASCII characters, so their length in characters is their length in bytes:
+ // the slice below starts on a character boundary.
+ let rest = if digits > 0 {
+ &text[digits..]
+ } else if letters == 1 {
+ &text[1..]
+ } else {
+ return false;
+ };
+ let mut after = rest.chars();
+ matches!(after.next(), Some('.' | ')')) && after.next().is_none_or(char::is_whitespace)
+ }
+
+ /// A row that opens with a list marker opens its own item: joining it to the row above is what
+ /// let an edit of one paragraph delete every item after it (#2564). The other error, splitting
+ /// an ordinary paragraph, costs one more paragraph to click and never any text — so err this way.
+ fn starts_list_item(row: &[usize], lines: &[TextLine]) -> bool {
+ row.iter().filter_map(|i| lines.get(*i)).map(|l| l.text.trim_start()).find(|t| !t.is_empty()).is_some_and(opens_with_marker)
+ }
+
+ fn group_layout(lines: &[TextLine], mixed: bool) -> Vec<TextBlock> {
+ let mut rows: Vec<Vec<usize>> = Vec::new();
+ for (i, line) in lines.iter().enumerate() {
+ let joins = rows.last().and_then(|r| r.last()).and_then(|i| lines.get(*i)).is_some_and(|prev| {
+ let gap = line.frame_rect()[0] - prev.frame_rect()[2];
+ // OCR words (invisible text over a scan) join only across a word space: a wider gap
+ // is a table cell or a tab stop, which a rewrite would close up.
+ let scanned = !mixed || (invisible(prev) == invisible(line) && (!invisible(line) || gap < prev.size.max(line.size) * 0.6));
+ scanned
+ && (mixed || same_style(prev, line))
+ && same_plane(prev, line)
+ // A superscript or subscript run (a footnote marker, say) sits on the same visual
+ // row as the text around it, raised or lowered by `Ts` from the body baseline
+ // (#3252). That shift is typically up to half the body size, not the marker's own
+ // smaller size — but the wider tolerance only applies between a run and a
+ // distinctly smaller or larger one, with no horizontal overlap (`gap >= 0.0`):
+ // two equal-size runs can land within it too, at a baseline shift tight columns
+ // or compressed text (`Tz`) can produce between genuinely separate rows, and the
+ // original 20% tolerance is what keeps those apart.
+ && ((prev.frame_origin().1 - line.frame_origin().1).abs() < prev.size.min(line.size) * 0.2
+ || (gap >= 0.0
+ && prev.size.min(line.size) < prev.size.max(line.size) * 0.9
+ && (prev.frame_origin().1 - line.frame_origin().1).abs() < prev.size.max(line.size) * 0.5))
+ && gap >= -prev.size.min(line.size) * 0.2
+ && gap < prev.size.max(line.size) * 1.5
+ // Separate same-style text objects that merely touch or overlap, with no space
+ // between them, are separate labels (for example a paragraph dragged against
+ // another, #594). Style runs and words separated by a space or gap still join.
+ && (prev.origin.bt_op == line.origin.bt_op
+ || gap > prev.size.min(line.size) * 0.01
+ || !same_style(prev, line)
+ || prev.text.ends_with(char::is_whitespace)
+ || line.text.starts_with(char::is_whitespace))
+ });
+ if joins && let Some(row) = rows.last_mut() {
+ row.push(i);
+ } else {
+ rows.push(vec![i]);
+ }
+ }
+ let mut blocks: Vec<TextBlock> = Vec::new();
+ for row in rows {
+ let Some(first) = row.first().and_then(|i| lines.get(*i)) else { continue };
+ let (Some(rect), Some(frame)) = (row_rect(&row, lines), frame_row_rect(&row, lines)) else { continue };
+ let joins = blocks.last().is_some_and(|block| {
+ // A bullet of its own opens a list item (#2564): such a row is a new paragraph, and
+ // letting it join is what made an edit of the row above delete this item and the ones
+ // after it.
+ if starts_list_item(&row, lines) {
+ return false;
+ }
+ let Some(prev_row) = block.rows.last() else { return false };
+ let Some(prev) = prev_row.first().and_then(|i| lines.get(*i)) else { return false };
+ let Some(pr) = frame_row_rect(prev_row, lines) else { return false };
+ let gap = prev.frame_origin().1 - first.frame_origin().1;
+ let tol = prev.size.max(first.size).max(1.0);
+ // The block opens with a list marker and this row sits further right: the item's text
+ // is at a hanging indent, so the row it wrapped onto continues it (#2564). A row at
+ // the block's own left edge is already covered by the match on `pr[0]`. Both boxes are
+ // in the frame, as the rest of this comparison is, so turned text matches too.
+ let hanging = frame[0] > pr[0]
+ && frame[0] - pr[0] <= tol * 3.0
+ && block.lines.first().and_then(|&i| lines.get(i)).is_some_and(|l| opens_with_marker(l.text.trim_start()));
+ let aligned = (pr[0] - frame[0]).abs() < tol
+ || ((pr[0] + pr[2] - frame[0] - frame[2]) / 2.0).abs() < tol
+ || (pr[2] - frame[2]).abs() < tol
+ || hanging;
+ // OCR lines stay apart: the scan fixes where each one is, so they never rewrap together.
+ (!mixed || !(invisible(prev) || invisible(first)))
+ && (mixed || same_style(prev, first))
+ && same_plane(prev, first)
+ // The rewrite sets every row in the first one's horizontal scale.
+ && (prev.origin.state.scale - first.origin.state.scale).abs() < 1e-6
+ && aligned
+ && first.size.min(prev.size) >= first.size.max(prev.size) * 0.4
+ && gap > first.size.min(prev.size) * 0.8
+ && gap < first.size.max(prev.size) * 2.5
+ });
+ if !joins {
+ blocks.push(TextBlock {
+ text: String::new(),
+ editor_text: String::new(),
+ spans: Vec::new(),
+ rect,
+ base_font: first.base_font.clone(),
+ size: first.size,
+ bold: first.bold,
+ italic: first.italic,
+ color: first.color,
+ rotation: first.rotation(),
+ lines: Vec::new(),
+ rows: Vec::new(),
+ invisible: true,
+ });
+ }
+ let Some(block) = blocks.last_mut() else { continue };
+ let mut row_text = String::new();
+ if !block.rows.is_empty() {
+ block.editor_text.push('\n');
+ }
+ for &index in &row {
+ let Some(line) = lines.get(index) else { continue };
+ // Some producers position separate words without encoding a space.
+ if let Some(prev) = block.lines.last().filter(|i| row.contains(i)).and_then(|i| lines.get(*i))
+ && !row_text.ends_with(char::is_whitespace)
+ && !line.text.starts_with(char::is_whitespace)
+ && line.frame_rect()[0] - prev.frame_rect()[2] > line.size * 0.12
+ {
+ row_text.push(' ');
+ block.editor_text.push(' ');
+ }
+ let start = block.editor_text.len();
+ block.editor_text.push_str(&line.text);
+ block.spans.push((start..block.editor_text.len(), index));
+ row_text.push_str(&line.text);
+ block.invisible &= line.origin.state.render_mode == 3;
+ block.lines.push(index);
+ }
+ if !block.text.is_empty() {
+ if block.text.ends_with('-') {
+ block.text.pop();
+ } else {
+ block.text.push(' ');
+ }
+ }
+ block.text.push_str(row_text.trim_matches(paragraph_separator));
+ block.rect = union(block.rect, rect);
+ block.rows.push(row);
+ }
+ blocks
+ }
diff --cc crates/edit/src/text_regions/styled.rs
index 000000000,09baf1ac7..6d4fc529a
mode 000000,100644..100644
--- a/crates/edit/src/text_regions/styled.rs
+++ b/crates/edit/src/text_regions/styled.rs
@@@ -1,0 -1,787 +1,802 @@@
+ use super::grouping::{across, is_centred, row_rect};
+ use super::*;
+
+ // The draft is capped at 4 MiB; also bound the outline data prepared across all fallback faces.
+ // A glyph budget worth 64 full batches (15,360 glyphs with the production batch size).
+ // Lowering the internal batch size for tests lowers the budget by the same ratio.
+ const MAX_STYLED_FALLBACK_BATCHES: usize = 64;
+
+ struct FallbackGroup {
+ face: &'static CraftFont,
+ seen: std::collections::HashSet<char>,
+ glyphs: Vec<Type3Glyph>,
+ positions: Vec<usize>,
+ }
+
+ /// Shape in the source or an explicitly registered matching full face. Never use interface fonts.
+ fn shape_source(
+ doc: &Document,
+ fonts: &Dict,
+ name: &str,
+ text: &str,
+ ) -> Result<Option<(Vec<u8>, pdfcraft_fonts::source_shaping::ShapedRun, String)>, EditError> {
+ if !pdfcraft_fonts::source_shaping::required(text) {
+ return Ok(None);
+ }
+ let source =
+ fonts.get(name.as_bytes()).and_then(|f| doc.dict(f)).ok_or_else(|| EditError::Invalid("the shaped text has no font resource".into()))?;
+ let family = Metrics::from_dict(doc, &source).base_font;
+ let mut candidates = vec![source];
+ candidates.extend(
+ fonts
+ .iter()
+ .filter_map(|(_, f)| doc.dict(f))
+ .filter(|f| pdfcraft_fonts::embedding::face_key(&Metrics::from_dict(doc, f).base_font) == pdfcraft_fonts::embedding::face_key(&family)),
+ );
+ for font in candidates {
+ if let Some(bytes) = pdfcraft_fonts::pdf::embedded_sfnt(doc, &font)
+ && pdfcraft_fonts::embedding::covers(&bytes, text)
+ && let Ok(shaped) = pdfcraft_fonts::source_shaping::shape(&bytes, text)
+ {
+ return Ok(Some((bytes, shaped, family)));
+ }
+ }
+ Err(EditError::Invalid("complex text needs the complete source TrueType/OpenType face; load that font before editing".into()))
+ }
+
+ /// For each output row (a range of the draft's characters), whether it is exactly the source row
+ /// at the same position: the same characters, none of them inserted or changed by the edit.
+ fn untouched_rows(block: &TextBlock, draft: &str, rows: &[std::ops::Range<usize>]) -> Vec<bool> {
+ let old: Vec<char> = block.editor_text.chars().collect();
+ let new: Vec<char> = draft.chars().collect();
+ let prefix = old.iter().zip(&new).take_while(|(a, b)| a == b).count();
+ let suffix = old.iter().rev().zip(new.iter().rev()).take(old.len().min(new.len()).saturating_sub(prefix)).take_while(|(a, b)| a == b).count();
+ // The source character a draft character is, if the edit left it alone.
+ let origin = |i: usize| {
+ if i < prefix {
+ Some(i)
+ } else if i >= new.len().saturating_sub(suffix) {
+ (old.len() + i).checked_sub(new.len())
+ } else {
+ None
+ }
+ };
+ let mut source_rows = Vec::new();
+ let mut start = 0;
+ for (i, ch) in old.iter().enumerate() {
+ if *ch == '\n' {
+ source_rows.push(start..i);
+ start = i + 1;
+ }
+ }
+ source_rows.push(start..old.len());
+ // A line break inside a source run would pair editor rows with the wrong visual rows.
+ if source_rows.len() != block.rows.len() {
+ return vec![false; rows.len()];
+ }
+ rows.iter()
+ .enumerate()
+ .map(|(r, range)| {
+ source_rows.get(r).is_some_and(|source| {
+ !range.is_empty() && range.len() == source.len() && range.clone().zip(source.clone()).all(|(i, j)| origin(i) == Some(j))
+ })
+ })
+ .collect()
+ }
+
+ /// Rewrite visual rows while keeping the source style on each surviving character. Resource
+ /// names may differ between Unicode subsets of the same face; encoding searches those subsets.
+ pub(crate) fn rewrite_styled_block(
+ doc: &mut Document,
+ page: usize,
+ block: &TextBlock,
+ lines: &[TextLine],
+ text: Option<&str>,
+ style: &BlockStyle,
+ max_glyphs: usize,
+ ) -> Result<LineEdit, EditError> {
+ let first = block.lines.first().and_then(|i| lines.get(*i)).ok_or_else(|| EditError::Invalid("the paragraph has no source runs".into()))?;
+ let draft = match text {
+ Some(t) if t != block.text => t,
+ _ => &block.editor_text,
+ };
+ if draft.len() > 4_000_000 {
+ return Err(EditError::Invalid("the replacement text is too large".into()));
+ }
+ if draft == block.editor_text && *style == BlockStyle::default() {
+ return Ok(LineEdit { substituted: None });
+ }
+ let mut ranges: Vec<_> = style.ranges.iter().collect();
+ ranges.sort_by_key(|r| r.range.start);
+ if ranges.len() > 1024
+ || ranges.iter().any(|r| {
+ r.range.start >= r.range.end
+ || draft.get(r.range.clone()).is_none()
+ || [r.size, r.char_spacing, r.scale].iter().flatten().any(|n| !n.is_finite())
+ || r.size.is_some_and(|n| n <= 0.0 || n > 14400.0)
+ || r.color.is_some_and(|c| c.iter().any(|n| !n.is_finite() || !(0.0..=1.0).contains(n)))
+ })
+ || ranges.windows(2).any(|r| r[0].range.end > r[1].range.start)
+ {
+ return Err(EditError::Invalid("text style ranges must be disjoint UTF-8 boundaries with finite formatting (at most 1024 ranges)".into()));
+ }
+ let source_count = lines.len();
+ let mut styled_lines = lines.to_vec();
+ let mut styled_spans = Vec::new();
+ let mut underlines = HashMap::new();
+ let mut overrides = HashMap::new();
+ for (span, source) in block.edited_spans(draft) {
+ let mut edges = vec![span.start, span.end];
+ for r in &ranges {
+ for edge in [r.range.start, r.range.end] {
+ if span.contains(&edge) {
+ edges.push(edge);
+ }
+ }
+ }
+ edges.sort_unstable();
+ edges.dedup();
+ for bounds in edges.windows(2) {
+ let (Some(start), Some(end)) = (bounds.first().copied(), bounds.get(1).copied()) else { continue };
+ let mut index = source;
+ let selected = ranges.iter().find(|r| r.range.contains(&start)).copied();
+ if selected.is_some() || style.family.is_some() || style.bold.is_some() {
+ let default_range = RangeStyle {
+ range: start..end,
+ family: None,
+ resource: None,
+ size: None,
+ color: None,
+ underline: None,
+ char_spacing: None,
+ scale: None,
+ };
+ let r = selected.unwrap_or(&default_range);
+ let mut line = lines.get(source).unwrap_or(first).clone();
+ if let Some((family, bold, italic)) =
+ r.family.or(style.family).or_else(|| style.bold.map(|b| (source_family(&line.base_font), b, line.italic)))
+ {
+ let base = family.base_font(bold, italic);
+ line.font = format!("PCRange{}", base.replace('-', ""));
+ line.base_font = base.to_owned();
+ line.bold = bold;
+ line.italic = italic;
+ }
+ if let Some(resource) = &r.resource {
+ line.font = resource.clone();
+ }
+ if let Some(size) = r.size {
+ line.size = size;
+ }
+ if let Some(color) = r.color {
+ line.color = color;
+ line.origin.state.fill = vec![Op::new("rg", color.map(Object::Real).to_vec())];
+ }
+ if let Some(spacing) = r.char_spacing {
+ line.origin.state.char_spacing = spacing / line.origin.k.max(1e-6);
+ }
+ if let Some(scale) = r.scale {
+ line.origin.state.scale = (scale / 100.0).clamp(0.1, 10.0);
+ }
+ index = styled_lines.len();
+ styled_lines.push(line);
+ if let Some(r) = selected {
+ overrides.insert(index, r);
+ }
+ if let Some(underline) = r.underline {
+ underlines.insert(index, underline);
+ }
+ }
+ styled_spans.push((start..end, index));
+ }
+ }
+ let lines = styled_lines.as_slice();
+ let p = page_dict(doc, page)?;
+ let mut res = p.dict.get(b"Resources").and_then(|r| doc.resolve(r).as_dict().cloned()).unwrap_or_default();
+ let mut fonts = res.get(b"Font").and_then(|r| doc.resolve(r).as_dict().cloned()).unwrap_or_default();
+ for line in lines.iter().filter(|line| line.font.starts_with("PCRange")) {
+ let mut f = Dict::new();
+ f.set(b"Type".to_vec(), Object::name("Font"));
+ f.set(b"Subtype".to_vec(), Object::name("Type1"));
+ f.set(b"BaseFont".to_vec(), Object::name(&line.base_font));
+ f.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
+ fonts.set(line.font.as_bytes().to_vec(), Object::Dict(f));
+ }
+ let mut metrics = std::collections::BTreeMap::new();
+ for (name, object) in fonts.iter().take(256) {
+ if let Some(font) = doc.resolve(object).as_dict() {
+ metrics.insert(String::from_utf8_lossy(name).into_owned(), Metrics::from_dict(doc, font));
+ }
+ }
+ for index in &block.lines {
+ if let Some(line) = lines.get(*index)
+ && !metrics.contains_key(&line.font)
+ && let Some(font) = fonts.get(line.font.as_bytes()).and_then(|f| doc.resolve(f).as_dict().cloned())
+ {
+ metrics.insert(line.font.clone(), Metrics::from_dict(doc, &font));
+ }
+ }
+ if [style.size, style.line_spacing, style.char_spacing, style.scale, style.width].iter().flatten().any(|v| !v.is_finite())
+ || style.color.is_some_and(|c| c.iter().any(|v| !v.is_finite()))
+ {
+ return Err(EditError::Invalid("the paragraph's formatting must use finite numbers".into()));
+ }
+ let [dx, dy] = style.offset.unwrap_or([0.0, 0.0]);
+ if !dx.is_finite() || !dy.is_finite() || style.width.is_some_and(|w| !w.is_finite()) {
+ return Err(EditError::Invalid("the paragraph's position and width must be finite".into()));
+ }
+ // A visual row grows even when it contains several source/font runs. Multi-row
+ // paragraphs retain their container width; an explicit width always wins.
+ let natural = if block.invisible || block.rows.len() == 1 {
+ (p.crop(doc)[2] - 36.0 - (block.rect[0] + dx)).max(block.rect[2] - block.rect[0])
+ } else {
+ block.rect[2] - block.rect[0]
+ };
+ let width = style.width.unwrap_or(natural).clamp(1.0, 14_400.0);
+ // Each tuple is a character, its source style and an encodable resource name.
+ let mut chars = Vec::new();
+ let mut substituted = None;
+ let mut fallback_groups: Vec<FallbackGroup> = Vec::new();
+ let mut fallback_names: std::collections::BTreeMap<(String, bool, char), usize> = std::collections::BTreeMap::new();
+ let mut fallback_glyphs = 0_usize;
+ let per_font = max_glyphs.clamp(1, MAX_TYPE3_GLYPHS);
+ let fallback_budget = per_font.saturating_mul(MAX_STYLED_FALLBACK_BATCHES);
+ let mut full_faces: HashMap<String, String> = HashMap::new();
+ let mut programs: HashMap<String, Option<std::sync::Arc<Vec<u8>>>> = HashMap::new();
+ for (range, index) in styled_spans {
+ let source = lines.get(index).unwrap_or(first);
+ let start = range.start;
+ for (offset, ch) in draft.get(range).unwrap_or_default().char_indices() {
+ if ch == '\n' {
+ chars.push((ch, index, source.font.clone()));
+ continue;
+ }
+ // A carriage return breaks the row too. Before `\n` the pair is one break, so the
+ // CR stays a `\r` the rows skip. Either way it keeps its place among the draft's
+ // characters, which rows are counted in.
+ if ch == '\r' {
+ let crlf = start.checked_add(offset).and_then(|at| draft.get(at.saturating_add(1)..)).is_some_and(|rest| rest.starts_with('\n'));
+ chars.push((if crlf { '\r' } else { '\n' }, index, source.font.clone()));
+ continue;
+ }
+ let s = ch.to_string();
+ let name = if let Some(resource) = overrides.get(&index).and_then(|r| r.resource.as_ref()).or(style.resource.as_ref()) {
+ if !metrics.get(resource).is_some_and(|m| source_encodes(m, &s)) {
+ return Err(EditError::Invalid(format!("the selected font resource {resource} cannot show U+{:04X}", u32::from(ch))));
+ }
+ resource.clone()
+ } else if metrics.get(&source.font).is_some_and(|m| source_encodes(m, &s)) {
+ source.font.clone()
+ } else if let Some((name, _)) = metrics.iter().find(|(_, m)| {
+ pdfcraft_fonts::embedding::face_key(&m.base_font) == pdfcraft_fonts::embedding::face_key(&source.base_font) && source_encodes(m, &s)
+ }) {
+ name.clone()
+ } else if let Some(face) =
+ pdfcraft_fonts::embedding::matching_faces(&source.base_font).into_iter().find(|f| pdfcraft_fonts::embedding::covers(f.bytes, &s))
+ {
+ let key = face.name();
+ if let Some(name) = full_faces.get(&key) {
+ name.clone()
+ } else {
+ let name = pdfcraft_fonts::embedding::embed(doc, &mut fonts, face.bytes, face.family).map_err(EditError::Invalid)?;
+ let font = fonts
+ .get(name.as_bytes())
+ .and_then(|f| doc.dict(f))
+ .ok_or_else(|| EditError::Invalid("the full source font could not be loaded".into()))?;
+ metrics.insert(name.clone(), Metrics::from_dict(doc, &font));
+ full_faces.insert(key, name.clone());
+ name
+ }
+ } else if let Some(bytes) = programs
+ .entry(source.font.clone())
+ .or_insert_with(|| source_program(doc, &fonts, &source.font).map(std::sync::Arc::new))
+ .clone()
+ .filter(|bytes| pdfcraft_fonts::embedding::covers(bytes, &s))
+ {
+ // The document's own complete program of this font has the glyph: draw it with
+ // that face rather than another family's fallback.
+ let key = format!("source {}", source.font);
+ if let Some(name) = full_faces.get(&key) {
+ name.clone()
+ } else {
+ let family = pdfcraft_fonts::embedding::names(&bytes).map_or_else(|_| source.base_font.clone(), |(family, _)| family);
+ let name = pdfcraft_fonts::embedding::embed(doc, &mut fonts, &bytes, &family).map_err(EditError::Invalid)?;
+ let font = fonts
+ .get(name.as_bytes())
+ .and_then(|f| doc.dict(f))
+ .ok_or_else(|| EditError::Invalid("the source font could not be loaded".into()))?;
+ metrics.insert(name.clone(), Metrics::from_dict(doc, &font));
+ full_faces.insert(key, name.clone());
+ name
+ }
+ } else {
+ let family = source_family(&source.base_font);
+ if needs_type3(&s) {
+ let key = (source.base_font.clone(), source.bold, ch);
+ let group_index = if let Some(index) = fallback_names.get(&key) {
+ *index
+ } else {
+ // Keep the old per-character face choice: a serif Japanese character
+ // and a Cyrillic character may need different faces even in one style.
+ // Hebrew uses the separate RTL path before reaching this writer.
+ let (faces, _) = type3_faces(&s, family, source.bold)?;
+ let face =
+ fallback_face(&faces, &[ch], |face, ch| japanese_glyph_from(face, ch).is_ok()).ok_or_else(|| no_fallback_font(&s))?;
+ let index = fallback_groups.iter().position(|group| std::ptr::eq(group.face, face)).unwrap_or_else(|| {
+ let index = fallback_groups.len();
+ fallback_groups.push(FallbackGroup { face, seen: Default::default(), glyphs: Vec::new(), positions: Vec::new() });
+ index
+ });
+ fallback_names.insert(key, index);
+ index
+ };
+ let group = fallback_groups.get_mut(group_index).ok_or_else(|| EditError::Invalid("the fallback face is missing".into()))?;
+ if group.seen.insert(ch) {
+ if fallback_glyphs >= fallback_budget {
+ return Err(EditError::Invalid(format!(
+ "the replacement needs more than {fallback_budget} fallback glyphs; edit a smaller paragraph or load a complete font"
+ )));
+ }
+ let (path, width) = type3_glyph(group.face, ch)?.ok_or_else(|| no_glyph_for(group.face, ch))?;
+ let code = u8::try_from((group.glyphs.len() % per_font).saturating_add(1))
+ .map_err(|_| EditError::Invalid("replacement text has too many unique characters".into()))?;
+ group.glyphs.push(Type3Glyph { code, ch, path, width });
+ fallback_glyphs = fallback_glyphs.saturating_add(1);
+ }
+ group.positions.push(chars.len());
+ // Filled from the prepared font/code map before measuring or drawing.
+ String::new()
+ } else {
+ let base = family.base_font(source.bold, source.italic);
+ let name = format!("PCEd{}", base.replace('-', ""));
+ let mut f = Dict::new();
+ f.set(b"Type".to_vec(), Object::name("Font"));
+ f.set(b"Subtype".to_vec(), Object::name("Type1"));
+ f.set(b"BaseFont".to_vec(), Object::name(base));
+ f.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
+ metrics.entry(name.clone()).or_insert_with(|| Metrics::from_dict(doc, &f));
+ fonts.set(name.clone().into_bytes(), Object::Dict(f));
+ substituted = Some(base.to_string());
+ name
+ }
+ };
+ chars.push((ch, index, name));
+ }
+ }
+ // All fallback outlines have now succeeded. Batch by actual face, preserving source
+ // style indices; the existing writer then coalesces adjacent equal-font/style characters.
+ for group in fallback_groups {
+ let fallback = write_type3_glyphs(doc, &mut fonts, group.face, false, group.glyphs, per_font);
+ for name in &fallback.names {
+ let font = fonts
+ .get(name.as_bytes())
+ .and_then(|f| doc.dict(f))
+ .ok_or_else(|| EditError::Invalid("the fallback font could not be loaded".into()))?;
+ metrics.insert(name.clone(), Metrics::from_dict(doc, &font));
+ }
+ for position in group.positions {
+ let item = chars.get_mut(position).ok_or_else(|| EditError::Invalid("the fallback character is missing".into()))?;
+ let (font, _) = fallback.codes.get(&item.0).ok_or_else(|| EditError::Invalid("the fallback glyph is missing".into()))?;
+ item.2 = fallback.names.get(*font).cloned().ok_or_else(|| EditError::Invalid("the fallback font is missing".into()))?;
+ }
+ substituted = Some(fallback.family.to_owned());
+ }
+ let size_of = |source: &TextLine, index: usize| {
+ overrides.get(&index).and_then(|r| r.size).or(style.size).unwrap_or(source.size).max(0.1) / source.origin.k.max(1e-6)
+ };
+ // A source run may carry TJ kerning/justification that is absent from its text state.
+ // Keep its measured advance when rebuilding the run instead of making it wrap on entry.
+ // Each font's space width, worked out once: when a font can't show a space, finding one
+ // reads every font on the page, and doing that for every character of a paragraph made each
+ // keystroke in a long paragraph take half a second (#2616).
+ // Only for the fonts the paragraph uses, when first asked: working out every page font's width
+ // up front would scan the page once per font for a short edit on a page of many fonts.
+ let spaces: std::cell::RefCell<HashMap<String, f64>> = std::cell::RefCell::new(HashMap::new());
+ let space_of = |name: &str, m: &Metrics| {
+ if let Some(w) = spaces.borrow().get(name) {
+ return *w;
+ }
+ let w = source_space(doc, &fonts, m);
+ spaces.borrow_mut().insert(name.to_owned(), w);
+ w
+ };
+ let mut calibration = HashMap::new();
+ for (index, source) in lines.iter().enumerate() {
+ if let Some(m) = metrics.get(&source.font) {
+ let nominal = source_width(
+ m,
+ &source.text,
+ source.origin.state.font.as_ref().map_or(1.0, |(_, s)| *s),
+ space_of(&source.font, m),
+ source.origin.state.char_spacing,
+ source.origin.state.word_spacing,
+ ) * source.origin.state.scale
+ * across(source);
+ let changed_face = style.resource.is_some() || overrides.get(&index).is_some_and(|r| r.family.is_some() || r.resource.is_some());
+ let factor = if nominal > 0.0 && !changed_face { ((source.rect[2] - source.rect[0]) / nominal).clamp(0.5, 2.0) } else { 1.0 };
+ calibration.insert(index, factor);
+ }
+ }
+ let advance = |item: &(char, usize, String)| -> f64 {
+ let source = lines.get(item.1).unwrap_or(first);
+ let Some(m) = metrics.get(&item.2) else { return 0.0 };
+ source_width(
+ m,
+ &item.0.to_string(),
+ size_of(source, item.1),
+ space_of(&item.2, m),
+ overrides
+ .get(&item.1)
+ .and_then(|r| r.char_spacing)
+ .or(style.char_spacing)
+ .map_or(source.origin.state.char_spacing, |c| c / source.origin.k.max(1e-6)),
+ source.origin.state.word_spacing,
+ ) * overrides.get(&item.1).and_then(|r| r.scale).or(style.scale).map_or(source.origin.state.scale, |s| (s / 100.0).clamp(0.1, 10.0))
+ * across(source)
+ * calibration.get(&item.1).copied().unwrap_or(1.0)
+ };
+ let measure = |items: &[(char, usize, String)]| -> Result<f64, EditError> {
+ let mut width = 0.0;
+ let mut at = 0;
+ while let Some(item) = items.get(at) {
+ let mut end = at + 1;
+ while items.get(end).is_some_and(|v| v.1 == item.1 && v.2 == item.2) {
+ end += 1;
+ }
+ let segment = items.get(at..end).unwrap_or_default();
+ let string: String = segment.iter().map(|v| v.0).collect();
+ if let Some((_, shaped, _)) = shape_source(doc, &fonts, &item.2, &string)? {
+ let source = lines.get(item.1).unwrap_or(first);
+ let scale =
+ overrides.get(&item.1).and_then(|r| r.scale).or(style.scale).map_or(source.origin.state.scale, |s| (s / 100.0).clamp(0.1, 10.0));
+ let spacing = overrides
+ .get(&item.1)
+ .and_then(|r| r.char_spacing)
+ .or(style.char_spacing)
+ .map_or(source.origin.state.char_spacing, |s| s / source.origin.k.max(1e-6));
+ width += (shaped.advance * size_of(source, item.1)
+ + spacing * string.chars().count() as f64
+ + source.origin.state.word_spacing * string.matches(' ').count() as f64)
+ * scale
+ * source.origin.k;
+ } else {
+ width += segment.iter().map(&advance).sum::<f64>();
+ }
+ at = end;
+ }
+ Ok(width)
+ };
+ let mut rows: Vec<Vec<(char, usize, String)>> = Vec::new();
+ // Each row's characters, as indexes into the draft's characters (`chars` holds all of them).
+ let mut row_ranges = Vec::new();
++ // Each row's line in the draft (its `\n`-separated part), which [`BlockStyle::aligns`] counts.
++ let mut row_lines: Vec<usize> = Vec::new();
++ let mut draft_line = 0usize;
+ let mut row_start = 0;
+ let mut row = Vec::new();
+ let mut row_width = 0.0;
+ // Wrap at word boundaries, retaining explicit source row breaks and whitespace.
+ let mut at = 0;
+ while at < chars.len() {
+ let Some(item) = chars.get(at) else { break };
+ // The CR of a CRLF: the `\n` after it breaks the row.
+ if item.0 == '\r' {
+ at += 1;
+ continue;
+ }
+ if item.0 == '\n' {
+ row_ranges.push(row_start..row_start + row.len());
++ row_lines.push(draft_line);
++ draft_line = draft_line.saturating_add(1);
+ rows.push(std::mem::take(&mut row));
+ row_width = 0.0;
+ at += 1;
+ row_start = at;
+ continue;
+ }
+ let mut end = at + 1;
+ if !item.0.is_whitespace() {
+ // A word ends at a space, or where Chinese or Japanese text may break between characters.
+ while let (Some(before), Some(c)) = (chars.get(end - 1), chars.get(end))
+ && !c.0.is_whitespace()
+ && !crate::linebreak::between(before.0, c.0)
+ {
+ end += 1;
+ }
+ }
+ let word = chars.get(at..end).unwrap_or_default();
+ let w = measure(word)?;
+ if !row.is_empty() && !item.0.is_whitespace() && row_width + w > width + 0.5 {
+ while row.last().is_some_and(|c: &(char, usize, String)| c.0.is_whitespace()) {
+ row.pop();
+ }
+ row_ranges.push(row_start..row_start + row.len());
++ row_lines.push(draft_line);
+ rows.push(std::mem::take(&mut row));
+ row_width = 0.0;
+ row_start = at;
+ }
+ row.extend_from_slice(word);
+ row_width += w;
+ at = end;
+ }
+ if !row.is_empty() {
+ row_ranges.push(row_start..row_start + row.len());
++ row_lines.push(draft_line);
+ rows.push(row);
+ }
+ let streams = content_streams(doc, &p.dict)?;
+ let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
+ let ops = pieces.parse().ops;
+ // A row the edit doesn't reach keeps its source operators, so its kerning, TJ word gaps and
- // glyph widths stay exactly as they were instead of being rebuilt from the text state.
- let plain = BlockStyle { ranges: Vec::new(), ..style.clone() } == BlockStyle::default();
++ // glyph widths stay exactly as they were instead of being rebuilt from the text state. A row
++ // aligned on its own is reached; the rows around it are not.
++ let plain = BlockStyle { ranges: Vec::new(), aligns: Vec::new(), ..style.clone() } == BlockStyle::default();
+ let mut kept = if plain {
- untouched_rows(block, draft, &row_ranges).into_iter().zip(&rows).map(|(same, row)| same && row.iter().all(|c| c.1 < source_count)).collect()
++ untouched_rows(block, draft, &row_ranges)
++ .into_iter()
++ .zip(&rows)
++ .zip(&row_lines)
++ .map(|((same, row), line)| same && row.iter().all(|c| c.1 < source_count) && style.aligns.get(*line).copied().flatten().is_none())
++ .collect()
+ } else {
+ vec![false; rows.len()]
+ };
+ let kept_lines: std::collections::HashSet<usize> =
+ kept.iter().enumerate().filter(|(_, k)| **k).filter_map(|(r, _)| block.rows.get(r)).flatten().copied().collect();
+ let rewritten: Vec<&TextLine> = block.lines.iter().filter(|i| !kept_lines.contains(i)).filter_map(|i| lines.get(*i)).collect();
+ // The rewrite goes where the last rewritten row was drawn, after any backgrounds painted
+ // between the rows. A dropped `'` or `"` also moved to the next line, which a kept row relies on.
+ let lead =
+ rewritten.last().copied().filter(|_| !rewritten.iter().flat_map(|l| &l.ops).any(|i| ops.get(*i).is_some_and(|op| op.is("'") || op.is("\""))));
+ let (members, lead) = match lead {
+ Some(lead) if !kept_lines.is_empty() => (rewritten, lead),
+ _ => {
+ kept.iter_mut().for_each(|k| *k = false);
+ let all: Vec<&TextLine> = block.lines.iter().filter_map(|i| lines.get(*i)).collect();
+ let last = all.last().copied().unwrap_or(first);
+ (all, last)
+ }
+ };
+ let o = &lead.origin;
+ let mut drop = coincident_ops(lines, &members);
+ drop.extend(members.iter().flat_map(|l| l.ops.iter().copied()));
+ let start = lead.ops.first().copied().unwrap_or(o.bt_op);
+ let split = ops
+ .get(o.bt_op..start)
+ .unwrap_or_default()
+ .iter()
+ .enumerate()
+ .any(|(i, op)| matches!(op.op.as_slice(), b"Tj" | b"TJ" | b"'" | b"\"") && !drop.contains(&(o.bt_op + i)));
+ // What is in force where the rewrite is drawn, and what the text after it expects.
+ let after = if split { &o.state } else { &o.bt_state };
+ for (row, _) in rows.iter().zip(&kept).filter(|(_, k)| !**k) {
+ let text: String = row.iter().map(|v| v.0).collect();
+ if pdfcraft_fonts::source_shaping::required(&text) && row.first().is_some_and(|first| row.iter().any(|v| v.1 != first.1 || v.2 != first.2)) {
+ return Err(EditError::Invalid(
+ "contextual/bidi text across font or style boundaries needs a uniform full-face row; mixed contextual runs are not yet supported"
+ .into(),
+ ));
+ }
+ }
+ let measured: Vec<_> = rows.iter().map(|r| measure(r)).collect::<Result<_, _>>()?;
+ let mut shaped_runs = HashMap::new();
+ let mut segment_advances = HashMap::new();
+ for (row_index, row) in rows.iter().enumerate().filter(|(r, _)| !kept.get(*r).copied().unwrap_or(false)) {
+ let mut at = 0;
+ while let Some(item) = row.get(at) {
+ let mut end = at + 1;
+ while row.get(end).is_some_and(|v| v.1 == item.1 && v.2 == item.2) {
+ end += 1;
+ }
+ segment_advances.insert((row_index, at), row.get(at..end).unwrap_or_default().iter().map(&advance).sum::<f64>());
+ let string: String = row.get(at..end).unwrap_or_default().iter().map(|v| v.0).collect();
+ if let Some((bytes, shaped, family)) = shape_source(doc, &fonts, &item.2, &string)? {
+ shaped_runs.insert((row_index, at), (bytes, shaped, family));
+ }
+ at = end;
+ }
+ }
+ let mut glyph_resources = HashMap::new();
+ for (key, (bytes, shaped, family)) in &shaped_runs {
+ let mappings: Vec<_> = shaped.glyphs.iter().map(|g| (g.text.clone(), g.id)).collect();
+ let resource = pdfcraft_fonts::embedding::embed_mapping(doc, &mut fonts, bytes, family, &mappings).map_err(EditError::Invalid)?;
+ glyph_resources.insert(*key, resource);
+ }
+ let n = pdfcraft_content::num;
+ let mut block_ops = vec![Op::new("q", vec![])];
+ block_ops.extend(reveal_ops(block, lines, style, o.ctm)?);
+ let back = Matrix([o.ctm[0], o.ctm[1], o.ctm[2], o.ctm[3], 0.0, 0.0])
+ .invert()
+ .ok_or_else(|| EditError::Invalid("the paragraph is drawn in a space it cannot be edited in".into()))?;
+ let (tx, ty) = back.apply(dx, dy);
+ block_ops.push(Op::new("cm", vec![n(1.0), n(0.0), n(0.0), n(1.0), n(tx), n(ty)]));
+ let crop = p.crop(doc);
+ let centered = is_centred(block, lines, (crop[0] + crop[2]) / 2.0, first.size);
+ let source_leading = block
+ .rows
+ .windows(2)
+ .filter_map(|rows| {
+ let a = rows[0].first().and_then(|i| lines.get(*i))?;
+ let b = rows[1].first().and_then(|i| lines.get(*i))?;
+ Some((a.origin.baseline - b.origin.baseline).abs())
+ })
+ .rfind(|v| *v > 0.0)
+ .unwrap_or(first.size * 1.5);
+ let mut baseline = first.origin.baseline;
+ for (row_index, row) in rows.iter().enumerate() {
+ let anchor = block.rows.get(row_index).and_then(|r| r.first()).and_then(|i| lines.get(*i));
+ if style.line_spacing.is_none()
+ && style.size.is_none()
+ && let Some(anchor) = anchor
+ {
+ baseline = anchor.origin.baseline;
+ }
+ let anchor = anchor.unwrap_or(first);
+ if kept.get(row_index).copied().unwrap_or(false) {
+ // Kept rows only occur without spacing or size changes, so this is the step below.
+ baseline -= source_leading;
+ continue;
+ }
+ let w = measured.get(row_index).copied().unwrap_or(0.0);
- let align = style.align.unwrap_or(if centered { crate::added::Align::Center } else { crate::added::Align::Left });
++ // The row's own alignment, or the paragraph's.
++ let asked = row_lines.get(row_index).and_then(|l| style.aligns.get(*l)).copied().flatten().or(style.align);
++ let align = asked.unwrap_or(if centered { crate::added::Align::Center } else { crate::added::Align::Left });
+ let original_rect = block.rows.get(row_index).and_then(|row| row_rect(row, lines)).unwrap_or(block.rect);
- let left = if style.width.is_none() && style.align.is_none() { original_rect[0] } else { block.rect[0] };
- let available = if style.width.is_none() && style.align.is_none() { original_rect[2] - original_rect[0] } else { width };
++ let left = if style.width.is_none() && asked.is_none() { original_rect[0] } else { block.rect[0] };
++ let available = if style.width.is_none() && asked.is_none() { original_rect[2] - original_rect[0] } else { width };
+ let mut x = left
+ + match align {
+ crate::added::Align::Center => (available - w) / 2.0,
+ crate::added::Align::Right => available - w,
+ _ => 0.0,
+ };
+ let mut pos = 0;
+ while pos < row.len() {
+ let Some(item) = row.get(pos) else { break };
+ let source = lines.get(item.1).unwrap_or(first);
+ let mut end = pos + 1;
+ while row.get(end).is_some_and(|other| other.1 == item.1 && other.2 == item.2) {
+ end += 1;
+ }
+ let segment = row.get(pos..end).unwrap_or_default();
+ let string: String = segment.iter().map(|c| c.0).collect();
+ let m = metrics.get(&item.2).ok_or_else(|| EditError::Invalid("the paragraph font is missing".into()))?;
+ let mut state = source.origin.state.clone();
+ state.font = Some((item.2.clone(), size_of(source, item.1)));
+ if let Some(c) = overrides.get(&item.1).and_then(|r| r.char_spacing).or(style.char_spacing) {
+ state.char_spacing = c / source.origin.k.max(1e-6);
+ }
+ if let Some(s) = overrides.get(&item.1).and_then(|r| r.scale).or(style.scale) {
+ state.scale = (s / 100.0).clamp(0.1, 10.0);
+ }
+ if !shaped_runs.contains_key(&(row_index, pos)) {
+ state.scale *= calibration.get(&item.1).copied().unwrap_or(1.0);
+ }
+ if let Some([r, g, b]) = overrides.get(&item.1).and_then(|r| r.color).or(style.color) {
+ state.fill = vec![Op::new("rg", vec![n(r), n(g), n(b)])];
+ }
+ let inverse = Matrix(o.ctm).invert().ok_or_else(|| EditError::Invalid("the paragraph has a singular transform".into()))?;
+ let mut tm = Matrix(source.origin.tm).then(&Matrix(source.origin.ctm)).then(&inverse).0;
+ let (ax, ay) = back.apply(x - source.origin.x, baseline - source.origin.baseline);
+ tm[4] += ax;
+ tm[5] += ay;
+ let mut segment_width = segment_advances.get(&(row_index, pos)).copied().unwrap_or(0.0);
+ // Each run in its own graphics state, restating what its source set inside its text
+ // object (`gs`, stroke, line width, `Tr`; #3508/#3509) from the state the rewrite is
+ // drawn in: a `gs` has no inverse, so one run's ExtGState would stay for the next.
+ block_ops.push(Op::new("q", vec![]));
+ block_ops.extend(state.paint_ops(after));
+ if let Some((_, shaped, _)) = shaped_runs.get(&(row_index, pos)) {
+ let resource = glyph_resources.get(&(row_index, pos)).ok_or_else(|| EditError::Invalid("shaped font is missing".into()))?;
+ let mut properties = Dict::new();
+ properties.set(b"ActualText".to_vec(), Object::String(PdfString::text(&string)));
+ block_ops.push(Op::new("BDC", vec![Object::name("Span"), Object::Dict(properties)]));
+ state.font = Some((resource.clone(), size_of(source, item.1)));
+ // One text object for the run: each glyph is placed where shaping put it by a TJ
+ // adjustment from where the glyph before it ends (its advance in the embedded
+ // font's widths), and raised by the text rise for a mark set above or below
+ // (ISO 32000-1 §9.4.3, §9.3.7). Font-program codes are separate from Unicode;
+ // ToUnicode and ActualText keep the logical text.
+ let size = size_of(source, item.1);
+ let per_unit = 1000.0 / size;
+ if !per_unit.is_finite() {
+ return Err(EditError::Invalid("the shaped text has no size".into()));
+ }
+ let shown = fonts
+ .get(resource.as_bytes())
+ .and_then(|f| doc.resolve(f).as_dict().cloned())
+ .map(|d| Metrics::from_dict(doc, &d))
+ .ok_or_else(|| EditError::Invalid("shaped font is missing".into()))?;
+ // Spacing is part of each glyph's position, so the run itself has none.
+ let (char_spacing, word_spacing, rise) = (state.char_spacing, state.word_spacing, state.rise);
+ state.char_spacing = 0.0;
+ state.word_spacing = 0.0;
+ block_ops.push(Op::new("BT", vec![]));
+ block_ops.extend(state.ops());
+ block_ops.push(Op::new("Tm", tm.iter().map(|v| n(*v)).collect()));
+ // `pen`: where the next glyph would start, in thousandths of the font size.
+ let (mut pen, mut extra, mut raised) = (0.0, 0.0, rise);
+ let mut shown_glyphs: Vec<Object> = Vec::new();
+ for (i, glyph) in shaped.glyphs.iter().enumerate() {
+ let target = (glyph.position[0] * size + extra) * per_unit;
+ let glyph_rise = rise + glyph.position[1] * size;
+ if (glyph_rise - raised).abs() > 1e-9 || shown_glyphs.len() >= 4096 {
+ if !shown_glyphs.is_empty() {
+ block_ops.push(Op::new("TJ", vec![Object::Array(std::mem::take(&mut shown_glyphs))]));
+ }
+ if (glyph_rise - raised).abs() > 1e-9 {
+ block_ops.push(Op::new("Ts", vec![n(glyph_rise)]));
+ raised = glyph_rise;
+ }
+ }
+ if (target - pen).abs() > 1e-6 {
+ shown_glyphs.push(n(pen - target));
+ }
+ let code = u16::try_from(i + 1).map_err(|_| EditError::Invalid("shaped glyph limit".into()))?;
+ shown_glyphs.push(Object::String(PdfString::literal(code.to_be_bytes().to_vec())));
+ pen = target + shown.width(u32::from(code)) * 1000.0;
+ extra += char_spacing * glyph.text.chars().count() as f64 + word_spacing * glyph.text.matches(' ').count() as f64;
+ }
+ if !shown_glyphs.is_empty() {
+ block_ops.push(Op::new("TJ", vec![Object::Array(shown_glyphs)]));
+ }
+ if (raised - rise).abs() > 1e-9 {
+ block_ops.push(Op::new("Ts", vec![n(rise)]));
+ }
+ block_ops.push(Op::new("ET", vec![]));
+ (state.char_spacing, state.word_spacing) = (char_spacing, word_spacing);
+ block_ops.push(Op::new("EMC", vec![]));
+ segment_width = (shaped.advance * size + extra) * state.scale * source.origin.k;
+ } else {
+ block_ops.push(Op::new("BT", vec![]));
+ block_ops.extend(state.ops());
+ block_ops.push(Op::new("Tm", tm.iter().map(|v| n(*v)).collect()));
+ block_ops.extend(source_show(
+ m,
+ &string,
+ size_of(source, item.1),
+ spaces.borrow().get(&item.2).copied().unwrap_or_else(|| source_space(doc, &fonts, m)),
+ state.char_spacing,
+ state.word_spacing,
+ )?);
+ block_ops.push(Op::new("ET", vec![]));
+ }
+ if underlines.get(&item.1).copied().or(style.underline) == Some(true) {
+ let [r, g, b] = overrides.get(&item.1).and_then(|r| r.color).or(style.color).unwrap_or(source.color);
+ let underline_size = size_of(source, item.1) * source.origin.k;
+ let (x0, y0) = back.apply(x - o.ctm[4], baseline - o.ctm[5] - underline_size * 0.12);
+ let (x1, y1) = back.apply(x + segment_width - o.ctm[4], baseline - o.ctm[5] - underline_size * 0.12);
+ block_ops.push(Op::new("RG", vec![n(r), n(g), n(b)]));
+ block_ops.push(Op::new("w", vec![n(underline_size * 0.06 / o.ctm[2].hypot(o.ctm[3]).max(1e-6))]));
+ block_ops.push(Op::new("m", vec![n(x0), n(y0)]));
+ block_ops.push(Op::new("l", vec![n(x1), n(y1)]));
+ block_ops.push(Op::new("S", vec![]));
+ }
+ block_ops.push(Op::new("Q", vec![]));
+ x += segment_width;
+ pos = end;
+ }
+ baseline -= if style.line_spacing.is_none() && style.size.is_none() {
+ source_leading
+ } else {
+ style.line_spacing.unwrap_or(1.5).clamp(0.5, 5.0) * style.size.unwrap_or(anchor.size)
+ };
+ }
+ block_ops.push(Op::new("Q", vec![]));
+ block_ops.extend(after.ops());
+ if split {
+ block_ops.insert(0, Op::new("ET", vec![]));
+ block_ops.push(Op::new("BT", vec![]));
+ block_ops.push(Op::new("Tm", o.tlm.iter().map(|v| n(*v)).collect()));
+ }
+ let at = if split { start } else { o.bt_op };
+ let data = splice(&pieces, &ops, |i| (if i == at { std::mem::take(&mut block_ops) } else { Vec::new() }, !drop.contains(&i)));
+ let contents = rewritten_contents(doc, &streams, data);
+ res.set(b"Font".to_vec(), Object::Dict(fonts));
+ doc.update_dict(p.obj, |d| {
+ d.set(b"Contents".to_vec(), contents);
+ d.set(b"Resources".to_vec(), Object::Dict(res));
+ })?;
+ Ok(LineEdit { substituted })
+ }
diff --cc crates/ui-egui/src/editing.rs
index af6e01eb8,ba2d3cbf9..fc8d637a7
--- a/crates/ui-egui/src/editing.rs
+++ b/crates/ui-egui/src/editing.rs
@@@ -1376,425 -746,8 +883,28 @@@ fn bookmark_at<'a>(items: &'a [pdfcraft
if rest.is_empty() { Some(item) } else { bookmark_at(&item.children, rest) }
}
+/// Whether the page text box `id`, showing `text`, has typing its own Redo would put back: the
+/// test egui makes when it handles the key.
+fn has_typing_to_redo(ctx: &egui::Context, id: egui::Id, text: &str) -> bool {
+ egui::TextEdit::load_state(ctx, id)
+ .is_some_and(|state| state.cursor.char_range().is_some_and(|range| state.undoer().has_redo(&(range, text.to_owned()))))
+}
+
+/// The box's own Undo (or Redo), as the key does it: the box's text one step back (or forward) in
+/// its typing, with the box's history and cursor moved along. None when there is no such step.
+fn typing_step(ctx: &egui::Context, id: egui::Id, text: &str, undo: bool) -> Option<String> {
+ let mut state = egui::TextEdit::load_state(ctx, id)?;
+ let mut undoer = state.undoer();
+ let current = (state.cursor.char_range()?, text.to_owned());
+ let (range, stepped) = if undo { undoer.undo(&current) } else { undoer.redo(&current) }?.clone();
+ state.set_undoer(undoer);
+ state.cursor.set_char_range(Some(range));
+ egui::TextEdit::store_state(ctx, id, state);
+ Some(stepped)
+}
+
#[cfg(test)]
- mod tests {
- use super::{SaveTarget, is_mail_temp_copy, save_dialog_folder, write_atomically, write_atomically_syncing, write_atomically_with};
-
- #[test]
- fn save_dialogs_open_in_the_documents_folder() {
- use std::path::PathBuf;
- assert_eq!(save_dialog_folder(Some("/home/a/plans/f.pdf")), Some(PathBuf::from("/home/a/plans")));
- // A new document has no folder yet; a bare name has an empty parent; the root has none.
- assert_eq!(save_dialog_folder(None), None);
- assert_eq!(save_dialog_folder(Some("f.pdf")), None);
- assert_eq!(save_dialog_folder(Some("/")), None);
- // An email attachment's temporary copy is not offered.
- assert_eq!(save_dialog_folder(Some("C:\\Users\\a\\AppData\\Local\\Microsoft\\Windows\\INetCache\\Content.Outlook\\AB12\\f.pdf")), None);
- assert_eq!(save_dialog_folder(Some("/Users/a/Library/Containers/com.apple.mail/Data/Library/Mail Downloads/UUID/f.pdf")), None);
- }
-
- /// The Windows rules for `Path::parent` (UNC share roots included) only apply on Windows.
- #[cfg(windows)]
- #[test]
- fn save_dialog_folder_handles_unc_paths() {
- use std::path::PathBuf;
- assert_eq!(save_dialog_folder(Some(r"\\nas\projets\2026\f.pdf")), Some(PathBuf::from(r"\\nas\projets\2026")));
- assert_eq!(save_dialog_folder(Some(r"\\nas\projets\f.pdf")), Some(PathBuf::from(r"\\nas\projets\")));
- assert_eq!(save_dialog_folder(Some(r"\\nas\projets")), None);
- assert_eq!(save_dialog_folder(Some(r"C:\Users\a\f.pdf")), Some(PathBuf::from(r"C:\Users\a")));
- }
- use pdfcraft_platform::staging::{STAGING_ATTEMPTS, staging_suffixes};
- use std::path::{Path, PathBuf};
-
- /// A fresh, empty folder for one staging test.
- fn staging_dir(test: &str) -> PathBuf {
- let dir = std::env::temp_dir().join(format!("pdfcraft-ui-staging-{}-{test}", std::process::id()));
- let _ = std::fs::remove_dir_all(&dir);
- std::fs::create_dir_all(&dir).unwrap();
- dir
- }
-
- fn staged(dir: &Path, suffix: u64) -> PathBuf {
- dir.join(format!(".out.pdf.pdfcraft-{suffix:016x}.tmp"))
- }
-
- fn read(p: &Path) -> String {
- std::fs::read_to_string(p).unwrap()
- }
-
- /// A symbolic link to a file, where the system allows one (Windows needs Developer Mode or an
- /// administrator for it).
- fn file_symlink(target: &Path, link: &Path) -> std::io::Result<()> {
- #[cfg(unix)]
- {
- std::os::unix::fs::symlink(target, link)
- }
- #[cfg(windows)]
- {
- std::os::windows::fs::symlink_file(target, link)
- }
- #[cfg(not(any(unix, windows)))]
- {
- Err(std::io::Error::other(format!("no symbolic links here: {} {}", target.display(), link.display())))
- }
- }
-
- #[test]
- fn saving_never_writes_through_a_file_planted_at_the_staging_name() {
- let dir = staging_dir("planted");
- let outside = dir.join("outside.txt");
- std::fs::write(&outside, "PRECIOUS").unwrap();
- let target = dir.join("out.pdf");
- let path = target.to_string_lossy().into_owned();
- // A hard link needs no privileges on any system, and writing to it writes to `outside`.
- std::fs::hard_link(&outside, staged(&dir, 1)).unwrap();
- std::fs::write(staged(&dir, 2), "PLANTED").unwrap();
- write_atomically_with(&path, b"NEW", [1, 2, 3]).unwrap();
- assert_eq!(read(&target), "NEW");
- assert_eq!(read(&outside), "PRECIOUS");
- assert_eq!(read(&staged(&dir, 1)), "PRECIOUS");
- assert_eq!(read(&staged(&dir, 2)), "PLANTED");
- assert!(!staged(&dir, 3).exists(), "the staging file was renamed into place");
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn saving_never_writes_through_a_symbolic_link_at_the_staging_name() {
- let dir = staging_dir("symlink");
- let outside = dir.join("outside.txt");
- std::fs::write(&outside, "PRECIOUS").unwrap();
- let target = dir.join("out.pdf");
- if let Err(e) = file_symlink(&outside, &staged(&dir, 1)) {
- eprintln!("symbolic links not checked: {e}");
- return;
- }
- write_atomically_with(&target.to_string_lossy(), b"NEW", [1, 2]).unwrap();
- assert_eq!(read(&target), "NEW");
- assert_eq!(read(&outside), "PRECIOUS");
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn saving_never_creates_a_file_through_a_dangling_link_at_the_staging_name() {
- let dir = staging_dir("dangling");
- let unborn = dir.join("created-through-a-link.txt");
- let target = dir.join("out.pdf");
- if let Err(e) = file_symlink(&unborn, &staged(&dir, 1)) {
- eprintln!("symbolic links not checked: {e}");
- return;
- }
- write_atomically_with(&target.to_string_lossy(), b"NEW", [1, 2]).unwrap();
- assert_eq!(read(&target), "NEW");
- assert!(!unborn.exists(), "nothing was created through the dangling link");
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn a_folder_at_the_staging_name_is_left_alone() {
- let dir = staging_dir("folder");
- std::fs::create_dir(staged(&dir, 1)).unwrap();
- std::fs::write(staged(&dir, 1).join("inside.txt"), "PLANTED").unwrap();
- let target = dir.join("out.pdf");
- write_atomically_with(&target.to_string_lossy(), b"NEW", [1, 2]).unwrap();
- assert_eq!(read(&target), "NEW");
- assert_eq!(read(&staged(&dir, 1).join("inside.txt")), "PLANTED");
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn saving_gives_up_rather_than_reuse_a_taken_name() {
- let dir = staging_dir("taken");
- let target = dir.join("out.pdf");
- std::fs::write(&target, "OLD").unwrap();
- for s in 1..=STAGING_ATTEMPTS as u64 {
- std::fs::write(staged(&dir, s), "PLANTED").unwrap();
- }
- assert!(write_atomically_with(&target.to_string_lossy(), b"NEW", 1..).is_err());
- assert_eq!(read(&target), "OLD");
- for s in 1..=STAGING_ATTEMPTS as u64 {
- assert_eq!(read(&staged(&dir, s)), "PLANTED");
- }
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- /// The names in a folder: what a test can see was left behind.
- fn listing(dir: &Path) -> Vec<String> {
- let mut names: Vec<_> = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
- names.sort();
- names
- }
-
- #[test]
- fn saving_a_long_name_leaves_only_the_saved_file() {
- assert_ne!(staging_suffixes().next(), staging_suffixes().next(), "each save draws new names");
- // 60 four-byte characters: a 244-byte name, within every system's limit. Its staging name
- // must be too (on Linux the whole name in it would be 275 bytes).
- let dir = staging_dir("clean");
- let name = format!("{}.pdf", "\u{1F600}".repeat(60));
- let path = dir.join(&name).to_string_lossy().into_owned();
- write_atomically(&path, b"NEW").unwrap();
- write_atomically(&path, b"NEWER").unwrap();
- assert_eq!(read(&dir.join(&name)), "NEWER");
- assert_eq!(listing(&dir), [name], "no staging file is left behind");
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- /// A read-only target is refused before anything is staged, so no staging file is left
- /// behind.
- #[cfg(windows)]
- #[test]
- fn a_failed_save_removes_the_staging_file() {
- let dir = staging_dir("readonly");
- let target = dir.join("out.pdf");
- std::fs::write(&target, "OLD").unwrap();
- let mut perms = std::fs::metadata(&target).unwrap().permissions();
- perms.set_readonly(true);
- std::fs::set_permissions(&target, perms.clone()).unwrap();
- let e = write_atomically_with(&target.to_string_lossy(), b"NEW", [7]).unwrap_err();
- assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied, "a read-only target is refused: {e}");
- assert_eq!(read(&target), "OLD");
- assert_eq!(listing(&dir), ["out.pdf"], "the staging file was removed");
- #[allow(clippy::permissions_set_readonly_false)]
- perms.set_readonly(false);
- std::fs::set_permissions(&target, perms).unwrap();
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- /// On macOS `sync_all` asks for a full flush, which SMB and FUSE volumes (a Cryptomator vault,
- /// #981) refuse as unsupported: ENOTSUP (45) or ENOTTY (25). The save still goes through.
- #[cfg(target_os = "macos")]
- #[test]
- fn a_volume_without_full_flush_still_saves() {
- for errno in [45, 25] {
- let dir = staging_dir(&format!("nofullsync-{errno}"));
- let target = dir.join("out.pdf");
- std::fs::write(&target, "OLD").unwrap();
- let asked = std::cell::Cell::new(false);
- let refuse = |_: &std::fs::File| {
- asked.set(true);
- Err(std::io::Error::from_raw_os_error(errno))
- };
- write_atomically_syncing(&target.to_string_lossy(), b"NEW", [7], refuse).unwrap();
- assert!(asked.get(), "the full flush was tried");
- assert_eq!(read(&target), "NEW");
- assert_eq!(listing(&dir), ["out.pdf"], "no staging file is left behind");
- let _ = std::fs::remove_dir_all(&dir);
- }
- }
-
- /// Only "not supported" is let through: any other flush failure fails the save and keeps the
- /// original.
- #[test]
- fn a_failed_flush_keeps_the_original() {
- let dir = staging_dir("syncfails");
- let target = dir.join("out.pdf");
- std::fs::write(&target, "OLD").unwrap();
- let e = write_atomically_syncing(&target.to_string_lossy(), b"NEW", [7], |_| Err(std::io::Error::other("disk gone"))).unwrap_err();
- assert_eq!(e.to_string(), "disk gone");
- assert_eq!(read(&target), "OLD");
- assert_eq!(listing(&dir), ["out.pdf"], "the staging file was removed");
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[cfg(target_os = "macos")]
- #[test]
- fn a_save_preserves_opening_settings_changed_while_staging() {
- let dir = staging_dir("opening-metadata-changed");
- let target = dir.join("out.pdf");
- std::fs::write(&target, b"OLD").unwrap();
- xattr::set(&target, "com.apple.LaunchServices.OpenWith", b"old handler").unwrap();
- xattr::set(&target, "com.apple.quarantine", b"0082;1234;Preview;").unwrap();
- let suffixes = std::iter::once_with(|| {
- xattr::set(&target, "com.apple.LaunchServices.OpenWith", b"new handler").unwrap();
- xattr::set(&target, "com.apple.quarantine", b"0082;5678;another app;").unwrap();
- 7
- });
- write_atomically_with(&target.to_string_lossy(), b"NEW", suffixes).unwrap();
- assert_eq!(read(&target), "NEW");
- assert_eq!(xattr::get(&target, "com.apple.LaunchServices.OpenWith").unwrap(), Some(b"new handler".to_vec()));
- assert_eq!(xattr::get(&target, "com.apple.quarantine").unwrap(), Some(b"0082;5678;another app;".to_vec()));
- let _ = std::fs::remove_dir_all(dir);
- }
-
- #[test]
- fn outlook_attachment_copies_are_recognised_on_either_separator_and_in_any_case() {
- for p in [
- r"C:\Users\me\AppData\Local\Microsoft\Windows\INetCache\Content.Outlook\AB12CD34\Quote.pdf",
- r"c:\users\me\appdata\local\microsoft\windows\inetcache\content.outlook\ab12cd34\quote (2).pdf",
- r"C:\Users\me\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.Outlook\AB12CD34\Quote.pdf",
- r"C:\Users\me\AppData\Local\Packages\Microsoft.OutlookForWindows_8wekyb3d8bbwe\LocalCache\Quote.pdf",
- "C:/Users/me/AppData/Local/Microsoft/Windows/INetCache/Content.Outlook/AB12CD34/Quote.pdf",
- ] {
- assert!(is_mail_temp_copy(p), "{p}");
- }
- }
-
- #[test]
- fn apple_mail_attachment_copies_are_recognised() {
- for p in [
- "/Users/me/Library/Containers/com.apple.mail/Data/Library/Mail Downloads/6F1C2A9E-3B4D-4E5F-8A7B-9C0D1E2F3A4B/booking.pdf",
- "/Users/me/library/containers/COM.APPLE.MAIL/data/library/mail downloads/6F1C2A9E/Booking (2).pdf",
- ] {
- assert!(is_mail_temp_copy(p), "{p}");
- }
- }
-
- #[test]
- fn ordinary_paths_are_not_mail_copies() {
- for p in [
- r"C:\Users\me\Documents\Quote.pdf",
- r"C:\Users\me\OneDrive - Contoso\Content.Outlook notes\Quote.pdf",
- r"C:\Users\me\AppData\Local\Microsoft\Windows\INetCache\IE\Quote.pdf",
- "/home/microsoft.outlookforwindows/report.pdf",
- "/x/inetcache/content.outlook/y.pdf",
- "/x/temporary internet files/content.outlook/y.pdf",
- "/home/me/Documents/Quote.pdf",
- "/Users/me/Downloads/Mail Downloads/booking.pdf",
- "/Users/me/Library/Containers/com.apple.Notes/Data/Library/Mail Downloads/booking.pdf",
- "Quote.pdf",
- ] {
- assert!(!is_mail_temp_copy(p), "{p}");
- }
- }
-
- /// A one-page document with a proper xref table.
- fn one_page_pdf() -> Vec<u8> {
- let objs = [
- "<< /Type /Catalog /Pages 2 0 R >>",
- "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>",
- "<< /Type /Page /Parent 2 0 R >>",
- ];
- let mut out = b"%PDF-1.7\n".to_vec();
- let mut offsets = Vec::new();
- for (i, o) in objs.iter().enumerate() {
- offsets.push(out.len());
- out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
- }
- let xref = out.len();
- out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
- for o in offsets {
- out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
- }
- out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
- out
- }
-
- /// `one_page_pdf`, opening without a password, whose permissions refuse changes.
- fn no_changes_pdf() -> Vec<u8> {
- let mut doc = pdfcraft_cos::Document::open(std::sync::Arc::new(one_page_pdf())).unwrap();
- let encryption = pdfcraft_cos::NewEncryption {
- algorithm: pdfcraft_cos::Algorithm::Aes256,
- user_password: "",
- owner_password: "owner",
- permissions: -1 ^ 8,
- encrypt_metadata: true,
- seed: [4; 32],
- };
- doc.set_encryption(&encryption).unwrap();
- pdfcraft_cos::write_full(&doc, &Default::default()).unwrap()
- }
-
- /// Undo with a new text box open on a document that refuses changes: the box is put back as
- /// it was. Finishing it had asked for the new item to be selected, and that request stayed
- /// behind once the add was refused.
- #[test]
- fn a_refused_text_box_is_put_back_whole() {
- let mut app = crate::PdfCraftApp::new();
- app.set_option("language", "en").unwrap();
- app.open_bytes("a.pdf", None, no_changes_pdf()).unwrap();
- let style = crate::content_ui::default_style();
- app.views[0].content.draft = Some(crate::content_ui::TextDraft {
- page: 0,
- index: None,
- rect: [20.0, 20.0, 120.0, 40.0],
- text: "Typed".into(),
- style,
- focus: false,
- selection: None,
- typing_from: None,
- });
- app.undo();
- let content = &app.views[0].content;
- assert_eq!(content.draft.as_ref().map(|d| d.text.as_str()), Some("Typed"), "the refused box stays open");
- assert_eq!(content.select_added, None, "nothing was added to select");
- }
-
- #[test]
- fn save_commits_the_open_text_box() {
- let dir = staging_dir("open-text-box");
- let dest = dir.join("out.pdf");
- let mut app = crate::PdfCraftApp::new();
- app.set_option("language", "en").unwrap();
- app.open_bytes("a.pdf", None, one_page_pdf()).unwrap();
- app.save_override = Some(dest.to_string_lossy().into_owned());
- let style = crate::content_ui::default_style();
- app.views[0].content.draft = Some(crate::content_ui::TextDraft {
- page: 0,
- index: None,
- rect: [20.0, 20.0, 120.0, 40.0],
- text: "Typed text".into(),
- style,
- focus: true,
- selection: None,
- typing_from: None,
- });
-
- assert!(app.save_active(SaveTarget::InPlace));
- let id = app.views[0].id;
- let added = app.session.get(id).unwrap().added();
- assert_eq!(added.len(), 1, "the open text box was committed before the save");
- assert!(app.views[0].content.draft.is_none());
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn save_asks_where_to_keep_an_email_attachment_and_leaves_the_temporary_copy_alone() {
- let dir = staging_dir("mail-temp");
- let cache = dir.join("INetCache").join("Content.Outlook").join("AB12CD34");
- std::fs::create_dir_all(&cache).unwrap();
- let attachment = cache.join("Quote.pdf");
- let original = one_page_pdf();
- std::fs::write(&attachment, &original).unwrap();
- let kept = dir.join("Quote.pdf");
-
- let mut app = crate::PdfCraftApp::new();
- app.set_option("language", "en").unwrap();
- app.open_bytes("Quote.pdf", Some(attachment.to_string_lossy().into_owned()), original.clone()).unwrap();
- assert!(app.apply_edit(pdfcraft_engine::Edit::RotatePages { pages: vec![0], degrees: 90 }));
- app.pick_override = Some(vec![kept.to_string_lossy().into_owned()]);
-
- assert!(!app.save_active(SaveTarget::InPlace), "Save asks instead of writing the temporary copy");
- app.process_picked();
- assert_eq!(std::fs::read(&attachment).unwrap(), original, "the attachment's copy is untouched");
- assert!(std::fs::read(&kept).unwrap().starts_with(b"%PDF"), "the document went where the user chose");
-
- // The chosen file is the document's file now: the next Save writes it without asking.
- app.pick_override = None;
- assert!(app.apply_edit(pdfcraft_engine::Edit::RotatePages { pages: vec![0], degrees: 90 }));
- assert!(app.save_active(SaveTarget::InPlace));
- let _ = std::fs::remove_dir_all(&dir);
- }
- }
+ mod tests;
#[cfg(test)]
mod revert_draft_tests {
diff --cc crates/ui-egui/src/editing/tests.rs
index 000000000,87de7e8b8..76886ff54
mode 000000,100644..100644
--- a/crates/ui-egui/src/editing/tests.rs
+++ b/crates/ui-egui/src/editing/tests.rs
@@@ -1,0 -1,345 +1,393 @@@
+ use super::{SaveTarget, is_mail_temp_copy, save_dialog_folder, write_atomically, write_atomically_syncing, write_atomically_with};
+
+ #[test]
+ fn save_dialogs_open_in_the_documents_folder() {
+ use std::path::PathBuf;
+ assert_eq!(save_dialog_folder(Some("/home/a/plans/f.pdf")), Some(PathBuf::from("/home/a/plans")));
+ // A new document has no folder yet; a bare name has an empty parent; the root has none.
+ assert_eq!(save_dialog_folder(None), None);
+ assert_eq!(save_dialog_folder(Some("f.pdf")), None);
+ assert_eq!(save_dialog_folder(Some("/")), None);
+ // An email attachment's temporary copy is not offered.
+ assert_eq!(save_dialog_folder(Some("C:\\Users\\a\\AppData\\Local\\Microsoft\\Windows\\INetCache\\Content.Outlook\\AB12\\f.pdf")), None);
+ assert_eq!(save_dialog_folder(Some("/Users/a/Library/Containers/com.apple.mail/Data/Library/Mail Downloads/UUID/f.pdf")), None);
+ }
+
+ /// The Windows rules for `Path::parent` (UNC share roots included) only apply on Windows.
+ #[cfg(windows)]
+ #[test]
+ fn save_dialog_folder_handles_unc_paths() {
+ use std::path::PathBuf;
+ assert_eq!(save_dialog_folder(Some(r"\\nas\projets\2026\f.pdf")), Some(PathBuf::from(r"\\nas\projets\2026")));
+ assert_eq!(save_dialog_folder(Some(r"\\nas\projets\f.pdf")), Some(PathBuf::from(r"\\nas\projets\")));
+ assert_eq!(save_dialog_folder(Some(r"\\nas\projets")), None);
+ assert_eq!(save_dialog_folder(Some(r"C:\Users\a\f.pdf")), Some(PathBuf::from(r"C:\Users\a")));
+ }
+ use pdfcraft_platform::staging::{STAGING_ATTEMPTS, staging_suffixes};
+ use std::path::{Path, PathBuf};
+
+ /// A fresh, empty folder for one staging test.
+ fn staging_dir(test: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!("pdfcraft-ui-staging-{}-{test}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ fn staged(dir: &Path, suffix: u64) -> PathBuf {
+ dir.join(format!(".out.pdf.pdfcraft-{suffix:016x}.tmp"))
+ }
+
+ fn read(p: &Path) -> String {
+ std::fs::read_to_string(p).unwrap()
+ }
+
+ /// A symbolic link to a file, where the system allows one (Windows needs Developer Mode or an
+ /// administrator for it).
+ fn file_symlink(target: &Path, link: &Path) -> std::io::Result<()> {
+ #[cfg(unix)]
+ {
+ std::os::unix::fs::symlink(target, link)
+ }
+ #[cfg(windows)]
+ {
+ std::os::windows::fs::symlink_file(target, link)
+ }
+ #[cfg(not(any(unix, windows)))]
+ {
+ Err(std::io::Error::other(format!("no symbolic links here: {} {}", target.display(), link.display())))
+ }
+ }
+
+ #[test]
+ fn saving_never_writes_through_a_file_planted_at_the_staging_name() {
+ let dir = staging_dir("planted");
+ let outside = dir.join("outside.txt");
+ std::fs::write(&outside, "PRECIOUS").unwrap();
+ let target = dir.join("out.pdf");
+ let path = target.to_string_lossy().into_owned();
+ // A hard link needs no privileges on any system, and writing to it writes to `outside`.
+ std::fs::hard_link(&outside, staged(&dir, 1)).unwrap();
+ std::fs::write(staged(&dir, 2), "PLANTED").unwrap();
+ write_atomically_with(&path, b"NEW", [1, 2, 3]).unwrap();
+ assert_eq!(read(&target), "NEW");
+ assert_eq!(read(&outside), "PRECIOUS");
+ assert_eq!(read(&staged(&dir, 1)), "PRECIOUS");
+ assert_eq!(read(&staged(&dir, 2)), "PLANTED");
+ assert!(!staged(&dir, 3).exists(), "the staging file was renamed into place");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn saving_never_writes_through_a_symbolic_link_at_the_staging_name() {
+ let dir = staging_dir("symlink");
+ let outside = dir.join("outside.txt");
+ std::fs::write(&outside, "PRECIOUS").unwrap();
+ let target = dir.join("out.pdf");
+ if let Err(e) = file_symlink(&outside, &staged(&dir, 1)) {
+ eprintln!("symbolic links not checked: {e}");
+ return;
+ }
+ write_atomically_with(&target.to_string_lossy(), b"NEW", [1, 2]).unwrap();
+ assert_eq!(read(&target), "NEW");
+ assert_eq!(read(&outside), "PRECIOUS");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn saving_never_creates_a_file_through_a_dangling_link_at_the_staging_name() {
+ let dir = staging_dir("dangling");
+ let unborn = dir.join("created-through-a-link.txt");
+ let target = dir.join("out.pdf");
+ if let Err(e) = file_symlink(&unborn, &staged(&dir, 1)) {
+ eprintln!("symbolic links not checked: {e}");
+ return;
+ }
+ write_atomically_with(&target.to_string_lossy(), b"NEW", [1, 2]).unwrap();
+ assert_eq!(read(&target), "NEW");
+ assert!(!unborn.exists(), "nothing was created through the dangling link");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn a_folder_at_the_staging_name_is_left_alone() {
+ let dir = staging_dir("folder");
+ std::fs::create_dir(staged(&dir, 1)).unwrap();
+ std::fs::write(staged(&dir, 1).join("inside.txt"), "PLANTED").unwrap();
+ let target = dir.join("out.pdf");
+ write_atomically_with(&target.to_string_lossy(), b"NEW", [1, 2]).unwrap();
+ assert_eq!(read(&target), "NEW");
+ assert_eq!(read(&staged(&dir, 1).join("inside.txt")), "PLANTED");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn saving_gives_up_rather_than_reuse_a_taken_name() {
+ let dir = staging_dir("taken");
+ let target = dir.join("out.pdf");
+ std::fs::write(&target, "OLD").unwrap();
+ for s in 1..=STAGING_ATTEMPTS as u64 {
+ std::fs::write(staged(&dir, s), "PLANTED").unwrap();
+ }
+ assert!(write_atomically_with(&target.to_string_lossy(), b"NEW", 1..).is_err());
+ assert_eq!(read(&target), "OLD");
+ for s in 1..=STAGING_ATTEMPTS as u64 {
+ assert_eq!(read(&staged(&dir, s)), "PLANTED");
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ /// The names in a folder: what a test can see was left behind.
+ fn listing(dir: &Path) -> Vec<String> {
+ let mut names: Vec<_> = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
+ names.sort();
+ names
+ }
+
+ #[test]
+ fn saving_a_long_name_leaves_only_the_saved_file() {
+ assert_ne!(staging_suffixes().next(), staging_suffixes().next(), "each save draws new names");
+ // 60 four-byte characters: a 244-byte name, within every system's limit. Its staging name
+ // must be too (on Linux the whole name in it would be 275 bytes).
+ let dir = staging_dir("clean");
+ let name = format!("{}.pdf", "\u{1F600}".repeat(60));
+ let path = dir.join(&name).to_string_lossy().into_owned();
+ write_atomically(&path, b"NEW").unwrap();
+ write_atomically(&path, b"NEWER").unwrap();
+ assert_eq!(read(&dir.join(&name)), "NEWER");
+ assert_eq!(listing(&dir), [name], "no staging file is left behind");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ /// A read-only target is refused before anything is staged, so no staging file is left
+ /// behind.
+ #[cfg(windows)]
+ #[test]
+ fn a_failed_save_removes_the_staging_file() {
+ let dir = staging_dir("readonly");
+ let target = dir.join("out.pdf");
+ std::fs::write(&target, "OLD").unwrap();
+ let mut perms = std::fs::metadata(&target).unwrap().permissions();
+ perms.set_readonly(true);
+ std::fs::set_permissions(&target, perms.clone()).unwrap();
+ let e = write_atomically_with(&target.to_string_lossy(), b"NEW", [7]).unwrap_err();
+ assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied, "a read-only target is refused: {e}");
+ assert_eq!(read(&target), "OLD");
+ assert_eq!(listing(&dir), ["out.pdf"], "the staging file was removed");
+ #[allow(clippy::permissions_set_readonly_false)]
+ perms.set_readonly(false);
+ std::fs::set_permissions(&target, perms).unwrap();
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ /// On macOS `sync_all` asks for a full flush, which SMB and FUSE volumes (a Cryptomator vault,
+ /// #981) refuse as unsupported: ENOTSUP (45) or ENOTTY (25). The save still goes through.
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn a_volume_without_full_flush_still_saves() {
+ for errno in [45, 25] {
+ let dir = staging_dir(&format!("nofullsync-{errno}"));
+ let target = dir.join("out.pdf");
+ std::fs::write(&target, "OLD").unwrap();
+ let asked = std::cell::Cell::new(false);
+ let refuse = |_: &std::fs::File| {
+ asked.set(true);
+ Err(std::io::Error::from_raw_os_error(errno))
+ };
+ write_atomically_syncing(&target.to_string_lossy(), b"NEW", [7], refuse).unwrap();
+ assert!(asked.get(), "the full flush was tried");
+ assert_eq!(read(&target), "NEW");
+ assert_eq!(listing(&dir), ["out.pdf"], "no staging file is left behind");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+ }
+
+ /// Only "not supported" is let through: any other flush failure fails the save and keeps the
+ /// original.
+ #[test]
+ fn a_failed_flush_keeps_the_original() {
+ let dir = staging_dir("syncfails");
+ let target = dir.join("out.pdf");
+ std::fs::write(&target, "OLD").unwrap();
+ let e = write_atomically_syncing(&target.to_string_lossy(), b"NEW", [7], |_| Err(std::io::Error::other("disk gone"))).unwrap_err();
+ assert_eq!(e.to_string(), "disk gone");
+ assert_eq!(read(&target), "OLD");
+ assert_eq!(listing(&dir), ["out.pdf"], "the staging file was removed");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn a_save_preserves_opening_settings_changed_while_staging() {
+ let dir = staging_dir("opening-metadata-changed");
+ let target = dir.join("out.pdf");
+ std::fs::write(&target, b"OLD").unwrap();
+ xattr::set(&target, "com.apple.LaunchServices.OpenWith", b"old handler").unwrap();
+ xattr::set(&target, "com.apple.quarantine", b"0082;1234;Preview;").unwrap();
+ let suffixes = std::iter::once_with(|| {
+ xattr::set(&target, "com.apple.LaunchServices.OpenWith", b"new handler").unwrap();
+ xattr::set(&target, "com.apple.quarantine", b"0082;5678;another app;").unwrap();
+ 7
+ });
+ write_atomically_with(&target.to_string_lossy(), b"NEW", suffixes).unwrap();
+ assert_eq!(read(&target), "NEW");
+ assert_eq!(xattr::get(&target, "com.apple.LaunchServices.OpenWith").unwrap(), Some(b"new handler".to_vec()));
+ assert_eq!(xattr::get(&target, "com.apple.quarantine").unwrap(), Some(b"0082;5678;another app;".to_vec()));
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
+ #[test]
+ fn outlook_attachment_copies_are_recognised_on_either_separator_and_in_any_case() {
+ for p in [
+ r"C:\Users\me\AppData\Local\Microsoft\Windows\INetCache\Content.Outlook\AB12CD34\Quote.pdf",
+ r"c:\users\me\appdata\local\microsoft\windows\inetcache\content.outlook\ab12cd34\quote (2).pdf",
+ r"C:\Users\me\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.Outlook\AB12CD34\Quote.pdf",
+ r"C:\Users\me\AppData\Local\Packages\Microsoft.OutlookForWindows_8wekyb3d8bbwe\LocalCache\Quote.pdf",
+ "C:/Users/me/AppData/Local/Microsoft/Windows/INetCache/Content.Outlook/AB12CD34/Quote.pdf",
+ ] {
+ assert!(is_mail_temp_copy(p), "{p}");
+ }
+ }
+
+ #[test]
+ fn apple_mail_attachment_copies_are_recognised() {
+ for p in [
+ "/Users/me/Library/Containers/com.apple.mail/Data/Library/Mail Downloads/6F1C2A9E-3B4D-4E5F-8A7B-9C0D1E2F3A4B/booking.pdf",
+ "/Users/me/library/containers/COM.APPLE.MAIL/data/library/mail downloads/6F1C2A9E/Booking (2).pdf",
+ ] {
+ assert!(is_mail_temp_copy(p), "{p}");
+ }
+ }
+
+ #[test]
+ fn ordinary_paths_are_not_mail_copies() {
+ for p in [
+ r"C:\Users\me\Documents\Quote.pdf",
+ r"C:\Users\me\OneDrive - Contoso\Content.Outlook notes\Quote.pdf",
+ r"C:\Users\me\AppData\Local\Microsoft\Windows\INetCache\IE\Quote.pdf",
+ "/home/microsoft.outlookforwindows/report.pdf",
+ "/x/inetcache/content.outlook/y.pdf",
+ "/x/temporary internet files/content.outlook/y.pdf",
+ "/home/me/Documents/Quote.pdf",
+ "/Users/me/Downloads/Mail Downloads/booking.pdf",
+ "/Users/me/Library/Containers/com.apple.Notes/Data/Library/Mail Downloads/booking.pdf",
+ "Quote.pdf",
+ ] {
+ assert!(!is_mail_temp_copy(p), "{p}");
+ }
+ }
+
+ /// A one-page document with a proper xref table.
+ fn one_page_pdf() -> Vec<u8> {
+ let objs =
+ ["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>", "<< /Type /Page /Parent 2 0 R >>"];
+ let mut out = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, o) in objs.iter().enumerate() {
+ offsets.push(out.len());
+ out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
+ }
+ let xref = out.len();
+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
+ for o in offsets {
+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
+ }
+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
+ out
+ }
+
++/// `one_page_pdf`, opening without a password, whose permissions refuse changes.
++fn no_changes_pdf() -> Vec<u8> {
++ let mut doc = pdfcraft_cos::Document::open(std::sync::Arc::new(one_page_pdf())).unwrap();
++ let encryption = pdfcraft_cos::NewEncryption {
++ algorithm: pdfcraft_cos::Algorithm::Aes256,
++ user_password: "",
++ owner_password: "owner",
++ permissions: -1 ^ 8,
++ encrypt_metadata: true,
++ seed: [4; 32],
++ };
++ doc.set_encryption(&encryption).unwrap();
++ pdfcraft_cos::write_full(&doc, &Default::default()).unwrap()
++}
++
++/// Undo with a new text box open on a document that refuses changes: the box is put back as
++/// it was. Finishing it had asked for the new item to be selected, and that request stayed
++/// behind once the add was refused.
++#[test]
++fn a_refused_text_box_is_put_back_whole() {
++ let mut app = crate::PdfCraftApp::new();
++ app.set_option("language", "en").unwrap();
++ app.open_bytes("a.pdf", None, no_changes_pdf()).unwrap();
++ let style = crate::content_ui::default_style();
++ app.views[0].content.draft = Some(crate::content_ui::TextDraft {
++ page: 0,
++ index: None,
++ rect: [20.0, 20.0, 120.0, 40.0],
++ text: "Typed".into(),
++ style,
++ focus: false,
++ selection: None,
++ typing_from: None,
++ });
++ app.undo();
++ let content = &app.views[0].content;
++ assert_eq!(content.draft.as_ref().map(|d| d.text.as_str()), Some("Typed"), "the refused box stays open");
++ assert_eq!(content.select_added, None, "nothing was added to select");
++}
++
+ #[test]
+ fn save_commits_the_open_text_box() {
+ let dir = staging_dir("open-text-box");
+ let dest = dir.join("out.pdf");
+ let mut app = crate::PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ app.open_bytes("a.pdf", None, one_page_pdf()).unwrap();
+ app.save_override = Some(dest.to_string_lossy().into_owned());
+ let style = crate::content_ui::default_style();
- app.views[0].content.draft =
- Some(crate::content_ui::TextDraft { page: 0, index: None, rect: [20.0, 20.0, 120.0, 40.0], text: "Typed text".into(), style, focus: true });
++ app.views[0].content.draft = Some(crate::content_ui::TextDraft {
++ page: 0,
++ index: None,
++ rect: [20.0, 20.0, 120.0, 40.0],
++ text: "Typed text".into(),
++ style,
++ focus: true,
++ selection: None,
++ typing_from: None,
++ });
+
+ assert!(app.save_active(SaveTarget::InPlace));
+ let id = app.views[0].id;
+ let added = app.session.get(id).unwrap().added();
+ assert_eq!(added.len(), 1, "the open text box was committed before the save");
+ assert!(app.views[0].content.draft.is_none());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn save_asks_where_to_keep_an_email_attachment_and_leaves_the_temporary_copy_alone() {
+ let dir = staging_dir("mail-temp");
+ let cache = dir.join("INetCache").join("Content.Outlook").join("AB12CD34");
+ std::fs::create_dir_all(&cache).unwrap();
+ let attachment = cache.join("Quote.pdf");
+ let original = one_page_pdf();
+ std::fs::write(&attachment, &original).unwrap();
+ let kept = dir.join("Quote.pdf");
+
+ let mut app = crate::PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ app.open_bytes("Quote.pdf", Some(attachment.to_string_lossy().into_owned()), original.clone()).unwrap();
+ assert!(app.apply_edit(pdfcraft_engine::Edit::RotatePages { pages: vec![0], degrees: 90 }));
+ app.pick_override = Some(vec![kept.to_string_lossy().into_owned()]);
+
+ assert!(!app.save_active(SaveTarget::InPlace), "Save asks instead of writing the temporary copy");
+ app.process_picked();
+ assert_eq!(std::fs::read(&attachment).unwrap(), original, "the attachment's copy is untouched");
+ assert!(std::fs::read(&kept).unwrap().starts_with(b"%PDF"), "the document went where the user chose");
+
+ // The chosen file is the document's file now: the next Save writes it without asking.
+ app.pick_override = None;
+ assert!(app.apply_edit(pdfcraft_engine::Edit::RotatePages { pages: vec![0], degrees: 90 }));
+ assert!(app.save_active(SaveTarget::InPlace));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
diff --cc crates/ui-egui/src/panels/edit.rs
index 000000000,e10d0d01e..8883ec42e
mode 000000,100644..100644
--- a/crates/ui-egui/src/panels/edit.rs
+++ b/crates/ui-egui/src/panels/edit.rs
@@@ -1,0 -1,370 +1,421 @@@
+ use super::tools::row_label;
+ use super::*;
+
+ /// The page operations Edit shows as a row of icon buttons, as Acrobat's Edit panel does.
+ const EDIT_PAGE_BUTTONS: [&str; 4] = ["page.rotate", "page.insert", "page.delete", "page.extract"];
+
+ /// Add content items shown before More.
+ const EDIT_CONTENT_SHOWN: usize = 5;
+
+ /// Other options: the tools Acrobat's Edit panel links to.
+ const EDIT_OTHER_TOOLS: [&str; 3] = ["combine", "redact", "form"];
+
+ /// Edit a PDF, laid out as Acrobat's Edit panel: the title with Preferences and Close; Format text
+ /// while text is being edited or added; Modify page as a row of icon buttons and Organize pages;
+ /// Add content with the rarer items under More; and Other options, the neighbouring tools.
+ /// Edit text & images itself is on the floating toolbar, and on from the moment Edit opens.
+ /// Every item comes from the catalogue, so its label, icon and availability have one source.
+ pub(super) fn edit_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens, g: &'static ToolGroup) {
+ let items = || g.sections.iter().flat_map(|s| s.items.iter());
+ let item = |command: &str| items().find(|i| i.command == command);
+ let mut run = None;
+ let mut tool = None;
+ // Back to All tools only when Edit was opened from there; the Edit tab is its own way back.
+ let from_all_tools = app.mode != crate::Mode::Edit;
+ ui.horizontal(|ui| {
+ if from_all_tools && icons::button(ui, "chevron-left", 26.0, false, tl!("Back to all tools")).clicked() {
+ app.left = LeftPanel::AllTools;
+ app.enter_mode(crate::Mode::AllTools);
+ }
+ // "Edit" under the Edit tab, as Acrobat titles it; the tool's own name from All tools.
+ let title = if from_all_tools { tl!(g.label) } else { tl!("Edit") };
+ let title_width = (ui.available_width() - 2.0 * (26.0 + ui.spacing().item_spacing.x)).max(1.0);
+ ui.add_sized([title_width, 26.0], egui::Label::new(egui::RichText::new(title).font(theme::semibold(15.5)).color(t.text)).truncate())
+ .on_hover_text(title);
+ if icons::button(ui, "settings", 26.0, false, tl!("Preferences")).clicked() {
+ run = Some("app.preferences");
+ }
+ if icons::button(ui, "x", 26.0, false, tl!("Close panel")).clicked() {
+ app.left_open = false;
+ }
+ });
+ ui.add_space(4.0);
+ ui.separator();
+ ui.add_space(6.0);
+ // Several objects selected: how many, and how to move them. Acrobat's panel has no idle hint.
+ let count = app.active_ids().filter(|_| app.quick_tool == crate::QuickTool::EditText).map_or(0, |(i, _)| app.views[i].objects.count());
+ if count > 0 {
+ ui.label(crate::i18n::trn(crate::i18n::current(), count as u64, "{n} object selected", "{n} objects selected"));
+ ui.label(tl!("Drag the selection to move it. Esc clears the selection."));
+ ui.add_space(6.0);
+ }
+ // Format text at the top while text is selected or being added.
+ format_section(app, ui, t);
+ egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
+ widgets::section_title(ui, tl!("Modify page"));
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 6.0;
+ for i in EDIT_PAGE_BUTTONS.iter().filter_map(|c| item(c)) {
+ // Enabled as the command itself is: a document that forbids page assembly refuses these.
+ let enabled = pdfcraft_engine::commands::command(i.command).is_some_and(|spec| app.command_enabled(spec));
+ let resp = ui.add_enabled_ui(enabled, |ui| icons::button(ui, i.icon, 34.0, false, tl!(i.label))).inner;
+ if resp.clicked() {
+ run = Some(i.command);
+ }
+ }
+ });
+ ui.add_space(2.0);
+ // Organize pages is a workspace of its own: its panel replaces this one, with the grid.
+ if let Some(i) = item("page.organize")
+ && edit_row(ui, t, i.icon, tl!(i.label), i.availability).clicked()
+ {
+ // With no document there is no grid to open: the command asks for a file first.
+ if app.active.is_some() {
+ tool = Some("organize");
+ } else {
+ run = Some("page.organize");
+ }
+ }
+
+ widgets::section_title(ui, tl!("Add content"));
+ let content: Vec<_> =
+ g.sections.iter().filter(|s| s.title == "Add content").flat_map(|s| s.items.iter()).filter(|i| i.command != "edit.edit_text").collect();
+ let more_id = egui::Id::unique("edit_panel_more");
+ let more = ui.data(|d| d.get_temp::<bool>(more_id)).unwrap_or(false);
+ let shown = if more { content.len() } else { EDIT_CONTENT_SHOWN.min(content.len()) };
+ for i in content.iter().take(shown) {
+ let resp = edit_row(ui, t, i.icon, tl!(i.label), i.availability);
+ // Header and footer, Watermark and Background open their Add / Update / Remove menu.
+ if i.actions.is_empty() {
+ if resp.clicked() {
+ run = Some(i.command);
+ }
+ } else if let Some(cmd) = actions_menu(app, ui, &resp, i, resp.rect.right_center() - vec2(14.0, 0.0), t.text) {
+ run = Some(cmd);
+ }
+ }
+ if content.len() > EDIT_CONTENT_SHOWN {
+ ui.add_space(4.0);
+ let label = if more { tl!("Less") } else { tl!("More") };
+ let resp = ui
+ .add(
+ egui::Label::new(egui::RichText::new(label).color(t.accent_text).font(theme::medium(13.0)))
+ .selectable(false)
+ .sense(Sense::click()),
+ )
+ .on_hover_cursor(egui::CursorIcon::PointingHand);
+ if resp.clicked() {
+ ui.data_mut(|d| d.insert_temp(more_id, !more));
+ }
+ }
+
+ widgets::section_title(ui, tl!("Other options"));
+ for other in EDIT_OTHER_TOOLS.iter().filter_map(|id| catalog::group(id)) {
+ if edit_row(ui, t, other.icon, tl!(other.label), other.availability).clicked() {
+ tool = Some(other.id);
+ }
+ }
+ });
+ if let Some(id) = tool {
+ app.select_tool(id);
+ }
+ if let Some(cmd) = run {
+ app.run_command(cmd);
+ }
+ }
+
+ /// A tool entry with further commands (Add / Update / Remove): a caret at `caret` says it opens a
+ /// menu, and each command is enabled by its own needs. Returns the command chosen.
+ pub(super) fn actions_menu(
+ app: &PdfCraftApp,
+ ui: &egui::Ui,
+ resp: &egui::Response,
+ item: &ToolItem,
+ caret: egui::Pos2,
+ color: Color32,
+ ) -> Option<&'static str> {
+ ui.painter().add(egui::Shape::convex_polygon(
+ vec![caret + vec2(-3.5, -2.0), caret + vec2(3.5, -2.0), caret + vec2(0.0, 2.5)],
+ color,
+ egui::Stroke::NONE,
+ ));
+ let mut run = None;
+ egui::Popup::menu(resp).show(|ui| {
+ ui.set_min_width(180.0);
+ for (n, id) in item.actions.iter().enumerate() {
+ let Some(spec) = pdfcraft_engine::commands::command(id) else { continue };
+ // Add stays usable with no document open: it asks for a file first.
+ let enabled = (n == 0 && app.active.is_none()) || app.command_enabled(spec);
+ let label = crate::i18n::menu_label(spec.id, spec.label);
+ if ui.add_enabled(enabled, egui::Button::new(label)).clicked() {
+ run = Some(spec.id);
+ ui.close();
+ }
+ }
+ });
+ run
+ }
+
+ /// One row of the Edit panel: a monochrome icon and the label, as Acrobat draws them. A planned
+ /// item is muted and says when it ships when hovered.
+ fn edit_row(ui: &mut egui::Ui, t: &Tokens, icon: &str, label: &str, availability: Availability) -> egui::Response {
+ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 34.0), Sense::click());
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));
+ let press = theme::Press::track(ui, &resp);
+ press.wash(ui, rect, 6, false);
+ let body = rect.translate(press.offset());
+ let ready = availability == Availability::Ready;
+ let fg = if ready { t.text } else { t.text_muted };
+ icons::paint(ui, Rect::from_min_size(body.min + vec2(6.0, 8.0), vec2(18.0, 18.0)), icon, 17.0, if ready { t.text } else { t.text_faint });
+ row_label(ui, label, theme::regular(13.5), fg, body.left_center() + vec2(34.0, 0.0), rect.width() - 42.0);
+ let resp = theme::hand(resp);
+ match availability {
+ Availability::Ready => resp,
+ Availability::Planned(m) => resp.on_hover_text(format!("{} {m}", tl!("Planned for milestone"))),
+ Availability::Provider => resp.on_hover_text(tl!("Optional: needs an AI provider you configure")),
+ }
+ }
+
+ /// Add a stamp: Dynamic, Sign Here and Standard Business stamps; click one, then click on the
+ /// page to place it.
+ pub(super) fn stamp_palette(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) {
+ use pdfcraft_engine::{StampGroup, StampKind};
+ ui.label(egui::RichText::new(tl!("Choose a stamp, then click on the page to place it.")).small().color(t.text_faint));
+ egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
+ for (group, title) in [
+ (StampGroup::Dynamic, tl!("Dynamic")),
+ (StampGroup::SignHere, tl!("Sign Here")),
+ (StampGroup::StandardBusiness, tl!("Standard Business")),
+ ] {
+ widgets::section_title(ui, title);
+ for kind in StampKind::ALL.into_iter().filter(|k| k.group() == group) {
+ let active = app.quick_tool == crate::QuickTool::Stamp(kind);
+ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 38.0), Sense::click());
+ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, active, kind.label()));
+ let press = theme::Press::track(ui, &resp);
+ press.wash(ui, rect, 6, active);
+ let body = rect.translate(press.offset());
+ let [r, g, b] = kind.color().map(|v| (v * 255.0) as u8);
+ let col = Color32::from_rgb(r, g, b);
+ let chip = Rect::from_min_size(body.min + vec2(8.0, 5.0), vec2((rect.width() - 16.0).min(200.0), 28.0));
+ if group == StampGroup::SignHere {
+ let tip = chip.height() * 0.45;
+ let pts = vec![
+ chip.left_center(),
+ chip.left_top() + vec2(tip, 0.0),
+ chip.right_top(),
+ chip.right_bottom(),
+ chip.left_bottom() + vec2(tip, 0.0),
+ ];
+ ui.painter().add(egui::Shape::convex_polygon(pts, col, Stroke::NONE));
+ let label = kind.label();
+ let font = theme::semibold(11.0);
+ let shown = crate::widgets::fit_line(label, (chip.width() - 10.0).max(0.0), |s| crate::widgets::text_width(ui, s, &font));
+ ui.painter().with_clip_rect(chip.shrink(3.0)).text(
+ chip.center() + vec2(tip / 2.0, 0.0),
+ Align2::CENTER_CENTER,
+ shown,
+ font,
+ Color32::WHITE,
+ );
+ } else {
+ ui.painter().rect(chip, CornerRadius::same(5), col.gamma_multiply(0.1), Stroke::new(1.5, col), egui::StrokeKind::Inside);
+ let y = if group == StampGroup::Dynamic { chip.center().y - 4.0 } else { chip.center().y };
+ let font = theme::semibold(11.0);
+ let shown = crate::widgets::fit_line(kind.label(), (chip.width() - 10.0).max(0.0), |s| crate::widgets::text_width(ui, s, &font));
+ ui.painter().with_clip_rect(chip.shrink(3.0)).text(egui::pos2(chip.center().x, y), Align2::CENTER_CENTER, shown, font, col);
+ if group == StampGroup::Dynamic {
+ let by = "By name at time, date";
+ let by_font = theme::regular(7.5);
+ let by_shown = crate::widgets::fit_line(by, (chip.width() - 8.0).max(0.0), |s| crate::widgets::text_width(ui, s, &by_font));
+ ui.painter().with_clip_rect(chip.shrink(2.0)).text(
+ egui::pos2(chip.center().x, chip.bottom() - 6.0),
+ Align2::CENTER_CENTER,
+ by_shown,
+ by_font,
+ col,
+ );
+ }
+ }
+ if theme::hand(resp).clicked() {
+ app.quick_tool = crate::QuickTool::Stamp(kind);
+ }
+ }
+ }
+ crate::stamps_ui::palette_section(app, ui, t);
+ });
+ }
+
+ /// Edit a PDF ▸ Format text: for the selected added text (one undoable change), or the style
+ /// new text gets.
+ fn format_section(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) {
+ // Editing a paragraph of existing text: its formatting, applied as it changes.
+ if let Some((i, _)) = app.active_ids()
+ && let Some(ed) = app.views[i].line_editor.clone()
+ {
+ use crate::format_text_ui::{FontChoice, Fonts};
+ let mut ed = ed;
+ let sources: Vec<(String, String)> = app
+ .session
+ .get(app.views[i].id)
+ .map(|d| d.text_editor_fonts(ed.page))
+ .unwrap_or_default()
+ .into_iter()
+ .map(|f| (f.resource, f.face))
+ .collect();
+ let shown = ed.font_shown(&sources);
- let out = crate::format_text_ui::panel(ui, t, &mut ed.look, Some(&mut ed.extras), Fonts { sources: Some(&sources), shown });
++ // A selection aligns the rows it touches; the caret alone, the whole paragraph.
++ let paragraphs = crate::format_text_ui::Paragraphs { text: &ed.text, selection: ed.selection.clone(), tidy: false };
++ let out = crate::format_text_ui::panel(ui, t, &mut ed.look, Some(&mut ed.extras), Fonts { sources: Some(&sources), shown }, Some(paragraphs));
+ let mut changed = out.changed;
+ match out.font {
+ Some(FontChoice::KeepSource) => {
+ ed.keep_source_font();
+ changed = true;
+ }
+ Some(FontChoice::Resource(resource)) => {
+ ed.font_resource = Some(resource);
+ changed = true;
+ }
+ Some(FontChoice::Family(family)) => {
+ ed.choose_family(family);
+ changed = true;
+ }
+ Some(FontChoice::Load) => app.pick_files(crate::files::FilePurpose::TextFont { page: ed.page }, false),
+ #[cfg(not(target_arch = "wasm32"))]
+ Some(FontChoice::Installed(path)) => app.use_paths(crate::files::FilePurpose::TextFont { page: ed.page }, &[path]),
+ #[cfg(target_arch = "wasm32")]
+ Some(FontChoice::Installed(_)) => {}
+ None => {}
+ }
+ if changed {
+ app.apply_line_format(i, ed, Some(ui.ctx()));
+ }
+ return;
+ }
++ // Typing added text: the box's formatting, and alignment for the lines a selection touches.
++ if let Some(i) = app.active_ids().map(|(i, _)| i)
++ && let Some(draft) = app.views[i].content.draft.clone()
++ {
++ if draft.index.is_none() && app.quick_tool == crate::QuickTool::AddText {
++ crate::content_ui::hint(ui, t);
++ }
++ let mut style = draft.style.clone();
++ let paragraphs = crate::format_text_ui::Paragraphs { text: &draft.text, selection: draft.selection.clone(), tidy: true };
++ added_text_format(ui, t, &mut style, Some(paragraphs));
++ if style != draft.style {
++ app.restyle_draft(i, style);
++ }
++ return;
++ }
+ let image = app.active_ids().and_then(|(i, id)| {
+ let (page, index) = app.views[i].content.selected?;
+ let doc = app.session.get(id)?;
+ match &doc.added().iter().filter(|a| a.page == page).nth(index)?.content {
+ pdfcraft_engine::AddedContent::Image(img) => Some((page, index, img.clone())),
+ _ => None,
+ }
+ });
+ if let Some((page, index, img)) = image {
+ match crate::content_ui::image_panel(ui, t, &img) {
+ Some(crate::content_ui::ImageAction::Update(content)) => {
+ app.apply_edit(pdfcraft_engine::Edit::UpdateContent { page, index, content });
+ }
+ Some(crate::content_ui::ImageAction::Replace) => app.replace_image_dialog(page, index),
+ None => {}
+ }
+ ui.add_space(6.0);
+ ui.separator();
+ return;
+ }
+ let selected = app.active_ids().and_then(|(i, id)| {
+ let (page, index) = app.views[i].content.selected?;
+ let doc = app.session.get(id)?;
+ let a = doc.added().iter().filter(|a| a.page == page).nth(index)?;
+ match &a.content {
+ pdfcraft_engine::AddedContent::Text(text) => Some((page, index, text.clone())),
+ _ => None,
+ }
+ });
+ match selected {
+ Some((page, index, text)) => {
+ let mut style = text.clone();
- added_text_format(ui, t, &mut style);
++ added_text_format(ui, t, &mut style, None);
+ if style != text {
+ // The reusable style follows the selection only when the edit took, so a refused one adds nothing odd later.
+ if app.apply_edit(pdfcraft_engine::Edit::UpdateContent { page, index, content: pdfcraft_engine::AddedContent::Text(style.clone()) }) {
- app.text_style = pdfcraft_engine::AddedText { text: String::new(), rect: [0.0; 4], ..style };
++ app.text_style = pdfcraft_engine::AddedText { text: String::new(), rect: [0.0; 4], aligns: Vec::new(), ..style };
+ }
+ }
+ }
+ None if app.quick_tool == crate::QuickTool::AddText => {
+ crate::content_ui::hint(ui, t);
+ let mut style = app.text_style.clone();
- added_text_format(ui, t, &mut style);
++ added_text_format(ui, t, &mut style, None);
+ app.text_style = style;
+ }
+ None => {}
+ }
+ }
+
-/// Format text for added text: the standard families, size, colour, style and alignment.
-fn added_text_format(ui: &mut egui::Ui, t: &Tokens, style: &mut pdfcraft_engine::AddedText) {
++/// Format text for added text: the standard families, size, colour, style and alignment
++/// (of the lines `paragraphs` selects, while the text is being typed).
++fn added_text_format(ui: &mut egui::Ui, t: &Tokens, style: &mut pdfcraft_engine::AddedText, paragraphs: Option<crate::format_text_ui::Paragraphs>) {
+ let shown = style.family.label().to_string();
- let out = crate::format_text_ui::panel(ui, t, style, None, crate::format_text_ui::Fonts { sources: None, shown });
++ let out = crate::format_text_ui::panel(ui, t, style, None, crate::format_text_ui::Fonts { sources: None, shown }, paragraphs);
+ if let Some(crate::format_text_ui::FontChoice::Family(family)) = out.font {
+ style.family = family;
+ }
+ }
+
+ impl PdfCraftApp {
++ /// Format text changed while added text is being typed in view `index`: the box takes the new
++ /// style at once and stays open. Text already on the page is updated with what has been typed,
++ /// as one undoable change; new text waits until it is finished. Text typed after this styling
++ /// starts from it too.
++ pub(crate) fn restyle_draft(&mut self, index: usize, style: pdfcraft_engine::AddedText) {
++ let Some(view) = self.views.get_mut(index) else { return };
++ // Text the standard fonts can't draw stays in the box, unwritten, until it is corrected (#125).
++ let blocked = view.content.blocked().is_some();
++ let Some(d) = view.content.draft.as_mut() else { return };
++ let committed = d.style.clone();
++ // `text` and `rect` stay what the page has; the rest is the new style.
++ d.style = pdfcraft_engine::AddedText { text: committed.text.clone(), rect: committed.rect, ..style };
++ d.focus = true;
++ self.text_style = pdfcraft_engine::AddedText { text: String::new(), rect: [0.0; 4], aligns: Vec::new(), ..d.style.clone() };
++ let (page, item) = (d.page, d.index);
++ let text = d.text.trim_end().to_string();
++ let Some(item) = item.filter(|_| !text.trim().is_empty() && !blocked) else { return };
++ let aligns = pdfcraft_engine::paragraph_align::remap(&d.text, &text, &d.style.aligns);
++ let updated = pdfcraft_engine::AddedText { text, rect: d.rect, aligns, ..d.style.clone() };
++ if updated == committed {
++ return;
++ }
++ if self.apply_edit(pdfcraft_engine::Edit::UpdateContent { page, index: item, content: pdfcraft_engine::AddedContent::Text(updated.clone()) })
++ && let Some(d) = self.views.get_mut(index).and_then(|v| v.content.draft.as_mut())
++ {
++ // What the page has now. The aligns stay those of the text in the box.
++ d.style = pdfcraft_engine::AddedText { aligns: std::mem::take(&mut d.style.aligns), ..updated };
++ // The page has the box's text: its typing history restarts at the next claim, even
++ // when the restyle left the text as it was, so a Redo can't put undone typing back.
++ d.typing_from = None;
++ }
++ }
++
+ /// Apply the open paragraph's formatting as one change; the paragraph stays open.
+ pub(crate) fn apply_line_format(&mut self, index: usize, mut ed: crate::edit_text_ui::LineEditor, ctx: Option<&egui::Context>) {
+ let edit = pdfcraft_engine::Edit::EditTextBlock { page: ed.page, block: ed.block, text: ed.text.clone(), style: ed.style() };
+ if self.apply_edit(edit) {
+ ed.applied();
+ if let Some(doc) = self.session.get(self.views[index].id)
+ && let Some(block) = doc.text_blocks(ed.page).get(ed.block)
+ {
+ ed.refresh_source(block, doc.text_lines(ed.page));
+ if let Some(ctx) = ctx {
+ ed.fonts = crate::edit_text_ui::install_source_fonts(ctx, doc, ed.page);
+ }
+ }
+ }
+ self.views[index].line_editor = Some(ed);
+ }
+ }
diff --cc crates/ui-egui/src/tools/edit_text_ui.rs
index 793383b99,66daa6edb..f169ace73
--- a/crates/ui-egui/src/tools/edit_text_ui.rs
+++ b/crates/ui-egui/src/tools/edit_text_ui.rs
@@@ -513,335 -204,11 +333,29 @@@ impl LineEditor
self.source_rect = block.rect.map(|v| v as f32);
self.multiline = block.rows.len() > 1;
self.source = Some((block.clone(), lines));
- self.text = block.editor_text.clone();
+ let before = std::mem::replace(&mut self.text, block.editor_text.clone());
+ if self.text != before {
+ // A byte range of the old text: it may name other characters, or none, in the new.
+ self.selection = None;
+ }
+ self.follow_rows(&before);
self.original = self.text.clone();
}
+
+ /// The text changed from `before` through the box's own typing (typing, Undo, Redo): rows
+ /// aligned on their own keep their alignment, and a row Undo brings back gets its own back.
+ pub(crate) fn follow_typed_rows(&mut self, ctx: &egui::Context, before: &str) {
+ follow_typing(ctx, input_id(), before, &self.text, &mut [&mut self.look.aligns, &mut self.look0.aligns]);
+ }
+
+ /// The text changed from `before`: rows aligned on their own keep their alignment.
+ pub(crate) fn follow_rows(&mut self, before: &str) {
+ for look in [&mut self.look, &mut self.look0] {
+ look.aligns = pdfcraft_engine::paragraph_align::remap(before, &self.text, &look.aligns);
+ }
+ }
}
- /// The look shown for a paragraph: the family and weight guessed from its PDF font name.
- fn source_look(base_font: &str, size: f64, color: [f64; 3], detected_bold: bool, detected_italic: bool) -> pdfcraft_engine::AddedText {
- use pdfcraft_engine::FontFamily as F;
- let name = base_font.to_ascii_lowercase();
- let family = if ["courier", "mono", "consolas", "menlo", "monaco", "lucida console"].iter().any(|s| name.contains(s)) {
- F::Courier
- } else if !name.contains("sans") && ["times", "serif", "roman", "cambria", "georgia", "palatino", "garamond"].iter().any(|s| name.contains(s)) {
- F::Times
- } else {
- F::Helvetica
- };
- pdfcraft_engine::AddedText {
- family,
- bold: detected_bold || ["bold", "black", "heavy", "semibold", "demi"].iter().any(|s| name.contains(s)),
- italic: detected_italic || ["italic", "oblique", "slanted"].iter().any(|s| name.contains(s)),
- size: (size * 10.0).round() / 10.0,
- color,
- ..Default::default()
- }
- }
-
- fn look_of(b: &pdfcraft_engine::TextBlock) -> pdfcraft_engine::AddedText {
- source_look(&b.base_font, b.size, b.color, b.bold, b.italic)
- }
-
- pub(crate) fn editor_font(look: &pdfcraft_engine::AddedText, size: f32) -> FontId {
- let family = match (look.family, look.bold) {
- (pdfcraft_engine::FontFamily::Courier, _) => FontFamily::Monospace,
- (_, true) => FontFamily::Name("semibold".into()),
- (_, false) => FontFamily::Proportional,
- };
- FontId::new(size, family)
- }
-
- fn color32(color: [f64; 3]) -> Color32 {
- Color32::from_rgb(
- (color[0].clamp(0.0, 1.0) * 255.0).round() as u8,
- (color[1].clamp(0.0, 1.0) * 255.0).round() as u8,
- (color[2].clamp(0.0, 1.0) * 255.0).round() as u8,
- )
- }
-
- /// The dark box behind text too pale to read on white.
- const DARK_EDITOR_FILL: Color32 = Color32::from_gray(0x26);
-
- /// WCAG relative luminance of an sRGB colour.
- fn luminance(c: Color32) -> f32 {
- let channel = |v: u8| {
- let v = f32::from(v) / 255.0;
- if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
- };
- 0.2126 * channel(c.r()) + 0.7152 * channel(c.g()) + 0.0722 * channel(c.b())
- }
-
- /// WCAG contrast ratio between two colours (1 to 21).
- fn contrast(a: Color32, b: Color32) -> f32 {
- let (la, lb) = (luminance(a), luminance(b));
- (la.max(lb) + 0.05) / (la.min(lb) + 0.05)
- }
-
- /// The inline editor's background for text drawn in `text`: white, or a dark box when the text
- /// reads better on that (white or pale text, which would vanish on white).
- pub(crate) fn editor_fill(text: Color32) -> Color32 {
- if contrast(text, Color32::WHITE) >= contrast(text, DARK_EDITOR_FILL) { Color32::WHITE } else { DARK_EDITOR_FILL }
- }
-
- /// A selected page image, and what the pointer is doing to it.
- #[derive(Clone, Debug, PartialEq)]
- pub struct ImageSelection {
- pub page: usize,
- pub index: usize,
- /// Dragging: the start point and, for a corner, the opposite corner (screen).
- drag: Option<(Pos2, Option<Pos2>)>,
- /// Crop mode (Acrobat's crop handles): the box kept so far.
- pub crop: Option<CropMode>,
- /// The drag is turning the picture by its rotate handle (the `drag` start is then unused).
- turning: bool,
- /// A move or resize applied on release: the frame it had and the one it got, in the page's
- /// 0..1 coordinates, while the page raster still has the picture where it was.
- settled: Option<(Rect, Rect)>,
- }
-
- impl ImageSelection {
- /// Cancel an in-progress text, rotation or crop drag and restore the crop it was previewing.
- pub(crate) fn cancel_pointer_gesture(&mut self) {
- self.drag = None;
- self.turning = false;
- if let Some(crop) = &mut self.crop
- && let Some((_, _, before)) = crop.drag.take()
- {
- crop.keep = before;
- }
- }
- }
-
- /// Cropping a page image: the handles trim instead of resizing, the part that will go is
- /// dimmed, Enter or Done applies and Esc or Cancel leaves it.
- #[derive(Clone, Debug, PartialEq)]
- pub struct CropMode {
- /// The box to keep (user space).
- pub keep: [f64; 4],
- /// A drag in progress: the grip (0–3 corners, 4–7 edges, 8 the inside), where it started
- /// and the box then.
- drag: Option<(usize, Pos2, [f64; 4])>,
- }
-
- impl CropMode {
- pub fn new(keep: [f64; 4]) -> Self {
- Self { keep, drag: None }
- }
- }
-
- /// The screen boxes of the crop's eight handles: corners, then the top, right, bottom and left
- /// edge midpoints.
- fn crop_handles(k: Rect) -> [Pos2; 8] {
- [k.left_top(), k.right_top(), k.left_bottom(), k.right_bottom(), k.center_top(), k.right_center(), k.center_bottom(), k.left_center()]
- }
-
- /// Crop mode for the selected image `i` whose visible frame is `b` (screen). Returns `true`
- /// (the pointer and keys are the crop's while it lasts).
- #[allow(clippy::too_many_arguments)]
- fn crop_input(
- ui: &egui::Ui,
- resp: &egui::Response,
- xf: &PageXform,
- ptr: &PagePointer,
- page: usize,
- info: &DocInfo,
- view: &mut DocView,
- i: usize,
- b: Rect,
- allow_interaction: bool,
- ) -> bool {
- let painter = ui.painter();
- let Some(mode) = view.image_selection.as_mut().and_then(|s| s.crop.as_mut()) else { return false };
- let hover_pos = ptr.pos;
- let keep_screen = |keep: [f64; 4]| xf.user_rect(info, page, keep.map(|v| v as f32)).intersect(b);
- // A drag in progress moves a grip; the box stays inside the picture and at least 6 px.
- if allow_interaction
- && resp.drag_started()
- && let Some(o) = ptr.origin
- {
- let k = keep_screen(mode.keep);
- let grip = crop_handles(k).iter().position(|h| h.distance(o) < 8.0).or_else(|| k.contains(o).then_some(8));
- if let Some(g) = grip {
- mode.drag = Some((g, o, mode.keep));
- }
- }
- if let Some((grip, start, at_start)) = mode.drag
- && let Some(p) = hover_pos
- {
- let d = p - start;
- let k0 = keep_screen(at_start);
- let (mut min, mut max) = (k0.min, k0.max);
- match grip {
- 0 => {
- min.x += d.x;
- min.y += d.y;
- }
- 1 => {
- max.x += d.x;
- min.y += d.y;
- }
- 2 => {
- min.x += d.x;
- max.y += d.y;
- }
- 3 => {
- max.x += d.x;
- max.y += d.y;
- }
- 4 => min.y += d.y,
- 5 => max.x += d.x,
- 6 => max.y += d.y,
- 7 => min.x += d.x,
- _ => {
- let shift = egui::vec2(d.x.clamp(b.min.x - k0.min.x, b.max.x - k0.max.x), d.y.clamp(b.min.y - k0.min.y, b.max.y - k0.max.y));
- min += shift;
- max += shift;
- }
- }
- let (min_w, min_h) = (6.0_f32.min(b.width()), 6.0_f32.min(b.height()));
- min.x = min.x.clamp(b.min.x, b.max.x - min_w);
- min.y = min.y.clamp(b.min.y, b.max.y - min_h);
- max.x = max.x.clamp(min.x + min_w, b.max.x);
- max.y = max.y.clamp(min.y + min_h, b.max.y);
- mode.keep = user_box(xf, info, page, Rect::from_min_max(min, max));
- if resp.drag_stopped() || !ptr.primary_down {
- mode.drag = None;
- }
- }
- let k = keep_screen(mode.keep);
- // What goes is dimmed; what stays keeps its frame and handles.
- let dim = Color32::from_black_alpha(96);
- for r in [
- Rect::from_min_max(b.min, Pos2::new(b.max.x, k.min.y)),
- Rect::from_min_max(Pos2::new(b.min.x, k.max.y), b.max),
- Rect::from_min_max(Pos2::new(b.min.x, k.min.y), Pos2::new(k.min.x, k.max.y)),
- Rect::from_min_max(Pos2::new(k.max.x, k.min.y), Pos2::new(b.max.x, k.max.y)),
- ] {
- if r.is_positive() {
- painter.rect_filled(r.intersect(xf.rect), CornerRadius::ZERO, dim);
- }
- }
- painter.rect_stroke(k, CornerRadius::ZERO, Stroke::new(1.5, ACCENT), egui::StrokeKind::Outside);
- for h in crop_handles(k) {
- painter.rect(
- Rect::from_center_size(h, egui::vec2(8.0, 8.0)),
- CornerRadius::ZERO,
- Color32::WHITE,
- Stroke::new(1.0, ACCENT),
- egui::StrokeKind::Middle,
- );
- }
- // Done and Cancel, painted under the box (above it near the bottom of the view).
- let font = egui::FontId::proportional(12.5);
- let pill = |label: &str, right: f32, y: f32| -> Rect {
- let w = painter.layout_no_wrap(label.to_string(), font.clone(), Color32::WHITE).size().x + 20.0;
- Rect::from_min_size(Pos2::new(right - w, y), egui::vec2(w, 22.0))
- };
- let y = if k.max.y + 30.0 < xf.rect.max.y { k.max.y + 6.0 } else { k.min.y - 28.0 };
- let done = pill(tl!("Done"), k.max.x, y);
- let cancel = pill(tl!("Cancel"), done.min.x - 6.0, y);
- let t = crate::theme::Tokens::get(ui.ctx());
- painter.rect_filled(done, CornerRadius::same(11), ACCENT);
- painter.text(done.center(), egui::Align2::CENTER_CENTER, tl!("Done"), font.clone(), Color32::WHITE);
- painter.rect(cancel, CornerRadius::same(11), t.panel, Stroke::new(1.0, t.border), egui::StrokeKind::Inside);
- painter.text(cancel.center(), egui::Align2::CENTER_CENTER, tl!("Cancel"), font, t.text);
- if let Some(p) = hover_pos {
- let icon = if let Some(g) = crop_handles(k).iter().position(|h| h.distance(p) < 8.0) {
- match g {
- 0 | 3 => egui::CursorIcon::ResizeNwSe,
- 1 | 2 => egui::CursorIcon::ResizeNeSw,
- 4 | 6 => egui::CursorIcon::ResizeVertical,
- _ => egui::CursorIcon::ResizeHorizontal,
- }
- } else if done.contains(p) || cancel.contains(p) {
- egui::CursorIcon::PointingHand
- } else if k.contains(p) {
- egui::CursorIcon::Move
- } else {
- egui::CursorIcon::Default
- };
- ui.ctx().set_cursor_icon(icon);
- }
- let clicked = |r: Rect| allow_interaction && resp.clicked() && hover_pos.is_some_and(|p| r.contains(p));
- let keys = |key: egui::Key| allow_interaction && ui.input(|inp| inp.key_pressed(key)) && !ui.ctx().egui_wants_keyboard_input();
- if clicked(done) || keys(egui::Key::Enter) {
- let keep = mode.keep;
- if let Some(s) = view.image_selection.as_mut() {
- s.crop = None;
- }
- if keep_screen(keep) != b {
- view.pending_edit = Some(Edit::EditPageImage { page, index: i, change: pdfcraft_engine::ImageEdit::Crop(keep) });
- }
- } else if (clicked(cancel) || keys(egui::Key::Escape))
- && let Some(s) = view.image_selection.as_mut()
- {
- s.crop = None;
- }
- true
- }
-
- impl ImageSelection {
- pub(crate) fn dragging(&self) -> bool {
- self.drag.is_some()
- }
- }
-
- /// The page raster's picture of the box `from`, stretched into `to`, over blanks at `blank` (where
- /// the screen may still show the picture).
- fn stretched_picture(painter: &egui::Painter, xf: &PageXform, tex: egui::TextureId, blank: &[Rect], from: Rect, to: Rect) {
- let clipped = painter.with_clip_rect(painter.clip_rect().intersect(xf.rect));
- for r in blank {
- clipped.rect_filled(*r, CornerRadius::ZERO, Color32::WHITE);
- }
- let mut mesh = egui::Mesh::with_texture(tex);
- for (a, b) in [
- (from.left_top(), to.left_top()),
- (from.right_top(), to.right_top()),
- (from.right_bottom(), to.right_bottom()),
- (from.left_bottom(), to.left_bottom()),
- ] {
- let (u, v) = xf.screen_to_norm(a);
- mesh.vertices.push(egui::epaint::Vertex { pos: b, uv: Pos2::new(u, v), color: Color32::WHITE });
- }
- mesh.add_triangle(0, 1, 2);
- mesh.add_triangle(0, 2, 3);
- clipped.add(egui::Shape::mesh(mesh));
- }
-
- /// Once a selected corner or the rotate knob is grabbed, text under it cannot take over the gesture. The same
- /// applies after the pointer leaves the image/page while dragging.
- pub(crate) fn image_owns_pointer(ui: &egui::Ui, xf: &PageXform, ptr: &PagePointer, page: usize, info: &DocInfo, view: &DocView) -> bool {
- let Some(selection) = view.image_selection.as_ref().filter(|s| s.page == page) else { return false };
- if selection.drag.is_some() {
- return true;
- }
- let Some(image) = view.edit_images.get(&page).and_then(|(_, images)| images.get(selection.index)) else { return false };
- let Some(rect) = image.visible_rect else { return false };
- let b = xf.user_rect(info, page, rect.map(|v| v as f32));
- let p = if ptr.primary_down { ptr.origin } else { ptr.pos };
- let knob = rotate_knob(b, ui.clip_rect()).0;
- p.is_some_and(|p| [b.left_top(), b.right_top(), b.left_bottom(), b.right_bottom(), knob].iter().any(|c| c.distance(p) < 8.0))
- }
-
/// What a drag on a paragraph box takes hold of.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Grip {
@@@ -1522,220 -492,8 +640,9 @@@ pub(crate) fn page_input
true
}
- /// One TextEdit lays out all source runs; its caret and selection span the whole region.
- pub(crate) fn install_source_fonts(ctx: &egui::Context, doc: &pdfcraft_engine::Document, page: usize) -> BTreeMap<String, String> {
- let programs = doc.text_editor_fonts(page);
- let mut definitions = ctx.fonts(|f| f.definitions().clone());
- // Only the current editor's document fonts live in the atlas. Never accumulate the
- // programs of previously opened files or add them to the interface's default families.
- definitions.font_data.retain(|name, _| !name.starts_with("pdf-source-"));
- definitions.families.retain(|family, _| !matches!(family, FontFamily::Name(name) if name.starts_with("pdf-source-")));
- let mut families = BTreeMap::new();
- for (index, program) in programs.iter().enumerate() {
- let name = format!("pdf-source-{index}");
- definitions.font_data.insert(name.clone(), Arc::new(egui::FontData::from_owned(program.bytes.clone())));
- families.insert(program.resource.clone(), name);
- }
- for program in &programs {
- let Some(name) = families.get(&program.resource) else { continue };
- // Word-created PDFs often split one face into several subsets. Use all of the
- // document's matching subsets before falling back for newly inserted characters.
- let mut stack = vec![name.clone()];
- stack.extend(
- programs
- .iter()
- .filter(|p| {
- pdfcraft_fonts::embedding::face_key(&p.face) == pdfcraft_fonts::embedding::face_key(&program.face)
- && p.resource != program.resource
- })
- .filter_map(|p| families.get(&p.resource).cloned()),
- );
- if let Some(fallback) = definitions.families.get(&FontFamily::Proportional) {
- stack.extend(fallback.iter().cloned());
- }
- definitions.families.insert(FontFamily::Name(name.clone().into()), stack);
- }
- if !families.is_empty() {
- ctx.set_fonts(definitions);
- }
- families
- }
-
- fn editor_job(ui: &egui::Ui, ed: &LineEditor, text: &str, scale: f32, width: f32) -> egui::text::LayoutJob {
- let mut job = egui::text::LayoutJob::default();
- // An unchanged PDF row already has an authoritative line break. Do not rewrap it
- // because font rounding or a fallback face measures a fraction of a pixel wider.
- job.wrap.max_width = if text == ed.original && ed.look == ed.look0 && ed.extras == ed.extras0 { f32::INFINITY } else { width };
- if let Some((block, lines)) = &ed.source {
- let lefts: Vec<_> = block.rows.iter().filter_map(|r| r.first().and_then(|i| lines.get(*i)).map(|l| l.rect[0])).collect();
- let left_span = lefts.iter().copied().fold(f64::NEG_INFINITY, f64::max) - lefts.iter().copied().fold(f64::INFINITY, f64::min);
- let centered = block.rows.len() > 1
- && left_span > block.size * 0.5
- && block.rows.iter().all(|row| {
- let rect = row
- .iter()
- .filter_map(|i| lines.get(*i))
- .map(|l| l.rect)
- .reduce(|a, b| [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])]);
- rect.is_some_and(|r| ((r[0] + r[2] - block.rect[0] - block.rect[2]) / 2.0).abs() < block.size)
- });
- if centered {
- job.halign = egui::Align::Center;
- }
- for (range, index) in block.edited_spans(text) {
- let Some(line) = lines.get(index) else { continue };
- let mut look = source_look(&line.base_font, line.size, line.color, line.bold, line.italic);
- look.size = line.size;
- if ed.look.family != ed.look0.family || ed.family_chosen {
- look.family = ed.look.family;
- }
- if ed.look.bold != ed.look0.bold {
- look.bold = ed.look.bold;
- }
- if ed.look.italic != ed.look0.italic {
- look.italic = ed.look.italic;
- }
- if ed.look.color != ed.look0.color {
- look.color = ed.look.color;
- }
- if ed.look.size != ed.look0.size {
- look.size = ed.look.size;
- }
- let mut font = editor_font(&look, (look.size as f32 * scale).clamp(1.0, 300.0));
- let original_face =
- ed.look.family == ed.look0.family && !ed.family_chosen && ed.look.bold == ed.look0.bold && ed.look.italic == ed.look0.italic;
- let embedded = original_face && ed.fonts.contains_key(&line.font);
- if embedded && let Some(name) = ed.fonts.get(&line.font) {
- font.family = FontFamily::Name(name.clone().into());
- }
- let native_width = ui.fonts_mut(|f| f.layout_no_wrap(line.text.clone(), font.clone(), Color32::BLACK).size().x);
- let target_width = ((line.rect[2] - line.rect[0]) * look.size / line.size.max(0.01)) as f32 * scale;
- let spacing = if original_face { (target_width - native_width) / line.text.chars().count().saturating_sub(1).max(1) as f32 } else { 0.0 };
- job.append(
- text.get(range).unwrap_or_default(),
- 0.0,
- egui::TextFormat {
- font_id: font,
- extra_letter_spacing: spacing + ed.extras.char_spacing as f32 * scale,
- color: color32(look.color),
- italics: look.italic && !embedded,
- ..Default::default()
- },
- );
- }
- } else {
- job.append(
- text,
- 0.0,
- egui::TextFormat {
- font_id: editor_font(&ed.look, ed.size),
- color: color32(ed.look.color),
- italics: ed.look.italic,
- ..Default::default()
- },
- );
- }
- job
- }
-
- /// `galley` drawn in no colour: its rows still place the caret and the selection.
- fn unseen(mut galley: Arc<egui::Galley>) -> Arc<egui::Galley> {
- for placed in &mut Arc::make_mut(&mut galley).rows {
- for vertex in &mut Arc::make_mut(&mut placed.row).visuals.mesh.vertices {
- vertex.color = Color32::TRANSPARENT;
- }
- }
- galley
- }
-
- /// Align the editable galley's baselines to the source rows instead of egui's interface
- /// leading. Glyphs, meshes, caret and selection receive the same transform.
- fn editor_galley(ui: &egui::Ui, ed: &LineEditor, text: &str, scale: f32, width: f32) -> Arc<egui::Galley> {
- let mut job = editor_job(ui, ed, text, scale, width);
- let centered = job.halign == egui::Align::Center;
- job.halign = egui::Align::LEFT;
- let mut galley = ui.fonts_mut(|fonts| fonts.layout_job(job));
- let Some((block, lines)) = &ed.source else { return galley };
- let sources: Vec<_> = block
- .rows
- .iter()
- .filter_map(|row| {
- let first = row.first().and_then(|i| lines.get(*i))?;
- let rect = row
- .iter()
- .filter_map(|i| lines.get(*i))
- .map(|l| l.rect)
- .reduce(|a, b| [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])])?;
- Some((first.baseline()[1], rect))
- })
- .collect();
- let Some((first_baseline, first_rect)) = sources.first().copied() else { return galley };
- let leading = if ed.extras.line_spacing > 0.0 {
- ed.extras.line_spacing * ed.look.size
- } else {
- let fallback = if block.lines.len() == 1 && !text.contains('\n') {
- block.lines.first().and_then(|i| lines.get(*i)).map_or(block.size * 1.2, |line| line.wrap_leading())
- } else {
- block.size * 1.5
- };
- sources.windows(2).map(|r| (r[0].0 - r[1].0).abs()).rfind(|v| *v > 0.0).unwrap_or(fallback)
- };
- let g = Arc::make_mut(&mut galley);
- let mut bounds = Rect::NOTHING;
- let mut meshes = Rect::NOTHING;
- // Which line of the text (between `\n`s) each row is on: rows aligned on their own go where
- // the rewrite will put them, in the paragraph's width.
- let mut line = 0usize;
- for (index, placed) in g.rows.iter_mut().enumerate() {
- let own = ed.look.aligns.get(line).copied().flatten();
- if placed.ends_with_newline {
- line = line.saturating_add(1);
- }
- let (last_baseline, last_rect) = sources.last().copied().unwrap_or((first_baseline, first_rect));
- let (baseline, source_rect) = sources
- .get(index)
- .copied()
- .unwrap_or((last_baseline - index.saturating_add(1).saturating_sub(sources.len()) as f64 * leading, last_rect));
- let changed_size = ed.look.size != ed.look0.size;
- let ratio = if changed_size { ed.look.size / ed.look0.size.max(0.01) } else { 1.0 };
- let ascent = (source_rect[3] - sources.get(index).map_or(last_baseline, |s| s.0)) as f32 * scale * ratio as f32;
- let descent = (sources.get(index).map_or(last_baseline, |s| s.0) - source_rect[1]) as f32 * scale * ratio as f32;
- let base_y = (block.rect[3] - baseline) as f32 * scale;
- let row = Arc::make_mut(&mut placed.row);
- placed.pos.y = base_y - ascent;
- let free = (width - row.size.x).max(0.0);
- placed.pos.x = match own {
- Some(pdfcraft_engine::TextAlign::Center) => free / 2.0,
- Some(pdfcraft_engine::TextAlign::Right) => free,
- Some(pdfcraft_engine::TextAlign::Left | pdfcraft_engine::TextAlign::Justify) => 0.0,
- None if centered => (width - row.size.x) / 2.0,
- None => (source_rect[0] - block.rect[0]) as f32 * scale,
- };
- for glyph in &mut row.glyphs {
- let dy = ascent - glyph.pos.y;
- glyph.pos.y = ascent;
- glyph.font_ascent = ascent;
- glyph.font_height = ascent + descent;
- glyph.line_height = ascent + descent;
- if !glyph.uv_rect.is_nothing() {
- for vertex in row.visuals.mesh.vertices.iter_mut().skip(glyph.first_vertex as usize).take(4) {
- vertex.pos.y += dy;
- }
- }
- }
- row.size.y = (ascent + descent).max(1.0);
- row.visuals.mesh_bounds = row.visuals.mesh.vertices.iter().fold(Rect::NOTHING, |r, v| r.union(Rect::from_min_max(v.pos, v.pos)));
- bounds = bounds.union(Rect::from_min_size(placed.pos, row.size));
- meshes = meshes.union(row.visuals.mesh_bounds.translate(placed.pos.to_vec2()));
- }
- g.rect = Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(bounds.right().max(0.0), bounds.bottom().max(0.0)));
- g.mesh_bounds = meshes;
- galley
- }
-
/// The inline editor; returns the edit once the text is applied.
pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView, info: &DocInfo) -> Option<Edit> {
+ let view_id = view.id;
// Clicks outside the document (the Format text panel) keep the paragraph open. Where the
// click landed is `interact_pos`: `latest_pos` is gone on the frame a tap lifts.
let outside = ctx.input(|i| i.pointer.interact_pos()).is_some_and(|p| !view.viewport_rect().contains(p));
diff --cc crates/ui-egui/src/tools/edit_text_ui/layout.rs
index 000000000,a59c10899..966e0c6a8
mode 000000,100644..100644
--- a/crates/ui-egui/src/tools/edit_text_ui/layout.rs
+++ b/crates/ui-egui/src/tools/edit_text_ui/layout.rs
@@@ -1,0 -1,270 +1,284 @@@
+ use super::*;
+
+ /// The look shown for a paragraph: the family and weight guessed from its PDF font name.
+ fn source_look(base_font: &str, size: f64, color: [f64; 3], detected_bold: bool, detected_italic: bool) -> pdfcraft_engine::AddedText {
+ use pdfcraft_engine::FontFamily as F;
+ let name = base_font.to_ascii_lowercase();
+ let family = if ["courier", "mono", "consolas", "menlo", "monaco", "lucida console"].iter().any(|s| name.contains(s)) {
+ F::Courier
+ } else if !name.contains("sans") && ["times", "serif", "roman", "cambria", "georgia", "palatino", "garamond"].iter().any(|s| name.contains(s)) {
+ F::Times
+ } else {
+ F::Helvetica
+ };
+ pdfcraft_engine::AddedText {
+ family,
+ bold: detected_bold || ["bold", "black", "heavy", "semibold", "demi"].iter().any(|s| name.contains(s)),
+ italic: detected_italic || ["italic", "oblique", "slanted"].iter().any(|s| name.contains(s)),
+ size: (size * 10.0).round() / 10.0,
+ color,
+ ..Default::default()
+ }
+ }
+
+ pub(super) fn look_of(b: &pdfcraft_engine::TextBlock) -> pdfcraft_engine::AddedText {
+ source_look(&b.base_font, b.size, b.color, b.bold, b.italic)
+ }
+
+ pub(crate) fn editor_font(look: &pdfcraft_engine::AddedText, size: f32) -> FontId {
+ let family = match (look.family, look.bold) {
+ (pdfcraft_engine::FontFamily::Courier, _) => FontFamily::Monospace,
+ (_, true) => FontFamily::Name("semibold".into()),
+ (_, false) => FontFamily::Proportional,
+ };
+ FontId::new(size, family)
+ }
+
+ pub(super) fn color32(color: [f64; 3]) -> Color32 {
+ Color32::from_rgb(
+ (color[0].clamp(0.0, 1.0) * 255.0).round() as u8,
+ (color[1].clamp(0.0, 1.0) * 255.0).round() as u8,
+ (color[2].clamp(0.0, 1.0) * 255.0).round() as u8,
+ )
+ }
+
+ /// The dark box behind text too pale to read on white.
+ pub(super) const DARK_EDITOR_FILL: Color32 = Color32::from_gray(0x26);
+
+ /// WCAG relative luminance of an sRGB colour.
+ pub(super) fn luminance(c: Color32) -> f32 {
+ let channel = |v: u8| {
+ let v = f32::from(v) / 255.0;
+ if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
+ };
+ 0.2126 * channel(c.r()) + 0.7152 * channel(c.g()) + 0.0722 * channel(c.b())
+ }
+
+ /// WCAG contrast ratio between two colours (1 to 21).
+ pub(super) fn contrast(a: Color32, b: Color32) -> f32 {
+ let (la, lb) = (luminance(a), luminance(b));
+ (la.max(lb) + 0.05) / (la.min(lb) + 0.05)
+ }
+
+ /// The inline editor's background for text drawn in `text`: white, or a dark box when the text
+ /// reads better on that (white or pale text, which would vanish on white).
+ pub(crate) fn editor_fill(text: Color32) -> Color32 {
+ if contrast(text, Color32::WHITE) >= contrast(text, DARK_EDITOR_FILL) { Color32::WHITE } else { DARK_EDITOR_FILL }
+ }
+
+ /// One TextEdit lays out all source runs; its caret and selection span the whole region.
+ pub(crate) fn install_source_fonts(ctx: &egui::Context, doc: &pdfcraft_engine::Document, page: usize) -> BTreeMap<String, String> {
+ let programs = doc.text_editor_fonts(page);
+ let mut definitions = ctx.fonts(|f| f.definitions().clone());
+ // Only the current editor's document fonts live in the atlas. Never accumulate the
+ // programs of previously opened files or add them to the interface's default families.
+ definitions.font_data.retain(|name, _| !name.starts_with("pdf-source-"));
+ definitions.families.retain(|family, _| !matches!(family, FontFamily::Name(name) if name.starts_with("pdf-source-")));
+ let mut families = BTreeMap::new();
+ for (index, program) in programs.iter().enumerate() {
+ let name = format!("pdf-source-{index}");
+ definitions.font_data.insert(name.clone(), Arc::new(egui::FontData::from_owned(program.bytes.clone())));
+ families.insert(program.resource.clone(), name);
+ }
+ for program in &programs {
+ let Some(name) = families.get(&program.resource) else { continue };
+ // Word-created PDFs often split one face into several subsets. Use all of the
+ // document's matching subsets before falling back for newly inserted characters.
+ let mut stack = vec![name.clone()];
+ stack.extend(
+ programs
+ .iter()
+ .filter(|p| {
+ pdfcraft_fonts::embedding::face_key(&p.face) == pdfcraft_fonts::embedding::face_key(&program.face)
+ && p.resource != program.resource
+ })
+ .filter_map(|p| families.get(&p.resource).cloned()),
+ );
+ if let Some(fallback) = definitions.families.get(&FontFamily::Proportional) {
+ stack.extend(fallback.iter().cloned());
+ }
+ definitions.families.insert(FontFamily::Name(name.clone().into()), stack);
+ }
+ if !families.is_empty() {
+ ctx.set_fonts(definitions);
+ }
+ families
+ }
+
+ pub(super) fn editor_job(ui: &egui::Ui, ed: &LineEditor, text: &str, scale: f32, width: f32) -> egui::text::LayoutJob {
+ let mut job = egui::text::LayoutJob::default();
+ // An unchanged PDF row already has an authoritative line break. Do not rewrap it
+ // because font rounding or a fallback face measures a fraction of a pixel wider.
+ job.wrap.max_width = if text == ed.original && ed.look == ed.look0 && ed.extras == ed.extras0 { f32::INFINITY } else { width };
+ if let Some((block, lines)) = &ed.source {
+ let lefts: Vec<_> = block.rows.iter().filter_map(|r| r.first().and_then(|i| lines.get(*i)).map(|l| l.rect[0])).collect();
+ let left_span = lefts.iter().copied().fold(f64::NEG_INFINITY, f64::max) - lefts.iter().copied().fold(f64::INFINITY, f64::min);
+ let centered = block.rows.len() > 1
+ && left_span > block.size * 0.5
+ && block.rows.iter().all(|row| {
+ let rect = row
+ .iter()
+ .filter_map(|i| lines.get(*i))
+ .map(|l| l.rect)
+ .reduce(|a, b| [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])]);
+ rect.is_some_and(|r| ((r[0] + r[2] - block.rect[0] - block.rect[2]) / 2.0).abs() < block.size)
+ });
+ if centered {
+ job.halign = egui::Align::Center;
+ }
+ for (range, index) in block.edited_spans(text) {
+ let Some(line) = lines.get(index) else { continue };
+ let mut look = source_look(&line.base_font, line.size, line.color, line.bold, line.italic);
+ look.size = line.size;
+ if ed.look.family != ed.look0.family || ed.family_chosen {
+ look.family = ed.look.family;
+ }
+ if ed.look.bold != ed.look0.bold {
+ look.bold = ed.look.bold;
+ }
+ if ed.look.italic != ed.look0.italic {
+ look.italic = ed.look.italic;
+ }
+ if ed.look.color != ed.look0.color {
+ look.color = ed.look.color;
+ }
+ if ed.look.size != ed.look0.size {
+ look.size = ed.look.size;
+ }
+ let mut font = editor_font(&look, (look.size as f32 * scale).clamp(1.0, 300.0));
+ let original_face =
+ ed.look.family == ed.look0.family && !ed.family_chosen && ed.look.bold == ed.look0.bold && ed.look.italic == ed.look0.italic;
+ let embedded = original_face && ed.fonts.contains_key(&line.font);
+ if embedded && let Some(name) = ed.fonts.get(&line.font) {
+ font.family = FontFamily::Name(name.clone().into());
+ }
+ let native_width = ui.fonts_mut(|f| f.layout_no_wrap(line.text.clone(), font.clone(), Color32::BLACK).size().x);
+ let target_width = ((line.rect[2] - line.rect[0]) * look.size / line.size.max(0.01)) as f32 * scale;
+ let spacing = if original_face { (target_width - native_width) / line.text.chars().count().saturating_sub(1).max(1) as f32 } else { 0.0 };
+ job.append(
+ text.get(range).unwrap_or_default(),
+ 0.0,
+ egui::TextFormat {
+ font_id: font,
+ extra_letter_spacing: spacing + ed.extras.char_spacing as f32 * scale,
+ color: color32(look.color),
+ italics: look.italic && !embedded,
+ ..Default::default()
+ },
+ );
+ }
+ } else {
+ job.append(
+ text,
+ 0.0,
+ egui::TextFormat {
+ font_id: editor_font(&ed.look, ed.size),
+ color: color32(ed.look.color),
+ italics: ed.look.italic,
+ ..Default::default()
+ },
+ );
+ }
+ job
+ }
+
+ /// `galley` drawn in no colour: its rows still place the caret and the selection.
+ pub(super) fn unseen(mut galley: Arc<egui::Galley>) -> Arc<egui::Galley> {
+ for placed in &mut Arc::make_mut(&mut galley).rows {
+ for vertex in &mut Arc::make_mut(&mut placed.row).visuals.mesh.vertices {
+ vertex.color = Color32::TRANSPARENT;
+ }
+ }
+ galley
+ }
+
+ /// Align the editable galley's baselines to the source rows instead of egui's interface
+ /// leading. Glyphs, meshes, caret and selection receive the same transform.
+ pub(super) fn editor_galley(ui: &egui::Ui, ed: &LineEditor, text: &str, scale: f32, width: f32) -> Arc<egui::Galley> {
+ let mut job = editor_job(ui, ed, text, scale, width);
+ let centered = job.halign == egui::Align::Center;
+ job.halign = egui::Align::LEFT;
+ let mut galley = ui.fonts_mut(|fonts| fonts.layout_job(job));
+ let Some((block, lines)) = &ed.source else { return galley };
+ let sources: Vec<_> = block
+ .rows
+ .iter()
+ .filter_map(|row| {
+ let first = row.first().and_then(|i| lines.get(*i))?;
+ let rect = row
+ .iter()
+ .filter_map(|i| lines.get(*i))
+ .map(|l| l.rect)
+ .reduce(|a, b| [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])])?;
+ Some((first.baseline()[1], rect))
+ })
+ .collect();
+ let Some((first_baseline, first_rect)) = sources.first().copied() else { return galley };
+ let leading = if ed.extras.line_spacing > 0.0 {
+ ed.extras.line_spacing * ed.look.size
+ } else {
+ let fallback = if block.lines.len() == 1 && !text.contains('\n') {
+ block.lines.first().and_then(|i| lines.get(*i)).map_or(block.size * 1.2, |line| line.wrap_leading())
+ } else {
+ block.size * 1.5
+ };
+ sources.windows(2).map(|r| (r[0].0 - r[1].0).abs()).rfind(|v| *v > 0.0).unwrap_or(fallback)
+ };
+ let g = Arc::make_mut(&mut galley);
+ let mut bounds = Rect::NOTHING;
+ let mut meshes = Rect::NOTHING;
++ // Which line of the text (between `\n`s) each row is on: rows aligned on their own go where
++ // the rewrite will put them, in the paragraph's width.
++ let mut line = 0usize;
+ for (index, placed) in g.rows.iter_mut().enumerate() {
++ let own = ed.look.aligns.get(line).copied().flatten();
++ if placed.ends_with_newline {
++ line = line.saturating_add(1);
++ }
+ let (last_baseline, last_rect) = sources.last().copied().unwrap_or((first_baseline, first_rect));
+ let (baseline, source_rect) = sources
+ .get(index)
+ .copied()
+ .unwrap_or((last_baseline - index.saturating_add(1).saturating_sub(sources.len()) as f64 * leading, last_rect));
+ let changed_size = ed.look.size != ed.look0.size;
+ let ratio = if changed_size { ed.look.size / ed.look0.size.max(0.01) } else { 1.0 };
+ let ascent = (source_rect[3] - sources.get(index).map_or(last_baseline, |s| s.0)) as f32 * scale * ratio as f32;
+ let descent = (sources.get(index).map_or(last_baseline, |s| s.0) - source_rect[1]) as f32 * scale * ratio as f32;
+ let base_y = (block.rect[3] - baseline) as f32 * scale;
+ let row = Arc::make_mut(&mut placed.row);
+ placed.pos.y = base_y - ascent;
- placed.pos.x = if centered { (width - row.size.x) / 2.0 } else { (source_rect[0] - block.rect[0]) as f32 * scale };
++ let free = (width - row.size.x).max(0.0);
++ placed.pos.x = match own {
++ Some(pdfcraft_engine::TextAlign::Center) => free / 2.0,
++ Some(pdfcraft_engine::TextAlign::Right) => free,
++ Some(pdfcraft_engine::TextAlign::Left | pdfcraft_engine::TextAlign::Justify) => 0.0,
++ None if centered => (width - row.size.x) / 2.0,
++ None => (source_rect[0] - block.rect[0]) as f32 * scale,
++ };
+ for glyph in &mut row.glyphs {
+ let dy = ascent - glyph.pos.y;
+ glyph.pos.y = ascent;
+ glyph.font_ascent = ascent;
+ glyph.font_height = ascent + descent;
+ glyph.line_height = ascent + descent;
+ if !glyph.uv_rect.is_nothing() {
+ for vertex in row.visuals.mesh.vertices.iter_mut().skip(glyph.first_vertex as usize).take(4) {
+ vertex.pos.y += dy;
+ }
+ }
+ }
+ row.size.y = (ascent + descent).max(1.0);
+ row.visuals.mesh_bounds = row.visuals.mesh.vertices.iter().fold(Rect::NOTHING, |r, v| r.union(Rect::from_min_max(v.pos, v.pos)));
+ bounds = bounds.union(Rect::from_min_size(placed.pos, row.size));
+ meshes = meshes.union(row.visuals.mesh_bounds.translate(placed.pos.to_vec2()));
+ }
+ g.rect = Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(bounds.right().max(0.0), bounds.bottom().max(0.0)));
+ g.mesh_bounds = meshes;
+ galley
+ }
+
+ /// Caret colour that stays visible on a field filled with `fill`: black on light fills, white on dark ones.
+ pub(crate) fn caret_color_on(fill: Color32) -> Color32 {
+ let luma = 299 * u32::from(fill.r()) + 587 * u32::from(fill.g()) + 114 * u32::from(fill.b());
+ if luma > 127_500 { Color32::BLACK } else { Color32::WHITE }
+ }