Files
pdfcraft/crates/fonts/src/lib.rs
T
9f04acccef M10: OCR engines, confidence, preprocessing and a review workflow (#977)
* M10.20: plan Unicode text for OCR output in Type3 faces (fonts, edit)

OCR output used to flatten every character beyond WinAnsi to a silent `?`. This
adds the two pieces that let the OCR layers write the recognized words as they
are; the OCR code that uses them follows in M10.21.

pdfcraft-fonts
- `TextPlan::for_words` maps each word to the standard Helvetica when WinAnsi
  covers it, else to Type3 fonts drawn from the craft-fonts faces (the Japanese
  document face first, then the rest of the build input). Characters no face
  has a glyph for are counted (`missing`), never dropped silently. At most 240
  characters per font and 2400 per plan, so one hostile word cannot balloon.
- Which face has which character is asked once per (face, character) for a plan,
  not once per word.
- `face_has`, `craft_glyph`, `win_ansi_char`, `fits_win_ansi` are public for it.

pdfcraft-edit
- `add_type3_fonts` / `stamp_with_fonts` register a plan's fonts on a page under
  a free `PCOcr`, `PCOcr1`, ... name, build each font once and share the object
  with later pages. A shared face is registered under a free name on a later
  page that already has a font of the name it was given first, instead of
  replacing that page's own font.
- The fonts carry real advances and a ToUnicode CMap, so extraction reads the
  text back.

pdfcraft-redact
- A test shows a hand-built Type3 text layer (the shape the OCR output writes) is
  redacted like any other text and the verifier passes.

Tests: pdfcraft-fonts 62 passed, pdfcraft-edit 129 passed, pdfcraft-redact 33
passed; clippy -D warnings clean on the three crates. The name-reuse and the
redaction tests build their fonts by hand, so they run without the craft-fonts
build input; the tests that plan real faces skip without it and were not run in
this commit's own check.

* M12: give the hostile-XFA open test more room on a loaded machine

The test opens a form whose calculate script sets a value 50 000 times, against
the one-second budget of an unasked script and a five-second wall-clock bound
on the open. Both sit close to what a machine running several suites at once
can take, so the test can fail without anything being wrong.

It now runs 20 000 iterations (the total is 19999) and allows 30 seconds, which
still fails for a script that hangs or is not capped. Test-only; unrelated to
the OCR work in this series, so it is a commit of its own.

Tests: both hostile_xfa tests in pdfcraft-engine pass.

* M10.21: pluggable OCR engines, preprocessing, review sessions and the OCR tools (ocr, engine, create, automation)

Scan & OCR gets a second engine, optional raster clean-up, a review step before
anything is applied, editable output and a batch mode, headlessly first: the
interface for them follows in M10.22.

pdfcraft-ocr
- A `Recognizer` trait with two engines: the built-in ocrs (moved out of lib.rs)
  and the installed tesseract program, run as a fenced external process: fixed
  argv, allow-listed language codes, a private temp directory (mode 0700 on
  Unix), 120 s timeout, 64 MiB output cap, 50 000-word reading cap. A location
  from PDFCRAFT_TESSERACT is validated (absolute, existing, executable) and an
  invalid one fails closed instead of falling back to the PATH. `--list-langs`
  and `--version` are read from stdout or, for older versions, stderr.
- Strategies: PrimaryOnly, ConfidenceWeighted (the second engine joins when the
  first reading's mean is under 70 or unknown) and a ROVER merge (higher
  confidence wins per word; against an ocrs word of unknown confidence a
  tesseract word wins only at 70 or more; capped at 100 M comparisons; a failing
  partner degrades to the primary with a note).
- Preprocessing: opt-in auto-rotate, deskew, denoise and binarize on the RGBA
  raster, each with an exact inverse so word boxes map back to the scan. The
  300 dpi normalization the steps are calibrated for runs only when a step is
  on: with every step off the render is read as rendered, as before. (Enlarging
  a 72 dpi render 4x on its own made the models read "due: €250" as "ue: ?250".)
  `OcrImage` is validated by construction (side and 64 MP area caps, checked
  before any buffer is allocated, including by the resize).
- Confidence bands (High >= 90, Medium 70-89, Low < 70) drive review.

pdfcraft-engine, pdfcraft-create
- `OcrSettings` gains engine, strategy, the four steps, output mode, region, the
  skip flags and the low-confidence threshold; Automatic reads confidence
  weighted unless a strategy is chosen.
- A recognition is a session: the document guard refuses a stale result with its
  reason, pages can be applied one at a time (the guard is taken again after each
  applied page), and applying is one undoable step. A per-language dictionary
  (a plain-text file: words added from any document stay on disk after it closes).
- Output is searchable (an invisible layer) or a NEW editable document of visible
  text at the recognized boxes (`create::from_contents`); words beyond WinAnsi use
  the Type3 faces of M10.20 in both, with the shared plan across pages.
- Engine discovery never blocks the interface: results are cached, a stale
  answer is shown while a background probe retries, and the models search and
  `--version` are cached. Batch: pages or files that already have text are
  skipped unless forced, and inputs sharing a file name are found up front.

pdfcraft-automation
- ocr_recognize (engine, strategy, steps, region, output mode), ocr_words (with a
  retained review handle), ocr_review_apply, ocr_dictionary, ocr_status and
  ocr_recognize_files. The editable `out` must be a new file inside --root and is
  refused for a searchable run (it used to be ignored), two batch inputs of one
  file name are refused before anything is read, and the batch folder is checked
  for existing outputs.

pdfcraft-ui-egui
- Only what the new API needs: the Recognize Text dialog reads with
  `recognizers(&settings)`. `ocr.correct` is registered with its label in every
  catalog; the screen itself is M10.22.

Tests: pdfcraft-ocr 78 passed; pdfcraft-create passed; pdfcraft-engine and
pdfcraft-automation 450 passed and 1 failed (the automation lib 17, automation.rs
157, hostile_args 2 among them); pdfcraft-ui-egui lib + ocr + control tests 391
passed; clippy -D warnings clean on the five crates. The one failure is in a
test this commit does not change:
recognize_text_makes_a_scanned_page_searchable fails where the models are
installed (they read "quick" as "auick" at that render size); the roadmap on main
already records it. The real tesseract binary ran in
tesseract::tests::recognize_runs_the_installed_binary (tesseract 5.4.0, PATH).

* M10.22: OCR Verify screen, the Recognize Text options and the interface catalogs (ui-egui)

Scan & OCR ▸ Correct recognized text: a full-window screen where a recognition
is reviewed before anything is applied, plus the dialog and batch options for
the engines of M10.21.

OCR Verify screen
- Four panes: the page list, the source page with confidence-coloured word boxes
  (click to select, drag to draw a region), the recognized text, and a zoom plus
  word inspector. Corrections commit on Enter (an empty commit removes the word),
  Remove/Restore, "+ Dictionary" (a per-language file in the preferences folder,
  so a word added from a document stays on disk after it closes), per-word and
  per-page Verified, F8 / Shift+F8 walk the low-confidence words, Ctrl+T marks the
  page reviewed, Ctrl+Tab moves the pane focus, and review edits undo within the
  panel.
- Re-OCR of the whole page or a drawn region. A region re-read moves the review
  marks of the words it keeps to their new positions and selects the first new
  word; a whole-page re-read clears that page's marks (and the undo brings them
  back). The region outline is scaled onto the pane, not mapped through user
  space again, so it is right on rotated and cropped pages.
