mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-28 14:19:22 -08:00
Merge main into #2712
Conflict resolution: contributors/people.toml keep-both again (the PR's [people.marcoarnulfo] entry and main's new [people.gmrmad1] entry).
This commit is contained in:
commit
6c2316ba15
38 files changed
+2738
-199
No files matched your search
@@ -264,6 +264,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
| 8 | 1.0 polish: performance, right-to-left, missing languages, keyboard-only (M14) | 55–95 |
|
||||
|
||||
## Progress log
|
||||
- **2026-10-16 (M4, Insert from File):** Catalog attachments come along with inserted pages in the same undo step. Existing attachments and destination name trees stay; duplicate UTF-16 keys keep their encoding. Generated engine regressions cover save/undo/redo and failed-batch rollback. Estimates unchanged.
|
||||
|
||||
- **2026-11-16 (M5, #3741):** Ctrl+M opens Comments on Windows/Linux and repeated activation keeps it open. macOS leaves Command+M unbound for Minimize. Dispatch, menus, palette, shortcut help and control/headless metadata resolve the platform-specific registry binding. Mapping and real-input regressions are retained through the rebase; estimates unchanged.
|
||||
- **2026-11-03 (M3, #3669):** A drag across a table selects its rows, as Preview does, instead of reading order's detour down each column; a cell padded with spaces reads with the next cell of its row. Synthetic render and UI drag regressions; estimates unchanged.
|
||||
@@ -425,6 +426,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
- **2026-10-13 (M10, OCR review, batch and two engines):** Scan & OCR gains a review step, a second engine and Unicode output. Recognition can clean the raster first (opt-in auto-rotate, deskew, denoise, binarize; word boxes map back to the scan) and read with the built-in ocrs engine, an installed tesseract program run as a fenced external process (a validated location that fails closed instead of falling back to the PATH, allow-listed languages, a private temp directory, timeout and output caps), or both: Automatic asks tesseract when the ocrs reading is weak or of unknown confidence, and a ROVER merge keeps the more confident word (an unscored ocrs word yields only to a tesseract word of 70 or more). The OCR Verify screen (Scan & OCR ▸ Correct recognized text) reviews a recognition before it is applied: confidence-coloured word boxes, corrections, a per-language user dictionary (a plain-text file in the preferences folder, so a word added from any document stays on disk after it closes), Re-OCR of a page or a region, Accept/Reject per page or whole. Pages accepted one by one each apply once; a region re-read moves the review marks of the words it keeps, and a whole-page re-read clears that page's marks (undoable in the panel). Output is searchable (an invisible layer, one undo step) or a NEW editable document of visible text. Words beyond WinAnsi are drawn in Type3 faces from craft-fonts with a ToUnicode map in the editable output (characters no bundled face has appear as '?'); the searchable layer writes them as Type3 fonts with empty character programs and a ToUnicode map, so extraction reads them back with no fonts and no substitutions; redaction removes that layer like any other text (tests in pdfcraft-redact; the end-to-end engine test needs the craft-fonts build input and is skipped without it). Batch runs skip pages that already have text unless forced, and skip whole files that have text only with the opt-in skip-files flag (off by default; Force OCR overrides both); they refuse two inputs of the same file name and existing outputs before reading anything, and report low-confidence pages at the settings' threshold. Headless: ocr_recognize (engine, strategy, preprocessing, region; the editable output goes to an `out` that must not exist yet, and `out` is refused for a searchable run), ocr_words, ocr_review_apply, ocr_dictionary, ocr_status and ocr_recognize_files. All 21 interface catalogs carry the new strings; the Lithuanian ones were added without native review. Reading with every cleaning step off passes the render through untouched, as on main (the 300 dpi normalization runs only when a cleaning step is on: enlarging a 72 dpi render 4x on its own made the models read "due: €250" as "ue: ?250"). Still missing: the deep scan clean-up options (descreen, background and edge-shadow removal), scan images in the editable output, matching the scanned typeface, and recognition quality beyond the tested English set.
|
||||
- **2026-10-13 (M10, #1757):** Office export keeps each dotted-leader contents entry in one paragraph, with its page number, instead of inferring table cells from its separate text objects.
|
||||
- **2026-10-22 (M6, calculation scripts):** The Calculate tab and a rename read simplified field notation only from a comment, where Acrobat writes it: a string that spells `BVCALC … EVCALC` is no longer taken for the notation, or rewritten by a rename. A `/` after the condition of `if`, `while`, `for` or `with` starts a regular expression, so a rename no longer rewrites a name inside one, and a quote inside one no longer hides the `getField` calls after it. Both found in review of #3550. A `//` comment ends at `\r`, U+2028 or U+2029 as well as `\n`, so in a script with `\r` line endings the code after one is no longer hidden from a rename, or taken for the notation. Estimates unchanged.
|
||||
- **2026-10-21 (M3, startup notification on Linux):** Opened from the menu or dock with `StartupNotify=true`, PdfCraft hands the launcher's activation token back from its first window (`XDG_ACTIVATION_TOKEN` on Wayland, `DESKTOP_STARTUP_ID` on X11). GNOME kept its busy cursor for 15 seconds after the window appeared, because eframe never gives winit the token, and the window opened without keyboard focus. Vendored winit patch 14, with unit tests of the policy (later windows don't reuse the spent token; an empty or oversized token is ignored). Checked by hand in a test build on GNOME 50 (Wayland): the busy cursor clears as the window appears, and the window has keyboard focus. Estimates unchanged.
|
||||
- **2026-10-20 (M6, calculation order page):** Prepare a form ▸ Calculation order, a page of its own, lists the calculated fields in the order they calculate with their formulas and values, moved with Up/Down arrows (as Acrobat's Set Field Calculation Order), Alt+↑/↓ or by dragging. A card says what is wrong with the order and holds Fix order; a loop has a card of its own that opens one of its formulas. On the page, each calculated field shows its step, and arrows show what the field in focus reads and what reads it. Estimates unchanged.
|
||||
- **2026-10-20 (M6, calculation order):** The order a form's fields calculate in (`/CO`) is read, checked, fixed and set headlessly with `form_calculation_order`: it says which fields read one calculated later (they show stale values), which read each other in a loop, and which the PDF's order leaves out; Fix order moves only what must move, in one undo step, and the form recalculates. Editing a formula no longer moves its field to the end of the order, and a field the order lists twice calculates once. Estimates unchanged.
|
||||
- **2026-10-20 (M2, #3574):** Forms without Resources use page Properties for ActualText and layer visibility. Synthetic tests cover boundaries, nested/shared forms, and save/reopen. Estimates unchanged.
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
//! vendor/winit patch (14) (vendor/README.md).
|
||||
|
||||
#[test]
|
||||
fn winit_hands_the_launchers_activation_token_back() {
|
||||
// A launcher with `StartupNotify=true` (the packaged desktop entry) passes an activation token
|
||||
// in `XDG_ACTIVATION_TOKEN` (Wayland) or `DESKTOP_STARTUP_ID` (X11) and shows a busy cursor
|
||||
// until a window hands it back. eframe never gives winit a token, so GNOME kept the busy
|
||||
// cursor for 15 seconds and the window opened without focus. vendor/winit gives the first
|
||||
// window the environment's token. The policy is tested beside it (`startup_token::tests`, run
|
||||
// them in the vendored crate); this guards the copy, which workspace tests don't test. A
|
||||
// re-vendored copy without the patch would silently bring the bug back: re-apply the patch, or
|
||||
// drop the copy once winit or eframe hands the token back.
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let linux = root.join("vendor/winit/src/platform_impl/linux");
|
||||
let module = std::fs::read_to_string(linux.join("mod.rs")).unwrap();
|
||||
assert!(module.contains("mod startup_token;"));
|
||||
let (_, new) = module.split_once(" pub(crate) fn new(\n window_target: &ActiveEventLoop,").expect("Window::new moved");
|
||||
let new = new.split_once("\n }\n").map_or(new, |(body, _)| body);
|
||||
assert!(
|
||||
new.contains("startup_token::for_new_window(given, startup_notify::WAYLAND_VAR)"),
|
||||
"a Wayland window no longer takes the launcher's token"
|
||||
);
|
||||
assert!(new.contains("startup_token::for_new_window(given, startup_notify::X11_VAR)"), "an X11 window no longer takes the launcher's token");
|
||||
assert_eq!(new.matches("reservation.commit();").count(), 2, "a created window no longer spends the launcher's token");
|
||||
// The backends mark the token spent where they hand it back, so a window that fails earlier
|
||||
// releases it for a retry and one that fails later doesn't reuse it.
|
||||
for backend in ["wayland/window/mod.rs", "x11/window.rs"] {
|
||||
let source = std::fs::read_to_string(linux.join(backend)).unwrap();
|
||||
assert!(source.contains("startup_token::handing_back();"), "{backend} no longer marks the token spent at its handoff");
|
||||
}
|
||||
let policy = std::fs::read_to_string(linux.join("startup_token.rs")).unwrap();
|
||||
assert!(policy.contains("fn the_first_window_takes_the_launchers_token"));
|
||||
assert!(policy.contains("fn a_later_window_does_not_reuse_the_spent_token"));
|
||||
assert!(policy.contains("fn a_window_that_fails_before_handing_the_token_back_releases_it"));
|
||||
// The token reaches the app only when the launcher asks for startup notification.
|
||||
let desktop = std::fs::read_to_string(root.join("packaging/linux/ai.storyteller.pdfcraft.desktop")).unwrap();
|
||||
assert!(desktop.contains("StartupNotify=true"));
|
||||
}
|
||||
@@ -202,3 +202,6 @@ sync_github_name = true
|
||||
real_name = "Marco Arnulfo"
|
||||
display_name = "Marco Arnulfo"
|
||||
sync_github_name = false
|
||||
|
||||
[people.gmrmad1]
|
||||
real_name = "Madhav Agarwal"
|
||||
+134
-48
@@ -2,7 +2,10 @@
|
||||
//!
|
||||
//! Each text object becomes a paragraph, or a heading when its size or weight sets it apart from
|
||||
//! the body text ([`crate::autotag_roles`]); either can be retagged with the existing tag-property
|
||||
//! tool after human review. Painted paths, shadings and images outside text objects
|
||||
//! tool after human review. Running headers, footers and page numbers, found by repetition across
|
||||
//! the pages ([`crate::autotag_running`]), are wrapped in
|
||||
//! `/Artifact <</Type /Pagination /Subtype /Header>> BDC … EMC` (or `/Footer`) instead of being
|
||||
//! tagged. Painted paths, shadings and images outside text objects
|
||||
//! are wrapped in `/Artifact BMC … EMC` so the resulting page passes the tagged-content check.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
@@ -11,6 +14,7 @@ use pdfcraft_content::{Op, Pieces, serialize_ops};
|
||||
use pdfcraft_cos::{DecodeBudget, Dict, Document, ObjRef, Object, Stream};
|
||||
|
||||
use crate::autotag_roles::{self, Evidence};
|
||||
use crate::autotag_running::{self, Edge, Frame, PageText};
|
||||
|
||||
const MAX_PAGES: usize = 1_000;
|
||||
const MAX_PAGE_BYTES: usize = 16 * 1024 * 1024;
|
||||
@@ -26,6 +30,21 @@ pub struct AutoTagResult {
|
||||
pub pages: usize,
|
||||
pub paragraphs: usize,
|
||||
pub headings: usize,
|
||||
/// Text objects marked as running header artifacts.
|
||||
pub headers: usize,
|
||||
/// Text objects marked as running footer artifacts, page numbers included.
|
||||
pub footers: usize,
|
||||
}
|
||||
|
||||
/// A text object auto-tag marks as a running header or footer instead of tagging it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct RunningText {
|
||||
/// 0-based page index.
|
||||
pub page: usize,
|
||||
/// `"Header"` or `"Footer"`, the artifact subtype written.
|
||||
pub subtype: &'static str,
|
||||
/// The text shown, at most 256 characters.
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq)]
|
||||
@@ -50,6 +69,14 @@ struct Plan {
|
||||
spans: Vec<(usize, usize)>,
|
||||
evidence: Vec<Evidence>,
|
||||
artifacts: HashMap<usize, usize>,
|
||||
frame: Frame,
|
||||
}
|
||||
|
||||
/// What a text object's span is wrapped in.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Mark {
|
||||
Tag(usize, &'static str),
|
||||
Running(Edge),
|
||||
}
|
||||
|
||||
fn unsupported(page: usize, reason: impl Into<String>) -> AutoTagError {
|
||||
@@ -269,7 +296,8 @@ fn plan_page(
|
||||
}
|
||||
let resources = page_fonts(doc, &page.dict);
|
||||
let evidence = autotag_roles::evidence(doc, fonts, &resources, &parsed.ops, &spans);
|
||||
Ok(Plan { page: page.obj, ops: parsed.ops, spans, evidence, artifacts })
|
||||
let frame = Frame { rotation: page.rotation(doc), crop: page.crop(doc) };
|
||||
Ok(Plan { page: page.obj, ops: parsed.ops, spans, evidence, artifacts, frame })
|
||||
}
|
||||
|
||||
fn plan(doc: &Document) -> Result<Vec<Plan>, AutoTagError> {
|
||||
@@ -301,21 +329,26 @@ fn plan(doc: &Document) -> Result<Vec<Plan>, AutoTagError> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn mark_ops(
|
||||
ops: Vec<Op>,
|
||||
starts: &HashMap<usize, (usize, &'static str)>,
|
||||
ends: &HashSet<usize>,
|
||||
artifacts: &HashMap<usize, usize>,
|
||||
) -> Result<Vec<Op>, AutoTagError> {
|
||||
fn mark_ops(ops: Vec<Op>, starts: &HashMap<usize, Mark>, ends: &HashSet<usize>, artifacts: &HashMap<usize, usize>) -> Result<Vec<Op>, AutoTagError> {
|
||||
let artifact_ends: HashSet<usize> = artifacts.values().copied().collect();
|
||||
let extra = starts.len().saturating_add(artifacts.len()).saturating_mul(2);
|
||||
let mut marked = Vec::with_capacity(ops.len().saturating_add(extra));
|
||||
for (at, op) in ops.into_iter().enumerate() {
|
||||
let is_artifact = artifacts.contains_key(&at);
|
||||
if let Some(&(mcid, role)) = starts.get(&at) {
|
||||
if let Some(&mark) = starts.get(&at) {
|
||||
let mut properties = Dict::new();
|
||||
properties.set(b"MCID".to_vec(), Object::Int(i64::try_from(mcid).map_err(|_| AutoTagError::TooManyPages)?));
|
||||
marked.push(Op::new("BDC", vec![Object::name(role), Object::Dict(properties)]));
|
||||
let tag = match mark {
|
||||
Mark::Tag(mcid, role) => {
|
||||
properties.set(b"MCID".to_vec(), Object::Int(i64::try_from(mcid).map_err(|_| AutoTagError::TooManyPages)?));
|
||||
role
|
||||
}
|
||||
Mark::Running(edge) => {
|
||||
properties.set(b"Type".to_vec(), Object::name("Pagination"));
|
||||
properties.set(b"Subtype".to_vec(), Object::name(edge.subtype()));
|
||||
"Artifact"
|
||||
}
|
||||
};
|
||||
marked.push(Op::new("BDC", vec![Object::name(tag), Object::Dict(properties)]));
|
||||
} else if is_artifact {
|
||||
marked.push(Op::new("BMC", vec![Object::name("Artifact")]));
|
||||
}
|
||||
@@ -361,54 +394,107 @@ fn write_structure(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Tag every text object in an untagged PDF as a paragraph or a heading and mark painted paths, shadings and
|
||||
/// The edge each planned text object repeats at, for running text, per page and span.
|
||||
fn running(plans: &[Plan]) -> Vec<Vec<Option<Edge>>> {
|
||||
let pages: Vec<PageText<'_>> = plans.iter().map(|p| PageText { frame: p.frame, objects: &p.evidence }).collect();
|
||||
autotag_running::find(&pages, autotag_roles::body_size(plans.iter().flat_map(|p| &p.evidence)))
|
||||
}
|
||||
|
||||
/// The running headers, footers and page numbers [`autotag_text`] would mark as artifacts, in page
|
||||
/// order. Refuses what `autotag_text` refuses, and changes nothing.
|
||||
pub fn running_text(doc: &Document) -> Result<Vec<RunningText>, AutoTagError> {
|
||||
let plans = plan(doc)?;
|
||||
let mut out = Vec::new();
|
||||
for (page, (plan, edges)) in plans.iter().zip(running(&plans)).enumerate() {
|
||||
for (evidence, edge) in plan.evidence.iter().zip(edges) {
|
||||
if let Some(edge) = edge {
|
||||
out.push(RunningText { page, subtype: edge.subtype(), text: evidence.text.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// What [`autotag_text`] has written so far.
|
||||
struct Written {
|
||||
children: Vec<Object>,
|
||||
numbers: Vec<Object>,
|
||||
result: AutoTagResult,
|
||||
}
|
||||
|
||||
/// Tag or mark one page's text objects, and write its marked content.
|
||||
fn tag_page(
|
||||
next: &mut Document,
|
||||
document: ObjRef,
|
||||
page: Plan,
|
||||
edges: &[Option<Edge>],
|
||||
roles: &mut impl Iterator<Item = &'static str>,
|
||||
written: &mut Written,
|
||||
) -> Result<(), AutoTagError> {
|
||||
let (mut starts, mut ends, mut parents) = (HashMap::new(), HashSet::new(), Vec::new());
|
||||
let key = i64::try_from(written.result.pages).map_err(|_| AutoTagError::TooManyPages)?;
|
||||
for (at, &(first, last)) in page.spans.iter().enumerate() {
|
||||
ends.insert(last);
|
||||
if let Some(edge) = edges.get(at).copied().flatten() {
|
||||
starts.insert(first, Mark::Running(edge));
|
||||
let count = if edge == Edge::Top { &mut written.result.headers } else { &mut written.result.footers };
|
||||
*count = count.saturating_add(1);
|
||||
continue;
|
||||
}
|
||||
let role = roles.next().unwrap_or("P");
|
||||
let mcid = parents.len();
|
||||
let mut element = Dict::new();
|
||||
element.set(b"Type".to_vec(), Object::name("StructElem"));
|
||||
element.set(b"S".to_vec(), Object::name(role));
|
||||
element.set(b"P".to_vec(), Object::Ref(document));
|
||||
element.set(b"Pg".to_vec(), Object::Ref(page.page));
|
||||
element.set(b"K".to_vec(), Object::Int(i64::try_from(mcid).map_err(|_| AutoTagError::TooManyPages)?));
|
||||
let reference = next.add(element);
|
||||
parents.push(Object::Ref(reference));
|
||||
written.children.push(Object::Ref(reference));
|
||||
starts.insert(first, Mark::Tag(mcid, role));
|
||||
let count = if role == "P" { &mut written.result.paragraphs } else { &mut written.result.headings };
|
||||
*count = count.saturating_add(1);
|
||||
}
|
||||
if !parents.is_empty() {
|
||||
next.update_dict(page.page, |d| d.set(b"StructParents".to_vec(), Object::Int(key)))?;
|
||||
written.numbers.extend([Object::Int(key), Object::Array(parents)]);
|
||||
written.result.pages = written.result.pages.saturating_add(1);
|
||||
}
|
||||
let marked = mark_ops(page.ops, &starts, &ends, &page.artifacts)?;
|
||||
let stream = next.add(Stream::flate(Dict::new(), &serialize_ops(&marked)));
|
||||
next.update_dict(page.page, |d| d.set(b"Contents".to_vec(), Object::Ref(stream)))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Tag every text object in an untagged PDF as a paragraph or a heading, mark running headers,
|
||||
/// footers and page numbers as pagination artifacts, and mark painted paths, shadings and
|
||||
/// images outside text objects as artifacts. The full structure tree, parent tree and
|
||||
/// marked-content IDs are written together. Unsupported operators are refused before any
|
||||
/// mutation. On success the caller can use tag-property edits to correct the roles after review.
|
||||
pub fn autotag_text(doc: &mut Document) -> Result<AutoTagResult, AutoTagError> {
|
||||
let plans = plan(doc)?;
|
||||
let all: Vec<Evidence> = plans.iter().flat_map(|p| p.evidence.iter().copied()).collect();
|
||||
let mut roles = autotag_roles::roles(&all).into_iter();
|
||||
let running = running(&plans);
|
||||
// Running text is left out of the body style and the heading levels, as it is out of the tags.
|
||||
let tagged: Vec<Evidence> = plans
|
||||
.iter()
|
||||
.zip(&running)
|
||||
.flat_map(|(p, edges)| p.evidence.iter().zip(edges).filter(|(_, edge)| edge.is_none()).map(|(e, _)| e.clone()))
|
||||
.collect();
|
||||
let mut roles = autotag_roles::roles(&tagged).into_iter();
|
||||
let mut next = doc.clone();
|
||||
let catalog = next.root().ok_or(AutoTagError::NoCatalog)?;
|
||||
let (root, document) = (next.add(Object::Null), next.add(Object::Null));
|
||||
let (mut children, mut numbers, mut tagged_pages, mut paragraphs, mut headings) = (Vec::new(), Vec::new(), 0usize, 0usize, 0usize);
|
||||
for page in plans {
|
||||
let result = AutoTagResult { pages: 0, paragraphs: 0, headings: 0, headers: 0, footers: 0 };
|
||||
let mut written = Written { children: Vec::new(), numbers: Vec::new(), result };
|
||||
for (page, edges) in plans.into_iter().zip(running) {
|
||||
if page.spans.is_empty() && page.artifacts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (mut starts, mut ends) = (HashMap::new(), HashSet::new());
|
||||
if !page.spans.is_empty() {
|
||||
let key = i64::try_from(tagged_pages).map_err(|_| AutoTagError::TooManyPages)?;
|
||||
let mut parents = Vec::with_capacity(page.spans.len());
|
||||
for (mcid, (first, last)) in page.spans.iter().enumerate() {
|
||||
let role = roles.next().unwrap_or("P");
|
||||
let mut element = Dict::new();
|
||||
element.set(b"Type".to_vec(), Object::name("StructElem"));
|
||||
element.set(b"S".to_vec(), Object::name(role));
|
||||
element.set(b"P".to_vec(), Object::Ref(document));
|
||||
element.set(b"Pg".to_vec(), Object::Ref(page.page));
|
||||
element.set(b"K".to_vec(), Object::Int(i64::try_from(mcid).map_err(|_| AutoTagError::TooManyPages)?));
|
||||
let reference = next.add(element);
|
||||
parents.push(Object::Ref(reference));
|
||||
children.push(Object::Ref(reference));
|
||||
starts.insert(*first, (mcid, role));
|
||||
ends.insert(*last);
|
||||
if role == "P" {
|
||||
paragraphs = paragraphs.saturating_add(1);
|
||||
} else {
|
||||
headings = headings.saturating_add(1);
|
||||
}
|
||||
}
|
||||
next.update_dict(page.page, |d| d.set(b"StructParents".to_vec(), Object::Int(key)))?;
|
||||
numbers.extend([Object::Int(key), Object::Array(parents)]);
|
||||
tagged_pages += 1;
|
||||
}
|
||||
let marked = mark_ops(page.ops, &starts, &ends, &page.artifacts)?;
|
||||
let stream = next.add(Stream::flate(Dict::new(), &serialize_ops(&marked)));
|
||||
next.update_dict(page.page, |d| d.set(b"Contents".to_vec(), Object::Ref(stream)))?;
|
||||
tag_page(&mut next, document, page, &edges, &mut roles, &mut written)?;
|
||||
}
|
||||
write_structure(&mut next, catalog, root, document, children, numbers, tagged_pages)?;
|
||||
let Written { children, numbers, result } = written;
|
||||
write_structure(&mut next, catalog, root, document, children, numbers, result.pages)?;
|
||||
*doc = next;
|
||||
Ok(AutoTagResult { pages: tagged_pages, paragraphs, headings })
|
||||
Ok(result)
|
||||
}
|
||||
@@ -15,7 +15,7 @@ use pdfcraft_cos::{Dict, Document, ObjRef, Object};
|
||||
use pdfcraft_fonts::pdf::Metrics;
|
||||
|
||||
/// A line this much larger than body text reads as a heading.
|
||||
const HEADING_SIZE_RATIO: f64 = 1.15;
|
||||
pub(crate) const HEADING_SIZE_RATIO: f64 = 1.15;
|
||||
/// Bold text this much of the body size or more can be a heading by weight.
|
||||
const WEIGHT_SIZE_RATIO: f64 = 0.9;
|
||||
const MAX_LINES: usize = 3;
|
||||
@@ -25,9 +25,12 @@ const MAX_CHARS: usize = 200;
|
||||
const MAX_SAVED: usize = 64;
|
||||
/// Distinct fonts measured per document; text in any further font counts as unstyled.
|
||||
const MAX_FONTS: usize = 256;
|
||||
/// Characters of an object's text kept for finding running headers and footers; longer text is
|
||||
/// body text.
|
||||
pub(crate) const MAX_KEPT_CHARS: usize = 256;
|
||||
|
||||
/// What one text object shows.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(crate) struct Evidence {
|
||||
/// The size, in user space, carrying the most of the object's characters.
|
||||
pub size: f64,
|
||||
@@ -37,6 +40,13 @@ pub(crate) struct Evidence {
|
||||
/// Characters shown, whitespace excluded.
|
||||
pub chars: usize,
|
||||
pub letters: bool,
|
||||
/// The text shown, at most [`MAX_KEPT_CHARS`] characters, with a space at each line move.
|
||||
pub text: String,
|
||||
/// `[x0, y0, x1, y1]` in user space around each shown string's run from its origin to where
|
||||
/// it advances to, and from its baseline to one font size above. `None` when any of it is in
|
||||
/// glyphs whose widths the font does not declare ([`Metrics::width_declared`]) or that have no
|
||||
/// Unicode mapping, or in a font that writes vertically.
|
||||
pub extent: Option<[f64; 4]>,
|
||||
}
|
||||
|
||||
/// The structure type for each text object, in document order: `H1`–`H6` or `P`.
|
||||
@@ -73,10 +83,15 @@ fn half_points(size: f64) -> i64 {
|
||||
(size * 2.0).round() as i64
|
||||
}
|
||||
|
||||
/// The body text size: the size carrying the most characters.
|
||||
pub(crate) fn body_size<'a>(objects: impl IntoIterator<Item = &'a Evidence>) -> Option<f64> {
|
||||
body_style(objects).map(|(size, _)| size)
|
||||
}
|
||||
|
||||
/// The size carrying the most characters, and whether most of them are bold.
|
||||
fn body_style(objects: &[Evidence]) -> Option<(f64, bool)> {
|
||||
fn body_style<'a>(objects: impl IntoIterator<Item = &'a Evidence>) -> Option<(f64, bool)> {
|
||||
let mut by_size: HashMap<i64, (usize, usize)> = HashMap::new();
|
||||
for e in objects.iter().filter(|e| e.chars > 0) {
|
||||
for e in objects.into_iter().filter(|e| e.chars > 0) {
|
||||
let entry = by_size.entry(half_points(e.size)).or_default();
|
||||
entry.0 = entry.0.saturating_add(e.chars);
|
||||
if e.bold {
|
||||
@@ -94,10 +109,16 @@ struct State {
|
||||
tlm: Matrix,
|
||||
size: f64,
|
||||
leading: f64,
|
||||
/// `Ts`, in unscaled text space units.
|
||||
rise: f64,
|
||||
/// `Tc`, `Tw` and `Tz` / 100.
|
||||
spacing: [f64; 3],
|
||||
/// Text render mode 3 or 7: shown text that paints nothing, such as an OCR layer or a
|
||||
/// clip-only object.
|
||||
invisible: bool,
|
||||
metrics: Option<Rc<Metrics>>,
|
||||
/// The font writes vertically, which the extents do not measure.
|
||||
vertical: bool,
|
||||
}
|
||||
|
||||
/// Font metrics for a whole document, measured once per font object and capped at
|
||||
@@ -136,11 +157,26 @@ struct Shown {
|
||||
shown: bool,
|
||||
moved: bool,
|
||||
letters: bool,
|
||||
text: String,
|
||||
kept: usize,
|
||||
extent: Option<[f64; 4]>,
|
||||
/// Text shown whose run is not known: in glyphs without a declared width or a Unicode mapping,
|
||||
/// in a vertical font, or out of range.
|
||||
unbounded: bool,
|
||||
}
|
||||
|
||||
impl Shown {
|
||||
fn show(&mut self, state: &State, bytes: &[u8]) {
|
||||
let Some(metrics) = state.metrics.as_ref().filter(|_| !state.invisible) else { return };
|
||||
// A vertical font's glyphs advance down the page, invisible or not, so the text after
|
||||
// them is placed where the extents do not follow.
|
||||
self.unbounded |= state.vertical;
|
||||
let Some(metrics) = state.metrics.as_ref().filter(|_| !state.invisible) else {
|
||||
self.unbounded |= state.metrics.is_none();
|
||||
return;
|
||||
};
|
||||
// Codes without a Unicode mapping still paint glyphs: the text's extent is not known.
|
||||
let unmapped = metrics.codes(bytes).iter().any(|&(code, _)| metrics.text_of(code).is_none());
|
||||
self.unbounded |= unmapped;
|
||||
let text = metrics.decode(bytes);
|
||||
let chars = text.chars().filter(|c| !c.is_whitespace()).count();
|
||||
if chars == 0 {
|
||||
@@ -151,13 +187,23 @@ impl Shown {
|
||||
(self.shown, self.lines) = (true, 1);
|
||||
} else if self.moved {
|
||||
self.lines = self.lines.saturating_add(1);
|
||||
self.keep(" ");
|
||||
}
|
||||
self.moved = false;
|
||||
let [_, _, c, d, _, _] = state.tm.then(&state.ctm).0;
|
||||
let [a, b, c, d, e, f] = state.tm.then(&state.ctm).0;
|
||||
let size = (state.size * c.hypot(d)).abs();
|
||||
if !size.is_finite() || size <= 0.0 || size > 1e6 {
|
||||
return;
|
||||
}
|
||||
self.keep(&text);
|
||||
let run = advance(state, metrics, bytes);
|
||||
self.unbounded |= !run.declared;
|
||||
let (low, high) = (state.rise, state.rise + state.size);
|
||||
for along in run.span {
|
||||
let (x, y) = (e + along * a, f + along * b);
|
||||
self.reach(x + low * c, y + low * d);
|
||||
self.reach(x + high * c, y + high * d);
|
||||
}
|
||||
let entry = self.by_size.entry(half_points(size)).or_default();
|
||||
entry.0 = entry.0.saturating_add(chars);
|
||||
if metrics.bold {
|
||||
@@ -165,6 +211,22 @@ impl Shown {
|
||||
}
|
||||
}
|
||||
|
||||
fn keep(&mut self, text: &str) {
|
||||
for ch in text.chars().take(MAX_KEPT_CHARS.saturating_sub(self.kept)) {
|
||||
self.text.push(ch);
|
||||
self.kept = self.kept.saturating_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
fn reach(&mut self, x: f64, y: f64) {
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
self.unbounded = true;
|
||||
return;
|
||||
}
|
||||
let [x0, y0, x1, y1] = self.extent.unwrap_or([x, y, x, y]);
|
||||
self.extent = Some([x0.min(x), y0.min(y), x1.max(x), y1.max(y)]);
|
||||
}
|
||||
|
||||
/// A line move counts once text is shown after it, so blank lines and trailing moves do not.
|
||||
fn new_line(&mut self) {
|
||||
self.moved = self.shown;
|
||||
@@ -175,16 +237,159 @@ impl Shown {
|
||||
let Some((size, (count, bold))) = self.by_size.into_iter().max_by_key(|&(s, (n, _))| (n, s)) else {
|
||||
return Evidence::default();
|
||||
};
|
||||
Evidence { size: size as f64 / 2.0, bold: bold.saturating_mul(2) > count, lines: self.lines, chars, letters: self.letters }
|
||||
Evidence {
|
||||
size: size as f64 / 2.0,
|
||||
bold: bold.saturating_mul(2) > count,
|
||||
lines: self.lines,
|
||||
chars,
|
||||
letters: self.letters,
|
||||
text: self.text,
|
||||
extent: self.extent.filter(|_| !self.unbounded),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a string's glyphs move and reach along the text line, in unscaled text space (§9.4.4).
|
||||
struct Run {
|
||||
/// The advance past the string.
|
||||
width: f64,
|
||||
/// The lowest and highest points any glyph or the advance reaches: negative spacing can
|
||||
/// pull glyphs back over each other, so the ends of the run alone do not bound them.
|
||||
/// Non-finite when the spacing or size is.
|
||||
span: [f64; 2],
|
||||
/// Whether the font declares every glyph's width.
|
||||
declared: bool,
|
||||
}
|
||||
|
||||
fn advance(state: &State, metrics: &Metrics, bytes: &[u8]) -> Run {
|
||||
let [char_spacing, word_spacing, scale] = state.spacing;
|
||||
let (mut at, mut low, mut high, mut declared) = (0.0f64, 0.0f64, 0.0f64, true);
|
||||
for (code, len) in metrics.codes(bytes) {
|
||||
let glyph = metrics.width(code) * state.size;
|
||||
(low, high) = (low.min(at).min(at + glyph), high.max(at).max(at + glyph));
|
||||
let word = if metrics.is_space(code, len) { word_spacing } else { 0.0 };
|
||||
at += glyph + char_spacing + word;
|
||||
declared &= metrics.width_declared(code);
|
||||
}
|
||||
// `min` and `max` drop a NaN, but once `at` is not finite it stays so: pass it on instead.
|
||||
let span = if at.is_finite() { [low.min(at), high.max(at)] } else { [at, at] };
|
||||
Run { width: at * scale, span: span.map(|v| v * scale), declared }
|
||||
}
|
||||
|
||||
/// Whether `font` writes vertically: a Type 0 font whose `/Encoding` is a predefined CMap name
|
||||
/// ending in `-V`, or an embedded CMap whose `/WMode` is 1 (§9.7.5).
|
||||
fn vertical(doc: &Document, font: &Object) -> bool {
|
||||
let font = doc.resolve(font);
|
||||
let Some(font) = font.as_dict() else { return false };
|
||||
if font.get(b"Subtype").map(|s| doc.resolve(s)).as_deref().and_then(Object::as_name) != Some(b"Type0".as_slice()) {
|
||||
return false;
|
||||
}
|
||||
match font.get(b"Encoding").map(|e| doc.resolve(e)).as_deref() {
|
||||
Some(Object::Name(n)) => n.ends_with(b"-V"),
|
||||
Some(Object::Stream(s)) => s.dict.int(b"WMode") == Some(1),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows `bytes` in `object`, if any, then moves the text matrix past them.
|
||||
fn show(state: &mut State, object: Option<&mut Shown>, bytes: &[u8]) {
|
||||
if let Some(o) = object {
|
||||
o.show(state, bytes);
|
||||
}
|
||||
let moved = state.metrics.as_ref().map_or(0.0, |m| advance(state, m, bytes).width);
|
||||
state.tm = Matrix::translate(moved, 0.0).then(&state.tm);
|
||||
}
|
||||
|
||||
/// The text state and text-showing operators other than `Tf`.
|
||||
fn text_op(state: &mut State, object: Option<&mut Shown>, op: &Op) {
|
||||
match op.op.as_slice() {
|
||||
b"TL" => state.leading = op.num(0).unwrap_or(state.leading),
|
||||
b"Ts" => state.rise = op.num(0).unwrap_or(state.rise),
|
||||
b"Tr" => state.invisible = matches!(op.num(0), Some(m) if m == 3.0 || m == 7.0),
|
||||
b"Tc" => state.spacing[0] = op.num(0).unwrap_or(state.spacing[0]),
|
||||
b"Tw" => state.spacing[1] = op.num(0).unwrap_or(state.spacing[1]),
|
||||
b"Tz" => state.spacing[2] = op.num(0).map_or(state.spacing[2], |z| z / 100.0),
|
||||
b"Td" | b"TD" => {
|
||||
if let Some([x, y]) = op.nums::<2>() {
|
||||
if op.op == b"TD" {
|
||||
state.leading = -y;
|
||||
}
|
||||
state.tlm = Matrix::translate(x, y).then(&state.tlm);
|
||||
state.tm = state.tlm;
|
||||
if y != 0.0
|
||||
&& let Some(o) = object
|
||||
{
|
||||
o.new_line();
|
||||
}
|
||||
}
|
||||
}
|
||||
b"Tm" => {
|
||||
if let Some(m) = op.nums::<6>() {
|
||||
let moved = m[5] != state.tlm.0[5];
|
||||
(state.tm, state.tlm) = (Matrix(m), Matrix(m));
|
||||
if moved && let Some(o) = object {
|
||||
o.new_line();
|
||||
}
|
||||
}
|
||||
}
|
||||
b"T*" | b"'" | b"\"" => {
|
||||
if op.op == b"\""
|
||||
&& let (Some(word), Some(char)) = (op.num(0), op.num(1))
|
||||
{
|
||||
state.spacing = [char, word, state.spacing[2]];
|
||||
}
|
||||
state.tlm = Matrix::translate(0.0, -state.leading).then(&state.tlm);
|
||||
state.tm = state.tlm;
|
||||
let mut object = object;
|
||||
if let Some(o) = object.as_deref_mut() {
|
||||
o.new_line();
|
||||
}
|
||||
if op.op != b"T*"
|
||||
&& let Some(Object::String(s)) = op.operands.last()
|
||||
{
|
||||
show(state, object, &s.bytes);
|
||||
}
|
||||
}
|
||||
b"Tj" => {
|
||||
if let Some(Object::String(s)) = op.operands.first() {
|
||||
show(state, object, &s.bytes);
|
||||
}
|
||||
}
|
||||
b"TJ" => {
|
||||
if let Some(Object::Array(items)) = op.operands.first() {
|
||||
let mut object = object;
|
||||
for item in items {
|
||||
match item {
|
||||
Object::String(s) => show(state, object.as_deref_mut(), &s.bytes),
|
||||
other => {
|
||||
let n = other.as_f64().unwrap_or(0.0);
|
||||
let moved = -n / 1000.0 * state.size * state.spacing[2];
|
||||
state.tm = Matrix::translate(moved, 0.0).then(&state.tm);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The evidence for each `(BT, ET)` operator span of a page, in order. `resources` is the page's
|
||||
/// `/Font` resource dictionary; `fonts` is shared by the document's pages.
|
||||
pub(crate) fn evidence(doc: &Document, fonts: &mut Fonts, resources: &Dict, ops: &[Op], spans: &[(usize, usize)]) -> Vec<Evidence> {
|
||||
let mut by_name: HashMap<Vec<u8>, Option<Rc<Metrics>>> = HashMap::new();
|
||||
let mut state =
|
||||
State { ctm: Matrix::IDENTITY, tm: Matrix::IDENTITY, tlm: Matrix::IDENTITY, size: 0.0, leading: 0.0, invisible: false, metrics: None };
|
||||
let mut by_name: HashMap<Vec<u8>, (Option<Rc<Metrics>>, bool)> = HashMap::new();
|
||||
let mut state = State {
|
||||
ctm: Matrix::IDENTITY,
|
||||
tm: Matrix::IDENTITY,
|
||||
tlm: Matrix::IDENTITY,
|
||||
size: 0.0,
|
||||
leading: 0.0,
|
||||
rise: 0.0,
|
||||
spacing: [0.0, 0.0, 1.0],
|
||||
invisible: false,
|
||||
metrics: None,
|
||||
vertical: false,
|
||||
};
|
||||
let (mut saved, mut unsaved) = (Vec::new(), 0usize);
|
||||
let mut out = Vec::with_capacity(spans.len());
|
||||
let mut spans = spans.iter().peekable();
|
||||
@@ -211,62 +416,15 @@ pub(crate) fn evidence(doc: &Document, fonts: &mut Fonts, resources: &Dict, ops:
|
||||
b"BT" => (state.tm, state.tlm) = (Matrix::IDENTITY, Matrix::IDENTITY),
|
||||
b"Tf" => {
|
||||
state.size = op.num(1).unwrap_or(state.size);
|
||||
state.metrics = op
|
||||
.name(0)
|
||||
.and_then(|name| by_name.entry(name.to_vec()).or_insert_with(|| resources.get(name).and_then(|f| fonts.get(doc, f))).clone());
|
||||
(state.metrics, state.vertical) = op.name(0).map_or((None, false), |name| {
|
||||
let font = || resources.get(name);
|
||||
by_name
|
||||
.entry(name.to_vec())
|
||||
.or_insert_with(|| (font().and_then(|f| fonts.get(doc, f)), font().is_some_and(|f| vertical(doc, f))))
|
||||
.clone()
|
||||
});
|
||||
}
|
||||
b"TL" => state.leading = op.num(0).unwrap_or(state.leading),
|
||||
b"Tr" => state.invisible = matches!(op.num(0), Some(m) if m == 3.0 || m == 7.0),
|
||||
b"Td" | b"TD" => {
|
||||
if let Some([x, y]) = op.nums::<2>() {
|
||||
if op.op == b"TD" {
|
||||
state.leading = -y;
|
||||
}
|
||||
state.tlm = Matrix::translate(x, y).then(&state.tlm);
|
||||
state.tm = state.tlm;
|
||||
if y != 0.0
|
||||
&& let Some(o) = object
|
||||
{
|
||||
o.new_line();
|
||||
}
|
||||
}
|
||||
}
|
||||
b"Tm" => {
|
||||
if let Some(m) = op.nums::<6>() {
|
||||
let moved = m[5] != state.tlm.0[5];
|
||||
(state.tm, state.tlm) = (Matrix(m), Matrix(m));
|
||||
if moved && let Some(o) = object {
|
||||
o.new_line();
|
||||
}
|
||||
}
|
||||
}
|
||||
b"T*" | b"'" | b"\"" => {
|
||||
state.tlm = Matrix::translate(0.0, -state.leading).then(&state.tlm);
|
||||
state.tm = state.tlm;
|
||||
if let Some(o) = object {
|
||||
o.new_line();
|
||||
if op.op != b"T*"
|
||||
&& let Some(Object::String(s)) = op.operands.last()
|
||||
{
|
||||
o.show(&state, &s.bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
b"Tj" => {
|
||||
if let (Some(o), Some(Object::String(s))) = (object, op.operands.first()) {
|
||||
o.show(&state, &s.bytes);
|
||||
}
|
||||
}
|
||||
b"TJ" => {
|
||||
if let (Some(o), Some(Object::Array(items))) = (object, op.operands.first()) {
|
||||
for item in items {
|
||||
if let Object::String(s) = item {
|
||||
o.show(&state, &s.bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
_ => text_op(&mut state, object, op),
|
||||
}
|
||||
if current.as_ref().is_some_and(|c| c.0 == at)
|
||||
&& let Some((_, o)) = current.take()
|
||||
@@ -283,7 +441,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn text(size: f64, chars: usize) -> Evidence {
|
||||
Evidence { size, bold: false, lines: 1, chars, letters: true }
|
||||
Evidence { size, bold: false, lines: 1, chars, letters: true, ..Evidence::default() }
|
||||
}
|
||||
|
||||
fn bold(e: Evidence) -> Evidence {
|
||||
@@ -343,15 +501,23 @@ mod tests {
|
||||
assert!(roles(&[]).is_empty());
|
||||
}
|
||||
|
||||
/// The evidence for each `BT`..`ET` of `content`, drawn in Helvetica-Bold as `/F1`.
|
||||
/// The evidence for each `BT`..`ET` of `content`, drawn in Helvetica-Bold as `/F1`, a font
|
||||
/// with no widths whose name is no standard face as `/F2`, and one whose `/Widths` covers
|
||||
/// only `a` as `/F3`.
|
||||
fn walk(content: &[u8]) -> Vec<Evidence> {
|
||||
let doc = Document::new_empty();
|
||||
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("Helvetica-Bold"));
|
||||
let mut resources = Dict::new();
|
||||
resources.set(b"F1".to_vec(), Object::Dict(font));
|
||||
for (name, base, widths) in [("F1", "Helvetica-Bold", None), ("F2", "HouseFont", None), ("F3", "HouseFont", Some(500))] {
|
||||
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 let Some(w) = widths {
|
||||
font.set(b"FirstChar".to_vec(), Object::Int(97));
|
||||
font.set(b"Widths".to_vec(), Object::Array(vec![Object::Int(w)]));
|
||||
}
|
||||
resources.set(name.as_bytes().to_vec(), Object::Dict(font));
|
||||
}
|
||||
let ops = pdfcraft_content::parse(content).ops;
|
||||
let at = |name: &[u8]| -> Vec<usize> { ops.iter().enumerate().filter(|(_, o)| o.op == name).map(|(i, _)| i).collect() };
|
||||
let spans: Vec<(usize, usize)> = at(b"BT").into_iter().zip(at(b"ET")).collect();
|
||||
@@ -363,12 +529,56 @@ mod tests {
|
||||
let found = walk(
|
||||
b"q 2 0 0 2 0 0 cm BT /F1 1 Tf 9 0 0 9 10 10 Tm (Title) Tj ET Q BT /F1 12 Tf 10 50 Td (one) Tj T* (two) ' 0 -14 Td (three) Tj ET BT ET",
|
||||
);
|
||||
assert_eq!(found[0], Evidence { size: 18.0, bold: true, lines: 1, chars: 5, letters: true });
|
||||
assert_eq!(found[1], Evidence { size: 12.0, bold: true, lines: 3, chars: 11, letters: true });
|
||||
assert_eq!(found[0], Evidence { size: 18.0, bold: true, lines: 1, chars: 5, letters: true, ..found[0].clone() });
|
||||
assert_eq!(found[1], Evidence { size: 12.0, bold: true, lines: 3, chars: 11, letters: true, ..found[1].clone() });
|
||||
assert_eq!(found[0].text, "Title");
|
||||
// "Title" is 2.056 em wide in Helvetica-Bold, at 18 units from x 20.
|
||||
assert_eq!(rounded(found[0].extent), Some([20.0, 20.0, 57.008, 38.0]), "the run and one font size above it, through Tm and cm");
|
||||
assert_eq!(found[1].text, "one two three");
|
||||
assert_eq!(found[2], Evidence::default());
|
||||
assert_eq!(found.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_rise_moves_the_extent() {
|
||||
// Ts is text space, so a 2x Tm doubles it; it outlives BT and is undone by Q.
|
||||
let found = walk(b"q BT /F1 10 Tf 2 0 0 2 72 760 Tm -180 Ts (Body) Tj ET BT /F1 10 Tf 1 0 0 1 72 760 Tm (Still) Tj ET Q BT /F1 10 Tf 1 0 0 1 72 760 Tm (Back) Tj ET");
|
||||
// Body, Still and Back are 2.5, 1.834 and 2.39 em wide in Helvetica-Bold.
|
||||
assert_eq!(rounded(found[0].extent), Some([72.0, 400.0, 122.0, 420.0]));
|
||||
assert_eq!(rounded(found[1].extent), Some([72.0, 580.0, 90.34, 590.0]));
|
||||
assert_eq!(rounded(found[2].extent), Some([72.0, 760.0, 95.9, 770.0]));
|
||||
}
|
||||
|
||||
fn rounded(extent: Option<[f64; 4]>) -> Option<[f64; 4]> {
|
||||
extent.map(|p| p.map(|v| (v * 1000.0).round() / 1000.0))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_extent_follows_the_run_in_any_direction_with_spacing() {
|
||||
// Turned to run down the page, "Body" reaches 30 units below its origin; one font size
|
||||
// up is to the right. Tc 1 adds 4, TJ -500 adds 6, and Tz 50 halves the whole run.
|
||||
let found = walk(b"q BT /F1 12 Tf 0 -1 1 0 72 760 Tm (Body) Tj ET BT /F1 12 Tf 1 Tc 50 Tz 1 0 0 1 72 700 Tm [(Bo) -500 (dy)] TJ ET Q");
|
||||
assert_eq!(rounded(found[0].extent), Some([72.0, 730.0, 84.0, 760.0]));
|
||||
assert_eq!(rounded(found[1].extent), Some([72.0, 700.0, 92.0, 712.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_in_widths_the_font_does_not_declare_has_no_extent() {
|
||||
let found = walk(b"BT /F2 10 Tf (a) Tj ET BT /F3 10 Tf (ab) Tj ET BT /F3 10 Tf (a) Tj ET BT /F1 10 Tf (a) Tj /F9 10 Tf (b) Tj ET");
|
||||
assert_eq!(found[0].extent, None, "no /Widths, and Helvetica only a guess");
|
||||
assert_eq!(found[1].extent, None, "b is past /Widths");
|
||||
assert_eq!(rounded(found[2].extent), Some([0.0, 0.0, 5.0, 10.0]), "a is in /Widths");
|
||||
assert_eq!(found[3].extent, None, "part of it has no font");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_origin_past_f64_leaves_no_extent() {
|
||||
// Two translations near f64::MAX add up to infinity; the text is kept, its position is not.
|
||||
let far = format!("{}.0", "9".repeat(308));
|
||||
let found = walk(format!("q 1 0 0 1 {far} 0 cm BT /F1 10 Tf 1 0 0 1 {far} 0 Tm (far) Tj ET Q").as_bytes());
|
||||
assert_eq!((found[0].text.as_str(), found[0].extent), ("far", None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_moves_leading_invisible_text_and_absurd_sizes() {
|
||||
let found = walk(
|
||||
@@ -379,4 +589,70 @@ mod tests {
|
||||
assert_eq!(found[2].chars, 5, "render mode 3 and 7 text is not counted");
|
||||
assert_eq!(found[3], Evidence::default(), "a size past 1e6 is dropped");
|
||||
}
|
||||
|
||||
/// The evidence for each `BT`..`ET` of `content` in two-byte Type 0 fonts declaring every
|
||||
/// width as 1000: `/H` and `/V` map their codes to Unicode and write horizontally and
|
||||
/// vertically, and `/U` has no Unicode mapping; with `/F1` as in [`walk`].
|
||||
fn walk_type0(content: &[u8]) -> Vec<Evidence> {
|
||||
let cmap = "begincmap 1 begincodespacerange <0000> <FFFF> endcodespacerange 1 beginbfrange <0020> <007E> <0020> endbfrange endcmap";
|
||||
let type0 = |encoding: &str, unicode: &str| {
|
||||
format!("<< /Type /Font /Subtype /Type0 /BaseFont /House /Encoding /{encoding} /DescendantFonts [2 0 R] {unicode} >>")
|
||||
};
|
||||
let doc = crate::tests::pdf(
|
||||
&[
|
||||
"<< /Type /Catalog >>".into(),
|
||||
"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /House /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /DW 1000 >>".into(),
|
||||
crate::tests::stream(cmap),
|
||||
type0("Identity-H", "/ToUnicode 3 0 R"),
|
||||
type0("Identity-V", "/ToUnicode 3 0 R"),
|
||||
type0("Identity-H", ""),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>".into(),
|
||||
],
|
||||
"",
|
||||
);
|
||||
let mut resources = Dict::new();
|
||||
for (name, n) in [("H", 4), ("V", 5), ("U", 6), ("F1", 7)] {
|
||||
resources.set(name.as_bytes().to_vec(), Object::Ref(ObjRef::new(n, 0)));
|
||||
}
|
||||
let ops = pdfcraft_content::parse(content).ops;
|
||||
let at = |name: &[u8]| -> Vec<usize> { ops.iter().enumerate().filter(|(_, o)| o.op == name).map(|(i, _)| i).collect() };
|
||||
let spans: Vec<(usize, usize)> = at(b"BT").into_iter().zip(at(b"ET")).collect();
|
||||
evidence(&doc, &mut Fonts::default(), &resources, &ops, &spans)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_in_glyphs_without_a_unicode_mapping_has_no_extent() {
|
||||
// A mapped header and, in the same object, unmapped glyphs further down the page: the
|
||||
// object reaches the body, though its text is only the header's.
|
||||
let found = walk_type0(b"BT /F1 12 Tf 72 760 Td (Header) Tj /U 12 Tf 0 -360 Td <00410042> Tj ET BT /H 12 Tf 72 760 Td <00410042> Tj ET");
|
||||
assert_eq!((found[0].text.as_str(), found[0].extent), ("Header", None));
|
||||
assert_eq!(rounded(found[1].extent), Some([72.0, 760.0, 96.0, 772.0]), "mapped Type 0 text keeps its extent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_after_invisible_vertical_text_has_no_extent() {
|
||||
// The invisible glyph moves the text 360 units down the page before "Body" is shown.
|
||||
let found = walk_type0(b"BT /V 360 Tf 3 Tr 72 760 Td <0041> Tj /F1 12 Tf 0 Tr (Body) Tj ET BT /F1 12 Tf 72 760 Td (Body) Tj ET");
|
||||
assert_eq!((found[0].text.as_str(), found[0].extent), ("Body", None));
|
||||
assert!(found[1].extent.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spacing_past_f64_leaves_no_extent() {
|
||||
// Tc and Tw near f64::MAX each overflow to infinity and cancel to NaN on the first space.
|
||||
let big = format!("1.0e{}", 999);
|
||||
let found =
|
||||
walk(format!("BT /F1 10 Tf {big} Tc -{big} Tw 72 760 Td ( Body) Tj ET BT /F1 10 Tf 0 Tc 0 Tw 72 760 Td ( Body) Tj ET").as_bytes());
|
||||
assert_eq!((found[0].text.as_str(), found[0].extent), (" Body", None));
|
||||
assert!(found[1].extent.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_in_a_vertical_font_has_no_extent() {
|
||||
// Thirty glyphs at 12 run 360 units down the page in a vertical font, not along x.
|
||||
let glyphs = format!("<{}>", "0041".repeat(30));
|
||||
let found = walk_type0(format!("BT /V 12 Tf 72 760 Td {glyphs} Tj ET BT /H 12 Tf 72 760 Td {glyphs} Tj ET").as_bytes());
|
||||
assert_eq!((found[0].chars, found[0].extent), (30, None));
|
||||
assert_eq!(rounded(found[1].extent), Some([72.0, 760.0, 432.0, 772.0]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
//! Running headers, footers and page numbers among auto-tagged text objects, found by repetition.
|
||||
//!
|
||||
//! A text object is running text when it lies wholly inside the top or bottom 15% of the page as
|
||||
//! displayed, and the same text appears within 4 units of the same distance from that edge on at
|
||||
//! least 40% of the pages, and at least two. Text is compared lowercase with whitespace collapsed,
|
||||
//! each run of digits, and a roman numeral standing alone or after `Page`, matching any number, so
|
||||
//! page numbers repeat. 40% lets alternating left- and right-page headers qualify. A group whose
|
||||
//! text changes from page to page and is all heading-sized (`Chapter 1`, `Chapter 2`) is a
|
||||
//! sequence of headings, not running text, unless it reads as a page number (`Page 3`, `3 of 9`).
|
||||
//! Every object in some qualifying span of distances counts, so spans that overlap and spans that
|
||||
//! lie apart are each marked. Position alone never makes running text.
|
||||
//! A text object whose extent is not known (see [`Evidence::extent`]) is never running text.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::autotag_roles::{Evidence, HEADING_SIZE_RATIO, MAX_KEPT_CHARS};
|
||||
|
||||
/// Depth of the top and bottom bands, as a fraction of the page height.
|
||||
const BAND: f64 = 0.15;
|
||||
/// How far, in user-space units, the same running text may move from page to page.
|
||||
const TOLERANCE: f64 = 4.0;
|
||||
/// Height clusters marked per group of the same text; copies at further heights stay content.
|
||||
const MAX_CLUSTERS: usize = 8;
|
||||
|
||||
/// The page edge running text repeats at.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub(crate) enum Edge {
|
||||
Top,
|
||||
Bottom,
|
||||
}
|
||||
|
||||
impl Edge {
|
||||
/// The artifact subtype (ISO 32000-2 Table 363) for running text at this edge.
|
||||
pub(crate) fn subtype(self) -> &'static str {
|
||||
match self {
|
||||
Edge::Top => "Header",
|
||||
Edge::Bottom => "Footer",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a page is displayed: its `/Rotate` (0, 90, 180 or 270) and its crop box in user space.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Frame {
|
||||
pub rotation: i64,
|
||||
pub crop: [f64; 4],
|
||||
}
|
||||
|
||||
/// One page's text objects, in the order of its `(BT, ET)` spans.
|
||||
pub(crate) struct PageText<'a> {
|
||||
pub frame: Frame,
|
||||
pub objects: &'a [Evidence],
|
||||
}
|
||||
|
||||
struct Member<'a> {
|
||||
page: usize,
|
||||
object: usize,
|
||||
distance: f64,
|
||||
evidence: &'a Evidence,
|
||||
}
|
||||
|
||||
/// The edge each text object repeats at, for running text, per page and object.
|
||||
pub(crate) fn find(pages: &[PageText<'_>], body: Option<f64>) -> Vec<Vec<Option<Edge>>> {
|
||||
let mut out: Vec<Vec<Option<Edge>>> = pages.iter().map(|p| vec![None; p.objects.len()]).collect();
|
||||
if pages.len() < 2 {
|
||||
return out;
|
||||
}
|
||||
let needed = pages.len().saturating_mul(2).div_ceil(5).max(2);
|
||||
for ((edge, key), mut members) in groups(pages) {
|
||||
members.sort_by(|a, b| a.distance.total_cmp(&b.distance));
|
||||
for cluster in clusters(&members, needed) {
|
||||
if is_heading_sequence(cluster, &key, body) {
|
||||
continue;
|
||||
}
|
||||
for m in cluster {
|
||||
if let Some(slot) = out.get_mut(m.page).and_then(|p| p.get_mut(m.object)) {
|
||||
*slot = Some(edge);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `Chapter 1`, `Chapter 2`: heading-sized text that changes, unless it reads as a page number.
|
||||
fn is_heading_sequence(window: &[Member<'_>], key: &str, body: Option<f64>) -> bool {
|
||||
let texts_differ = window.windows(2).any(|w| matches!(w, [a, b] if folded(&a.evidence.text) != folded(&b.evidence.text)));
|
||||
let heading_sized = body.is_some_and(|body| window.iter().all(|m| m.evidence.size >= body * HEADING_SIZE_RATIO));
|
||||
let worded = window.iter().all(|m| m.evidence.letters) && !is_page_number(key);
|
||||
texts_differ && heading_sized && worded
|
||||
}
|
||||
|
||||
/// Lowercase with whitespace collapsed, digits kept: `ANNUAL REPORT` and `Annual report` are the
|
||||
/// same heading, `Chapter 1` and `Chapter 2` are not.
|
||||
fn folded(text: &str) -> String {
|
||||
text.to_lowercase().split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// A normalised key that is a page number alone or with its label: `#`, `page #`, `p. #`,
|
||||
/// `# of #`, `page # of #`, `#/#`, optionally in dashes or brackets.
|
||||
fn is_page_number(key: &str) -> bool {
|
||||
let bare = key.trim_matches(|c: char| matches!(c, '-' | '\u{2013}' | '\u{2014}' | '[' | ']' | '(' | ')' | ' '));
|
||||
matches!(bare, "#" | "page #" | "p. #" | "# of #" | "page # of #" | "#/#" | "# / #")
|
||||
}
|
||||
|
||||
/// Text objects inside a band, grouped by edge and normalised text.
|
||||
fn groups<'a>(pages: &'a [PageText<'a>]) -> HashMap<(Edge, String), Vec<Member<'a>>> {
|
||||
let mut groups: HashMap<(Edge, String), Vec<Member<'a>>> = HashMap::new();
|
||||
for (page, text) in pages.iter().enumerate() {
|
||||
let (low, high) = vertical(text.frame.rotation, text.frame.crop);
|
||||
let band = (high - low) * BAND;
|
||||
for (object, evidence) in text.objects.iter().enumerate() {
|
||||
let Some(extent) = evidence.extent.filter(|_| evidence.chars > 0 && evidence.text.chars().count() < MAX_KEPT_CHARS) else {
|
||||
continue;
|
||||
};
|
||||
let (bottom, top) = vertical(text.frame.rotation, extent);
|
||||
let (edge, distance) = if bottom >= high - band && top <= high {
|
||||
(Edge::Top, high - top)
|
||||
} else if top <= low + band && bottom >= low {
|
||||
(Edge::Bottom, bottom - low)
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
let key = normalise(&evidence.text);
|
||||
if key.is_empty() || !distance.is_finite() {
|
||||
continue;
|
||||
}
|
||||
groups.entry((edge, key)).or_default().push(Member { page, object, distance, evidence });
|
||||
}
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
/// The clusters of `members` (sorted by distance) that run: the union of every window of members
|
||||
/// within [`TOLERANCE`] of the window's first that covers at least `needed` pages, with windows that
|
||||
/// share a member joined into one cluster. A dense run of such windows makes one cluster wider than
|
||||
/// [`TOLERANCE`], still inside the edge band, and the heading check then judges the cluster as a
|
||||
/// whole. At most [`MAX_CLUSTERS`] are returned, nearest the edge first.
|
||||
fn clusters<'m, 'a>(members: &'m [Member<'a>], needed: usize) -> Vec<&'m [Member<'a>]> {
|
||||
let mut on_page: HashMap<usize, usize> = HashMap::new();
|
||||
let mut found: Vec<&'m [Member<'a>]> = Vec::new();
|
||||
let mut current: Option<(usize, usize)> = None;
|
||||
let mut end = 0usize;
|
||||
for (start, first) in members.iter().enumerate() {
|
||||
while let Some(next) = members.get(end).filter(|m| m.distance - first.distance <= TOLERANCE) {
|
||||
let n = on_page.entry(next.page).or_default();
|
||||
*n = n.saturating_add(1);
|
||||
end = end.saturating_add(1);
|
||||
}
|
||||
if on_page.len() >= needed {
|
||||
current = match current {
|
||||
Some((from, to)) if start < to => Some((from, to.max(end))),
|
||||
done => {
|
||||
if let Some(cluster) = done.and_then(|(from, to)| members.get(from..to)) {
|
||||
found.push(cluster);
|
||||
}
|
||||
if found.len() >= MAX_CLUSTERS {
|
||||
return found;
|
||||
}
|
||||
Some((start, end))
|
||||
}
|
||||
};
|
||||
}
|
||||
if let Some(n) = on_page.get_mut(&first.page) {
|
||||
*n = n.saturating_sub(1);
|
||||
if *n == 0 {
|
||||
on_page.remove(&first.page);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(cluster) = current.and_then(|(from, to)| members.get(from..to)) {
|
||||
found.push(cluster);
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The bottom and top of a user-space box as the page displays it.
|
||||
fn vertical(rotation: i64, [x0, y0, x1, y1]: [f64; 4]) -> (f64, f64) {
|
||||
let (a, b) = match rotation {
|
||||
90 => (-x0, -x1),
|
||||
180 => (-y0, -y1),
|
||||
270 => (x0, x1),
|
||||
_ => (y0, y1),
|
||||
};
|
||||
(a.min(b), a.max(b))
|
||||
}
|
||||
|
||||
/// Lowercase, whitespace collapsed, and each digit run, and a roman numeral standing alone or
|
||||
/// after `page`, replaced by `#`.
|
||||
fn normalise(text: &str) -> String {
|
||||
let lower = text.to_lowercase();
|
||||
let words: Vec<&str> = lower.split_whitespace().collect();
|
||||
let roman_alone = match words.as_slice() {
|
||||
[w] | ["page", w] => is_roman(w),
|
||||
_ => false,
|
||||
};
|
||||
let mut out = String::new();
|
||||
for (i, w) in words.iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push(' ');
|
||||
}
|
||||
if roman_alone && i + 1 == words.len() {
|
||||
out.push('#');
|
||||
continue;
|
||||
}
|
||||
let mut in_digits = false;
|
||||
for c in w.chars() {
|
||||
if c.is_ascii_digit() {
|
||||
if !in_digits {
|
||||
out.push('#');
|
||||
}
|
||||
in_digits = true;
|
||||
} else {
|
||||
out.push(c);
|
||||
in_digits = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A canonical lowercase roman numeral from 1 to 3999 (`mid` and `iiii` are not).
|
||||
fn is_roman(s: &str) -> bool {
|
||||
const UNITS: [(u32, &str); 13] = [
|
||||
(1000, "m"),
|
||||
(900, "cm"),
|
||||
(500, "d"),
|
||||
(400, "cd"),
|
||||
(100, "c"),
|
||||
(90, "xc"),
|
||||
(50, "l"),
|
||||
(40, "xl"),
|
||||
(10, "x"),
|
||||
(9, "ix"),
|
||||
(5, "v"),
|
||||
(4, "iv"),
|
||||
(1, "i"),
|
||||
];
|
||||
if s.is_empty() || s.len() > 15 {
|
||||
return false;
|
||||
}
|
||||
let (mut rest, mut value) = (s, 0u32);
|
||||
for (v, sym) in UNITS {
|
||||
let mut repeats = 0;
|
||||
while let Some(r) = rest.strip_prefix(sym) {
|
||||
(rest, value, repeats) = (r, value.saturating_add(v), repeats + 1);
|
||||
if repeats > 3 {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !rest.is_empty() || value == 0 {
|
||||
return false;
|
||||
}
|
||||
let mut canonical = String::new();
|
||||
for (v, sym) in UNITS {
|
||||
while value >= v {
|
||||
canonical.push_str(sym);
|
||||
value = value.saturating_sub(v);
|
||||
}
|
||||
}
|
||||
canonical == s
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const LETTER: Frame = Frame { rotation: 0, crop: [0.0, 0.0, 612.0, 792.0] };
|
||||
|
||||
/// One line of 10-unit text at baseline `y`.
|
||||
fn line(text: &str, y: f64) -> Evidence {
|
||||
Evidence {
|
||||
size: 10.0,
|
||||
lines: 1,
|
||||
chars: text.chars().filter(|c| !c.is_whitespace()).count(),
|
||||
letters: true,
|
||||
text: text.into(),
|
||||
extent: Some([72.0, y, 72.0, y + 10.0]),
|
||||
..Evidence::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn run(pages: &[Vec<Evidence>], body: Option<f64>) -> Vec<Vec<Option<Edge>>> {
|
||||
let text: Vec<PageText<'_>> = pages.iter().map(|objects| PageText { frame: LETTER, objects }).collect();
|
||||
find(&text, body)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn digits_and_roman_numerals_match_any_number() {
|
||||
assert_eq!(normalise("Page 12 of 30"), "page # of #");
|
||||
assert_eq!(normalise("Annual Report 2026"), "annual report #");
|
||||
assert_eq!(normalise("xiv"), "#");
|
||||
assert_eq!(normalise("Page IX"), "page #");
|
||||
assert_eq!(normalise("mid"), "mid", "not a canonical numeral");
|
||||
assert_eq!(normalise("Chapter iv"), "chapter iv", "a numeral after another word is a word");
|
||||
assert!(is_page_number("#") && is_page_number("page # of #") && is_page_number("- # -") && is_page_number("[p. #]"));
|
||||
assert!(!is_page_number("chapter #") && !is_page_number("page") && !is_page_number("annual report #"));
|
||||
assert!(is_roman("mmmcmxcix") && !is_roman("iiii") && !is_roman("ic") && !is_roman(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_and_a_numbered_footer_repeat_but_a_body_line_does_not() {
|
||||
let page = |n: usize| vec![line("Annual report", 760.0), line("Repeated body line", 400.0), line(&format!("Page {n}"), 30.0)];
|
||||
let found = run(&[page(1), page(2), page(3)], Some(10.0));
|
||||
for page in found {
|
||||
assert_eq!(page, [Some(Edge::Top), None, Some(Edge::Bottom)]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_page_has_no_running_text() {
|
||||
let found = run(&[vec![line("Annual report", 760.0), line("1", 30.0)]], Some(10.0));
|
||||
assert_eq!(found, [[None, None]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_on_too_few_pages_or_at_another_height_is_not_running() {
|
||||
// Five pages: the footer on one of them, the header 20 units lower on each.
|
||||
let pages: Vec<Vec<Evidence>> = (0..5u32)
|
||||
.map(|i| {
|
||||
let mut page = vec![line("Header", 760.0 - f64::from(i) * 20.0)];
|
||||
if i < 1 {
|
||||
page.push(line("Draft", 30.0));
|
||||
}
|
||||
page
|
||||
})
|
||||
.collect();
|
||||
assert!(run(&pages, None).iter().flatten().all(Option::is_none));
|
||||
// Within the tolerance, alternate headers on two of five pages qualify.
|
||||
let pages: Vec<Vec<Evidence>> = (0..5u32).map(|i| vec![line(if i % 2 == 0 { "Left" } else { "Right" }, 760.0 + f64::from(i))]).collect();
|
||||
let found = run(&pages, None);
|
||||
assert!(found.iter().flatten().all(|e| *e == Some(Edge::Top)), "{found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinct_pages_are_counted_not_objects() {
|
||||
// Six pages need three. Copies at 30 and 32 on the first page and one at 31 on the second
|
||||
// are three objects in a row by height, but only two pages.
|
||||
let note = |y: f64| line("Note", y);
|
||||
let mut pages = vec![vec![note(30.0), note(32.0)], vec![note(31.0)], Vec::new(), Vec::new(), Vec::new(), Vec::new()];
|
||||
assert!(run(&pages, None).iter().flatten().all(Option::is_none));
|
||||
pages[2].push(note(31.0));
|
||||
assert!(run(&pages, None).iter().flatten().any(Option::is_some), "on three pages it runs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_qualifying_cluster_of_heights_counts() {
|
||||
// Six pages need three: "Note" 20 units below the top on three pages and 40 below on the
|
||||
// other three, plus a second copy on the first page just inside the first cluster.
|
||||
let at = |distance: f64| line("Note", 792.0 - 10.0 - distance);
|
||||
let pages = vec![vec![at(20.0), at(21.0)], vec![at(20.0)], vec![at(20.0)], vec![at(40.0)], vec![at(40.0)], vec![at(40.0)]];
|
||||
let found = run(&pages, None);
|
||||
assert!(found.iter().flatten().all(|e| *e == Some(Edge::Top)), "{found:?}");
|
||||
// On two pages, a copy every 10 units from 20 down puts 9 clusters in the band, past the cap.
|
||||
let column: Vec<Evidence> = (0..12u32).map(|i| at(20.0 + f64::from(i) * 10.0)).collect();
|
||||
let found = run(&[column.clone(), column], None);
|
||||
let marked = found.iter().flatten().filter(|e| e.is_some()).count();
|
||||
assert_eq!(marked, 16, "8 clusters on 2 pages: {found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_qualifying_spans_of_heights_both_count() {
|
||||
// Six pages need three: "Note" 20 units below the top on two pages, 24 on one and 28 on
|
||||
// two. 20..24 and 24..28 each cover three pages and share the copy at 24.
|
||||
let at = |distance: f64| line("Note", 792.0 - 10.0 - distance);
|
||||
let pages = vec![vec![at(20.0)], vec![at(20.0)], vec![at(24.0)], vec![at(28.0)], vec![at(28.0)], Vec::new()];
|
||||
let found = run(&pages, None);
|
||||
assert_eq!(found.iter().flatten().filter(|e| **e == Some(Edge::Top)).count(), 5, "{found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heading_sized_text_that_changes_is_a_heading_not_a_header() {
|
||||
let big = |text: &str| Evidence { size: 20.0, ..line(text, 750.0) };
|
||||
let found = run(&[vec![big("Chapter 1")], vec![big("Chapter 2")]], Some(10.0));
|
||||
assert_eq!(found, [[None], [None]]);
|
||||
let found = run(&[vec![big("Annual report")], vec![big("Annual report")]], Some(10.0));
|
||||
assert_eq!(found, [[Some(Edge::Top)], [Some(Edge::Top)]], "the same large text on every page is still a header");
|
||||
let number = |text: &str| Evidence { letters: false, ..big(text) };
|
||||
let found = run(&[vec![number("12")], vec![number("13")]], Some(10.0));
|
||||
assert_eq!(found, [[Some(Edge::Top)], [Some(Edge::Top)]], "a large page number is still a page number");
|
||||
let found = run(&[vec![big("xii")], vec![big("xiii")]], Some(10.0));
|
||||
assert_eq!(found, [[Some(Edge::Top)], [Some(Edge::Top)]], "so is a large roman one");
|
||||
let found = run(&[vec![big("Page 1")], vec![big("Page 2")], vec![big("- 3 of 9 -")], vec![big("- 4 of 9 -")]], Some(10.0));
|
||||
assert!(found.iter().flatten().all(|e| *e == Some(Edge::Top)), "a labelled page number is too: {found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_heading_differing_only_in_case_or_spacing_does_not_change() {
|
||||
let big = |text: &str| Evidence { size: 18.0, ..line(text, 750.0) };
|
||||
let found = run(&[vec![big("ANNUAL REPORT")], vec![big("Annual report")]], Some(12.0));
|
||||
assert_eq!(found, [[Some(Edge::Top)], [Some(Edge::Top)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bands_follow_the_displayed_page() {
|
||||
// Turned 90° clockwise, the displayed top is the user-space left edge (x = 0).
|
||||
let turned = Frame { rotation: 90, crop: [0.0, 0.0, 612.0, 792.0] };
|
||||
let side = Evidence { extent: Some([20.0, 300.0, 30.0, 300.0]), ..line("Side title", 0.0) };
|
||||
let objects = vec![side];
|
||||
let pages = [PageText { frame: turned, objects: &objects }, PageText { frame: turned, objects: &objects }];
|
||||
assert_eq!(find(&pages, None), [[Some(Edge::Top)], [Some(Edge::Top)]]);
|
||||
assert_eq!(run(&[objects.clone(), objects], None), [[None], [None]], "upright, it sits mid-page");
|
||||
// Upside down the displayed top is the user-space bottom; turned 270° it is the right edge.
|
||||
let upside = Frame { rotation: 180, ..turned };
|
||||
let low = vec![line("Upside down", 30.0)];
|
||||
assert_eq!(
|
||||
find(&[PageText { frame: upside, objects: &low }, PageText { frame: upside, objects: &low }], None),
|
||||
[[Some(Edge::Top)], [Some(Edge::Top)]]
|
||||
);
|
||||
let left = Frame { rotation: 270, ..turned };
|
||||
let right = vec![Evidence { extent: Some([590.0, 300.0, 600.0, 300.0]), ..line("Turned left", 0.0) }];
|
||||
assert_eq!(
|
||||
find(&[PageText { frame: left, objects: &right }, PageText { frame: left, objects: &right }], None),
|
||||
[[Some(Edge::Top)], [Some(Edge::Top)]]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bands_follow_the_crop_box() {
|
||||
// Cropped to y 100..892, text at 860 is in the top band and text at 760 is not.
|
||||
let cropped = Frame { rotation: 0, crop: [0.0, 100.0, 612.0, 892.0] };
|
||||
let objects = vec![line("Inside", 860.0), line("Below the band", 760.0)];
|
||||
let pages = [PageText { frame: cropped, objects: &objects }, PageText { frame: cropped, objects: &objects }];
|
||||
assert_eq!(find(&pages, None), [[Some(Edge::Top), None], [Some(Edge::Top), None]]);
|
||||
assert_eq!(run(&[objects.clone(), objects], None)[0], [None, Some(Edge::Top)], "against the media box it is the other way");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
//! Heading levels for blocks of text laid out on the page, by the rules Auto-tag uses for text
|
||||
//! objects ([`crate::autotag_text`]): the body style is the size carrying the most characters,
|
||||
//! a block is a heading when it is short and larger than the body (or bold where the body is
|
||||
//! not), and levels rank the heading styles over the whole document without skipping a level.
|
||||
|
||||
use crate::autotag_roles::{Evidence, roles};
|
||||
|
||||
/// What one block of text shows: a run of lines set in one style, such as a heading that wraps.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct TextBlock {
|
||||
/// The size it is shown at, in user space.
|
||||
pub size: f64,
|
||||
pub bold: bool,
|
||||
pub lines: usize,
|
||||
/// Characters shown, whitespace excluded.
|
||||
pub chars: usize,
|
||||
/// Whether it includes a letter: a number alone is never a heading.
|
||||
pub letters: bool,
|
||||
}
|
||||
|
||||
/// The heading level of each block, in document order: `Some(1)` to `Some(6)`, or `None` for a
|
||||
/// block that is not a heading. A heading's level is at most one deeper than the heading before.
|
||||
pub fn heading_levels(blocks: &[TextBlock]) -> Vec<Option<u8>> {
|
||||
let evidence: Vec<Evidence> =
|
||||
blocks.iter().map(|b| Evidence { size: b.size, bold: b.bold, lines: b.lines, chars: b.chars, letters: b.letters }).collect();
|
||||
roles(&evidence).into_iter().map(|role| role.strip_prefix('H').and_then(|n| n.parse().ok())).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn block(size: f64, bold: bool, lines: usize, chars: usize) -> TextBlock {
|
||||
TextBlock { size, bold, lines, chars, letters: true }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocks_take_the_levels_auto_tag_gives_text_objects() {
|
||||
let blocks = [
|
||||
block(18.0, true, 1, 12),
|
||||
block(11.0, false, 8, 600),
|
||||
block(14.0, true, 2, 30),
|
||||
block(11.0, false, 6, 500),
|
||||
block(18.0, true, 1, 9),
|
||||
block(11.0, true, 1, 20),
|
||||
TextBlock { letters: false, ..block(30.0, false, 1, 2) },
|
||||
];
|
||||
assert_eq!(heading_levels(&blocks), [Some(1), None, Some(2), None, Some(1), Some(2), None]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_text_has_no_headings() {
|
||||
assert!(heading_levels(&[]).is_empty());
|
||||
assert_eq!(heading_levels(&[TextBlock::default()]), [None]);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,8 @@ use pdfcraft_model::Page;
|
||||
|
||||
use crate::alt::{page_content, standard, tree_root};
|
||||
|
||||
const MAX_HEADINGS: usize = 10_000;
|
||||
/// The most headings [`headings`] returns.
|
||||
pub const MAX_HEADINGS: usize = 10_000;
|
||||
const MAX_VISITS: usize = 1_000_000;
|
||||
const MAX_DEPTH: usize = 256;
|
||||
/// Characters kept of a heading's title.
|
||||
@@ -39,7 +40,13 @@ struct Walker<'a> {
|
||||
texts: HashMap<usize, HashMap<i64, String>>,
|
||||
/// What is left of [`MAX_TITLE_SOURCE_BYTES`].
|
||||
title_left: usize,
|
||||
/// [`Walker::attr`] declined a string the allowance could not hold, since the last reset.
|
||||
declined: bool,
|
||||
out: Vec<Heading>,
|
||||
/// A limit left out a heading that could have been found.
|
||||
cut: bool,
|
||||
/// [`MAX_HEADINGS`] were found and one more was met: the walk stops.
|
||||
full: bool,
|
||||
}
|
||||
|
||||
/// Bytes of `/ActualText`, `/Alt` and `/T` strings the headings of one document decode in all.
|
||||
@@ -49,7 +56,14 @@ const MAX_TITLE_SOURCE_BYTES: usize = 32 << 20;
|
||||
|
||||
/// The headings, in document order. Headings without text or a page are left out.
|
||||
pub fn headings(doc: &Document) -> Vec<Heading> {
|
||||
let Some(root) = tree_root(doc) else { return Vec::new() };
|
||||
headings_with_truncation(doc).0
|
||||
}
|
||||
|
||||
/// [`headings`], and whether headings may be missing from it: there were more than
|
||||
/// [`MAX_HEADINGS`], the structure tree nests or branches past the walk's limits, or a heading's
|
||||
/// only title source was past the title allowance.
|
||||
pub fn headings_with_truncation(doc: &Document) -> (Vec<Heading>, bool) {
|
||||
let Some(root) = tree_root(doc) else { return (Vec::new(), false) };
|
||||
let pages = pdfcraft_model::pages(doc);
|
||||
let mut w = Walker {
|
||||
doc,
|
||||
@@ -60,19 +74,27 @@ pub fn headings(doc: &Document) -> Vec<Heading> {
|
||||
visits: 0,
|
||||
texts: HashMap::new(),
|
||||
title_left: MAX_TITLE_SOURCE_BYTES,
|
||||
declined: false,
|
||||
out: Vec::new(),
|
||||
cut: false,
|
||||
full: false,
|
||||
};
|
||||
if let Some(k) = root.get(b"K") {
|
||||
w.walk(k, None, 0, 0);
|
||||
}
|
||||
w.out
|
||||
(w.out, w.cut)
|
||||
}
|
||||
|
||||
impl Walker<'_> {
|
||||
/// Whether `k` may be visited (bounded depth and size, each object once).
|
||||
/// Whether `k` may be visited (bounded depth and size, each object once). A depth or size
|
||||
/// limit only skips `k`, and is reported in `cut`.
|
||||
fn enter(&mut self, k: &Object, depth: usize) -> bool {
|
||||
self.visits += 1;
|
||||
depth <= MAX_DEPTH && self.visits <= MAX_VISITS && self.out.len() < MAX_HEADINGS && !matches!(k, Object::Ref(r) if !self.seen.insert(*r))
|
||||
if depth > MAX_DEPTH || self.visits > MAX_VISITS {
|
||||
self.cut = true;
|
||||
return false;
|
||||
}
|
||||
!self.full && !matches!(k, Object::Ref(r) if !self.seen.insert(*r))
|
||||
}
|
||||
|
||||
fn element_of(&self, k: &Object) -> Option<(Option<ObjRef>, Dict)> {
|
||||
@@ -101,6 +123,11 @@ impl Walker<'_> {
|
||||
_ => None,
|
||||
};
|
||||
if let Some(level) = level {
|
||||
if self.out.len() >= MAX_HEADINGS {
|
||||
self.cut = true;
|
||||
self.full = true;
|
||||
return;
|
||||
}
|
||||
self.heading(obj, &d, pg, level, depth);
|
||||
return;
|
||||
}
|
||||
@@ -139,6 +166,7 @@ impl Walker<'_> {
|
||||
self.marks(kids, pg, depth + 1, &mut marks);
|
||||
}
|
||||
let Some(page) = pg.or_else(|| marks.iter().find_map(|m| m.0)).and_then(|p| self.page_index.get(&p).copied()) else { return };
|
||||
self.declined = false;
|
||||
let title = match self.attr(d, b"ActualText") {
|
||||
Some(t) => Some(t),
|
||||
None => match self.marked_text(&marks, page) {
|
||||
@@ -146,7 +174,11 @@ impl Walker<'_> {
|
||||
None => self.attr(d, b"Alt").or_else(|| self.attr(d, b"T")),
|
||||
},
|
||||
};
|
||||
let Some(title) = title else { return };
|
||||
let Some(title) = title else {
|
||||
// A title the allowance turned away is a heading left out, not one without text.
|
||||
self.cut |= self.declined;
|
||||
return;
|
||||
};
|
||||
let title: String = title.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(MAX_TITLE).collect();
|
||||
self.out.push(Heading { obj, level, title, page });
|
||||
}
|
||||
@@ -160,6 +192,7 @@ impl Walker<'_> {
|
||||
// not fit the remaining allowance is never decoded: the raw check alone let a string at
|
||||
// the raw limit decode to three times it before the allowance was reduced.
|
||||
if s.bytes.len().saturating_mul(3) > self.title_left {
|
||||
self.declined = true;
|
||||
return None;
|
||||
}
|
||||
let text = s.to_text();
|
||||
|
||||
@@ -16,7 +16,9 @@ mod alt;
|
||||
mod autotag;
|
||||
mod autotag_fields;
|
||||
mod autotag_roles;
|
||||
mod autotag_running;
|
||||
mod content;
|
||||
mod heading_levels;
|
||||
mod headings;
|
||||
mod layout_table;
|
||||
mod report;
|
||||
@@ -40,9 +42,10 @@ fn count_mark_reads(_n: usize) {
|
||||
}
|
||||
|
||||
pub use alt::{AltError, ArtifactError, Figure, figures, mark_decorative, mark_tag_artifact, set_alt};
|
||||
pub use autotag::{AutoTagError, AutoTagResult, autotag_text};
|
||||
pub use autotag::{AutoTagError, AutoTagResult, RunningText, autotag_text, running_text};
|
||||
pub use autotag_fields::tag_form_fields;
|
||||
pub use headings::{Heading, headings};
|
||||
pub use heading_levels::{TextBlock, heading_levels};
|
||||
pub use headings::{Heading, MAX_HEADINGS, headings, headings_with_truncation};
|
||||
pub use layout_table::{LayoutTableError, layout_table_to_blocks};
|
||||
pub use report::{REPORT_WORDS, report_html};
|
||||
pub use tags::{TagContentItem, TagError, TagInfo, TagPlacement, TagProperty, move_tag, set_tag_property, tag_content, tags};
|
||||
|
||||
+283
-6
@@ -5,7 +5,7 @@ use pdfcraft_cos::{Document, Object};
|
||||
use super::*;
|
||||
|
||||
/// A PDF from object bodies (object n = bodies[n - 1]) and extra trailer entries.
|
||||
fn pdf(bodies: &[String], trailer: &str) -> Document {
|
||||
pub(crate) fn pdf(bodies: &[String], trailer: &str) -> Document {
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, b) in bodies.iter().enumerate() {
|
||||
@@ -21,7 +21,7 @@ fn pdf(bodies: &[String], trailer: &str) -> Document {
|
||||
Document::open(Arc::new(out)).unwrap()
|
||||
}
|
||||
|
||||
fn stream(data: &str) -> String {
|
||||
pub(crate) fn stream(data: &str) -> String {
|
||||
format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len())
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ fn autotag_text_writes_marked_content_and_parent_tree_across_pages() {
|
||||
"",
|
||||
);
|
||||
let result = autotag_text(&mut doc).unwrap();
|
||||
assert_eq!(result, AutoTagResult { pages: 2, paragraphs: 2, headings: 1 });
|
||||
assert_eq!(result, AutoTagResult { pages: 2, paragraphs: 2, headings: 1, headers: 0, footers: 0 });
|
||||
let catalog = doc.get(doc.root().unwrap());
|
||||
let root = catalog.as_dict().unwrap().reference(b"StructTreeRoot").unwrap();
|
||||
let tree = doc.get(root);
|
||||
@@ -83,6 +83,194 @@ fn autotag_text_writes_marked_content_and_parent_tree_across_pages() {
|
||||
assert_eq!(status(&check(&reopened, &Options::default()), Rule::TaggedContent), Status::Passed);
|
||||
}
|
||||
|
||||
/// Three pages with a running header, a numbered footer and a body line repeated mid-page
|
||||
/// (#7065): the header and footer become pagination artifacts without MCIDs, the rest is tagged.
|
||||
fn running_text_pdf() -> Document {
|
||||
let page = |n: usize| {
|
||||
stream(&format!(
|
||||
"BT /F1 9 Tf 72 760 Td (Annual report) Tj ET BT /F1 12 Tf 72 640 Td (Body text on page {n} that is long enough to set the body size) Tj ET \
|
||||
BT /F1 12 Tf 72 400 Td (A body line repeated on every page) Tj ET BT /F1 9 Tf 300 30 Td (Page {n}) Tj ET"
|
||||
))
|
||||
};
|
||||
let leaf = |contents: usize| format!("<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R >>");
|
||||
pdf(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 /MediaBox [0 0 612 792] /Resources << /Font << /F1 9 0 R >> >> >>".into(),
|
||||
leaf(6),
|
||||
leaf(7),
|
||||
leaf(8),
|
||||
page(1),
|
||||
page(2),
|
||||
page(3),
|
||||
FONT.into(),
|
||||
],
|
||||
"",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autotag_text_marks_running_headers_and_footers_as_pagination_artifacts() {
|
||||
let mut doc = running_text_pdf();
|
||||
let found = running_text(&doc).unwrap();
|
||||
let listed: Vec<(usize, &str, &str)> = found.iter().map(|r| (r.page, r.subtype, r.text.as_str())).collect();
|
||||
assert_eq!(
|
||||
listed,
|
||||
[
|
||||
(0, "Header", "Annual report"),
|
||||
(0, "Footer", "Page 1"),
|
||||
(1, "Header", "Annual report"),
|
||||
(1, "Footer", "Page 2"),
|
||||
(2, "Header", "Annual report"),
|
||||
(2, "Footer", "Page 3")
|
||||
]
|
||||
);
|
||||
let result = autotag_text(&mut doc).unwrap();
|
||||
assert_eq!(result, AutoTagResult { pages: 3, paragraphs: 6, headings: 0, headers: 3, footers: 3 });
|
||||
for page in pdfcraft_model::pages(&doc) {
|
||||
let content = doc.resolve(page.dict.get(b"Contents").unwrap());
|
||||
let Object::Stream(stream) = &*content else { panic!("marked page content") };
|
||||
let text = String::from_utf8(stream.decoded_strict().unwrap()).unwrap();
|
||||
// Each BDC in order: the artifact subtype, or the tag and its MCID.
|
||||
let marks: Vec<String> = pdfcraft_content::parse(text.as_bytes())
|
||||
.ops
|
||||
.iter()
|
||||
.filter(|op| op.op == b"BDC")
|
||||
.map(|op| {
|
||||
let d = op.operands.get(1).and_then(Object::as_dict).unwrap();
|
||||
match op.name(0).unwrap() {
|
||||
b"Artifact" => {
|
||||
assert_eq!(d.name(b"Type"), Some(&b"Pagination"[..]));
|
||||
assert!(!d.contains(b"MCID"), "an artifact has no MCID");
|
||||
String::from_utf8(d.name(b"Subtype").unwrap().to_vec()).unwrap()
|
||||
}
|
||||
tag => format!("{} {}", String::from_utf8_lossy(tag), d.get(b"MCID").and_then(Object::as_int).unwrap()),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(marks, ["Header", "P 0", "P 1", "Footer"], "{text}");
|
||||
}
|
||||
let kinds: Vec<String> = tags(&doc).iter().map(|t| t.kind.clone()).collect();
|
||||
assert_eq!(kinds, ["Document", "P", "P", "P", "P", "P", "P"]);
|
||||
assert_eq!(status(&check(&doc, &Options::default()), Rule::TaggedContent), Status::Passed);
|
||||
}
|
||||
|
||||
/// Roles are assigned over the tagged text only: a running header before a heading does not
|
||||
/// shift the heading's role onto the next object.
|
||||
#[test]
|
||||
fn autotag_text_assigns_roles_past_running_headers() {
|
||||
let body = "BT /F1 12 Tf 72 640 Td (Body text that is long enough to set the body size of the document) Tj ET";
|
||||
let page = |extra: &str| stream(&format!("BT /F1 9 Tf 72 760 Td (Annual report) Tj ET {extra} {body}"));
|
||||
let leaf = |contents: usize| format!("<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R >>");
|
||||
let mut doc = pdf(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> >>".into(),
|
||||
leaf(5),
|
||||
leaf(6),
|
||||
page("BT /F1 18 Tf 72 700 Td (Introduction) Tj ET"),
|
||||
page(""),
|
||||
FONT.into(),
|
||||
],
|
||||
"",
|
||||
);
|
||||
let result = autotag_text(&mut doc).unwrap();
|
||||
assert_eq!((result.headers, result.headings, result.paragraphs), (2, 1, 2));
|
||||
let kinds: Vec<String> = tags(&doc).iter().map(|t| t.kind.clone()).collect();
|
||||
assert_eq!(kinds, ["Document", "H1", "P", "P"]);
|
||||
}
|
||||
|
||||
/// A page whose only text is running text has nothing in the parent tree and gets no
|
||||
/// `StructParents`; the next tagged page takes the next key.
|
||||
#[test]
|
||||
fn autotag_text_gives_a_page_of_running_text_alone_no_struct_parents() {
|
||||
let header = "BT /F1 9 Tf 72 760 Td (Annual report) Tj ET";
|
||||
let leaf = |contents: usize| format!("<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R >>");
|
||||
let mut doc = pdf(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> >>".into(),
|
||||
leaf(5),
|
||||
leaf(6),
|
||||
stream(header),
|
||||
stream(&format!("{header} BT /F1 12 Tf 72 640 Td (Body) Tj ET")),
|
||||
FONT.into(),
|
||||
],
|
||||
"",
|
||||
);
|
||||
let result = autotag_text(&mut doc).unwrap();
|
||||
assert_eq!(result, AutoTagResult { pages: 1, paragraphs: 1, headings: 0, headers: 2, footers: 0 });
|
||||
let keys: Vec<Option<i64>> = pdfcraft_model::pages(&doc).iter().map(|p| p.dict.get(b"StructParents").and_then(Object::as_int)).collect();
|
||||
assert_eq!(keys, [None, Some(0)]);
|
||||
assert_eq!(status(&check(&doc, &Options::default()), Rule::TaggedContent), Status::Passed);
|
||||
}
|
||||
|
||||
/// A body line turned to run down from the top of each page starts in the header band but does
|
||||
/// not lie inside it: it is not running text.
|
||||
#[test]
|
||||
fn autotag_text_leaves_turned_text_that_runs_out_of_the_band_tagged() {
|
||||
let body = "BT /F1 12 Tf 0 -1 1 0 72 760 Tm (A body line set turned so that it runs down the page) Tj ET";
|
||||
let leaf = |contents: usize| format!("<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R >>");
|
||||
let doc = pdf(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> >>".into(),
|
||||
leaf(5),
|
||||
leaf(6),
|
||||
stream(body),
|
||||
stream(body),
|
||||
FONT.into(),
|
||||
],
|
||||
"",
|
||||
);
|
||||
assert_eq!(running_text(&doc).unwrap(), []);
|
||||
}
|
||||
|
||||
/// Turned body text whose negative character spacing brings each line's advance back to zero
|
||||
/// still has glyphs running down the page from the header band: it is not running text.
|
||||
#[test]
|
||||
fn autotag_text_leaves_turned_text_pulled_back_by_negative_spacing_tagged() {
|
||||
// A is 12 units wide and advances 6 at Tc -6; B is 0 wide and advances -6. Thirty of each
|
||||
// end where they began, but the A glyphs reach 186 units down from y 760.
|
||||
let body = format!("BT /F1 12 Tf -6 Tc 0 -1 1 0 72 760 Tm ({}{}) Tj ET", "A".repeat(30), "B".repeat(30));
|
||||
let font = "<< /Type /Font /Subtype /Type1 /BaseFont /HouseFont /FirstChar 65 /LastChar 66 /Widths [1000 0] >>";
|
||||
let leaf = |contents: usize| format!("<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R >>");
|
||||
let mut doc = pdf(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> >>".into(),
|
||||
leaf(5),
|
||||
leaf(6),
|
||||
stream(&body),
|
||||
stream(&body),
|
||||
font.into(),
|
||||
],
|
||||
"",
|
||||
);
|
||||
assert_eq!(running_text(&doc).unwrap(), []);
|
||||
let result = autotag_text(&mut doc).unwrap();
|
||||
assert_eq!((result.headers, result.footers, result.paragraphs), (0, 0, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autotag_text_leaves_a_single_page_header_tagged() {
|
||||
let mut doc = pdf(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".into(),
|
||||
stream(
|
||||
"BT /F1 9 Tf 72 760 Td (Annual report) Tj ET BT /F1 12 Tf 72 640 Td (Body text long enough to set the body size) Tj ET BT /F1 9 Tf 300 30 Td (1) Tj ET",
|
||||
),
|
||||
FONT.into(),
|
||||
],
|
||||
"",
|
||||
);
|
||||
assert_eq!(running_text(&doc).unwrap(), []);
|
||||
let result = autotag_text(&mut doc).unwrap();
|
||||
assert_eq!((result.headers, result.footers, result.paragraphs), (0, 0, 3));
|
||||
}
|
||||
|
||||
/// Page content behind a predictor whose `/DecodeParms` are given by reference is read through
|
||||
/// them: autotagging writes the text back as it was, marked, not with the predictor's tag bytes in
|
||||
/// it (a `\0` every eight bytes, which split `24` into `2 4`).
|
||||
@@ -108,7 +296,7 @@ fn autotag_text_reads_content_with_parameters_given_by_reference() {
|
||||
let mut predicted = pdfcraft_cos::Stream::flate(Dict::new(), &rows);
|
||||
predicted.dict.set(b"DecodeParms".to_vec(), Object::Ref(parms));
|
||||
doc.set(ObjRef::new(4, 0), predicted);
|
||||
assert_eq!(autotag_text(&mut doc).unwrap(), AutoTagResult { pages: 1, paragraphs: 1, headings: 0 });
|
||||
assert_eq!(autotag_text(&mut doc).unwrap(), AutoTagResult { pages: 1, paragraphs: 1, headings: 0, headers: 0, footers: 0 });
|
||||
let page = &pdfcraft_model::pages(&doc)[0];
|
||||
let written = doc.resolve(page.dict.get(b"Contents").unwrap());
|
||||
let Object::Stream(written) = &*written else { panic!("page content") };
|
||||
@@ -161,7 +349,7 @@ fn autotag_text_marks_vector_graphics_and_images_as_artifacts() {
|
||||
"",
|
||||
);
|
||||
let result = autotag_text(&mut doc).unwrap();
|
||||
assert_eq!(result, AutoTagResult { pages: 1, paragraphs: 1, headings: 0 });
|
||||
assert_eq!(result, AutoTagResult { pages: 1, paragraphs: 1, headings: 0, headers: 0, footers: 0 });
|
||||
let report = check(&doc, &Options { rules: [Rule::TaggedPdf, Rule::TaggedContent].into(), pages: None });
|
||||
assert_eq!(status(&report, Rule::TaggedPdf), Status::Passed);
|
||||
assert_eq!(status(&report, Rule::TaggedContent), Status::Passed);
|
||||
@@ -1680,8 +1868,97 @@ fn headings_naming_one_large_string_stop_decoding_it_at_the_allowance() {
|
||||
format!("({})", "a".repeat(512 << 10)),
|
||||
];
|
||||
objects.extend((0..count).map(|_| "<< /S /H1 /P 6 0 R /Pg 3 0 R /ActualText 7 0 R >>".to_string()));
|
||||
let found = headings(&pdf(&objects, ""));
|
||||
let (found, cut) = headings_with_truncation(&pdf(&objects, ""));
|
||||
assert!(!found.is_empty() && found.len() < count, "{}", found.len());
|
||||
assert!(cut, "headings whose title the allowance turned away were dropped unreported");
|
||||
}
|
||||
|
||||
/// A title source too large for the allowance is passed over for the next one, and the heading
|
||||
/// it names is kept and not reported as missing.
|
||||
#[test]
|
||||
fn a_title_too_large_for_the_allowance_falls_back_without_truncation() {
|
||||
let objects = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /MarkInfo << /Marked true >> /StructTreeRoot 5 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R >>".to_string(),
|
||||
stream("BT ET"),
|
||||
"<< /Type /StructTreeRoot /K 6 0 R >>".to_string(),
|
||||
"<< /S /Document /P 5 0 R /K [8 0 R] >>".to_string(),
|
||||
format!("({})", "a".repeat((32 << 20) / 3 + 1)),
|
||||
"<< /S /H1 /P 6 0 R /Pg 3 0 R /ActualText 7 0 R /Alt (Short) >>".to_string(),
|
||||
];
|
||||
let (found, cut) = headings_with_truncation(&pdf(&objects, ""));
|
||||
let titles: Vec<String> = found.into_iter().map(|h| h.title).collect();
|
||||
assert_eq!((titles, cut), (vec!["Short".to_string()], false));
|
||||
}
|
||||
|
||||
/// A tree of `count` H1 elements, each with its text and page.
|
||||
fn many_headings(count: usize) -> Vec<String> {
|
||||
let kids: String = (0..count).map(|i| format!("{} 0 R ", i + 7)).collect();
|
||||
let mut objects = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 5 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R >>".to_string(),
|
||||
stream("BT ET"),
|
||||
"<< /Type /StructTreeRoot /K 6 0 R >>".to_string(),
|
||||
format!("<< /S /Document /P 5 0 R /K [{kids}] >>"),
|
||||
];
|
||||
objects.extend((0..count).map(|_| "<< /S /H1 /P 6 0 R /Pg 3 0 R /ActualText (Head) >>".to_string()));
|
||||
objects
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headings_past_the_cap_are_reported() {
|
||||
let (at_cap, cut) = headings_with_truncation(&pdf(&many_headings(MAX_HEADINGS), ""));
|
||||
assert_eq!((at_cap.len(), cut), (MAX_HEADINGS, false));
|
||||
let (over, cut) = headings_with_truncation(&pdf(&many_headings(MAX_HEADINGS + 1), ""));
|
||||
assert_eq!((over.len(), cut), (MAX_HEADINGS, true), "a heading past the cap was dropped unreported");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_heading_nested_past_the_depth_limit_is_reported() {
|
||||
let mut objs = headings_doc();
|
||||
let (found, cut) = headings_with_truncation(&pdf(&objs, ""));
|
||||
assert!(!found.is_empty() && !cut);
|
||||
// Element 17 opens a chain of 300 sections, each holding the next, around one H1.
|
||||
let first = objs.len() + 1;
|
||||
objs[9] = format!("<< /S /Document /K [12 0 R {first} 0 R] >>");
|
||||
objs.extend((1..=300).map(|i| format!("<< /S /Sect /K {} 0 R >>", first + i)));
|
||||
objs.push("<< /S /H1 /Pg 3 0 R /ActualText (Deep) >>".into());
|
||||
let (found, cut) = headings_with_truncation(&pdf(&objs, ""));
|
||||
assert!(found.iter().all(|h| h.title != "Deep") && cut, "a heading too deep to reach was dropped unreported");
|
||||
}
|
||||
|
||||
/// A branch too deep to walk is skipped, not the end of the walk: a heading after it is found.
|
||||
#[test]
|
||||
fn a_heading_after_a_branch_past_the_depth_limit_is_found() {
|
||||
let mut objs = headings_doc();
|
||||
let first = objs.len() + 1;
|
||||
objs[9] = format!("<< /S /Document /K [{first} 0 R 12 0 R] >>");
|
||||
objs.extend((1..=300).map(|i| format!("<< /S /Sect /K {} 0 R >>", first + i)));
|
||||
objs.push("<< /S /H1 /Pg 3 0 R /ActualText (Deep) >>".into());
|
||||
let (found, cut) = headings_with_truncation(&pdf(&objs, ""));
|
||||
let titles: Vec<&str> = found.iter().map(|h| h.title.as_str()).collect();
|
||||
assert_eq!((titles, cut), (vec!["Chapter One"], true), "the deep branch stopped the walk");
|
||||
}
|
||||
|
||||
/// An H1 `sects + 1` elements down whose title is only its marked content.
|
||||
fn heading_under_sections(sects: usize) -> (Vec<Heading>, bool) {
|
||||
let mut objs = headings_doc();
|
||||
let first = objs.len() + 1;
|
||||
objs[9] = format!("<< /S /Document /K {first} 0 R >>");
|
||||
objs.extend((1..=sects).map(|i| format!("<< /S /Sect /K {} 0 R >>", first + i)));
|
||||
objs.push("<< /S /H1 /Pg 3 0 R /K 0 >>".into());
|
||||
headings_with_truncation(&pdf(&objs, ""))
|
||||
}
|
||||
|
||||
/// Marked content past the depth limit is reported too: the H1 whose title it holds is lost.
|
||||
#[test]
|
||||
fn marked_content_past_the_depth_limit_is_reported() {
|
||||
let (found, cut) = heading_under_sections(254);
|
||||
assert_eq!((found.iter().map(|h| h.title.as_str()).collect::<Vec<_>>(), cut), (vec!["Chapter One"], false));
|
||||
let (found, cut) = heading_under_sections(255);
|
||||
assert!(found.is_empty() && cut, "a heading whose text was too deep was dropped unreported");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -206,19 +206,31 @@ fn review_html(record: &Value) -> Result<String> {
|
||||
Ok(html)
|
||||
}
|
||||
|
||||
/// Running headers and footers listed by `accessibility_autotag_apply`, at most.
|
||||
const MAX_RUNNING_LISTED: usize = 200;
|
||||
|
||||
/// Tags in one page of `accessibility_tags`, by default and at most.
|
||||
const TAG_PAGE: usize = 200;
|
||||
const MAX_TAG_PAGE: usize = 1000;
|
||||
|
||||
impl Automation {
|
||||
pub(crate) fn accessibility_autotag_apply(&mut self, a: &Args) -> Result<Value> {
|
||||
let id = self.doc(a)?.id;
|
||||
let doc = self.doc(a)?;
|
||||
let id = doc.id;
|
||||
// Read before applying: once tagged, the document is refused. A refusal here is Apply's too.
|
||||
let running = doc.autotag_running_text().unwrap_or_default();
|
||||
let warnings = self.apply_with_warnings(id, pdfcraft_engine::Edit::AutoTagText)?;
|
||||
let tags = self.accessibility_tags(a)?;
|
||||
let out = json!({
|
||||
"tags": tags["tags"], "count": tags["count"],
|
||||
"note": "Text objects were tagged as headings (H1-H6, by size and weight against the body text) or paragraphs. Review heading roles, reading order and remaining accessibility findings manually.",
|
||||
});
|
||||
let listed: Vec<Value> =
|
||||
running.iter().take(MAX_RUNNING_LISTED).map(|r| json!({ "page": r.page + 1, "subtype": r.subtype, "text": r.text })).collect();
|
||||
let note = format!(
|
||||
"Text objects were tagged as headings (H1-H6, by size and weight against the body text) or paragraphs. \
|
||||
{} text objects repeating at the top or bottom of the pages were marked as running header or footer artifacts \
|
||||
instead (listed in running_text{}). Review heading roles, the running text, reading order and remaining accessibility findings manually.",
|
||||
running.len(),
|
||||
if running.len() > MAX_RUNNING_LISTED { format!(", first {MAX_RUNNING_LISTED}") } else { String::new() },
|
||||
);
|
||||
let out = json!({ "tags": tags["tags"], "count": tags["count"], "running_text": listed, "running_count": running.len(), "note": note });
|
||||
Ok(with_warnings(out, warnings))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Bookmark trees in and out of documents: `bookmark_export`, `bookmark_import`, `bookmark_copy`.
|
||||
//! Bookmark trees in and out of documents: `bookmark_export`, `bookmark_import`, `bookmark_copy`,
|
||||
//! and `bookmark_suggest`, which proposes a tree for review before `bookmark_import` applies it.
|
||||
//!
|
||||
//! The portable form is JSON: `{"bookmarks": [node, …]}`, where a node is `title`, `page`
|
||||
//! (1-based, or `null` for one that goes nowhere), `view` (`{"type", "values"}`: a destination
|
||||
@@ -60,6 +61,31 @@ impl Automation {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub(crate) fn bookmark_suggest(&self, a: &Args) -> Result<Value> {
|
||||
// The titles are the document's text, as text_lines is.
|
||||
let doc = self.doc_to_copy(a)?;
|
||||
let id = doc.id.0;
|
||||
let s = doc.suggest_outline().ok_or_else(|| failed(format!("document {id} can't be read for editing")))?;
|
||||
let source = match s.source {
|
||||
pdfcraft_engine::suggest_outline::OutlineSource::Structure => "structure",
|
||||
pdfcraft_engine::suggest_outline::OutlineSource::Layout => "layout",
|
||||
};
|
||||
let mut out = json!({
|
||||
"source": source,
|
||||
"bookmarks": s.tree().iter().map(node_json).collect::<Vec<_>>(),
|
||||
"headings": s.entries.len(),
|
||||
"pages": s.pages,
|
||||
"pages_read": s.pages_read,
|
||||
"truncated": s.truncated,
|
||||
});
|
||||
if s.entries.is_empty() {
|
||||
out["note"] = json!(
|
||||
"no headings found: the text may be in one style; text_styles lists the styles, and bookmark_from_text_styles makes bookmarks from chosen ones"
|
||||
);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn outline_of(&self, id: DocId, path: &[usize]) -> Result<pdfcraft_engine::OutlineTree> {
|
||||
match self.session.outline_tree(id, path) {
|
||||
// The engine names the path 0-based; the caller gave it 1-based.
|
||||
|
||||
@@ -203,6 +203,7 @@ impl Automation {
|
||||
"bookmark_export" => self.bookmark_export(&a)?,
|
||||
"bookmark_import" => self.bookmark_import(&a)?,
|
||||
"bookmark_copy" => self.bookmark_copy(&a)?,
|
||||
"bookmark_suggest" => self.bookmark_suggest(&a)?,
|
||||
"bookmark_add" => {
|
||||
let page = self.page(&a)?;
|
||||
let parent = a.opt_path("parent")?.unwrap_or_default();
|
||||
|
||||
@@ -111,7 +111,8 @@ fn resolve_paper(name: Option<&str>, printer: Option<&str>) -> Result<((f64, f64
|
||||
/// naming none got (A4 under Letter sheets on the queue in #3752), and tells CUPS which way the
|
||||
/// laid-out `sheets` run, as the Print dialog does (#2713): an orientation the caller chose in
|
||||
/// `options` stands. It asks the driver for grayscale only when the pages aren't grey pictures
|
||||
/// already ([`print::driver_needs_grayscale`]).
|
||||
/// already ([`print::driver_needs_grayscale`]). Any caller-supplied `media` option (case-insensitive)
|
||||
/// is replaced by the laid-out paper's media.
|
||||
fn spool_job(
|
||||
a: &Args,
|
||||
printer: &str,
|
||||
@@ -143,7 +144,10 @@ fn spool_job(
|
||||
grey_pages: false,
|
||||
title,
|
||||
options: {
|
||||
let mut options: Vec<(String, String)> = options.into_iter().chain(media.map(|m| ("media".to_string(), m.to_string()))).collect();
|
||||
let mut options: Vec<(String, String)> = options.into_iter().filter(|(k, _)| !k.eq_ignore_ascii_case("media")).collect();
|
||||
if let Some(m) = media {
|
||||
options.push(("media".to_string(), m.to_string()));
|
||||
}
|
||||
print::add_cups_orientation(&mut options, sheets);
|
||||
options
|
||||
},
|
||||
@@ -581,4 +585,26 @@ mod tests {
|
||||
assert_eq!(paper_size(spec), None, "{spec}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A user-supplied `media` option must not reach the spooler alongside the
|
||||
/// laid-out paper's own `media` option: the job carries exactly one `media`
|
||||
/// entry, and it is the paper the sheets were laid out on.
|
||||
#[test]
|
||||
fn spool_job_does_not_duplicate_media_option() {
|
||||
let index = 0; // US Letter
|
||||
let media_name = print::cups_media(index).unwrap();
|
||||
let job = spool_job(
|
||||
&Args(&json!({ "options": { "InputSlot": "Tray3", "media": "A4" } })),
|
||||
"Office",
|
||||
"a.pdf".into(),
|
||||
None,
|
||||
Some(media_name),
|
||||
None,
|
||||
&[],
|
||||
)
|
||||
.unwrap();
|
||||
let media: Vec<&(String, String)> = job.options.iter().filter(|(k, _)| k == "media").collect();
|
||||
assert_eq!(media, [print::media_option(index).as_ref().unwrap()]);
|
||||
assert!(job.options.contains(&("InputSlot".to_string(), "Tray3".to_string())));
|
||||
}
|
||||
}
|
||||
@@ -494,6 +494,13 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"Make bookmarks from the document's tagged headings (H, H1-H6), nested by level under a new first bookmark titled \"Untitled\". Fails if the document has no tagged headings. Returns the first page of the bookmark tree (see bookmark_list). Undoable.",
|
||||
)
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
t(
|
||||
"bookmark_suggest",
|
||||
"Suggest bookmarks",
|
||||
"Propose a bookmark tree for the whole document, for review: its tagged headings (H, H1-H6) when it has them (source \"structure\"), or else headings found from how its text looks (source \"layout\"): short blocks set larger than the body text, or bold where the body is not, levelled by size without skipping a level, a heading set on several lines as one bookmark that goes to its top; captions such as \"Figure 3\" are left out. Reads the first 5000 pages for a layout suggestion; pages_read counts the pages whose text was read. truncated is true when headings may be missing: the document has more pages, a page's text could not be read, there were more than 10000 headings (the first 10000 are given), or the structure tree nests or branches too far to read whole. Changes nothing: bookmarks is in bookmark_export's form, so edit titles, remove entries or move them into or out of a bookmark's children to change the nesting, then apply it with bookmark_import (with replace to drop the existing outline), one undoable step. headings counts the suggested bookmarks; note says what to try when there are none. Needs the document to allow copying, as its text is returned.",
|
||||
)
|
||||
.ro()
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
t(
|
||||
"text_styles",
|
||||
"List text styles",
|
||||
@@ -774,7 +781,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
t(
|
||||
"doc_print",
|
||||
"Print",
|
||||
"Print with Acrobat's Print dialog options, or save the print-ready PDF. pages: a range such as \"1-3, 6, 9-\" (page labels allowed, \"(n)\" for the nth page whatever its label, unless a page is labelled exactly \"(n)\", since labels are looked up first; default all); subset odd/even (by page number, as Acrobat counts them: pages 2, 7-10 with even prints 2, 8 and 10, not every second page of the range); reverse. layout: fit (default), actual, shrink, custom (scale %), multiple (per_sheet 2/4/6/9/16, which turns the sheet to suit the grid, or a custom grid of cols across by rows down, each 1-99, on the sheet as oriented (auto prints portrait); order, border, auto_rotate; cut-stack order arranges single-sided sheets for cutting into piles and stacking left to right, top to bottom, keeping sheet order within each pile; duplex must be off), booklet (booklet_subset both/front/back, binding left/right; a booklet sets two-sided itself, as Acrobat does: both flips on the short edge, front or back prints one-sided), poster (scale %, overlap pt, cut_marks). orientation auto/portrait/landscape; comments_forms document / document-and-markups (default) / document-and-stamps / form-fields-only; paper Letter/Legal/Tabloid, ARCH A/B/C/D/E1/E, ANSI C/D/E, A0/A1/A2/A3/A4/A5/A6, US #10 Envelope, a driver paper name from printer_papers, or dimensions \"<w>x<h>\"; when printer is given and paper is omitted, uses the printer's default paper if available; use layout actual for 100% in the print-ready PDF; printer drivers may still substitute paper or scale. Then path (save) or printer (a name or \"default\") with copies, collate, duplex off/long-edge/short-edge, grayscale, and options (driver options from printer_options, CUPS). color_management app (Acrobat's Color Handling, the app managing colours) prints the pages as images converted into color_profile with rendering_intent and black_point_compensation; turn the driver's own colour management off for that job, or the printer converts them again.",
|
||||
"Print with Acrobat's Print dialog options, or save the print-ready PDF. pages: a range such as \"1-3, 6, 9-\" (page labels allowed, \"(n)\" for the nth page whatever its label, unless a page is labelled exactly \"(n)\", since labels are looked up first; default all); subset odd/even (by page number, as Acrobat counts them: pages 2, 7-10 with even prints 2, 8 and 10, not every second page of the range); reverse. layout: fit (default), actual, shrink, custom (scale %), multiple (per_sheet 2/4/6/9/16, which turns the sheet to suit the grid, or a custom grid of cols across by rows down, each 1-99, on the sheet as oriented (auto prints portrait); order, border, auto_rotate; cut-stack order arranges single-sided sheets for cutting into piles and stacking left to right, top to bottom, keeping sheet order within each pile; duplex must be off), booklet (booklet_subset both/front/back, binding left/right; a booklet sets two-sided itself, as Acrobat does: both flips on the short edge, front or back prints one-sided), poster (scale %, overlap pt, cut_marks). orientation auto/portrait/landscape; comments_forms document / document-and-markups (default) / document-and-stamps / form-fields-only; paper Letter/Legal/Tabloid, ARCH A/B/C/D/E1/E, ANSI C/D/E, A0/A1/A2/A3/A4/A5/A6, US #10 Envelope, a driver paper name from printer_papers, or dimensions \"<w>x<h>\"; when printer is given and paper is omitted, uses the printer's default paper if available; use layout actual for 100% in the print-ready PDF; printer drivers may still substitute paper or scale. Then path (save) or printer (a name or \"default\") with copies, collate, duplex off/long-edge/short-edge, grayscale, and options (driver options from printer_options, CUPS). color_management app (Acrobat's Color Handling, the app managing colours) prints the pages as images converted into color_profile with rendering_intent and black_point_compensation; turn the driver's own colour management off for that job, or the printer converts them again. Any caller-supplied `media` option is replaced by the paper the document was laid out on."
|
||||
)
|
||||
.with(schema(
|
||||
json!({
|
||||
@@ -797,7 +804,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"cut_marks": { "type": "boolean" },
|
||||
"orientation": { "type": "string", "enum": ["auto", "portrait", "landscape"] },
|
||||
"comments_forms": { "type": "string", "enum": ["document", "document-and-markups", "document-and-stamps", "form-fields-only"] },
|
||||
"paper": { "type": "string", "description": "A paper name (US Letter, A4…) or a size of its own such as 8.5x14in, 210x297mm, 10x15cm or 612x792pt (1 to 200 inches a side)." },
|
||||
"paper": { "type": "string", "description": "A paper name (US Letter, A4…) or a size of its own such as 8.5x14in, 210x297mm, 10x15cm or 612x792pt (1 to 200 inches a side). The paper the document is laid out on determines the `media` option sent to the printer; any caller-supplied `media` option in `options` is replaced by this paper." },
|
||||
"path": { "type": "string" },
|
||||
"printer": { "type": "string" },
|
||||
"copies": { "type": "integer", "minimum": 1, "maximum": 999 },
|
||||
@@ -807,7 +814,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"area": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4, "description": "Print a selected area: [x0, y0, x1, y1] in points from the top-left of the displayed page, of the one page in pages, sized by layout fit/actual/shrink/custom." },
|
||||
"as_image": { "type": "boolean", "description": "Print as image (Acrobat's Advanced Print Setup): every page rendered to a picture at dpi before it is placed on the paper, for printers that skip text, shading or transparency; the print is no longer searchable text, and with grayscale the pictures are grey, so the printer isn't asked for grayscale (a driver without that setting still prints them)." },
|
||||
"dpi": { "type": "number", "minimum": 72, "maximum": 600, "description": "Resolution for as_image (default 300)." },
|
||||
"options": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Printer driver options from printer_options: key → choice value." },
|
||||
"options": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Printer driver options from printer_options: key → choice value. Any caller-supplied `media` option is replaced by the paper the document was laid out on." },
|
||||
"color_management": { "type": "string", "enum": ["printer", "app"], "description": "Who converts the colours: printer (default, the driver does) or app, which prints the pages as images (dpi, grayscale apply) converted from sRGB into color_profile." },
|
||||
"color_profile": { "type": "string", "description": "For color_management app: a name or file name from print_color_profiles, or the path of an RGB or grey ICC printer profile." },
|
||||
"rendering_intent": { "type": "string", "enum": ["perceptual", "relative", "saturation", "absolute"], "description": "For color_management app: how colours the printer can't reach are mapped (default relative colorimetric)." },
|
||||
@@ -1320,7 +1327,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
t("accessibility_autotag_preview", "Preview automatic tags", "Propose paragraph and heading tags for visible text blocks on one page. Returns page bounds, tentative roles and reasons. Does not change the PDF or claim accessibility compliance. Images, tables, lists, annotations and existing structure require separate review.")
|
||||
.ro()
|
||||
.with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 } }), &["doc", "page"])),
|
||||
t("accessibility_autotag_apply", "Automatically tag text-only PDF", "Write marked content, a Document structure element, paragraph tags and a parent tree for every text object in an untagged, text-only PDF. Refuses graphics, images, annotations, forms, existing tags and malformed streams before changing anything. Review all resulting roles; this does not certify accessibility. Undoable.")
|
||||
t("accessibility_autotag_apply", "Automatically tag text-only PDF", "Write marked content, a Document structure element, heading and paragraph tags and a parent tree for every text object in an untagged, text-only PDF. Text repeating at the top or bottom of most pages (running headers, footers and page numbers) is marked as pagination artifacts instead and listed in running_text. Refuses graphics, images, annotations, forms, existing tags and malformed streams before changing anything. Review all resulting roles; this does not certify accessibility. Undoable.")
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
t("accessibility_autotag_form_fields", "Tag form fields", "Write `/Form` tags, widget structure-parent keys, and a parent tree for all page widgets in an untagged AcroForm. Existing tag trees are refused for review. Text, figures, links, and other content are not tagged.")
|
||||
.cmd("a11y.autotag_fields")
|
||||
|
||||
@@ -554,6 +554,68 @@ fn autotag_apply_tags_headings_by_size_across_pages() {
|
||||
assert_eq!(nesting["status"], "passed", "{check}");
|
||||
}
|
||||
|
||||
/// #7065: Apply marks a running header and a numbered footer as pagination artifacts and lists
|
||||
/// them, and tags a body line that repeats mid-page like any other text.
|
||||
#[test]
|
||||
fn autotag_apply_marks_running_headers_and_footers_as_artifacts() {
|
||||
let dir = workdir("autotag-running");
|
||||
let page = |n: usize| {
|
||||
format!(
|
||||
"BT /FR 9 Tf 72 760 Td (Annual report) Tj ET BT /FR 11 Tf 72 640 Td (Body text on page {n} that runs long enough to set the body size) Tj ET \
|
||||
BT /FR 11 Tf 72 400 Td (A body line repeated on every page) Tj ET BT /FR 9 Tf 300 30 Td (Page {n}) Tj ET"
|
||||
)
|
||||
};
|
||||
let mut objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 /MediaBox [0 0 612 792] /Resources << /Font << /FR 9 0 R >> >> >>".into(),
|
||||
];
|
||||
objs.extend((6..9).map(|c| format!("<< /Type /Page /Parent 2 0 R /Contents {c} 0 R >>")));
|
||||
objs.extend((1..4).map(|n| {
|
||||
let content = page(n);
|
||||
format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len())
|
||||
}));
|
||||
objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into());
|
||||
let mut bytes = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(bytes.len());
|
||||
bytes.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = bytes.len();
|
||||
bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
std::fs::write(dir.join("running.pdf"), bytes).unwrap();
|
||||
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "running.pdf" }))["doc"].as_u64().unwrap();
|
||||
let applied = ok(&mut a, "accessibility_autotag_apply", json!({ "doc": doc }));
|
||||
let types: Vec<&str> = applied["tags"].as_array().unwrap().iter().map(|t| t["type"].as_str().unwrap()).collect();
|
||||
assert_eq!(types, ["Document", "P", "P", "P", "P", "P", "P"], "only the body text is tagged: {applied}");
|
||||
assert_eq!(applied["running_count"], 6);
|
||||
let listed: Vec<(u64, &str, &str)> = applied["running_text"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|r| (r["page"].as_u64().unwrap(), r["subtype"].as_str().unwrap(), r["text"].as_str().unwrap()))
|
||||
.collect();
|
||||
assert_eq!(listed[..2], [(1, "Header", "Annual report"), (1, "Footer", "Page 1")]);
|
||||
assert_eq!(listed[5], (3, "Footer", "Page 3"));
|
||||
assert!(applied["note"].as_str().unwrap().contains("6 text objects"), "{applied}");
|
||||
let check = ok(&mut a, "accessibility_check", json!({ "doc": doc, "rules": ["tagged-content"] }));
|
||||
let content = check["results"].as_array().unwrap().iter().find(|r| r["rule"] == "tagged-content").unwrap();
|
||||
assert_eq!(content["status"], "passed", "{check}");
|
||||
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "tagged.pdf" }));
|
||||
let reopened = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join("tagged.pdf")).unwrap())).unwrap();
|
||||
let first = pdfcraft_model::pages(&reopened).into_iter().next().unwrap();
|
||||
let pdfcraft_cos::Object::Stream(stream) = &*reopened.resolve(first.dict.get(b"Contents").unwrap()) else { panic!("page content") };
|
||||
let text = String::from_utf8(stream.decoded_strict().unwrap()).unwrap();
|
||||
assert!(text.contains("/Artifact <</Type /Pagination/Subtype /Header>> BDC"), "{text}");
|
||||
assert!(text.contains("/Artifact <</Type /Pagination/Subtype /Footer>> BDC"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autotag_form_fields_writes_reviewable_widget_tags() {
|
||||
let dir = workdir("autotag-form-fields");
|
||||
|
||||
@@ -25,6 +25,7 @@ mod portfolio_info;
|
||||
mod redact_after_stray_q_form;
|
||||
mod redact_text_after_q;
|
||||
mod render_warnings;
|
||||
mod suggest_outline;
|
||||
mod text_copy;
|
||||
mod timesheet_compat;
|
||||
mod unreadable_objects;
|
||||
@@ -0,0 +1,157 @@
|
||||
//! #6020: `bookmark_suggest` proposes an outline for an untagged document from how its text looks,
|
||||
//! uses the tags once there are some, and its proposal goes back in through `bookmark_import`.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use pdfcraft_automation::{Automation, Content};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn tmp(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("pdfcraft-suggest-outline-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
fn ok(a: &mut Automation, tool: &str, args: Value) -> Value {
|
||||
match a.call(tool, &args) {
|
||||
Ok(mut c) => match c.remove(0) {
|
||||
Content::Json(v) => v,
|
||||
other => panic!("{tool}: expected JSON, got {other:?}"),
|
||||
},
|
||||
Err(e) => panic!("{tool} {args}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
const BODY: &str = "Body text runs on for a good many characters across the page.";
|
||||
|
||||
/// A chapter heading (Helvetica-Bold 20) set on two lines, body text (Helvetica 11), a bold
|
||||
/// caption, a section heading (Helvetica-Bold 14), and a second chapter on page 2.
|
||||
fn report_pdf() -> Vec<u8> {
|
||||
let body = |y: u32| format!("BT /FR 11 Tf 72 {y} Td ({BODY}) Tj ET ");
|
||||
let page1 = format!(
|
||||
"BT /FB 20 Tf 72 740 Td (Getting started) Tj 0 -22 Td (with the toolkit) Tj ET {}{}\
|
||||
BT /FB 14 Tf 72 640 Td (Figure 1 The toolkit) Tj ET {}\
|
||||
BT /FB 14 Tf 72 590 Td (Installing) Tj ET {}{}",
|
||||
body(690),
|
||||
body(676),
|
||||
body(620),
|
||||
body(566),
|
||||
body(552)
|
||||
);
|
||||
let page2 = format!("BT /FB 20 Tf 72 740 Td (Reference) Tj ET {}{}", body(700), body(686));
|
||||
two_pages(&page1, &page2)
|
||||
}
|
||||
|
||||
/// Two untagged pages drawing `page1` and `page2` with `/FB` (Helvetica-Bold) and `/FR`
|
||||
/// (Helvetica).
|
||||
fn two_pages(page1: &str, page2: &str) -> Vec<u8> {
|
||||
let contents = [page1, page2];
|
||||
let mut objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /FB 7 0 R /FR 8 0 R >> >> >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Contents 5 0 R >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Contents 6 0 R >>".into(),
|
||||
];
|
||||
objs.extend(contents.iter().map(|c| format!("<< /Length {} >>\nstream\n{c}\nendstream", c.len())));
|
||||
objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>".into());
|
||||
objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into());
|
||||
let mut bytes = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(bytes.len());
|
||||
bytes.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = bytes.len();
|
||||
bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
bytes
|
||||
}
|
||||
|
||||
/// (title, page, children's titles) for each top-level node.
|
||||
fn outline(nodes: &Value) -> Vec<(String, u64, Vec<String>)> {
|
||||
let title = |n: &Value| n["title"].as_str().unwrap().to_string();
|
||||
nodes
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|n| (title(n), n["page"].as_u64().unwrap(), n["children"].as_array().map_or(Vec::new(), |c| c.iter().map(title).collect())))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggest_from_layout_then_import_and_undo() {
|
||||
let dir = tmp("layout");
|
||||
std::fs::write(dir.join("report.pdf"), report_pdf()).unwrap();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap();
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "report.pdf" }))["doc"].as_u64().unwrap();
|
||||
let s = ok(&mut a, "bookmark_suggest", json!({ "doc": doc }));
|
||||
assert_eq!(s["source"], "layout");
|
||||
assert_eq!(s["truncated"], false);
|
||||
assert_eq!((s["headings"].as_u64(), s["pages"].as_u64(), s["pages_read"].as_u64()), (Some(3), Some(2), Some(2)));
|
||||
let expected =
|
||||
vec![("Getting started with the toolkit".to_string(), 1, vec!["Installing".to_string()]), ("Reference".to_string(), 2, Vec::new())];
|
||||
assert_eq!(outline(&s["bookmarks"]), expected, "the caption is left out and the wrapped heading is one bookmark");
|
||||
let view = &s["bookmarks"][0]["view"];
|
||||
assert_eq!(view["type"], "XYZ");
|
||||
assert_eq!(view["values"][2], Value::Null, "the zoom is the reader's");
|
||||
assert!(view["values"][1].as_f64().is_some_and(|top| top > 740.0), "goes to the top of the heading: {view}");
|
||||
// It changed nothing; the reviewed list goes in as one undoable step.
|
||||
assert_eq!(ok(&mut a, "bookmark_list", json!({ "doc": doc }))["bookmarks"], json!([]));
|
||||
ok(&mut a, "bookmark_import", json!({ "doc": doc, "bookmarks": s["bookmarks"], "replace": true }));
|
||||
let back = ok(&mut a, "bookmark_export", json!({ "doc": doc }));
|
||||
assert_eq!(outline(&back["bookmarks"]), expected);
|
||||
ok(&mut a, "edit_undo", json!({ "doc": doc }));
|
||||
assert_eq!(ok(&mut a, "bookmark_list", json!({ "doc": doc }))["bookmarks"], json!([]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggest_uses_the_tags_once_there_are_some() {
|
||||
let dir = tmp("structure");
|
||||
std::fs::write(dir.join("report.pdf"), report_pdf()).unwrap();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap();
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "report.pdf" }))["doc"].as_u64().unwrap();
|
||||
ok(&mut a, "accessibility_autotag_apply", json!({ "doc": doc }));
|
||||
let s = ok(&mut a, "bookmark_suggest", json!({ "doc": doc }));
|
||||
assert_eq!(s["source"], "structure");
|
||||
let titles: Vec<&str> = s["bookmarks"].as_array().unwrap().iter().map(|n| n["title"].as_str().unwrap()).collect();
|
||||
assert!(titles.first().is_some_and(|t| t.starts_with("Getting started")), "{s}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_in_one_style_gets_no_suggestion_and_a_note() {
|
||||
let dir = tmp("plain");
|
||||
let page = format!("BT /FR 11 Tf 72 700 Td ({BODY}) Tj 0 -14 Td ({BODY}) Tj ET");
|
||||
std::fs::write(dir.join("plain.pdf"), two_pages(&page, &page)).unwrap();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap();
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "plain.pdf" }))["doc"].as_u64().unwrap();
|
||||
let s = ok(&mut a, "bookmark_suggest", json!({ "doc": doc }));
|
||||
assert_eq!((s["source"].as_str(), s["headings"].as_u64(), &s["bookmarks"]), (Some("layout"), Some(0), &json!([])));
|
||||
assert!(s["note"].as_str().is_some_and(|n| n.contains("bookmark_from_text_styles")), "{s}");
|
||||
}
|
||||
|
||||
/// A suggested bookmark has no level to edit: bookmark_import refuses one, and the nesting changes
|
||||
/// by moving a bookmark into or out of another's children, as the tool description says.
|
||||
#[test]
|
||||
fn a_suggestion_is_renested_through_children_not_levels() {
|
||||
let dir = tmp("renest");
|
||||
std::fs::write(dir.join("report.pdf"), report_pdf()).unwrap();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap();
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "report.pdf" }))["doc"].as_u64().unwrap();
|
||||
let mut bookmarks = ok(&mut a, "bookmark_suggest", json!({ "doc": doc }))["bookmarks"].clone();
|
||||
let mut leveled = bookmarks.clone();
|
||||
leveled[0]["level"] = json!(2);
|
||||
let refused = a.call("bookmark_import", &json!({ "doc": doc, "bookmarks": leveled, "replace": true }));
|
||||
assert!(refused.is_err_and(|e| e.to_string().contains("unknown key")), "a level was taken");
|
||||
let child = bookmarks[0]["children"].as_array_mut().unwrap().remove(0);
|
||||
bookmarks.as_array_mut().unwrap().push(child);
|
||||
ok(&mut a, "bookmark_import", json!({ "doc": doc, "bookmarks": bookmarks, "replace": true }));
|
||||
let back = ok(&mut a, "bookmark_export", json!({ "doc": doc }));
|
||||
let top: Vec<String> = outline(&back["bookmarks"]).into_iter().map(|(t, _, _)| t).collect();
|
||||
assert_eq!(top, ["Getting started with the toolkit", "Reference", "Installing"]);
|
||||
let tool = pdfcraft_automation::tools().into_iter().find(|t| t.name == "bookmark_suggest").unwrap();
|
||||
assert!(tool.description.contains("children") && !tool.description.contains("levels or"), "{}", tool.description);
|
||||
}
|
||||
@@ -83,4 +83,12 @@ impl Document {
|
||||
.collect();
|
||||
Ok(Preview { candidates, unclassified_images: self.page_images(page).len(), unclassified_text_blocks, existing_structure })
|
||||
}
|
||||
|
||||
/// The running headers, footers and page numbers that applying auto-tag would mark as
|
||||
/// pagination artifacts. Reads the working PDF and does not alter it; refuses what auto-tag
|
||||
/// refuses.
|
||||
pub fn autotag_running_text(&self) -> Result<Vec<crate::a11y::RunningText>, String> {
|
||||
let editor = self.editor.as_ref().ok_or("the document can't be read")?;
|
||||
crate::a11y::running_text(&editor.cos).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
@@ -437,6 +437,16 @@ impl Document {
|
||||
self.editor.as_ref().map(|e| crate::text_style_bookmarks::styles(&e.cos)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Suggest outline (#6020): the bookmark tree proposed for the document, from its tagged
|
||||
/// headings or else from how its text looks. `None` when the document doesn't allow copying
|
||||
/// (the titles are its text) or can't be read for editing.
|
||||
pub fn suggest_outline(&self) -> Option<crate::suggest_outline::OutlineSuggestion> {
|
||||
if !self.allows_copying() {
|
||||
return None;
|
||||
}
|
||||
self.editor.as_ref().map(|e| crate::suggest_outline::suggest(&e.cos))
|
||||
}
|
||||
|
||||
/// Edit a PDF ▸ Edit text: the lines of existing text on `page` (0-based).
|
||||
pub fn text_lines(&self, page: usize) -> Vec<pdfcraft_edit::TextLine> {
|
||||
self.editor.as_ref().and_then(|e| pdfcraft_edit::text_lines(&e.cos, page).ok()).unwrap_or_default()
|
||||
|
||||
@@ -609,11 +609,7 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
|
||||
pdfcraft_organize::import_outline(doc, parent, *index, bookmarks, *replace)?;
|
||||
}
|
||||
Edit::BookmarksFromStructure => {
|
||||
let entries: Vec<_> = pdfcraft_a11y::headings(doc)
|
||||
.into_iter()
|
||||
.map(|h| pdfcraft_organize::OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj, left: None, top: None })
|
||||
.collect();
|
||||
pdfcraft_organize::add_bookmark_tree(doc, "Untitled", &entries)?;
|
||||
pdfcraft_organize::add_bookmark_tree(doc, "Untitled", &crate::suggest_outline::structure_entries(doc).0)?;
|
||||
}
|
||||
Edit::BookmarksFromTextStyles { levels } => {
|
||||
if levels.is_empty() {
|
||||
|
||||
@@ -60,6 +60,7 @@ pub mod signature_scan;
|
||||
mod sources;
|
||||
pub mod spooler;
|
||||
mod stamp_preview;
|
||||
pub mod suggest_outline;
|
||||
#[cfg(test)]
|
||||
mod test_hooks;
|
||||
pub mod text_fonts;
|
||||
|
||||
@@ -0,0 +1,510 @@
|
||||
//! Suggest outline (#6020): a bookmark tree proposed for the whole document, for review before
|
||||
//! it is applied. Tagged headings (H, H1–H6) are used when the document has them. Otherwise the
|
||||
//! headings are inferred from how the text looks, by the rules Auto-tag uses
|
||||
//! ([`pdfcraft_a11y::heading_levels`]): lines in one style that follow each other down the page
|
||||
//! are one block (a heading that wraps is one bookmark), the body style is the size carrying the
|
||||
//! most characters, a short block larger than the body (or bold where the body is not) is a
|
||||
//! heading, and levels rank the heading styles over the document without skipping a level.
|
||||
//! Captions (`Figure 3`, `Table 2`) are not headings, nor are bold words inside a sentence. Each
|
||||
//! inferred bookmark goes to the top of its heading as displayed (ISO 32000-2 §12.3.2.2 `/XYZ`);
|
||||
//! tagged ones go to their page.
|
||||
|
||||
use pdfcraft_a11y::TextBlock;
|
||||
use pdfcraft_cos::Document;
|
||||
use pdfcraft_organize::{OutlineEntry, OutlineNode};
|
||||
|
||||
use crate::text_style_bookmarks::{Line, MAX_BOOKMARKS, MAX_TITLE_CHARS, SIZE_TOLERANCE, read_lines};
|
||||
|
||||
/// Blocks looked back over for one a line continues: a heading's next line can come after lines
|
||||
/// of other columns on the same row.
|
||||
const LOOKBACK: usize = 8;
|
||||
/// The deepest a suggested tree nests: bookmark_import takes 33 levels, counting a parent.
|
||||
const MAX_DEPTH: usize = 32;
|
||||
/// How far, in ems, text may sit beside a line and still be in the same sentence: a word space is
|
||||
/// about a quarter of an em and a justified one rarely passes half. A gutter between columns can
|
||||
/// be under an em, so this stays below it.
|
||||
const BESIDE_GAP: f64 = 0.5;
|
||||
/// The most lines looked at on either side of a line for text beside it, which bounds the work on
|
||||
/// a page with many runs on one row.
|
||||
const MAX_BESIDE: usize = 64;
|
||||
|
||||
/// Where the suggested headings come from.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum OutlineSource {
|
||||
/// The structure tree's headings.
|
||||
Structure,
|
||||
/// The size and weight of the text.
|
||||
Layout,
|
||||
}
|
||||
|
||||
/// A suggested outline.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct OutlineSuggestion {
|
||||
pub source: OutlineSource,
|
||||
/// The headings in document order, nested by level (see [`OutlineSuggestion::tree`]).
|
||||
pub entries: Vec<OutlineEntry>,
|
||||
/// Pages in the document.
|
||||
pub pages: usize,
|
||||
/// Pages whose text was read: at most [`MAX_PAGES`](crate::text_style_bookmarks::MAX_PAGES)
|
||||
/// for a suggestion from layout, fewer when a page's text can't be read.
|
||||
pub pages_read: usize,
|
||||
/// Headings may have been left out: pages weren't read, layout found more than
|
||||
/// [`MAX_BOOKMARKS`], or the structure tree ran past a limit of
|
||||
/// [`pdfcraft_a11y::headings_with_truncation`].
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
impl OutlineSuggestion {
|
||||
/// The entries as a bookmark tree, every bookmark expanded: a level-2 entry goes under the
|
||||
/// level-1 entry before it, and so on. Levels deeper than [`MAX_DEPTH`] stay at that depth.
|
||||
pub fn tree(&self) -> Vec<OutlineNode> {
|
||||
nest(&self.entries, &mut 0, 0, 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// The entries from `*at` on that go under a parent of level `above` at `depth` (recursion
|
||||
/// bounded by [`MAX_DEPTH`]); `*at` ends at the first that doesn't.
|
||||
fn nest(entries: &[OutlineEntry], at: &mut usize, above: u8, depth: usize) -> Vec<OutlineNode> {
|
||||
let mut out = Vec::new();
|
||||
while let Some(e) = entries.get(*at) {
|
||||
if depth > 0 && e.level <= above {
|
||||
break;
|
||||
}
|
||||
*at = at.saturating_add(1);
|
||||
let mut n = node(e);
|
||||
if depth.saturating_add(1) < MAX_DEPTH {
|
||||
n.children = nest(entries, at, e.level, depth.saturating_add(1));
|
||||
}
|
||||
out.push(n);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn node(e: &OutlineEntry) -> OutlineNode {
|
||||
let view = (e.left.is_some() || e.top.is_some()).then(|| (b"XYZ".to_vec(), vec![e.left, e.top, None]));
|
||||
OutlineNode { title: e.title.clone(), page: Some(e.page), view, color: None, italic: false, bold: false, open: true, children: Vec::new() }
|
||||
}
|
||||
|
||||
/// The tagged headings as outline entries, each linked to its element (`/SE`), and whether
|
||||
/// headings may be missing ([`pdfcraft_a11y::headings_with_truncation`]).
|
||||
pub(crate) fn structure_entries(doc: &Document) -> (Vec<OutlineEntry>, bool) {
|
||||
let (found, cut) = pdfcraft_a11y::headings_with_truncation(doc);
|
||||
let entries =
|
||||
found.into_iter().map(|h| OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj, left: None, top: None }).collect();
|
||||
(entries, cut)
|
||||
}
|
||||
|
||||
/// The outline suggested for `doc`: its tagged headings, or else headings inferred from the
|
||||
/// first [`MAX_PAGES`](crate::text_style_bookmarks::MAX_PAGES) pages' text. Empty when neither
|
||||
/// finds a heading.
|
||||
pub fn suggest(doc: &Document) -> OutlineSuggestion {
|
||||
let pages = pdfcraft_organize::page_count(doc).unwrap_or(0);
|
||||
let (tagged, cut) = structure_entries(doc);
|
||||
if !tagged.is_empty() {
|
||||
return OutlineSuggestion { source: OutlineSource::Structure, entries: tagged, pages, pages_read: pages, truncated: cut };
|
||||
}
|
||||
let (lines, pages_read) = read_lines(doc);
|
||||
let (entries, capped) = inferred(lines);
|
||||
OutlineSuggestion { source: OutlineSource::Layout, entries, pages, pages_read, truncated: cut || capped || pages_read < pages }
|
||||
}
|
||||
|
||||
/// Lines in one style, one after another down a page.
|
||||
struct Block {
|
||||
first: Line,
|
||||
last: Line,
|
||||
title: String,
|
||||
lines: usize,
|
||||
chars: usize,
|
||||
letters: bool,
|
||||
/// Whether any of its lines is set inside a sentence ([`set_inline`]).
|
||||
inline: bool,
|
||||
}
|
||||
|
||||
impl Block {
|
||||
fn new(line: Line, inline: bool) -> Block {
|
||||
let mut b = Block { first: line.clone(), last: line, title: String::new(), lines: 0, chars: 0, letters: false, inline };
|
||||
b.count(&b.first.text.clone());
|
||||
b
|
||||
}
|
||||
|
||||
fn add(&mut self, line: Line, inline: bool) {
|
||||
self.inline |= inline;
|
||||
if self.title.chars().count() < MAX_TITLE_CHARS {
|
||||
self.title.push(' ');
|
||||
}
|
||||
self.count(&line.text);
|
||||
self.last = line;
|
||||
}
|
||||
|
||||
fn count(&mut self, text: &str) {
|
||||
self.lines = self.lines.saturating_add(1);
|
||||
self.chars = self.chars.saturating_add(text.chars().filter(|c| !c.is_whitespace()).count());
|
||||
self.letters |= text.chars().any(char::is_alphabetic);
|
||||
let room = MAX_TITLE_CHARS.saturating_sub(self.title.chars().count());
|
||||
self.title.extend(text.chars().take(room));
|
||||
}
|
||||
|
||||
/// What the heading rules see. A block set inside a sentence still counts toward the body
|
||||
/// style, since it is the paragraph's text, but is never a heading: the rules take no block
|
||||
/// without letters as one.
|
||||
fn evidence(&self) -> TextBlock {
|
||||
let s = &self.first.style;
|
||||
TextBlock { size: s.size, bold: s.bold, lines: self.lines, chars: self.chars, letters: self.letters && !self.inline }
|
||||
}
|
||||
}
|
||||
|
||||
/// `lines`, in reading order, grouped into blocks: a line joins the most recent of the last
|
||||
/// [`LOOKBACK`] blocks in its style that it continues ([`Line::continues`]).
|
||||
fn blocks(lines: Vec<Line>) -> Vec<Block> {
|
||||
let flags = set_inline(&lines);
|
||||
let mut out: Vec<Block> = Vec::new();
|
||||
for (line, inline) in lines.into_iter().zip(flags) {
|
||||
let start = out.len().saturating_sub(LOOKBACK);
|
||||
let found = out.get_mut(start..).and_then(|recent| {
|
||||
recent.iter_mut().rev().find(|b| b.last.page == line.page && b.first.style.matches(&line.style) && line.continues(&b.last))
|
||||
});
|
||||
match found {
|
||||
Some(b) => b.add(line, inline),
|
||||
None => out.push(Block::new(line, inline)),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// For each of `lines` (in reading order), whether it is set inside a sentence: prose in another
|
||||
/// style, no smaller than it, sits right beside it on its row. A bold word in a paragraph (a
|
||||
/// requirement keyword, a defined term) is emphasis, not a heading. Text beside it is prose only
|
||||
/// when it has a lower-case letter, so a section number set apart from its bold title (`2.3`)
|
||||
/// leaves the title a heading.
|
||||
fn set_inline(lines: &[Line]) -> Vec<bool> {
|
||||
lines
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, l)| {
|
||||
// Lines are sorted down each page, so those on its row are next to it.
|
||||
let near = |o: &&Line| o.page == l.page && (o.top - l.top).abs() < l.style.size;
|
||||
let before = lines.get(..i).unwrap_or_default().iter().rev().take(MAX_BESIDE).take_while(near);
|
||||
let after = lines.get(i.saturating_add(1)..).unwrap_or_default().iter().take(MAX_BESIDE).take_while(near);
|
||||
before.chain(after).any(|o| beside(l, o))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether prose `o` sits beside `l` in the same sentence: on the same row (their boxes share at
|
||||
/// least half the shorter one's height, since a box runs from the font's ascent to its descent
|
||||
/// and tight leading makes stacked lines' boxes touch), side by side rather than one over the
|
||||
/// other, no smaller than `l`, in another style, at most [`BESIDE_GAP`] ems apart. A heading set
|
||||
/// beside text more than [`SIZE_TOLERANCE`] smaller is still a heading; a word set smaller than
|
||||
/// the prose around it is not. Prose whose box spans `l` on its row also counts: a producer may
|
||||
/// set a sentence as one run with a gap, and paint the bold word into the gap.
|
||||
fn beside(l: &Line, o: &Line) -> bool {
|
||||
let size = l.style.size;
|
||||
let shared = l.top.min(o.top) - l.bottom.max(o.bottom);
|
||||
let shorter = (l.top - l.bottom).min(o.top - o.bottom);
|
||||
let gap = l.left.max(o.left) - l.right.min(o.right);
|
||||
let spans = o.left <= l.left && l.right <= o.right;
|
||||
shared >= shorter * 0.5
|
||||
&& (spans || gap >= -size * 0.25)
|
||||
&& gap <= size * BESIDE_GAP
|
||||
&& size <= o.style.size + SIZE_TOLERANCE
|
||||
&& !o.style.matches(&l.style)
|
||||
&& o.text.chars().any(char::is_lowercase)
|
||||
}
|
||||
|
||||
/// A caption's lead in any case: `Figure`, `Fig.`, `Table`, `Chart`, `Exhibit` or `Plate`, then a
|
||||
/// number.
|
||||
fn is_caption(text: &str) -> bool {
|
||||
let t = text.trim_start();
|
||||
["Figure", "Fig.", "Table", "Chart", "Exhibit", "Plate"].iter().any(|lead| {
|
||||
let rest = t.get(..lead.len()).filter(|head| head.eq_ignore_ascii_case(lead)).and_then(|_| t.get(lead.len()..));
|
||||
rest.is_some_and(|rest| rest.trim_start().chars().next().is_some_and(|c| c.is_ascii_digit()))
|
||||
})
|
||||
}
|
||||
|
||||
/// The headings among `lines`, as outline entries: the first [`MAX_BOOKMARKS`], and whether there
|
||||
/// were more.
|
||||
fn inferred(lines: Vec<Line>) -> (Vec<OutlineEntry>, bool) {
|
||||
let blocks: Vec<Block> = blocks(lines).into_iter().filter(|b| !is_caption(&b.title)).collect();
|
||||
let evidence: Vec<TextBlock> = blocks.iter().map(Block::evidence).collect();
|
||||
let mut entries: Vec<OutlineEntry> = blocks
|
||||
.iter()
|
||||
.zip(pdfcraft_a11y::heading_levels(&evidence))
|
||||
.filter_map(|(b, level)| {
|
||||
let [left, top] = b.first.anchor;
|
||||
Some(OutlineEntry { level: level?, title: b.title.clone(), page: b.first.page, element: None, left, top })
|
||||
})
|
||||
.take(MAX_BOOKMARKS.saturating_add(1))
|
||||
.collect();
|
||||
let capped = entries.len() > MAX_BOOKMARKS;
|
||||
entries.truncate(MAX_BOOKMARKS);
|
||||
(entries, capped)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::text_style_bookmarks::TextStyle;
|
||||
|
||||
/// A line at `top` (its box 0.8 of its size tall) from x 72 to 400.
|
||||
fn line(page: usize, top: f64, size: f64, bold: bool, text: &str) -> Line {
|
||||
let style = TextStyle { font: if bold { "Helvetica-Bold" } else { "Helvetica" }.into(), size, bold, italic: false };
|
||||
Line { page, text: text.into(), style, top, bottom: top - size * 0.8, left: 72.0, right: 400.0, anchor: [None, Some(top)] }
|
||||
}
|
||||
|
||||
fn body(page: usize, top: f64) -> Line {
|
||||
line(page, top, 11.0, false, "Body text that runs on for a good many characters across the page.")
|
||||
}
|
||||
|
||||
fn titles(entries: &[OutlineEntry]) -> Vec<(u8, &str, usize)> {
|
||||
entries.iter().map(|e| (e.level, e.title.as_str(), e.page)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headings_take_levels_by_size_and_weight_and_wrapped_lines_join() {
|
||||
let lines = vec![
|
||||
line(0, 760.0, 20.0, true, "Getting started"),
|
||||
line(0, 738.0, 20.0, true, "with the toolkit"),
|
||||
body(0, 700.0),
|
||||
body(0, 686.0),
|
||||
body(0, 672.0),
|
||||
body(0, 658.0),
|
||||
line(0, 630.0, 11.0, true, "Installing"),
|
||||
body(0, 610.0),
|
||||
body(0, 596.0),
|
||||
line(1, 760.0, 20.0, true, "Reference"),
|
||||
body(1, 730.0),
|
||||
body(1, 716.0),
|
||||
];
|
||||
let (found, capped) = inferred(lines);
|
||||
assert!(!capped);
|
||||
assert_eq!(titles(&found), [(1, "Getting started with the toolkit", 0), (2, "Installing", 0), (1, "Reference", 1)]);
|
||||
assert_eq!((found[0].left, found[0].top), (None, Some(760.0)), "a bookmark goes to the top of its first line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrapped_heading_joins_across_a_line_of_another_column() {
|
||||
let mut right = body(0, 760.0);
|
||||
(right.left, right.right) = (420.0, 560.0);
|
||||
let lines = vec![line(0, 760.0, 20.0, true, "Two column"), right, line(0, 738.0, 20.0, true, "heading"), body(0, 700.0), body(0, 686.0)];
|
||||
assert_eq!(titles(&inferred(lines).0), [(1, "Two column heading", 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captions_and_numbers_are_not_headings() {
|
||||
let lines = vec![line(0, 760.0, 16.0, true, "Figure 3: The toolkit"), line(0, 730.0, 16.0, true, "42"), body(0, 700.0), body(0, 686.0)];
|
||||
assert!(inferred(lines).0.is_empty());
|
||||
assert!(is_caption("Table 12 Results") && is_caption("Fig. 2") && !is_caption("Tables are useful"));
|
||||
}
|
||||
|
||||
/// A line of `text` in `style` from `left` to `right` at `top`.
|
||||
fn run(top: f64, bold: bool, text: &str, left: f64, right: f64) -> Line {
|
||||
Line { left, right, ..line(0, top, 11.0, bold, text) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bold_word_inside_a_sentence_is_not_a_heading() {
|
||||
let lines = vec![
|
||||
line(0, 760.0, 11.0, true, "MUST"),
|
||||
body(0, 740.0),
|
||||
run(726.0, false, "A recipient", 72.0, 130.0),
|
||||
run(726.0, true, "MUST", 133.0, 165.0),
|
||||
run(726.0, false, "ignore the field.", 168.0, 400.0),
|
||||
body(0, 712.0),
|
||||
run(690.0, false, "2.3", 72.0, 88.0),
|
||||
run(690.0, true, "Numbered title", 96.0, 180.0),
|
||||
body(0, 670.0),
|
||||
body(0, 656.0),
|
||||
];
|
||||
assert_eq!(titles(&inferred(lines).0), [(1, "MUST", 0), (1, "Numbered title", 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bold_word_set_smaller_than_its_sentence_is_not_a_heading_but_a_larger_one_is() {
|
||||
let mut small = run(726.0, true, "MUST", 133.0, 163.0);
|
||||
small.style.size = 10.0;
|
||||
small.top = 725.2;
|
||||
small.bottom = small.top - 8.0;
|
||||
let lines = vec![
|
||||
line(0, 760.0, 11.0, true, "MUST"),
|
||||
body(0, 740.0),
|
||||
run(726.0, false, "A recipient", 72.0, 130.0),
|
||||
small,
|
||||
run(726.0, false, "ignore the field.", 166.0, 400.0),
|
||||
body(0, 712.0),
|
||||
Line { left: 72.0, right: 110.0, ..line(0, 690.0, 14.0, true, "Scope") },
|
||||
run(688.8, false, "covers the rest of this page.", 113.0, 400.0),
|
||||
body(0, 670.0),
|
||||
body(0, 656.0),
|
||||
];
|
||||
assert_eq!(titles(&inferred(lines).0), [(1, "MUST", 0), (1, "Scope", 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bold_word_painted_into_a_gap_in_one_run_of_prose_is_not_a_heading() {
|
||||
let mut word = run(725.2, true, "MUST", 192.0, 219.0);
|
||||
word.style.size = 10.0;
|
||||
word.bottom = word.top - 8.0;
|
||||
let lines = vec![
|
||||
line(0, 760.0, 11.0, true, "MUST"),
|
||||
body(0, 740.0),
|
||||
run(726.0, false, "A recipient ignore the field.", 72.0, 400.0),
|
||||
word,
|
||||
body(0, 712.0),
|
||||
body(0, 698.0),
|
||||
];
|
||||
assert_eq!(titles(&inferred(lines).0), [(1, "MUST", 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_beside_an_italic_word_still_sets_the_body_size() {
|
||||
let italic = |top: f64| {
|
||||
let mut l = run(top, false, "term", 252.0, 275.0);
|
||||
l.style.italic = true;
|
||||
l.style.font = "Helvetica-Oblique".into();
|
||||
l
|
||||
};
|
||||
let mut lines = vec![line(0, 780.0, 14.0, true, "Overview")];
|
||||
for top in [750.0, 736.0, 722.0, 708.0] {
|
||||
lines.extend([
|
||||
run(top, false, "The first part of the row runs to", 72.0, 250.0),
|
||||
italic(top),
|
||||
run(top, false, "and the rest of it follows on.", 277.0, 400.0),
|
||||
]);
|
||||
}
|
||||
assert_eq!(titles(&inferred(lines).0), [(1, "Overview", 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_heading_over_tightly_set_text_or_across_a_narrow_gutter_stays_a_heading() {
|
||||
let lines = vec![
|
||||
// Its box overlaps the first body line's by 1.5 pt.
|
||||
run(760.0, true, "Tight heading", 72.0, 180.0),
|
||||
body(0, 752.7),
|
||||
body(0, 740.0),
|
||||
// A gutter of 9 pt, under an em: prose ends the left column on the heading's row.
|
||||
run(700.0, false, "ends the left column here", 72.0, 291.0),
|
||||
run(700.0, true, "Right column heading", 300.0, 520.0),
|
||||
body(0, 686.0),
|
||||
body(0, 672.0),
|
||||
];
|
||||
assert_eq!(titles(&inferred(lines).0), [(1, "Tight heading", 0), (1, "Right column heading", 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captions_match_in_any_case() {
|
||||
let lines = vec![line(0, 760.0, 16.0, true, "FIGURE 3: Architecture"), body(0, 700.0), body(0, 686.0)];
|
||||
assert!(inferred(lines).0.is_empty(), "an upper-case caption was suggested as a heading");
|
||||
assert!(is_caption("table 2") && is_caption("FIG. 4") && !is_caption("TABLES are useful") && !is_caption("Figé 3"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn more_headings_than_the_cap_are_reported() {
|
||||
// Each heading on a page of its own, with a line of body text under it.
|
||||
let pages = |n: usize| (0..n).flat_map(|p| [line(p, 760.0, 20.0, true, "Heading"), body(p, 700.0)]).collect::<Vec<_>>();
|
||||
let (at_cap, capped) = inferred(pages(MAX_BOOKMARKS));
|
||||
assert_eq!((at_cap.len(), capped), (MAX_BOOKMARKS, false));
|
||||
let (over, capped) = inferred(pages(MAX_BOOKMARKS + 1));
|
||||
assert_eq!((over.len(), capped), (MAX_BOOKMARKS, true), "a heading past the cap was dropped unreported");
|
||||
}
|
||||
|
||||
/// A page past the page decode allowance (two compressed streams of spaces, each just over
|
||||
/// half of it) can't be read: it doesn't count as read, and the suggestion says headings
|
||||
/// may be missing.
|
||||
#[test]
|
||||
fn a_page_whose_text_cant_be_read_is_not_counted() {
|
||||
let packed = pdfcraft_filters::encode_flate(&vec![b' '; pdfcraft_cos::MAX_PAGE_DECODED / 2 + 1]);
|
||||
let stream = |dict: &str, data: &[u8]| [format!("<< /Length {} {dict} >>\nstream\n", data.len()).as_bytes(), data, b"\nendstream"].concat();
|
||||
let objs: Vec<Vec<u8>> = vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F 7 0 R >> >> >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /Contents 5 0 R >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /Contents [6 0 R 6 0 R] >>".to_vec(),
|
||||
stream("", b"BT /F 11 Tf 72 700 Td (Body) Tj ET"),
|
||||
stream("/Filter /FlateDecode", &packed),
|
||||
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(),
|
||||
];
|
||||
let s = suggest(&doc_of(&objs));
|
||||
assert_eq!((s.pages, s.pages_read, s.truncated), (2, 1, true), "the unread page counted as read");
|
||||
}
|
||||
|
||||
/// A PDF of these objects (object n = `objs[n - 1]`), the first the catalog.
|
||||
fn doc_of(objs: &[Vec<u8>]) -> Document {
|
||||
let mut bytes = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(bytes.len());
|
||||
bytes.extend_from_slice(&[format!("{} 0 obj\n", i + 1).as_bytes(), o, b"\nendobj\n"].concat());
|
||||
}
|
||||
let xref = bytes.len();
|
||||
bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
Document::open(std::sync::Arc::new(bytes)).unwrap()
|
||||
}
|
||||
|
||||
/// More tagged headings than the structure reader returns: the suggestion says some are missing.
|
||||
#[test]
|
||||
fn tagged_headings_past_the_cap_are_reported() {
|
||||
let tagged = |count: usize| {
|
||||
let kids: String = (0..count).map(|i| format!("{} 0 R ", i + 6)).collect();
|
||||
let mut objs = vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 4 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_vec(),
|
||||
b"<< /Type /StructTreeRoot /K 5 0 R >>".to_vec(),
|
||||
format!("<< /S /Document /K [{kids}] >>").into_bytes(),
|
||||
];
|
||||
objs.extend((0..count).map(|_| b"<< /S /H1 /Pg 3 0 R /ActualText (Head) >>".to_vec()));
|
||||
suggest(&doc_of(&objs))
|
||||
};
|
||||
let cap = pdfcraft_a11y::MAX_HEADINGS;
|
||||
let at_cap = tagged(cap);
|
||||
assert_eq!((at_cap.source, at_cap.entries.len(), at_cap.truncated), (OutlineSource::Structure, cap, false));
|
||||
let over = tagged(cap + 1);
|
||||
assert_eq!((over.entries.len(), over.truncated), (cap, true), "a tagged heading past the cap was dropped unreported");
|
||||
}
|
||||
|
||||
/// A tagged heading too deep for the structure walk, on a page without text: layout finds
|
||||
/// nothing either, and the suggestion still says a heading may be missing. The same page
|
||||
/// untagged is not truncated.
|
||||
#[test]
|
||||
fn a_tagged_heading_past_the_depth_limit_is_reported_from_layout() {
|
||||
let mut objs = vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 4 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_vec(),
|
||||
b"<< /Type /StructTreeRoot /K 5 0 R >>".to_vec(),
|
||||
];
|
||||
objs.extend((5..305).map(|n| format!("<< /S /Sect /K {} 0 R >>", n + 1).into_bytes()));
|
||||
objs.push(b"<< /S /H1 /Pg 3 0 R /ActualText (Deep) >>".to_vec());
|
||||
let s = suggest(&doc_of(&objs));
|
||||
assert_eq!((s.source, s.entries.len(), s.truncated), (OutlineSource::Layout, 0, true), "the structure walk's cut was dropped");
|
||||
objs[0] = b"<< /Type /Catalog /Pages 2 0 R >>".to_vec();
|
||||
let s = suggest(&doc_of(&objs));
|
||||
assert_eq!((s.entries.len(), s.pages_read, s.truncated), (0, 1, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tree_nests_by_level_and_caps_the_depth() {
|
||||
let entry = |level: u8, title: &str| OutlineEntry { level, title: title.into(), page: 0, element: None, left: None, top: Some(700.0) };
|
||||
let mut entries = vec![entry(1, "A"), entry(2, "A.1"), entry(3, "A.1.a"), entry(2, "A.2"), entry(1, "B")];
|
||||
let s = OutlineSuggestion { source: OutlineSource::Layout, entries: entries.clone(), pages: 1, pages_read: 1, truncated: false };
|
||||
let tree = s.tree();
|
||||
assert_eq!(tree.iter().map(|n| n.title.as_str()).collect::<Vec<_>>(), ["A", "B"]);
|
||||
assert_eq!(tree[0].children.iter().map(|n| n.title.as_str()).collect::<Vec<_>>(), ["A.1", "A.2"]);
|
||||
assert_eq!(tree[0].children[0].children[0].title, "A.1.a");
|
||||
assert_eq!(tree[0].view, Some((b"XYZ".to_vec(), vec![None, Some(700.0), None])));
|
||||
// A tagged H nested in 40 sections stops at the deepest level bookmark_import takes.
|
||||
entries = (1..=40).map(|l| entry(l, "deep")).collect();
|
||||
let deep = OutlineSuggestion { entries, ..s }.tree();
|
||||
let mut depth = 0;
|
||||
let mut at = &deep;
|
||||
while let Some(n) = at.first() {
|
||||
depth += 1;
|
||||
at = &n.children;
|
||||
}
|
||||
assert_eq!(depth, MAX_DEPTH);
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ impl TextStyle {
|
||||
}
|
||||
|
||||
/// How far apart two sizes may be and still be one style.
|
||||
const SIZE_TOLERANCE: f64 = 0.25;
|
||||
pub(crate) const SIZE_TOLERANCE: f64 = 0.25;
|
||||
|
||||
/// A style and how much text is set in it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -49,29 +49,41 @@ pub const MAX_PAGES: usize = 5000;
|
||||
/// The most bookmarks made at once.
|
||||
pub const MAX_BOOKMARKS: usize = 10_000;
|
||||
/// The longest bookmark title kept, in characters (a heading run on into a paragraph).
|
||||
const MAX_TITLE_CHARS: usize = 300;
|
||||
pub(crate) const MAX_TITLE_CHARS: usize = 300;
|
||||
/// The longest sample shown for a style.
|
||||
const SAMPLE_CHARS: usize = 60;
|
||||
/// The most styles listed, the largest first.
|
||||
const MAX_STYLES: usize = 200;
|
||||
|
||||
/// One line of text in reading order.
|
||||
struct Line {
|
||||
page: usize,
|
||||
text: String,
|
||||
style: TextStyle,
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Line {
|
||||
pub(crate) page: usize,
|
||||
pub(crate) text: String,
|
||||
pub(crate) style: TextStyle,
|
||||
/// Top, bottom, left and right of its box as displayed (after the page's `/Rotate`, y up), so
|
||||
/// reading order and the join of a heading's lines are right on a turned page. Only
|
||||
/// differences between these values are used: they are offset from points on the page.
|
||||
top: f64,
|
||||
bottom: f64,
|
||||
left: f64,
|
||||
right: f64,
|
||||
pub(crate) top: f64,
|
||||
pub(crate) bottom: f64,
|
||||
pub(crate) left: f64,
|
||||
pub(crate) right: f64,
|
||||
/// The `/XYZ` position `[left, top]` (user space) that puts the top of the line as displayed
|
||||
/// at the top of the window. The box edge displayed on top depends on the rotation: the top
|
||||
/// edge, the left edge (90), the bottom edge (180) or the right edge (270). On a page turned
|
||||
/// a quarter it is a user-space x, so it is `left`, and `top` stays unspecified.
|
||||
anchor: [Option<f64>; 2],
|
||||
pub(crate) anchor: [Option<f64>; 2],
|
||||
}
|
||||
|
||||
impl Line {
|
||||
/// Whether this line goes on with a heading whose last line is `above`: on the same page, on
|
||||
/// the next row down, close below it and under it. A line on the same row (two headings side
|
||||
/// by side), or in another column, starts a heading of its own.
|
||||
pub(crate) fn continues(&self, above: &Line) -> bool {
|
||||
let size = self.style.size;
|
||||
let under = self.left < above.right && above.left < self.right;
|
||||
self.page == above.page && self.top < above.top - size * 0.5 && above.bottom - self.top < size * 0.6 && under
|
||||
}
|
||||
}
|
||||
|
||||
/// A box in user space `[x0, y0, x1, y1]` on a page turned `rotation` degrees clockwise → its
|
||||
@@ -96,13 +108,21 @@ fn without_subset_tag(name: &str) -> &str {
|
||||
|
||||
/// The text lines of `doc`'s first [`MAX_PAGES`] pages, each page's in reading order. Text that
|
||||
/// is only whitespace, or whose size can't be read, is left out.
|
||||
fn lines(doc: &Document) -> Vec<Line> {
|
||||
pub(crate) fn lines(doc: &Document) -> Vec<Line> {
|
||||
read_lines(doc).0
|
||||
}
|
||||
|
||||
/// [`lines`], and how many pages' text was read: a page whose text can't be read (its content
|
||||
/// past the page's decode allowance, say) is skipped and not counted.
|
||||
pub(crate) fn read_lines(doc: &Document) -> (Vec<Line>, usize) {
|
||||
let pages = pdfcraft_organize::page_count(doc).unwrap_or(0).min(MAX_PAGES);
|
||||
let rotations = pdfcraft_organize::page_rotations(doc).unwrap_or_default();
|
||||
let mut out = Vec::new();
|
||||
let mut read = 0usize;
|
||||
for page in 0..pages {
|
||||
let rotation = rotations.get(page).copied().unwrap_or(0);
|
||||
let Ok(found) = pdfcraft_edit::text_lines(doc, page) else { continue };
|
||||
read = read.saturating_add(1);
|
||||
let mut on_page: Vec<Line> = found
|
||||
.into_iter()
|
||||
.filter_map(|l| {
|
||||
@@ -135,7 +155,7 @@ fn lines(doc: &Document) -> Vec<Line> {
|
||||
on_page.sort_by(|a, b| (b.top * 10.0).round().total_cmp(&(a.top * 10.0).round()).then(a.left.total_cmp(&b.left)));
|
||||
out.extend(on_page);
|
||||
}
|
||||
out
|
||||
(out, read)
|
||||
}
|
||||
|
||||
/// The styles `doc`'s text is set in, the largest size first (then the most used): headings
|
||||
@@ -183,22 +203,14 @@ pub fn styles(doc: &Document) -> Vec<TextStyleUse> {
|
||||
/// is one bookmark. Each goes to the top of its heading as displayed, also on a turned page.
|
||||
pub fn headings(doc: &Document, levels: &[TextStyle]) -> Vec<OutlineEntry> {
|
||||
let mut entries: Vec<OutlineEntry> = Vec::new();
|
||||
// The heading the previous line belonged to: its level, and the top, bottom, left and right
|
||||
// of its last line.
|
||||
let mut open: Option<(usize, f64, f64, f64, f64)> = None;
|
||||
// The heading the previous line belonged to: its level and its last line.
|
||||
let mut open: Option<(usize, Line)> = None;
|
||||
for line in lines(doc) {
|
||||
let Some(level) = levels.iter().position(|s| s.matches(&line.style)) else {
|
||||
open = None;
|
||||
continue;
|
||||
};
|
||||
// A heading goes on to the next row down, close below its last line and under it. A line
|
||||
// on the same row (two headings side by side), or in another column, is a heading of
|
||||
// its own.
|
||||
let continues = open.is_some_and(|(l, top, bottom, left, right)| {
|
||||
let size = line.style.size;
|
||||
let under = line.left < right && left < line.right;
|
||||
l == level && line.top < top - size * 0.5 && bottom - line.top < size * 0.6 && under
|
||||
}) && entries.last().is_some_and(|e| e.page == line.page);
|
||||
let continues = open.as_ref().is_some_and(|(l, above)| *l == level && line.continues(above));
|
||||
if continues {
|
||||
if let Some(e) = entries.last_mut()
|
||||
&& e.title.chars().count() < MAX_TITLE_CHARS
|
||||
@@ -217,7 +229,7 @@ pub fn headings(doc: &Document, levels: &[TextStyle]) -> Vec<OutlineEntry> {
|
||||
let [left, top] = line.anchor;
|
||||
entries.push(OutlineEntry { level, title: line.text.chars().take(MAX_TITLE_CHARS).collect(), page: line.page, element: None, left, top });
|
||||
}
|
||||
open = Some((level, line.top, line.bottom, line.left, line.right));
|
||||
open = Some((level, line));
|
||||
}
|
||||
entries
|
||||
}
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
|
||||
use pdfcraft_cos::{Dict, Document, Object, PdfString, SaveOptions, Stream, write_full};
|
||||
use pdfcraft_engine::{Edit, Session};
|
||||
use pdfcraft_organize::FieldConflicts;
|
||||
|
||||
fn dict<const N: usize>(entries: [(&str, Object); N]) -> Dict {
|
||||
let mut out = Dict::new();
|
||||
for (key, value) in entries {
|
||||
out.set(key.as_bytes().to_vec(), value);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn packet(title: &str, attachment_key: Option<Vec<u8>>, indirect_names: bool) -> Arc<Vec<u8>> {
|
||||
let mut doc = Document::new_empty();
|
||||
let pages = doc.add(Object::Null);
|
||||
let font = doc.add(dict([("Type", Object::name("Font")), ("Subtype", Object::name("Type1")), ("BaseFont", Object::name("Helvetica"))]));
|
||||
let body = format!("BT /F1 12 Tf 72 720 Td ({title}) Tj ET");
|
||||
let content = doc.add(Object::Stream(Stream::from_raw(Dict::new(), body.into_bytes())));
|
||||
let page = doc.add(dict([
|
||||
("Type", Object::name("Page")),
|
||||
("Parent", Object::Ref(pages)),
|
||||
("MediaBox", Object::Array([0, 0, 612, 792].map(Object::Int).to_vec())),
|
||||
("Contents", Object::Ref(content)),
|
||||
("Resources", Object::Dict(dict([("Font", Object::Dict(dict([("F1", Object::Ref(font))])))]))),
|
||||
]));
|
||||
doc.set(pages, dict([("Type", Object::name("Pages")), ("Kids", Object::Array(vec![Object::Ref(page)])), ("Count", Object::Int(1))]));
|
||||
let destinations = doc.add(dict([(
|
||||
"Names",
|
||||
Object::Array(vec![Object::String(PdfString::text("PaymentSchedule")), Object::Array(vec![Object::Ref(page), Object::name("Fit")])]),
|
||||
)]));
|
||||
let mut names = dict([("Dests", Object::Ref(destinations))]);
|
||||
if let Some(key) = attachment_key {
|
||||
let payload = format!("{title}: vendor insurance verified; review owner Procurement Operations; next review 2027-01-31.\n");
|
||||
let file = doc.add(Object::Stream(Stream::from_raw(
|
||||
dict([
|
||||
("Type", Object::name("EmbeddedFile")),
|
||||
("Subtype", Object::name("text/plain")),
|
||||
("Params", Object::Dict(dict([("Size", Object::Int(payload.len() as i64))]))),
|
||||
]),
|
||||
payload.into_bytes(),
|
||||
)));
|
||||
let spec = doc.add(dict([
|
||||
("Type", Object::name("Filespec")),
|
||||
("F", Object::String(PdfString::text("vendor-compliance.txt"))),
|
||||
("EF", Object::Dict(dict([("F", Object::Ref(file))]))),
|
||||
]));
|
||||
let leaf = doc.add(dict([
|
||||
("Names", Object::Array(vec![Object::String(PdfString::literal(key.clone())), Object::Ref(spec)])),
|
||||
("Limits", Object::Array(vec![Object::String(PdfString::literal(key.clone())), Object::String(PdfString::literal(key))])),
|
||||
]));
|
||||
let tree = doc.add(dict([("Kids", Object::Array(vec![Object::Ref(leaf)]))]));
|
||||
names.set(b"EmbeddedFiles".to_vec(), Object::Ref(tree));
|
||||
}
|
||||
let names = if indirect_names { Object::Ref(doc.add(names)) } else { Object::Dict(names) };
|
||||
let root = doc.add(dict([("Type", Object::name("Catalog")), ("Pages", Object::Ref(pages)), ("Names", names)]));
|
||||
doc.trailer_mut().set(b"Root".to_vec(), Object::Ref(root));
|
||||
Arc::new(write_full(&doc, &SaveOptions::default()).unwrap())
|
||||
}
|
||||
|
||||
fn attachments(doc: &Document) -> Vec<(Vec<u8>, Vec<u8>)> {
|
||||
fn visit(doc: &Document, tree: &Object, out: &mut Vec<(Vec<u8>, Vec<u8>)>) {
|
||||
let tree = doc.resolve(tree);
|
||||
let tree = tree.as_dict().unwrap();
|
||||
if let Some(names) = tree.get(b"Names") {
|
||||
for pair in doc.resolve(names).as_array().unwrap().as_chunks::<2>().0 {
|
||||
let key = pair[0].as_string().unwrap();
|
||||
let spec = doc.resolve(&pair[1]);
|
||||
let ef = doc.resolve(spec.as_dict().unwrap().get(b"EF").unwrap());
|
||||
let file = doc.resolve(ef.as_dict().unwrap().get(b"F").unwrap());
|
||||
let Object::Stream(file) = file.as_ref() else { panic!("embedded file stream expected") };
|
||||
out.push((key.bytes.to_vec(), file.decoded().unwrap()));
|
||||
}
|
||||
}
|
||||
if let Some(kids) = tree.get(b"Kids") {
|
||||
for kid in doc.resolve(kids).as_array().unwrap() {
|
||||
visit(doc, kid, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
let catalog = doc.get(doc.root().unwrap());
|
||||
let names = doc.resolve(catalog.as_dict().unwrap().get(b"Names").unwrap());
|
||||
let mut out = Vec::new();
|
||||
if let Some(tree) = names.as_dict().unwrap().get(b"EmbeddedFiles") {
|
||||
visit(doc, tree, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn assert_destination_retained(doc: &Document) {
|
||||
let catalog = doc.get(doc.root().unwrap());
|
||||
let names = doc.resolve(catalog.as_dict().unwrap().get(b"Names").unwrap());
|
||||
let dests = doc.resolve(names.as_dict().unwrap().get(b"Dests").expect("target destination tree retained"));
|
||||
let values = dests.as_dict().unwrap().get(b"Names").unwrap().as_array().unwrap();
|
||||
assert_eq!(values[0].as_string().unwrap().to_text(), "PaymentSchedule");
|
||||
let page = values[1].as_array().unwrap()[0].as_ref().unwrap();
|
||||
assert_eq!(doc.get(page).as_dict().unwrap().name(b"Type"), Some(b"Page".as_slice()));
|
||||
}
|
||||
|
||||
fn insert(bytes: Arc<Vec<u8>>) -> Edit {
|
||||
Edit::InsertPagesFrom { name: "Facilities Compliance Annex.pdf".into(), bytes, pages: None, at: 1, field_conflicts: FieldConflicts::Rename }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserted_catalog_attachments_follow_native_undo_redo() {
|
||||
let unicode = "合规审查.txt";
|
||||
let be: Vec<u8> = [0xfe, 0xff].into_iter().chain(unicode.encode_utf16().flat_map(u16::to_be_bytes)).collect();
|
||||
let le: Vec<u8> = [0xff, 0xfe].into_iter().chain(unicode.encode_utf16().flat_map(u16::to_le_bytes)).collect();
|
||||
for key in [b"vendor-compliance.txt".to_vec(), be, le] {
|
||||
// Check raw keys to preserve the incoming encoding, including LE files
|
||||
// whose labels PdfString::to_text does not currently decode.
|
||||
let mut renamed = key.clone();
|
||||
match key.get(..2) {
|
||||
Some([0xfe, 0xff]) => renamed.extend(" (2)".encode_utf16().flat_map(u16::to_be_bytes)),
|
||||
Some([0xff, 0xfe]) => renamed.extend(" (2)".encode_utf16().flat_map(u16::to_le_bytes)),
|
||||
_ => renamed.extend_from_slice(b" (2)"),
|
||||
}
|
||||
for indirect in [false, true] {
|
||||
let target = packet("Facilities Service Agreement", Some(key.clone()), indirect);
|
||||
let source = packet("Facilities Compliance Annex", Some(key.clone()), true);
|
||||
let mut session = Session::new();
|
||||
session.set_javascript(false);
|
||||
let id = session.open("Facilities Contract.pdf", None, target, None).unwrap();
|
||||
session.apply(id, Edit::Batch { label: "Merge Annex".into(), edits: vec![insert(source.clone())] }).unwrap();
|
||||
let bytes = session.save_bytes(id).unwrap();
|
||||
let merged = Document::open(bytes).unwrap();
|
||||
let entries = attachments(&merged);
|
||||
assert_eq!(entries.len(), 2, "target and source attachments must survive");
|
||||
assert!(entries.windows(2).all(|p| p[0].0 < p[1].0), "name tree keys sorted and unique");
|
||||
let by_key: BTreeMap<_, _> = entries.into_iter().collect();
|
||||
assert!(by_key[&key].starts_with(b"Facilities Service Agreement:"));
|
||||
assert!(by_key[&renamed].starts_with(b"Facilities Compliance Annex:"));
|
||||
assert_destination_retained(&merged);
|
||||
assert_eq!(session.get(id).unwrap().info.pages.len(), 2);
|
||||
assert_eq!(session.get(id).unwrap().can_undo(), Some("Merge Annex"));
|
||||
session.undo(id).unwrap();
|
||||
let undone = Document::open(session.save_bytes(id).unwrap()).unwrap();
|
||||
assert_eq!(attachments(&undone).len(), 1);
|
||||
assert_destination_retained(&undone);
|
||||
assert_eq!(session.get(id).unwrap().info.pages.len(), 1);
|
||||
session.redo(id).unwrap();
|
||||
let redone = Document::open(session.save_bytes(id).unwrap()).unwrap();
|
||||
assert_eq!(attachments(&redone).len(), 2);
|
||||
assert_destination_retained(&redone);
|
||||
assert_eq!(session.get(id).unwrap().info.pages.len(), 2);
|
||||
assert_eq!(attachments(&Document::open(source).unwrap()).len(), 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserting_into_a_document_without_attachments_retains_other_names() {
|
||||
let mut session = Session::new();
|
||||
session.set_javascript(false);
|
||||
let id = session.open("Facilities Contract.pdf", None, packet("Facilities Service Agreement", None, true), None).unwrap();
|
||||
session.apply(id, insert(packet("Facilities Compliance Annex", Some(b"vendor-compliance.txt".to_vec()), true))).unwrap();
|
||||
let result = Document::open(session.save_bytes(id).unwrap()).unwrap();
|
||||
assert_eq!(attachments(&result).len(), 1);
|
||||
assert_destination_retained(&result);
|
||||
session.undo(id).unwrap();
|
||||
assert!(attachments(&Document::open(session.save_bytes(id).unwrap()).unwrap()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserting_without_source_attachments_does_not_rewrite_target_names() {
|
||||
let mut session = Session::new();
|
||||
session.set_javascript(false);
|
||||
let id = session
|
||||
.open("Facilities Contract.pdf", None, packet("Facilities Service Agreement", Some(b"contract-evidence.txt".to_vec()), true), None)
|
||||
.unwrap();
|
||||
let before = Document::open(session.save_bytes(id).unwrap()).unwrap();
|
||||
let names = before.get(before.root().unwrap()).as_dict().unwrap().get(b"Names").unwrap().clone();
|
||||
assert!(matches!(names, Object::Ref(_)));
|
||||
session.apply(id, insert(packet("Facilities Payment Schedule", None, false))).unwrap();
|
||||
let after = Document::open(session.save_bytes(id).unwrap()).unwrap();
|
||||
assert_eq!(after.get(after.root().unwrap()).as_dict().unwrap().get(b"Names"), Some(&names));
|
||||
assert_eq!(attachments(&after), attachments(&before));
|
||||
assert_destination_retained(&after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selecting_no_pages_does_not_import_catalog_attachments() {
|
||||
let mut session = Session::new();
|
||||
session.set_javascript(false);
|
||||
let id = session
|
||||
.open("Facilities Contract.pdf", None, packet("Facilities Service Agreement", Some(b"contract-evidence.txt".to_vec()), true), None)
|
||||
.unwrap();
|
||||
let before = Document::open(session.save_bytes(id).unwrap()).unwrap();
|
||||
session
|
||||
.apply(
|
||||
id,
|
||||
Edit::InsertPagesFrom {
|
||||
name: "Facilities Compliance Annex.pdf".into(),
|
||||
bytes: packet("Facilities Compliance Annex", Some(b"vendor-compliance.txt".to_vec()), true),
|
||||
pages: Some(Vec::new()),
|
||||
at: 1,
|
||||
field_conflicts: FieldConflicts::Rename,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(session.get(id).unwrap().info.pages.len(), 1);
|
||||
let after = Document::open(session.save_bytes(id).unwrap()).unwrap();
|
||||
assert_eq!(attachments(&after), attachments(&before));
|
||||
assert_destination_retained(&after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_insert_batch_rolls_back_pages_and_attachments() {
|
||||
let mut session = Session::new();
|
||||
session.set_javascript(false);
|
||||
let id = session
|
||||
.open("Facilities Contract.pdf", None, packet("Facilities Service Agreement", Some(b"contract-evidence.txt".to_vec()), true), None)
|
||||
.unwrap();
|
||||
assert!(
|
||||
session
|
||||
.apply(
|
||||
id,
|
||||
Edit::Batch {
|
||||
label: "Merge Annex".into(),
|
||||
edits: vec![
|
||||
insert(packet("Facilities Compliance Annex", Some(b"vendor-compliance.txt".to_vec()), true)),
|
||||
Edit::RotatePages { pages: vec![99], degrees: 90 },
|
||||
]
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(session.get(id).unwrap().info.pages.len(), 1);
|
||||
assert_eq!(session.get(id).unwrap().can_undo(), None);
|
||||
let result = Document::open(session.save_bytes(id).unwrap()).unwrap();
|
||||
assert_eq!(attachments(&result).len(), 1);
|
||||
assert_destination_retained(&result);
|
||||
}
|
||||
+24
-1
@@ -42,6 +42,8 @@ pub struct Metrics {
|
||||
explicit_default: bool,
|
||||
/// The standard-14 face to measure with when the dictionary carries no `/Widths`.
|
||||
std14: Option<crate::Std14>,
|
||||
/// [`Metrics::std14`] is the face `/BaseFont` names (or a common alias of it), not a guess.
|
||||
std14_named: bool,
|
||||
/// Glyph units → text space (0.001, or `/FontMatrix[0]` for Type 3).
|
||||
pub scale: f64,
|
||||
/// Glyph box in text space per unit of font size.
|
||||
@@ -899,6 +901,7 @@ impl Metrics {
|
||||
default: 500.0,
|
||||
explicit_default: false,
|
||||
std14: Some(crate::Std14::Helvetica),
|
||||
std14_named: false,
|
||||
scale: 0.001,
|
||||
ascent: 0.9,
|
||||
descent: -0.25,
|
||||
@@ -1067,7 +1070,9 @@ impl Metrics {
|
||||
let base = String::from_utf8_lossy(font.name(b"BaseFont").unwrap_or(b"")).into_owned();
|
||||
// The real face, bold and italic included: the published metrics differ by style,
|
||||
// so Times-Bold is not Times-Roman and neither is Helvetica scaled.
|
||||
m.std14 = crate::Std14::from_base_font(&base).or(Some(crate::Std14::Helvetica));
|
||||
let recognised = crate::Std14::recognise(&base);
|
||||
m.std14_named = matches!(recognised, Some((_, crate::Std14Match::Alias)));
|
||||
m.std14 = recognised.map(|(face, _)| face).or(Some(crate::Std14::Helvetica));
|
||||
}
|
||||
}
|
||||
if let Some(d) = descriptor {
|
||||
@@ -1144,6 +1149,24 @@ impl Metrics {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether [`Metrics::width`] of `code` is a width the font declares: a `/Widths` entry (or
|
||||
/// the embedded program's advance where `/Widths` is absent), a `/W` entry or an explicit
|
||||
/// `/DW`, or the published metrics of the standard-14 face `/BaseFont` names. It is not for a
|
||||
/// `/MissingWidth`, the implied `/DW` of 1000, or a standard-14 face guessed from the name.
|
||||
pub fn width_declared(&self, code: u32) -> bool {
|
||||
if self.composite {
|
||||
let cid = self.cid(code);
|
||||
return self.explicit_default || self.cid_widths.contains_key(&cid) || self.cid_ranges.find(cid).is_some();
|
||||
}
|
||||
if code.checked_sub(self.first).and_then(|i| self.widths.get(i as usize)).is_some() {
|
||||
return true;
|
||||
}
|
||||
match self.std14.filter(|_| self.std14_named) {
|
||||
Some(f) => u8::try_from(self.std14_code(f, code)).is_ok_and(|c| f.width(c) != 0.0),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the standard-14 table, indexed by WinAnsi, holds the glyph `code` draws in this font:
|
||||
/// its encoding (base and `/Differences`) names the glyph, so a remapped code is measured as
|
||||
/// the glyph it now shows (#2894). Symbol and ZapfDingbats are indexed by their own encodings,
|
||||
|
||||
@@ -2165,3 +2165,42 @@ fn a_dropped_codespace_range_is_reported() {
|
||||
assert!(parse_cmap(b"1 begincodespacerange <00> <FFFF> endcodespacerange").2);
|
||||
assert!(!parse_cmap(b"2 begincodespacerange <0000> <FFFF> <0000> <FFFF> endcodespacerange").2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn widths_the_font_declares_are_told_from_fallbacks() {
|
||||
let mut doc = Document::new_empty();
|
||||
let simple = |doc: &mut Document, base: &str, widths: Option<Vec<Object>>| {
|
||||
let mut entries = vec![("Subtype", Object::name("Type1")), ("BaseFont", Object::name(base))];
|
||||
if let Some(w) = widths {
|
||||
entries.extend([("FirstChar", Object::Int(65)), ("Widths", Object::Array(w))]);
|
||||
}
|
||||
let dict = font(doc, entries);
|
||||
Metrics::from_dict(doc, &dict)
|
||||
};
|
||||
let listed = simple(&mut doc, "HouseFont", Some(vec![Object::Int(500)]));
|
||||
assert!(listed.width_declared(65));
|
||||
assert!(!listed.width_declared(66), "a code past /Widths takes /MissingWidth");
|
||||
assert!(simple(&mut doc, "Helvetica", None).width_declared(65));
|
||||
assert!(simple(&mut doc, "Arial", None).width_declared(65), "a common alias names the face");
|
||||
assert!(!simple(&mut doc, "HouseSerif", None).width_declared(65), "Times is a guess from the name");
|
||||
assert!(!simple(&mut doc, "HouseFont", None).width_declared(65), "Helvetica is a guess");
|
||||
let cid = |doc: &mut Document, dw: Option<i64>| {
|
||||
let mut desc = Dict::new();
|
||||
desc.set(b"Subtype".to_vec(), Object::name("CIDFontType2"));
|
||||
desc.set(b"W".to_vec(), Object::Array(vec![Object::Int(1), Object::Array(vec![Object::Int(600)])]));
|
||||
if let Some(dw) = dw {
|
||||
desc.set(b"DW".to_vec(), Object::Int(dw));
|
||||
}
|
||||
let entries = vec![
|
||||
("Subtype", Object::name("Type0")),
|
||||
("Encoding", Object::name("Identity-H")),
|
||||
("DescendantFonts", Object::Array(vec![Object::Dict(desc)])),
|
||||
];
|
||||
let dict = font(doc, entries);
|
||||
Metrics::from_dict(doc, &dict)
|
||||
};
|
||||
let implied = cid(&mut doc, None);
|
||||
assert!(implied.width_declared(1));
|
||||
assert!(!implied.width_declared(2), "a CID /W leaves out, with no /DW, takes the implied 1000");
|
||||
assert!(cid(&mut doc, Some(500)).width_declared(2));
|
||||
}
|
||||
@@ -114,7 +114,7 @@ pub fn set_attachment_description(doc: &mut Document, key: &str, description: Op
|
||||
}
|
||||
|
||||
/// The `/EmbeddedFiles` entries (key, file specification), in tree order.
|
||||
fn entries(doc: &Document) -> Vec<(Vec<u8>, Object)> {
|
||||
pub(crate) fn entries(doc: &Document) -> Vec<(Vec<u8>, Object)> {
|
||||
let Some(tree) = doc
|
||||
.root()
|
||||
.and_then(|r| doc.get(r).as_dict().cloned())
|
||||
|
||||
@@ -105,7 +105,9 @@ fn added_objects(dst: &Document, before: &HashSet<u32>) -> Vec<ObjRef> {
|
||||
/// under one new bookmark titled `title` (the file's name) at its first inserted page, as Combine
|
||||
/// Files does for each file. That bookmark goes among the top-level bookmarks where the pages went:
|
||||
/// before the first one that points after them. Bookmarks to pages left out stay behind, unless a
|
||||
/// bookmark below them leads to an inserted page; a file without bookmarks adds none.
|
||||
/// bookmark below them leads to an inserted page; a file without bookmarks adds none. Catalog
|
||||
/// attachments are merged with the destination's attachments, with duplicate name-tree keys
|
||||
/// renamed, as in Combine Files.
|
||||
pub fn insert_file_pages(
|
||||
dst: &mut Document,
|
||||
src: &Document,
|
||||
@@ -125,6 +127,15 @@ pub fn insert_file_pages(
|
||||
let after = at.min(crate::page_count(dst)?.saturating_sub(imported.pages.len())).saturating_add(imported.pages.len());
|
||||
insert_file_bookmark(dst, &Mark { title: title.to_string(), page: *first, outline }, after)?;
|
||||
}
|
||||
if !imported.pages.is_empty() {
|
||||
let mut incoming = Vec::new();
|
||||
carry::collect_attachments(dst, src, &mut incoming)?;
|
||||
if !incoming.is_empty() {
|
||||
let mut attachments = crate::attachments::entries(dst);
|
||||
attachments.append(&mut incoming);
|
||||
set_attachments(dst, attachments)?;
|
||||
}
|
||||
}
|
||||
Ok(ImportOutcome { pages: imported.pages, renamed_fields: imported.renamed_fields })
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -250,7 +250,8 @@ update the numbers.
|
||||
Read Out Loud; full keyboard operation of PdfCraft itself and a screen-reader audit.
|
||||
- **Evidence:** all 32 checker rules, figure alt text, tag property and sibling order edits, and
|
||||
a bounded auto-tag preview exist. Apply writes valid structure and parent-tree links for
|
||||
text-only files, tagging headings by size and weight; it refuses mixed content and existing tags;
|
||||
text-only files, tagging headings by size and weight and marking running headers and footers
|
||||
as pagination artifacts; it refuses mixed content and existing tags;
|
||||
`a11y.keyboard-only` (P0) planned, `a11y.app-screen-reader` partial.
|
||||
- **Impact:** most untagged files still need another editor to build their structure; PdfCraft itself is
|
||||
not yet usable without a mouse.
|
||||
|
||||
+6
-4
@@ -126,7 +126,7 @@
|
||||
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-15 · **Change:** minor (M2: objects in one large object stream are read in linear time; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
|
||||
> **Last reviewed:** 2026-10-16; **Last updated:** 2026-10-16; **Change:** minor (M5 #2669, item 5: reply groups and page root counts per frame; estimates unchanged)
|
||||
>
|
||||
> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-14 · **Change:** minor (M14: the Italian catalog has every entry the other catalogs had and the code looks up, 2,528 entries; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
|
||||
> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-16 · **Change:** patch (M4: Insert from File retains catalog attachments in its undo step; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
|
||||
> **Last reviewed:** 2026-10-16 | **Last updated:** 2026-10-16 | **Change:** minor (M10 #1201 partial: lossless image Decode; estimates unchanged) | **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
|
||||
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-13 · **Change:** minor (M2/M6: spot-colour images convert once per pixel value; widget placement and the Fields panel scale with the field count; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
|
||||
> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-14 · **Change:** minor (M3 candidate: coordinate control clicks on slow frames and coalesced text selection; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
|
||||
@@ -255,7 +255,7 @@ total matches the parity estimate.
|
||||
| M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings. Packed TIFF-predictor RGB rows retain later rows in decoding and rendering. Page marks, added content and print output retain small page-unit transform coefficients when serialized. Forms without Resources use page Properties for ActualText and layer visibility; own dictionaries stop fallback. Oversized missing inline-image samples, including header and terminator overhead, no longer pin the content window (#3107 / PR #3438); normal large streamed images retain deterministic sample boundaries. Radial luminosity fades have synthetic coverage for the existing #2132 mask guard, including per-pixel references, antialiased clips, previews, scales and tiles; no additional production fix was needed. Dotted TOC leaders no longer inflate letter tracking or hide word spaces (#3086); phrase search and selection are covered. Short tracked ellipses retain their gap samples and remain searchable. Missing spacing glyphs in non-embedded Japanese CID substitutes render blank without changing PDF advances or Unicode (#3601). The desktop viewer can use installed CJK fonts, including Windows GBK Song/Hei/Kai/FangSong and subset-prefixed Founder names; Combine thumbnails and accessibility figure previews use the same display-only fallback, without changing export or print font policy (#234, continuation of #1567, review #4172). Print previews exclude installed faces and isolate their font cache; GBK regressions cover view/print switching for inline and pooled whole-page/tile rendering. Installed-font helpers and their regression contracts have function documentation. GBK regression rasters match explicit-Unicode references with independently selected installed faces; wrong-glyph and wrong-family negative controls fail. Integration with main fa5f9f8c retains viewer fallback across the split engine session modules, renderer tests and Combine thumbnail workers. |
|
||||
| M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings. Packed TIFF-predictor RGB rows retain later rows in decoding and rendering. The renderer keeps its one-point crop-size floor in physical points after UserUnit scaling, with regression coverage for crop origins, rotations and f32 reciprocal rounding. Existing unit policy and nearly-zero fallback are retained. |
|
||||
| M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings |
|
||||
| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). #3808: the Pages inspector offers a 50–150% thumbnail slider and buttons, also available through `ui.set`. Missing: 60 fps test on a 500-page document, snapshot tests of every panel<br>Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). Selected-text Copy in Edit and the canvas context menu is covered by focused regressions and native clipboard checks (#1225); document copy restrictions apply to the floating action too. #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Page-label navigation displays logical labels, retains the current page on unchanged submission and refreshes focused same-document replacements; clean file-watcher reload preserves the chosen scrolling mode, preventing a Single Page reader from jumping to page 1 during replacement. Synthetic control regressions cover these behaviors. #3149: page-list changes discard render demand based on old geometry; actual raster dimensions are checked against the GPU limit before upload. Synthetic crash and continued-rendering regressions cover the replacement path. Save-prompt shortcuts yield to dialogs above them; stacked link-consent UI regression covers Escape and Return. Comment hover follows individual marked lines and original annotation paint order (#3541/#3620), independently of spatial inspection sorting; synthetic rotation, differing-upper-edge overlap and unchanged-document regressions. Optional page gaps join page edges without cropping PDF margins; current-document toggle, persisted default and UI control options are covered by viewer tests. Gap changes in Organize Pages preserve document scroll position, and both comparison panes follow menu and control choices. Repeated window resizes by an edge and moves by the tab strip on GNOME/Wayland work without a click in between. Optional --two-paged applies noncontinuous two-page layout to explicitly opened CLI files without changing defaults; explicit --layout wins. Crop pages is directly available in the quick toolbar (#5330). Native Recent rows also offer Reveal in Finder / File Explorer (#5452). |
|
||||
| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). #3808: the Pages inspector offers a 50–150% thumbnail slider and buttons, also available through `ui.set`. Missing: 60 fps test on a 500-page document, snapshot tests of every panel<br>Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). Selected-text Copy in Edit and the canvas context menu is covered by focused regressions and native clipboard checks (#1225); document copy restrictions apply to the floating action too. #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Page-label navigation displays logical labels, retains the current page on unchanged submission and refreshes focused same-document replacements; clean file-watcher reload preserves the chosen scrolling mode, preventing a Single Page reader from jumping to page 1 during replacement. Synthetic control regressions cover these behaviors. #3149: page-list changes discard render demand based on old geometry; actual raster dimensions are checked against the GPU limit before upload. Synthetic crash and continued-rendering regressions cover the replacement path. Save-prompt shortcuts yield to dialogs above them; stacked link-consent UI regression covers Escape and Return. Comment hover follows individual marked lines and original annotation paint order (#3541/#3620), independently of spatial inspection sorting; synthetic rotation, differing-upper-edge overlap and unchanged-document regressions. Optional page gaps join page edges without cropping PDF margins; current-document toggle, persisted default and UI control options are covered by viewer tests. Gap changes in Organize Pages preserve document scroll position, and both comparison panes follow menu and control choices. Repeated window resizes by an edge and moves by the tab strip on GNOME/Wayland work without a click in between. Optional --two-paged applies noncontinuous two-page layout to explicitly opened CLI files without changing defaults; explicit --layout wins. Crop pages is directly available in the quick toolbar (#5330). Native Recent rows also offer Reveal in Finder / File Explorer (#5452). Opened from a launcher with startup notification (the Linux desktop entry), the first window hands the launcher's activation token back, so GNOME's busy cursor clears when the window appears instead of after 15 seconds. |
|
||||
| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel<br>Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). Selected-text Copy in Edit and the canvas context menu is covered by focused regressions and native clipboard checks (#1225); document copy restrictions apply to the floating action too. #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Page-label navigation displays logical labels, retains the current page on unchanged submission and refreshes focused same-document replacements; clean file-watcher reload preserves the chosen scrolling mode, preventing a Single Page reader from jumping to page 1 during replacement. Synthetic control regressions cover these behaviors. Wrapped revision buttons stay above Binding in Document Properties (#2739); a synthetic UI test checks layout and saved revision content. |
|
||||
| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel<br>Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Later native-open replies stay queued while a modal or picker owns the foreground; regressions cover recipient ownership, completion/cancellation and one-shot wakes. |
|
||||
| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel<br>Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. #1980: exact quit modifiers preserve Ctrl+Alt+Q email input; Ctrl+Q/Cmd+Q asks before discarding unsaved documents. |
|
||||
@@ -264,7 +264,7 @@ total matches the parity estimate.
|
||||
| M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. A custom text match that ends on a reconstructed separator stops before the next glyph (#1315). Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings |
|
||||
| M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); Lab Bradford adaptation uses LMS white-point ratios, covered by independent neutral/chromatic and direct/Indexed render oracles; inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings. Literal page-label prefix whitespace is preserved; nine public-inspection cases cover prefix spaces, encodings and empty-prefix controls |
|
||||
| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel<br>Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). |
|
||||
| M4 | Engine, history, save, organize | 100–180 | 95% | 8–15 | Done:<br>- command registry (menus, shortcuts and palette all use it);<br>- undo/redo; incremental, atomic and encrypted saves;<br>- autosave and crash recovery;<br>- organize, combine, extract, split and insert-from-file, with identical fonts and images stored once;<br>- CLI `edit/combine/extract/split`.<br>Done since: Organize opens directly into the page overview, with checkbox selection, an editable page-range selection (#1092), and per-page rotate/delete controls; Combine files in its own tab (sortable, resizable columns; folders; early warnings; unlocking protected files), bookmark editing, page labels (Number pages), CLI `run`, Set Page Boxes, Crop tool, Duplicate pages, Ctrl+A / Cmd+A to select all pages in Organize, Replace pages, bookmarks from tagged headings. Extract and Split preserve shared Type 3 glyph resource graphs, retaining conservative pruning limits. Undo back to the opened or last saved file is clean; Revert opens that saved file after an undo; a later save appends to it so the saved revision stays in the file (#1310, #1311, #1312). Ctrl-drag (Option on macOS) on a grid thumbnail copies the pages into the drop gap, with a "+" badge and the copies selected (#2997). Initial-view window and interface options resolve indirect boolean preferences. Done since: #3309: Stack-safe named-destination pruning visits shared/cyclic indirect nodes once, without a name-count limit. Synthetic deep-tree and 60,000-name tests verify deletion, surviving targets, undo/redo, both save modes and reopening. Organize drags cancel after document edits and Undo/Redo (#3916 partial). Document Properties dismisses stale drafts after edits, reloads or tab changes; JSONL replay covers commit, cancellation and save/reopen. Missing: page transitions, recovery on the web. Maintainers are reviewing the vendored Document Properties runtime and the optional local scenario replay. |
|
||||
| M4 | Engine, history, save, organize | 100–180 | 95% | 8–15 | Done:<br>- command registry (menus, shortcuts and palette all use it);<br>- undo/redo; incremental, atomic and encrypted saves;<br>- autosave and crash recovery;<br>- organize, combine, extract, split and insert-from-file, with identical fonts and images stored once;<br>- CLI `edit/combine/extract/split`.<br>Done since: Organize opens directly into the page overview, with checkbox selection, an editable page-range selection (#1092), and per-page rotate/delete controls; Combine files in its own tab (sortable, resizable columns; folders; early warnings; unlocking protected files), bookmark editing, page labels (Number pages), CLI `run`, Set Page Boxes, Crop tool, Duplicate pages, Ctrl+A / Cmd+A to select all pages in Organize, Replace pages, bookmarks from tagged headings. Extract and Split preserve shared Type 3 glyph resource graphs, retaining conservative pruning limits. Undo back to the opened or last saved file is clean; Revert opens that saved file after an undo; a later save appends to it so the saved revision stays in the file (#1310, #1311, #1312). Insert from File retains catalog attachments in the same undo step, preserving existing destination name trees and duplicate-key encoding. Ctrl-drag (Option on macOS) on a grid thumbnail copies the pages into the drop gap, with a "+" badge and the copies selected (#2997). Initial-view window and interface options resolve indirect boolean preferences. Done since: #3309: Stack-safe named-destination pruning visits shared/cyclic indirect nodes once, without a name-count limit. Synthetic deep-tree and 60,000-name tests verify deletion, surviving targets, undo/redo, both save modes and reopening. Organize drags cancel after document edits and Undo/Redo (#3916 partial). Document Properties dismisses stale drafts after edits, reloads or tab changes; JSONL replay covers commit, cancellation and save/reopen. Missing: page transitions, recovery on the web. Maintainers are reviewing the vendored Document Properties runtime and the optional local scenario replay. |
|
||||
| M4 | Engine, history, save, organize | 100–180 | 95% | 8–15 | Done:<br>- command registry (menus, shortcuts and palette all use it);<br>- undo/redo; incremental, atomic and encrypted saves;<br>- autosave and crash recovery;<br>- organize, combine, extract, split and insert-from-file, with identical fonts and images stored once;<br>- CLI `edit/combine/extract/split`.<br>Done since: Organize opens directly into the page overview, with checkbox selection, an editable page-range selection (#1092), and per-page rotate/delete controls; Combine files in its own tab (sortable, resizable columns; folders; early warnings; unlocking protected files), bookmark editing, page labels (Number pages), CLI `run`, Set Page Boxes, Crop tool, Duplicate pages, Ctrl+A / Cmd+A to select all pages in Organize, Replace pages, bookmarks from tagged headings. Extract and Split preserve shared Type 3 glyph resource graphs, retaining conservative pruning limits. Undo back to the opened or last saved file is clean; Revert opens that saved file after an undo; a later save appends to it so the saved revision stays in the file (#1310, #1311, #1312). Rotation queries and edits resolve indirect values on pages and ancestors. Refreshed against upstream `99941daa` (2026-10-15). Repeated page indices accumulate rotations from the latest local value (#1919); saved/reopened regressions retain inherited angles and siblings. Missing: page transitions, recovery on the web |
|
||||
| M4 | Engine, history, save, organize | 100–180 | 95% | 8–15 | Done:<br>- command registry (menus, shortcuts and palette all use it);<br>- undo/redo; incremental, atomic and encrypted saves;<br>- autosave and crash recovery;<br>- organize, combine, extract, split and insert-from-file, with identical fonts and images stored once;<br>- CLI `edit/combine/extract/split`.<br>Done since: Organize opens directly into the page overview, with checkbox selection, an editable page-range selection (#1092), and per-page rotate/delete controls; Combine files in its own tab (sortable, resizable columns; folders; early warnings; unlocking protected files), bookmark editing, page labels (Number pages), CLI `run`, Set Page Boxes, Crop tool, Duplicate pages, Ctrl+A / Cmd+A to select all pages in Organize, Replace pages, bookmarks from tagged headings. Extract and Split preserve shared Type 3 glyph resource graphs, retaining conservative pruning limits. Undo back to the opened or last saved file is clean; Revert opens that saved file after an undo; a later save appends to it so the saved revision stays in the file (#1310, #1311, #1312). Rotation queries and edits resolve indirect values on pages and ancestors. Missing: page transitions, recovery on the web |
|
||||
| M4 | Engine, history, save, organize | 100–180 | 95% | 8–15 | Done:<br>- command registry (menus, shortcuts and palette all use it);<br>- undo/redo; incremental, atomic and encrypted saves;<br>- autosave and crash recovery;<br>- organize, combine, extract, split and insert-from-file, with identical fonts and images stored once;<br>- CLI `edit/combine/extract/split`.<br>Done since: Organize opens directly into the page overview, with checkbox selection, an editable page-range selection (#1092), and per-page rotate/delete controls; Combine files in its own tab (sortable, resizable columns; folders; early warnings; unlocking protected files), bookmark editing, page labels (Number pages), CLI `run`, Set Page Boxes, Crop tool, Duplicate pages, Ctrl+A / Cmd+A to select all pages in Organize, Replace pages, bookmarks from tagged headings. Extract and Split preserve shared Type 3 glyph resource graphs, retaining conservative pruning limits. Missing: page transitions, recovery on the web M4: Insert-from-file preserves source bookmarks; integration tests retained with current main. |
|
||||
@@ -299,7 +299,7 @@ total matches the parity estimate.
|
||||
| M11 | Optimize, preflight, PDF/A/X/UA, print production | 200–350 | 18% | 80–140 | Done: new `optimize` crate: Reduce File Size and the PDF Optimizer (images measured where drawn, bicubic downsampling, JPEG/ZIP recompression only when smaller, discard objects and user data, Flate clean-up, resource merging, object streams). Target-version compatibility is partial: newer content is not detected or converted. Content stream boundaries preserve comments, split operands and graphics state when image fragments merge. Image downsampling includes page-local `/UserUnit` scaling when measuring physical resolution. Done since: reject invalid image and soft-mask dimensions with checked sizing (#2178). Missing: fonts and transparency panels, space audit, preflight, PDF/A/X/UA |
|
||||
| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds. Character encoding accepts Identity-H/V with Adobe CJK collections and predefined CJK CMaps independently (#3673); per-glyph validation and embedded-font extraction remain separate.<br>Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded, text-only auto-tag proposal tool for one page. Marking a figure decorative rewrites only that stream (#1324). An XFA radio item whose value contains a space is written back unchanged (#1319). Done since: #2569: Growable multiline XFA text reflows after edits, with undo/redo, save/reopen and print coverage; oversized fields still become read-only page text. Structured-data synchronization warnings retain accepted whitespace without relayout from stale data. Done since: #2572: Every repeated page-master button resolves its own field to the shared XFA click script, including print buttons. Done since: #2570: Dynamic XFA rich-text fields carry exData/maxLength into AcroForm MaxLen for reported and enforced Unicode character limits, retained after save/reopen. Done since: #2589: Active XFA skips PDF-container fallback scripts while retaining requested messages and saved scripts; ordinary/static/unlaid-out documents and explicit console/field calls keep their existing behavior. Missing: writing proposed tags and parent tree, field autotag, visual Tags/Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA<br>Reading colours: pending page backgrounds follow the configured colour (#2059). |
|
||||
| M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 25–45 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers<br>Done since: CLI run and MCP reject missing, empty, repeated and option-valued --root arguments before any tool/script execution or MCP initialization. A single-hyphen directory name remains valid; synthetic CLI regressions preserve a would-be overwritten file. `text_find` also caps the per-page match ranges it materializes at the remaining result limit plus one continuation match. CLI robustness scans visit each directory once through overlapping roots and symlink aliases. |
|
||||
| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds. Character encoding accepts Identity-H/V with Adobe CJK collections and predefined CJK CMaps independently (#3673); per-glyph validation and embedded-font extraction remain separate.<br>Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded text-only auto-tag proposal tool; text-only Apply writes marked content, heading and paragraph tags and a parent tree, then opens the Tags panel for review. Missing: mixed-content and field autotag, list/table/figure classification, Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA<br>Done since: CLI info, text and render use dynamic XFA layout pages, with synthetic count/text/pixel and copy-permission regressions (#1645).<br>Reading colours: pending page backgrounds follow the configured colour (#2059). |
|
||||
| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds. Character encoding accepts Identity-H/V with Adobe CJK collections and predefined CJK CMaps independently (#3673); per-glyph validation and embedded-font extraction remain separate.<br>Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded text-only auto-tag proposal tool; text-only Apply writes marked content, heading and paragraph tags and a parent tree, marks running headers and footers as pagination artifacts, then opens the Tags panel for review. Missing: mixed-content and field autotag, list/table/figure classification, Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA<br>Done since: CLI info, text and render use dynamic XFA layout pages, with synthetic count/text/pixel and copy-permission regressions (#1645).<br>Reading colours: pending page backgrounds follow the configured colour (#2059). |
|
||||
| M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 25–45 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers<br>Done since: CLI run and MCP reject missing, empty, repeated and option-valued --root arguments before any tool/script execution or MCP initialization. A single-hyphen directory name remains valid; synthetic CLI regressions preserve a would-be overwritten file. `text_find` also caps the per-page match ranges it materializes at the remaining result limit plus one continuation match. |
|
||||
| M14 | 1.0 polish: performance, localization, installers | 120–250 | 15% | 80–150 | Local customization: adjustable, floating or side-docked hotbar with optional full-side strip and persistent tool picker; freehand highlighting is grouped with Highlight. Estimates unchanged. Done: PhotoCraft's translation system (`i18n/`: TSV catalogs, `tl!`, command-id and plural entries, system-language detection, strict catalog tests); every dialog, panel and notice goes through `tl!`. Catalogs of ≈ 2,000–2,140 entries for Japanese, Simplified and Traditional Chinese, Russian, Bulgarian, German, Spanish, French, Telugu, Hungarian, Ukrainian and Arabic (logical catalog; explicit right-to-left labels and mirrored stock chrome; end-to-end RTL workflows unqualified); the 2,674-entry Brazilian Portuguese catalog covers the current key union; Czech covers the menus. Italian has 2,528 entries: every key of the other catalogs that the code looks up. Signed and notarized macOS builds, signed Windows installers (x64, x86, ARM64), AppImage, deb, rpm, Flatpak and FreeBSD packages. #307 (bounded large-PDF memory): shared resource indexes and parser metadata, lazy inspection, bounded caches; a 9,156-page file inspects in ≈ 1.8 s at ≈ 500 MiB instead of exceeding 10 GiB. Edits let go of the previous working file before writing the next (a 1 GiB file peaks at two copies while editing, not three; gap 13). Shortcut display uses localized modifier/key names across menus, toolbar, palette, Help and tooltips (#496). Lithuanian adds a 2,578-entry catalog and date names, reviewed by a native-speaking contributor. Norwegian Bokmål adds a catalog and date names (terminology reviewed by a native speaker). Validated candidate (macOS raster probe; Windows runtime unverified): the Windows policy changes only embedded JetBrains Mono; horizontal alpha-edge energy per ink improves 2.78%, 3.87% and 1.59% at 100%, 125% and 150%, and is down 0.79% at 200%. Inter is pixel-identical; layout hashes, glyph coverage and the 8 MiB atlas are unchanged. Timing and RSS ranges overlap, with no improvement claimed. Estimates unchanged. Candidate #2383 clamps GPU requests to supported limits while retaining the adapter texture extent; synthetic V3D/downlevel and Windows GPU-required tests pass, but Raspberry Pi startup is unverified. Missing: end-to-end RTL workflow qualification, a Chinese web UI face, Hindi/Indonesian/Korean, file-backed input and global memory budgets, performance budgets, keyboard-only operation Linux/Unix UI fallback fonts also use Fontconfig directories, including Nix store paths, with bounded discovery and the existing candidate allowlist; relative includes and digit-prefixed config filtering have isolated regressions. Missing: end-to-end RTL workflow qualification, a Chinese web UI face, Hindi/Indonesian/Korean, file-backed input and global memory budgets, performance budgets, keyboard-only operation XDG desktops use the configuration base for preferences with non-overwriting migration and original-data preservation (#1395). Traditional Chinese accessibility statuses, rule semantics and Taiwan form/table terms have catalog regressions. Long main-menu lists scroll in short windows (#3373). Missing: end-to-end RTL workflow qualification, a Chinese web UI face, Hindi/Indonesian/Korean, file-backed input and global memory budgets, performance budgets, keyboard-only operation. Candidate #3558: bounded-worker macOS per-file PDFCraft association recovery after desktop open/save/sign; metadata-only watcher handling and upstream #3042 shared-writer preservation; recovery parser limits do not narrow save limits. Native workflow qualified on macOS 27.0.1; other versions and physical SMB/FUSE volumes remain unqualified. Estimates unchanged. Missing: end-to-end RTL workflow qualification, a Chinese web UI face, Hindi/Indonesian/Korean/Vietnamese, file-backed input and global memory budgets, performance budgets, keyboard-only operation. |
|
||||
| M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 25–45 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers |
|
||||
@@ -375,6 +375,7 @@ Estimates unchanged.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-16 | patch | M4: Insert from File retains catalog attachments with native undo/redo; existing name trees and encoded duplicate keys survive. Estimates unchanged. |
|
||||
| 2026-11-16 | patch | M5 #3741: Ctrl+M opens Comments on Windows/Linux without toggling it closed; macOS leaves Command+M for Minimize; platform-specific shortcut surfaces and regressions retained; estimates unchanged. |
|
||||
| 2026-10-29 | minor | M10 #5029: existing Text appearances keep their implicit NoRotate orientation in vector printing even when the flag is clear. Print eligibility and source/AP objects remain unchanged; native viewing without the flag remains a separate gap. Estimates unchanged. |
|
||||
| 2026-10-27 | minor | M10 #5029: vector printing preserves existing NoRotate appearance orientation and anchors; estimates unchanged. Missing appearances and NoZoom print behavior remain unchanged. |
|
||||
@@ -429,6 +430,7 @@ Estimates unchanged.
|
||||
| 2026-10-17 | minor | M8, gap 6 #2662: a filled cover that hides half of any one word of a long line counts as a redaction-audit finding, applied or not; a sliver under half of every word stays unflagged. Estimates unchanged. |
|
||||
| 2026-10-13 | minor | M10: dotted-leader contents entries retain titles and page numbers in separate paragraphs (#1757); estimates unchanged. |
|
||||
| 2026-10-22 | minor | M6: calculation scripts: simplified field notation is read only from a comment, and a regular expression after `if (…)`, `while (…)`, `for (…)` or `with (…)` as one, so a rename leaves strings and regular expressions alone; a `//` comment ends at any line terminator, not only `\n`. Estimates unchanged. |
|
||||
| 2026-10-21 | minor | M3: on Linux, the first window takes the launcher's activation token (`XDG_ACTIVATION_TOKEN`, `DESKTOP_STARTUP_ID`) and hands it back, so the busy cursor clears when the window appears (vendored winit patch 14). Estimates unchanged. |
|
||||
| 2026-10-20 | minor | M6: Prepare a form ▸ Calculation order: formulas and values, what is wrong and Fix order, Up/Down, Alt+↑/↓ and drag, links on the page. Estimates unchanged. |
|
||||
| 2026-10-20 | minor | M6: `form_calculation_order` reads, checks, fixes and sets the calculation order; an edited formula keeps its place in `/CO`. Estimates unchanged. |
|
||||
| 2026-10-20 | minor | M12 #3673: Character encoding accepts Identity-H/V with Adobe CJK collections, or a predefined non-Identity CMap; unknown names and foreign registries do not establish a mapping route. Synthetic checker and read-only automation regressions passed after failing before the fix. Per-glyph validation and embedded-font extraction remain separate; estimates unchanged. |
|
||||
|
||||
@@ -2788,8 +2788,8 @@ milestone = "M4"
|
||||
status = "shipped"
|
||||
commands = ["page.insert"]
|
||||
tools = ["page_insert_file"]
|
||||
evidence = ["crates/organize/src/tests.rs::inserting_pages_from_another_file_is_an_incremental_edit", "crates/organize/src/tests.rs::inserting_a_file_brings_its_bookmarks_under_one_named_after_it", "crates/automation/tests/it/automation.rs::inserting_a_file_brings_its_bookmarks", "crates/ui-egui/tests/it/editing.rs::inserting_a_file_goes_after_the_selection_and_undoes", "crates/ui-egui/tests/it/editing.rs::plus_between_pages_inserts_picked_files_there_in_order"]
|
||||
notes = "After the selection (toolbar, File menu) or at any gap of the page grid (a + between pages and at both ends); several files at once, in order; images and .txt files are converted first; the inserted pages end up selected. The file's bookmarks come along, collapsed under one named after the file, placed among the document's bookmarks where the pages went (as Combine does per file). The page_insert_file tool takes PDFs only. Missing: choosing which pages of the file to insert in the app; the file's tags (structure tree) are not merged."
|
||||
evidence = ["crates/organize/src/tests.rs::inserting_pages_from_another_file_is_an_incremental_edit", "crates/organize/src/tests.rs::inserting_a_file_brings_its_bookmarks_under_one_named_after_it", "crates/automation/tests/it/automation.rs::inserting_a_file_brings_its_bookmarks", "crates/ui-egui/tests/it/editing.rs::inserting_a_file_goes_after_the_selection_and_undoes", "crates/ui-egui/tests/it/editing.rs::plus_between_pages_inserts_picked_files_there_in_order", "crates/engine/tests/insert_attachments.rs::inserted_catalog_attachments_follow_native_undo_redo"]
|
||||
notes = "After the selection (toolbar, File menu) or at any gap of the page grid (a + between pages and at both ends); several files at once, in order; images and .txt files are converted first; the inserted pages end up selected. The file's bookmarks come along, collapsed under one named after the file, placed among the document's bookmarks where the pages went (as Combine does per file). Catalog attachments are merged with the document's existing attachments in the same undo step; colliding names are suffixed without changing their encoding. The page_insert_file tool takes PDFs only. Missing: choosing which pages of the file to insert in the app; the file's tags (structure tree) are not merged."
|
||||
|
||||
[[feature]]
|
||||
id = "organize.insert-from-clipboard"
|
||||
@@ -3171,9 +3171,9 @@ tier = "P1"
|
||||
milestone = "M4"
|
||||
status = "shipped"
|
||||
commands = []
|
||||
tools = []
|
||||
evidence = ["crates/organize/src/tests.rs::combine_nests_source_bookmarks_and_keeps_attachments"]
|
||||
notes = ""
|
||||
tools = ["doc_combine", "page_insert_file"]
|
||||
evidence = ["crates/organize/src/tests.rs::combine_nests_source_bookmarks_and_keeps_attachments", "crates/engine/tests/insert_attachments.rs::inserted_catalog_attachments_follow_native_undo_redo", "crates/engine/tests/insert_attachments.rs::inserting_into_a_document_without_attachments_retains_other_names"]
|
||||
notes = "Also preserved by Insert from File, including native undo/redo and existing destination name trees. This covers catalog EmbeddedFiles, not PDF 2.0 associated-file relationships (AF)."
|
||||
|
||||
[[feature]]
|
||||
id = "organize.field-name-conflicts"
|
||||
@@ -3427,6 +3427,18 @@ tools = ["text_styles", "bookmark_from_text_styles"]
|
||||
evidence = ["crates/engine/src/tests.rs::bookmarks_from_text_styles_nest_the_headings_and_undo", "crates/engine/src/text_style_bookmarks.rs::subset_tags_are_left_out_of_the_font_name", "crates/engine/src/text_style_bookmarks.rs::styles_match_within_a_quarter_point", "crates/automation/tests/it/automation.rs::bookmarks_from_text_styles_through_tools", "crates/ui-egui/tests/it/bookmarks.rs::new_bookmarks_from_text_styles_from_the_bookmark_options"]
|
||||
notes = "Bookmark options (and Pages) ▸ New bookmarks from text styles…, for documents whose headings aren't tagged (#1693): the dialog lists the document's text styles (font without its subset tag, the size shown at, bold, italic, line count and a sample), the largest first and offered for level 1; one style per level, up to four levels (nine headlessly). Every line in a level's style becomes a bookmark of that level under a new first \"Untitled\" bookmark, a heading set on several rows is one bookmark, and each goes to the top of its heading (/XYZ). Lines are read down each page, then left to right, so a multi-column page's headings are taken row by row across the columns; sizes within a quarter point match. Not yet: several styles for one level, colour as part of a style, and the first 5000 pages only. Acrobat has no such command (its bookmarks come from structure); this is beyond it"
|
||||
|
||||
[[feature]]
|
||||
id = "organize.suggest-outline"
|
||||
title = "Suggest bookmarks for review"
|
||||
area = "D"
|
||||
tier = "P2"
|
||||
milestone = "M4"
|
||||
status = "partial"
|
||||
commands = []
|
||||
tools = ["bookmark_suggest"]
|
||||
evidence = ["crates/automation/tests/it/suggest_outline.rs::suggest_from_layout_then_import_and_undo", "crates/automation/tests/it/suggest_outline.rs::suggest_uses_the_tags_once_there_are_some", "crates/engine/src/suggest_outline.rs::headings_take_levels_by_size_and_weight_and_wrapped_lines_join", "crates/engine/src/suggest_outline.rs::a_wrapped_heading_joins_across_a_line_of_another_column", "crates/engine/src/suggest_outline.rs::captions_and_numbers_are_not_headings", "crates/engine/src/suggest_outline.rs::captions_match_in_any_case", "crates/engine/src/suggest_outline.rs::a_bold_word_inside_a_sentence_is_not_a_heading", "crates/engine/src/suggest_outline.rs::a_bold_word_set_smaller_than_its_sentence_is_not_a_heading_but_a_larger_one_is", "crates/engine/src/suggest_outline.rs::a_bold_word_painted_into_a_gap_in_one_run_of_prose_is_not_a_heading", "crates/engine/src/suggest_outline.rs::a_heading_over_tightly_set_text_or_across_a_narrow_gutter_stays_a_heading", "crates/engine/src/suggest_outline.rs::text_beside_an_italic_word_still_sets_the_body_size", "crates/engine/src/suggest_outline.rs::more_headings_than_the_cap_are_reported", "crates/engine/src/suggest_outline.rs::a_page_whose_text_cant_be_read_is_not_counted", "crates/engine/src/suggest_outline.rs::the_tree_nests_by_level_and_caps_the_depth", "crates/a11y/src/heading_levels.rs::blocks_take_the_levels_auto_tag_gives_text_objects"]
|
||||
notes = "#6020, headless only: bookmark_suggest proposes a bookmark tree without changing the document, from its tagged headings when it has them, or else from how its text looks, by the heading rules Auto-tag uses (a short block larger than the body text, or bold where the body is not, levelled by size without skipping a level). A heading set on several lines is one bookmark going to its top (/XYZ); captions (Figure 3, Table 2) and bold words inside a sentence (prose in another style, no smaller than them, right beside them on the row or in one run spanning them) are left out, which also leaves out a run-in heading set on the same line as its paragraph, a side head no larger than the body text half an em beside it, a heading after a label with lower-case letters in another style (Appendix, then A Title in bold), a wrapped heading any of whose lines has prose beside it, and a heading drawn inside the box of a wider run of prose on its row. The proposal is in bookmark_export's form, so it is reviewed and edited as data and applied with bookmark_import in one undoable step. Not yet: the review dialog in the app, leaving out running headers and footers, multi-column reading order (lines are read down the page, then across), and the first 5000 pages only. Acrobat makes bookmarks from structure only; this is beyond it"
|
||||
|
||||
[[feature]]
|
||||
id = "organize.bookmarks-import-export"
|
||||
title = "Export, import and copy bookmarks"
|
||||
@@ -9151,8 +9163,8 @@ milestone = "M12"
|
||||
status = "partial"
|
||||
commands = ["a11y.autotag"]
|
||||
tools = ["accessibility_autotag_preview", "accessibility_autotag_apply"]
|
||||
evidence = ["crates/automation/tests/it/automation.rs::autotag_preview_proposes_text_without_changing_the_pdf", "crates/automation/tests/it/automation.rs::autotag_apply_writes_reviewable_tags_and_survives_save_reopen", "crates/automation/tests/it/automation.rs::autotag_apply_tags_headings_by_size_across_pages", "crates/a11y/src/autotag_roles.rs::levels_rank_styles_largest_first_and_never_skip_a_level", "crates/ui-egui/tests/it/accessibility.rs::automatic_text_tagging_opens_reviewable_tags"]
|
||||
notes = "Auto-tag writes real marked content, a Document structure element, H1-H6 and P tags and a parent tree for text-only PDFs, with undo and Tags-panel review. A text object is a heading when it is short and larger or bolder than the body text; levels rank those styles across the document and never skip a level. It refuses mixed content, forms, annotations and existing tags. The preview still proposes headings by its own single-line rule, so it can differ from Apply. Running headers and footers can still become headings (#7065); invisible text (render mode 3) is ignored. Images, tables, lists, links and fields are not classified or tagged by Apply."
|
||||
evidence = ["crates/automation/tests/it/automation.rs::autotag_preview_proposes_text_without_changing_the_pdf", "crates/automation/tests/it/automation.rs::autotag_apply_writes_reviewable_tags_and_survives_save_reopen", "crates/automation/tests/it/automation.rs::autotag_apply_tags_headings_by_size_across_pages", "crates/automation/tests/it/automation.rs::autotag_apply_marks_running_headers_and_footers_as_artifacts", "crates/a11y/src/tests.rs::autotag_text_leaves_turned_text_that_runs_out_of_the_band_tagged", "crates/a11y/src/autotag_roles.rs::levels_rank_styles_largest_first_and_never_skip_a_level", "crates/ui-egui/tests/it/accessibility.rs::automatic_text_tagging_opens_reviewable_tags"]
|
||||
notes = "Auto-tag writes real marked content, a Document structure element, H1-H6 and P tags and a parent tree for text-only PDFs, with undo and Tags-panel review. A text object is a heading when it is short and larger or bolder than the body text; levels rank those styles across the document and never skip a level. It refuses mixed content, forms, annotations and existing tags. The preview still proposes headings by its own single-line rule, so it can differ from Apply. Text repeating near the top or bottom edge of most pages (the same text, digits aside, at about the same height, its whole run from origin to advance inside the band) is marked as a /Pagination /Header or /Footer artifact instead of tagged, and Apply lists it for review; text in glyphs whose widths the font does not declare (no /Widths entry, not a standard-14 face it names) is never marked; invisible text (render mode 3) is ignored. Images, tables, lists, links and fields are not classified or tagged by Apply."
|
||||
|
||||
[[feature]]
|
||||
id = "a11y.autotag-fields"
|
||||
|
||||
Vendored
+1
-1
@@ -67,7 +67,7 @@ Other resource categories retain their existing parent-chain lookup.
|
||||
| hayro-jbig2 | 0.3.0 | Apache-2.0 OR MIT | (1) at most 2^28 pixels per bitmap and page bitmap, and 2^25 cells per halftone grid and grayscale image (each side could be 65535: 4.3 billion pixels decoded one by one, and a 4-byte value per cell); (2) at most as many symbol pixels per symbol dictionary as the largest page bitmap holds, 2^28 (a fuzzed dictionary decoded for minutes; each symbol now pays for its pixels out of the stream's decoding work and is held in the retained bitmaps, and at the earlier 2^26 the soft mask of a scanned drawing, one dictionary of 7,559 symbols, was refused: #6722), and a refusal by one of the decoder's limits is told apart from damaged data (`DecodeError::is_limit`, `OverflowError::BitmapLimit`); (3) a symbol dictionary's height classes are capped at one per new symbol and its export runs at `2 × symbols + 1`, each plus `EXTRA_EMPTY_STEPS` (1024): an empty height class or a zero-length export run doesn't advance, and past the end of its data the arithmetic decoder can decode them for ever (one changed byte hung the renderer); (4) a segment header's long-form referred-to segment count is capped at `u16::MAX` and a larger count is refused before its retention or referred-to bytes are read: the 29-bit count went straight to `Vec::with_capacity`, a reservation of about 2 GiB whose failure aborts the process (from storytold/craft-libs#176); (5) what a page's segments hold for later ones (intermediate regions, pattern and symbol dictionaries with their headers and retained contexts, and Huffman tables) is at most 64 MiB, two square bitmaps of 16,384 a side (`MAX_RETAINED_WORDS`), and a dictionary's new and exported symbols are counted against it as they are made: each was bounded on its own, but a few dozen bytes an intermediate region held 33 MB each, and 8 MiB symbols exported again and again killed the process, so a few kilobytes could exhaust memory; (6) a segment may refer to at most 2^20 symbols, checked before any are collected: references may repeat, and 65,535 of them to one dictionary, in a 78 KB stream, asked for 17 GB; (7) a pattern dictionary keeps at most 16 MiB of shifted copies, which only speed up drawing, and none that wouldn't fit what the page has left (`MAX_SHIFTED_WORDS`); (8) a custom Huffman table has at most 2^16 lines, and a stream with its globals at most 2^20 segments and 2^22 references, checked as they are read: both grew before anything counted them, and PDFs of a kilobyte or so reached 5 GB and more behind nested Flate; (9) a page past the bounds of (1) is refused when the stream is opened: a caller sizes its output from the header before the page bitmap is made, and an Indexed image in a 743-byte PDF asked for 137 GB, which aborts; (10) a stream may ask for at most 2^30 units of decoding work, four of the largest pages, about 6 s to 17 s (`MAX_WORK`): decoding a bitmap costs a pixel each and 4 a row, copying one a word each and 1 a row, and each integer an item reads costs 38, what one takes at worst, so one with no pixels pays too, before it is decoded: each bitmap was bounded, but nothing bounded how many there were, and a 795-byte PDF took 265 s; (11) `Image::decode_within` spends from what a run of images may still do, starting with its page's pixels, and `charge_reading` charges reading a stream and its globals before anything is parsed, so an operation over a document can bound what `MAX_WORK` bounds for one image, and images that fail or decode nothing add up too: a file of thousands of images made to reach that limit took as many times as long; (12) adding to a location, a reference offset, a symbol's corner or a Huffman range line near the end of an `i32`, and negating a decoded integer of 2^31, overflowed: a panic wherever overflow is checked. The refinement context, a text region's corners, the integer decoder and the Huffman table wrap, as a release build did, and `Bitmap::combine` saturates, which comes to the same, as a location that overflows is past the end of any page. What is drawn doesn't change; (13) a bitmap filled with a default pixel of 1 (a page, or an intermediate text or halftone region) had 1s past its width in the last word of each row, and a refinement, which reads its reference a word at a time, read them as pixels where the standard has 0 (6.3.5.2): refining such a reference not a multiple of 32 wide decoded to other pixels than were coded, release builds too. `Bitmap::clear_padding` clears those bits when a bitmap is filled with 1s, as cutting symbols and patterns from a collective bitmap already did. Ghostscript reads the test's page and text streams as they decode now; (14) a region's location is unsigned (5.4.4), so one past `i32::MAX` is off the page, where the decoder took it for a signed one: a region there was drawn back onto the page from the left or the top (at 0xFFFFFFFC, four pixels left of it), and a refinement there, of the page or of a region at the same place (7.4.7.5), was refused as an overflow, and Line truncated
|
||||
| lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589); (4) the object lookup keeps its cycle history through compressed objects, requires an ordinary in-file container, and caps the chain of indirect lookups at 16 (a chain of new objects, each a `/Length` compressed in a container whose own `/Length` names the next, or a stream whose `/Length` names the next stream, overflowed the stack: a dev build's 2 MiB thread within 800 hops); (5) object-stream members are parsed within their own extent (up to the next distinct offset), an entry whose offset repeats an earlier entry's is skipped (so a repeated object number can resolve to its earlier entry), and offsets are processed in index order; (6) `find_latest_trailer`: a rebuild takes a `/Type /XRef` stream dictionary as the trailer when the file has no `trailer` keyword (the latest in the file wins, as a later `trailer` would), so a concatenated or truncated file keeps its /Info and /ID instead of failing to load; a candidate whose /Root is the catalog beats one whose /Root is another dictionary, and an in-file /Root must match its generation (#2365); (7) object parsing builds at most 4,194,304 objects (every array element and dictionary value at any depth, `parser::MAX_OBJECT_NODES`, the same cap as `pdfcraft_cos`) per top-level object, an object stream reads at most 1,000,000 index entries (cos's `/N` clamp), and one load builds at most 8,388,608 objects from all of its object streams together, shared across rayon workers (a decoded stream of `0 0 0 ...` inside the 256 MiB decompression limit built ~120M objects, 10+ GB, and aborted). A lookup parses only the member it wants, so it isn't skipped behind a large member, and a load parses only the members it would add: none its cross-reference table places in another stream (stale copies) and none already loaded as an ordinary object or from an earlier stream. Members the table doesn't list at all are still parsed (a rebuilt table lists no compressed objects) and share the budget, so they can spend it before listed members of the same stream; a load expands its object streams one at a time in object-number order, a stream's members in parallel only when the budget holds all of them and otherwise in index order, so a spent budget skips the same members on every load (#5083) | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding`; (4) `inspect::tests::compressed_object_self_container_does_not_recurse`, `inspect::tests::compressed_object_mutual_containers_do_not_recurse`, `inspect::tests::object_stream_length_cycle_does_not_recurse`, `inspect::tests::compressed_object_container_chain_does_not_recurse`, `inspect::tests::compressed_length_chain_does_not_recurse`, `inspect::tests::plain_stream_length_chain_does_not_recurse`, `inspect::tests::compressed_objects_and_indirect_stream_length_still_load`, `inspect::tests::compressed_length_in_a_container_with_an_indirect_length_still_loads`; (5) `inspect::tests::object_stream_member_extents_bound_owned_strings`, `inspect::tests::object_stream_member_extents_preserve_index_order_and_whitespace`; (6) `inspect::tests::rebuilt_file_keeps_the_info_of_its_cross_reference_stream`, `inspect::tests::rebuilt_file_prefers_a_trailer_whose_root_is_the_catalog`; (7) `inspect::tests::{object_stream_members_over_the_node_cap_are_skipped, object_stream_index_entries_past_the_clamp_are_ignored, object_streams_of_one_load_share_their_node_budget, object_streams_loaded_in_parallel_share_their_node_budget, a_malformed_object_stream_member_refunds_its_reservation, a_tight_budget_builds_object_stream_members_in_index_order, a_lookup_in_an_object_stream_parses_only_the_member_it_wants}` (pdfcraft-render; `NodeBudget` and `ObjectStream::new_within` are public so these can use a small budget) |
|
||||
| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); an EI followed by a delimiter (EI%..., EI[...) ends the image like one followed by white space; only a regular character after EI skips the candidate; (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW, RunLength and ASCII85 never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice; (16) revision 5–6 (AES-256) passwords are tried in their SASLprep form (RFC 4013, then UTF-8, at most 127 bytes, as ISO 32000-2 §7.6.4.3.3 Algorithm 2.A asks and pdfcraft-crypt writes them) and then, if that differs, as given (`aes256_passwLine truncated
|
||||
| winit | 0.30.13 | Apache-2.0 | (1) on Windows 11 (build 22000 and later), `WM_DPICHANGED` applies the rect Windows suggests. It used to nudge the window onto the monitor `MonitorFromWindow` names, which during a drag is still the monitor being left; the nudge sent another `WM_DPICHANGED`, so a window dragged to a monitor with another scale factor grew and stayed on the wrong monitor at the wrong scale (#324). Backport of winit master 488c036a ([winit#4341](https://github.com/rust-windowing/winit/pull/4341)), which no 0.30 release has; Windows 10 keeps the old adjustment, as on winit master. (2) on Wayland, a seat's text input is destroyed when the seat goes away, not whenever it loses a capability: losing any capability (a touch screen or tablet unplugged, a remote-desktop session ending) destroyed it, and only an added capability recreated it, so IME stopped working until restart. Port of [winit#4747](https://github.com/rust-windowing/winit/pull/4747); (3) on Windows, an IME composition reports its cursor from `GCS_CURSORPOS` only when `WM_IME_COMPOSITION` says it is set, and at the end of the composition otherwise: the Microsoft Korean IME never sets it, so the cursor read as 0 (egui then drew no caret while composing; it now draws it after the syllable). Port of [winit#4746](https://github.com/rust-windowing/winit/pull/4746); (4) on Windows, a hidden window is not maximized until it is shown, and a hidden window shown while maximized gets one `ShowWindow(SW_MAXIMIZE)`: `SW_MAXIMIZE` shows a hidden window, so PdfCraft, which eframe keeps hidden until its first frame is drawn, appeared unpainted (white) when it restored a maximized window, and could lose its focus. Port of [winit#4587](https://github.com/rust-windowing/winit/pull/4587) (the later, focus-safe form of [winit#4575](https://github.com/rust-windowing/winit/pull/4575)); (5) on X11, when allowing or disallowing IME replaces the focused window's input context (egui does it each time a text field gains or loses focus), the new context is focused: no focus event follows, so it stayed unfocused until the window lost and regained focus. Port of [winit#4727](https://github.com/rust-windowing/winit/pull/4727); (6) on macOS, `insertText` commits through IME when a composition was started (`pending_commit`, set by `setMarkedText`) rather than when marked text is left: input methods that end a composition with `unmarkText` before `insertText` lost the text, and Apple Korean dropped the key typed after a syllable (`한` then `5` or `;`); other `insertText` calls stay `KeyboardInput`; a commit outside a key press (a candidate clicked with the mouse, dictation) clears the marked text and leaves no key to swallow, as in [winit#4748](https://github.com/rust-windowing/winit/pull/4748) (without it the next key, such as Backspace, was lost). `validAttributesForMarkedText` lists the underline and marked-clause attributes, without which some input methods don't compose. Port of [winit#4650](https://github.com/rust-windowing/winit/pull/4650), the 0.30 backport of [winit#4651](https://github.com/rust-windowing/winit/pull/4651) (merged on winit master), with the underline attribute spelled as AppKit's `NSUnderlineStyleAttributeName` (`NSUnderline`); (7) on macOS, disallowing IME with a composition in progress (focus leaving a text field) tells the input method to discard its marked text (`discardMarkedText`): it kept composing it once IME was allowed again, so the abandoned syllable came back (`하`, then `가` typed in the next field, became `학`, then `하` + `가`; Japanese `か` then `さ` became `傘`). Port of [winit#4745](https://github.com/rust-windowing/winit/pull/4745); (8) on macOS, text inserted outside a key press without a composition (the emoji picker) is reported as `Ime::Commit`; it was dropped. Port of the emoji-picker part of [winit#4749](https://github.com/rust-windowing/winit/pull/4749) (0.30 backport of [winit#4748](https://github.com/rust-windowing/winit/pull/4748)); its `selectedRange` change for dictation is left out because it switches on press-and-hold for every held key (an accent menu instead of key repeat, and the chosen accent added after the repeated letters); (9) on macOS, a key whose text was committed through IME isn't also sent as `KeyboardInput` unless AppKit forwards it as a command (Enter): Apple Korean answers Space with no syllable in progress with `setMarkedText(" ")`, `insertText(" ")`, `setMarkedText("")`, and the last call reset winit's state, so the space arrived twice. Same goal as [winit#4478](https://github.com/rust-windowing/winit/pull/4478), whose changes don't reach this call order (macOS 14); to be proposed upstream there; (10) on macOS, when the first key in a fresh app reaches Apple Korean's `insertText` as a raw compatibility jamo instead of starting a composition, that key is interpreted once more, synchronously, before it is sent as `KeyboardInput` (g k s typed ㅎㅏㄴ instead of 한); only an unmodified, Line truncated
|
||||
| winit | 0.30.13 | Apache-2.0 | (1) on Windows 11 (build 22000 and later), `WM_DPICHANGED` applies the rect Windows suggests. It used to nudge the window onto the monitor `MonitorFromWindow` names, which during a drag is still the monitor being left; the nudge sent another `WM_DPICHANGED`, so a window dragged to a monitor with another scale factor grew and stayed on the wrong monitor at the wrong scale (#324). Backport of winit master 488c036a ([winit#4341](https://github.com/rust-windowing/winit/pull/4341)), which no 0.30 release has; Windows 10 keeps the old adjustment, as on winit master. (2) on Wayland, a seat's text input is destroyed when the seat goes away, not whenever it loses a capability: losing any capability (a touch screen or tablet unplugged, a remote-desktop session ending) destroyed it, and only an added capability recreated it, so IME stopped working until restart. Port of [winit#4747](https://github.com/rust-windowing/winit/pull/4747); (3) on Windows, an IME composition reports its cursor from `GCS_CURSORPOS` only when `WM_IME_COMPOSITION` says it is set, and at the end of the composition otherwise: the Microsoft Korean IME never sets it, so the cursor read as 0 (egui then drew no caret while composing; it now draws it after the syllable). Port of [winit#4746](https://github.com/rust-windowing/winit/pull/4746); (4) on Windows, a hidden window is not maximized until it is shown, and a hidden window shown while maximized gets one `ShowWindow(SW_MAXIMIZE)`: `SW_MAXIMIZE` shows a hidden window, so PdfCraft, which eframe keeps hidden until its first frame is drawn, appeared unpainted (white) when it restored a maximized window, and could lose its focus. Port of [winit#4587](https://github.com/rust-windowing/winit/pull/4587) (the later, focus-safe form of [winit#4575](https://github.com/rust-windowing/winit/pull/4575)); (5) on X11, when allowing or disallowing IME replaces the focused window's input context (egui does it each time a text field gains or loses focus), the new context is focused: no focus event follows, so it stayed unfocused until the window lost and regained focus. Port of [winit#4727](https://github.com/rust-windowing/winit/pull/4727); (6) on macOS, `insertText` commits through IME when a composition was started (`pending_commit`, set by `setMarkedText`) rather than when marked text is left: input methods that end a composition with `unmarkText` before `insertText` lost the text, and Apple Korean dropped the key typed after a syllable (`한` then `5` or `;`); other `insertText` calls stay `KeyboardInput`; a commit outside a key press (a candidate clicked with the mouse, dictation) clears the marked text and leaves no key to swallow, as in [winit#4748](https://github.com/rust-windowing/winit/pull/4748) (without it the next key, such as Backspace, was lost). `validAttributesForMarkedText` lists the underline and marked-clause attributes, without which some input methods don't compose. Port of [winit#4650](https://github.com/rust-windowing/winit/pull/4650), the 0.30 backport of [winit#4651](https://github.com/rust-windowing/winit/pull/4651) (merged on winit master), with the underline attribute spelled as AppKit's `NSUnderlineStyleAttributeName` (`NSUnderline`); (7) on macOS, disallowing IME with a composition in progress (focus leaving a text field) tells the input method to discard its marked text (`discardMarkedText`): it kept composing it once IME was allowed again, so the abandoned syllable came back (`하`, then `가` typed in the next field, became `학`, then `하` + `가`; Japanese `か` then `さ` became `傘`). Port of [winit#4745](https://github.com/rust-windowing/winit/pull/4745); (8) on macOS, text inserted outside a key press without a composition (the emoji picker) is reported as `Ime::Commit`; it was dropped. Port of the emoji-picker part of [winit#4749](https://github.com/rust-windowing/winit/pull/4749) (0.30 backport of [winit#4748](https://github.com/rust-windowing/winit/pull/4748)); its `selectedRange` change for dictation is left out because it switches on press-and-hold for every held key (an accent menu instead of key repeat, and the chosen accent added after the repeated letters); (9) on macOS, a key whose text was committed through IME isn't also sent as `KeyboardInput` unless AppKit forwards it as a command (Enter): Apple Korean answers Space with no syllable in progress with `setMarkedText(" ")`, `insertText(" ")`, `setMarkedText("")`, and the last call reset winit's state, so the space arrived twice. Same goal as [winit#4478](https://github.com/rust-windowing/winit/pull/4478), whose changes don't reach this call order (macOS 14); to be proposed upstream there; (10) on macOS, when the first key in a fresh app reaches Apple Korean's `insertText` as a raw compatibility jamo instead of starting a composition, that key is interpreted once more, synchronously, before it is sent as `KeyboardInput` (g k s typed ㅎㅏㄴ instead of 한); only an unmodified, Line truncated
|
||||
| egui-wgpu | 0.36.2 | MIT OR Apache-2.0 | (1) `winit::surface_fit`: a window's surface is configured within the device's `max_texture_dimension_2d`, both sides shrunk by one factor that egui then draws at (`pixels_per_point × render_scale`), so the whole window is drawn into the surface (on DX12 it is stretched over the window and lines up with the pointer; wgpu's GL backend copies it unscaled into a corner); the longer side becomes exactly the limit; the depth and MSAA textures follow, and a recreated surface starts again from the window's own size. egui-wgpu configured the window's size as is, and `Surface::configure` panics beyond the limit: a window restored at another monitor's scale (opening an Outlook attachment on a mixed-DPI laptop asked an 8192-pixel device for 8600 × 3423, #577) or stretched across monitors closed PdfCraft, before its window appeared when it happened at start-up ([emilk/egui#8361](https://github.com/emilk/egui/issues/8361)). The published crate leaves out egui's licence files; `LICENSE-APACHE` and `LICENSE-MIT` are from the 0.36.2 tag; (2) `winit::catch_errors`: a new window's surface is configured inside wgpu error scopes (validation, out of memory, internal), and a failure is returned as `WgpuError::ConfigureSurface` (for the root window at start-up eframe returns it as `Error::Wgpu`, which PdfCraft retries with OpenGL); nothing is kept for the window. wgpu's default handler panicked instead, and eframe configures the root surface before the app is created, so a driver that can't configure one closed PdfCraft at launch (a 2015 Intel GPU through wgpu's GL backend timed out waiting for the GPU to go idle, `GpuWaitTimeout`, #519). Unchanged, so still a panic: an error in a later reconfigure (resize, a lost surface), a device lost during the first configure (wgpu reports it only to a callback), and a window shown at zero size (first configured on resize) | (1) `pdfcraft` `tests::a_window_larger_than_the_gpu_limit_gets_a_surface_within_it`, `tests::surface_fit_never_empties_or_overflows_a_surface`, and `tests::vendor_provenance_egui_wgpu_surface_fit_identity`, which keeps the patch in the build and in the paths that size a surface; (2) `pdfcraft` `tests::a_gpu_error_while_a_window_is_set_up_is_returned_not_a_panic` (a real device: an error inside `catch_errors` is returned, not a panic) and `tests::vendor_provenance_egui_wgpu_catch_errors_identity`, which keeps it around `add_surface`'s configure |
|
||||
| vello_common | 0.0.8 | Apache-2.0 OR MIT | (1) `clip::intersect` (the clip step every clipped path passes through) starts its row walk at the first row both paths have strips in, not the earlier of the two first rows. The walk visited every row from the top of the clip for each path (on the A1 sample's full-page canvas, about half its strip rows per stroke), and rows where one path has no strips produce no output, so the strips are unchanged (vello_common 0.1 starts at the later row too). Its cost grew with the page, and a full-page render of the A1 sample was about 30% faster; the output is byte-identical; (2) `StripStorage::room_for_path{,_within}`: whether one more path's coverage (at most the whole surface, counted twice) still fits below 2^31 values, the most a strip's packed alpha index reaches (`Strip::new` asserts it), or below a smaller limit; (4) `flatten::stroke`: when kurbo 0.13.1's stroker returns an outline containing NaN, which `fill` would drop whole, the path is stroked again from a copy (`robust_for_stroking`, one element out per element in) in which each curve whose control points lie within the stroke tolerance of its chord is a line (the #4907 fix, a nearly straight cubic given a NaN join, kurbo issues #617 and #519; its row here was lost in a merge and is restored with this entry) and each cubic whose second control point is its end point, as `y` builds (ISO 32000-2 §8.5.2.1 Table 58), has that control point moved the tolerance towards its first (`open_zero_end_handle`; the curve moves by at most 4/9 of the tolerance): kurbo's cusp search on such a curve's offset can stop on the end point, where the derivative is zero, and normalising it gives NaN, so at 16, 32 and 63 pt a two-curve `y` path drew nothing and a file in the PDFBox tracker lost its 32 pt "XX" outline. Only an exact zero triggers it (none of 192,000 random strokes with a handle 1e-9 long, nor of 256,000 `v` strokes, came back with NaN; 1,073 of 192,000 random `y`/`v` strokes at 1–64 pt did before and none after). A finite outline takes the old path unchanged | (1) `clip::tests::intersect_walks_only_rows_both_paths_have_strips` counts the rows the walk visits (`cargo test --manifest-path vendor/vello_common/Cargo.toml`) and fails without the patch; the render crate's pixel tests run through the patched crate; (2) `strip_generator::pdfcraft_tests::strips_have_room_until_a_surface_short_of_the_limit`; (4) `flatten::tests::a_tiny_degenerate_cubic_does_not_drop_the_stroke` and the render crate's `stroke_degenerate_cubic` fail without the near-line replacement, `flatten::tests::a_wide_stroke_of_a_curve_with_a_zero_end_tangent_is_drawn` (widths 1–64, every join and cap, `y` and the mirrored `v`) and the render crate's `stroke_zero_end_tangent` fail without the moved control point; `a_finite_outline_is_stroked_as_before` and `a_path_with_nan_is_still_dropped` pass either way |
|
||||
| vello_cpu | 0.0.8 | Apache-2.0 OR MIT | (1) the single-threaded dispatcher leaves out a fill, stroke, fast rectangle or layer clip once the scene has no room for one more path's coverage (`StripStorage::room_for_path_within`, vello_common patch 2), records it (`RenderContext::coverage_full`, cleared by `reset`) and can be kept to fewer values (`RenderContext::set_max_coverage`, kept across `reset`). Every path's coverage stays in one buffer until the scene is rasterized, so a page that painted one form 2^22 times over (PDFBOX-5415) grew it past 2^31 values at about 7 GB and panicked in `Strip::new` (`alpha_idx` too large); it now renders what fitted. The multi-threaded dispatcher is unchanged (PdfCraft renders single-threaded); the backport of linebender/vello#2000 is recorded under the KenM76 integration patches (#5199) | (1) `raster::tests::coverage_budget::a_page_past_its_coverage_leaves_the_rest_out_and_says_so` renders a page that fills a circle 2^10 times with the rasterizer kept to 200,000 values, and fails without the dispatcher's check; `strokes_past_the_coverage_are_left_out`, `fast_rectangles_past_the_coverage_are_left_out` and `layer_clips_past_the_coverage_are_left_out` (the last through `RenderContext` directly, as hayro pushes no clipped layers, with the first clip kept below the limit and its pixels checked) each fail without that path's check, and `a_layer_clip_past_the_coverage_is_itself_left_out` fails when the clip is generated without room; vello_cpu's own tests need upstream assets that are not vendored |
|
||||
|
||||
+2
-2
@@ -28,10 +28,10 @@ use crate::event_loop::{ActiveEventLoop, AsyncRequestSerial};
|
||||
use crate::window::{ActivationToken, Window, WindowAttributes};
|
||||
|
||||
/// The variable which is used mostly on X11.
|
||||
const X11_VAR: &str = "DESKTOP_STARTUP_ID";
|
||||
pub(crate) const X11_VAR: &str = "DESKTOP_STARTUP_ID";
|
||||
|
||||
/// The variable which is used mostly on Wayland.
|
||||
const WAYLAND_VAR: &str = "XDG_ACTIVATION_TOKEN";
|
||||
pub(crate) const WAYLAND_VAR: &str = "XDG_ACTIVATION_TOKEN";
|
||||
|
||||
pub trait EventLoopExtStartupNotify {
|
||||
/// Read the token from the environment.
|
||||
|
||||
+14
-3
@@ -25,6 +25,7 @@ use crate::event_loop::{
|
||||
use crate::icon::Icon;
|
||||
use crate::keyboard::Key;
|
||||
use crate::platform::pump_events::PumpStatus;
|
||||
use crate::platform::startup_notify;
|
||||
#[cfg(x11_platform)]
|
||||
use crate::platform::x11::{WindowType as XWindowType, XlibErrorHook};
|
||||
use crate::window::{
|
||||
@@ -38,6 +39,7 @@ pub(crate) use crate::icon::RgbaIcon as PlatformIcon;
|
||||
pub(crate) use crate::platform_impl::Fullscreen;
|
||||
|
||||
pub(crate) mod common;
|
||||
mod startup_token;
|
||||
#[cfg(wayland_platform)]
|
||||
pub(crate) mod wayland;
|
||||
#[cfg(x11_platform)]
|
||||
@@ -290,16 +292,25 @@ impl Window {
|
||||
#[inline]
|
||||
pub(crate) fn new(
|
||||
window_target: &ActiveEventLoop,
|
||||
attribs: WindowAttributes,
|
||||
mut attribs: WindowAttributes,
|
||||
) -> Result<Self, RootOsError> {
|
||||
let given = attribs.platform_specific.activation_token.take();
|
||||
match *window_target {
|
||||
#[cfg(wayland_platform)]
|
||||
ActiveEventLoop::Wayland(ref window_target) => {
|
||||
wayland::Window::new(window_target, attribs).map(Window::Wayland)
|
||||
let (token, reservation) = startup_token::for_new_window(given, startup_notify::WAYLAND_VAR);
|
||||
attribs.platform_specific.activation_token = token;
|
||||
let window = wayland::Window::new(window_target, attribs).map(Window::Wayland)?;
|
||||
reservation.commit();
|
||||
Ok(window)
|
||||
},
|
||||
#[cfg(x11_platform)]
|
||||
ActiveEventLoop::X(ref window_target) => {
|
||||
x11::Window::new(window_target, attribs).map(Window::X)
|
||||
let (token, reservation) = startup_token::for_new_window(given, startup_notify::X11_VAR);
|
||||
attribs.platform_specific.activation_token = token;
|
||||
let window = x11::Window::new(window_target, attribs).map(Window::X)?;
|
||||
reservation.commit();
|
||||
Ok(window)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
//! The launcher's activation token for the first window (PdfCraft patch).
|
||||
//!
|
||||
//! A launcher with `StartupNotify=true` passes an activation token in the environment
|
||||
//! (`XDG_ACTIVATION_TOKEN` on Wayland, `DESKTOP_STARTUP_ID` on X11) and shows a busy cursor
|
||||
//! until a window hands it back. winit hands back only a token given through
|
||||
//! `WindowAttributesExtStartupNotify::with_activation_token`, and eframe never gives one, so
|
||||
//! GNOME kept the busy cursor until its 15-second timeout and the window opened without focus.
|
||||
//!
|
||||
//! The first window the process creates without a token now takes the one in the environment.
|
||||
//! Later windows never do: the token is spent once a window has handed it back, or once the
|
||||
//! first window exists. A window that fails before handing it back releases it, so a retry
|
||||
//! still clears the busy cursor. The variable is left in the environment, unlike
|
||||
//! `reset_activation_token_env`, because changing the environment while other threads may read
|
||||
//! it is unsound, and an application can start threads before its first window.
|
||||
|
||||
use std::sync::atomic::{AtomicU8, Ordering};
|
||||
|
||||
use crate::window::ActivationToken;
|
||||
|
||||
/// Longer tokens are ignored. Launchers make tokens of a few dozen bytes; on X11 the token is
|
||||
/// written to a window property and sent to the window manager, and an oversized one would
|
||||
/// fail window creation.
|
||||
const MAX_TOKEN_LEN: usize = 1024;
|
||||
|
||||
/// No window has claimed the launcher's token.
|
||||
const FREE: u8 = 0;
|
||||
/// A window being created holds it.
|
||||
const RESERVED: u8 = 1;
|
||||
/// A window has handed it back, or the first window exists.
|
||||
const SPENT: u8 = 2;
|
||||
|
||||
static STATE: AtomicU8 = AtomicU8::new(FREE);
|
||||
|
||||
/// The launcher's token held by a window being created. Dropping it before it is committed or
|
||||
/// handed back releases the token for the next window.
|
||||
pub(crate) struct Reservation<'a> {
|
||||
state: &'a AtomicU8,
|
||||
held: bool,
|
||||
}
|
||||
|
||||
impl Reservation<'_> {
|
||||
/// The window was created: later windows don't take the launcher's token.
|
||||
pub(crate) fn commit(self) {
|
||||
if self.held {
|
||||
self.state.store(SPENT, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Reservation<'_> {
|
||||
fn drop(&mut self) {
|
||||
if self.held {
|
||||
// Fails, leaving the token spent, once it was committed or handed back.
|
||||
let _ = self.state.compare_exchange(RESERVED, FREE, Ordering::Relaxed, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The token for a window being created: `given` if there is one, else the environment's
|
||||
/// value of `var` for the process's first window, with the reservation the caller commits
|
||||
/// once the window exists.
|
||||
pub(crate) fn for_new_window(given: Option<ActivationToken>, var: &str) -> (Option<ActivationToken>, Reservation<'static>) {
|
||||
choose(given, &STATE, || std::env::var(var).ok())
|
||||
}
|
||||
|
||||
/// A backend is handing a window's token back to the launcher or compositor: from here on the
|
||||
/// launcher's token is spent even if creating the window fails.
|
||||
pub(crate) fn handing_back() {
|
||||
hand_back(&STATE);
|
||||
}
|
||||
|
||||
fn hand_back(state: &AtomicU8) {
|
||||
// Windows are created one at a time on the event loop's thread, so a reservation, if any,
|
||||
// is this window's.
|
||||
let _ = state.compare_exchange(RESERVED, SPENT, Ordering::Relaxed, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
fn choose(given: Option<ActivationToken>, state: &AtomicU8, read: impl FnOnce() -> Option<String>) -> (Option<ActivationToken>, Reservation<'_>) {
|
||||
// The first window holds the launcher's token, whether or not it was given one.
|
||||
let held = state.compare_exchange(FREE, RESERVED, Ordering::Relaxed, Ordering::Relaxed).is_ok();
|
||||
let reservation = Reservation { state, held };
|
||||
if given.is_some() || !held {
|
||||
return (given, reservation);
|
||||
}
|
||||
let token = read().filter(|token| !token.is_empty() && token.len() <= MAX_TOKEN_LEN).map(ActivationToken::from_raw);
|
||||
(token, reservation)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn token(raw: &str) -> Option<ActivationToken> {
|
||||
Some(ActivationToken::from_raw(raw.to_owned()))
|
||||
}
|
||||
|
||||
fn created(state: &AtomicU8, given: Option<ActivationToken>, env: &str) -> Option<ActivationToken> {
|
||||
let (token, reservation) = choose(given, state, || Some(env.to_owned()));
|
||||
reservation.commit();
|
||||
token
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_window_takes_the_launchers_token() {
|
||||
let state = AtomicU8::new(FREE);
|
||||
assert_eq!(created(&state, None, "gnome-shell/PdfCraft/1234"), token("gnome-shell/PdfCraft/1234"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_window_does_not_reuse_the_spent_token() {
|
||||
let state = AtomicU8::new(FREE);
|
||||
assert!(created(&state, None, "t").is_some());
|
||||
assert_eq!(created(&state, None, "t"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_given_token_wins_and_still_spends_the_launchers() {
|
||||
let state = AtomicU8::new(FREE);
|
||||
assert_eq!(created(&state, token("mine"), "env"), token("mine"));
|
||||
assert_eq!(created(&state, None, "env"), None);
|
||||
assert_eq!(created(&state, token("again"), "env"), token("again"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_that_fails_before_handing_the_token_back_releases_it() {
|
||||
let state = AtomicU8::new(FREE);
|
||||
let (first, failed) = choose(None, &state, || Some("t".into()));
|
||||
assert_eq!(first, token("t"));
|
||||
drop(failed);
|
||||
assert_eq!(created(&state, None, "t"), token("t"));
|
||||
assert_eq!(created(&state, None, "t"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_given_a_token_that_fails_early_releases_the_launchers() {
|
||||
let state = AtomicU8::new(FREE);
|
||||
drop(choose(token("mine"), &state, || Some("env".into())));
|
||||
assert_eq!(created(&state, None, "env"), token("env"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_that_fails_after_handing_the_token_back_spends_it() {
|
||||
let state = AtomicU8::new(FREE);
|
||||
let (first, failed) = choose(None, &state, || Some("t".into()));
|
||||
assert_eq!(first, token("t"));
|
||||
hand_back(&state);
|
||||
drop(failed);
|
||||
assert_eq!(created(&state, None, "t"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_created_while_the_token_is_held_does_not_take_or_release_it() {
|
||||
let state = AtomicU8::new(FREE);
|
||||
let (first, holder) = choose(None, &state, || Some("t".into()));
|
||||
assert_eq!(first, token("t"));
|
||||
let (other, reservation) = choose(None, &state, || Some("t".into()));
|
||||
assert_eq!(other, None);
|
||||
drop(reservation);
|
||||
assert_eq!(state.load(Ordering::Relaxed), RESERVED);
|
||||
drop(holder);
|
||||
assert_eq!(created(&state, None, "t"), token("t"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_empty_or_oversized_token_is_ignored() {
|
||||
assert_eq!(created(&AtomicU8::new(FREE), None, ""), None);
|
||||
assert_eq!(choose(None, &AtomicU8::new(FREE), || None).0, None);
|
||||
let long = "x".repeat(MAX_TOKEN_LEN + 1);
|
||||
assert_eq!(created(&AtomicU8::new(FREE), None, &long), None);
|
||||
let limit = "x".repeat(MAX_TOKEN_LEN);
|
||||
assert!(created(&AtomicU8::new(FREE), None, &limit).is_some());
|
||||
}
|
||||
}
|
||||
@@ -176,6 +176,7 @@ impl Window {
|
||||
if let (Some(xdg_activation), Some(token)) =
|
||||
(xdg_activation.as_ref(), attributes.platform_specific.activation_token)
|
||||
{
|
||||
super::super::startup_token::handing_back();
|
||||
xdg_activation.activate(token.token, &surface);
|
||||
}
|
||||
|
||||
|
||||
@@ -558,6 +558,7 @@ impl UnownedWindow {
|
||||
|
||||
// Remove the startup notification if we have one.
|
||||
if let Some(startup) = window_attrs.platform_specific.activation_token.as_ref() {
|
||||
super::super::startup_token::handing_back();
|
||||
leap!(xconn.remove_activation_token(xwindow, &startup.token));
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user