Files
pdfcraft/crates/fonts/src/plan.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

339 lines
15 KiB
Rust

//! Planning visible Unicode text output for OCR: which characters the standard WinAnsi
//! fonts show as is, which need a Type3 font drawn from the craft-fonts faces, and which have
//! no glyph anywhere (written as `?` — and counted, never silently dropped).
//!
//! The plan is a pure function of the words ([`TextPlan::for_words`]). The content generators
//! (`pdfcraft_ocr::text_layer` / `visible_text_layer`) read the per-character codes and
//! advances from it, and whoever registers the fonts (`pdfcraft_edit::add_type3_fonts`) fills
//! in each face's resource name and object. The build must work without craft-fonts too: there
//! [`CRAFT_FONTS`] is empty, nothing can be planned, and every non-WinAnsi character is
//! reported as a substitution instead.
use std::collections::HashMap;
use pdfcraft_cos::ObjRef;
use crate::{CraftFont, GlyphOutline, craft_glyph, document_japanese_font, face_has, fits_win_ansi, win_ansi_char};
/// Unique characters per Type3 font: the same bound the text-editing fallback uses, so one
/// hostile word cannot balloon into thousands of glyph streams. A face with more characters
/// simply gets another font.
pub const MAX_TYPE3_GLYPHS: usize = 240;
/// Planned glyphs per plan in total (10 full fonts). A page's recognition cannot realistically
/// exceed it; hostile input beyond it degrades to `?` substitutions, which are counted.
pub const MAX_PLAN_GLYPHS: usize = 2400;
/// One planned Type3 font: the glyphs of one craft-fonts face, one character per code
/// (`code = position + 1`, as in the text-editing fallback). `name` and `object` are filled in
/// when the font is added to a page's resources; until then the content generators fall back to
/// the WinAnsi path for the words that reference it.
pub struct PlannedType3 {
/// The face family the glyphs are drawn from ("Shippori Mincho").
pub family: &'static str,
/// (character, outline with its advance) per code, in code order.
pub glyphs: Vec<(char, GlyphOutline)>,
/// The resource name the content references (`PCOcr`, `PCOcr1`, …); empty until registered.
pub name: String,
/// The built font object, shared by every page that uses the font; set at registration.
pub object: Option<ObjRef>,
}
impl PlannedType3 {
fn new(family: &'static str) -> Self {
PlannedType3 { family, glyphs: Vec::new(), name: String::new(), object: None }
}
fn push(&mut self, ch: char, glyph: GlyphOutline) -> u8 {
self.glyphs.push((ch, glyph));
self.glyphs.len() as u8
}
}
/// How the text layers write a plan's characters: each planned character is a
/// `(font index, code)` pair in its font's encoding; a character no face had a glyph for is
/// either the font's `?` code or absent from the run (both counted in [`TextPlan::missing`]).
#[derive(Default)]
pub struct TextPlan {
/// One planned font per face chunk, in first-use order.
pub fonts: Vec<PlannedType3>,
/// Per input word: `(font, code)` per character; empty for a word the standard WinAnsi
/// fonts write as is (or for which nothing could be planned).
words: Vec<Vec<(usize, u8)>>,
/// character → where its glyph lives, across all fonts (codes are font-local).
index: HashMap<char, (usize, u8)>,
/// Characters with no code in their word's font: they appear as `?` (or, when not even a
/// `?` glyph exists, are left out) and are reported, never silently lost.
missing: usize,
}
impl TextPlan {
/// Plan the output for `words`, in order: characters the WinAnsi fonts can't show get codes
/// in Type3 fonts built from the craft-fonts faces (the document face preferred, then the
/// rest of the build input in manifest order); a word whose face can't show a character
/// substitutes its `?`. Faces are chosen per word, so a word of one script stays one face;
/// characters already planned for an earlier word keep their code. Built without
/// craft-fonts, the plan reports every non-WinAnsi character as a substitution.
pub fn for_words<'a>(words: impl IntoIterator<Item = &'a str>) -> TextPlan {
let faces = document_faces();
let mut coverage = Coverage::default();
let mut plan = TextPlan::default();
for word in words {
if fits_win_ansi(word) {
// The WinAnsi path substitutes '?' behind the caller's back; count it.
plan.missing += word.chars().filter(|&c| win_ansi_char(c).is_none()).count();
plan.words.push(Vec::new());
continue;
}
let Some(face) = choose_face(&faces, word, &mut coverage) else {
// No face for this word's script: the WinAnsi path writes '?' for what it
// can't encode.
plan.missing += word.chars().filter(|&c| win_ansi_char(c).is_none()).count();
plan.words.push(Vec::new());
continue;
};
let mut enc: Vec<(usize, u8)> = Vec::with_capacity(word.len());
let mut run: Option<usize> = None;
for ch in word.chars() {
if let Some(&where_) = plan.index.get(&ch) {
enc.push(where_);
run = Some(where_.0);
continue;
}
if let Ok(glyph) = craft_glyph(face, ch)
&& plan.planned_glyphs() < MAX_PLAN_GLYPHS
&& let Some((fi, code)) = plan.add_glyph(face, ch, glyph)
{
plan.index.insert(ch, (fi, code));
enc.push((fi, code));
run = Some(fi);
continue;
}
// The face has no glyph for the character (or the plan is full): substitute
// the font's '?', in the font the surrounding run is set in.
if let Some((fi, code)) = plan.question_mark(face, run.filter(|&f| plan.fonts[f].family == face.family)) {
enc.push((fi, code));
run = Some(fi);
}
plan.missing += 1;
}
plan.words.push(enc);
}
plan
}
/// The encoding of word `i` (parallel to the slice [`Self::for_words`] planned): a list of
/// `(font, code)` per character, or an empty slice for a word the WinAnsi fonts write.
/// Out-of-range indexes degrade to the empty slice rather than panicking — callers pass the
/// same word list they planned with.
pub fn encoding(&self, word: usize) -> &[(usize, u8)] {
self.words.get(word).map(Vec::as_slice).unwrap_or_default()
}
/// How many characters no font could show (they appear as `?`, or are left out when the
/// word's face has no `?` glyph either).
pub fn missing(&self) -> usize {
self.missing
}
/// The advance of one planned code, in em units (the Type3 glyphs' own widths). `0.0` for
/// anything out of range.
pub fn advance(&self, font: usize, code: u8) -> f64 {
self.fonts.get(font).and_then(|f| f.glyphs.get(usize::from(code).checked_sub(1)?)).map_or(0.0, |(_, g)| g.width)
}
/// The sum of the advances of a word's planned codes, in em units.
pub fn advance_of(&self, encoding: &[(usize, u8)]) -> f64 {
encoding.iter().map(|&(f, c)| self.advance(f, c)).sum()
}
/// Whether every font the encoding references has been registered (has a resource name).
/// Unregistered plans fall back to the WinAnsi path, the same output as before the
/// Unicode mapping existed.
pub fn registered(&self, encoding: &[(usize, u8)]) -> bool {
encoding.iter().all(|&(f, _)| self.fonts.get(f).is_some_and(|font| !font.name.is_empty()))
}
/// Characters with a planned glyph so far.
fn planned_glyphs(&self) -> usize {
self.fonts.iter().map(|f| f.glyphs.len()).sum()
}
/// Add a glyph to the face's current font (a fresh one when that font is full).
fn add_glyph(&mut self, face: &CraftFont, ch: char, glyph: GlyphOutline) -> Option<(usize, u8)> {
let fi = self.font_of_face(face.family)?;
let code = self.fonts[fi].push(ch, glyph);
Some((fi, code))
}
/// The index of the face's open font, or a fresh one. `None` without craft-fonts (the
/// face itself comes from there, so this cannot happen for a planned face).
fn font_of_face(&mut self, family: &'static str) -> Option<usize> {
if let Some(fi) = self.fonts.iter().rposition(|f| f.family == family && f.glyphs.len() < MAX_TYPE3_GLYPHS) {
return Some(fi);
}
if self.fonts.len() >= MAX_PLAN_GLYPHS / MAX_TYPE3_GLYPHS {
return None;
}
self.fonts.push(PlannedType3::new(family));
Some(self.fonts.len() - 1)
}
/// The code of the font's `?` stand-in, adding the glyph when the font lacks it.
/// `prefer` is the run's current font; `None` without craft-fonts.
fn question_mark(&mut self, face: &CraftFont, prefer: Option<usize>) -> Option<(usize, u8)> {
if let Some(fi) = prefer
&& let Some(code) = self.fonts[fi].glyphs.iter().position(|(c, _)| *c == '?')
{
return Some((fi, code as u8 + 1));
}
let fi = self.font_of_face(face.family)?;
if let Some(code) = self.fonts[fi].glyphs.iter().position(|(c, _)| *c == '?') {
return Some((fi, code as u8 + 1));
}
let glyph = craft_glyph(face, '?').ok()?;
let code = self.fonts[fi].push('?', glyph);
Some((fi, code))
}
}
/// The faces that can draw document text, in preference order: the Japanese document face
/// (serif document text) first, then the rest of the build input in manifest order.
fn document_faces() -> Vec<&'static CraftFont> {
let mut out = Vec::new();
if let Some(d) = document_japanese_font() {
out.push(d);
}
for f in crate::CRAFT_FONTS {
if !out.iter().any(|d| std::ptr::eq(*d, f)) {
out.push(f);
}
}
out
}
/// The face for a word: the first (in preference order) whose glyphs cover every character,
/// else the one covering the most characters (ties go to the earlier face). `None` when no
/// face covers any character of the word.
fn choose_face<'f>(faces: &[&'f CraftFont], word: &str, coverage: &mut Coverage) -> Option<&'f CraftFont> {
if let Some(f) = faces.iter().enumerate().find(|(i, f)| word.chars().all(|c| coverage.has(*i, f, c))).map(|(_, f)| *f) {
return Some(f);
}
faces
.iter()
.enumerate()
.map(|(i, f)| (word.chars().filter(|&c| coverage.has(i, f, c)).count(), std::cmp::Reverse(i), *f))
.max_by(|a, b| (a.0, a.1).cmp(&(b.0, b.1)))
.filter(|(covered, _, _)| *covered > 0)
.map(|(_, _, f)| f)
}
/// Which faces have a glyph for which characters, remembered for one plan: a page of words
/// asks the same (face, character) pairs over and over, and each fresh answer parses the font.
#[derive(Default)]
struct Coverage {
known: std::collections::HashMap<(usize, char), bool>,
lookups: usize,
}
impl Coverage {
/// Whether face number `i` (`face`) has `ch`; asks the font once per pair.
fn has(&mut self, i: usize, face: &CraftFont, ch: char) -> bool {
*self.known.entry((i, ch)).or_insert_with(|| {
self.lookups += 1;
face_has(face.bytes, ch)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Face coverage is asked once per (face, character): repeating words cost no new font
/// lookups.
#[test]
fn face_coverage_is_remembered_per_face_and_character() {
let faces = document_faces();
let Some(face) = faces.first() else {
eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to run it)");
return;
};
let mut coverage = Coverage::default();
let first = (0..50).map(|_| choose_face(&faces, "日本語", &mut coverage)).last().flatten();
assert!(first.is_some());
assert!(coverage.lookups <= faces.len() * 3, "{} lookups for 3 characters", coverage.lookups);
assert_eq!(coverage.has(0, face, '日'), face_has(face.bytes, '日'));
}
/// A page's vocabulary: German umlauts are WinAnsi, and a character no bundled face has
/// (here an emoji) is counted wherever it appears.
#[test]
fn win_ansi_words_get_no_encoding_and_count_only_real_losses() {
let plan = TextPlan::for_words(["Zürcher", "café", "size"]);
assert!(plan.words.iter().all(Vec::is_empty), "all WinAnsi: no Type3 fonts needed");
assert!(plan.fonts.is_empty());
assert_eq!(plan.missing(), 0);
let none = TextPlan::for_words(["plain text"]);
assert_eq!(none.missing(), 0);
// U+1F600 has no WinAnsi code and no glyph in any bundled face (with craft-fonts the
// JIS faces even cover the snowman): counted, shown as '?'.
let emoji = TextPlan::for_words(["\u{1f600}!"]);
assert_eq!(emoji.missing(), 1);
}
#[test]
fn without_craft_fonts_every_non_win_ansi_character_is_reported() {
if !crate::CRAFT_FONTS.is_empty() {
eprintln!("built with craft-fonts: the planning tests with faces cover this instead");
return;
}
let plan = TextPlan::for_words(["Привет", "日本", "abc"]);
assert!(plan.words.iter().all(Vec::is_empty));
assert!(plan.fonts.is_empty());
assert_eq!(plan.missing(), 8, "six Cyrillic + two CJK characters, each reported");
}
#[test]
fn encodings_are_aligned_and_total_the_advances() {
if crate::CRAFT_FONTS.is_empty() {
eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to run it)");
assert!(TextPlan::for_words(["日本"]).fonts.is_empty());
return;
}
let plan = TextPlan::for_words(["日本語", "語"]);
assert_eq!(plan.encoding(0).len(), 3);
assert_eq!(plan.encoding(1).len(), 1);
// 語 planned once keeps its code (and font) in both words.
let (f, c) = plan.encoding(1)[0];
assert_eq!(plan.encoding(0)[2], (f, c), "the repeated character keeps its code");
assert!(plan.advance(f, c) > 0.0);
assert_eq!(plan.advance(f, 0), 0.0, "codes start at 1");
assert_eq!(plan.encoding(7), &[], "out of range degrades to the WinAnsi path");
assert!(plan.advance_of(plan.encoding(0)) > plan.advance_of(plan.encoding(1)));
}
#[test]
fn hostile_input_stays_bounded() {
// Thousands of DISTINCT characters: the covered ones fill fonts up to the caps, the
// rest are reported substitutions.
let word: String = (0..4000u32).filter_map(|i| char::from_u32(0x4e00 + i)).collect();
let plan = TextPlan::for_words([word.as_str()]);
assert!(plan.planned_glyphs() <= MAX_PLAN_GLYPHS);
assert!(plan.fonts.iter().all(|f| f.glyphs.len() <= MAX_TYPE3_GLYPHS));
assert!(plan.missing() > 0, "characters beyond the caps are reported, never silently dropped");
}
#[test]
fn substitution_and_unknown_scripts_come_out_counted() {
if crate::CRAFT_FONTS.is_empty() {
eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to run it)");
return;
}
let plan = TextPlan::for_words(["日本\u{1f4a9}語"]);
// The emoji has no glyph in any bundled face; the kana/kanji do.
assert_eq!(plan.missing(), 1);
assert_eq!(plan.encoding(0).len(), 4, "the emoji still has an encoding: the font's ?");
}
}