- Accept / Reject per page or whole. Pages accepted one at a time each apply once
  (the document guard is taken again after each applied page; an edit made
  elsewhere in between is still refused with its reason), and Accept in
  searchable mode is one undoable step. Editable mode writes a NEW
  `<name>_ocr.pdf` through a save dialog and never the source. A real Cancel
  keeps the pages already read.
- The engine and strategy menus disable a choice that cannot run and say why;
  the check never waits on a process (a background probe fills a cache), and
  choosing Automatic moves "Primary only" to Confidence weighted.

Recognize Text dialog and batch
- Engine, strategy, the four clean-up steps and the skip flags are remembered with
  the other choices (a saved Automatic without a strategy reads confidence
  weighted). The batch refuses two inputs of one file name and existing outputs
  before reading anything, notes low-confidence pages at the settings' threshold,
  and its toast has a Cancel (the file in flight finishes).

Catalogs and attribution
- The 90 new interface strings are in all 21 catalogs (the Lithuanian ones were
  written without native review, and the Bulgarian ones avoid U+045D, which the
  bundled monospace face lacks). ATTRIBUTION.toml carries the new hashes, a
  note on the Lithuanian entries and the README screenshot; ATTRIBUTION.md is
  regenerated.
- README: a screenshot of the Verify screen, taken with
  `cargo xtask screenshots` from a synthetic scan (`shot --ocr-verify on`) built
  from allowed assets; the page reads it with the real engines.

Tests: pdfcraft-ui-egui lib 373 passed (1 ignored: the Windows hinting
measurement probe), tests ocr 6, control 46, fonts 9; clippy -D warnings clean on
the engine, ui-egui, pdfcraft and xtask packages; `cargo xtask assets` ok. The
review state machine has unit tests for every fix above; each was seen failing
with its fix reverted.

* M10.23: parity entries, roadmap and localization notes for the OCR workflow

Records what M10.20-M10.22 ship, and what they do not.

parity/acrobat-features.toml
- Status changes against main: ocr.rotation-detection and ocr.deskew planned ->
  shipped (the opt-in steps of M10.21, with their tests); ocr.correct-recognized-
  text and ocr.ocr-engines planned -> partial. Other Area I entries get their
  evidence and notes brought up to date.
- ocr.correct-recognized-text: the evidence includes the one-page-at-a-time accept
  and the region re-read tests; the notes say what the headless tools cover
  (ocr_words with a retained review, ocr_review_apply through the same stale-
  document guard, ocr_dictionary) and what is still UI-only (suggestions,
  per-word Verified marks, region re-reads).
- ocr.ocr-engines stays partial rather than shipped: part of its evidence is
  conditional (the real-binary test runs only where tesseract is installed and
  skips elsewhere, and the process-level tests are Unix-only). It cites the tests
  that always run (location validation and the fail-closed rule, --list-langs
  parsing from stdout or stderr, the merge rules, the default strategy) and says
  which part is not proven everywhere.
- `cargo xtask parity`: area I 32.7% -> 44.2% weighted (5 -> 7 shipped, 7 -> 9
  partial); overall 52.8% -> 53.0% shipped and 58.2% -> 58.5% weighted.

ROADMAP.md
- One progress-log entry (2026-10-13, newest first) and the banner line. It says
  the catalogs are 21 with the Lithuanian additions not natively reviewed, that
  the end-to-end redaction test of the Type3 layer needs the craft-fonts build
  input, and that recognize_text_makes_a_scanned_page_searchable still fails where
  the models are installed, as main's log already records.

docs/localization.md, docs/localization-parity.md
- The Lithuanian entry count (2,578 -> 2,668) and the counts of the other
  catalogs that carry entry counts are re-measured with the 90 new entries; the
  Lithuanian OCR entries are marked as not natively reviewed.

Checked: `cargo xtask parity` (numbers above, evidence tests exist) and
`cargo xtask assets` pass on this tree.

* M10.24: ocr: apply a late result only to the document it was read from

The Recognize Text dialog closes on Go, so the document can be edited, or have
text redacted, while a long run is still reading. The result was applied
without the stale check the tools and the Verify screen use, so words read
before a redaction could be written back as invisible text. The run now keeps
its guard and applies through the checked path.

Accept with the editable output in the Verify screen had the same gap (Exit
keeps the review open): it now refuses when the document changed since the
review started.

Both new tests fail with their guard switched off.

* M10.25: ocr: ocr_dictionary takes dictionary file names only

Updating sorts, lower-cases and rewrites the file it is given, so pointed at
.env or a README it would corrupt it. The tool now accepts only
ocr-dictionary-<language>.txt style names, for reading as well as writing.

The size-limit test used a file name the rule now refuses first, so it renamed
its fixture to keep testing the size limit. The new test fails with the rule
switched off.

* M10.26: pt-BR: keep (s) on the word counts and say mecanismo for engine

Two review fixes from a native speaker: the two word(s) lines had lost their
(s), so a count of 1 read as 1 palavras, and engine was translated both as
motor and mecanismo. Mecanismo is the Brazilian word for a software engine and
two lines already used it, so the other six now match.

* M10: fit the rebased OCR workflow to current main's structure

* Fix OCR workflow issues from the review

Honor the Recognize dialog's editable-output choice: its result opens in
the review screen (whose Accept writes the editable document) instead of
an invisible layer. Make page acceptance idempotent: a second Accept
entire page never appends the OCR layer twice and keeps later
corrections. Move page and region re-OCR onto a worker thread with a
status line and a cancel that discards the reading. Skip the Tesseract
probe for jobs that name their engines. Bound Tesseract's stderr while
the child runs, not only after it exits. Surface the editable output's
substitution notes in the tools' and the run's results.

Also repair the OCR batch tool against the current structure: inputs are
held to the read root again, and a batch whose inputs share an output
name is refused before the output folder is created, compared the way
the default filesystem compares names; and the editable writer test's
word stays inside the fixture's pages.

* Apply pre-review fixes to the OCR workflow

Hold the automation OCR tools to the document's copying permission, as
the other text tools are: the recognized text is left out of the
results when copying is forbidden, and the paths that carry the words
out of the document (the editable output, the review word list) are
refused. Mark the ocr_dictionary tool as overwriting its path. Close
the searchable layer's graphics state around its invisible text so the
rendering mode cannot leak into later content. Read the OCR user
dictionary folder from the portable data folder in portable mode, like
the recovery store does. Resolve the attribution manifest's leftover
conflict markers and regenerate the generated attribution. Describe the
review flow, the searchable layer's Type3 fonts and the parity evidence
references accurately, and drop an undeclared copy of the recovery
module.

* OCR: reject readings that exceed the word limit

Assisted-by: OpenAI Codex

* OCR: new documents go through the page tree builder main added

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* OCR: review notes and lints

The editable output refuses a file created during recognition. ocr_words takes
skip_text_pages and force_ocr. Automatic OCR checks the engine it will use. The
stderr test stays below the kill cap, and a failed --ocr-verify shot exits with
an error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* OCR: restore the Verify screenshot attribution, follow the moved constants

The merge dropped the screenshot row with the translation rows. The model
filename constants live in ocrs.rs now, so the license check reads them there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Attribution: the Verify screenshot entry goes after the header comment

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Attribution: the screenshot row in the table follows the manifest order

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: eliets2 <287273517+eliets2@users.noreply.github.com>
Co-authored-by: FredApps <FredApps@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 23:39:55 +01:00

492 lines
23 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! pdfcraft-fonts — font metrics and encodings for generated appearances (L2).
//!
//! Standard-14 advance widths are exact (`Std14`, ISO 32000-2 Annex D). What remains approximate
//! is everything that needs a font *program*: this crate reads font dictionaries, never embedded
//! programs, so it has no glyph outlines for document fonts and cannot subset or re-embed. That
//! is phase F 4.2 in docs/plan/execution-plan.md.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(test)]
mod cjk_scripts;
mod craft;
pub mod embedding;
mod encodings;
pub mod fallback;
pub mod pdf;
pub mod plan;
mod script;
mod shaping;
pub mod source_shaping;
mod std14;
mod std14_metrics;
pub use craft::{
CRAFT_FONTS, CraftFont, SHIPPORI_MINCHO, document_arabic_font, document_devanagari_font, document_hebrew_font, document_japanese_font,
document_japanese_font_for_style, document_japanese_fonts_for_style, document_latin_fonts, document_thai_font, ui_arabic_fonts, ui_chinese_fonts,
ui_cjk_fonts, ui_devanagari_fonts, ui_hebrew_fonts, ui_japanese_fonts, ui_telugu_fonts, ui_thai_fonts,
};
pub use plan::{MAX_PLAN_GLYPHS, MAX_TYPE3_GLYPHS, PlannedType3, TextPlan};
pub use script::{
GlyphError, GlyphOutline, INTER_REGULAR, MAX_SIGNATURE_CHARS, ScriptOutline, craft_glyph, face_has, japanese_glyph, japanese_glyph_from,
script_missing, script_outline,
};
pub use shaping::{
ShapedCluster, ShapedScript, arabic_glyph, arabic_has, hebrew_has, shape_arabic, shape_hebrew, shape_thai, shaped_glyph, thai_has,
};
pub use std14::Std14;
/// Advance of `s` in Helvetica at `size` points, using the exact standard-14 metrics.
///
/// Kept as a free function because generated appearances overwhelmingly use Helvetica; reach for
/// [`Std14`] directly for any other face, and never for a scaled approximation of this one.
pub fn helvetica_width(s: &str, size: f64) -> f64 {
Std14::Helvetica.text_width(s, size)
}
/// Approximate advance of `s` at `size` points in a CJK font: full-width characters take one
/// em, half-width forms half of one, and everything else is measured as Helvetica.
pub fn cjk_width(s: &str, size: f64) -> f64 {
let mut buf = [0u8; 4];
s.chars()
.map(|c| match c {
'\u{ff61}'..='\u{ffdc}' | '\u{ffe8}'..='\u{ffee}' => size * 0.5,
_ if is_wide(c) => size,
_ => helvetica_width(c.encode_utf8(&mut buf), size),
})
.sum()
}
/// Approximate advance of `s` in Inter Regular at `size` points.
pub fn inter_width(s: &str, size: f64) -> f64 {
use skrifa::MetadataProvider as _;
let Ok(font) = skrifa::FontRef::new(INTER_REGULAR) else { return helvetica_width(s, size) };
let loc = skrifa::instance::LocationRef::default();
let upem = font.metrics(skrifa::instance::Size::unscaled(), loc).units_per_em.max(1) as f64;
let scale = size / upem;
let charmap = font.charmap();
let advances = font.glyph_metrics(skrifa::instance::Size::unscaled(), loc);
s.chars().map(|c| charmap.map(c).and_then(|gid| advances.advance_width(gid)).unwrap_or(0.0) as f64 * scale).sum()
}
/// East Asian wide and full-width characters (Unicode UAX #11 W and F, by block).
fn is_wide(c: char) -> bool {
matches!(c,
'\u{1100}'..='\u{115f}' // Hangul Jamo initials
| '\u{2e80}'..='\u{303e}' // CJK radicals, Kangxi, ideographic description, CJK symbols
| '\u{3041}'..='\u{33ff}' // kana, Bopomofo, Hangul compatibility, Kanbun, CJK compatibility
| '\u{3400}'..='\u{4dbf}' // CJK extension A
| '\u{4e00}'..='\u{9fff}' // CJK unified ideographs
| '\u{a000}'..='\u{a4cf}' // Yi
| '\u{ac00}'..='\u{d7a3}' // Hangul syllables
| '\u{f900}'..='\u{faff}' // CJK compatibility ideographs
| '\u{fe30}'..='\u{fe4f}' // CJK compatibility forms
| '\u{ff00}'..='\u{ff60}' // full-width forms
| '\u{ffe0}'..='\u{ffe6}'
| '\u{20000}'..='\u{3fffd}' // supplementary ideographic planes
)
}
/// Greedy line breaking within `width` points (paragraphs split on line breaks, where CRLF counts as one; words longer
/// than a line are broken by character).
pub fn wrap(text: &str, size: f64, width: f64) -> Vec<String> {
wrap_with(text, size, width, helvetica_width)
}
/// [`wrap`], measuring with `measure` (for example [`cjk_width`]).
///
/// A line measures as the sum of its words, the spaces between them and the characters of a broken
/// word, each measured once, so the work stays linear in `text` however much fits on a line.
pub fn wrap_with(text: &str, size: f64, width: f64, measure: impl Fn(&str, f64) -> f64) -> Vec<String> {
let mut lines = Vec::new();
let space = measure(" ", size);
let mut buf = [0u8; 4];
// A CRLF pair is one break, a lone CR or LF is one break each.
for para in text.replace("\r\n", "\n").split(['\n', '\r']) {
let mut line = String::new();
let mut line_width = 0.0;
// No word is on the line yet; an empty word (a leading space) still starts it.
let mut fresh = true;
for word in para.split(' ') {
let word_width = measure(word, size);
let candidate = if fresh { word_width } else { line_width + space + word_width };
if candidate <= width {
if !fresh {
line.push(' ');
}
line.push_str(word);
line_width = candidate;
fresh = false;
continue;
}
// Indentation alone is not a line: drop it before an over-long word.
if line.trim().is_empty() {
line.clear();
} else {
lines.push(std::mem::take(&mut line));
}
line_width = 0.0;
for ch in word.chars() {
let ch_width = measure(ch.encode_utf8(&mut buf), size);
if !line.is_empty() && line_width + ch_width > width {
lines.push(std::mem::take(&mut line));
line_width = 0.0;
}
line.push(ch);
line_width += ch_width;
}
fresh = line.is_empty();
}
lines.push(line);
}
lines
}
/// The WinAnsiEncoding (ISO 32000-2 Annex D) code for `c`, if the encoding has one.
///
/// Codes 0x80–0x9F come from the same table the text extractor decodes with, so encoding and
/// decoding agree (Š š Ž ž Œ œ Ÿ ƒ † ‡ ˆ ˜ ‰ ‹ › as well as quotes, dashes, € and ™).
pub fn win_ansi_byte(c: char) -> Option<u8> {
match c {
'\u{20}'..='\u{7e}' | '\u{a0}'..='\u{ff}' => u8::try_from(u32::from(c)).ok(),
_ => {
let high = encodings::WIN_ANSI.get(0x80..0xa0)?;
let i = high.iter().position(|&u| u != 0 && u == u32::from(c))?;
u8::try_from(0x80 + i).ok()
}
}
}
/// Encode text in WinAnsiEncoding (ISO 32000-2 Annex D); tabs become spaces and unmappable
/// characters become `?`.
pub fn win_ansi(s: &str) -> Vec<u8> {
s.chars().map(|c| if c == '\t' { b' ' } else { win_ansi_byte(c).unwrap_or(b'?') }).collect()
}
/// The character encoding of a predefined Unicode CMap (`UniJIS-UTF16-H`, `UniGB-UCS2-H`, …;
/// ISO 32000-2 §9.7.5.2), which maps Unicode text straight to codes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UnicodeCMap {
Ucs2,
Utf16,
Utf8,
Utf32,
}
impl UnicodeCMap {
/// The encoding of the predefined CMap `name`, if it is a horizontal Unicode one. Vertical
/// (`-V`) CMaps are refused: field appearances are laid out horizontally, so their glyphs
/// would be drawn stacked down the field instead of across it.
pub fn from_name(name: &[u8]) -> Option<Self> {
let name = std::str::from_utf8(name).ok()?;
if !name.starts_with("Uni") || !name.ends_with("-H") {
return None;
}
name.split('-').find_map(|part| match part {
"UCS2" => Some(Self::Ucs2),
"UTF16" => Some(Self::Utf16),
"UTF8" => Some(Self::Utf8),
"UTF32" => Some(Self::Utf32),
_ => None,
})
}
/// The first character of `s` this encoding can't hold, which [`Self::encode`] would write as
/// `?`: a character beyond U+FFFF in UCS-2 (`𠀋`). UTF-16, UTF-8 and UTF-32 hold every one.
pub fn first_unencodable(self, s: &str) -> Option<char> {
match self {
Self::Ucs2 => s.chars().find(|c| u16::try_from(u32::from(*c)).is_err()),
Self::Utf16 | Self::Utf8 | Self::Utf32 => None,
}
}
/// Encode `s`; tabs become spaces, and characters UCS-2 can't hold become `?` (check them
/// first with [`Self::first_unencodable`]: PdfCraft refuses such text rather than write `?`).
pub fn encode(self, s: &str) -> Vec<u8> {
let mut out = Vec::with_capacity(s.len().saturating_mul(2));
let mut units = [0u16; 2];
let mut buf = [0u8; 4];
for c in s.chars() {
let c = if c == '\t' { ' ' } else { c };
match self {
Self::Ucs2 => {
let unit = u16::try_from(u32::from(c)).unwrap_or(u16::from(b'?'));
out.extend_from_slice(&unit.to_be_bytes());
}
Self::Utf16 => {
for unit in c.encode_utf16(&mut units) {
out.extend_from_slice(&unit.to_be_bytes());
}
}
Self::Utf8 => out.extend_from_slice(c.encode_utf8(&mut buf).as_bytes()),
Self::Utf32 => out.extend_from_slice(&u32::from(c).to_be_bytes()),
}
}
out
}
}
/// Whether [`win_ansi`] keeps `c` rather than writing `?` (a tab becomes a space).
pub fn win_ansi_encodable(c: char) -> bool {
c == '\t' || win_ansi_byte(c).is_some()
}
/// The first character of `s` that [`win_ansi`] can't encode and would write as `?`.
pub fn first_non_win_ansi(s: &str) -> Option<char> {
s.chars().find(|c| !win_ansi_encodable(*c))
}
/// The first character of `s` the standard fonts (Helvetica and the rest of the standard 14, in
/// WinAnsiEncoding) can't draw, so that a generated appearance would show it as `?`. Line breaks
/// don't count: appearances lay lines out themselves. PdfCraft refuses such text with
/// [`undrawable_message`] instead of writing `?` (AGENTS.md §4: never lose work silently).
pub fn first_undrawable(s: &str) -> Option<char> {
s.chars().find(|c| !matches!(c, '\n' | '\r') && !win_ansi_encodable(*c))
}
/// The error for text the standard fonts can't draw ([`first_undrawable`]): which character, in
/// what (`"the comment"`, `"the reason"`), and what can be written instead. One wording for every
/// path that writes text in the standard fonts, so agents and users can act on it the same way.
pub fn undrawable_message(what: &str, c: char) -> String {
format!(
"the standard fonts can't draw \"{}\" (U+{:04X}) in {what}; only Western European characters can be written there for now",
c.escape_debug(),
u32::from(c)
)
}
/// The private key on an annotation (a comment or a form field's widget) whose appearance PdfCraft
/// drew with `?` in place of characters its fonts can't draw: a text string holding the first
/// such character. The text itself (a field's `/V`, a comment's `/Contents`) is stored as typed;
/// the mark lets flattening refuse to make that `?` permanent, lets an edit report it, and tells
/// such an appearance apart from one another program drew with a font that has those characters.
pub const UNDRAWN_MARK: &[u8] = b"PCUndrawn";
/// The character [`UNDRAWN_MARK`] records on `d`, if PdfCraft drew its appearance with `?`.
pub fn undrawn_mark(d: &pdfcraft_cos::Dict) -> Option<char> {
d.get(UNDRAWN_MARK).and_then(pdfcraft_cos::Object::as_string).and_then(|s| s.to_text().chars().next())
}
/// Record (`Some`) or clear (`None`) [`UNDRAWN_MARK`] on `d`, for the appearance just drawn.
pub fn set_undrawn_mark(d: &mut pdfcraft_cos::Dict, c: Option<char>) {
match c {
Some(c) => d.set(UNDRAWN_MARK.to_vec(), pdfcraft_cos::PdfString::text(&c.to_string())),
None => {
d.remove(UNDRAWN_MARK);
}
}
}
/// The byte used by Unicode text plans, from the shared WinAnsi table (tabs become spaces).
pub fn win_ansi_char(c: char) -> Option<u8> {
if c == '\t' { Some(b' ') } else { win_ansi_byte(c) }
}
/// Whether every character can be represented without substitution in WinAnsi.
pub fn fits_win_ansi(s: &str) -> bool {
s.chars().all(win_ansi_encodable)
}
/// Bytes as a PDF literal string, `(` … `)`, with delimiters escaped.
pub fn literal(bytes: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(bytes.len() + 2);
out.push(b'(');
for &b in bytes {
match b {
b'(' | b')' | b'\\' => out.extend_from_slice(&[b'\\', b]),
b'\r' => out.extend_from_slice(b"\\r"),
b'\n' => out.extend_from_slice(b"\\n"),
_ => out.push(b),
}
}
out.push(b')');
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn wrap_keeps_leading_spaces() {
assert_eq!(wrap(" indented", 11.0, 500.0), [" indented"]);
assert_eq!(wrap(" a b\n c", 11.0, 500.0), [" a b", " c"]);
assert_eq!(wrap("", 11.0, 500.0), [""]);
// A single leading space before a word that must be broken leaves no blank first line.
let broken = wrap(" abcdefghijklmnopqrstuvwxyz", 11.0, 40.0);
assert!(broken.len() > 1 && broken.iter().all(|l| !l.is_empty()), "{broken:?}");
// So does indentation of two or more spaces: no whitespace-only line, same as one space.
let broken = wrap(" abcdefghijklmnopqrstuvwxyz", 11.0, 40.0);
assert!(broken.len() > 1 && broken.iter().all(|l| !l.trim().is_empty()), "{broken:?}");
assert_eq!(broken, wrap(" abcdefghijklmnopqrstuvwxyz", 11.0, 40.0));
}
#[test]
fn crlf_is_one_line_break() {
assert_eq!(wrap("a\r\nb", 12.0, 100.0), ["a", "b"]);
assert_eq!(wrap("a\rb", 12.0, 100.0), ["a", "b"]);
assert_eq!(wrap("a\nb", 12.0, 100.0), ["a", "b"]);
assert_eq!(wrap("a\r\n\r\nb", 12.0, 100.0), ["a", "", "b"]);
assert_eq!(wrap("a\n\rb", 12.0, 100.0), ["a", "", "b"]);
}
#[test]
fn win_ansi_encodability_matches_the_encoder() {
for c in ['a', 'é', 'ÿ', '€', '—', '™', '\t', '?'] {
assert!(win_ansi_encodable(c), "{c:?}");
}
for c in ['中', 'あ', 'Ω', 'č', 'ă', '☃', '😀'] {
assert!(!win_ansi_encodable(c), "{c:?}");
}
assert_eq!(first_non_win_ansi("Café — 5€"), None);
assert_eq!(first_non_win_ansi("Dvořák"), Some('ř'));
// Line breaks are laid out, not drawn; other controls would be written as `?`.
assert_eq!(first_undrawable("Café\r\n— 5€\tok"), None);
assert_eq!(first_undrawable("签名 Ada"), Some('签'));
assert_eq!(first_undrawable("a\u{7}b"), Some('\u{7}'));
assert_eq!(first_undrawable("𠀋"), Some('𠀋'));
let m = undrawable_message("the comment", '签');
assert_eq!(m, "the standard fonts can't draw \"签\" (U+7B7E) in the comment; only Western European characters can be written there for now");
assert!(undrawable_message("the reason", '\u{7}').contains("\"\\u{7}\" (U+0007)"));
assert!(undrawable_message("x", '𠀋').contains("(U+2000B)"));
}
#[test]
fn the_undrawn_mark_records_one_character_and_clears() {
let mut d = pdfcraft_cos::Dict::new();
assert_eq!(undrawn_mark(&d), None);
set_undrawn_mark(&mut d, Some('𠀋'));
assert_eq!(undrawn_mark(&d), Some('𠀋'), "beyond U+FFFF, as a UTF-16 text string");
set_undrawn_mark(&mut d, Some('签'));
assert_eq!(undrawn_mark(&d), Some('签'));
set_undrawn_mark(&mut d, None);
assert!(!d.contains(UNDRAWN_MARK));
// Another value under the key is not a character: no mark.
d.set(UNDRAWN_MARK.to_vec(), pdfcraft_cos::Object::Bool(true));
assert_eq!(undrawn_mark(&d), None);
}
#[test]
fn inter_width_measures_latin_extended_and_ascii() {
assert!(inter_width("Luka Petravić", 12.0) > 0.0);
assert_eq!(inter_width("", 12.0), 0.0);
let w = inter_width("čžšć", 10.0);
assert!(w > 10.0 && w < 100.0);
}
#[test]
fn widths_wrap_and_encode() {
assert!(helvetica_width("MMMM", 10.0) > helvetica_width("iiii", 10.0) * 2.0);
assert_eq!(helvetica_width("", 12.0), 0.0);
let lines = wrap("the quick brown fox jumps over the lazy dog", 12.0, 80.0);
assert!(lines.len() > 2 && lines.iter().all(|l| helvetica_width(l, 12.0) <= 80.0));
assert_eq!(wrap("a\nb", 12.0, 100.0), ["a", "b"]);
let long = wrap("Supercalifragilisticexpialidocious", 12.0, 40.0);
assert!(long.len() > 3 && long.concat() == "Supercalifragilisticexpialidocious");
assert_eq!(win_ansi("Café — 5€ ☃"), b"Caf\xe9 \x97 5\x80 ?");
assert_eq!(literal(b"a(b)\\c"), b"(a\\(b\\)\\\\c)");
}
/// WinAnsiEncoding's 0xAD is the `hyphen` glyph and its 0xA0 is `space`, not U+00AD and
/// U+00A0; MacRomanEncoding's 0xCA is `space` too.
///
/// Annex D.2 gives each of those codes the same glyph name as the ordinary one (0x2D, 0x20),
/// so the bytes a Windows codepage calls a soft hyphen and a non-breaking space draw ordinary
/// ink and must extract as it. Reading them as the formatting characters hid them: a soft
/// hyphen is invisible, so a search for "well-known" missed text that drew exactly that, and
/// `redact`'s pattern matching missed it too; a non-breaking space does not match the space a
/// reader types. Over the 989-file pdf.js corpus this takes the soft hyphens we extract from
/// 117 to 13 (104 of them in `XiaoBiaoSong.pdf` alone) and the non-breaking spaces from 30 to
/// 26; what remains comes from `/ToUnicode` maps, which say so explicitly and are not touched.
/// pdftotext reads both codes as the ordinary character.
#[test]
fn the_alias_codes_read_as_the_glyph_they_draw() {
assert_eq!(encodings::WIN_ANSI.get(0xAD), Some(&u32::from('-')));
assert_eq!(encodings::WIN_ANSI.get(0x2D), Some(&u32::from('-')));
assert_eq!(encodings::WIN_ANSI.get(0xA0), Some(&u32::from(' ')));
assert_eq!(encodings::WIN_ANSI.get(0x20), Some(&u32::from(' ')));
assert_eq!(encodings::MAC_ROMAN.get(0xCA), Some(&u32::from(' ')));
assert_eq!(encodings::MAC_ROMAN.get(0x20), Some(&u32::from(' ')));
// MacRoman has no soft hyphen; 0xAD there is `notequal`, and keeps it.
assert_eq!(encodings::MAC_ROMAN.get(0xAD), Some(&0x2260));
// Writing is unaffected: '-' and ' ' take the canonical low codes, and a caller holding a
// literal U+00AD or U+00A0 still writes the high byte, which is the one that draws them.
assert_eq!(win_ansi_byte('-'), Some(0x2D));
assert_eq!(win_ansi_byte(' '), Some(0x20));
assert_eq!(win_ansi_byte('\u{00ad}'), Some(0xAD));
assert_eq!(win_ansi_byte('\u{00a0}'), Some(0xA0));
assert_eq!(win_ansi("a-b c"), b"a-b c");
}
#[test]
fn win_ansi_covers_the_0x80_to_0x9f_glyphs() {
// Every character in the WinAnsiEncoding table encodes to its code and back (#347), except
// where two codes share one glyph: 0xAD is `hyphen`, the same glyph as 0x2D, and 0xA0 is
// `space`, the same glyph as 0x20, so each decodes to the ordinary character and that
// character encodes back to the canonical low code. Round-tripping the *code* is what
// cannot hold there; round-tripping the character still does.
const ALIASES: &[u8] = &[0xA0, 0xAD];
for (code, &u) in encodings::WIN_ANSI.iter().enumerate() {
let Some(c) = char::from_u32(u).filter(|_| u != 0) else { continue };
if ALIASES.contains(&(code as u8)) {
let canonical = win_ansi_byte(c).expect("an aliased glyph still encodes");
assert!(canonical < code as u8, "{c:?}: the canonical code is the lower one");
assert_eq!(encodings::WIN_ANSI.get(usize::from(canonical)), Some(&u), "both codes mean the same character");
continue;
}
assert_eq!(win_ansi_byte(c), Some(code as u8), "{c:?} (U+{u:04X})");
assert_eq!(win_ansi(&c.to_string()), [code as u8]);
}
assert_eq!(
win_ansi("Šta? žaba, œuvre — „ok“ ‰ ƒ † ‡ ˆ ˜ ‹›Ÿ"),
b"\x8ata? \x9eaba, \x9cuvre \x97 \x84ok\x93 \x89 \x83 \x86 \x87 \x88 \x98 \x8b\x9b\x9f"
);
// Not in WinAnsi: č ć still need the fallback font; undefined codes are never produced.
assert_eq!(win_ansi("čć\u{81}\u{8d}\t"), b"???? ");
assert_eq!(win_ansi_byte('\0'), None);
}
#[test]
fn unicode_cmaps_encode_cjk_text() {
assert_eq!(UnicodeCMap::from_name(b"UniJIS-UTF16-H"), Some(UnicodeCMap::Utf16));
assert_eq!(UnicodeCMap::from_name(b"UniGB-UCS2-V"), None);
assert_eq!(UnicodeCMap::from_name(b"UniJIS-UCS2-HW-H"), Some(UnicodeCMap::Ucs2));
assert_eq!(UnicodeCMap::from_name(b"UniKS-UTF8-H"), Some(UnicodeCMap::Utf8));
assert_eq!(UnicodeCMap::from_name(b"UniJIS2004-UTF32-H"), Some(UnicodeCMap::Utf32));
assert_eq!(UnicodeCMap::from_name(b"Identity-H"), None);
assert_eq!(UnicodeCMap::from_name(b"90ms-RKSJ-H"), None);
assert_eq!(UnicodeCMap::from_name(b"\xff\xfe"), None);
assert_eq!(UnicodeCMap::Utf16.encode("令A"), [0x4e, 0xe4, 0x00, 0x41]);
assert_eq!(UnicodeCMap::Utf16.encode("𠀋"), [0xd8, 0x40, 0xdc, 0x0b]);
assert_eq!(UnicodeCMap::Ucs2.encode("𠀋\t"), [0x00, b'?', 0x00, b' ']);
// That `?` is never written silently: callers check first.
assert_eq!(UnicodeCMap::Ucs2.first_unencodable("令和𠀋"), Some('𠀋'));
assert_eq!(UnicodeCMap::Ucs2.first_unencodable("令和"), None);
for cmap in [UnicodeCMap::Utf16, UnicodeCMap::Utf8, UnicodeCMap::Utf32] {
assert_eq!(cmap.first_unencodable("令和𠀋"), None, "{cmap:?}");
}
assert_eq!(UnicodeCMap::Utf8.encode("令"), "令".as_bytes());
assert_eq!(UnicodeCMap::Utf32.encode("令"), [0, 0, 0x4e, 0xe4]);
assert_eq!(cjk_width("令和", 10.0), 20.0);
assert_eq!(cjk_width("ア", 10.0), 5.0);
assert_eq!(cjk_width("A", 10.0), helvetica_width("A", 10.0));
let lines = wrap_with("日本語のテキストは文字単位で折り返されます", 10.0, 45.0, cjk_width);
assert!(lines.len() > 3 && lines.iter().all(|l| cjk_width(l, 10.0) <= 45.0), "{lines:?}");
}
/// Wrapping measures each word and character a bounded number of times, however many fit on a line.
#[test]
fn wrapping_measures_each_word_a_few_times() {
let measured = std::cell::Cell::new(0usize);
let measure = |s: &str, size: f64| {
measured.set(measured.get() + s.len());
helvetica_width(s, size)
};
let text = format!("{} {}", "word ".repeat(5_000), "x".repeat(5_000));
let lines = wrap_with(&text, 1.0, 13_000.0, measure);
assert_eq!(lines.len(), 2, "the words fit on one line, the long word on another");
assert!(measured.get() <= 4 * text.len(), "{} bytes measured", measured.get());
let narrow = wrap_with(&text, 10.0, 100.0, helvetica_width);
assert!(narrow.iter().all(|l| helvetica_width(l, 10.0) <= 100.0), "{narrow:?}");
}
}