From 45286e048983246ae1c7debf4e01e102762b2783 Mon Sep 17 00:00:00 2001 From: selune <35337584+0xlillith@users.noreply.github.com> Date: Fri, 30 Oct 2026 23:33:09 +0100 Subject: [PATCH] wip(drawings): preserve F0 checked font-plan sources and original acceptance --- .../F0-textplan-fontobjects/README.md | 52 + .../negative-compile-obligations.rs | 42 + .../acceptance/new-f0-wrapper-cases.rs | 78 ++ .../new-production-boundary-cases.rs | 70 + .../acceptance/retained-b1-cases.rs | 210 +++ .../before/acceptance/owned-b1-cases.rs | 210 +++ .../before/acceptance/v2-retained-b1-cases.rs | 210 +++ .../crates/io/src/paper/pdf/text_plan.rs | 351 +++++ .../crates/io/src/paper/pdf/font_objects.rs | 1191 ++++++++++++++++ .../crates/io/src/paper/pdf/text_plan.rs | 335 +++++ .../crates/io/src/paper/pdf/font_objects.rs | 1219 +++++++++++++++++ .../crates/io/src/paper/pdf/text_plan.rs | 387 ++++++ .../acceptance-accessor-fix-from-v2.patch | 36 + .../acceptance-from-owned-appendix.patch | 80 ++ .../product-from-alternative-partial.patch | 227 +++ .../deltas/product-from-canonical.patch | 259 ++++ .../source-bindings.json | 261 ++++ proposals/drawings/README.md | 11 + 18 files changed, 5229 insertions(+) create mode 100644 proposals/drawings/2026-10-30/F0-textplan-fontobjects/README.md create mode 100644 proposals/drawings/2026-10-30/F0-textplan-fontobjects/acceptance/negative-compile-obligations.rs create mode 100644 proposals/drawings/2026-10-30/F0-textplan-fontobjects/acceptance/new-f0-wrapper-cases.rs create mode 100644 proposals/drawings/2026-10-30/F0-textplan-fontobjects/acceptance/new-production-boundary-cases.rs create mode 100644 proposals/drawings/2026-10-30/F0-textplan-fontobjects/acceptance/retained-b1-cases.rs create mode 100644 proposals/drawings/2026-10-30/F0-textplan-fontobjects/before/acceptance/owned-b1-cases.rs create mode 100644 proposals/drawings/2026-10-30/F0-textplan-fontobjects/before/acceptance/v2-retained-b1-cases.rs create mode 100644 proposals/drawings/2026-10-30/F0-textplan-fontobjects/before/alternative-partial/crates/io/src/paper/pdf/text_plan.rs create mode 100644 proposals/drawings/2026-10-30/F0-textplan-fontobjects/before/canonical/crates/io/src/paper/pdf/font_objects.rs create mode 100644 proposals/drawings/2026-10-30/F0-textplan-fontobjects/before/canonical/crates/io/src/paper/pdf/text_plan.rs create mode 100644 proposals/drawings/2026-10-30/F0-textplan-fontobjects/candidate/crates/io/src/paper/pdf/font_objects.rs create mode 100644 proposals/drawings/2026-10-30/F0-textplan-fontobjects/candidate/crates/io/src/paper/pdf/text_plan.rs create mode 100644 proposals/drawings/2026-10-30/F0-textplan-fontobjects/deltas/acceptance-accessor-fix-from-v2.patch create mode 100644 proposals/drawings/2026-10-30/F0-textplan-fontobjects/deltas/acceptance-from-owned-appendix.patch create mode 100644 proposals/drawings/2026-10-30/F0-textplan-fontobjects/deltas/product-from-alternative-partial.patch create mode 100644 proposals/drawings/2026-10-30/F0-textplan-fontobjects/deltas/product-from-canonical.patch create mode 100644 proposals/drawings/2026-10-30/F0-textplan-fontobjects/source-bindings.json diff --git a/proposals/drawings/2026-10-30/F0-textplan-fontobjects/README.md b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/README.md new file mode 100644 index 000000000..9ac8b6c4f --- /dev/null +++ b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/README.md @@ -0,0 +1,52 @@ +# P2 F0 font-plan boundary — source preservation, v3 + +**UNFORMATTED, UNCOMPILED, UNRUN, UNREGISTERED.** This packet preserves two owned product proposals and original acceptance fragments. It is not an integrated branch, production font support, a completed PDF, a passing gate or a merge claim. Earlier archives remain available; none is overwritten. + +## Actual source and lineage + +The current F0 contract is pinned to Cam's B1a [#9512 at 16c9e911](https://github.com/tangency-labs/solidcraft/pull/9512) and B1b [#9513 at a46d46e9](https://github.com/tangency-labs/solidcraft/pull/9513): `TextRun.font` names `Font.id`, and `paper_text` returns the unique used `Vec`. The numeric `Font.bundled` field is gone. `Font.embed` belongs to F2 and is **not** invented here. Full immutable heads, blobs, byte hashes and per-file baselines are in [source-bindings.json](source-bindings.json). + +The predecessor [width/Refs composition](https://github.com/tangency-labs/solidcraft/tree/5f127aceb09f04dcfe6e4dc1d0253a292787dffa/proposals/drawings/2026-10-30/P2-width-Refs-composition) remains bound to its older records. This successor carries the F0 and checked-source boundary work. The v3 source manifest is `1b6f64a24513cb069efd76708fd8788dd29ff09da802ea662c1a60da2bbc24ed`; its product candidates remain byte-identical to v2 (`6795b37c`). + +## DW decision since this archived source + +Cam has now [resolved the DW contract](https://github.com/tangency-labs/solidcraft/pull/7626#issuecomment-6534292604): explicit `/W` coverage for **every emitted CID**, without relying on `/DW`; B1 adds no GID-0 width. The embedded font program's `.notdef` glyph is a separate embedding responsibility. + +The exact v3 product below predates that decision and **still contains its old absent-GID-0 refusal**. It is not the implementation of the now-resolved contract. A separate v4 successor is being prepared; no product bytes are changed in this archival payload and no new public question is asked. The old refusal is preserved as history, not presented as an unanswered owner decision. + +## What the proposed boundary actually checks + +`TextPlan::font_input` can expose a borrowed `FontPlanView` only after successful plan construction. Its font, immutable factory-produced subset, descriptor and codes are private fields with existing read-only getters. The production font input accepts that view plus the subset tag and local output allowance. Raw parts and component emission remain module-private; descendant component tests use explicit private aliases rather than a new proof constructor. This prevents a safe sibling caller from simply pairing arbitrary Font and Subset records at that entry. It does not certify facts the plan never checks. + +The existing exact regular-font policy remains. The proposed path compares the actual bytes and face with the fresh builtin `font_data(None)` result, using the existing catalog path before installed-font/filesystem/cache lookup. The original B1 bytes-plus-face identity, original-GID intrinsic-advance check and single subset→closure→RAW admission chain remain. The font-object helper removes its redundant identity rehash; this is **not** removal of the original identity/admission checks or permission to add another parser/RAW admission. `/W` still uses checked B1 original-GID advances, distinct from placed advances. No font lookup fallback, new asset, new dependency or broadened embedding policy is supplied. + +The view attests only those performed checks. It does not attest arbitrary outlines, historic layout provenance, licensing/distribution rights, all runs in a document, global budgets or successful future PDF emission. The mutable-advance poison fixture edits the Font **before** `Scene.prepare`; structural preparation succeeds and planning must refuse it. No mutation of an already-live immutable Prepared borrow or executed success is claimed. + +## Acceptance and the narrow v3 correction + +There are **46 ordinary written declarations** in this proposed subset: 24 inline helper cases, 13 retained B1 cases, 4 F0 wrapper cases and 5 production-boundary cases. The [four negative compile obligations](acceptance/negative-compile-obligations.rs) are separate intentional invalid snippets, not ordinary module code. Their expected diagnostic classes are not observed compiler results. No positive case has been relabelled as compile-fail. + +The sole v2 source finding was six positive-test lines still reading removed raw input fields. V3 changes exactly eight reads on those six lines to the existing `source.font()`, `source.descriptor()` and `source.codes()` getters. The descriptor getter borrows a successful plan's nonoptional descriptor; this does not remove the missing-descriptor refusal from the raw component boundary. Test names, order, classification, assertions, literal text/numbers, seeds, tolerances, budgets and fixtures are preserved. + +The independent focal closure (`335195903fca30866b1dbef23417b191439bee063e6bf35487858151c40c1fcf`) closes **only that source accessor finding**. Product bytes and product patch alternatives are unchanged from v2. No formatting, compiler, ordinary/negative-test execution, PDF generation/readback or full-feature qualification follows from this closure. The worker's sealed-before-review manifest remains historical; no private report is republished here. + +Earlier Cam/P1/many-page, Refs and other P2 acceptance remain in the predecessor archives and must survive a future assembly. The count 46 is this proposal's components, not the whole project or an executable inventory. + +## Choose one route; do not overlay alternatives + +- `candidate/` contains the final two proposed files. +- [Product canonical delta](deltas/product-from-canonical.patch) starts from `before/canonical/`, the owned predecessor's per-file bytes. +- [Product alternative delta](deltas/product-from-alternative-partial.patch) starts from the earlier partial text plan in `before/alternative-partial/` and the same canonical font-object baseline. These routes produce the same two candidates; they are alternatives, not sequential patches. +- [Retained-case cumulative delta](deltas/acceptance-from-owned-appendix.patch) starts from `before/acceptance/owned-b1-cases.rs`. Its logical filename deliberately identifies an **owned appendix**, not Cam's complete `pdf_tests.rs`. +- [Accessor-only delta](deltas/acceptance-accessor-fix-from-v2.patch) starts from `before/acceptance/v2-retained-b1-cases.rs`. It is the alternative route to the same final retained fragment. The wrapper and boundary fragments append unchanged when normally integrating into the area's existing test file. Keep negative obligations separate. + +All paths are portable source artifacts. These mixed component baselines are not one validated Git head, and no parent registration or application is supplied. Preserve earlier test suffixes and contributor authorship when composing the eventual source. + +## Still pending + +- **Implementing the resolved DW contract** remains a separate successor task. This exact v3 still reaches its historical missing-GID-0 refusal; full emitted-CID `/W` coverage without a `/DW` fallback is not implemented or qualified by these files. No default width, unused glyph or new B1 field is invented, and no text-emission success is claimed. +- Cam's actual #9647 parent/page/content/resource builder is untouched. Normal modules, all-runs-per-font grouping, aggregate budgets, font/page resources and actual text emission remain open. +- Multi-glyph ActualText and real RTL/text extraction remain unsupported/unqualified. Source-only positioning is not reader evidence. +- F2 embedding policy/rights, coherent dependency and Cargo.lock integration, current-source compiler/native/wasm/strict/full gate, actual old-versus-new PDF byte comparison and PDF rendering/readback remain unrun. + +Changes a default: no. Original Worker #1/Engineer-team source and cases retain the existing Cam, P2 and font contributors' authorship/notices. No font binary, private machine data, launcher, log, grant or control file is included. diff --git a/proposals/drawings/2026-10-30/F0-textplan-fontobjects/acceptance/negative-compile-obligations.rs b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/acceptance/negative-compile-obligations.rs new file mode 100644 index 000000000..fc43c5a6c --- /dev/null +++ b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/acceptance/negative-compile-obligations.rs @@ -0,0 +1,42 @@ +// NEGATIVE COMPILE OBLIGATIONS, NOT RUN. +// Compile each function as a separate sibling module of text_plan/font_objects +// under paper::pdf in a coherent future acceptance assembly. Do not include +// these intentional errors in the normal test module or infer a pass here. +// No trybuild dependency or test-only proof constructor is introduced. + +// Expected: E0451, FontPlanView fields private to text_plan. +fn cannot_pair_arbitrary_raw_font_and_subset<'a>( + font: &'a solidcraft_geom::paper::text::Font, + subset: &'a super::subset_font::SubsetFont, + descriptor: &'a super::font_objects::DescriptorMetrics, + codes: &'a [super::font_objects::CodeToGlyph<'a>], +) -> super::text_plan::FontPlanView<'a> { + super::text_plan::FontPlanView { font, subset, descriptor, codes } +} + +// Expected: E0560: no raw source_font/subset/descriptor/codes fields on the +// production input. A validated view cannot be replaced by serde assertions. +fn cannot_restore_the_raw_production_input<'a>( + font: &'a solidcraft_geom::paper::text::Font, + subset: &'a super::subset_font::SubsetFont, +) -> super::font_objects::FontObjectInput<'a> { + super::font_objects::FontObjectInput { + source_font: font, + subset, + codes: &[], + descriptor: None, + postscript_name: b"LiberationSans", + subset_tag: *b"ABCDEF", + max_chunk_bytes: 1 << 20, + } +} + +// Expected: Deserialize is not implemented; there is no token rehydration API. +fn cannot_deserialize_a_production_view() { + let _: super::text_plan::FontPlanView<'_> = serde_json::from_str("{}").unwrap(); +} + +// Expected: E0603: the raw preparation entry is private to font_objects. +fn cannot_call_the_component_emitter_from_a_sibling() { + let _ = super::font_objects::font_objects_parts; +} diff --git a/proposals/drawings/2026-10-30/F0-textplan-fontobjects/acceptance/new-f0-wrapper-cases.rs b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/acceptance/new-f0-wrapper-cases.rs new file mode 100644 index 000000000..f298c2052 --- /dev/null +++ b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/acceptance/new-f0-wrapper-cases.rs @@ -0,0 +1,78 @@ +// Proposed own acceptance appendix. NOT REGISTERED, UNCOMPILED, UNRUN. +// Append after the preserved own13 cases only when Engineer selects a coherent +// F0 base and resolves the existing Font.bundled policy seam. No Cam test edit. +fn f0_plan_scene( + runs: Vec, + fonts: Vec, +) -> solidcraft_geom::paper::Scene { + use solidcraft_geom::paper::{Group, Item, ObjectKind, Scene}; + Scene { + fonts, + ..Scene::new( + solidcraft_geom::Vec2::new(210.0, 297.0), + vec![Group { object: 1, kind: ObjectKind::TitleBlock, items: runs.into_iter().map(Item::Text).collect() }], + ) + } +} + +#[test] +fn f0_text_plan_resolves_the_real_id_through_prepared_without_moving_glyphs() { + let font = b1_plan_font(&[(36, 1366)]); + let run = b1_plan_run("A", &[36]); + assert_eq!(run.font, font.id); + let scene = f0_plan_scene(vec![run.clone()], vec![font]); + let prepared = scene.prepare().unwrap(); + let plan = super::text_plan::plan_prepared_text(&prepared, &[&run], 1 << 20, 410_820).unwrap(); + assert_eq!(plan.glyphs()[0].original_gid, 36); + assert_eq!(plan.glyphs()[0].intrinsic_advance_fu, 1366); + assert_eq!(plan.glyphs()[0].placed_advance_mm, 0.5); + assert_eq!(plan.glyphs()[0].matrix_mm, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + assert_eq!(plan.runs()[0].text, "A"); +} + +#[test] +fn f0_text_plan_refuses_empty_or_unknown_id_without_a_numeric_font_fallback() { + let empty = f0_plan_scene(vec![], vec![]); + let prepared = empty.prepare().unwrap(); + assert!(super::text_plan::plan_prepared_text(&prepared, &[], 1 << 20, 410_820).is_err()); + let font = b1_plan_font(&[(36, 1366)]); + let run = b1_plan_run("A", &[36]); + let scene = f0_plan_scene(vec![run.clone()], vec![font]); + let prepared = scene.prepare().unwrap(); + let mut wrong = run.clone(); + wrong.font[0] ^= 1; + assert!(prepared.font(&wrong).is_none()); + let error = super::text_plan::plan_prepared_text(&prepared, &[&wrong], 1 << 20, 410_820).err().unwrap().to_string(); + assert!(error.contains("run font ID is absent from the prepared scene")); + assert!(super::text_plan::plan_prepared_text(&prepared, &[&run, &wrong], 1 << 20, 410_820).is_err()); +} + +#[test] +fn f0_prepared_boundary_refuses_missing_duplicate_and_unsorted_font_tables() { + let font = b1_plan_font(&[(36, 1366)]); + let run = b1_plan_run("A", &[36]); + assert!(f0_plan_scene(vec![run.clone()], vec![]).prepare().is_err()); + assert!(f0_plan_scene(vec![run.clone()], vec![font.clone(), font.clone()]).prepare().is_err()); + // Synthetic second identity tests only the Scene ordering refusal. It is not + // a claim that another face is admitted for embedding by this P2 adapter. + let mut other_font = font.clone(); + other_font.id[0] ^= 1; + let mut other_run = run.clone(); + other_run.font = other_font.id; + let mut fonts = vec![font, other_font]; + fonts.sort_by_key(|font| font.id); + fonts.reverse(); + assert!(f0_plan_scene(vec![run, other_run], fonts).prepare().is_err()); +} + +#[test] +fn f0_serialized_scene_cannot_supply_prepared_fonts_without_trusted_bytes() { + let font = b1_plan_font(&[(36, 1366)]); + let run = b1_plan_run("A", &[36]); + let scene = f0_plan_scene(vec![run], vec![font]); + let value = serde_json::to_value(&scene).unwrap(); + assert!(value["fonts"][0].get("bytes").is_none()); + let read: solidcraft_geom::paper::Scene = serde_json::from_value(value).unwrap(); + assert!(read.fonts[0].bytes.is_empty()); + assert!(read.prepare().is_err(), "no Prepared value reaches the consumer after untrusted JSON"); +} diff --git a/proposals/drawings/2026-10-30/F0-textplan-fontobjects/acceptance/new-production-boundary-cases.rs b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/acceptance/new-production-boundary-cases.rs new file mode 100644 index 000000000..0a098e3ca --- /dev/null +++ b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/acceptance/new-production-boundary-cases.rs @@ -0,0 +1,70 @@ +// Own production-boundary acceptance. UNREGISTERED, UNCOMPILED, UNRUN. +// Depends on the retained13 and unchanged four F0 wrapper cases/helpers. + +#[test] +fn f0_builtin_identity_rejects_changed_bytes_even_with_a_matching_recomputed_id() { + use sha2::{Digest, Sha256}; + let mut font = b1_plan_font(&[(36, 1366)]); + let mut bytes = font.bytes.to_vec(); + bytes[4096] ^= 1; + font.bytes = std::sync::Arc::from(bytes); + font.id = Sha256::new().chain_update(font.bytes.as_ref()) + .chain_update(font.face.to_le_bytes()).finalize().into(); + let mut run = b1_plan_run("A", &[36]); + run.font = font.id; + let error = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).err().unwrap().to_string(); + assert!(error.contains("builtin drawing font"), "{error}"); +} + +#[test] +fn f0_prepared_public_advance_is_rechecked_before_any_production_view_exists() { + let mut font = b1_plan_font(&[(36, 1366)]); + font.glyphs.get_mut(&36).unwrap().advance = 1367; + let run = b1_plan_run("A", &[36]); + let scene = f0_plan_scene(vec![run.clone()], vec![font]); + let prepared = scene.prepare().unwrap(); + let error = super::text_plan::plan_prepared_text(&prepared, &[&run], 1 << 20, 410_820).err().unwrap().to_string(); + assert!(error.contains("intrinsic advance does not match the admitted hmtx"), "{error}"); +} + +#[test] +fn f0_structural_preparation_does_not_attest_changed_descriptor_metrics() { + let mut font = b1_plan_font(&[(36, 1366)]); + font.metrics.ascent = 1855; + let run = b1_plan_run("A", &[36]); + let scene = f0_plan_scene(vec![run.clone()], vec![font]); + let prepared = scene.prepare().unwrap(); + assert!(super::text_plan::plan_prepared_text(&prepared, &[&run], 1 << 20, 410_820).is_err()); +} + +#[test] +fn f0_production_view_keeps_the_same_borrowed_source_codes_and_subset() { + let font = b1_plan_font(&[(36, 1366), (57, 1366)]); + let run = b1_plan_run("AV", &[36, 57]); + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + let input = plan.font_input(*b"ABCDEF", 1 << 20); + assert!(std::ptr::eq(input.source.font(), &font)); + assert_eq!(input.source.subset().mapping(), [(0, 0), (36, 1), (57, 2)]); + assert_eq!(input.source.codes().iter().map(|row| (row.code, row.subset_gid, row.logical)).collect::>(), + [(1, 1, "A"), (2, 2, "V")]); + assert_eq!(input.source.font().glyphs[&36].advance, 1366); + assert_eq!(plan.glyphs()[0].placed_advance_mm, 0.5); +} + +#[test] +fn f0_opaque_production_input_does_not_bypass_the_unresolved_default_width_gate() { + use pdf_writer::Ref; + let font = b1_plan_font(&[(36, 1366)]); + let before = font.clone(); + let run = b1_plan_run("A", &[36]); + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + let input = plan.font_input(*b"ABCDEF", 1 << 20); + let refs = super::font_objects::FontObjectRefs { + type0: Ref::new(6), cid_font: Ref::new(7), descriptor: Ref::new(8), + font_file2: Ref::new(9), to_unicode: Ref::new(10), cid_to_gid: Ref::new(11), + }; + let error = super::font_objects::font_objects(refs, input).err().unwrap().to_string(); + assert!(error.contains("PDF default-width policy is unresolved"), "{error}"); + assert_eq!(font, before); + assert!(!font.glyphs.contains_key(&0)); +} diff --git a/proposals/drawings/2026-10-30/F0-textplan-fontobjects/acceptance/retained-b1-cases.rs b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/acceptance/retained-b1-cases.rs new file mode 100644 index 000000000..e4a21d31c --- /dev/null +++ b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/acceptance/retained-b1-cases.rs @@ -0,0 +1,210 @@ +// P2 B1 text-plan acceptance: original records, not a replacement layout engine. +// Font constants are literal fields of the pinned original Liberation resource; +// synthetic logical aliases below test the record contract, not real shaping. +fn b1_plan_font(ids: &[(u16, u16)]) -> solidcraft_geom::paper::text::Font { + use sha2::{Digest, Sha256}; + use solidcraft_geom::paper::text::{Font, FontFlags, FontGlyph, FontMetrics}; + let bytes: std::sync::Arc<[u8]> = std::sync::Arc::from(&include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/liberation-sans/LiberationSans-Regular.ttf"))[..]); + let id = Sha256::new().chain_update(bytes.as_ref()).chain_update(0u32.to_le_bytes()).finalize().into(); + Font { + id, bytes, face: 0, postscript_name: "LiberationSans".into(), num_glyphs: 2620, units_per_em: 2048, + metrics: FontMetrics { + ascent: 1854, descent: -434, cap_height: 1409, bbox: [-1114, -621, 2666, 2007], + italic_angle: 0.0, flags: FontFlags::default(), stem_v: 180, + }, + glyphs: ids.iter().map(|&(id, advance)| (id, FontGlyph { advance, outline: vec![] })).collect(), + } +} + +fn b1_plan_run(text: &str, ids: &[u16]) -> solidcraft_geom::paper::text::TextRun { + use solidcraft_geom::paper::text::{Cluster, PlacedGlyph, TextRun}; + assert_eq!(text.chars().count(), ids.len()); + let chars: Vec<_> = text.char_indices().map(|(i, _)| i).chain(std::iter::once(text.len())).collect(); + TextRun { + font: b1_plan_font(&[]).id, scale: 1.0 / 2048.0, origin: solidcraft_geom::Vec2::new(0.0, 0.0), angle: 0.0, slant: 0.0, rtl: false, + glyphs: ids.iter().enumerate().map(|(i, &id)| PlacedGlyph { id, x: i as f64 * 0.375, rise: 0.0, advance: 0.5 }).collect(), + text: text.into(), + clusters: ids.iter().enumerate().map(|(i, _)| Cluster { glyphs: i as u32..i as u32 + 1, text: chars[i] as u32..chars[i + 1] as u32 }).collect(), + } +} + +#[test] +fn b1_text_plan_keeps_intrinsic_width_separate_from_placed_advance() { + let font = b1_plan_font(&[(36, 1366), (57, 1366)]); + let run = b1_plan_run("AV", &[36, 57]); + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + assert_eq!(plan.runs()[0].font_size_mm, 1.0); + assert_eq!(plan.runs()[0].text, "AV"); + assert_eq!(plan.runs()[0].glyphs, 0..2); + let g = &plan.glyphs()[1]; + assert_eq!((g.original_gid, g.intrinsic_advance_fu, g.placed_advance_mm), (57, 1366, 0.5)); + assert_eq!(g.matrix_mm, [1.0, 0.0, 0.0, 1.0, 0.375, 0.0]); + let input = plan.font_input(*b"ABCDEF", 1 << 20); + assert_eq!(input.source.font().postscript_name.as_bytes(), b"LiberationSans"); + assert_eq!(input.source.descriptor().ascent_1000, 905.2734375); +} + +#[test] +fn b1_text_plan_same_gid_with_distinct_logical_text_has_distinct_codes() { + let font = b1_plan_font(&[(36, 1366)]); + let first = b1_plan_run("A", &[36]); + let second = b1_plan_run("B", &[36]); + let plan = super::text_plan::plan_text(&font, &[&second, &first, &first], 1 << 20, 410_820).unwrap(); + assert_eq!(plan.glyphs().iter().map(|g| (g.code, g.logical)).collect::>(), [(2, "B"), (1, "A"), (1, "A")]); + let input = plan.font_input(*b"ABCDEF", 1 << 20); + assert_eq!(input.source.codes().len(), 2); + assert_eq!(input.source.codes()[0].subset_gid, input.source.codes()[1].subset_gid); + assert_eq!((input.source.codes()[0].logical, input.source.codes()[1].logical), ("A", "B")); +} + +#[test] +fn b1_text_plan_preserves_quarter_turn_slant_and_mark_rise_once() { + let font = b1_plan_font(&[(36, 1366)]); + let mut run = b1_plan_run("A", &[36]); + run.origin = solidcraft_geom::Vec2::new(100.0, 50.0); + run.angle = std::f64::consts::FRAC_PI_2; + run.slant = 0.25; + run.glyphs[0].x = 3.0; + run.glyphs[0].rise = 2.0; + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + for (actual, expected) in plan.glyphs()[0].matrix_mm.into_iter().zip([0.0, 1.0, -1.0, 0.25, 98.0, 53.0]) { + assert!((actual - expected).abs() < 1e-12, "fixed quarter-turn f64 trig allowance: {actual} != {expected}"); + } + assert_eq!(run.origin, solidcraft_geom::Vec2::new(100.0, 50.0)); + assert_eq!((run.glyphs[0].x, run.glyphs[0].rise), (3.0, 2.0)); +} + +#[test] +fn b1_text_plan_single_glyph_literal_cluster_is_not_split_or_normalized() { + let font = b1_plan_font(&[(36, 1366)]); + let mut run = b1_plan_run("A", &[36]); + run.text = "fi\u{301}".into(); + run.clusters[0].text = 0..4; + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + assert_eq!(plan.glyphs()[0].logical, "fi\u{301}"); + assert_eq!(plan.font_input(*b"ABCDEF", 1 << 20).source.codes()[0].logical, "fi\u{301}"); +} + +#[test] +fn b1_text_plan_rtl_keeps_positions_but_uses_logical_cluster_order() { + let font = b1_plan_font(&[(36, 1366), (37, 1366)]); + let mut run = b1_plan_run("AB", &[37, 36]); + run.rtl = true; + run.clusters[0].text = 1..2; + run.clusters[1].text = 0..1; + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + assert!(plan.runs()[0].rtl); + assert_eq!(plan.glyphs().iter().map(|g| g.logical).collect::(), "AB"); + assert_eq!(plan.glyphs().iter().map(|g| g.source_glyph_index).collect::>(), [1, 0]); + assert_eq!((plan.glyphs()[0].matrix_mm[4], plan.glyphs()[1].matrix_mm[4]), (0.375, 0.0)); +} + +#[test] +fn b1_text_plan_multi_glyph_cluster_refuses_instead_of_duplicating_text() { + let font = b1_plan_font(&[(36, 1366), (37, 1366)]); + let mut run = b1_plan_run("AB", &[36, 37]); + run.text = "A".into(); + run.clusters.truncate(1); + run.clusters[0].glyphs = 0..2; + run.clusters[0].text = 0..1; + let error = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).err().unwrap().to_string(); + assert!(error.contains("multi-glyph cluster extraction is not supported"), "{error}"); +} + +#[test] +fn b1_text_plan_tounicode_destination_limit_is_inclusive_and_never_split() { + let font = b1_plan_font(&[(36, 1366)]); + let mut run = b1_plan_run("A", &[36]); + run.text = "A".repeat(256); + run.clusters[0].text = 0..256; + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + assert_eq!(plan.glyphs()[0].logical.len(), 256); + drop(plan); + run.text.push('A'); + run.clusters[0].text.end += 1; + let error = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).err().unwrap().to_string(); + assert!(error.contains("512-byte destination"), "{error}"); +} + +#[test] +fn b1_text_plan_space_keeps_advance_and_text_despite_empty_outline() { + let font = b1_plan_font(&[(3, 569)]); + let run = b1_plan_run(" ", &[3]); + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + assert_eq!((plan.glyphs()[0].original_gid, plan.glyphs()[0].intrinsic_advance_fu, plan.glyphs()[0].logical), (3, 569, " ")); +} + +#[test] +fn b1_text_plan_refuses_wrong_identity_descriptor_face_and_intrinsic_width() { + let font = b1_plan_font(&[(36, 1366)]); + let run = b1_plan_run("A", &[36]); + for kind in 0..5 { + let mut wrong = font.clone(); + match kind { + 0 => wrong.id[0] ^= 1, + 1 => wrong.face = 1, + 2 => wrong.metrics.stem_v = 181, + 3 => wrong.metrics.flags.italic = true, + _ => wrong.glyphs.get_mut(&36).unwrap().advance = 1024, + } + assert!(super::text_plan::plan_text(&wrong, &[&run], 1 << 20, 410_820).is_err()); + } +} + +#[test] +fn b1_text_plan_refuses_invalid_partitions_unmatched_font_and_nonfinite_positions() { + let font = b1_plan_font(&[(36, 1366)]); + let run = b1_plan_run("A", &[36]); + for kind in 0..6 { + let mut wrong = run.clone(); + match kind { + 0 => wrong.clusters[0].glyphs.end = 2, + 1 => wrong.clusters[0].text.end = 2, + 2 => wrong.clusters.clear(), + 3 => wrong.font[0] ^= 1, + 4 => wrong.glyphs[0].x = f64::NAN, + _ => { wrong.text = "\u{e9}".into(); wrong.clusters[0].text = 0..1; } + } + assert!(super::text_plan::plan_text(&font, &[&wrong], 1 << 20, 410_820).is_err()); + } +} + +#[test] +fn b1_text_plan_bounds_storage_subsets_run_count_and_exact_used_font_table() { + let font = b1_plan_font(&[(36, 1366)]); + let run = b1_plan_run("A", &[36]); + for (plan_bytes, subset_bytes) in [(0, 410_820), (1, 410_820), (1 << 20, 0), (1 << 20, 1)] { + assert!(super::text_plan::plan_text(&font, &[&run], plan_bytes, subset_bytes).is_err()); + } + assert!(super::text_plan::plan_text(&font, &vec![&run; 1025], 1 << 20, 410_820).is_err()); + let extra = b1_plan_font(&[(36, 1366), (37, 1366)]); + assert!(super::text_plan::plan_text(&extra, &[&run], 1 << 20, 410_820).is_err()); +} + +#[test] +fn b1_text_plan_repeats_real_subset_mapping_and_resource_inputs() { + let font = b1_plan_font(&[(36, 1366), (57, 1366)]); + let run = b1_plan_run("AV", &[36, 57]); + let first = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + let second = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + let a = first.font_input(*b"ABCDEF", 1 << 20); + let b = second.font_input(*b"ABCDEF", 1 << 20); + assert_eq!(a.source.subset().bytes(), b.source.subset().bytes()); + assert_eq!(a.source.subset().mapping(), [(0, 0), (36, 1), (57, 2)]); + assert_eq!(a.source.subset().mapping(), b.source.subset().mapping()); + assert_eq!(a.source.codes().iter().map(|g| (g.code, g.subset_gid, g.logical)).collect::>(), [(1, 1, "A"), (2, 2, "V")]); + assert_eq!(a.source.descriptor().flags, pdf_writer::types::FontFlags::NON_SYMBOLIC.bits()); +} + +#[test] +fn b1_text_plan_font_byte_envelope_refuses_before_identity_or_table_work() { + let font = b1_plan_font(&[(36, 1366)]); + let run = b1_plan_run("A", &[36]); + for len in [0, 410_819, 410_821] { + let mut wrong = font.clone(); + // Identity is deliberately stale too: byte-envelope refusal has priority. + wrong.bytes = std::sync::Arc::from(vec![0; len]); + let error = super::text_plan::plan_text(&wrong, &[&run], 1, 410_820).err().unwrap().to_string(); + assert!(error.contains("font byte length is outside the reviewed resource envelope"), "{error}"); + } +} diff --git a/proposals/drawings/2026-10-30/F0-textplan-fontobjects/before/acceptance/owned-b1-cases.rs b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/before/acceptance/owned-b1-cases.rs new file mode 100644 index 000000000..f11767cfe --- /dev/null +++ b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/before/acceptance/owned-b1-cases.rs @@ -0,0 +1,210 @@ +// P2 B1 text-plan acceptance: original records, not a replacement layout engine. +// Font constants are literal fields of the pinned original Liberation resource; +// synthetic logical aliases below test the record contract, not real shaping. +fn b1_plan_font(ids: &[(u16, u16)]) -> solidcraft_geom::paper::text::Font { + use sha2::{Digest, Sha256}; + use solidcraft_geom::paper::text::{Font, FontFlags, FontGlyph, FontMetrics}; + let bytes: std::sync::Arc<[u8]> = std::sync::Arc::from(&include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/liberation-sans/LiberationSans-Regular.ttf"))[..]); + let id = Sha256::new().chain_update(bytes.as_ref()).chain_update(0u32.to_le_bytes()).finalize().into(); + Font { + bundled: 0, id, bytes, face: 0, postscript_name: "LiberationSans".into(), num_glyphs: 2620, units_per_em: 2048, + metrics: FontMetrics { + ascent: 1854, descent: -434, cap_height: 1409, bbox: [-1114, -621, 2666, 2007], + italic_angle: 0.0, flags: FontFlags::default(), stem_v: 180, + }, + glyphs: ids.iter().map(|&(id, advance)| (id, FontGlyph { advance, outline: vec![] })).collect(), + } +} + +fn b1_plan_run(text: &str, ids: &[u16]) -> solidcraft_geom::paper::text::TextRun { + use solidcraft_geom::paper::text::{Cluster, PlacedGlyph, TextRun}; + assert_eq!(text.chars().count(), ids.len()); + let chars: Vec<_> = text.char_indices().map(|(i, _)| i).chain(std::iter::once(text.len())).collect(); + TextRun { + font: 0, scale: 1.0 / 2048.0, origin: solidcraft_geom::Vec2::new(0.0, 0.0), angle: 0.0, slant: 0.0, rtl: false, + glyphs: ids.iter().enumerate().map(|(i, &id)| PlacedGlyph { id, x: i as f64 * 0.375, rise: 0.0, advance: 0.5 }).collect(), + text: text.into(), + clusters: ids.iter().enumerate().map(|(i, _)| Cluster { glyphs: i as u32..i as u32 + 1, text: chars[i] as u32..chars[i + 1] as u32 }).collect(), + } +} + +#[test] +fn b1_text_plan_keeps_intrinsic_width_separate_from_placed_advance() { + let font = b1_plan_font(&[(36, 1366), (57, 1366)]); + let run = b1_plan_run("AV", &[36, 57]); + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + assert_eq!(plan.runs()[0].font_size_mm, 1.0); + assert_eq!(plan.runs()[0].text, "AV"); + assert_eq!(plan.runs()[0].glyphs, 0..2); + let g = &plan.glyphs()[1]; + assert_eq!((g.original_gid, g.intrinsic_advance_fu, g.placed_advance_mm), (57, 1366, 0.5)); + assert_eq!(g.matrix_mm, [1.0, 0.0, 0.0, 1.0, 0.375, 0.0]); + let input = plan.font_input(*b"ABCDEF", 1 << 20); + assert_eq!(input.postscript_name, b"LiberationSans"); + assert_eq!(input.descriptor.unwrap().ascent_1000, 905.2734375); +} + +#[test] +fn b1_text_plan_same_gid_with_distinct_logical_text_has_distinct_codes() { + let font = b1_plan_font(&[(36, 1366)]); + let first = b1_plan_run("A", &[36]); + let second = b1_plan_run("B", &[36]); + let plan = super::text_plan::plan_text(&font, &[&second, &first, &first], 1 << 20, 410_820).unwrap(); + assert_eq!(plan.glyphs().iter().map(|g| (g.code, g.logical)).collect::>(), [(2, "B"), (1, "A"), (1, "A")]); + let input = plan.font_input(*b"ABCDEF", 1 << 20); + assert_eq!(input.codes.len(), 2); + assert_eq!(input.codes[0].subset_gid, input.codes[1].subset_gid); + assert_eq!((input.codes[0].logical, input.codes[1].logical), ("A", "B")); +} + +#[test] +fn b1_text_plan_preserves_quarter_turn_slant_and_mark_rise_once() { + let font = b1_plan_font(&[(36, 1366)]); + let mut run = b1_plan_run("A", &[36]); + run.origin = solidcraft_geom::Vec2::new(100.0, 50.0); + run.angle = std::f64::consts::FRAC_PI_2; + run.slant = 0.25; + run.glyphs[0].x = 3.0; + run.glyphs[0].rise = 2.0; + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + for (actual, expected) in plan.glyphs()[0].matrix_mm.into_iter().zip([0.0, 1.0, -1.0, 0.25, 98.0, 53.0]) { + assert!((actual - expected).abs() < 1e-12, "fixed quarter-turn f64 trig allowance: {actual} != {expected}"); + } + assert_eq!(run.origin, solidcraft_geom::Vec2::new(100.0, 50.0)); + assert_eq!((run.glyphs[0].x, run.glyphs[0].rise), (3.0, 2.0)); +} + +#[test] +fn b1_text_plan_single_glyph_literal_cluster_is_not_split_or_normalized() { + let font = b1_plan_font(&[(36, 1366)]); + let mut run = b1_plan_run("A", &[36]); + run.text = "fi\u{301}".into(); + run.clusters[0].text = 0..4; + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + assert_eq!(plan.glyphs()[0].logical, "fi\u{301}"); + assert_eq!(plan.font_input(*b"ABCDEF", 1 << 20).codes[0].logical, "fi\u{301}"); +} + +#[test] +fn b1_text_plan_rtl_keeps_positions_but_uses_logical_cluster_order() { + let font = b1_plan_font(&[(36, 1366), (37, 1366)]); + let mut run = b1_plan_run("AB", &[37, 36]); + run.rtl = true; + run.clusters[0].text = 1..2; + run.clusters[1].text = 0..1; + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + assert!(plan.runs()[0].rtl); + assert_eq!(plan.glyphs().iter().map(|g| g.logical).collect::(), "AB"); + assert_eq!(plan.glyphs().iter().map(|g| g.source_glyph_index).collect::>(), [1, 0]); + assert_eq!((plan.glyphs()[0].matrix_mm[4], plan.glyphs()[1].matrix_mm[4]), (0.375, 0.0)); +} + +#[test] +fn b1_text_plan_multi_glyph_cluster_refuses_instead_of_duplicating_text() { + let font = b1_plan_font(&[(36, 1366), (37, 1366)]); + let mut run = b1_plan_run("AB", &[36, 37]); + run.text = "A".into(); + run.clusters.truncate(1); + run.clusters[0].glyphs = 0..2; + run.clusters[0].text = 0..1; + let error = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).err().unwrap().to_string(); + assert!(error.contains("multi-glyph cluster extraction is not supported"), "{error}"); +} + +#[test] +fn b1_text_plan_tounicode_destination_limit_is_inclusive_and_never_split() { + let font = b1_plan_font(&[(36, 1366)]); + let mut run = b1_plan_run("A", &[36]); + run.text = "A".repeat(256); + run.clusters[0].text = 0..256; + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + assert_eq!(plan.glyphs()[0].logical.len(), 256); + drop(plan); + run.text.push('A'); + run.clusters[0].text.end += 1; + let error = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).err().unwrap().to_string(); + assert!(error.contains("512-byte destination"), "{error}"); +} + +#[test] +fn b1_text_plan_space_keeps_advance_and_text_despite_empty_outline() { + let font = b1_plan_font(&[(3, 569)]); + let run = b1_plan_run(" ", &[3]); + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + assert_eq!((plan.glyphs()[0].original_gid, plan.glyphs()[0].intrinsic_advance_fu, plan.glyphs()[0].logical), (3, 569, " ")); +} + +#[test] +fn b1_text_plan_refuses_wrong_identity_descriptor_face_and_intrinsic_width() { + let font = b1_plan_font(&[(36, 1366)]); + let run = b1_plan_run("A", &[36]); + for kind in 0..5 { + let mut wrong = font.clone(); + match kind { + 0 => wrong.id[0] ^= 1, + 1 => wrong.face = 1, + 2 => wrong.metrics.stem_v = 181, + 3 => wrong.metrics.flags.italic = true, + _ => wrong.glyphs.get_mut(&36).unwrap().advance = 1024, + } + assert!(super::text_plan::plan_text(&wrong, &[&run], 1 << 20, 410_820).is_err()); + } +} + +#[test] +fn b1_text_plan_refuses_invalid_partitions_unmatched_font_and_nonfinite_positions() { + let font = b1_plan_font(&[(36, 1366)]); + let run = b1_plan_run("A", &[36]); + for kind in 0..6 { + let mut wrong = run.clone(); + match kind { + 0 => wrong.clusters[0].glyphs.end = 2, + 1 => wrong.clusters[0].text.end = 2, + 2 => wrong.clusters.clear(), + 3 => wrong.font = 1, + 4 => wrong.glyphs[0].x = f64::NAN, + _ => { wrong.text = "\u{e9}".into(); wrong.clusters[0].text = 0..1; } + } + assert!(super::text_plan::plan_text(&font, &[&wrong], 1 << 20, 410_820).is_err()); + } +} + +#[test] +fn b1_text_plan_bounds_storage_subsets_run_count_and_exact_used_font_table() { + let font = b1_plan_font(&[(36, 1366)]); + let run = b1_plan_run("A", &[36]); + for (plan_bytes, subset_bytes) in [(0, 410_820), (1, 410_820), (1 << 20, 0), (1 << 20, 1)] { + assert!(super::text_plan::plan_text(&font, &[&run], plan_bytes, subset_bytes).is_err()); + } + assert!(super::text_plan::plan_text(&font, &vec![&run; 1025], 1 << 20, 410_820).is_err()); + let extra = b1_plan_font(&[(36, 1366), (37, 1366)]); + assert!(super::text_plan::plan_text(&extra, &[&run], 1 << 20, 410_820).is_err()); +} + +#[test] +fn b1_text_plan_repeats_real_subset_mapping_and_resource_inputs() { + let font = b1_plan_font(&[(36, 1366), (57, 1366)]); + let run = b1_plan_run("AV", &[36, 57]); + let first = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + let second = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + let a = first.font_input(*b"ABCDEF", 1 << 20); + let b = second.font_input(*b"ABCDEF", 1 << 20); + assert_eq!(a.subset.bytes(), b.subset.bytes()); + assert_eq!(a.subset.mapping(), [(0, 0), (36, 1), (57, 2)]); + assert_eq!(a.subset.mapping(), b.subset.mapping()); + assert_eq!(a.codes.iter().map(|g| (g.code, g.subset_gid, g.logical)).collect::>(), [(1, 1, "A"), (2, 2, "V")]); + assert_eq!(a.descriptor.unwrap().flags, pdf_writer::types::FontFlags::NON_SYMBOLIC.bits()); +} + +#[test] +fn b1_text_plan_font_byte_envelope_refuses_before_identity_or_table_work() { + let font = b1_plan_font(&[(36, 1366)]); + let run = b1_plan_run("A", &[36]); + for len in [0, 410_819, 410_821] { + let mut wrong = font.clone(); + // Identity is deliberately stale too: byte-envelope refusal has priority. + wrong.bytes = std::sync::Arc::from(vec![0; len]); + let error = super::text_plan::plan_text(&wrong, &[&run], 1, 410_820).err().unwrap().to_string(); + assert!(error.contains("font byte length is outside the reviewed resource envelope"), "{error}"); + } +} diff --git a/proposals/drawings/2026-10-30/F0-textplan-fontobjects/before/acceptance/v2-retained-b1-cases.rs b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/before/acceptance/v2-retained-b1-cases.rs new file mode 100644 index 000000000..abaae690c --- /dev/null +++ b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/before/acceptance/v2-retained-b1-cases.rs @@ -0,0 +1,210 @@ +// P2 B1 text-plan acceptance: original records, not a replacement layout engine. +// Font constants are literal fields of the pinned original Liberation resource; +// synthetic logical aliases below test the record contract, not real shaping. +fn b1_plan_font(ids: &[(u16, u16)]) -> solidcraft_geom::paper::text::Font { + use sha2::{Digest, Sha256}; + use solidcraft_geom::paper::text::{Font, FontFlags, FontGlyph, FontMetrics}; + let bytes: std::sync::Arc<[u8]> = std::sync::Arc::from(&include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/liberation-sans/LiberationSans-Regular.ttf"))[..]); + let id = Sha256::new().chain_update(bytes.as_ref()).chain_update(0u32.to_le_bytes()).finalize().into(); + Font { + id, bytes, face: 0, postscript_name: "LiberationSans".into(), num_glyphs: 2620, units_per_em: 2048, + metrics: FontMetrics { + ascent: 1854, descent: -434, cap_height: 1409, bbox: [-1114, -621, 2666, 2007], + italic_angle: 0.0, flags: FontFlags::default(), stem_v: 180, + }, + glyphs: ids.iter().map(|&(id, advance)| (id, FontGlyph { advance, outline: vec![] })).collect(), + } +} + +fn b1_plan_run(text: &str, ids: &[u16]) -> solidcraft_geom::paper::text::TextRun { + use solidcraft_geom::paper::text::{Cluster, PlacedGlyph, TextRun}; + assert_eq!(text.chars().count(), ids.len()); + let chars: Vec<_> = text.char_indices().map(|(i, _)| i).chain(std::iter::once(text.len())).collect(); + TextRun { + font: b1_plan_font(&[]).id, scale: 1.0 / 2048.0, origin: solidcraft_geom::Vec2::new(0.0, 0.0), angle: 0.0, slant: 0.0, rtl: false, + glyphs: ids.iter().enumerate().map(|(i, &id)| PlacedGlyph { id, x: i as f64 * 0.375, rise: 0.0, advance: 0.5 }).collect(), + text: text.into(), + clusters: ids.iter().enumerate().map(|(i, _)| Cluster { glyphs: i as u32..i as u32 + 1, text: chars[i] as u32..chars[i + 1] as u32 }).collect(), + } +} + +#[test] +fn b1_text_plan_keeps_intrinsic_width_separate_from_placed_advance() { + let font = b1_plan_font(&[(36, 1366), (57, 1366)]); + let run = b1_plan_run("AV", &[36, 57]); + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + assert_eq!(plan.runs()[0].font_size_mm, 1.0); + assert_eq!(plan.runs()[0].text, "AV"); + assert_eq!(plan.runs()[0].glyphs, 0..2); + let g = &plan.glyphs()[1]; + assert_eq!((g.original_gid, g.intrinsic_advance_fu, g.placed_advance_mm), (57, 1366, 0.5)); + assert_eq!(g.matrix_mm, [1.0, 0.0, 0.0, 1.0, 0.375, 0.0]); + let input = plan.font_input(*b"ABCDEF", 1 << 20); + assert_eq!(input.postscript_name, b"LiberationSans"); + assert_eq!(input.descriptor.unwrap().ascent_1000, 905.2734375); +} + +#[test] +fn b1_text_plan_same_gid_with_distinct_logical_text_has_distinct_codes() { + let font = b1_plan_font(&[(36, 1366)]); + let first = b1_plan_run("A", &[36]); + let second = b1_plan_run("B", &[36]); + let plan = super::text_plan::plan_text(&font, &[&second, &first, &first], 1 << 20, 410_820).unwrap(); + assert_eq!(plan.glyphs().iter().map(|g| (g.code, g.logical)).collect::>(), [(2, "B"), (1, "A"), (1, "A")]); + let input = plan.font_input(*b"ABCDEF", 1 << 20); + assert_eq!(input.codes.len(), 2); + assert_eq!(input.codes[0].subset_gid, input.codes[1].subset_gid); + assert_eq!((input.codes[0].logical, input.codes[1].logical), ("A", "B")); +} + +#[test] +fn b1_text_plan_preserves_quarter_turn_slant_and_mark_rise_once() { + let font = b1_plan_font(&[(36, 1366)]); + let mut run = b1_plan_run("A", &[36]); + run.origin = solidcraft_geom::Vec2::new(100.0, 50.0); + run.angle = std::f64::consts::FRAC_PI_2; + run.slant = 0.25; + run.glyphs[0].x = 3.0; + run.glyphs[0].rise = 2.0; + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + for (actual, expected) in plan.glyphs()[0].matrix_mm.into_iter().zip([0.0, 1.0, -1.0, 0.25, 98.0, 53.0]) { + assert!((actual - expected).abs() < 1e-12, "fixed quarter-turn f64 trig allowance: {actual} != {expected}"); + } + assert_eq!(run.origin, solidcraft_geom::Vec2::new(100.0, 50.0)); + assert_eq!((run.glyphs[0].x, run.glyphs[0].rise), (3.0, 2.0)); +} + +#[test] +fn b1_text_plan_single_glyph_literal_cluster_is_not_split_or_normalized() { + let font = b1_plan_font(&[(36, 1366)]); + let mut run = b1_plan_run("A", &[36]); + run.text = "fi\u{301}".into(); + run.clusters[0].text = 0..4; + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + assert_eq!(plan.glyphs()[0].logical, "fi\u{301}"); + assert_eq!(plan.font_input(*b"ABCDEF", 1 << 20).codes[0].logical, "fi\u{301}"); +} + +#[test] +fn b1_text_plan_rtl_keeps_positions_but_uses_logical_cluster_order() { + let font = b1_plan_font(&[(36, 1366), (37, 1366)]); + let mut run = b1_plan_run("AB", &[37, 36]); + run.rtl = true; + run.clusters[0].text = 1..2; + run.clusters[1].text = 0..1; + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + assert!(plan.runs()[0].rtl); + assert_eq!(plan.glyphs().iter().map(|g| g.logical).collect::(), "AB"); + assert_eq!(plan.glyphs().iter().map(|g| g.source_glyph_index).collect::>(), [1, 0]); + assert_eq!((plan.glyphs()[0].matrix_mm[4], plan.glyphs()[1].matrix_mm[4]), (0.375, 0.0)); +} + +#[test] +fn b1_text_plan_multi_glyph_cluster_refuses_instead_of_duplicating_text() { + let font = b1_plan_font(&[(36, 1366), (37, 1366)]); + let mut run = b1_plan_run("AB", &[36, 37]); + run.text = "A".into(); + run.clusters.truncate(1); + run.clusters[0].glyphs = 0..2; + run.clusters[0].text = 0..1; + let error = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).err().unwrap().to_string(); + assert!(error.contains("multi-glyph cluster extraction is not supported"), "{error}"); +} + +#[test] +fn b1_text_plan_tounicode_destination_limit_is_inclusive_and_never_split() { + let font = b1_plan_font(&[(36, 1366)]); + let mut run = b1_plan_run("A", &[36]); + run.text = "A".repeat(256); + run.clusters[0].text = 0..256; + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + assert_eq!(plan.glyphs()[0].logical.len(), 256); + drop(plan); + run.text.push('A'); + run.clusters[0].text.end += 1; + let error = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).err().unwrap().to_string(); + assert!(error.contains("512-byte destination"), "{error}"); +} + +#[test] +fn b1_text_plan_space_keeps_advance_and_text_despite_empty_outline() { + let font = b1_plan_font(&[(3, 569)]); + let run = b1_plan_run(" ", &[3]); + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + assert_eq!((plan.glyphs()[0].original_gid, plan.glyphs()[0].intrinsic_advance_fu, plan.glyphs()[0].logical), (3, 569, " ")); +} + +#[test] +fn b1_text_plan_refuses_wrong_identity_descriptor_face_and_intrinsic_width() { + let font = b1_plan_font(&[(36, 1366)]); + let run = b1_plan_run("A", &[36]); + for kind in 0..5 { + let mut wrong = font.clone(); + match kind { + 0 => wrong.id[0] ^= 1, + 1 => wrong.face = 1, + 2 => wrong.metrics.stem_v = 181, + 3 => wrong.metrics.flags.italic = true, + _ => wrong.glyphs.get_mut(&36).unwrap().advance = 1024, + } + assert!(super::text_plan::plan_text(&wrong, &[&run], 1 << 20, 410_820).is_err()); + } +} + +#[test] +fn b1_text_plan_refuses_invalid_partitions_unmatched_font_and_nonfinite_positions() { + let font = b1_plan_font(&[(36, 1366)]); + let run = b1_plan_run("A", &[36]); + for kind in 0..6 { + let mut wrong = run.clone(); + match kind { + 0 => wrong.clusters[0].glyphs.end = 2, + 1 => wrong.clusters[0].text.end = 2, + 2 => wrong.clusters.clear(), + 3 => wrong.font[0] ^= 1, + 4 => wrong.glyphs[0].x = f64::NAN, + _ => { wrong.text = "\u{e9}".into(); wrong.clusters[0].text = 0..1; } + } + assert!(super::text_plan::plan_text(&font, &[&wrong], 1 << 20, 410_820).is_err()); + } +} + +#[test] +fn b1_text_plan_bounds_storage_subsets_run_count_and_exact_used_font_table() { + let font = b1_plan_font(&[(36, 1366)]); + let run = b1_plan_run("A", &[36]); + for (plan_bytes, subset_bytes) in [(0, 410_820), (1, 410_820), (1 << 20, 0), (1 << 20, 1)] { + assert!(super::text_plan::plan_text(&font, &[&run], plan_bytes, subset_bytes).is_err()); + } + assert!(super::text_plan::plan_text(&font, &vec![&run; 1025], 1 << 20, 410_820).is_err()); + let extra = b1_plan_font(&[(36, 1366), (37, 1366)]); + assert!(super::text_plan::plan_text(&extra, &[&run], 1 << 20, 410_820).is_err()); +} + +#[test] +fn b1_text_plan_repeats_real_subset_mapping_and_resource_inputs() { + let font = b1_plan_font(&[(36, 1366), (57, 1366)]); + let run = b1_plan_run("AV", &[36, 57]); + let first = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + let second = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + let a = first.font_input(*b"ABCDEF", 1 << 20); + let b = second.font_input(*b"ABCDEF", 1 << 20); + assert_eq!(a.source.subset().bytes(), b.source.subset().bytes()); + assert_eq!(a.source.subset().mapping(), [(0, 0), (36, 1), (57, 2)]); + assert_eq!(a.source.subset().mapping(), b.source.subset().mapping()); + assert_eq!(a.source.codes().iter().map(|g| (g.code, g.subset_gid, g.logical)).collect::>(), [(1, 1, "A"), (2, 2, "V")]); + assert_eq!(a.source.descriptor().flags, pdf_writer::types::FontFlags::NON_SYMBOLIC.bits()); +} + +#[test] +fn b1_text_plan_font_byte_envelope_refuses_before_identity_or_table_work() { + let font = b1_plan_font(&[(36, 1366)]); + let run = b1_plan_run("A", &[36]); + for len in [0, 410_819, 410_821] { + let mut wrong = font.clone(); + // Identity is deliberately stale too: byte-envelope refusal has priority. + wrong.bytes = std::sync::Arc::from(vec![0; len]); + let error = super::text_plan::plan_text(&wrong, &[&run], 1, 410_820).err().unwrap().to_string(); + assert!(error.contains("font byte length is outside the reviewed resource envelope"), "{error}"); + } +} diff --git a/proposals/drawings/2026-10-30/F0-textplan-fontobjects/before/alternative-partial/crates/io/src/paper/pdf/text_plan.rs b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/before/alternative-partial/crates/io/src/paper/pdf/text_plan.rs new file mode 100644 index 000000000..ae70aa415 --- /dev/null +++ b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/before/alternative-partial/crates/io/src/paper/pdf/text_plan.rs @@ -0,0 +1,351 @@ +//! Bounded PDF planning from the actual B1a Font/TextRun records (#4890 P2). +//! +//! This neither shapes text nor writes a page. It keeps intrinsic hmtx widths +//! separate from the producer's placed glyph x/rise/advance. One glyph per logical +//! cluster is supported, including a glyph carrying several characters; a +//! multi-glyph cluster is refused until its extraction/content policy is supplied. +//! The ToUnicode destination limit stays 512 UTF-16BE bytes, not a silent split. +//! +//! Plans retain no new font/document Arc: strings/font records are borrowed. +//! Local vector storage and returned subset bytes have separate allowances. The +//! existing subsetter/pdf-writer internal allocation limitations still apply. +//! No parent registration, global PDF Ref allocator, page resource or text arm is +//! introduced here. The parent must preserve the planned placements and reading +//! order and qualify real PDF rendering/extraction; these records prove neither. + +use std::mem::size_of; +use std::ops::Range; + +use pdf_writer::types::FontFlags; +use sha2::{Digest, Sha256}; +use solidcraft_geom::paper::text::{Font, TextRun}; +use solidcraft_geom::paper::MAX_COORDINATE_MM; + +use super::font_objects::{CodeToGlyph, DescriptorMetrics, FontObjectInput}; +use super::subset_font::{SubsetFont, subset_font}; +use crate::{IoError, Result}; + +const MAX_RUNS: usize = 1024; +const MAX_GLYPHS: usize = 16_384; +const MAX_PLAN_BYTES: usize = 16 << 20; +const MAX_LOGICAL_BYTES: usize = 4 << 20; +const MAX_CLUSTER_BYTES: usize = 768; +const MAX_CLUSTER_UNITS: usize = 256; +const APPROVED_FONT_BYTES: usize = 410_820; + +/// One actual glyph, with a code for its original GID AND literal logical text. +/// The matrix has unit basis vectors and a translation in sheet millimetres; +/// font_size_mm is on its run. Parent applies its mm-to-point scale only once. +pub(super) struct PlannedGlyph<'a> { + pub(super) code: u16, + pub(super) original_gid: u16, + pub(super) source_glyph_index: usize, + pub(super) intrinsic_advance_fu: u16, + pub(super) placed_advance_mm: f64, + pub(super) matrix_mm: [f64; 6], + pub(super) logical: &'a str, +} + +/// Glyphs occupy one contiguous range in the plan, in logical reading order. +/// For an RTL run their SOURCE indices descend; positions are never recomputed +/// from font widths. Input run order remains unchanged. +pub(super) struct PlannedRun<'a> { + pub(super) glyphs: Range, + pub(super) font_size_mm: f64, + pub(super) rtl: bool, + pub(super) text: &'a str, +} + +pub(super) struct TextPlan<'a> { + font: &'a Font, + subset: SubsetFont, + descriptor: DescriptorMetrics, + codes: Vec>, + runs: Vec>, + glyphs: Vec>, +} + +impl TextPlan<'_> { + pub(super) fn runs(&self) -> &[PlannedRun<'_>] { + &self.runs + } + + pub(super) fn glyphs(&self) -> &[PlannedGlyph<'_>] { + &self.glyphs + } + + /// Caller still supplies six globally reserved refs to font_objects, a + /// globally unique subset tag, page resources and a cumulative output budget. + pub(super) fn font_input(&self, subset_tag: [u8; 6], max_chunk_bytes: usize) -> FontObjectInput<'_> { + FontObjectInput { + source_font: self.font, + subset: &self.subset, + codes: &self.codes, + descriptor: Some(&self.descriptor), + postscript_name: self.font.postscript_name.as_bytes(), + subset_tag, + max_chunk_bytes, + } + } +} + +fn invalid(message: &'static str) -> IoError { + IoError::Invalid(format!("PDF text plan: {message}")) +} + +fn reserve(count: usize) -> Result> { + let mut values = Vec::new(); + values.try_reserve_exact(count).map_err(|_| invalid("cannot allocate bounded plan storage"))?; + Ok(values) +} + +fn bytes(count: usize) -> Result { + count.checked_mul(size_of::()).ok_or_else(|| invalid("plan storage overflow")) +} + +fn total(parts: &[usize], limit: usize) -> Result { + parts.iter().try_fold(0usize, |n, part| { + n.checked_add(*part).filter(|n| *n <= limit).ok_or_else(|| invalid("plan storage allowance exceeded")) + }) +} + +fn u16_at(bytes: &[u8], at: usize) -> Result { + let end = at.checked_add(2).ok_or_else(|| invalid("font table range overflow"))?; + let value = bytes.get(at..end).and_then(|b| b.try_into().ok()).ok_or_else(|| invalid("truncated admitted font table"))?; + Ok(u16::from_be_bytes(value)) +} + +fn u32_at(bytes: &[u8], at: usize) -> Result { + let end = at.checked_add(4).ok_or_else(|| invalid("font table range overflow"))?; + let value = bytes.get(at..end).and_then(|b| b.try_into().ok()).ok_or_else(|| invalid("truncated admitted font table"))?; + Ok(u32::from_be_bytes(value)) +} + +/// A bounded original hmtx view, not a general font parser. The subset adapter +/// performs the existing exact-resource/embedding admission before plan return. +fn table<'a>(bytes: &'a [u8], tag: &[u8; 4]) -> Result<&'a [u8]> { + let count = usize::from(u16_at(bytes, 4)?); + if count == 0 || count > 19 { + return Err(invalid("font directory exceeds the reviewed resource")); + } + let mut found = None; + for i in 0..count { + let at = 12 + 16 * i; + if bytes.get(at..at + 4) != Some(tag) { + continue; + } + if found.is_some() { + return Err(invalid("duplicate font table")); + } + let start = usize::try_from(u32_at(bytes, at + 8)?).map_err(|_| invalid("font offset exceeds the platform"))?; + let length = usize::try_from(u32_at(bytes, at + 12)?).map_err(|_| invalid("font length exceeds the platform"))?; + let end = start.checked_add(length).ok_or_else(|| invalid("font table range overflow"))?; + found = bytes.get(start..end); + if found.is_none() { + return Err(invalid("font table is outside its bytes")); + } + } + found.ok_or_else(|| invalid("required font table is absent")) +} + +fn intrinsic_advance(font: &Font, gid: u16) -> Result { + if gid >= font.num_glyphs { + return Err(invalid("glyph is outside the admitted font")); + } + let count = usize::from(u16_at(table(&font.bytes, b"hhea")?, 34)?); + if count == 0 || count > usize::from(font.num_glyphs) { + return Err(invalid("invalid hmtx metric count")); + } + u16_at(table(&font.bytes, b"hmtx")?, usize::from(gid).min(count - 1) * 4) +} + +fn descriptor(font: &Font) -> Result { + // Public Font is hostile input too. Refuse its cheap byte envelope before + // hashing or looking through tables, even when the caller's plan budget is tiny. + if font.bytes.len() != APPROVED_FONT_BYTES { + return Err(invalid("font byte length is outside the reviewed resource envelope")); + } + // B1 hashes bytes + faceLE. The existing subset admission hashes RAW bytes; + // their digests are different identities and are never compared to each other. + let m = &font.metrics; + // Original fixed-resource metadata, not fitted/default descriptor values. + // Values come from this exact Liberation Sans head/hhea/OS2/post and l glyph. + if font.bundled != 0 || font.face != 0 || font.postscript_name != "LiberationSans" + || font.num_glyphs != 2620 || font.units_per_em != 2048 + || m.bbox != [-1114, -621, 2666, 2007] || m.ascent != 1854 || m.descent != -434 + || m.cap_height != 1409 || m.stem_v != 180 || m.italic_angle != 0.0 + || m.flags.fixed_pitch || m.flags.serif || m.flags.italic || m.flags.symbolic + { + return Err(invalid("B1 font identity or metrics differ from the reviewed regular bundled face")); + } + let identity: [u8; 32] = Sha256::new().chain_update(font.bytes.as_ref()).chain_update(font.face.to_le_bytes()).finalize().into(); + if font.id != identity { + return Err(invalid("B1 bytes-and-face identity does not match its supplied bytes")); + } + let k = 1000.0 / f32::from(font.units_per_em); + Ok(DescriptorMetrics { + bbox_1000: m.bbox.map(|n| f32::from(n) * k), + ascent_1000: f32::from(m.ascent) * k, + descent_1000: f32::from(m.descent) * k, + cap_height_1000: f32::from(m.cap_height) * k, + italic_angle_degrees: m.italic_angle as f32, + stem_v_1000: f32::from(m.stem_v) * k, + flags: FontFlags::NON_SYMBOLIC.bits(), + }) +} + +/// Check the actual B1 cluster partition and the narrower first P2 contract +/// BEFORE allocating or subsetting. Returning an error exposes no partial plan. +fn check_run(font: &Font, run: &TextRun) -> Result { + if run.font != font.id || !(1..=4000).contains(&run.glyphs.len()) || run.text.len() > 4000 { + return Err(invalid("run font, glyph count or text length is outside B1")); + } + let cap = run.scale * f64::from(font.metrics.cap_height); + let within = |x: f64| x.is_finite() && x.abs() <= MAX_COORDINATE_MM; + if !run.scale.is_finite() || !(1e-6..1e6).contains(&cap) || cap == 1e-6 + || !within(run.origin.x) || !within(run.origin.y) + || !run.angle.is_finite() || run.angle.abs() > std::f64::consts::TAU + || !run.slant.is_finite() || run.slant.abs() > 1.0 + { + return Err(invalid("run transform is outside B1")); + } + let mut glyph_end = 0usize; + let mut text_end = if run.rtl { run.text.len() } else { 0 }; + for cluster in &run.clusters { + let (g0, g1, t0, t1) = ( + cluster.glyphs.start as usize, cluster.glyphs.end as usize, + cluster.text.start as usize, cluster.text.end as usize, + ); + if g0 != glyph_end || g0 >= g1 || t0 >= t1 || (if run.rtl { t1 != text_end } else { t0 != text_end }) { + return Err(invalid("clusters do not partition glyphs and logical text in B1 order")); + } + if g1 - g0 != 1 { + return Err(invalid("multi-glyph cluster extraction is not supported by this text-plan increment")); + } + let logical = run.text.get(t0..t1).ok_or_else(|| invalid("cluster text is not whole UTF-8 characters"))?; + if logical.len() > MAX_CLUSTER_BYTES || logical.encode_utf16().take(MAX_CLUSTER_UNITS + 1).count() > MAX_CLUSTER_UNITS { + return Err(invalid("cluster exceeds the existing ToUnicode 512-byte destination contract")); + } + let glyph = run.glyphs.get(g0).ok_or_else(|| invalid("cluster glyph is outside the run"))?; + if ![glyph.x, glyph.rise, glyph.advance].into_iter().all(within) { + return Err(invalid("placed glyph is outside B1 coordinates")); + } + let intrinsic = font.glyphs.get(&glyph.id).ok_or_else(|| invalid("glyph is absent from the B1 font table"))?; + if intrinsic.advance != intrinsic_advance(font, glyph.id)? { + return Err(invalid("B1 intrinsic advance does not match the admitted hmtx")); + } + glyph_end = g1; + text_end = if run.rtl { t0 } else { t1 }; + } + if glyph_end != run.glyphs.len() || text_end != if run.rtl { 0 } else { run.text.len() } { + return Err(invalid("clusters do not cover the whole run exactly once")); + } + Ok(run.glyphs.len()) +} + +/// Resolve an F0 run through the already validated Scene table, never by a +/// bundled number or Vec index. This increment still plans ONE font and all +/// its runs; mixed-font input is rejected by the existing plan_text checks. +/// Preparation is not proof of PDF embedding permission or trusted advances; +/// the existing owned admission/provenance boundary remains mandatory. +pub(super) fn plan_prepared_text<'a>( + prepared: &solidcraft_geom::paper::Prepared<'a>, + runs: &[&'a TextRun], + max_plan_bytes: usize, + max_subset_bytes: usize, +) -> Result> { + let first = runs.first().copied().ok_or_else(|| invalid("empty allowance or unsupported run count"))?; + let font = prepared.font(first).ok_or_else(|| invalid("run font ID is absent from the prepared scene"))?; + plan_text(font, runs, max_plan_bytes, max_subset_bytes) +} + +/// One bundled font and ALL its runs, in their existing paint order. Code keys +/// are sorted (original GID, literal text), so iteration/export repetition cannot +/// change their allocation. Code zero stays reserved for .notdef, not user text. +pub(super) fn plan_text<'a>(font: &'a Font, runs: &[&'a TextRun], max_plan_bytes: usize, max_subset_bytes: usize) -> Result> { + let limit = max_plan_bytes.min(MAX_PLAN_BYTES); + if limit == 0 || max_subset_bytes == 0 || runs.is_empty() || runs.len() > MAX_RUNS { + return Err(invalid("empty allowance or unsupported run count")); + } + let descriptor = descriptor(font)?; + let mut count = 0usize; + let mut logical_bytes = 0usize; + for run in runs { + count = count.checked_add(check_run(font, run)?).filter(|n| *n <= MAX_GLYPHS) + .ok_or_else(|| invalid("combined glyph count exceeds 16384"))?; + logical_bytes = logical_bytes.checked_add(run.text.len()).filter(|n| *n <= MAX_LOGICAL_BYTES) + .ok_or_else(|| invalid("combined logical text exceeds its allowance"))?; + } + total(&[ + bytes::<(u16, &str)>(count)?, bytes::(count)?, bytes::>(count)?, + bytes::>(count)?, bytes::>(runs.len())?, + ], limit)?; + let mut keys = reserve::<(u16, &str)>(count)?; + let mut used = reserve::(count)?; + let mut codes = reserve::>(count)?; + let mut planned_runs = reserve::>(runs.len())?; + let mut glyphs = reserve::>(count)?; + total(&[ + bytes::<(u16, &str)>(keys.capacity())?, bytes::(used.capacity())?, bytes::>(codes.capacity())?, + bytes::>(glyphs.capacity())?, bytes::>(planned_runs.capacity())?, + ], limit)?; + for run in runs { + for cluster in &run.clusters { + let glyph = run.glyphs.get(cluster.glyphs.start as usize).ok_or_else(|| invalid("checked glyph disappeared"))?; + if glyph.id == 0 { + return Err(invalid(".notdef cannot replace a missing text glyph")); + } + let logical = run.text.get(cluster.text.start as usize..cluster.text.end as usize).ok_or_else(|| invalid("checked text disappeared"))?; + keys.push((glyph.id, logical)); + } + } + keys.sort_unstable(); + keys.dedup(); + for (gid, _) in &keys { + if used.last() != Some(gid) { + used.push(*gid); + } + } + if !font.glyphs.keys().copied().eq(used.iter().copied()) { + return Err(invalid("the font table is not exactly the glyphs of the supplied runs")); + } + // Reuse the real existing admission, composite closure and subset library. + // There is no duplicate raw-font admission hash or copied font implementation. + let subset = subset_font(&font.bytes, font.face, &used, max_subset_bytes)?; + for (index, (gid, logical)) in keys.iter().enumerate() { + let code = u16::try_from(index + 1).map_err(|_| invalid("text codes exceed u16"))?; + let at = subset.mapping().binary_search_by_key(gid, |(old, _)| *old).map_err(|_| invalid("subset lost an original glyph"))?; + let (_, subset_gid) = subset.mapping().get(at).ok_or_else(|| invalid("subset mapping is incomplete"))?; + codes.push(CodeToGlyph { code, subset_gid: *subset_gid, logical }); + } + for run in runs { + let first = glyphs.len(); + let (sin, cos) = run.angle.sin_cos(); + for logical_index in 0..run.clusters.len() { + let at = if run.rtl { run.clusters.len() - 1 - logical_index } else { logical_index }; + let cluster = run.clusters.get(at).ok_or_else(|| invalid("checked cluster disappeared"))?; + let source = cluster.glyphs.start as usize; + let glyph = run.glyphs.get(source).ok_or_else(|| invalid("checked glyph disappeared"))?; + let logical = run.text.get(cluster.text.start as usize..cluster.text.end as usize).ok_or_else(|| invalid("checked text disappeared"))?; + let key = keys.binary_search(&(glyph.id, logical)).map_err(|_| invalid("text code is absent"))?; + let code = codes.get(key).ok_or_else(|| invalid("text code is outside its table"))?.code; + let matrix_mm = [ + cos, sin, cos * run.slant - sin, sin * run.slant + cos, + run.origin.x + cos * glyph.x - sin * glyph.rise, + run.origin.y + sin * glyph.x + cos * glyph.rise, + ]; + if !matrix_mm.iter().all(|n| n.is_finite()) { + return Err(invalid("glyph transform is not finite")); + } + glyphs.push(PlannedGlyph { + code, original_gid: glyph.id, source_glyph_index: source, + intrinsic_advance_fu: intrinsic_advance(font, glyph.id)?, placed_advance_mm: glyph.advance, + matrix_mm, logical, + }); + } + planned_runs.push(PlannedRun { + glyphs: first..glyphs.len(), font_size_mm: run.scale * f64::from(font.units_per_em), rtl: run.rtl, text: &run.text, + }); + } + Ok(TextPlan { font, subset, descriptor, codes, runs: planned_runs, glyphs }) +} diff --git a/proposals/drawings/2026-10-30/F0-textplan-fontobjects/before/canonical/crates/io/src/paper/pdf/font_objects.rs b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/before/canonical/crates/io/src/paper/pdf/font_objects.rs new file mode 100644 index 000000000..a6879ab91 --- /dev/null +++ b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/before/canonical/crates/io/src/paper/pdf/font_objects.rs @@ -0,0 +1,1191 @@ +//! Private PDF font resources for one admitted subset; no B1 or content writer. +//! +//! Identity-H explicitly maps two-byte codes to CIDs. A separate stream maps +//! CIDs to subset GIDs; logical text remains keyed by code in real ToUnicode. +//! W widths come from actual B1 original-GID advances, never subset hmtx. +//! Missing B1 glyph-zero metrics explicitly block the old DW path. +//! Descriptor metrics must come from the SAME admitted source font. Numeric +//! validation does not prove that provenance, and no metrics are estimated. +//! +//! pdf-writer 0.15.0 allocates internally without fallible allocation controls. +//! This returns a local Chunk, never mutating a caller-owned Pdf on Result errors. +//! A later extend has no rollback or OOM guarantee. Caller owns global Ref/tag +//! reservations, page resources, content, positioning and document budgets. + +use pdf_writer::types::{CidFontType, FontFlags, SystemInfo}; +use pdf_writer::{Chunk, Name, Rect, Ref, Str}; + +use sha2::{Digest, Sha256}; +use solidcraft_geom::paper::text::Font; + +use super::subset_font::SubsetFont; +use super::to_unicode::write_to_unicode; +use crate::{IoError, MAX_DRAWING_BYTES, Result}; + +const MAX_REFS_ID: i32 = 100_000; +const MAX_CODES: usize = 65_536; +const MAX_GLYPHS: usize = 16_384; +const MAX_FONT_BYTES: usize = 410_820; +const MAX_MAP_BYTES: usize = 131_072; +const MAX_UTF8_BYTES: usize = 4 << 20; +const MAX_CLUSTER_BYTES: usize = 768; +const MAX_CHUNK_BYTES: usize = 16 << 20; +const MAX_METRIC: f32 = 1_000_000.0; +const ROW_BYTES: usize = 128; +const FIXED_BYTES: usize = 32 << 10; +const POSTSCRIPT_NAME: &[u8] = b"LiberationSans"; + +/// Six already reserved real references. Local validation cannot reserve them +/// globally or discover collisions with future P3/font objects. +pub(super) struct FontObjectRefs { + pub(super) type0: Ref, + pub(super) cid_font: Ref, + pub(super) descriptor: Ref, + pub(super) font_file2: Ref, + pub(super) to_unicode: Ref, + pub(super) cid_to_gid: Ref, +} + +impl FontObjectRefs { + fn all(&self) -> [Ref; 6] { + [self.type0, self.cid_font, self.descriptor, self.font_file2, self.to_unicode, self.cid_to_gid] + } + + fn validate(&self) -> Result<()> { + let ids = self.all(); + for (index, id) in ids.iter().enumerate() { + if !(6..=MAX_REFS_ID).contains(&id.get()) || ids.iter().take(index).any(|prior| prior == id) { + return Err(invalid("font object references must be distinct, outside core 1..5, and at most 100000")); + } + } + Ok(()) + } +} + +/// Reserve the next six font objects from the ACTUAL many-page parent Refs. +/// This is a private pure seam; it neither writes a Pdf nor invents a parallel +/// document allocator, subset tag or page-resource entry. The parent retains +/// its catalog/pages/Info/layers window and calls this after its reservations. +/// Failed local validation/overflow leaves the parent's cursor unchanged. +pub(super) fn reserve_font_refs(refs: &mut super::Refs) -> Result { + if refs.0 <= 0 { + return Err(invalid("font object allocator must start at a positive object number")); + } + // Refs has no Clone API at this pinned revision. A local staging cursor of + // that SAME real type makes the six-number reservation all-or-nothing. + // No fabricated Ref::new arithmetic duplicates the parent's next() policy. + let mut staged = super::Refs(refs.0); + let reserved = FontObjectRefs { + type0: staged.next()?, + cid_font: staged.next()?, + descriptor: staged.next()?, + font_file2: staged.next()?, + to_unicode: staged.next()?, + cid_to_gid: staged.next()?, + }; + // Reuse this helper's existing distinct/core/range policy, rather than + // duplicating its 100000 cap in a second allocator or skipping it. + reserved.validate()?; + *refs = staged; + Ok(reserved) +} + +/// A caller-assigned two-byte code, interpreted as a CID by Identity-H. +/// Neither code nor logical text is inferred from subset_gid. +pub(super) struct CodeToGlyph<'a> { + pub(super) code: u16, + pub(super) subset_gid: u16, + pub(super) logical: &'a str, +} + +/// Explicit PDF descriptor values, not an existing B1/provider record. +/// Lengths use 1000-unit glyph space; italic angle uses degrees. +/// Caller supplies faithful source metrics; no StemV/ascent defaults exist here. +pub(super) struct DescriptorMetrics { + pub(super) bbox_1000: [f32; 4], + pub(super) ascent_1000: f32, + pub(super) descent_1000: f32, + pub(super) cap_height_1000: f32, + pub(super) italic_angle_degrees: f32, + pub(super) stem_v_1000: f32, + pub(super) flags: u32, +} + +impl DescriptorMetrics { + fn validate(&self) -> Result { + let numbers = [ + self.ascent_1000, self.descent_1000, self.cap_height_1000, + self.italic_angle_degrees, self.stem_v_1000, + ]; + if self.bbox_1000.iter().chain(numbers.iter()).any(|n| { + !n.is_finite() || n.abs() > MAX_METRIC || (*n != 0.0 && n.abs() < f32::MIN_POSITIVE) + }) { + return Err(invalid("font descriptor numbers must be finite and bounded")); + } + let [left, bottom, right, top] = self.bbox_1000; + if left >= right || bottom >= top || self.ascent_1000 <= 0.0 + || self.descent_1000 >= 0.0 || self.cap_height_1000 <= 0.0 + || self.cap_height_1000 > self.ascent_1000 || self.stem_v_1000 <= 0.0 + || self.italic_angle_degrees.abs() > 90.0 + { + return Err(invalid("font descriptor has invalid bounds, signs, cap height or stem")); + } + let flags = FontFlags::from_bits(self.flags).ok_or_else(|| invalid("font descriptor contains reserved flags"))?; + let symbolic = flags.contains(FontFlags::SYMBOLIC); + let nonsymbolic = flags.contains(FontFlags::NON_SYMBOLIC); + if symbolic == nonsymbolic { + return Err(invalid("font descriptor must select exactly one Symbolic or Nonsymbolic flag")); + } + Ok(flags) + } +} + +/// IO parameters borrowing the actual B1 resource, not a global allocator. +/// Advances must come from the trusted bundled B1 producer, not JSON assertions; +/// resource identity alone does not attest its public per-glyph fields. +pub(super) struct FontObjectInput<'a> { + pub(super) source_font: &'a Font, + pub(super) subset: &'a SubsetFont, + pub(super) codes: &'a [CodeToGlyph<'a>], + pub(super) descriptor: Option<&'a DescriptorMetrics>, + pub(super) postscript_name: &'a [u8], + pub(super) subset_tag: [u8; 6], + pub(super) max_chunk_bytes: usize, +} + +fn invalid(message: &'static str) -> IoError { + IoError::Invalid(message.into()) +} + +/// One identity-bound B1 width provider over an immutable, already validated +/// subset artifact. No font tables are read here: original FontGlyph advances +/// are the sole W authority; subset IDs are joined back to ORIGINAL GIDs. +struct B1Widths<'a> { + font: &'a Font, + subset: &'a SubsetFont, +} + +// Identity of the exact already admitted regular resource, with face 0 LE +// appended as B1b does. This is not the different raw-resource SHA256. +const REVIEWED_B1_ID: [u8; 32] = [ + 0xaf, 0x02, 0xdb, 0xc8, 0x83, 0x9b, 0x7c, 0xad, + 0xae, 0x15, 0xe5, 0x28, 0xaa, 0x3d, 0x9f, 0xf8, + 0x5c, 0x54, 0x5b, 0x71, 0x5b, 0x55, 0x1d, 0x21, + 0x8b, 0xf3, 0x8a, 0x93, 0x7e, 0xe7, 0xe2, 0xb0, +]; + +/// Numeric conversion only: no shaping, placed advance, default or font parse. +/// u16 inputs cannot encode NaN/Infinity. Still check the division and f32 +/// serialization envelope explicitly; the integer product is checked too. +fn width_1000(advance: u16, units_per_em: u16) -> Result { + if !(16..=16384).contains(&units_per_em) { + return Err(invalid("B1 font units per em are outside 16..16384")); + } + let numerator = u32::from(advance).checked_mul(1000) + .ok_or_else(|| invalid("B1 intrinsic width product overflow"))?; + let value = f64::from(numerator) / f64::from(units_per_em); + let width = value as f32; + if !value.is_finite() || !width.is_finite() || width.abs() > MAX_METRIC + || (width != 0.0 && width.abs() < f32::MIN_POSITIVE) + { + return Err(invalid("PDF B1 glyph width is not finite and bounded")); + } + Ok(width) +} + +impl<'a> B1Widths<'a> { + fn read(font: &'a Font, subset: &'a SubsetFont) -> Result { + // Public B1 fields are bounded before digest, table walks or allocation. + // The actual subset factory admits just these source bytes/face and + // validates its returned program. Its private fields cannot be forged + // here. This identity check binds B1 to that same fixed-source policy; + // it does not cryptographically attest caller-modified advance records. + if font.bytes.len() != MAX_FONT_BYTES { + return Err(invalid("B1 font byte envelope differs from the reviewed resource")); + } + if font.bundled != 0 || font.face != 0 || font.postscript_name.as_bytes() != POSTSCRIPT_NAME + || font.num_glyphs != 2620 || font.units_per_em != 2048 + || font.glyphs.len() > usize::from(font.num_glyphs) + || font.glyphs.keys().any(|gid| *gid >= font.num_glyphs) + { + return Err(invalid("B1 font metadata differs from the reviewed regular face")); + } + let identity: [u8; 32] = Sha256::new().chain_update(font.bytes.as_ref()) + .chain_update(font.face.to_le_bytes()).finalize().into(); + if font.id != identity || identity != REVIEWED_B1_ID { + return Err(invalid("B1 font bytes/face/id do not identify the reviewed resource")); + } + let glyphs = subset.mapping().len(); + if glyphs == 0 || glyphs > MAX_GLYPHS || subset.bytes().is_empty() + || subset.bytes().len() > MAX_FONT_BYTES + { + return Err(invalid("font subset exceeds the admitted fixed-resource contract")); + } + // Preserve the old non-parser mapping guards. The immutable factory's + // check_subset_program still validates maxp/head/hhea/hmtx structure. + let mut previous = None; + for (expected, &(old, new)) in subset.mapping().iter().enumerate() { + if previous.is_some_and(|prior| old <= prior) || usize::from(new) != expected + || old >= font.num_glyphs || (expected == 0 && old != 0) + { + return Err(invalid("font subset mapping is not original-zero ordered and dense")); + } + previous = Some(old); + } + Ok(Self { font, subset }) + } + + fn advance(&self, subset_gid: u16) -> Result { + let &(original_gid, mapped) = self.subset.mapping().get(usize::from(subset_gid)) + .ok_or_else(|| invalid("PDF code maps outside the subset glyph range"))?; + if mapped != subset_gid { + return Err(invalid("PDF subset glyph does not match its original-GID mapping")); + } + let glyph = self.font.glyphs.get(&original_gid) + .ok_or_else(|| invalid("B1 font lacks an intrinsic width for an emitted original glyph"))?; + width_1000(glyph.advance, self.font.units_per_em) + } + + fn default_width(&self) -> Result { + // No extra .notdef record is invented and no width is parsed from the + // subset. Preserve the old explicit DW path ONLY if actual B1 owns GID0. + // Most exactly-used B1 tables omit it: those callers refuse until an + // owner-agreed DW/full-emitted-CID-coverage policy is implemented. + let glyph = self.font.glyphs.get(&0) + .ok_or_else(|| invalid("B1 glyph zero is absent; PDF default-width policy is unresolved"))?; + width_1000(glyph.advance, self.font.units_per_em) + } +} + +fn fixed_font_name(name: &[u8], tag: [u8; 6]) -> Result<[u8; 21]> { + if name != POSTSCRIPT_NAME || !tag.iter().all(u8::is_ascii_uppercase) { + return Err(invalid("PDF font requires LiberationSans and a caller-supplied six-uppercase subset tag")); + } + let mut result = *b"AAAAAA+LiberationSans"; + for (slot, byte) in result.iter_mut().take(6).zip(tag) { + *slot = byte; + } + Ok(result) +} + +/// Conservative byte bound for this exact six-object call sequence/settings. +/// W rows: at most 5 CID digits + 64 finite-f32 bytes + punctuation/spaces < 128. +/// Fixed dictionaries/three streams: 31 pairs including nested SystemInfo, +/// keys <= 16, scalar/name/ref tokens <= 64, bbox value < 262. Each fixed +/// pair costs < 512 bytes; all headers/trailers < 4096. Thus fixed bytes +/// < 31*512+4096 = 19968 < 32768, excluding W rows and raw stream payloads. +/// Stream payload bytes are counted separately, exactly once each in Chunk. +/// This bounds serialized bytes, not Vec capacity, transient memory or OOM. +fn byte_bound(font: usize, cmap: usize, map: usize, rows: usize) -> Result { + rows.checked_mul(ROW_BYTES).and_then(|n| n.checked_add(FIXED_BYTES)) + .and_then(|n| n.checked_add(font)).and_then(|n| n.checked_add(cmap)) + .and_then(|n| n.checked_add(map)).ok_or_else(|| invalid("font object byte budget overflow")) +} + +struct Prepared<'a> { + font: &'a [u8], + unicode: Vec, + cid_map: Vec, + widths: Vec<(u16, f32)>, + default_width: f32, + name: [u8; 21], + descriptor: &'a DescriptorMetrics, + flags: FontFlags, + limit: usize, + bound: usize, +} + +fn prepare(input: FontObjectInput<'_>) -> Result> { + let descriptor = input.descriptor.ok_or_else(|| invalid("essential font descriptor metrics are missing"))?; + let flags = descriptor.validate()?; + let name = fixed_font_name(input.postscript_name, input.subset_tag)?; + if input.codes.len() > MAX_CODES { + return Err(invalid("PDF font code count exceeds 65536")); + } + let metrics = B1Widths::read(input.source_font, input.subset)?; + let default_width = metrics.default_width()?; + let limit = input.max_chunk_bytes.min(MAX_CHUNK_BYTES).min(MAX_DRAWING_BYTES); + let max_cid = input.codes.last().map_or(0, |row| usize::from(row.code)); + let map_len = max_cid.checked_add(1).and_then(|n| n.checked_mul(2)) + .filter(|n| *n <= MAX_MAP_BYTES).ok_or_else(|| invalid("CID to GID map byte limit exceeded"))?; + let without_unicode = byte_bound(input.subset.bytes().len(), 0, map_len, input.codes.len())?; + let unicode_allowance = limit.checked_sub(without_unicode).ok_or_else(|| invalid("font objects exceed their preflight byte allowance"))?; + + let (mut previous, mut utf8) = (None, 0usize); + // Counts/order/ranges/lengths before allocating code-derived buffers. + for row in input.codes { + if previous.is_some_and(|prior| row.code <= prior) { + return Err(invalid("PDF font codes must be strictly increasing and unique")); + } + if row.code == 0 && row.subset_gid != 0 { + return Err(invalid("CID zero must map to subset glyph zero")); + } + metrics.advance(row.subset_gid)?; + if row.logical.is_empty() || row.logical.len() > MAX_CLUSTER_BYTES { + return Err(invalid("PDF font code requires a nonempty bounded literal cluster")); + } + utf8 = utf8.checked_add(row.logical.len()).filter(|n| *n <= MAX_UTF8_BYTES) + .ok_or_else(|| invalid("PDF font logical text input exceeds its byte limit"))?; + previous = Some(row.code); + } + + let mut pairs = Vec::new(); + pairs.try_reserve_exact(input.codes.len()).map_err(|_| invalid("cannot allocate PDF ToUnicode pairs"))?; + let mut widths = Vec::new(); + widths.try_reserve_exact(input.codes.len()).map_err(|_| invalid("cannot allocate PDF CID widths"))?; + let mut cid_map = Vec::new(); + cid_map.try_reserve_exact(map_len).map_err(|_| invalid("cannot allocate PDF CID to GID map"))?; + cid_map.resize(map_len, 0); + for row in input.codes { + pairs.push((row.code, row.logical)); + widths.push((row.code, metrics.advance(row.subset_gid)?)); + let at = usize::from(row.code).checked_mul(2).ok_or_else(|| invalid("CID map offset overflow"))?; + let end = at.checked_add(2).ok_or_else(|| invalid("CID map offset overflow"))?; + cid_map.get_mut(at..end).ok_or_else(|| invalid("CID map range exceeds its allowance"))? + .copy_from_slice(&row.subset_gid.to_be_bytes()); + } + let unicode = write_to_unicode(&pairs, unicode_allowance)?; + let bound = byte_bound(input.subset.bytes().len(), unicode.len(), cid_map.len(), widths.len())?; + if bound > limit { + return Err(invalid("font objects exceed their complete preflight byte allowance")); + } + // Stream::start panics above i32::MAX, so check each real stream explicitly. + for length in [input.subset.bytes().len(), unicode.len(), cid_map.len()] { + i32::try_from(length).map_err(|_| invalid("font stream length exceeds the PDF writer limit"))?; + } + Ok(Prepared { + font: input.subset.bytes(), unicode, cid_map, widths, + default_width, name, descriptor, flags, limit, bound, + }) +} + +fn check_chunk(chunk: &Chunk, limit: usize, bound: usize) -> Result<()> { + if chunk.len() > limit || chunk.len() > bound { + return Err(invalid("serialized font objects exceed their checked byte bound")); + } + Ok(()) +} + +/// Prepare six independent resource objects locally. Caller must reserve their +/// Ref IDs/tag globally and later attach the Type0 ref to page resources. +/// No caller Pdf is borrowed, so Result refusals cannot mutate that document. +pub(super) fn font_objects(refs: FontObjectRefs, input: FontObjectInput<'_>) -> Result { + refs.validate()?; + let prepared = prepare(input)?; + let Prepared { font, unicode, cid_map, widths, default_width, name, descriptor, flags, limit, bound } = prepared; + let mut chunk = Chunk::new(); + { + let mut writer = chunk.type0_font(refs.type0); + writer.base_font(Name(&name)).encoding_predefined(Name(b"Identity-H")) + .descendant_font(refs.cid_font).to_unicode(refs.to_unicode); + } + check_chunk(&chunk, limit, bound)?; + { + let mut writer = chunk.cid_font(refs.cid_font); + writer.subtype(CidFontType::Type2).base_font(Name(&name)) + .system_info(SystemInfo { registry: Str(b"Adobe"), ordering: Str(b"Identity"), supplement: 0 }) + .font_descriptor(refs.descriptor).default_width(default_width) + .cid_to_gid_map_stream(refs.cid_to_gid); + let mut array = writer.widths(); + for &(cid, width) in &widths { + array.consecutive(cid, std::iter::once(width)); + } + } + check_chunk(&chunk, limit, bound)?; + { + let [left, bottom, right, top] = descriptor.bbox_1000; + let mut writer = chunk.font_descriptor(refs.descriptor); + writer.name(Name(&name)).flags(flags).bbox(Rect::new(left, bottom, right, top)) + .italic_angle(descriptor.italic_angle_degrees).ascent(descriptor.ascent_1000) + .descent(descriptor.descent_1000).cap_height(descriptor.cap_height_1000) + .stem_v(descriptor.stem_v_1000).font_file2(refs.font_file2); + } + check_chunk(&chunk, limit, bound)?; + { + let length = i32::try_from(font.len()).map_err(|_| invalid("FontFile2 length exceeds i32"))?; + chunk.stream(refs.font_file2, font).pair(Name(b"Length1"), length); + } + check_chunk(&chunk, limit, bound)?; + { + chunk.stream(refs.to_unicode, &unicode); + } + check_chunk(&chunk, limit, bound)?; + { + chunk.stream(refs.cid_to_gid, &cid_map); + } + check_chunk(&chunk, limit, bound)?; + if !chunk.refs().eq(refs.all()) { + return Err(invalid("font object references differ from the six reserved IDs")); + } + Ok(chunk) +} + +#[cfg(test)] +mod tests { + use super::*; + use super::super::subset_font::subset_font; + + // Unchanged legacy metric reader retained as a test-only independent + // subset/width oracle. Production resource emission has no SFNT reader. + fn part(bytes: &[u8], at: usize, len: usize) -> Result<&[u8]> { + let end = at.checked_add(len).ok_or_else(|| invalid("font metric offset overflow"))?; + bytes.get(at..end).ok_or_else(|| invalid("truncated font metric data")) + } + + fn word(bytes: &[u8], at: usize) -> Result { + Ok(u16::from_be_bytes(part(bytes, at, 2)?.try_into().map_err(|_| invalid("invalid font metric word"))?)) + } + + fn dword(bytes: &[u8], at: usize) -> Result { + let raw = u32::from_be_bytes(part(bytes, at, 4)?.try_into().map_err(|_| invalid("invalid font metric offset"))?); + usize::try_from(raw).map_err(|_| invalid("font metric offset exceeds platform")) + } + + /// Small bounded table view over the already validated, immutable SubsetFont. + /// This does not repeat admission, glyph closure or composite parsing. + fn table<'a>(bytes: &'a [u8], tag: &[u8; 4]) -> Result<&'a [u8]> { + let count = usize::from(word(bytes, 4)?); + if count == 0 || count > 19 { + return Err(invalid("font metric table count exceeds the admitted subset contract")); + } + part(bytes, 0, 12 + count * 16)?; // count <= 19. + for index in 0..count { + let record = 12 + index * 16; + if part(bytes, record, 4)? == tag { + return part(bytes, dword(bytes, record + 8)?, dword(bytes, record + 12)?); + } + } + Err(invalid("subset lacks a required metric table")) + } + + struct MetricView<'a> { + hmtx: &'a [u8], + glyphs: usize, + full_metrics: usize, + units_per_em: u16, + } + + impl<'a> MetricView<'a> { + fn read(subset: &'a SubsetFont) -> Result { + let glyphs = subset.mapping().len(); + if glyphs == 0 || glyphs > MAX_GLYPHS || subset.bytes().len() > MAX_FONT_BYTES { + return Err(invalid("font subset exceeds the admitted fixed-resource contract")); + } + let mut previous = None; + for (expected, &(old, new)) in subset.mapping().iter().enumerate() { + if previous.is_some_and(|prior| old <= prior) || usize::from(new) != expected { + return Err(invalid("font subset mapping is not ordered and dense")); + } + if expected == 0 && old != 0 { + return Err(invalid("font subset lacks original glyph zero")); + } + previous = Some(old); + } + let bytes = subset.bytes(); + let head = table(bytes, b"head")?; + let hhea = table(bytes, b"hhea")?; + let hmtx = table(bytes, b"hmtx")?; + let maxp = table(bytes, b"maxp")?; + if usize::from(word(maxp, 4)?) != glyphs { + return Err(invalid("font subset glyph count differs from its mapping")); + } + let units_per_em = word(head, 18)?; + if units_per_em != 2048 { + return Err(invalid("font subset units per em differ from the one admitted font")); + } + let full_metrics = usize::from(word(hhea, 34)?); + if full_metrics == 0 || full_metrics > glyphs { + return Err(invalid("subset has invalid numberOfHMetrics")); + } + let expected = full_metrics.checked_mul(4) + .and_then(|full| (glyphs - full_metrics).checked_mul(2).and_then(|tail| full.checked_add(tail))) + .ok_or_else(|| invalid("subset metric length overflow"))?; + if hmtx.len() != expected { + return Err(invalid("subset hmtx length does not match its glyph metrics")); + } + Ok(Self { hmtx, glyphs, full_metrics, units_per_em }) + } + + fn advance(&self, gid: u16) -> Result { + let gid = usize::from(gid); + if gid >= self.glyphs { + return Err(invalid("PDF code maps outside the subset glyph range")); + } + let index = gid.min(self.full_metrics - 1); // full_metrics checked > 0. + let advance = word(self.hmtx, index.checked_mul(4).ok_or_else(|| invalid("font advance offset overflow"))?)?; + let width = (f64::from(advance) * 1000.0 / f64::from(self.units_per_em)) as f32; + if !width.is_finite() || width.abs() > MAX_METRIC { + return Err(invalid("PDF glyph width is not finite and bounded")); + } + Ok(width) + } + } + + const BUNDLED: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/liberation-sans/LiberationSans-Regular.ttf")); + + // SYNTHETIC descriptor for serialization/refusal tests. These are NOT + // measured Liberation values or a choice of the real provider's policies. + fn synthetic_descriptor() -> DescriptorMetrics { + DescriptorMetrics { + bbox_1000: [-100.0, -250.0, 1100.0, 900.0], + ascent_1000: 800.0, descent_1000: -200.0, cap_height_1000: 700.0, + italic_angle_degrees: 0.0, stem_v_1000: 80.0, + flags: FontFlags::NON_SYMBOLIC.bits(), + } + } + + fn admitted_subset() -> SubsetFont { + // Read-only original metadata: glyph0 metric(1536,205), 2/3=(569,0), + // original IDs0,2,3 become subset IDs0,1,2. No B1/shaping assertion. + subset_font(BUNDLED, 0, &[3, 2, 3], MAX_FONT_BYTES).unwrap() + } + + fn refs(first: i32) -> FontObjectRefs { + FontObjectRefs { + type0: Ref::new(first), cid_font: Ref::new(first + 1), + descriptor: Ref::new(first + 2), font_file2: Ref::new(first + 3), + to_unicode: Ref::new(first + 4), cid_to_gid: Ref::new(first + 5), + } + } + + // Synthetic B1 resource record for the existing serialization/refusal + // tests only: not a valid exactly-used Scene or a shaper/layout assertion. + fn source_font() -> &'static Font { + static FONT: std::sync::OnceLock = std::sync::OnceLock::new(); + FONT.get_or_init(|| { + use solidcraft_geom::paper::text::{FontFlags as B1Flags, FontGlyph, FontMetrics}; + Font { + bundled: 0, id: REVIEWED_B1_ID, bytes: std::sync::Arc::from(BUNDLED), face: 0, + postscript_name: "LiberationSans".into(), num_glyphs: 2620, units_per_em: 2048, + metrics: FontMetrics { + ascent: 1854, descent: -434, cap_height: 1409, bbox: [-1114, -621, 2666, 2007], + italic_angle: 0.0, flags: B1Flags::default(), stem_v: 180, + }, + glyphs: [(0, 1536), (2, 569), (3, 569)].into_iter() + .map(|(gid, advance)| (gid, FontGlyph { advance, outline: vec![] })).collect(), + } + }) + } + + fn input<'a>(subset: &'a SubsetFont, codes: &'a [CodeToGlyph<'a>], descriptor: &'a DescriptorMetrics) -> FontObjectInput<'a> { + FontObjectInput { + source_font: source_font(), subset, codes, descriptor: Some(descriptor), + postscript_name: POSTSCRIPT_NAME, subset_tag: *b"ABCDEF", + max_chunk_bytes: MAX_CHUNK_BYTES, + } + } + + struct Parsed<'a> { + id: i32, + dict: &'a str, + stream: Option<&'a [u8]>, + } + + fn skip_space(bytes: &[u8], at: &mut usize) { + while bytes.get(*at).is_some_and(u8::is_ascii_whitespace) { *at += 1; } + } + + fn number(dict: &str, key: &str) -> usize { + dict.split_ascii_whitespace().skip_while(|token| *token != key) + .nth(1).unwrap().parse().unwrap() + } + + // Original tiny reader for THIS fixed dictionary/stream grammar, not a + // general PDF parser. Binary font bytes are skipped by declared Length, + // never scanned for endobj/endstream text or used as an expected golden. + fn objects(bytes: &[u8]) -> Vec> { + let mut out = Vec::new(); + let mut at = 0; + while at < bytes.len() { + skip_space(bytes, &mut at); + if at == bytes.len() { break; } + let start = at; + while bytes[at].is_ascii_digit() { at += 1; } + let id = std::str::from_utf8(&bytes[start..at]).unwrap().parse().unwrap(); + assert!(bytes[at..].starts_with(b" 0 obj\n")); + at += b" 0 obj\n".len(); + let start = at; + assert!(bytes[at..].starts_with(b"<<")); + let mut depth = 0; + loop { + if bytes[at..].starts_with(b"<<") { depth += 1; at += 2; } + else if bytes[at..].starts_with(b">>") { + depth -= 1; + at += 2; + if depth == 0 { break; } + } else { at += 1; } + } + let dict = std::str::from_utf8(&bytes[start..at]).unwrap(); + skip_space(bytes, &mut at); + let stream = if bytes[at..].starts_with(b"stream\n") { + at += b"stream\n".len(); + let len = number(dict, "/Length"); + let payload = &bytes[at..at + len]; + at += len; + assert!(bytes[at..].starts_with(b"\nendstream")); + at += b"\nendstream".len(); + skip_space(bytes, &mut at); + Some(payload) + } else { None }; + assert!(bytes[at..].starts_with(b"endobj")); + at += b"endobj".len(); + out.push(Parsed { id, dict, stream }); + } + out + } + + fn object<'a, 'b>(objects: &'b [Parsed<'a>], id: i32) -> &'b Parsed<'a> { + objects.iter().find(|object| object.id == id).unwrap() + } + + #[test] + fn six_real_refs_link_exact_objects_and_preserve_raw_font_bytes() { + let subset = admitted_subset(); + let descriptor = synthetic_descriptor(); + let chunk = font_objects(refs(6), input(&subset, &[], &descriptor)).unwrap(); + let parsed = objects(chunk.as_bytes()); + assert_eq!(parsed.iter().map(|o| o.id).collect::>(), [6, 7, 8, 9, 10, 11]); + let type0 = object(&parsed, 6).dict; + assert!(type0.contains("/Subtype /Type0")); + assert!(type0.contains("/Encoding /Identity-H")); + assert!(type0.contains("/DescendantFonts [7 0 R]")); + assert!(type0.contains("/ToUnicode 10 0 R")); + assert!(type0.contains("/BaseFont /ABCDEF+LiberationSans")); + let cid = object(&parsed, 7).dict; + assert!(cid.contains("/Subtype /CIDFontType2")); + assert!(cid.contains("/CIDToGIDMap 11 0 R")); + assert!(cid.contains("/FontDescriptor 8 0 R")); + assert!(cid.contains("/Registry (Adobe)") && cid.contains("/Ordering (Identity)")); + let desc = object(&parsed, 8).dict; + assert!(desc.contains("/FontName /ABCDEF+LiberationSans")); + assert!(desc.contains("/FontFile2 9 0 R")); + assert!(desc.contains("/StemV 80") && desc.contains("/Ascent 800")); + assert!(desc.contains("/CapHeight 700") && desc.contains("/Flags 32")); + let file = object(&parsed, 9); + assert_eq!(file.stream.unwrap(), subset.bytes()); + assert_eq!(number(file.dict, "/Length1"), subset.bytes().len()); + assert!(!file.dict.contains("/Filter")); + assert_eq!(object(&parsed, 11).stream.unwrap(), [0, 0]); + } + + #[test] + fn distinct_codes_share_a_gid_without_losing_literal_logical_clusters() { + let subset = admitted_subset(); + let descriptor = synthetic_descriptor(); + // Synthetic routing semantics only; no claim that these words are + // shaped or rendered by the space/empty glyph in the fixed resource. + let codes = [ + CodeToGlyph { code: 2, subset_gid: 1, logical: "one" }, + CodeToGlyph { code: 7, subset_gid: 1, logical: "two" }, + CodeToGlyph { code: 9, subset_gid: 0, logical: "notdef" }, + ]; + let chunk = font_objects(refs(6), input(&subset, &codes, &descriptor)).unwrap(); + let parsed = objects(chunk.as_bytes()); + let map = object(&parsed, 11).stream.unwrap(); + let mut expected = vec![0; 20]; + expected[5] = 1; + expected[15] = 1; + assert_eq!(map, expected); + let cmap = std::str::from_utf8(object(&parsed, 10).stream.unwrap()).unwrap(); + assert!(cmap.contains("<0002> <006F006E0065>")); + assert!(cmap.contains("<0007> <00740077006F>")); + assert!(cmap.contains("<0009> <006E006F0074006400650066>")); + assert!(!cmap.contains("<0001> <")); + } + + #[test] + fn sparse_maximum_cid_has_bounded_map_and_zero_stays_notdef() { + let subset = admitted_subset(); + let descriptor = synthetic_descriptor(); + let codes = [CodeToGlyph { code: u16::MAX, subset_gid: 2, logical: "z" }]; + let chunk = font_objects(refs(6), input(&subset, &codes, &descriptor)).unwrap(); + let parsed = objects(chunk.as_bytes()); + let map = object(&parsed, 11).stream.unwrap(); + assert_eq!(map.len(), 131_072); + assert!(map[..131_070].iter().all(|byte| *byte == 0)); + assert_eq!(&map[131_070..], [0, 2]); + let bad = [CodeToGlyph { code: 0, subset_gid: 1, logical: "x" }]; + assert!(font_objects(refs(6), input(&subset, &bad, &descriptor)).is_err()); + let zero = [CodeToGlyph { code: 0, subset_gid: 0, logical: "notdef" }]; + assert!(font_objects(refs(6), input(&subset, &zero, &descriptor)).is_ok()); + } + + // Test-only parser for this oracle's EXACT two-row W shape. It preserves + // the outer array and one-element inner arrays instead of flattening them. + // Bounded input/tokens, no deliberate panic, and no general PDF claim. + struct WidthField<'a> { + bytes: &'a [u8], + at: usize, + } + + impl WidthField<'_> { + fn literal(&mut self, token: &[u8]) -> Result<()> { + skip_space(self.bytes, &mut self.at); + let end = self.at.checked_add(token.len()).ok_or_else(|| invalid("W oracle offset overflow"))?; + if self.bytes.get(self.at..end) != Some(token) { + return Err(invalid("W oracle expected an array delimiter or field key")); + } + self.at = end; + Ok(()) + } + + fn cid(&mut self) -> Result { + skip_space(self.bytes, &mut self.at); + let start = self.at; + while self.bytes.get(self.at).is_some_and(u8::is_ascii_digit) { + if self.at - start == 5 { + return Err(invalid("W oracle CID token exceeds five digits")); + } + self.at += 1; + } + let token = self.bytes.get(start..self.at).ok_or_else(|| invalid("W oracle CID range"))?; + let token = std::str::from_utf8(token).map_err(|_| invalid("W oracle CID encoding"))?; + token.parse::().map_err(|_| invalid("W oracle expected a u16 CID")) + } + + fn width(&mut self) -> Result { + skip_space(self.bytes, &mut self.at); + let start = self.at; + while let Some(byte) = self.bytes.get(self.at) { + if byte.is_ascii_whitespace() || matches!(*byte, b'[' | b']') { + break; + } + if self.at - start == 64 { + return Err(invalid("W oracle width token exceeds its limit")); + } + self.at += 1; + } + let token = self.bytes.get(start..self.at).ok_or_else(|| invalid("W oracle width range"))?; + if !token.iter().any(u8::is_ascii_digit) + || token.iter().any(|byte| !byte.is_ascii_digit() && !matches!(*byte, b'+' | b'-' | b'.')) + { + return Err(invalid("W oracle expected a decimal width token")); + } + let token = std::str::from_utf8(token).map_err(|_| invalid("W oracle width encoding"))?; + let width = token.parse::().map_err(|_| invalid("W oracle decimal width"))?; + if !width.is_finite() || width < 0.0 { + return Err(invalid("W oracle requires a finite nonnegative width")); + } + Ok(width) + } + + fn row(&mut self) -> Result<(u16, [f32; 1])> { + let cid = self.cid()?; + self.literal(b"[")?; + let width = self.width()?; + self.literal(b"]")?; + Ok((cid, [width])) + } + } + + fn parse_two_width_rows(field: &str) -> Result<[(u16, [f32; 1]); 2]> { + if field.len() > 512 { + return Err(invalid("W oracle field exceeds its byte limit")); + } + let mut reader = WidthField { bytes: field.as_bytes(), at: 0 }; + reader.literal(b"/W")?; + reader.literal(b"[")?; + let first = reader.row()?; + let second = reader.row()?; + reader.literal(b"]")?; + skip_space(reader.bytes, &mut reader.at); + if reader.at != reader.bytes.len() { + return Err(invalid("W oracle has trailing data or additional rows")); + } + Ok([first, second]) + } + + #[test] + fn widths_use_the_mapped_subset_gid_but_are_indexed_by_cid() { + let subset = admitted_subset(); + let descriptor = synthetic_descriptor(); + let codes = [ + CodeToGlyph { code: 42, subset_gid: 2, logical: "synthetic" }, + CodeToGlyph { code: 300, subset_gid: 0, logical: "notdef" }, + ]; + let prepared = prepare(input(&subset, &codes, &descriptor)).unwrap(); + // Independent original-font integer metadata, not emitter output. + let empty_width = (569_000.0_f64 / 2048.0) as f32; + assert_eq!(prepared.default_width, 750.0); //1536*1000/2048. + assert_eq!(prepared.widths, [(42, empty_width), (300, 750.0)]); + // Subsetter compresses the repeated569 width of the two empty glyphs. + let view = MetricView::read(&subset).unwrap(); + assert_eq!(view.advance(1).unwrap(), empty_width); + assert_eq!(view.advance(2).unwrap(), empty_width); + let chunk = font_objects(refs(6), input(&subset, &codes, &descriptor)).unwrap(); + let parsed = objects(chunk.as_bytes()); + let cid = object(&parsed, 7).dict; + assert!(cid.contains("/DW 750")); + // W is the last entry of this emitted dictionary; remove ONLY its + // dictionary terminator, then parse all of W including both array levels. + let field = cid.get(cid.find("/W ").unwrap()..).unwrap() + .strip_suffix(">>").unwrap().trim_end(); + let expected = [(42, [empty_width]), (300, [750.0])]; + assert_eq!(parse_two_width_rows(field).unwrap(), expected); + // Independent literals, not emitter-generated goldens. The former + // flattened-token oracle would miss these nesting/trailing mutations. + for malformed in [ + "/W [42 277.83203125 300 750]", + "/W [42 [277.83203125] 300 [750] 999 [123]]", + "/W [42 [277.83203125] 300 [750]] 999 [123]", + "/W [42 [277.83203125] 300 [750]", + "/W [42 [277.83203125 999] 300 [750]]", + ] { + assert!(parse_two_width_rows(malformed).is_err(), "accepted malformed W: {malformed}"); + } + assert_eq!(parse_two_width_rows("/W [42 [277.83203125] 300 [750]]").unwrap(), expected); + } + + #[test] + fn invalid_code_order_gid_and_logical_clusters_refuse() { + let subset = admitted_subset(); + let descriptor = synthetic_descriptor(); + for codes in [ + vec![CodeToGlyph { code: 2, subset_gid: 3, logical: "outside" }], + vec![CodeToGlyph { code: 2, subset_gid: 1, logical: "" }], + vec![CodeToGlyph { code: 2, subset_gid: 1, logical: "a" }, CodeToGlyph { code: 2, subset_gid: 1, logical: "b" }], + vec![CodeToGlyph { code: 2, subset_gid: 1, logical: "a" }, CodeToGlyph { code: 1, subset_gid: 1, logical: "b" }], + ] { + assert!(font_objects(refs(6), input(&subset, &codes, &descriptor)).is_err()); + } + let too_long = "x".repeat(769); + let codes = [CodeToGlyph { code: 1, subset_gid: 1, logical: &too_long }]; + assert!(font_objects(refs(6), input(&subset, &codes, &descriptor)).is_err()); + let too_many_utf16 = "x".repeat(257); // Within UTF8 cap, beyond512UTF16BE bytes. + let codes = [CodeToGlyph { code: 1, subset_gid: 1, logical: &too_many_utf16 }]; + assert!(font_objects(refs(6), input(&subset, &codes, &descriptor)).is_err()); + } + + #[test] + fn essential_descriptor_fields_refuse_missing_invalid_and_underflow_values() { + let subset = admitted_subset(); + let valid = synthetic_descriptor(); + let mut missing = input(&subset, &[], &valid); + missing.descriptor = None; + assert!(font_objects(refs(6), missing).is_err()); + for case in 0..12 { + let mut descriptor = synthetic_descriptor(); + match case { + 0 => descriptor.stem_v_1000 = 0.0, + 1 => descriptor.ascent_1000 = 0.0, + 2 => descriptor.descent_1000 = 0.0, + 3 => descriptor.cap_height_1000 = -1.0, + 4 => descriptor.cap_height_1000 = 900.0, + 5 => descriptor.bbox_1000 = [0.0; 4], + 6 => descriptor.stem_v_1000 = f32::NAN, + 7 => descriptor.bbox_1000[3] = f32::INFINITY, + 8 => descriptor.ascent_1000 = MAX_METRIC + 1.0, + 9 => descriptor.italic_angle_degrees = 91.0, + 10 => descriptor.stem_v_1000 = f32::from_bits(1), + _ => descriptor.bbox_1000 = [10.0, 0.0, 0.0, 900.0], + } + assert!(font_objects(refs(6), input(&subset, &[], &descriptor)).is_err(), "synthetic case{case}"); + } + for flags in [0, 1 << 31, FontFlags::SYMBOLIC.bits() | FontFlags::NON_SYMBOLIC.bits()] { + let mut descriptor = synthetic_descriptor(); + descriptor.flags = flags; + assert!(font_objects(refs(6), input(&subset, &[], &descriptor)).is_err()); + } + } + + #[test] + fn fixed_name_tag_and_real_ref_constraints_are_explicit() { + let subset = admitted_subset(); + let descriptor = synthetic_descriptor(); + let mut wrong_name = input(&subset, &[], &descriptor); + wrong_name.postscript_name = b"OtherFont"; + assert!(font_objects(refs(6), wrong_name).is_err()); + for tag in [*b"abcDEF", *b"ABCDE ", [255; 6]] { + let mut wrong_tag = input(&subset, &[], &descriptor); + wrong_tag.subset_tag = tag; + assert!(font_objects(refs(6), wrong_tag).is_err()); + } + let mut duplicate = refs(6); + duplicate.cid_font = duplicate.type0; + assert!(font_objects(duplicate, input(&subset, &[], &descriptor)).is_err()); + assert!(font_objects(refs(1), input(&subset, &[], &descriptor)).is_err()); + let mut too_high = refs(6); + too_high.cid_to_gid = Ref::new(100_001); + assert!(font_objects(too_high, input(&subset, &[], &descriptor)).is_err()); + let mut inclusive = refs(6); + inclusive.cid_to_gid = Ref::new(100_000); + assert!(font_objects(inclusive, input(&subset, &[], &descriptor)).is_ok()); + } + + #[test] + fn preflight_byte_allowance_is_inclusive_and_actual_serialization_is_below_it() { + let subset = admitted_subset(); + let descriptor = synthetic_descriptor(); + let codes = [CodeToGlyph { code: 42, subset_gid: 1, logical: "x" }]; + let prepared = prepare(input(&subset, &codes, &descriptor)).unwrap(); + let bound = prepared.bound; // Boundary property, not a generated font golden. + let mut exact = input(&subset, &codes, &descriptor); + exact.max_chunk_bytes = bound; + let chunk = font_objects(refs(6), exact).unwrap(); + assert!(chunk.len() <= bound); + let mut short = input(&subset, &codes, &descriptor); + short.max_chunk_bytes = bound - 1; + assert!(font_objects(refs(6), short).is_err()); + let mut zero = input(&subset, &codes, &descriptor); + zero.max_chunk_bytes = 0; + assert!(font_objects(refs(6), zero).is_err()); + assert!(byte_bound(usize::MAX, 0, 0, 0).is_err()); + assert!(byte_bound(0, 0, 0, usize::MAX).is_err()); + } + + #[test] + fn repeated_complete_inputs_are_deterministic_and_leave_source_unchanged() { + let subset = admitted_subset(); + let descriptor = synthetic_descriptor(); + let source = subset.bytes().to_vec(); + let mapping = subset.mapping().to_vec(); + let codes = [CodeToGlyph { code: 10, subset_gid: 1, logical: "x" }]; + let a = font_objects(refs(6), input(&subset, &codes, &descriptor)).unwrap(); + let b = font_objects(refs(6), input(&subset, &codes, &descriptor)).unwrap(); + assert_eq!(a.as_bytes(), b.as_bytes()); + assert_eq!(source, subset.bytes()); + assert_eq!(mapping, subset.mapping()); + } + + #[test] + fn full_u16_code_space_is_inclusive_and_one_extra_record_refuses() { + let subset = admitted_subset(); + let descriptor = synthetic_descriptor(); + let mut codes: Vec<_> = (0..=u16::MAX).map(|code| CodeToGlyph { + code, subset_gid: if code == 0 { 0 } else { 1 }, logical: "x", + }).collect(); + let chunk = font_objects(refs(6), input(&subset, &codes, &descriptor)).unwrap(); + assert_eq!(chunk.refs().count(), 6); + assert!(chunk.len() <= MAX_CHUNK_BYTES); + codes.push(CodeToGlyph { code: 0, subset_gid: 0, logical: "x" }); + assert!(font_objects(refs(6), input(&subset, &codes, &descriptor)).is_err()); + } + + #[test] + fn source_derived_p3_offset_arithmetic_is_a_caller_reservation_not_a_registry() { + let subset = admitted_subset(); + let descriptor = synthetic_descriptor(); + for layers in [0, 5] { + let first = 6 + layers; + let chunk = font_objects(refs(first), input(&subset, &[], &descriptor)).unwrap(); + let ids: Vec<_> = chunk.refs().map(Ref::get).collect(); + assert_eq!(ids, (first..=first + 5).collect::>()); + assert!(ids.iter().all(|id| *id > 5 + layers)); + } + // This only checks the derived offsets with synthetic descriptors. + // The actual P3 allocator/page resource integration is NOT exercised. + } + // New ORIGINAL B1 width-provider acceptance. These are synthetic record + // contracts over the real resource, not an exactly-used Scene or shaping + // claim. Real producer + page-content acceptance remains separate. + fn b1_width_font(ids: &[(u16, u16)]) -> Font { + use solidcraft_geom::paper::text::FontGlyph; + let mut font = source_font().clone(); + font.glyphs = ids.iter().map(|&(gid, advance)| (gid, FontGlyph { advance, outline: vec![] })).collect(); + font + } + + fn input_from_b1<'a>(subset: &'a SubsetFont, codes: &'a [CodeToGlyph<'a>], descriptor: &'a DescriptorMetrics, font: &'a Font) -> FontObjectInput<'a> { + let mut result = input(subset, codes, descriptor); + result.source_font = font; + result + } + + #[test] + fn b1_widths_use_original_gid_join_and_cid_index_with_distinct_real_advances() { + let subset = subset_font(BUNDLED, 0, &[36, 3], MAX_FONT_BYTES).unwrap(); + assert_eq!(subset.mapping(), [(0, 0), (3, 1), (36, 2)]); + // Original hmtx metadata: space3=569, A36=1366, .notdef0=1536. + // A wrong font.glyphs[subset_gid] join lacks 1/2 and cannot pass. + let font = b1_width_font(&[(0, 1536), (3, 569), (36, 1366)]); + let descriptor = synthetic_descriptor(); + let codes = [ + CodeToGlyph { code: 42, subset_gid: 2, logical: "A" }, + CodeToGlyph { code: 300, subset_gid: 1, logical: " " }, + ]; + let prepared = prepare(input_from_b1(&subset, &codes, &descriptor, &font)).unwrap(); + assert_eq!(prepared.widths, [(42, (666.992_187_5_f64 as f32)), (300, (277.832_031_25_f64 as f32))]); + assert_eq!(prepared.default_width, 750.0); + let chunk = font_objects(refs(16), input_from_b1(&subset, &codes, &descriptor, &font)).unwrap(); + let parsed = objects(chunk.as_bytes()); + assert_eq!(object(&parsed, 19).stream.unwrap(), subset.bytes()); + let field = object(&parsed, 17).dict; + let field = field.get(field.find("/W ").unwrap()..).unwrap().strip_suffix(">>").unwrap().trim_end(); + assert_eq!(parse_two_width_rows(field).unwrap(), [(42, [(666.992_187_5_f64 as f32)]), (300, [(277.832_031_25_f64 as f32)])]); + let cmap = std::str::from_utf8(object(&parsed, 20).stream.unwrap()).unwrap(); + assert!(cmap.contains("<002A> <0041>") && cmap.contains("<012C> <0020>")); + } + + #[test] + fn b1_widths_keep_real_zero_advance_and_exact_intrinsic_units() { + let subset = subset_font(BUNDLED, 0, &[1], MAX_FONT_BYTES).unwrap(); + let font = b1_width_font(&[(0, 1536), (1, 0)]); // original glyph1=(0,0). + let provider = B1Widths::read(&font, &subset).unwrap(); + assert_eq!(provider.advance(1).unwrap(), 0.0); + let descriptor = synthetic_descriptor(); + let codes = [CodeToGlyph { code: 9, subset_gid: 1, logical: "zero" }]; + let result = prepare(input_from_b1(&subset, &codes, &descriptor, &font)).unwrap(); + assert_eq!(result.widths, [(9, 0.0)]); + assert_eq!(result.default_width, 750.0); + } + + #[test] + fn b1_widths_arithmetic_has_literal_zero_fraction_and_u16_envelope_oracles() { + assert_eq!(width_1000(0, 2048).unwrap(), 0.0); + assert_eq!(width_1000(569, 2048).unwrap(), (277.832_031_25_f64 as f32)); + assert_eq!(width_1000(1366, 2048).unwrap(), (666.992_187_5_f64 as f32)); + assert_eq!(width_1000(1536, 2048).unwrap(), 750.0); + assert_eq!(width_1000(u16::MAX, 16384).unwrap(), (65_535_000.0_f64 / 16384.0) as f32); + // Every valid u16 product fits u32; the checked multiply remains a guard + // against future widening. No overflow input is representable today. + assert_eq!(u32::from(u16::MAX).checked_mul(1000), Some(65_535_000)); + } + + #[test] + fn b1_widths_arithmetic_refuses_zero_and_out_of_contract_units_without_dividing() { + for units in [0, 1, 15, 16385, u16::MAX] { + assert!(width_1000(1, units).is_err(), "units={units}"); + assert!(width_1000(0, units).is_err(), "zero advance does not excuse units={units}"); + } + } + + #[test] + fn b1_widths_arithmetic_preserves_inclusive_serialized_metric_bound() { + assert_eq!(width_1000(16000, 16).unwrap(), 1_000_000.0); + assert!(width_1000(16001, 16).is_err()); + assert!(width_1000(u16::MAX, 16).is_err()); + // B1 fields are u16, so NaN/Infinity cannot enter this arithmetic. + // The original descriptor hostile-float cases remain unchanged. + } + + #[test] + fn b1_widths_missing_original_advance_refuses_without_subset_metric_fallback() { + let subset = subset_font(BUNDLED, 0, &[36], MAX_FONT_BYTES).unwrap(); + let font = b1_width_font(&[(0, 1536)]); + let provider = B1Widths::read(&font, &subset).unwrap(); + let e = provider.advance(1).unwrap_err().to_string(); + assert!(e.contains("lacks an intrinsic width for an emitted original glyph"), "{e}"); + let descriptor = synthetic_descriptor(); + let codes = [CodeToGlyph { code: 5, subset_gid: 1, logical: "A" }]; + assert!(font_objects(refs(6), input_from_b1(&subset, &codes, &descriptor, &font)).is_err()); + } + + #[test] + fn b1_widths_unemitted_closure_glyphs_do_not_require_invented_b1_entries() { + let subset = subset_font(BUNDLED, 0, &[3, 36], MAX_FONT_BYTES).unwrap(); + // Original36 is embedded but no code emits it. No width lookup for it. + let font = b1_width_font(&[(0, 1536), (3, 569)]); + let descriptor = synthetic_descriptor(); + let codes = [CodeToGlyph { code: 5, subset_gid: 1, logical: " " }]; + let prepared = prepare(input_from_b1(&subset, &codes, &descriptor, &font)).unwrap(); + assert_eq!(prepared.widths, [(5, (277.832_031_25_f64 as f32))]); + assert_eq!(prepared.font, subset.bytes()); + } + + #[test] + fn b1_widths_omitted_notdef_still_plans_used_width_but_blocks_default_policy() { + let subset = subset_font(BUNDLED, 0, &[36], MAX_FONT_BYTES).unwrap(); + let font = b1_width_font(&[(36, 1366)]); + let provider = B1Widths::read(&font, &subset).unwrap(); + assert_eq!(provider.advance(1).unwrap(), (666.992_187_5_f64 as f32)); + let e = provider.default_width().unwrap_err().to_string(); + assert!(e.contains("glyph zero is absent; PDF default-width policy is unresolved"), "{e}"); + let descriptor = synthetic_descriptor(); + let codes = [CodeToGlyph { code: 1, subset_gid: 1, logical: "A" }]; + let e = match font_objects(refs(6), input_from_b1(&subset, &codes, &descriptor, &font)) { + Ok(_) => panic!("emitted font objects without an agreed default-width source"), + Err(e) => e.to_string(), + }; + assert!(e.contains("default-width policy is unresolved"), "{e}"); + // A caller cannot bypass the unresolved policy by emitting no codes. + assert!(font_objects(refs(6), input_from_b1(&subset, &[], &descriptor, &font)).is_err()); + assert!(!font.glyphs.contains_key(&0)); + } + + #[test] + fn b1_widths_raw_digest_cannot_replace_b1_bytes_plus_face_identity() { + let subset = admitted_subset(); + let mut font = source_font().clone(); + let raw: [u8; 32] = Sha256::digest(BUNDLED).into(); + assert_ne!(raw, font.id); + font.id = raw; + assert!(B1Widths::read(&font, &subset).is_err()); + font = source_font().clone(); + font.id[0] ^= 1; + assert!(B1Widths::read(&font, &subset).is_err()); + let mut changed = BUNDLED.to_vec(); + changed[4096] ^= 1; + font.bytes = std::sync::Arc::from(changed); + font.id = Sha256::new().chain_update(font.bytes.as_ref()).chain_update(0u32.to_le_bytes()).finalize().into(); + assert!(B1Widths::read(&font, &subset).is_err(), "internally matching id is not resource admission"); + } + + #[test] + fn b1_widths_byte_envelope_refuses_before_identity_work() { + let subset = admitted_subset(); + for length in [0, 410819, 410821] { + let mut font = source_font().clone(); + font.bytes = std::sync::Arc::from(vec![0u8; length]); + font.id = [0; 32]; + let e = match B1Widths::read(&font, &subset) { + Ok(_) => panic!("accepted length {length}"), + Err(e) => e.to_string(), + }; + assert!(e.contains("byte envelope differs"), "{length}: {e}"); + } + // This checks the observable refusal reason and source order, not a + // runtime timing guarantee or a digest-call counter. + } + + #[test] + fn b1_widths_fixed_face_upem_glyph_count_and_used_id_caps_stay_closed() { + let subset = admitted_subset(); + for case in 0..7 { + let mut font = source_font().clone(); + match case { + 0 => font.face = 1, + 1 => font.bundled = 1, + 2 => font.units_per_em = 0, + 3 => font.units_per_em = 1024, + 4 => font.num_glyphs = 0, + 5 => font.postscript_name = "other".into(), + _ => { font.glyphs.insert(2620, solidcraft_geom::paper::text::FontGlyph { advance: 1, outline: vec![] }); } + } + assert!(B1Widths::read(&font, &subset).is_err(), "case={case}"); + } + } + + #[test] + fn b1_widths_missing_subset_ids_refuse_even_when_b1_has_other_widths() { + let subset = admitted_subset(); + let provider = B1Widths::read(source_font(), &subset).unwrap(); + for gid in [3, u16::MAX] { + assert!(provider.advance(gid).is_err(), "subset GID {gid}"); + } + } + + #[test] + fn b1_widths_binding_and_emission_leave_source_records_program_and_mapping_unchanged() { + let subset = admitted_subset(); + let font = source_font().clone(); + let before_font = font.clone(); + let before_bytes = subset.bytes().to_vec(); + let before_mapping = subset.mapping().to_vec(); + let descriptor = synthetic_descriptor(); + let codes = [ + CodeToGlyph { code: 42, subset_gid: 2, logical: "alias1" }, + CodeToGlyph { code: 300, subset_gid: 2, logical: "alias2" }, + ]; + let a = font_objects(refs(6), input_from_b1(&subset, &codes, &descriptor, &font)).unwrap(); + let b = font_objects(refs(6), input_from_b1(&subset, &codes, &descriptor, &font)).unwrap(); + assert_eq!(a.as_bytes(), b.as_bytes()); + assert_eq!(font, before_font); + assert_eq!(subset.bytes(), before_bytes); + assert_eq!(subset.mapping(), before_mapping); + let prepared = prepare(input_from_b1(&subset, &codes, &descriptor, &font)).unwrap(); + assert_eq!(prepared.widths, [(42, (277.832_031_25_f64 as f32)), (300, (277.832_031_25_f64 as f32))]); + } + +} + + diff --git a/proposals/drawings/2026-10-30/F0-textplan-fontobjects/before/canonical/crates/io/src/paper/pdf/text_plan.rs b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/before/canonical/crates/io/src/paper/pdf/text_plan.rs new file mode 100644 index 000000000..f26754d9d --- /dev/null +++ b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/before/canonical/crates/io/src/paper/pdf/text_plan.rs @@ -0,0 +1,335 @@ +//! Bounded PDF planning from the actual B1a Font/TextRun records (#4890 P2). +//! +//! This neither shapes text nor writes a page. It keeps intrinsic hmtx widths +//! separate from the producer's placed glyph x/rise/advance. One glyph per logical +//! cluster is supported, including a glyph carrying several characters; a +//! multi-glyph cluster is refused until its extraction/content policy is supplied. +//! The ToUnicode destination limit stays 512 UTF-16BE bytes, not a silent split. +//! +//! Plans retain no new font/document Arc: strings/font records are borrowed. +//! Local vector storage and returned subset bytes have separate allowances. The +//! existing subsetter/pdf-writer internal allocation limitations still apply. +//! No parent registration, global PDF Ref allocator, page resource or text arm is +//! introduced here. The parent must preserve the planned placements and reading +//! order and qualify real PDF rendering/extraction; these records prove neither. + +use std::mem::size_of; +use std::ops::Range; + +use pdf_writer::types::FontFlags; +use sha2::{Digest, Sha256}; +use solidcraft_geom::paper::text::{Font, TextRun}; +use solidcraft_geom::paper::MAX_COORDINATE_MM; + +use super::font_objects::{CodeToGlyph, DescriptorMetrics, FontObjectInput}; +use super::subset_font::{SubsetFont, subset_font}; +use crate::{IoError, Result}; + +const MAX_RUNS: usize = 1024; +const MAX_GLYPHS: usize = 16_384; +const MAX_PLAN_BYTES: usize = 16 << 20; +const MAX_LOGICAL_BYTES: usize = 4 << 20; +const MAX_CLUSTER_BYTES: usize = 768; +const MAX_CLUSTER_UNITS: usize = 256; +const APPROVED_FONT_BYTES: usize = 410_820; + +/// One actual glyph, with a code for its original GID AND literal logical text. +/// The matrix has unit basis vectors and a translation in sheet millimetres; +/// font_size_mm is on its run. Parent applies its mm-to-point scale only once. +pub(super) struct PlannedGlyph<'a> { + pub(super) code: u16, + pub(super) original_gid: u16, + pub(super) source_glyph_index: usize, + pub(super) intrinsic_advance_fu: u16, + pub(super) placed_advance_mm: f64, + pub(super) matrix_mm: [f64; 6], + pub(super) logical: &'a str, +} + +/// Glyphs occupy one contiguous range in the plan, in logical reading order. +/// For an RTL run their SOURCE indices descend; positions are never recomputed +/// from font widths. Input run order remains unchanged. +pub(super) struct PlannedRun<'a> { + pub(super) glyphs: Range, + pub(super) font_size_mm: f64, + pub(super) rtl: bool, + pub(super) text: &'a str, +} + +pub(super) struct TextPlan<'a> { + font: &'a Font, + subset: SubsetFont, + descriptor: DescriptorMetrics, + codes: Vec>, + runs: Vec>, + glyphs: Vec>, +} + +impl TextPlan<'_> { + pub(super) fn runs(&self) -> &[PlannedRun<'_>] { + &self.runs + } + + pub(super) fn glyphs(&self) -> &[PlannedGlyph<'_>] { + &self.glyphs + } + + /// Caller still supplies six globally reserved refs to font_objects, a + /// globally unique subset tag, page resources and a cumulative output budget. + pub(super) fn font_input(&self, subset_tag: [u8; 6], max_chunk_bytes: usize) -> FontObjectInput<'_> { + FontObjectInput { + source_font: self.font, + subset: &self.subset, + codes: &self.codes, + descriptor: Some(&self.descriptor), + postscript_name: self.font.postscript_name.as_bytes(), + subset_tag, + max_chunk_bytes, + } + } +} + +fn invalid(message: &'static str) -> IoError { + IoError::Invalid(format!("PDF text plan: {message}")) +} + +fn reserve(count: usize) -> Result> { + let mut values = Vec::new(); + values.try_reserve_exact(count).map_err(|_| invalid("cannot allocate bounded plan storage"))?; + Ok(values) +} + +fn bytes(count: usize) -> Result { + count.checked_mul(size_of::()).ok_or_else(|| invalid("plan storage overflow")) +} + +fn total(parts: &[usize], limit: usize) -> Result { + parts.iter().try_fold(0usize, |n, part| { + n.checked_add(*part).filter(|n| *n <= limit).ok_or_else(|| invalid("plan storage allowance exceeded")) + }) +} + +fn u16_at(bytes: &[u8], at: usize) -> Result { + let end = at.checked_add(2).ok_or_else(|| invalid("font table range overflow"))?; + let value = bytes.get(at..end).and_then(|b| b.try_into().ok()).ok_or_else(|| invalid("truncated admitted font table"))?; + Ok(u16::from_be_bytes(value)) +} + +fn u32_at(bytes: &[u8], at: usize) -> Result { + let end = at.checked_add(4).ok_or_else(|| invalid("font table range overflow"))?; + let value = bytes.get(at..end).and_then(|b| b.try_into().ok()).ok_or_else(|| invalid("truncated admitted font table"))?; + Ok(u32::from_be_bytes(value)) +} + +/// A bounded original hmtx view, not a general font parser. The subset adapter +/// performs the existing exact-resource/embedding admission before plan return. +fn table<'a>(bytes: &'a [u8], tag: &[u8; 4]) -> Result<&'a [u8]> { + let count = usize::from(u16_at(bytes, 4)?); + if count == 0 || count > 19 { + return Err(invalid("font directory exceeds the reviewed resource")); + } + let mut found = None; + for i in 0..count { + let at = 12 + 16 * i; + if bytes.get(at..at + 4) != Some(tag) { + continue; + } + if found.is_some() { + return Err(invalid("duplicate font table")); + } + let start = usize::try_from(u32_at(bytes, at + 8)?).map_err(|_| invalid("font offset exceeds the platform"))?; + let length = usize::try_from(u32_at(bytes, at + 12)?).map_err(|_| invalid("font length exceeds the platform"))?; + let end = start.checked_add(length).ok_or_else(|| invalid("font table range overflow"))?; + found = bytes.get(start..end); + if found.is_none() { + return Err(invalid("font table is outside its bytes")); + } + } + found.ok_or_else(|| invalid("required font table is absent")) +} + +fn intrinsic_advance(font: &Font, gid: u16) -> Result { + if gid >= font.num_glyphs { + return Err(invalid("glyph is outside the admitted font")); + } + let count = usize::from(u16_at(table(&font.bytes, b"hhea")?, 34)?); + if count == 0 || count > usize::from(font.num_glyphs) { + return Err(invalid("invalid hmtx metric count")); + } + u16_at(table(&font.bytes, b"hmtx")?, usize::from(gid).min(count - 1) * 4) +} + +fn descriptor(font: &Font) -> Result { + // Public Font is hostile input too. Refuse its cheap byte envelope before + // hashing or looking through tables, even when the caller's plan budget is tiny. + if font.bytes.len() != APPROVED_FONT_BYTES { + return Err(invalid("font byte length is outside the reviewed resource envelope")); + } + // B1 hashes bytes + faceLE. The existing subset admission hashes RAW bytes; + // their digests are different identities and are never compared to each other. + let m = &font.metrics; + // Original fixed-resource metadata, not fitted/default descriptor values. + // Values come from this exact Liberation Sans head/hhea/OS2/post and l glyph. + if font.bundled != 0 || font.face != 0 || font.postscript_name != "LiberationSans" + || font.num_glyphs != 2620 || font.units_per_em != 2048 + || m.bbox != [-1114, -621, 2666, 2007] || m.ascent != 1854 || m.descent != -434 + || m.cap_height != 1409 || m.stem_v != 180 || m.italic_angle != 0.0 + || m.flags.fixed_pitch || m.flags.serif || m.flags.italic || m.flags.symbolic + { + return Err(invalid("B1 font identity or metrics differ from the reviewed regular bundled face")); + } + let identity: [u8; 32] = Sha256::new().chain_update(font.bytes.as_ref()).chain_update(font.face.to_le_bytes()).finalize().into(); + if font.id != identity { + return Err(invalid("B1 bytes-and-face identity does not match its supplied bytes")); + } + let k = 1000.0 / f32::from(font.units_per_em); + Ok(DescriptorMetrics { + bbox_1000: m.bbox.map(|n| f32::from(n) * k), + ascent_1000: f32::from(m.ascent) * k, + descent_1000: f32::from(m.descent) * k, + cap_height_1000: f32::from(m.cap_height) * k, + italic_angle_degrees: m.italic_angle as f32, + stem_v_1000: f32::from(m.stem_v) * k, + flags: FontFlags::NON_SYMBOLIC.bits(), + }) +} + +/// Check the actual B1 cluster partition and the narrower first P2 contract +/// BEFORE allocating or subsetting. Returning an error exposes no partial plan. +fn check_run(font: &Font, run: &TextRun) -> Result { + if run.font != font.bundled || !(1..=4000).contains(&run.glyphs.len()) || run.text.len() > 4000 { + return Err(invalid("run font, glyph count or text length is outside B1")); + } + let cap = run.scale * f64::from(font.metrics.cap_height); + let within = |x: f64| x.is_finite() && x.abs() <= MAX_COORDINATE_MM; + if !run.scale.is_finite() || !(1e-6..1e6).contains(&cap) || cap == 1e-6 + || !within(run.origin.x) || !within(run.origin.y) + || !run.angle.is_finite() || run.angle.abs() > std::f64::consts::TAU + || !run.slant.is_finite() || run.slant.abs() > 1.0 + { + return Err(invalid("run transform is outside B1")); + } + let mut glyph_end = 0usize; + let mut text_end = if run.rtl { run.text.len() } else { 0 }; + for cluster in &run.clusters { + let (g0, g1, t0, t1) = ( + cluster.glyphs.start as usize, cluster.glyphs.end as usize, + cluster.text.start as usize, cluster.text.end as usize, + ); + if g0 != glyph_end || g0 >= g1 || t0 >= t1 || (if run.rtl { t1 != text_end } else { t0 != text_end }) { + return Err(invalid("clusters do not partition glyphs and logical text in B1 order")); + } + if g1 - g0 != 1 { + return Err(invalid("multi-glyph cluster extraction is not supported by this text-plan increment")); + } + let logical = run.text.get(t0..t1).ok_or_else(|| invalid("cluster text is not whole UTF-8 characters"))?; + if logical.len() > MAX_CLUSTER_BYTES || logical.encode_utf16().take(MAX_CLUSTER_UNITS + 1).count() > MAX_CLUSTER_UNITS { + return Err(invalid("cluster exceeds the existing ToUnicode 512-byte destination contract")); + } + let glyph = run.glyphs.get(g0).ok_or_else(|| invalid("cluster glyph is outside the run"))?; + if ![glyph.x, glyph.rise, glyph.advance].into_iter().all(within) { + return Err(invalid("placed glyph is outside B1 coordinates")); + } + let intrinsic = font.glyphs.get(&glyph.id).ok_or_else(|| invalid("glyph is absent from the B1 font table"))?; + if intrinsic.advance != intrinsic_advance(font, glyph.id)? { + return Err(invalid("B1 intrinsic advance does not match the admitted hmtx")); + } + glyph_end = g1; + text_end = if run.rtl { t0 } else { t1 }; + } + if glyph_end != run.glyphs.len() || text_end != if run.rtl { 0 } else { run.text.len() } { + return Err(invalid("clusters do not cover the whole run exactly once")); + } + Ok(run.glyphs.len()) +} + +/// One bundled font and ALL its runs, in their existing paint order. Code keys +/// are sorted (original GID, literal text), so iteration/export repetition cannot +/// change their allocation. Code zero stays reserved for .notdef, not user text. +pub(super) fn plan_text<'a>(font: &'a Font, runs: &[&'a TextRun], max_plan_bytes: usize, max_subset_bytes: usize) -> Result> { + let limit = max_plan_bytes.min(MAX_PLAN_BYTES); + if limit == 0 || max_subset_bytes == 0 || runs.is_empty() || runs.len() > MAX_RUNS { + return Err(invalid("empty allowance or unsupported run count")); + } + let descriptor = descriptor(font)?; + let mut count = 0usize; + let mut logical_bytes = 0usize; + for run in runs { + count = count.checked_add(check_run(font, run)?).filter(|n| *n <= MAX_GLYPHS) + .ok_or_else(|| invalid("combined glyph count exceeds 16384"))?; + logical_bytes = logical_bytes.checked_add(run.text.len()).filter(|n| *n <= MAX_LOGICAL_BYTES) + .ok_or_else(|| invalid("combined logical text exceeds its allowance"))?; + } + total(&[ + bytes::<(u16, &str)>(count)?, bytes::(count)?, bytes::>(count)?, + bytes::>(count)?, bytes::>(runs.len())?, + ], limit)?; + let mut keys = reserve::<(u16, &str)>(count)?; + let mut used = reserve::(count)?; + let mut codes = reserve::>(count)?; + let mut planned_runs = reserve::>(runs.len())?; + let mut glyphs = reserve::>(count)?; + total(&[ + bytes::<(u16, &str)>(keys.capacity())?, bytes::(used.capacity())?, bytes::>(codes.capacity())?, + bytes::>(glyphs.capacity())?, bytes::>(planned_runs.capacity())?, + ], limit)?; + for run in runs { + for cluster in &run.clusters { + let glyph = run.glyphs.get(cluster.glyphs.start as usize).ok_or_else(|| invalid("checked glyph disappeared"))?; + if glyph.id == 0 { + return Err(invalid(".notdef cannot replace a missing text glyph")); + } + let logical = run.text.get(cluster.text.start as usize..cluster.text.end as usize).ok_or_else(|| invalid("checked text disappeared"))?; + keys.push((glyph.id, logical)); + } + } + keys.sort_unstable(); + keys.dedup(); + for (gid, _) in &keys { + if used.last() != Some(gid) { + used.push(*gid); + } + } + if !font.glyphs.keys().copied().eq(used.iter().copied()) { + return Err(invalid("the font table is not exactly the glyphs of the supplied runs")); + } + // Reuse the real existing admission, composite closure and subset library. + // There is no duplicate raw-font admission hash or copied font implementation. + let subset = subset_font(&font.bytes, font.face, &used, max_subset_bytes)?; + for (index, (gid, logical)) in keys.iter().enumerate() { + let code = u16::try_from(index + 1).map_err(|_| invalid("text codes exceed u16"))?; + let at = subset.mapping().binary_search_by_key(gid, |(old, _)| *old).map_err(|_| invalid("subset lost an original glyph"))?; + let (_, subset_gid) = subset.mapping().get(at).ok_or_else(|| invalid("subset mapping is incomplete"))?; + codes.push(CodeToGlyph { code, subset_gid: *subset_gid, logical }); + } + for run in runs { + let first = glyphs.len(); + let (sin, cos) = run.angle.sin_cos(); + for logical_index in 0..run.clusters.len() { + let at = if run.rtl { run.clusters.len() - 1 - logical_index } else { logical_index }; + let cluster = run.clusters.get(at).ok_or_else(|| invalid("checked cluster disappeared"))?; + let source = cluster.glyphs.start as usize; + let glyph = run.glyphs.get(source).ok_or_else(|| invalid("checked glyph disappeared"))?; + let logical = run.text.get(cluster.text.start as usize..cluster.text.end as usize).ok_or_else(|| invalid("checked text disappeared"))?; + let key = keys.binary_search(&(glyph.id, logical)).map_err(|_| invalid("text code is absent"))?; + let code = codes.get(key).ok_or_else(|| invalid("text code is outside its table"))?.code; + let matrix_mm = [ + cos, sin, cos * run.slant - sin, sin * run.slant + cos, + run.origin.x + cos * glyph.x - sin * glyph.rise, + run.origin.y + sin * glyph.x + cos * glyph.rise, + ]; + if !matrix_mm.iter().all(|n| n.is_finite()) { + return Err(invalid("glyph transform is not finite")); + } + glyphs.push(PlannedGlyph { + code, original_gid: glyph.id, source_glyph_index: source, + intrinsic_advance_fu: intrinsic_advance(font, glyph.id)?, placed_advance_mm: glyph.advance, + matrix_mm, logical, + }); + } + planned_runs.push(PlannedRun { + glyphs: first..glyphs.len(), font_size_mm: run.scale * f64::from(font.units_per_em), rtl: run.rtl, text: &run.text, + }); + } + Ok(TextPlan { font, subset, descriptor, codes, runs: planned_runs, glyphs }) +} diff --git a/proposals/drawings/2026-10-30/F0-textplan-fontobjects/candidate/crates/io/src/paper/pdf/font_objects.rs b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/candidate/crates/io/src/paper/pdf/font_objects.rs new file mode 100644 index 000000000..ae4de4207 --- /dev/null +++ b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/candidate/crates/io/src/paper/pdf/font_objects.rs @@ -0,0 +1,1219 @@ +//! Private PDF font resources for one admitted subset; no B1 or content writer. +//! +//! Identity-H explicitly maps two-byte codes to CIDs. A separate stream maps +//! CIDs to subset GIDs; logical text remains keyed by code in real ToUnicode. +//! W widths come from actual B1 original-GID advances, never subset hmtx. +//! Missing B1 glyph-zero metrics explicitly block the old DW path. +//! Descriptor metrics must come from the SAME admitted source font. Numeric +//! validation does not prove that provenance, and no metrics are estimated. +//! +//! pdf-writer 0.15.0 allocates internally without fallible allocation controls. +//! This returns a local Chunk, never mutating a caller-owned Pdf on Result errors. +//! A later extend has no rollback or OOM guarantee. Caller owns global Ref/tag +//! reservations, page resources, content, positioning and document budgets. + +use pdf_writer::types::{CidFontType, FontFlags, SystemInfo}; +use pdf_writer::{Chunk, Name, Rect, Ref, Str}; + +use solidcraft_geom::paper::text::Font; + +use super::subset_font::SubsetFont; +use super::text_plan::{FontPlanView, check_builtin_source}; +use super::to_unicode::write_to_unicode; +use crate::{IoError, MAX_DRAWING_BYTES, Result}; + +const MAX_REFS_ID: i32 = 100_000; +const MAX_CODES: usize = 65_536; +const MAX_GLYPHS: usize = 16_384; +const MAX_FONT_BYTES: usize = 410_820; +const MAX_MAP_BYTES: usize = 131_072; +const MAX_UTF8_BYTES: usize = 4 << 20; +const MAX_CLUSTER_BYTES: usize = 768; +const MAX_CHUNK_BYTES: usize = 16 << 20; +const MAX_METRIC: f32 = 1_000_000.0; +const ROW_BYTES: usize = 128; +const FIXED_BYTES: usize = 32 << 10; +const POSTSCRIPT_NAME: &[u8] = b"LiberationSans"; + +/// Six already reserved real references. Local validation cannot reserve them +/// globally or discover collisions with future P3/font objects. +pub(super) struct FontObjectRefs { + pub(super) type0: Ref, + pub(super) cid_font: Ref, + pub(super) descriptor: Ref, + pub(super) font_file2: Ref, + pub(super) to_unicode: Ref, + pub(super) cid_to_gid: Ref, +} + +impl FontObjectRefs { + fn all(&self) -> [Ref; 6] { + [self.type0, self.cid_font, self.descriptor, self.font_file2, self.to_unicode, self.cid_to_gid] + } + + fn validate(&self) -> Result<()> { + let ids = self.all(); + for (index, id) in ids.iter().enumerate() { + if !(6..=MAX_REFS_ID).contains(&id.get()) || ids.iter().take(index).any(|prior| prior == id) { + return Err(invalid("font object references must be distinct, outside core 1..5, and at most 100000")); + } + } + Ok(()) + } +} + +/// Reserve the next six font objects from the ACTUAL many-page parent Refs. +/// This is a private pure seam; it neither writes a Pdf nor invents a parallel +/// document allocator, subset tag or page-resource entry. The parent retains +/// its catalog/pages/Info/layers window and calls this after its reservations. +/// Failed local validation/overflow leaves the parent's cursor unchanged. +pub(super) fn reserve_font_refs(refs: &mut super::Refs) -> Result { + if refs.0 <= 0 { + return Err(invalid("font object allocator must start at a positive object number")); + } + // Refs has no Clone API at this pinned revision. A local staging cursor of + // that SAME real type makes the six-number reservation all-or-nothing. + // No fabricated Ref::new arithmetic duplicates the parent's next() policy. + let mut staged = super::Refs(refs.0); + let reserved = FontObjectRefs { + type0: staged.next()?, + cid_font: staged.next()?, + descriptor: staged.next()?, + font_file2: staged.next()?, + to_unicode: staged.next()?, + cid_to_gid: staged.next()?, + }; + // Reuse this helper's existing distinct/core/range policy, rather than + // duplicating its 100000 cap in a second allocator or skipping it. + reserved.validate()?; + *refs = staged; + Ok(reserved) +} + +/// A caller-assigned two-byte code, interpreted as a CID by Identity-H. +/// Neither code nor logical text is inferred from subset_gid. +pub(super) struct CodeToGlyph<'a> { + pub(super) code: u16, + pub(super) subset_gid: u16, + pub(super) logical: &'a str, +} + +/// Explicit PDF descriptor values, not an existing B1/provider record. +/// Lengths use 1000-unit glyph space; italic angle uses degrees. +/// Caller supplies faithful source metrics; no StemV/ascent defaults exist here. +pub(super) struct DescriptorMetrics { + pub(super) bbox_1000: [f32; 4], + pub(super) ascent_1000: f32, + pub(super) descent_1000: f32, + pub(super) cap_height_1000: f32, + pub(super) italic_angle_degrees: f32, + pub(super) stem_v_1000: f32, + pub(super) flags: u32, +} + +impl DescriptorMetrics { + fn validate(&self) -> Result { + let numbers = [ + self.ascent_1000, self.descent_1000, self.cap_height_1000, + self.italic_angle_degrees, self.stem_v_1000, + ]; + if self.bbox_1000.iter().chain(numbers.iter()).any(|n| { + !n.is_finite() || n.abs() > MAX_METRIC || (*n != 0.0 && n.abs() < f32::MIN_POSITIVE) + }) { + return Err(invalid("font descriptor numbers must be finite and bounded")); + } + let [left, bottom, right, top] = self.bbox_1000; + if left >= right || bottom >= top || self.ascent_1000 <= 0.0 + || self.descent_1000 >= 0.0 || self.cap_height_1000 <= 0.0 + || self.cap_height_1000 > self.ascent_1000 || self.stem_v_1000 <= 0.0 + || self.italic_angle_degrees.abs() > 90.0 + { + return Err(invalid("font descriptor has invalid bounds, signs, cap height or stem")); + } + let flags = FontFlags::from_bits(self.flags).ok_or_else(|| invalid("font descriptor contains reserved flags"))?; + let symbolic = flags.contains(FontFlags::SYMBOLIC); + let nonsymbolic = flags.contains(FontFlags::NON_SYMBOLIC); + if symbolic == nonsymbolic { + return Err(invalid("font descriptor must select exactly one Symbolic or Nonsymbolic flag")); + } + Ok(flags) + } +} + +/// Production parameters: the source, subset, descriptor and codes are bound +/// by an opaque view obtainable only from a successful TextPlan. +pub(super) struct FontObjectInput<'a> { + pub(super) source: FontPlanView<'a>, + pub(super) subset_tag: [u8; 6], + pub(super) max_chunk_bytes: usize, +} + +/// Internal preparation components, never an independently callable production +/// input. Component tests below retain their synthetic scope via private aliases. +struct FontObjectParts<'a> { + source_font: &'a Font, + subset: &'a SubsetFont, + codes: &'a [CodeToGlyph<'a>], + descriptor: Option<&'a DescriptorMetrics>, + postscript_name: &'a [u8], + subset_tag: [u8; 6], + max_chunk_bytes: usize, +} + +fn invalid(message: &'static str) -> IoError { + IoError::Invalid(message.into()) +} + +/// One identity-bound B1 width provider over an immutable, already validated +/// subset artifact. No font tables are read here: original FontGlyph advances +/// are the sole W authority; subset IDs are joined back to ORIGINAL GIDs. +struct B1Widths<'a> { + font: &'a Font, + subset: &'a SubsetFont, +} + +// Identity of the exact already admitted regular resource, with face 0 LE +// appended as B1b does. This is not the different raw-resource SHA256. +const REVIEWED_B1_ID: [u8; 32] = [ + 0xaf, 0x02, 0xdb, 0xc8, 0x83, 0x9b, 0x7c, 0xad, + 0xae, 0x15, 0xe5, 0x28, 0xaa, 0x3d, 0x9f, 0xf8, + 0x5c, 0x54, 0x5b, 0x71, 0x5b, 0x55, 0x1d, 0x21, + 0x8b, 0xf3, 0x8a, 0x93, 0x7e, 0xe7, 0xe2, 0xb0, +]; + +/// Numeric conversion only: no shaping, placed advance, default or font parse. +/// u16 inputs cannot encode NaN/Infinity. Still check the division and f32 +/// serialization envelope explicitly; the integer product is checked too. +fn width_1000(advance: u16, units_per_em: u16) -> Result { + if !(16..=16384).contains(&units_per_em) { + return Err(invalid("B1 font units per em are outside 16..16384")); + } + let numerator = u32::from(advance).checked_mul(1000) + .ok_or_else(|| invalid("B1 intrinsic width product overflow"))?; + let value = f64::from(numerator) / f64::from(units_per_em); + let width = value as f32; + if !value.is_finite() || !width.is_finite() || width.abs() > MAX_METRIC + || (width != 0.0 && width.abs() < f32::MIN_POSITIVE) + { + return Err(invalid("PDF B1 glyph width is not finite and bounded")); + } + Ok(width) +} + +impl<'a> B1Widths<'a> { + fn read(font: &'a Font, subset: &'a SubsetFont) -> Result { + // Public B1 fields are bounded before digest, table walks or allocation. + // Production obtains these bound records only through FontPlanView; + // TextPlan already checked every used original-GID advance and the + // single admitted subset chain. These repeated cheap identity/mapping + // guards also retain the independent synthetic component-test scope. + if font.bytes.len() != MAX_FONT_BYTES { + return Err(invalid("B1 font byte envelope differs from the reviewed resource")); + } + if font.face != 0 || font.postscript_name.as_bytes() != POSTSCRIPT_NAME + || font.num_glyphs != 2620 || font.units_per_em != 2048 + || font.glyphs.len() > usize::from(font.num_glyphs) + || font.glyphs.keys().any(|gid| *gid >= font.num_glyphs) + { + return Err(invalid("B1 font metadata differs from the reviewed regular face")); + } + // Exact current builtin bytes/face replace the removed numeric index. + // The plan already checked bytes+face ID and admitted the SAME source + // through subset_font. Compare the fixed B1 ID here without rehashing. + check_builtin_source(font)?; + if font.id != REVIEWED_B1_ID { + return Err(invalid("B1 font bytes/face/id do not identify the reviewed resource")); + } + let glyphs = subset.mapping().len(); + if glyphs == 0 || glyphs > MAX_GLYPHS || subset.bytes().is_empty() + || subset.bytes().len() > MAX_FONT_BYTES + { + return Err(invalid("font subset exceeds the admitted fixed-resource contract")); + } + // Preserve the old non-parser mapping guards. The immutable factory's + // check_subset_program still validates maxp/head/hhea/hmtx structure. + let mut previous = None; + for (expected, &(old, new)) in subset.mapping().iter().enumerate() { + if previous.is_some_and(|prior| old <= prior) || usize::from(new) != expected + || old >= font.num_glyphs || (expected == 0 && old != 0) + { + return Err(invalid("font subset mapping is not original-zero ordered and dense")); + } + previous = Some(old); + } + Ok(Self { font, subset }) + } + + fn advance(&self, subset_gid: u16) -> Result { + let &(original_gid, mapped) = self.subset.mapping().get(usize::from(subset_gid)) + .ok_or_else(|| invalid("PDF code maps outside the subset glyph range"))?; + if mapped != subset_gid { + return Err(invalid("PDF subset glyph does not match its original-GID mapping")); + } + let glyph = self.font.glyphs.get(&original_gid) + .ok_or_else(|| invalid("B1 font lacks an intrinsic width for an emitted original glyph"))?; + width_1000(glyph.advance, self.font.units_per_em) + } + + fn default_width(&self) -> Result { + // No extra .notdef record is invented and no width is parsed from the + // subset. Preserve the old explicit DW path ONLY if actual B1 owns GID0. + // Most exactly-used B1 tables omit it: those callers refuse until an + // owner-agreed DW/full-emitted-CID-coverage policy is implemented. + let glyph = self.font.glyphs.get(&0) + .ok_or_else(|| invalid("B1 glyph zero is absent; PDF default-width policy is unresolved"))?; + width_1000(glyph.advance, self.font.units_per_em) + } +} + +fn fixed_font_name(name: &[u8], tag: [u8; 6]) -> Result<[u8; 21]> { + if name != POSTSCRIPT_NAME || !tag.iter().all(u8::is_ascii_uppercase) { + return Err(invalid("PDF font requires LiberationSans and a caller-supplied six-uppercase subset tag")); + } + let mut result = *b"AAAAAA+LiberationSans"; + for (slot, byte) in result.iter_mut().take(6).zip(tag) { + *slot = byte; + } + Ok(result) +} + +/// Conservative byte bound for this exact six-object call sequence/settings. +/// W rows: at most 5 CID digits + 64 finite-f32 bytes + punctuation/spaces < 128. +/// Fixed dictionaries/three streams: 31 pairs including nested SystemInfo, +/// keys <= 16, scalar/name/ref tokens <= 64, bbox value < 262. Each fixed +/// pair costs < 512 bytes; all headers/trailers < 4096. Thus fixed bytes +/// < 31*512+4096 = 19968 < 32768, excluding W rows and raw stream payloads. +/// Stream payload bytes are counted separately, exactly once each in Chunk. +/// This bounds serialized bytes, not Vec capacity, transient memory or OOM. +fn byte_bound(font: usize, cmap: usize, map: usize, rows: usize) -> Result { + rows.checked_mul(ROW_BYTES).and_then(|n| n.checked_add(FIXED_BYTES)) + .and_then(|n| n.checked_add(font)).and_then(|n| n.checked_add(cmap)) + .and_then(|n| n.checked_add(map)).ok_or_else(|| invalid("font object byte budget overflow")) +} + +struct Prepared<'a> { + font: &'a [u8], + unicode: Vec, + cid_map: Vec, + widths: Vec<(u16, f32)>, + default_width: f32, + name: [u8; 21], + descriptor: &'a DescriptorMetrics, + flags: FontFlags, + limit: usize, + bound: usize, +} + +fn prepare(input: FontObjectParts<'_>) -> Result> { + let descriptor = input.descriptor.ok_or_else(|| invalid("essential font descriptor metrics are missing"))?; + let flags = descriptor.validate()?; + let name = fixed_font_name(input.postscript_name, input.subset_tag)?; + if input.codes.len() > MAX_CODES { + return Err(invalid("PDF font code count exceeds 65536")); + } + let metrics = B1Widths::read(input.source_font, input.subset)?; + let default_width = metrics.default_width()?; + let limit = input.max_chunk_bytes.min(MAX_CHUNK_BYTES).min(MAX_DRAWING_BYTES); + let max_cid = input.codes.last().map_or(0, |row| usize::from(row.code)); + let map_len = max_cid.checked_add(1).and_then(|n| n.checked_mul(2)) + .filter(|n| *n <= MAX_MAP_BYTES).ok_or_else(|| invalid("CID to GID map byte limit exceeded"))?; + let without_unicode = byte_bound(input.subset.bytes().len(), 0, map_len, input.codes.len())?; + let unicode_allowance = limit.checked_sub(without_unicode).ok_or_else(|| invalid("font objects exceed their preflight byte allowance"))?; + + let (mut previous, mut utf8) = (None, 0usize); + // Counts/order/ranges/lengths before allocating code-derived buffers. + for row in input.codes { + if previous.is_some_and(|prior| row.code <= prior) { + return Err(invalid("PDF font codes must be strictly increasing and unique")); + } + if row.code == 0 && row.subset_gid != 0 { + return Err(invalid("CID zero must map to subset glyph zero")); + } + metrics.advance(row.subset_gid)?; + if row.logical.is_empty() || row.logical.len() > MAX_CLUSTER_BYTES { + return Err(invalid("PDF font code requires a nonempty bounded literal cluster")); + } + utf8 = utf8.checked_add(row.logical.len()).filter(|n| *n <= MAX_UTF8_BYTES) + .ok_or_else(|| invalid("PDF font logical text input exceeds its byte limit"))?; + previous = Some(row.code); + } + + let mut pairs = Vec::new(); + pairs.try_reserve_exact(input.codes.len()).map_err(|_| invalid("cannot allocate PDF ToUnicode pairs"))?; + let mut widths = Vec::new(); + widths.try_reserve_exact(input.codes.len()).map_err(|_| invalid("cannot allocate PDF CID widths"))?; + let mut cid_map = Vec::new(); + cid_map.try_reserve_exact(map_len).map_err(|_| invalid("cannot allocate PDF CID to GID map"))?; + cid_map.resize(map_len, 0); + for row in input.codes { + pairs.push((row.code, row.logical)); + widths.push((row.code, metrics.advance(row.subset_gid)?)); + let at = usize::from(row.code).checked_mul(2).ok_or_else(|| invalid("CID map offset overflow"))?; + let end = at.checked_add(2).ok_or_else(|| invalid("CID map offset overflow"))?; + cid_map.get_mut(at..end).ok_or_else(|| invalid("CID map range exceeds its allowance"))? + .copy_from_slice(&row.subset_gid.to_be_bytes()); + } + let unicode = write_to_unicode(&pairs, unicode_allowance)?; + let bound = byte_bound(input.subset.bytes().len(), unicode.len(), cid_map.len(), widths.len())?; + if bound > limit { + return Err(invalid("font objects exceed their complete preflight byte allowance")); + } + // Stream::start panics above i32::MAX, so check each real stream explicitly. + for length in [input.subset.bytes().len(), unicode.len(), cid_map.len()] { + i32::try_from(length).map_err(|_| invalid("font stream length exceeds the PDF writer limit"))?; + } + Ok(Prepared { + font: input.subset.bytes(), unicode, cid_map, widths, + default_width, name, descriptor, flags, limit, bound, + }) +} + +fn check_chunk(chunk: &Chunk, limit: usize, bound: usize) -> Result<()> { + if chunk.len() > limit || chunk.len() > bound { + return Err(invalid("serialized font objects exceed their checked byte bound")); + } + Ok(()) +} + +/// Prepare six independent resource objects locally. Caller must reserve their +/// Ref IDs/tag globally and later attach the Type0 ref to page resources. +/// No caller Pdf is borrowed, so Result refusals cannot mutate that document. +pub(super) fn font_objects(refs: FontObjectRefs, input: FontObjectInput<'_>) -> Result { + let source = input.source; + font_objects_parts(refs, FontObjectParts { + source_font: source.font(), + subset: source.subset(), + codes: source.codes(), + descriptor: Some(source.descriptor()), + postscript_name: source.font().postscript_name.as_bytes(), + subset_tag: input.subset_tag, + max_chunk_bytes: input.max_chunk_bytes, + }) +} + +/// The raw preparation path is private to this module. Outside callers cannot +/// supply an independent Font/Subset pair or manufacture a validated view. +fn font_objects_parts(refs: FontObjectRefs, input: FontObjectParts<'_>) -> Result { + refs.validate()?; + let prepared = prepare(input)?; + let Prepared { font, unicode, cid_map, widths, default_width, name, descriptor, flags, limit, bound } = prepared; + let mut chunk = Chunk::new(); + { + let mut writer = chunk.type0_font(refs.type0); + writer.base_font(Name(&name)).encoding_predefined(Name(b"Identity-H")) + .descendant_font(refs.cid_font).to_unicode(refs.to_unicode); + } + check_chunk(&chunk, limit, bound)?; + { + let mut writer = chunk.cid_font(refs.cid_font); + writer.subtype(CidFontType::Type2).base_font(Name(&name)) + .system_info(SystemInfo { registry: Str(b"Adobe"), ordering: Str(b"Identity"), supplement: 0 }) + .font_descriptor(refs.descriptor).default_width(default_width) + .cid_to_gid_map_stream(refs.cid_to_gid); + let mut array = writer.widths(); + for &(cid, width) in &widths { + array.consecutive(cid, std::iter::once(width)); + } + } + check_chunk(&chunk, limit, bound)?; + { + let [left, bottom, right, top] = descriptor.bbox_1000; + let mut writer = chunk.font_descriptor(refs.descriptor); + writer.name(Name(&name)).flags(flags).bbox(Rect::new(left, bottom, right, top)) + .italic_angle(descriptor.italic_angle_degrees).ascent(descriptor.ascent_1000) + .descent(descriptor.descent_1000).cap_height(descriptor.cap_height_1000) + .stem_v(descriptor.stem_v_1000).font_file2(refs.font_file2); + } + check_chunk(&chunk, limit, bound)?; + { + let length = i32::try_from(font.len()).map_err(|_| invalid("FontFile2 length exceeds i32"))?; + chunk.stream(refs.font_file2, font).pair(Name(b"Length1"), length); + } + check_chunk(&chunk, limit, bound)?; + { + chunk.stream(refs.to_unicode, &unicode); + } + check_chunk(&chunk, limit, bound)?; + { + chunk.stream(refs.cid_to_gid, &cid_map); + } + check_chunk(&chunk, limit, bound)?; + if !chunk.refs().eq(refs.all()) { + return Err(invalid("font object references differ from the six reserved IDs")); + } + Ok(chunk) +} + +#[cfg(test)] +mod tests { + use super::*; + // Synthetic serialization/refusal components are not proof constructors. + // Only these descendant tests can call the module-private raw parts path. + use super::{FontObjectParts as FontObjectInput, font_objects_parts as font_objects}; + use sha2::{Digest, Sha256}; + use super::super::subset_font::subset_font; + + // Unchanged legacy metric reader retained as a test-only independent + // subset/width oracle. Production resource emission has no SFNT reader. + fn part(bytes: &[u8], at: usize, len: usize) -> Result<&[u8]> { + let end = at.checked_add(len).ok_or_else(|| invalid("font metric offset overflow"))?; + bytes.get(at..end).ok_or_else(|| invalid("truncated font metric data")) + } + + fn word(bytes: &[u8], at: usize) -> Result { + Ok(u16::from_be_bytes(part(bytes, at, 2)?.try_into().map_err(|_| invalid("invalid font metric word"))?)) + } + + fn dword(bytes: &[u8], at: usize) -> Result { + let raw = u32::from_be_bytes(part(bytes, at, 4)?.try_into().map_err(|_| invalid("invalid font metric offset"))?); + usize::try_from(raw).map_err(|_| invalid("font metric offset exceeds platform")) + } + + /// Small bounded table view over the already validated, immutable SubsetFont. + /// This does not repeat admission, glyph closure or composite parsing. + fn table<'a>(bytes: &'a [u8], tag: &[u8; 4]) -> Result<&'a [u8]> { + let count = usize::from(word(bytes, 4)?); + if count == 0 || count > 19 { + return Err(invalid("font metric table count exceeds the admitted subset contract")); + } + part(bytes, 0, 12 + count * 16)?; // count <= 19. + for index in 0..count { + let record = 12 + index * 16; + if part(bytes, record, 4)? == tag { + return part(bytes, dword(bytes, record + 8)?, dword(bytes, record + 12)?); + } + } + Err(invalid("subset lacks a required metric table")) + } + + struct MetricView<'a> { + hmtx: &'a [u8], + glyphs: usize, + full_metrics: usize, + units_per_em: u16, + } + + impl<'a> MetricView<'a> { + fn read(subset: &'a SubsetFont) -> Result { + let glyphs = subset.mapping().len(); + if glyphs == 0 || glyphs > MAX_GLYPHS || subset.bytes().len() > MAX_FONT_BYTES { + return Err(invalid("font subset exceeds the admitted fixed-resource contract")); + } + let mut previous = None; + for (expected, &(old, new)) in subset.mapping().iter().enumerate() { + if previous.is_some_and(|prior| old <= prior) || usize::from(new) != expected { + return Err(invalid("font subset mapping is not ordered and dense")); + } + if expected == 0 && old != 0 { + return Err(invalid("font subset lacks original glyph zero")); + } + previous = Some(old); + } + let bytes = subset.bytes(); + let head = table(bytes, b"head")?; + let hhea = table(bytes, b"hhea")?; + let hmtx = table(bytes, b"hmtx")?; + let maxp = table(bytes, b"maxp")?; + if usize::from(word(maxp, 4)?) != glyphs { + return Err(invalid("font subset glyph count differs from its mapping")); + } + let units_per_em = word(head, 18)?; + if units_per_em != 2048 { + return Err(invalid("font subset units per em differ from the one admitted font")); + } + let full_metrics = usize::from(word(hhea, 34)?); + if full_metrics == 0 || full_metrics > glyphs { + return Err(invalid("subset has invalid numberOfHMetrics")); + } + let expected = full_metrics.checked_mul(4) + .and_then(|full| (glyphs - full_metrics).checked_mul(2).and_then(|tail| full.checked_add(tail))) + .ok_or_else(|| invalid("subset metric length overflow"))?; + if hmtx.len() != expected { + return Err(invalid("subset hmtx length does not match its glyph metrics")); + } + Ok(Self { hmtx, glyphs, full_metrics, units_per_em }) + } + + fn advance(&self, gid: u16) -> Result { + let gid = usize::from(gid); + if gid >= self.glyphs { + return Err(invalid("PDF code maps outside the subset glyph range")); + } + let index = gid.min(self.full_metrics - 1); // full_metrics checked > 0. + let advance = word(self.hmtx, index.checked_mul(4).ok_or_else(|| invalid("font advance offset overflow"))?)?; + let width = (f64::from(advance) * 1000.0 / f64::from(self.units_per_em)) as f32; + if !width.is_finite() || width.abs() > MAX_METRIC { + return Err(invalid("PDF glyph width is not finite and bounded")); + } + Ok(width) + } + } + + const BUNDLED: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/liberation-sans/LiberationSans-Regular.ttf")); + + // SYNTHETIC descriptor for serialization/refusal tests. These are NOT + // measured Liberation values or a choice of the real provider's policies. + fn synthetic_descriptor() -> DescriptorMetrics { + DescriptorMetrics { + bbox_1000: [-100.0, -250.0, 1100.0, 900.0], + ascent_1000: 800.0, descent_1000: -200.0, cap_height_1000: 700.0, + italic_angle_degrees: 0.0, stem_v_1000: 80.0, + flags: FontFlags::NON_SYMBOLIC.bits(), + } + } + + fn admitted_subset() -> SubsetFont { + // Read-only original metadata: glyph0 metric(1536,205), 2/3=(569,0), + // original IDs0,2,3 become subset IDs0,1,2. No B1/shaping assertion. + subset_font(BUNDLED, 0, &[3, 2, 3], MAX_FONT_BYTES).unwrap() + } + + fn refs(first: i32) -> FontObjectRefs { + FontObjectRefs { + type0: Ref::new(first), cid_font: Ref::new(first + 1), + descriptor: Ref::new(first + 2), font_file2: Ref::new(first + 3), + to_unicode: Ref::new(first + 4), cid_to_gid: Ref::new(first + 5), + } + } + + // Synthetic B1 resource record for the existing serialization/refusal + // tests only: not a valid exactly-used Scene or a shaper/layout assertion. + fn source_font() -> &'static Font { + static FONT: std::sync::OnceLock = std::sync::OnceLock::new(); + FONT.get_or_init(|| { + use solidcraft_geom::paper::text::{FontFlags as B1Flags, FontGlyph, FontMetrics}; + Font { + id: REVIEWED_B1_ID, bytes: std::sync::Arc::from(BUNDLED), face: 0, + postscript_name: "LiberationSans".into(), num_glyphs: 2620, units_per_em: 2048, + metrics: FontMetrics { + ascent: 1854, descent: -434, cap_height: 1409, bbox: [-1114, -621, 2666, 2007], + italic_angle: 0.0, flags: B1Flags::default(), stem_v: 180, + }, + glyphs: [(0, 1536), (2, 569), (3, 569)].into_iter() + .map(|(gid, advance)| (gid, FontGlyph { advance, outline: vec![] })).collect(), + } + }) + } + + fn input<'a>(subset: &'a SubsetFont, codes: &'a [CodeToGlyph<'a>], descriptor: &'a DescriptorMetrics) -> FontObjectInput<'a> { + FontObjectInput { + source_font: source_font(), subset, codes, descriptor: Some(descriptor), + postscript_name: POSTSCRIPT_NAME, subset_tag: *b"ABCDEF", + max_chunk_bytes: MAX_CHUNK_BYTES, + } + } + + struct Parsed<'a> { + id: i32, + dict: &'a str, + stream: Option<&'a [u8]>, + } + + fn skip_space(bytes: &[u8], at: &mut usize) { + while bytes.get(*at).is_some_and(u8::is_ascii_whitespace) { *at += 1; } + } + + fn number(dict: &str, key: &str) -> usize { + dict.split_ascii_whitespace().skip_while(|token| *token != key) + .nth(1).unwrap().parse().unwrap() + } + + // Original tiny reader for THIS fixed dictionary/stream grammar, not a + // general PDF parser. Binary font bytes are skipped by declared Length, + // never scanned for endobj/endstream text or used as an expected golden. + fn objects(bytes: &[u8]) -> Vec> { + let mut out = Vec::new(); + let mut at = 0; + while at < bytes.len() { + skip_space(bytes, &mut at); + if at == bytes.len() { break; } + let start = at; + while bytes[at].is_ascii_digit() { at += 1; } + let id = std::str::from_utf8(&bytes[start..at]).unwrap().parse().unwrap(); + assert!(bytes[at..].starts_with(b" 0 obj\n")); + at += b" 0 obj\n".len(); + let start = at; + assert!(bytes[at..].starts_with(b"<<")); + let mut depth = 0; + loop { + if bytes[at..].starts_with(b"<<") { depth += 1; at += 2; } + else if bytes[at..].starts_with(b">>") { + depth -= 1; + at += 2; + if depth == 0 { break; } + } else { at += 1; } + } + let dict = std::str::from_utf8(&bytes[start..at]).unwrap(); + skip_space(bytes, &mut at); + let stream = if bytes[at..].starts_with(b"stream\n") { + at += b"stream\n".len(); + let len = number(dict, "/Length"); + let payload = &bytes[at..at + len]; + at += len; + assert!(bytes[at..].starts_with(b"\nendstream")); + at += b"\nendstream".len(); + skip_space(bytes, &mut at); + Some(payload) + } else { None }; + assert!(bytes[at..].starts_with(b"endobj")); + at += b"endobj".len(); + out.push(Parsed { id, dict, stream }); + } + out + } + + fn object<'a, 'b>(objects: &'b [Parsed<'a>], id: i32) -> &'b Parsed<'a> { + objects.iter().find(|object| object.id == id).unwrap() + } + + #[test] + fn six_real_refs_link_exact_objects_and_preserve_raw_font_bytes() { + let subset = admitted_subset(); + let descriptor = synthetic_descriptor(); + let chunk = font_objects(refs(6), input(&subset, &[], &descriptor)).unwrap(); + let parsed = objects(chunk.as_bytes()); + assert_eq!(parsed.iter().map(|o| o.id).collect::>(), [6, 7, 8, 9, 10, 11]); + let type0 = object(&parsed, 6).dict; + assert!(type0.contains("/Subtype /Type0")); + assert!(type0.contains("/Encoding /Identity-H")); + assert!(type0.contains("/DescendantFonts [7 0 R]")); + assert!(type0.contains("/ToUnicode 10 0 R")); + assert!(type0.contains("/BaseFont /ABCDEF+LiberationSans")); + let cid = object(&parsed, 7).dict; + assert!(cid.contains("/Subtype /CIDFontType2")); + assert!(cid.contains("/CIDToGIDMap 11 0 R")); + assert!(cid.contains("/FontDescriptor 8 0 R")); + assert!(cid.contains("/Registry (Adobe)") && cid.contains("/Ordering (Identity)")); + let desc = object(&parsed, 8).dict; + assert!(desc.contains("/FontName /ABCDEF+LiberationSans")); + assert!(desc.contains("/FontFile2 9 0 R")); + assert!(desc.contains("/StemV 80") && desc.contains("/Ascent 800")); + assert!(desc.contains("/CapHeight 700") && desc.contains("/Flags 32")); + let file = object(&parsed, 9); + assert_eq!(file.stream.unwrap(), subset.bytes()); + assert_eq!(number(file.dict, "/Length1"), subset.bytes().len()); + assert!(!file.dict.contains("/Filter")); + assert_eq!(object(&parsed, 11).stream.unwrap(), [0, 0]); + } + + #[test] + fn distinct_codes_share_a_gid_without_losing_literal_logical_clusters() { + let subset = admitted_subset(); + let descriptor = synthetic_descriptor(); + // Synthetic routing semantics only; no claim that these words are + // shaped or rendered by the space/empty glyph in the fixed resource. + let codes = [ + CodeToGlyph { code: 2, subset_gid: 1, logical: "one" }, + CodeToGlyph { code: 7, subset_gid: 1, logical: "two" }, + CodeToGlyph { code: 9, subset_gid: 0, logical: "notdef" }, + ]; + let chunk = font_objects(refs(6), input(&subset, &codes, &descriptor)).unwrap(); + let parsed = objects(chunk.as_bytes()); + let map = object(&parsed, 11).stream.unwrap(); + let mut expected = vec![0; 20]; + expected[5] = 1; + expected[15] = 1; + assert_eq!(map, expected); + let cmap = std::str::from_utf8(object(&parsed, 10).stream.unwrap()).unwrap(); + assert!(cmap.contains("<0002> <006F006E0065>")); + assert!(cmap.contains("<0007> <00740077006F>")); + assert!(cmap.contains("<0009> <006E006F0074006400650066>")); + assert!(!cmap.contains("<0001> <")); + } + + #[test] + fn sparse_maximum_cid_has_bounded_map_and_zero_stays_notdef() { + let subset = admitted_subset(); + let descriptor = synthetic_descriptor(); + let codes = [CodeToGlyph { code: u16::MAX, subset_gid: 2, logical: "z" }]; + let chunk = font_objects(refs(6), input(&subset, &codes, &descriptor)).unwrap(); + let parsed = objects(chunk.as_bytes()); + let map = object(&parsed, 11).stream.unwrap(); + assert_eq!(map.len(), 131_072); + assert!(map[..131_070].iter().all(|byte| *byte == 0)); + assert_eq!(&map[131_070..], [0, 2]); + let bad = [CodeToGlyph { code: 0, subset_gid: 1, logical: "x" }]; + assert!(font_objects(refs(6), input(&subset, &bad, &descriptor)).is_err()); + let zero = [CodeToGlyph { code: 0, subset_gid: 0, logical: "notdef" }]; + assert!(font_objects(refs(6), input(&subset, &zero, &descriptor)).is_ok()); + } + + // Test-only parser for this oracle's EXACT two-row W shape. It preserves + // the outer array and one-element inner arrays instead of flattening them. + // Bounded input/tokens, no deliberate panic, and no general PDF claim. + struct WidthField<'a> { + bytes: &'a [u8], + at: usize, + } + + impl WidthField<'_> { + fn literal(&mut self, token: &[u8]) -> Result<()> { + skip_space(self.bytes, &mut self.at); + let end = self.at.checked_add(token.len()).ok_or_else(|| invalid("W oracle offset overflow"))?; + if self.bytes.get(self.at..end) != Some(token) { + return Err(invalid("W oracle expected an array delimiter or field key")); + } + self.at = end; + Ok(()) + } + + fn cid(&mut self) -> Result { + skip_space(self.bytes, &mut self.at); + let start = self.at; + while self.bytes.get(self.at).is_some_and(u8::is_ascii_digit) { + if self.at - start == 5 { + return Err(invalid("W oracle CID token exceeds five digits")); + } + self.at += 1; + } + let token = self.bytes.get(start..self.at).ok_or_else(|| invalid("W oracle CID range"))?; + let token = std::str::from_utf8(token).map_err(|_| invalid("W oracle CID encoding"))?; + token.parse::().map_err(|_| invalid("W oracle expected a u16 CID")) + } + + fn width(&mut self) -> Result { + skip_space(self.bytes, &mut self.at); + let start = self.at; + while let Some(byte) = self.bytes.get(self.at) { + if byte.is_ascii_whitespace() || matches!(*byte, b'[' | b']') { + break; + } + if self.at - start == 64 { + return Err(invalid("W oracle width token exceeds its limit")); + } + self.at += 1; + } + let token = self.bytes.get(start..self.at).ok_or_else(|| invalid("W oracle width range"))?; + if !token.iter().any(u8::is_ascii_digit) + || token.iter().any(|byte| !byte.is_ascii_digit() && !matches!(*byte, b'+' | b'-' | b'.')) + { + return Err(invalid("W oracle expected a decimal width token")); + } + let token = std::str::from_utf8(token).map_err(|_| invalid("W oracle width encoding"))?; + let width = token.parse::().map_err(|_| invalid("W oracle decimal width"))?; + if !width.is_finite() || width < 0.0 { + return Err(invalid("W oracle requires a finite nonnegative width")); + } + Ok(width) + } + + fn row(&mut self) -> Result<(u16, [f32; 1])> { + let cid = self.cid()?; + self.literal(b"[")?; + let width = self.width()?; + self.literal(b"]")?; + Ok((cid, [width])) + } + } + + fn parse_two_width_rows(field: &str) -> Result<[(u16, [f32; 1]); 2]> { + if field.len() > 512 { + return Err(invalid("W oracle field exceeds its byte limit")); + } + let mut reader = WidthField { bytes: field.as_bytes(), at: 0 }; + reader.literal(b"/W")?; + reader.literal(b"[")?; + let first = reader.row()?; + let second = reader.row()?; + reader.literal(b"]")?; + skip_space(reader.bytes, &mut reader.at); + if reader.at != reader.bytes.len() { + return Err(invalid("W oracle has trailing data or additional rows")); + } + Ok([first, second]) + } + + #[test] + fn widths_use_the_mapped_subset_gid_but_are_indexed_by_cid() { + let subset = admitted_subset(); + let descriptor = synthetic_descriptor(); + let codes = [ + CodeToGlyph { code: 42, subset_gid: 2, logical: "synthetic" }, + CodeToGlyph { code: 300, subset_gid: 0, logical: "notdef" }, + ]; + let prepared = prepare(input(&subset, &codes, &descriptor)).unwrap(); + // Independent original-font integer metadata, not emitter output. + let empty_width = (569_000.0_f64 / 2048.0) as f32; + assert_eq!(prepared.default_width, 750.0); //1536*1000/2048. + assert_eq!(prepared.widths, [(42, empty_width), (300, 750.0)]); + // Subsetter compresses the repeated569 width of the two empty glyphs. + let view = MetricView::read(&subset).unwrap(); + assert_eq!(view.advance(1).unwrap(), empty_width); + assert_eq!(view.advance(2).unwrap(), empty_width); + let chunk = font_objects(refs(6), input(&subset, &codes, &descriptor)).unwrap(); + let parsed = objects(chunk.as_bytes()); + let cid = object(&parsed, 7).dict; + assert!(cid.contains("/DW 750")); + // W is the last entry of this emitted dictionary; remove ONLY its + // dictionary terminator, then parse all of W including both array levels. + let field = cid.get(cid.find("/W ").unwrap()..).unwrap() + .strip_suffix(">>").unwrap().trim_end(); + let expected = [(42, [empty_width]), (300, [750.0])]; + assert_eq!(parse_two_width_rows(field).unwrap(), expected); + // Independent literals, not emitter-generated goldens. The former + // flattened-token oracle would miss these nesting/trailing mutations. + for malformed in [ + "/W [42 277.83203125 300 750]", + "/W [42 [277.83203125] 300 [750] 999 [123]]", + "/W [42 [277.83203125] 300 [750]] 999 [123]", + "/W [42 [277.83203125] 300 [750]", + "/W [42 [277.83203125 999] 300 [750]]", + ] { + assert!(parse_two_width_rows(malformed).is_err(), "accepted malformed W: {malformed}"); + } + assert_eq!(parse_two_width_rows("/W [42 [277.83203125] 300 [750]]").unwrap(), expected); + } + + #[test] + fn invalid_code_order_gid_and_logical_clusters_refuse() { + let subset = admitted_subset(); + let descriptor = synthetic_descriptor(); + for codes in [ + vec![CodeToGlyph { code: 2, subset_gid: 3, logical: "outside" }], + vec![CodeToGlyph { code: 2, subset_gid: 1, logical: "" }], + vec![CodeToGlyph { code: 2, subset_gid: 1, logical: "a" }, CodeToGlyph { code: 2, subset_gid: 1, logical: "b" }], + vec![CodeToGlyph { code: 2, subset_gid: 1, logical: "a" }, CodeToGlyph { code: 1, subset_gid: 1, logical: "b" }], + ] { + assert!(font_objects(refs(6), input(&subset, &codes, &descriptor)).is_err()); + } + let too_long = "x".repeat(769); + let codes = [CodeToGlyph { code: 1, subset_gid: 1, logical: &too_long }]; + assert!(font_objects(refs(6), input(&subset, &codes, &descriptor)).is_err()); + let too_many_utf16 = "x".repeat(257); // Within UTF8 cap, beyond512UTF16BE bytes. + let codes = [CodeToGlyph { code: 1, subset_gid: 1, logical: &too_many_utf16 }]; + assert!(font_objects(refs(6), input(&subset, &codes, &descriptor)).is_err()); + } + + #[test] + fn essential_descriptor_fields_refuse_missing_invalid_and_underflow_values() { + let subset = admitted_subset(); + let valid = synthetic_descriptor(); + let mut missing = input(&subset, &[], &valid); + missing.descriptor = None; + assert!(font_objects(refs(6), missing).is_err()); + for case in 0..12 { + let mut descriptor = synthetic_descriptor(); + match case { + 0 => descriptor.stem_v_1000 = 0.0, + 1 => descriptor.ascent_1000 = 0.0, + 2 => descriptor.descent_1000 = 0.0, + 3 => descriptor.cap_height_1000 = -1.0, + 4 => descriptor.cap_height_1000 = 900.0, + 5 => descriptor.bbox_1000 = [0.0; 4], + 6 => descriptor.stem_v_1000 = f32::NAN, + 7 => descriptor.bbox_1000[3] = f32::INFINITY, + 8 => descriptor.ascent_1000 = MAX_METRIC + 1.0, + 9 => descriptor.italic_angle_degrees = 91.0, + 10 => descriptor.stem_v_1000 = f32::from_bits(1), + _ => descriptor.bbox_1000 = [10.0, 0.0, 0.0, 900.0], + } + assert!(font_objects(refs(6), input(&subset, &[], &descriptor)).is_err(), "synthetic case{case}"); + } + for flags in [0, 1 << 31, FontFlags::SYMBOLIC.bits() | FontFlags::NON_SYMBOLIC.bits()] { + let mut descriptor = synthetic_descriptor(); + descriptor.flags = flags; + assert!(font_objects(refs(6), input(&subset, &[], &descriptor)).is_err()); + } + } + + #[test] + fn fixed_name_tag_and_real_ref_constraints_are_explicit() { + let subset = admitted_subset(); + let descriptor = synthetic_descriptor(); + let mut wrong_name = input(&subset, &[], &descriptor); + wrong_name.postscript_name = b"OtherFont"; + assert!(font_objects(refs(6), wrong_name).is_err()); + for tag in [*b"abcDEF", *b"ABCDE ", [255; 6]] { + let mut wrong_tag = input(&subset, &[], &descriptor); + wrong_tag.subset_tag = tag; + assert!(font_objects(refs(6), wrong_tag).is_err()); + } + let mut duplicate = refs(6); + duplicate.cid_font = duplicate.type0; + assert!(font_objects(duplicate, input(&subset, &[], &descriptor)).is_err()); + assert!(font_objects(refs(1), input(&subset, &[], &descriptor)).is_err()); + let mut too_high = refs(6); + too_high.cid_to_gid = Ref::new(100_001); + assert!(font_objects(too_high, input(&subset, &[], &descriptor)).is_err()); + let mut inclusive = refs(6); + inclusive.cid_to_gid = Ref::new(100_000); + assert!(font_objects(inclusive, input(&subset, &[], &descriptor)).is_ok()); + } + + #[test] + fn preflight_byte_allowance_is_inclusive_and_actual_serialization_is_below_it() { + let subset = admitted_subset(); + let descriptor = synthetic_descriptor(); + let codes = [CodeToGlyph { code: 42, subset_gid: 1, logical: "x" }]; + let prepared = prepare(input(&subset, &codes, &descriptor)).unwrap(); + let bound = prepared.bound; // Boundary property, not a generated font golden. + let mut exact = input(&subset, &codes, &descriptor); + exact.max_chunk_bytes = bound; + let chunk = font_objects(refs(6), exact).unwrap(); + assert!(chunk.len() <= bound); + let mut short = input(&subset, &codes, &descriptor); + short.max_chunk_bytes = bound - 1; + assert!(font_objects(refs(6), short).is_err()); + let mut zero = input(&subset, &codes, &descriptor); + zero.max_chunk_bytes = 0; + assert!(font_objects(refs(6), zero).is_err()); + assert!(byte_bound(usize::MAX, 0, 0, 0).is_err()); + assert!(byte_bound(0, 0, 0, usize::MAX).is_err()); + } + + #[test] + fn repeated_complete_inputs_are_deterministic_and_leave_source_unchanged() { + let subset = admitted_subset(); + let descriptor = synthetic_descriptor(); + let source = subset.bytes().to_vec(); + let mapping = subset.mapping().to_vec(); + let codes = [CodeToGlyph { code: 10, subset_gid: 1, logical: "x" }]; + let a = font_objects(refs(6), input(&subset, &codes, &descriptor)).unwrap(); + let b = font_objects(refs(6), input(&subset, &codes, &descriptor)).unwrap(); + assert_eq!(a.as_bytes(), b.as_bytes()); + assert_eq!(source, subset.bytes()); + assert_eq!(mapping, subset.mapping()); + } + + #[test] + fn full_u16_code_space_is_inclusive_and_one_extra_record_refuses() { + let subset = admitted_subset(); + let descriptor = synthetic_descriptor(); + let mut codes: Vec<_> = (0..=u16::MAX).map(|code| CodeToGlyph { + code, subset_gid: if code == 0 { 0 } else { 1 }, logical: "x", + }).collect(); + let chunk = font_objects(refs(6), input(&subset, &codes, &descriptor)).unwrap(); + assert_eq!(chunk.refs().count(), 6); + assert!(chunk.len() <= MAX_CHUNK_BYTES); + codes.push(CodeToGlyph { code: 0, subset_gid: 0, logical: "x" }); + assert!(font_objects(refs(6), input(&subset, &codes, &descriptor)).is_err()); + } + + #[test] + fn source_derived_p3_offset_arithmetic_is_a_caller_reservation_not_a_registry() { + let subset = admitted_subset(); + let descriptor = synthetic_descriptor(); + for layers in [0, 5] { + let first = 6 + layers; + let chunk = font_objects(refs(first), input(&subset, &[], &descriptor)).unwrap(); + let ids: Vec<_> = chunk.refs().map(Ref::get).collect(); + assert_eq!(ids, (first..=first + 5).collect::>()); + assert!(ids.iter().all(|id| *id > 5 + layers)); + } + // This only checks the derived offsets with synthetic descriptors. + // The actual P3 allocator/page resource integration is NOT exercised. + } + // New ORIGINAL B1 width-provider acceptance. These are synthetic record + // contracts over the real resource, not an exactly-used Scene or shaping + // claim. Real producer + page-content acceptance remains separate. + fn b1_width_font(ids: &[(u16, u16)]) -> Font { + use solidcraft_geom::paper::text::FontGlyph; + let mut font = source_font().clone(); + font.glyphs = ids.iter().map(|&(gid, advance)| (gid, FontGlyph { advance, outline: vec![] })).collect(); + font + } + + fn input_from_b1<'a>(subset: &'a SubsetFont, codes: &'a [CodeToGlyph<'a>], descriptor: &'a DescriptorMetrics, font: &'a Font) -> FontObjectInput<'a> { + let mut result = input(subset, codes, descriptor); + result.source_font = font; + result + } + + #[test] + fn b1_widths_use_original_gid_join_and_cid_index_with_distinct_real_advances() { + let subset = subset_font(BUNDLED, 0, &[36, 3], MAX_FONT_BYTES).unwrap(); + assert_eq!(subset.mapping(), [(0, 0), (3, 1), (36, 2)]); + // Original hmtx metadata: space3=569, A36=1366, .notdef0=1536. + // A wrong font.glyphs[subset_gid] join lacks 1/2 and cannot pass. + let font = b1_width_font(&[(0, 1536), (3, 569), (36, 1366)]); + let descriptor = synthetic_descriptor(); + let codes = [ + CodeToGlyph { code: 42, subset_gid: 2, logical: "A" }, + CodeToGlyph { code: 300, subset_gid: 1, logical: " " }, + ]; + let prepared = prepare(input_from_b1(&subset, &codes, &descriptor, &font)).unwrap(); + assert_eq!(prepared.widths, [(42, (666.992_187_5_f64 as f32)), (300, (277.832_031_25_f64 as f32))]); + assert_eq!(prepared.default_width, 750.0); + let chunk = font_objects(refs(16), input_from_b1(&subset, &codes, &descriptor, &font)).unwrap(); + let parsed = objects(chunk.as_bytes()); + assert_eq!(object(&parsed, 19).stream.unwrap(), subset.bytes()); + let field = object(&parsed, 17).dict; + let field = field.get(field.find("/W ").unwrap()..).unwrap().strip_suffix(">>").unwrap().trim_end(); + assert_eq!(parse_two_width_rows(field).unwrap(), [(42, [(666.992_187_5_f64 as f32)]), (300, [(277.832_031_25_f64 as f32)])]); + let cmap = std::str::from_utf8(object(&parsed, 20).stream.unwrap()).unwrap(); + assert!(cmap.contains("<002A> <0041>") && cmap.contains("<012C> <0020>")); + } + + #[test] + fn b1_widths_keep_real_zero_advance_and_exact_intrinsic_units() { + let subset = subset_font(BUNDLED, 0, &[1], MAX_FONT_BYTES).unwrap(); + let font = b1_width_font(&[(0, 1536), (1, 0)]); // original glyph1=(0,0). + let provider = B1Widths::read(&font, &subset).unwrap(); + assert_eq!(provider.advance(1).unwrap(), 0.0); + let descriptor = synthetic_descriptor(); + let codes = [CodeToGlyph { code: 9, subset_gid: 1, logical: "zero" }]; + let result = prepare(input_from_b1(&subset, &codes, &descriptor, &font)).unwrap(); + assert_eq!(result.widths, [(9, 0.0)]); + assert_eq!(result.default_width, 750.0); + } + + #[test] + fn b1_widths_arithmetic_has_literal_zero_fraction_and_u16_envelope_oracles() { + assert_eq!(width_1000(0, 2048).unwrap(), 0.0); + assert_eq!(width_1000(569, 2048).unwrap(), (277.832_031_25_f64 as f32)); + assert_eq!(width_1000(1366, 2048).unwrap(), (666.992_187_5_f64 as f32)); + assert_eq!(width_1000(1536, 2048).unwrap(), 750.0); + assert_eq!(width_1000(u16::MAX, 16384).unwrap(), (65_535_000.0_f64 / 16384.0) as f32); + // Every valid u16 product fits u32; the checked multiply remains a guard + // against future widening. No overflow input is representable today. + assert_eq!(u32::from(u16::MAX).checked_mul(1000), Some(65_535_000)); + } + + #[test] + fn b1_widths_arithmetic_refuses_zero_and_out_of_contract_units_without_dividing() { + for units in [0, 1, 15, 16385, u16::MAX] { + assert!(width_1000(1, units).is_err(), "units={units}"); + assert!(width_1000(0, units).is_err(), "zero advance does not excuse units={units}"); + } + } + + #[test] + fn b1_widths_arithmetic_preserves_inclusive_serialized_metric_bound() { + assert_eq!(width_1000(16000, 16).unwrap(), 1_000_000.0); + assert!(width_1000(16001, 16).is_err()); + assert!(width_1000(u16::MAX, 16).is_err()); + // B1 fields are u16, so NaN/Infinity cannot enter this arithmetic. + // The original descriptor hostile-float cases remain unchanged. + } + + #[test] + fn b1_widths_missing_original_advance_refuses_without_subset_metric_fallback() { + let subset = subset_font(BUNDLED, 0, &[36], MAX_FONT_BYTES).unwrap(); + let font = b1_width_font(&[(0, 1536)]); + let provider = B1Widths::read(&font, &subset).unwrap(); + let e = provider.advance(1).unwrap_err().to_string(); + assert!(e.contains("lacks an intrinsic width for an emitted original glyph"), "{e}"); + let descriptor = synthetic_descriptor(); + let codes = [CodeToGlyph { code: 5, subset_gid: 1, logical: "A" }]; + assert!(font_objects(refs(6), input_from_b1(&subset, &codes, &descriptor, &font)).is_err()); + } + + #[test] + fn b1_widths_unemitted_closure_glyphs_do_not_require_invented_b1_entries() { + let subset = subset_font(BUNDLED, 0, &[3, 36], MAX_FONT_BYTES).unwrap(); + // Original36 is embedded but no code emits it. No width lookup for it. + let font = b1_width_font(&[(0, 1536), (3, 569)]); + let descriptor = synthetic_descriptor(); + let codes = [CodeToGlyph { code: 5, subset_gid: 1, logical: " " }]; + let prepared = prepare(input_from_b1(&subset, &codes, &descriptor, &font)).unwrap(); + assert_eq!(prepared.widths, [(5, (277.832_031_25_f64 as f32))]); + assert_eq!(prepared.font, subset.bytes()); + } + + #[test] + fn b1_widths_omitted_notdef_still_plans_used_width_but_blocks_default_policy() { + let subset = subset_font(BUNDLED, 0, &[36], MAX_FONT_BYTES).unwrap(); + let font = b1_width_font(&[(36, 1366)]); + let provider = B1Widths::read(&font, &subset).unwrap(); + assert_eq!(provider.advance(1).unwrap(), (666.992_187_5_f64 as f32)); + let e = provider.default_width().unwrap_err().to_string(); + assert!(e.contains("glyph zero is absent; PDF default-width policy is unresolved"), "{e}"); + let descriptor = synthetic_descriptor(); + let codes = [CodeToGlyph { code: 1, subset_gid: 1, logical: "A" }]; + let e = match font_objects(refs(6), input_from_b1(&subset, &codes, &descriptor, &font)) { + Ok(_) => panic!("emitted font objects without an agreed default-width source"), + Err(e) => e.to_string(), + }; + assert!(e.contains("default-width policy is unresolved"), "{e}"); + // A caller cannot bypass the unresolved policy by emitting no codes. + assert!(font_objects(refs(6), input_from_b1(&subset, &[], &descriptor, &font)).is_err()); + assert!(!font.glyphs.contains_key(&0)); + } + + #[test] + fn b1_widths_raw_digest_cannot_replace_b1_bytes_plus_face_identity() { + let subset = admitted_subset(); + let mut font = source_font().clone(); + let raw: [u8; 32] = Sha256::digest(BUNDLED).into(); + assert_ne!(raw, font.id); + font.id = raw; + assert!(B1Widths::read(&font, &subset).is_err()); + font = source_font().clone(); + font.id[0] ^= 1; + assert!(B1Widths::read(&font, &subset).is_err()); + let mut changed = BUNDLED.to_vec(); + changed[4096] ^= 1; + font.bytes = std::sync::Arc::from(changed); + font.id = Sha256::new().chain_update(font.bytes.as_ref()).chain_update(0u32.to_le_bytes()).finalize().into(); + assert!(B1Widths::read(&font, &subset).is_err(), "internally matching id is not resource admission"); + } + + #[test] + fn b1_widths_byte_envelope_refuses_before_identity_work() { + let subset = admitted_subset(); + for length in [0, 410819, 410821] { + let mut font = source_font().clone(); + font.bytes = std::sync::Arc::from(vec![0u8; length]); + font.id = [0; 32]; + let e = match B1Widths::read(&font, &subset) { + Ok(_) => panic!("accepted length {length}"), + Err(e) => e.to_string(), + }; + assert!(e.contains("byte envelope differs"), "{length}: {e}"); + } + // This checks the observable refusal reason and source order, not a + // runtime timing guarantee or a digest-call counter. + } + + #[test] + fn b1_widths_fixed_face_upem_glyph_count_and_used_id_caps_stay_closed() { + let subset = admitted_subset(); + for case in 0..7 { + let mut font = source_font().clone(); + match case { + 0 => font.face = 1, + 1 => { let mut bytes = font.bytes.to_vec(); bytes[4096] ^= 1; font.bytes = std::sync::Arc::from(bytes); }, + 2 => font.units_per_em = 0, + 3 => font.units_per_em = 1024, + 4 => font.num_glyphs = 0, + 5 => font.postscript_name = "other".into(), + _ => { font.glyphs.insert(2620, solidcraft_geom::paper::text::FontGlyph { advance: 1, outline: vec![] }); } + } + assert!(B1Widths::read(&font, &subset).is_err(), "case={case}"); + } + } + + #[test] + fn b1_widths_missing_subset_ids_refuse_even_when_b1_has_other_widths() { + let subset = admitted_subset(); + let provider = B1Widths::read(source_font(), &subset).unwrap(); + for gid in [3, u16::MAX] { + assert!(provider.advance(gid).is_err(), "subset GID {gid}"); + } + } + + #[test] + fn b1_widths_binding_and_emission_leave_source_records_program_and_mapping_unchanged() { + let subset = admitted_subset(); + let font = source_font().clone(); + let before_font = font.clone(); + let before_bytes = subset.bytes().to_vec(); + let before_mapping = subset.mapping().to_vec(); + let descriptor = synthetic_descriptor(); + let codes = [ + CodeToGlyph { code: 42, subset_gid: 2, logical: "alias1" }, + CodeToGlyph { code: 300, subset_gid: 2, logical: "alias2" }, + ]; + let a = font_objects(refs(6), input_from_b1(&subset, &codes, &descriptor, &font)).unwrap(); + let b = font_objects(refs(6), input_from_b1(&subset, &codes, &descriptor, &font)).unwrap(); + assert_eq!(a.as_bytes(), b.as_bytes()); + assert_eq!(font, before_font); + assert_eq!(subset.bytes(), before_bytes); + assert_eq!(subset.mapping(), before_mapping); + let prepared = prepare(input_from_b1(&subset, &codes, &descriptor, &font)).unwrap(); + assert_eq!(prepared.widths, [(42, (277.832_031_25_f64 as f32)), (300, (277.832_031_25_f64 as f32))]); + } + +} + + diff --git a/proposals/drawings/2026-10-30/F0-textplan-fontobjects/candidate/crates/io/src/paper/pdf/text_plan.rs b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/candidate/crates/io/src/paper/pdf/text_plan.rs new file mode 100644 index 000000000..7cdbf7024 --- /dev/null +++ b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/candidate/crates/io/src/paper/pdf/text_plan.rs @@ -0,0 +1,387 @@ +//! Bounded PDF planning from the actual B1a Font/TextRun records (#4890 P2). +//! +//! This neither shapes text nor writes a page. It keeps intrinsic hmtx widths +//! separate from the producer's placed glyph x/rise/advance. One glyph per logical +//! cluster is supported, including a glyph carrying several characters; a +//! multi-glyph cluster is refused until its extraction/content policy is supplied. +//! The ToUnicode destination limit stays 512 UTF-16BE bytes, not a silent split. +//! +//! Plans retain no new font/document Arc: strings/font records are borrowed. +//! Local vector storage and returned subset bytes have separate allowances. The +//! existing subsetter/pdf-writer internal allocation limitations still apply. +//! No parent registration, global PDF Ref allocator, page resource or text arm is +//! introduced here. The parent must preserve the planned placements and reading +//! order and qualify real PDF rendering/extraction; these records prove neither. + +use std::mem::size_of; +use std::ops::Range; + +use pdf_writer::types::FontFlags; +use sha2::{Digest, Sha256}; +use solidcraft_geom::paper::text::{Font, TextRun}; +use solidcraft_geom::paper::MAX_COORDINATE_MM; + +use super::font_objects::{CodeToGlyph, DescriptorMetrics, FontObjectInput}; +use super::subset_font::{SubsetFont, subset_font}; +use crate::{IoError, Result}; + +const MAX_RUNS: usize = 1024; +const MAX_GLYPHS: usize = 16_384; +const MAX_PLAN_BYTES: usize = 16 << 20; +const MAX_LOGICAL_BYTES: usize = 4 << 20; +const MAX_CLUSTER_BYTES: usize = 768; +const MAX_CLUSTER_UNITS: usize = 256; +const APPROVED_FONT_BYTES: usize = 410_820; + +/// One actual glyph, with a code for its original GID AND literal logical text. +/// The matrix has unit basis vectors and a translation in sheet millimetres; +/// font_size_mm is on its run. Parent applies its mm-to-point scale only once. +pub(super) struct PlannedGlyph<'a> { + pub(super) code: u16, + pub(super) original_gid: u16, + pub(super) source_glyph_index: usize, + pub(super) intrinsic_advance_fu: u16, + pub(super) placed_advance_mm: f64, + pub(super) matrix_mm: [f64; 6], + pub(super) logical: &'a str, +} + +/// Glyphs occupy one contiguous range in the plan, in logical reading order. +/// For an RTL run their SOURCE indices descend; positions are never recomputed +/// from font widths. Input run order remains unchanged. +pub(super) struct PlannedRun<'a> { + pub(super) glyphs: Range, + pub(super) font_size_mm: f64, + pub(super) rtl: bool, + pub(super) text: &'a str, +} + +pub(super) struct TextPlan<'a> { + font: &'a Font, + subset: SubsetFont, + descriptor: DescriptorMetrics, + codes: Vec>, + runs: Vec>, + glyphs: Vec>, +} + +/// Borrowed only from a successfully constructed TextPlan. Private fields +/// bind checked source records, the factory-produced subset, descriptor and +/// codes for one immutable plan; no raw-record or serde constructor exists. +pub(super) struct FontPlanView<'a> { + font: &'a Font, + subset: &'a SubsetFont, + descriptor: &'a DescriptorMetrics, + codes: &'a [CodeToGlyph<'a>], +} + +impl<'a> FontPlanView<'a> { + pub(super) fn font(&self) -> &'a Font { self.font } + pub(super) fn subset(&self) -> &'a SubsetFont { self.subset } + pub(super) fn descriptor(&self) -> &'a DescriptorMetrics { self.descriptor } + pub(super) fn codes(&self) -> &'a [CodeToGlyph<'a>] { self.codes } +} + +impl TextPlan<'_> { + pub(super) fn runs(&self) -> &[PlannedRun<'_>] { + &self.runs + } + + pub(super) fn glyphs(&self) -> &[PlannedGlyph<'_>] { + &self.glyphs + } + + /// Caller still supplies six globally reserved refs to font_objects, a + /// globally unique subset tag, page resources and a cumulative output budget. + pub(super) fn font_input(&self, subset_tag: [u8; 6], max_chunk_bytes: usize) -> FontObjectInput<'_> { + FontObjectInput { + source: FontPlanView { + font: self.font, + subset: &self.subset, + descriptor: &self.descriptor, + codes: &self.codes, + }, + subset_tag, + max_chunk_bytes, + } + } +} + +fn invalid(message: &'static str) -> IoError { + IoError::Invalid(format!("PDF text plan: {message}")) +} + +fn reserve(count: usize) -> Result> { + let mut values = Vec::new(); + values.try_reserve_exact(count).map_err(|_| invalid("cannot allocate bounded plan storage"))?; + Ok(values) +} + +fn bytes(count: usize) -> Result { + count.checked_mul(size_of::()).ok_or_else(|| invalid("plan storage overflow")) +} + +fn total(parts: &[usize], limit: usize) -> Result { + parts.iter().try_fold(0usize, |n, part| { + n.checked_add(*part).filter(|n| *n <= limit).ok_or_else(|| invalid("plan storage allowance exceeded")) + }) +} + +fn u16_at(bytes: &[u8], at: usize) -> Result { + let end = at.checked_add(2).ok_or_else(|| invalid("font table range overflow"))?; + let value = bytes.get(at..end).and_then(|b| b.try_into().ok()).ok_or_else(|| invalid("truncated admitted font table"))?; + Ok(u16::from_be_bytes(value)) +} + +fn u32_at(bytes: &[u8], at: usize) -> Result { + let end = at.checked_add(4).ok_or_else(|| invalid("font table range overflow"))?; + let value = bytes.get(at..end).and_then(|b| b.try_into().ok()).ok_or_else(|| invalid("truncated admitted font table"))?; + Ok(u32::from_be_bytes(value)) +} + +/// A bounded original hmtx view, not a general font parser. The subset adapter +/// performs the existing exact-resource/embedding admission before plan return. +fn table<'a>(bytes: &'a [u8], tag: &[u8; 4]) -> Result<&'a [u8]> { + let count = usize::from(u16_at(bytes, 4)?); + if count == 0 || count > 19 { + return Err(invalid("font directory exceeds the reviewed resource")); + } + let mut found = None; + for i in 0..count { + let at = 12 + 16 * i; + if bytes.get(at..at + 4) != Some(tag) { + continue; + } + if found.is_some() { + return Err(invalid("duplicate font table")); + } + let start = usize::try_from(u32_at(bytes, at + 8)?).map_err(|_| invalid("font offset exceeds the platform"))?; + let length = usize::try_from(u32_at(bytes, at + 12)?).map_err(|_| invalid("font length exceeds the platform"))?; + let end = start.checked_add(length).ok_or_else(|| invalid("font table range overflow"))?; + found = bytes.get(start..end); + if found.is_none() { + return Err(invalid("font table is outside its bytes")); + } + } + found.ok_or_else(|| invalid("required font table is absent")) +} + +fn intrinsic_advance(font: &Font, gid: u16) -> Result { + if gid >= font.num_glyphs { + return Err(invalid("glyph is outside the admitted font")); + } + let count = usize::from(u16_at(table(&font.bytes, b"hhea")?, 34)?); + if count == 0 || count > usize::from(font.num_glyphs) { + return Err(invalid("invalid hmtx metric count")); + } + u16_at(table(&font.bytes, b"hmtx")?, usize::from(gid).min(count - 1) * 4) +} + +/// Current builtin bytes/face only, obtained by the existing None catalog path +/// before any installed-font, filesystem or cache lookup. This does not attest +/// mutable metrics/advances or waive the existing single subset admission. +pub(super) fn check_builtin_source(font: &Font) -> Result<()> { + if font.bytes.len() != APPROVED_FONT_BYTES { + return Err(invalid("font byte length is outside the reviewed resource envelope")); + } + let builtin = solidcraft_doc::sketch::font_data(None) + .map_err(|_| invalid("the builtin drawing font is unavailable"))?; + if builtin.index != 0 || builtin.weight.is_some() || font.face != builtin.index + || font.bytes.as_ref() != builtin.bytes() + { + return Err(invalid("font bytes/face differ from the current builtin drawing font")); + } + Ok(()) +} + +fn descriptor(font: &Font) -> Result { + // Public Font is hostile input too. Refuse its cheap byte envelope before + // hashing or looking through tables, even when the caller's plan budget is tiny. + if font.bytes.len() != APPROVED_FONT_BYTES { + return Err(invalid("font byte length is outside the reviewed resource envelope")); + } + check_builtin_source(font)?; + // B1 hashes bytes + faceLE. The existing subset admission hashes RAW bytes; + // their digests are different identities and are never compared to each other. + let m = &font.metrics; + // Original fixed-resource metadata, not fitted/default descriptor values. + // Values come from this exact Liberation Sans head/hhea/OS2/post and l glyph. + if font.face != 0 || font.postscript_name != "LiberationSans" + || font.num_glyphs != 2620 || font.units_per_em != 2048 + || m.bbox != [-1114, -621, 2666, 2007] || m.ascent != 1854 || m.descent != -434 + || m.cap_height != 1409 || m.stem_v != 180 || m.italic_angle != 0.0 + || m.flags.fixed_pitch || m.flags.serif || m.flags.italic || m.flags.symbolic + { + return Err(invalid("B1 font identity or metrics differ from the reviewed regular bundled face")); + } + let identity: [u8; 32] = Sha256::new().chain_update(font.bytes.as_ref()).chain_update(font.face.to_le_bytes()).finalize().into(); + if font.id != identity { + return Err(invalid("B1 bytes-and-face identity does not match its supplied bytes")); + } + let k = 1000.0 / f32::from(font.units_per_em); + Ok(DescriptorMetrics { + bbox_1000: m.bbox.map(|n| f32::from(n) * k), + ascent_1000: f32::from(m.ascent) * k, + descent_1000: f32::from(m.descent) * k, + cap_height_1000: f32::from(m.cap_height) * k, + italic_angle_degrees: m.italic_angle as f32, + stem_v_1000: f32::from(m.stem_v) * k, + flags: FontFlags::NON_SYMBOLIC.bits(), + }) +} + +/// Check the actual B1 cluster partition and the narrower first P2 contract +/// BEFORE allocating or subsetting. Returning an error exposes no partial plan. +fn check_run(font: &Font, run: &TextRun) -> Result { + if run.font != font.id || !(1..=4000).contains(&run.glyphs.len()) || run.text.len() > 4000 { + return Err(invalid("run font, glyph count or text length is outside B1")); + } + let cap = run.scale * f64::from(font.metrics.cap_height); + let within = |x: f64| x.is_finite() && x.abs() <= MAX_COORDINATE_MM; + if !run.scale.is_finite() || !(1e-6..1e6).contains(&cap) || cap == 1e-6 + || !within(run.origin.x) || !within(run.origin.y) + || !run.angle.is_finite() || run.angle.abs() > std::f64::consts::TAU + || !run.slant.is_finite() || run.slant.abs() > 1.0 + { + return Err(invalid("run transform is outside B1")); + } + let mut glyph_end = 0usize; + let mut text_end = if run.rtl { run.text.len() } else { 0 }; + for cluster in &run.clusters { + let (g0, g1, t0, t1) = ( + cluster.glyphs.start as usize, cluster.glyphs.end as usize, + cluster.text.start as usize, cluster.text.end as usize, + ); + if g0 != glyph_end || g0 >= g1 || t0 >= t1 || (if run.rtl { t1 != text_end } else { t0 != text_end }) { + return Err(invalid("clusters do not partition glyphs and logical text in B1 order")); + } + if g1 - g0 != 1 { + return Err(invalid("multi-glyph cluster extraction is not supported by this text-plan increment")); + } + let logical = run.text.get(t0..t1).ok_or_else(|| invalid("cluster text is not whole UTF-8 characters"))?; + if logical.len() > MAX_CLUSTER_BYTES || logical.encode_utf16().take(MAX_CLUSTER_UNITS + 1).count() > MAX_CLUSTER_UNITS { + return Err(invalid("cluster exceeds the existing ToUnicode 512-byte destination contract")); + } + let glyph = run.glyphs.get(g0).ok_or_else(|| invalid("cluster glyph is outside the run"))?; + if ![glyph.x, glyph.rise, glyph.advance].into_iter().all(within) { + return Err(invalid("placed glyph is outside B1 coordinates")); + } + let intrinsic = font.glyphs.get(&glyph.id).ok_or_else(|| invalid("glyph is absent from the B1 font table"))?; + if intrinsic.advance != intrinsic_advance(font, glyph.id)? { + return Err(invalid("B1 intrinsic advance does not match the admitted hmtx")); + } + glyph_end = g1; + text_end = if run.rtl { t0 } else { t1 }; + } + if glyph_end != run.glyphs.len() || text_end != if run.rtl { 0 } else { run.text.len() } { + return Err(invalid("clusters do not cover the whole run exactly once")); + } + Ok(run.glyphs.len()) +} + +/// Resolve an F0 run through the already validated Scene table, never by a +/// bundled number or Vec index. This increment still plans ONE font and all +/// its runs; mixed-font input is rejected by the existing plan_text checks. +/// Preparation is not proof of PDF embedding permission or trusted advances; +/// the existing owned admission/provenance boundary remains mandatory. +pub(super) fn plan_prepared_text<'a>( + prepared: &solidcraft_geom::paper::Prepared<'a>, + runs: &[&'a TextRun], + max_plan_bytes: usize, + max_subset_bytes: usize, +) -> Result> { + let first = runs.first().copied().ok_or_else(|| invalid("empty allowance or unsupported run count"))?; + let font = prepared.font(first).ok_or_else(|| invalid("run font ID is absent from the prepared scene"))?; + plan_text(font, runs, max_plan_bytes, max_subset_bytes) +} + +/// One bundled font and ALL its runs, in their existing paint order. Code keys +/// are sorted (original GID, literal text), so iteration/export repetition cannot +/// change their allocation. Code zero stays reserved for .notdef, not user text. +pub(super) fn plan_text<'a>(font: &'a Font, runs: &[&'a TextRun], max_plan_bytes: usize, max_subset_bytes: usize) -> Result> { + let limit = max_plan_bytes.min(MAX_PLAN_BYTES); + if limit == 0 || max_subset_bytes == 0 || runs.is_empty() || runs.len() > MAX_RUNS { + return Err(invalid("empty allowance or unsupported run count")); + } + let descriptor = descriptor(font)?; + let mut count = 0usize; + let mut logical_bytes = 0usize; + for run in runs { + count = count.checked_add(check_run(font, run)?).filter(|n| *n <= MAX_GLYPHS) + .ok_or_else(|| invalid("combined glyph count exceeds 16384"))?; + logical_bytes = logical_bytes.checked_add(run.text.len()).filter(|n| *n <= MAX_LOGICAL_BYTES) + .ok_or_else(|| invalid("combined logical text exceeds its allowance"))?; + } + total(&[ + bytes::<(u16, &str)>(count)?, bytes::(count)?, bytes::>(count)?, + bytes::>(count)?, bytes::>(runs.len())?, + ], limit)?; + let mut keys = reserve::<(u16, &str)>(count)?; + let mut used = reserve::(count)?; + let mut codes = reserve::>(count)?; + let mut planned_runs = reserve::>(runs.len())?; + let mut glyphs = reserve::>(count)?; + total(&[ + bytes::<(u16, &str)>(keys.capacity())?, bytes::(used.capacity())?, bytes::>(codes.capacity())?, + bytes::>(glyphs.capacity())?, bytes::>(planned_runs.capacity())?, + ], limit)?; + for run in runs { + for cluster in &run.clusters { + let glyph = run.glyphs.get(cluster.glyphs.start as usize).ok_or_else(|| invalid("checked glyph disappeared"))?; + if glyph.id == 0 { + return Err(invalid(".notdef cannot replace a missing text glyph")); + } + let logical = run.text.get(cluster.text.start as usize..cluster.text.end as usize).ok_or_else(|| invalid("checked text disappeared"))?; + keys.push((glyph.id, logical)); + } + } + keys.sort_unstable(); + keys.dedup(); + for (gid, _) in &keys { + if used.last() != Some(gid) { + used.push(*gid); + } + } + if !font.glyphs.keys().copied().eq(used.iter().copied()) { + return Err(invalid("the font table is not exactly the glyphs of the supplied runs")); + } + // Reuse the real existing admission, composite closure and subset library. + // There is no duplicate raw-font admission hash or copied font implementation. + let subset = subset_font(&font.bytes, font.face, &used, max_subset_bytes)?; + for (index, (gid, logical)) in keys.iter().enumerate() { + let code = u16::try_from(index + 1).map_err(|_| invalid("text codes exceed u16"))?; + let at = subset.mapping().binary_search_by_key(gid, |(old, _)| *old).map_err(|_| invalid("subset lost an original glyph"))?; + let (_, subset_gid) = subset.mapping().get(at).ok_or_else(|| invalid("subset mapping is incomplete"))?; + codes.push(CodeToGlyph { code, subset_gid: *subset_gid, logical }); + } + for run in runs { + let first = glyphs.len(); + let (sin, cos) = run.angle.sin_cos(); + for logical_index in 0..run.clusters.len() { + let at = if run.rtl { run.clusters.len() - 1 - logical_index } else { logical_index }; + let cluster = run.clusters.get(at).ok_or_else(|| invalid("checked cluster disappeared"))?; + let source = cluster.glyphs.start as usize; + let glyph = run.glyphs.get(source).ok_or_else(|| invalid("checked glyph disappeared"))?; + let logical = run.text.get(cluster.text.start as usize..cluster.text.end as usize).ok_or_else(|| invalid("checked text disappeared"))?; + let key = keys.binary_search(&(glyph.id, logical)).map_err(|_| invalid("text code is absent"))?; + let code = codes.get(key).ok_or_else(|| invalid("text code is outside its table"))?.code; + let matrix_mm = [ + cos, sin, cos * run.slant - sin, sin * run.slant + cos, + run.origin.x + cos * glyph.x - sin * glyph.rise, + run.origin.y + sin * glyph.x + cos * glyph.rise, + ]; + if !matrix_mm.iter().all(|n| n.is_finite()) { + return Err(invalid("glyph transform is not finite")); + } + glyphs.push(PlannedGlyph { + code, original_gid: glyph.id, source_glyph_index: source, + intrinsic_advance_fu: intrinsic_advance(font, glyph.id)?, placed_advance_mm: glyph.advance, + matrix_mm, logical, + }); + } + planned_runs.push(PlannedRun { + glyphs: first..glyphs.len(), font_size_mm: run.scale * f64::from(font.units_per_em), rtl: run.rtl, text: &run.text, + }); + } + Ok(TextPlan { font, subset, descriptor, codes, runs: planned_runs, glyphs }) +} diff --git a/proposals/drawings/2026-10-30/F0-textplan-fontobjects/deltas/acceptance-accessor-fix-from-v2.patch b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/deltas/acceptance-accessor-fix-from-v2.patch new file mode 100644 index 000000000..cbcac31d2 --- /dev/null +++ b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/deltas/acceptance-accessor-fix-from-v2.patch @@ -0,0 +1,36 @@ +diff --git a/acceptance/retained-b1-cases.rs b/acceptance/retained-b1-cases.rs +--- a/acceptance/retained-b1-cases.rs ++++ b/acceptance/retained-b1-cases.rs +@@ -40,8 +40,8 @@ + assert_eq!((g.original_gid, g.intrinsic_advance_fu, g.placed_advance_mm), (57, 1366, 0.5)); + assert_eq!(g.matrix_mm, [1.0, 0.0, 0.0, 1.0, 0.375, 0.0]); + let input = plan.font_input(*b"ABCDEF", 1 << 20); +- assert_eq!(input.postscript_name, b"LiberationSans"); +- assert_eq!(input.descriptor.unwrap().ascent_1000, 905.2734375); ++ assert_eq!(input.source.font().postscript_name.as_bytes(), b"LiberationSans"); ++ assert_eq!(input.source.descriptor().ascent_1000, 905.2734375); + } + + #[test] +@@ -52,9 +52,9 @@ + let plan = super::text_plan::plan_text(&font, &[&second, &first, &first], 1 << 20, 410_820).unwrap(); + assert_eq!(plan.glyphs().iter().map(|g| (g.code, g.logical)).collect::>(), [(2, "B"), (1, "A"), (1, "A")]); + let input = plan.font_input(*b"ABCDEF", 1 << 20); +- assert_eq!(input.codes.len(), 2); +- assert_eq!(input.codes[0].subset_gid, input.codes[1].subset_gid); +- assert_eq!((input.codes[0].logical, input.codes[1].logical), ("A", "B")); ++ assert_eq!(input.source.codes().len(), 2); ++ assert_eq!(input.source.codes()[0].subset_gid, input.source.codes()[1].subset_gid); ++ assert_eq!((input.source.codes()[0].logical, input.source.codes()[1].logical), ("A", "B")); + } + + #[test] +@@ -82,7 +82,7 @@ + run.clusters[0].text = 0..4; + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + assert_eq!(plan.glyphs()[0].logical, "fi\u{301}"); +- assert_eq!(plan.font_input(*b"ABCDEF", 1 << 20).codes[0].logical, "fi\u{301}"); ++ assert_eq!(plan.font_input(*b"ABCDEF", 1 << 20).source.codes()[0].logical, "fi\u{301}"); + } + + #[test] diff --git a/proposals/drawings/2026-10-30/F0-textplan-fontobjects/deltas/acceptance-from-owned-appendix.patch b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/deltas/acceptance-from-owned-appendix.patch new file mode 100644 index 000000000..7aad7a522 --- /dev/null +++ b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/deltas/acceptance-from-owned-appendix.patch @@ -0,0 +1,80 @@ +diff --git a/OWNED_APPENDIX_ONLY_NOT_CAM_pdf_tests.rs b/OWNED_APPENDIX_ONLY_NOT_CAM_pdf_tests.rs +--- a/OWNED_APPENDIX_ONLY_NOT_CAM_pdf_tests.rs ++++ b/OWNED_APPENDIX_ONLY_NOT_CAM_pdf_tests.rs +@@ -7,7 +7,7 @@ + let bytes: std::sync::Arc<[u8]> = std::sync::Arc::from(&include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/liberation-sans/LiberationSans-Regular.ttf"))[..]); + let id = Sha256::new().chain_update(bytes.as_ref()).chain_update(0u32.to_le_bytes()).finalize().into(); + Font { +- bundled: 0, id, bytes, face: 0, postscript_name: "LiberationSans".into(), num_glyphs: 2620, units_per_em: 2048, ++ id, bytes, face: 0, postscript_name: "LiberationSans".into(), num_glyphs: 2620, units_per_em: 2048, + metrics: FontMetrics { + ascent: 1854, descent: -434, cap_height: 1409, bbox: [-1114, -621, 2666, 2007], + italic_angle: 0.0, flags: FontFlags::default(), stem_v: 180, +@@ -21,7 +21,7 @@ + assert_eq!(text.chars().count(), ids.len()); + let chars: Vec<_> = text.char_indices().map(|(i, _)| i).chain(std::iter::once(text.len())).collect(); + TextRun { +- font: 0, scale: 1.0 / 2048.0, origin: solidcraft_geom::Vec2::new(0.0, 0.0), angle: 0.0, slant: 0.0, rtl: false, ++ font: b1_plan_font(&[]).id, scale: 1.0 / 2048.0, origin: solidcraft_geom::Vec2::new(0.0, 0.0), angle: 0.0, slant: 0.0, rtl: false, + glyphs: ids.iter().enumerate().map(|(i, &id)| PlacedGlyph { id, x: i as f64 * 0.375, rise: 0.0, advance: 0.5 }).collect(), + text: text.into(), + clusters: ids.iter().enumerate().map(|(i, _)| Cluster { glyphs: i as u32..i as u32 + 1, text: chars[i] as u32..chars[i + 1] as u32 }).collect(), +@@ -40,8 +40,8 @@ + assert_eq!((g.original_gid, g.intrinsic_advance_fu, g.placed_advance_mm), (57, 1366, 0.5)); + assert_eq!(g.matrix_mm, [1.0, 0.0, 0.0, 1.0, 0.375, 0.0]); + let input = plan.font_input(*b"ABCDEF", 1 << 20); +- assert_eq!(input.postscript_name, b"LiberationSans"); +- assert_eq!(input.descriptor.unwrap().ascent_1000, 905.2734375); ++ assert_eq!(input.source.font().postscript_name.as_bytes(), b"LiberationSans"); ++ assert_eq!(input.source.descriptor().ascent_1000, 905.2734375); + } + + #[test] +@@ -52,9 +52,9 @@ + let plan = super::text_plan::plan_text(&font, &[&second, &first, &first], 1 << 20, 410_820).unwrap(); + assert_eq!(plan.glyphs().iter().map(|g| (g.code, g.logical)).collect::>(), [(2, "B"), (1, "A"), (1, "A")]); + let input = plan.font_input(*b"ABCDEF", 1 << 20); +- assert_eq!(input.codes.len(), 2); +- assert_eq!(input.codes[0].subset_gid, input.codes[1].subset_gid); +- assert_eq!((input.codes[0].logical, input.codes[1].logical), ("A", "B")); ++ assert_eq!(input.source.codes().len(), 2); ++ assert_eq!(input.source.codes()[0].subset_gid, input.source.codes()[1].subset_gid); ++ assert_eq!((input.source.codes()[0].logical, input.source.codes()[1].logical), ("A", "B")); + } + + #[test] +@@ -82,7 +82,7 @@ + run.clusters[0].text = 0..4; + let plan = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + assert_eq!(plan.glyphs()[0].logical, "fi\u{301}"); +- assert_eq!(plan.font_input(*b"ABCDEF", 1 << 20).codes[0].logical, "fi\u{301}"); ++ assert_eq!(plan.font_input(*b"ABCDEF", 1 << 20).source.codes()[0].logical, "fi\u{301}"); + } + + #[test] +@@ -161,7 +161,7 @@ + 0 => wrong.clusters[0].glyphs.end = 2, + 1 => wrong.clusters[0].text.end = 2, + 2 => wrong.clusters.clear(), +- 3 => wrong.font = 1, ++ 3 => wrong.font[0] ^= 1, + 4 => wrong.glyphs[0].x = f64::NAN, + _ => { wrong.text = "\u{e9}".into(); wrong.clusters[0].text = 0..1; } + } +@@ -189,11 +189,11 @@ + let second = super::text_plan::plan_text(&font, &[&run], 1 << 20, 410_820).unwrap(); + let a = first.font_input(*b"ABCDEF", 1 << 20); + let b = second.font_input(*b"ABCDEF", 1 << 20); +- assert_eq!(a.subset.bytes(), b.subset.bytes()); +- assert_eq!(a.subset.mapping(), [(0, 0), (36, 1), (57, 2)]); +- assert_eq!(a.subset.mapping(), b.subset.mapping()); +- assert_eq!(a.codes.iter().map(|g| (g.code, g.subset_gid, g.logical)).collect::>(), [(1, 1, "A"), (2, 2, "V")]); +- assert_eq!(a.descriptor.unwrap().flags, pdf_writer::types::FontFlags::NON_SYMBOLIC.bits()); ++ assert_eq!(a.source.subset().bytes(), b.source.subset().bytes()); ++ assert_eq!(a.source.subset().mapping(), [(0, 0), (36, 1), (57, 2)]); ++ assert_eq!(a.source.subset().mapping(), b.source.subset().mapping()); ++ assert_eq!(a.source.codes().iter().map(|g| (g.code, g.subset_gid, g.logical)).collect::>(), [(1, 1, "A"), (2, 2, "V")]); ++ assert_eq!(a.source.descriptor().flags, pdf_writer::types::FontFlags::NON_SYMBOLIC.bits()); + } + + #[test] diff --git a/proposals/drawings/2026-10-30/F0-textplan-fontobjects/deltas/product-from-alternative-partial.patch b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/deltas/product-from-alternative-partial.patch new file mode 100644 index 000000000..a47e12124 --- /dev/null +++ b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/deltas/product-from-alternative-partial.patch @@ -0,0 +1,227 @@ +diff --git a/crates/io/src/paper/pdf/text_plan.rs b/crates/io/src/paper/pdf/text_plan.rs +--- a/crates/io/src/paper/pdf/text_plan.rs ++++ b/crates/io/src/paper/pdf/text_plan.rs +@@ -65,6 +65,23 @@ + glyphs: Vec>, + } + ++/// Borrowed only from a successfully constructed TextPlan. Private fields ++/// bind checked source records, the factory-produced subset, descriptor and ++/// codes for one immutable plan; no raw-record or serde constructor exists. ++pub(super) struct FontPlanView<'a> { ++ font: &'a Font, ++ subset: &'a SubsetFont, ++ descriptor: &'a DescriptorMetrics, ++ codes: &'a [CodeToGlyph<'a>], ++} ++ ++impl<'a> FontPlanView<'a> { ++ pub(super) fn font(&self) -> &'a Font { self.font } ++ pub(super) fn subset(&self) -> &'a SubsetFont { self.subset } ++ pub(super) fn descriptor(&self) -> &'a DescriptorMetrics { self.descriptor } ++ pub(super) fn codes(&self) -> &'a [CodeToGlyph<'a>] { self.codes } ++} ++ + impl TextPlan<'_> { + pub(super) fn runs(&self) -> &[PlannedRun<'_>] { + &self.runs +@@ -78,11 +95,12 @@ + /// globally unique subset tag, page resources and a cumulative output budget. + pub(super) fn font_input(&self, subset_tag: [u8; 6], max_chunk_bytes: usize) -> FontObjectInput<'_> { + FontObjectInput { +- source_font: self.font, +- subset: &self.subset, +- codes: &self.codes, +- descriptor: Some(&self.descriptor), +- postscript_name: self.font.postscript_name.as_bytes(), ++ source: FontPlanView { ++ font: self.font, ++ subset: &self.subset, ++ descriptor: &self.descriptor, ++ codes: &self.codes, ++ }, + subset_tag, + max_chunk_bytes, + } +@@ -159,18 +177,36 @@ + u16_at(table(&font.bytes, b"hmtx")?, usize::from(gid).min(count - 1) * 4) + } + ++/// Current builtin bytes/face only, obtained by the existing None catalog path ++/// before any installed-font, filesystem or cache lookup. This does not attest ++/// mutable metrics/advances or waive the existing single subset admission. ++pub(super) fn check_builtin_source(font: &Font) -> Result<()> { ++ if font.bytes.len() != APPROVED_FONT_BYTES { ++ return Err(invalid("font byte length is outside the reviewed resource envelope")); ++ } ++ let builtin = solidcraft_doc::sketch::font_data(None) ++ .map_err(|_| invalid("the builtin drawing font is unavailable"))?; ++ if builtin.index != 0 || builtin.weight.is_some() || font.face != builtin.index ++ || font.bytes.as_ref() != builtin.bytes() ++ { ++ return Err(invalid("font bytes/face differ from the current builtin drawing font")); ++ } ++ Ok(()) ++} ++ + fn descriptor(font: &Font) -> Result { + // Public Font is hostile input too. Refuse its cheap byte envelope before + // hashing or looking through tables, even when the caller's plan budget is tiny. + if font.bytes.len() != APPROVED_FONT_BYTES { + return Err(invalid("font byte length is outside the reviewed resource envelope")); + } ++ check_builtin_source(font)?; + // B1 hashes bytes + faceLE. The existing subset admission hashes RAW bytes; + // their digests are different identities and are never compared to each other. + let m = &font.metrics; + // Original fixed-resource metadata, not fitted/default descriptor values. + // Values come from this exact Liberation Sans head/hhea/OS2/post and l glyph. +- if font.bundled != 0 || font.face != 0 || font.postscript_name != "LiberationSans" ++ if font.face != 0 || font.postscript_name != "LiberationSans" + || font.num_glyphs != 2620 || font.units_per_em != 2048 + || m.bbox != [-1114, -621, 2666, 2007] || m.ascent != 1854 || m.descent != -434 + || m.cap_height != 1409 || m.stem_v != 180 || m.italic_angle != 0.0 +diff --git a/crates/io/src/paper/pdf/font_objects.rs b/crates/io/src/paper/pdf/font_objects.rs +--- a/crates/io/src/paper/pdf/font_objects.rs ++++ b/crates/io/src/paper/pdf/font_objects.rs +@@ -15,10 +15,10 @@ + use pdf_writer::types::{CidFontType, FontFlags, SystemInfo}; + use pdf_writer::{Chunk, Name, Rect, Ref, Str}; + +-use sha2::{Digest, Sha256}; + use solidcraft_geom::paper::text::Font; + + use super::subset_font::SubsetFont; ++use super::text_plan::{FontPlanView, check_builtin_source}; + use super::to_unicode::write_to_unicode; + use crate::{IoError, MAX_DRAWING_BYTES, Result}; + +@@ -140,19 +140,26 @@ + } + } + +-/// IO parameters borrowing the actual B1 resource, not a global allocator. +-/// Advances must come from the trusted bundled B1 producer, not JSON assertions; +-/// resource identity alone does not attest its public per-glyph fields. ++/// Production parameters: the source, subset, descriptor and codes are bound ++/// by an opaque view obtainable only from a successful TextPlan. + pub(super) struct FontObjectInput<'a> { +- pub(super) source_font: &'a Font, +- pub(super) subset: &'a SubsetFont, +- pub(super) codes: &'a [CodeToGlyph<'a>], +- pub(super) descriptor: Option<&'a DescriptorMetrics>, +- pub(super) postscript_name: &'a [u8], ++ pub(super) source: FontPlanView<'a>, + pub(super) subset_tag: [u8; 6], + pub(super) max_chunk_bytes: usize, + } + ++/// Internal preparation components, never an independently callable production ++/// input. Component tests below retain their synthetic scope via private aliases. ++struct FontObjectParts<'a> { ++ source_font: &'a Font, ++ subset: &'a SubsetFont, ++ codes: &'a [CodeToGlyph<'a>], ++ descriptor: Option<&'a DescriptorMetrics>, ++ postscript_name: &'a [u8], ++ subset_tag: [u8; 6], ++ max_chunk_bytes: usize, ++} ++ + fn invalid(message: &'static str) -> IoError { + IoError::Invalid(message.into()) + } +@@ -196,23 +203,25 @@ + impl<'a> B1Widths<'a> { + fn read(font: &'a Font, subset: &'a SubsetFont) -> Result { + // Public B1 fields are bounded before digest, table walks or allocation. +- // The actual subset factory admits just these source bytes/face and +- // validates its returned program. Its private fields cannot be forged +- // here. This identity check binds B1 to that same fixed-source policy; +- // it does not cryptographically attest caller-modified advance records. ++ // Production obtains these bound records only through FontPlanView; ++ // TextPlan already checked every used original-GID advance and the ++ // single admitted subset chain. These repeated cheap identity/mapping ++ // guards also retain the independent synthetic component-test scope. + if font.bytes.len() != MAX_FONT_BYTES { + return Err(invalid("B1 font byte envelope differs from the reviewed resource")); + } +- if font.bundled != 0 || font.face != 0 || font.postscript_name.as_bytes() != POSTSCRIPT_NAME ++ if font.face != 0 || font.postscript_name.as_bytes() != POSTSCRIPT_NAME + || font.num_glyphs != 2620 || font.units_per_em != 2048 + || font.glyphs.len() > usize::from(font.num_glyphs) + || font.glyphs.keys().any(|gid| *gid >= font.num_glyphs) + { + return Err(invalid("B1 font metadata differs from the reviewed regular face")); + } +- let identity: [u8; 32] = Sha256::new().chain_update(font.bytes.as_ref()) +- .chain_update(font.face.to_le_bytes()).finalize().into(); +- if font.id != identity || identity != REVIEWED_B1_ID { ++ // Exact current builtin bytes/face replace the removed numeric index. ++ // The plan already checked bytes+face ID and admitted the SAME source ++ // through subset_font. Compare the fixed B1 ID here without rehashing. ++ check_builtin_source(font)?; ++ if font.id != REVIEWED_B1_ID { + return Err(invalid("B1 font bytes/face/id do not identify the reviewed resource")); + } + let glyphs = subset.mapping().len(); +@@ -295,7 +304,7 @@ + bound: usize, + } + +-fn prepare(input: FontObjectInput<'_>) -> Result> { ++fn prepare(input: FontObjectParts<'_>) -> Result> { + let descriptor = input.descriptor.ok_or_else(|| invalid("essential font descriptor metrics are missing"))?; + let flags = descriptor.validate()?; + let name = fixed_font_name(input.postscript_name, input.subset_tag)?; +@@ -370,6 +379,21 @@ + /// Ref IDs/tag globally and later attach the Type0 ref to page resources. + /// No caller Pdf is borrowed, so Result refusals cannot mutate that document. + pub(super) fn font_objects(refs: FontObjectRefs, input: FontObjectInput<'_>) -> Result { ++ let source = input.source; ++ font_objects_parts(refs, FontObjectParts { ++ source_font: source.font(), ++ subset: source.subset(), ++ codes: source.codes(), ++ descriptor: Some(source.descriptor()), ++ postscript_name: source.font().postscript_name.as_bytes(), ++ subset_tag: input.subset_tag, ++ max_chunk_bytes: input.max_chunk_bytes, ++ }) ++} ++ ++/// The raw preparation path is private to this module. Outside callers cannot ++/// supply an independent Font/Subset pair or manufacture a validated view. ++fn font_objects_parts(refs: FontObjectRefs, input: FontObjectParts<'_>) -> Result { + refs.validate()?; + let prepared = prepare(input)?; + let Prepared { font, unicode, cid_map, widths, default_width, name, descriptor, flags, limit, bound } = prepared; +@@ -423,6 +447,10 @@ + #[cfg(test)] + mod tests { + use super::*; ++ // Synthetic serialization/refusal components are not proof constructors. ++ // Only these descendant tests can call the module-private raw parts path. ++ use super::{FontObjectParts as FontObjectInput, font_objects_parts as font_objects}; ++ use sha2::{Digest, Sha256}; + use super::super::subset_font::subset_font; + + // Unchanged legacy metric reader retained as a test-only independent +@@ -555,7 +583,7 @@ + FONT.get_or_init(|| { + use solidcraft_geom::paper::text::{FontFlags as B1Flags, FontGlyph, FontMetrics}; + Font { +- bundled: 0, id: REVIEWED_B1_ID, bytes: std::sync::Arc::from(BUNDLED), face: 0, ++ id: REVIEWED_B1_ID, bytes: std::sync::Arc::from(BUNDLED), face: 0, + postscript_name: "LiberationSans".into(), num_glyphs: 2620, units_per_em: 2048, + metrics: FontMetrics { + ascent: 1854, descent: -434, cap_height: 1409, bbox: [-1114, -621, 2666, 2007], +@@ -1144,7 +1172,7 @@ + let mut font = source_font().clone(); + match case { + 0 => font.face = 1, +- 1 => font.bundled = 1, ++ 1 => { let mut bytes = font.bytes.to_vec(); bytes[4096] ^= 1; font.bytes = std::sync::Arc::from(bytes); }, + 2 => font.units_per_em = 0, + 3 => font.units_per_em = 1024, + 4 => font.num_glyphs = 0, diff --git a/proposals/drawings/2026-10-30/F0-textplan-fontobjects/deltas/product-from-canonical.patch b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/deltas/product-from-canonical.patch new file mode 100644 index 000000000..598f9f160 --- /dev/null +++ b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/deltas/product-from-canonical.patch @@ -0,0 +1,259 @@ +diff --git a/crates/io/src/paper/pdf/text_plan.rs b/crates/io/src/paper/pdf/text_plan.rs +--- a/crates/io/src/paper/pdf/text_plan.rs ++++ b/crates/io/src/paper/pdf/text_plan.rs +@@ -65,6 +65,23 @@ + glyphs: Vec>, + } + ++/// Borrowed only from a successfully constructed TextPlan. Private fields ++/// bind checked source records, the factory-produced subset, descriptor and ++/// codes for one immutable plan; no raw-record or serde constructor exists. ++pub(super) struct FontPlanView<'a> { ++ font: &'a Font, ++ subset: &'a SubsetFont, ++ descriptor: &'a DescriptorMetrics, ++ codes: &'a [CodeToGlyph<'a>], ++} ++ ++impl<'a> FontPlanView<'a> { ++ pub(super) fn font(&self) -> &'a Font { self.font } ++ pub(super) fn subset(&self) -> &'a SubsetFont { self.subset } ++ pub(super) fn descriptor(&self) -> &'a DescriptorMetrics { self.descriptor } ++ pub(super) fn codes(&self) -> &'a [CodeToGlyph<'a>] { self.codes } ++} ++ + impl TextPlan<'_> { + pub(super) fn runs(&self) -> &[PlannedRun<'_>] { + &self.runs +@@ -78,11 +95,12 @@ + /// globally unique subset tag, page resources and a cumulative output budget. + pub(super) fn font_input(&self, subset_tag: [u8; 6], max_chunk_bytes: usize) -> FontObjectInput<'_> { + FontObjectInput { +- source_font: self.font, +- subset: &self.subset, +- codes: &self.codes, +- descriptor: Some(&self.descriptor), +- postscript_name: self.font.postscript_name.as_bytes(), ++ source: FontPlanView { ++ font: self.font, ++ subset: &self.subset, ++ descriptor: &self.descriptor, ++ codes: &self.codes, ++ }, + subset_tag, + max_chunk_bytes, + } +@@ -159,18 +177,36 @@ + u16_at(table(&font.bytes, b"hmtx")?, usize::from(gid).min(count - 1) * 4) + } + ++/// Current builtin bytes/face only, obtained by the existing None catalog path ++/// before any installed-font, filesystem or cache lookup. This does not attest ++/// mutable metrics/advances or waive the existing single subset admission. ++pub(super) fn check_builtin_source(font: &Font) -> Result<()> { ++ if font.bytes.len() != APPROVED_FONT_BYTES { ++ return Err(invalid("font byte length is outside the reviewed resource envelope")); ++ } ++ let builtin = solidcraft_doc::sketch::font_data(None) ++ .map_err(|_| invalid("the builtin drawing font is unavailable"))?; ++ if builtin.index != 0 || builtin.weight.is_some() || font.face != builtin.index ++ || font.bytes.as_ref() != builtin.bytes() ++ { ++ return Err(invalid("font bytes/face differ from the current builtin drawing font")); ++ } ++ Ok(()) ++} ++ + fn descriptor(font: &Font) -> Result { + // Public Font is hostile input too. Refuse its cheap byte envelope before + // hashing or looking through tables, even when the caller's plan budget is tiny. + if font.bytes.len() != APPROVED_FONT_BYTES { + return Err(invalid("font byte length is outside the reviewed resource envelope")); + } ++ check_builtin_source(font)?; + // B1 hashes bytes + faceLE. The existing subset admission hashes RAW bytes; + // their digests are different identities and are never compared to each other. + let m = &font.metrics; + // Original fixed-resource metadata, not fitted/default descriptor values. + // Values come from this exact Liberation Sans head/hhea/OS2/post and l glyph. +- if font.bundled != 0 || font.face != 0 || font.postscript_name != "LiberationSans" ++ if font.face != 0 || font.postscript_name != "LiberationSans" + || font.num_glyphs != 2620 || font.units_per_em != 2048 + || m.bbox != [-1114, -621, 2666, 2007] || m.ascent != 1854 || m.descent != -434 + || m.cap_height != 1409 || m.stem_v != 180 || m.italic_angle != 0.0 +@@ -197,7 +233,7 @@ + /// Check the actual B1 cluster partition and the narrower first P2 contract + /// BEFORE allocating or subsetting. Returning an error exposes no partial plan. + fn check_run(font: &Font, run: &TextRun) -> Result { +- if run.font != font.bundled || !(1..=4000).contains(&run.glyphs.len()) || run.text.len() > 4000 { ++ if run.font != font.id || !(1..=4000).contains(&run.glyphs.len()) || run.text.len() > 4000 { + return Err(invalid("run font, glyph count or text length is outside B1")); + } + let cap = run.scale * f64::from(font.metrics.cap_height); +@@ -241,6 +277,22 @@ + return Err(invalid("clusters do not cover the whole run exactly once")); + } + Ok(run.glyphs.len()) ++} ++ ++/// Resolve an F0 run through the already validated Scene table, never by a ++/// bundled number or Vec index. This increment still plans ONE font and all ++/// its runs; mixed-font input is rejected by the existing plan_text checks. ++/// Preparation is not proof of PDF embedding permission or trusted advances; ++/// the existing owned admission/provenance boundary remains mandatory. ++pub(super) fn plan_prepared_text<'a>( ++ prepared: &solidcraft_geom::paper::Prepared<'a>, ++ runs: &[&'a TextRun], ++ max_plan_bytes: usize, ++ max_subset_bytes: usize, ++) -> Result> { ++ let first = runs.first().copied().ok_or_else(|| invalid("empty allowance or unsupported run count"))?; ++ let font = prepared.font(first).ok_or_else(|| invalid("run font ID is absent from the prepared scene"))?; ++ plan_text(font, runs, max_plan_bytes, max_subset_bytes) + } + + /// One bundled font and ALL its runs, in their existing paint order. Code keys +diff --git a/crates/io/src/paper/pdf/font_objects.rs b/crates/io/src/paper/pdf/font_objects.rs +--- a/crates/io/src/paper/pdf/font_objects.rs ++++ b/crates/io/src/paper/pdf/font_objects.rs +@@ -15,10 +15,10 @@ + use pdf_writer::types::{CidFontType, FontFlags, SystemInfo}; + use pdf_writer::{Chunk, Name, Rect, Ref, Str}; + +-use sha2::{Digest, Sha256}; + use solidcraft_geom::paper::text::Font; + + use super::subset_font::SubsetFont; ++use super::text_plan::{FontPlanView, check_builtin_source}; + use super::to_unicode::write_to_unicode; + use crate::{IoError, MAX_DRAWING_BYTES, Result}; + +@@ -140,19 +140,26 @@ + } + } + +-/// IO parameters borrowing the actual B1 resource, not a global allocator. +-/// Advances must come from the trusted bundled B1 producer, not JSON assertions; +-/// resource identity alone does not attest its public per-glyph fields. ++/// Production parameters: the source, subset, descriptor and codes are bound ++/// by an opaque view obtainable only from a successful TextPlan. + pub(super) struct FontObjectInput<'a> { +- pub(super) source_font: &'a Font, +- pub(super) subset: &'a SubsetFont, +- pub(super) codes: &'a [CodeToGlyph<'a>], +- pub(super) descriptor: Option<&'a DescriptorMetrics>, +- pub(super) postscript_name: &'a [u8], ++ pub(super) source: FontPlanView<'a>, + pub(super) subset_tag: [u8; 6], + pub(super) max_chunk_bytes: usize, + } + ++/// Internal preparation components, never an independently callable production ++/// input. Component tests below retain their synthetic scope via private aliases. ++struct FontObjectParts<'a> { ++ source_font: &'a Font, ++ subset: &'a SubsetFont, ++ codes: &'a [CodeToGlyph<'a>], ++ descriptor: Option<&'a DescriptorMetrics>, ++ postscript_name: &'a [u8], ++ subset_tag: [u8; 6], ++ max_chunk_bytes: usize, ++} ++ + fn invalid(message: &'static str) -> IoError { + IoError::Invalid(message.into()) + } +@@ -196,23 +203,25 @@ + impl<'a> B1Widths<'a> { + fn read(font: &'a Font, subset: &'a SubsetFont) -> Result { + // Public B1 fields are bounded before digest, table walks or allocation. +- // The actual subset factory admits just these source bytes/face and +- // validates its returned program. Its private fields cannot be forged +- // here. This identity check binds B1 to that same fixed-source policy; +- // it does not cryptographically attest caller-modified advance records. ++ // Production obtains these bound records only through FontPlanView; ++ // TextPlan already checked every used original-GID advance and the ++ // single admitted subset chain. These repeated cheap identity/mapping ++ // guards also retain the independent synthetic component-test scope. + if font.bytes.len() != MAX_FONT_BYTES { + return Err(invalid("B1 font byte envelope differs from the reviewed resource")); + } +- if font.bundled != 0 || font.face != 0 || font.postscript_name.as_bytes() != POSTSCRIPT_NAME ++ if font.face != 0 || font.postscript_name.as_bytes() != POSTSCRIPT_NAME + || font.num_glyphs != 2620 || font.units_per_em != 2048 + || font.glyphs.len() > usize::from(font.num_glyphs) + || font.glyphs.keys().any(|gid| *gid >= font.num_glyphs) + { + return Err(invalid("B1 font metadata differs from the reviewed regular face")); + } +- let identity: [u8; 32] = Sha256::new().chain_update(font.bytes.as_ref()) +- .chain_update(font.face.to_le_bytes()).finalize().into(); +- if font.id != identity || identity != REVIEWED_B1_ID { ++ // Exact current builtin bytes/face replace the removed numeric index. ++ // The plan already checked bytes+face ID and admitted the SAME source ++ // through subset_font. Compare the fixed B1 ID here without rehashing. ++ check_builtin_source(font)?; ++ if font.id != REVIEWED_B1_ID { + return Err(invalid("B1 font bytes/face/id do not identify the reviewed resource")); + } + let glyphs = subset.mapping().len(); +@@ -295,7 +304,7 @@ + bound: usize, + } + +-fn prepare(input: FontObjectInput<'_>) -> Result> { ++fn prepare(input: FontObjectParts<'_>) -> Result> { + let descriptor = input.descriptor.ok_or_else(|| invalid("essential font descriptor metrics are missing"))?; + let flags = descriptor.validate()?; + let name = fixed_font_name(input.postscript_name, input.subset_tag)?; +@@ -370,6 +379,21 @@ + /// Ref IDs/tag globally and later attach the Type0 ref to page resources. + /// No caller Pdf is borrowed, so Result refusals cannot mutate that document. + pub(super) fn font_objects(refs: FontObjectRefs, input: FontObjectInput<'_>) -> Result { ++ let source = input.source; ++ font_objects_parts(refs, FontObjectParts { ++ source_font: source.font(), ++ subset: source.subset(), ++ codes: source.codes(), ++ descriptor: Some(source.descriptor()), ++ postscript_name: source.font().postscript_name.as_bytes(), ++ subset_tag: input.subset_tag, ++ max_chunk_bytes: input.max_chunk_bytes, ++ }) ++} ++ ++/// The raw preparation path is private to this module. Outside callers cannot ++/// supply an independent Font/Subset pair or manufacture a validated view. ++fn font_objects_parts(refs: FontObjectRefs, input: FontObjectParts<'_>) -> Result { + refs.validate()?; + let prepared = prepare(input)?; + let Prepared { font, unicode, cid_map, widths, default_width, name, descriptor, flags, limit, bound } = prepared; +@@ -423,6 +447,10 @@ + #[cfg(test)] + mod tests { + use super::*; ++ // Synthetic serialization/refusal components are not proof constructors. ++ // Only these descendant tests can call the module-private raw parts path. ++ use super::{FontObjectParts as FontObjectInput, font_objects_parts as font_objects}; ++ use sha2::{Digest, Sha256}; + use super::super::subset_font::subset_font; + + // Unchanged legacy metric reader retained as a test-only independent +@@ -555,7 +583,7 @@ + FONT.get_or_init(|| { + use solidcraft_geom::paper::text::{FontFlags as B1Flags, FontGlyph, FontMetrics}; + Font { +- bundled: 0, id: REVIEWED_B1_ID, bytes: std::sync::Arc::from(BUNDLED), face: 0, ++ id: REVIEWED_B1_ID, bytes: std::sync::Arc::from(BUNDLED), face: 0, + postscript_name: "LiberationSans".into(), num_glyphs: 2620, units_per_em: 2048, + metrics: FontMetrics { + ascent: 1854, descent: -434, cap_height: 1409, bbox: [-1114, -621, 2666, 2007], +@@ -1144,7 +1172,7 @@ + let mut font = source_font().clone(); + match case { + 0 => font.face = 1, +- 1 => font.bundled = 1, ++ 1 => { let mut bytes = font.bytes.to_vec(); bytes[4096] ^= 1; font.bytes = std::sync::Arc::from(bytes); }, + 2 => font.units_per_em = 0, + 3 => font.units_per_em = 1024, + 4 => font.num_glyphs = 0, diff --git a/proposals/drawings/2026-10-30/F0-textplan-fontobjects/source-bindings.json b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/source-bindings.json new file mode 100644 index 000000000..9c1ff5d6f --- /dev/null +++ b/proposals/drawings/2026-10-30/F0-textplan-fontobjects/source-bindings.json @@ -0,0 +1,261 @@ +{ + "format_version": 1, + "repository": "tangency-labs/solidcraft", + "status": "SOURCE_ONLY_UNFORMATTED_UNCOMPILED_UNRUN_UNREGISTERED", + "producer": { + "B1a_PR": 9512, + "B1a_head": "16c9e9119214a3595b1303e2f1116cd067986c38", + "B1b_PR": 9513, + "B1b_head": "a46d46e95a7f5c7680ae7440d3c9989846947128", + "drawings_base": "562bb379a5b426506d7fc75cc069bc0936044671", + "owner_reply": "https://github.com/tangency-labs/solidcraft/issues/4890#issuecomment-6532962216", + "contract": "TextRun.font names Font.id; paper_text returns unique used Vec; no public Font.bundled or invented Font.embed.", + "Font_embed": "F2 pending; not present in this proposal" + }, + "lineage": { + "public_predecessor_commit": "5f127aceb09f04dcfe6e4dc1d0253a292787dffa", + "public_predecessor_url": "https://github.com/tangency-labs/solidcraft/tree/5f127aceb09f04dcfe6e4dc1d0253a292787dffa/proposals/drawings/2026-10-30/P2-width-Refs-composition", + "private_source_v3_manifest_sha256": "1b6f64a24513cb069efd76708fd8788dd29ff09da802ea662c1a60da2bbc24ed", + "v2_manifest_sha256": "6795b37c0189fed058a04ecf618e50cf34c6bc3952b2a14b62a0ff97d1b323f6", + "canonical_private_predecessor_manifest_sha256": "c1981fe32538252f848da8ef1bb1bab440cc97b826308b36e5bfd6070a0f5262", + "alternative_partial_manifest_sha256": "a1bc785b5fa6fb39f8a07359631110de5ccf30ec50464a0e48d1315a073a953e", + "no_single_composed_Git_head": true + }, + "source_reviews": { + "prior_product_boundary_review_sha256": "eddb84822dda988afac07d3eae718b2d7dc90a2a078b6f815af9fbb34955b2e0", + "v2_review_sha256": "faf09fbe4b49279770681338e417a5d36b58fd7e0f2416712fa80270f952a649", + "v3_focal_accessor_closure_sha256": "335195903fca30866b1dbef23417b191439bee063e6bf35487858151c40c1fcf", + "scope": "The single accessor source finding is closed. Two product candidates/patches are unchanged from v2; the focal closure is not a fresh compiler, negative-compilation result, PDF result or full-feature review." + }, + "product_candidates": [ + { + "path": "candidate/crates/io/src/paper/pdf/text_plan.rs", + "sha256": "eddb5120912b934c41fd58cea345c9cc8e74f067995336da8401737a9a2fc027", + "bytes": 18699 + }, + { + "path": "candidate/crates/io/src/paper/pdf/font_objects.rs", + "sha256": "393ed32fb7a7633fa949ad6758fe9989cab4633ea3771752886c3404558d8a33", + "bytes": 58307 + } + ], + "patch_routes": { + "canonical": { + "patch": "deltas/product-from-canonical.patch", + "baselines": { + "crates/io/src/paper/pdf/text_plan.rs": "before/canonical/crates/io/src/paper/pdf/text_plan.rs", + "crates/io/src/paper/pdf/font_objects.rs": "before/canonical/crates/io/src/paper/pdf/font_objects.rs" + } + }, + "alternative_partial": { + "patch": "deltas/product-from-alternative-partial.patch", + "baselines": { + "crates/io/src/paper/pdf/text_plan.rs": "before/alternative-partial/crates/io/src/paper/pdf/text_plan.rs", + "crates/io/src/paper/pdf/font_objects.rs": "before/canonical/crates/io/src/paper/pdf/font_objects.rs" + } + }, + "retained_acceptance_from_original": { + "patch": "deltas/acceptance-from-owned-appendix.patch", + "logical_patch_filename": "OWNED_APPENDIX_ONLY_NOT_CAM_pdf_tests.rs", + "baseline": "before/acceptance/owned-b1-cases.rs", + "candidate": "acceptance/retained-b1-cases.rs" + }, + "retained_acceptance_from_v2": { + "patch": "deltas/acceptance-accessor-fix-from-v2.patch", + "logical_patch_filename": "acceptance/retained-b1-cases.rs", + "baseline": "before/acceptance/v2-retained-b1-cases.rs", + "candidate": "acceptance/retained-b1-cases.rs" + }, + "alternatives_not_sequential": true, + "mixed_per_file_component_bases": true, + "normal_existing_test_file_adoption_required": true + }, + "acceptance": { + "ordinary_declarations": { + "existing_font_objects_inline": 24, + "retained_B1": 13, + "F0_wrapper": 4, + "production_boundary": 5, + "total": 46 + }, + "negative_compile_obligations": 4, + "negative_file": "acceptance/negative-compile-obligations.rs", + "negative_obligations_are_not_ordinary_tests": true, + "negative_diagnostics_expected_not_observed": true, + "ordinary_cases_not_reclassified_as_negative": true, + "v3_delta": "Exactly6 normal acceptance lines/eight field reads use existing immutable view getters; no product/oracle/fixture/expected-value/seed/tolerance/budget change.", + "all_registered": false, + "all_compiled": false, + "all_executed": false + }, + "checked_boundary": { + "mint": "TextPlan::font_input only constructs FontPlanView after plan_text returns successfully.", + "view_private_fields": [ + "font", + "subset", + "descriptor", + "codes" + ], + "public_production_input": [ + "source:FontPlanView", + "subset_tag", + "max_chunk_bytes" + ], + "raw_parts": "FontObjectParts and font_objects_parts are module-private, no safe sibling/public/serde entry; descendant component tests use explicit private aliases, never mint the view.", + "same_immutable_source_subset": true, + "checks_preserved": [ + "cheap byte/record allowances", + "exact descriptor metadata", + "bytes+face B1 ID", + "original-GID FontGlyph.advance vs original hmtx", + "exact used-glyph table", + "one subset_font\u2192glyph_closure\u2192check_liberation_sans RAW admission", + "subset mapping/program guards", + "all Ref/tag/code/finite/missing/DW/output caps" + ] + }, + "builtin_source_identity": { + "api": "solidcraft_doc::sketch::font_data(None)", + "fields": "fresh index0/weightNone; bounded original-byte slice equality and face equality", + "before_filesystem_or_cache": true, + "substitution_or_fallback": false, + "new_parser": false, + "new_admission": false, + "duplicate_hash": false, + "B1_hash_in_textplan": "existing bytes||faceLE check retained", + "B1_hash_in_fontobjects": "removed redundant recomputation; fixed reviewedB1ID and exact builtin source comparison retained", + "RAW_SHA256": "075e71be4c58beda172ecb574a799308f04c3d054c6a5b7434954d3b0f1b28d8", + "B1_ID": "af02dbc8839b7cadae15e528aa3d9ff85c545b715b551d218bf38a937ee7e2b0", + "licence_or_F2_waiver": false + }, + "unmodified_source_admission": { + "font_admission": { + "repository_path": "crates/io/src/paper/pdf/font_admission.rs", + "sha256": "a8abc3b4aaef9325694ec404512c228f9973b82006b5718eb304ef57d5c30b23", + "bytes": 4170 + }, + "glyph_closure": { + "repository_path": "crates/io/src/paper/pdf/glyph_closure.rs", + "sha256": "a8d94c9996a5c718346e66d1983e6d2f2edb224286d3f45e92d731ab0013f1d8", + "bytes": 38397 + }, + "subset_font": { + "repository_path": "crates/io/src/paper/pdf/subset_font.rs", + "sha256": "a9808063f2223fd9e86e208d55092b6b9e9a5ae7ba0eaba2dce5d557a7fd5f26", + "bytes": 8941 + } + }, + "upstream_source_pins": [ + { + "path": "b1a-text", + "repository_path": "crates/geom/src/paper/text.rs", + "url": "https://github.com/CamWight/solidcraft/blob/16c9e9119214a3595b1303e2f1116cd067986c38/crates/geom/src/paper/text.rs", + "blob_sha1": "f16f1e703323a11a0dfbd17de680278006aca997", + "sha256": "8b813342836802bdd6f7955ae26bcc3a605c2e9e6e358e4a2097c330d860eb65", + "bytes": 14124 + }, + { + "path": "f0-text", + "repository_path": "crates/geom/src/paper/text.rs", + "url": "https://github.com/CamWight/solidcraft/blob/a46d46e95a7f5c7680ae7440d3c9989846947128/crates/geom/src/paper/text.rs", + "blob_sha1": "f16f1e703323a11a0dfbd17de680278006aca997", + "sha256": "8b813342836802bdd6f7955ae26bcc3a605c2e9e6e358e4a2097c330d860eb65", + "bytes": 14124 + }, + { + "path": "f0-paper", + "repository_path": "crates/geom/src/paper.rs", + "url": "https://github.com/CamWight/solidcraft/blob/a46d46e95a7f5c7680ae7440d3c9989846947128/crates/geom/src/paper.rs", + "blob_sha1": "f8f924b0529255efed81b5d2eaa00ae6e8692cb6", + "sha256": "5b9fb55ddcfb1d1fa488622dfc69b6d2ee5545943e0d453645aaf8b421bf75d5", + "bytes": 10593 + }, + { + "path": "f0-layout", + "repository_path": "crates/sketch/src/paper_text.rs", + "url": "https://github.com/CamWight/solidcraft/blob/a46d46e95a7f5c7680ae7440d3c9989846947128/crates/sketch/src/paper_text.rs", + "blob_sha1": "63a73ef4c34fe9a1a206e60dd9527b90744b078f", + "sha256": "6b3dcb84ba8cdac8b50ee264443b0ac5e27296a1cd02f48ac74a5b2e80908553", + "bytes": 10871 + }, + { + "path": "f0-layout-tests", + "repository_path": "crates/sketch/src/paper_text_tests.rs", + "url": "https://github.com/CamWight/solidcraft/blob/a46d46e95a7f5c7680ae7440d3c9989846947128/crates/sketch/src/paper_text_tests.rs", + "blob_sha1": "bab262b09dd31d93df6e50fe7cc7ca5385a28c60", + "sha256": "6c06017f6afbeae37856e7298135a03efdad85b4b1ab89b928deb425828b88a4", + "bytes": 9807 + }, + { + "path": "f0-record-tests", + "repository_path": "crates/geom/src/paper/text_tests.rs", + "url": "https://github.com/CamWight/solidcraft/blob/a46d46e95a7f5c7680ae7440d3c9989846947128/crates/geom/src/paper/text_tests.rs", + "blob_sha1": "16ffc7677f85ff0aff8a6ca67bc30e21cfffdfbc", + "sha256": "0799c62e97576c1483437a15d72c58fe7dda1441e21019405b4cb65d90bd2ce3", + "bytes": 12753 + }, + { + "path": "font_admission.rs", + "repository_path": "crates/io/src/paper/pdf/font_admission.rs", + "url": "https://github.com/tangency-labs/solidcraft/blob/bf2a6fd567b03e1d25dcb66624e719a0cec109fc/crates/io/src/paper/pdf/font_admission.rs", + "blob_sha1": "632d21b81d25626dd5fe6e3b28d274a96a640382", + "sha256": "a8abc3b4aaef9325694ec404512c228f9973b82006b5718eb304ef57d5c30b23", + "bytes": 4170 + }, + { + "path": "subset_font.rs", + "repository_path": "crates/io/src/paper/pdf/subset_font.rs", + "url": "https://github.com/tangency-labs/solidcraft/blob/bf2a6fd567b03e1d25dcb66624e719a0cec109fc/crates/io/src/paper/pdf/subset_font.rs", + "blob_sha1": "cef7bd532639faf95f5ec5f9ea7451b79b03c688", + "sha256": "a9808063f2223fd9e86e208d55092b6b9e9a5ae7ba0eaba2dce5d557a7fd5f26", + "bytes": 8941 + }, + { + "path": "public-sources/9513-a46d/crates/sketch/src/fonts.rs", + "repository_path": "crates/sketch/src/fonts.rs", + "url": "https://github.com/CamWight/solidcraft/blob/a46d46e95a7f5c7680ae7440d3c9989846947128/crates/sketch/src/fonts.rs", + "blob_sha1": "4b104ec49eac9516dc2f69aa56fff779eccdb7f2", + "sha256": "f497592266ef11a4071d550277cf61c75ce4d2e6e40e4e0e3b8da6e06969c3d0", + "bytes": 22385 + }, + { + "path": "public-sources/9513-a46d/crates/doc/src/lib.rs", + "repository_path": "crates/doc/src/lib.rs", + "url": "https://github.com/CamWight/solidcraft/blob/a46d46e95a7f5c7680ae7440d3c9989846947128/crates/doc/src/lib.rs", + "blob_sha1": "0123c4bac25559c19a9f3e9c0043dfbc46dd3b3d", + "sha256": "e67a61f9ef907a36105d0689a7808cad3e44175a14607d3f78a246af7e81a882", + "bytes": 4091 + }, + { + "path": "public-sources/9513-a46d/crates/io/Cargo.toml", + "repository_path": "crates/io/Cargo.toml", + "url": "https://github.com/CamWight/solidcraft/blob/a46d46e95a7f5c7680ae7440d3c9989846947128/crates/io/Cargo.toml", + "blob_sha1": "e9a701fe1a60be6b30e083a911554a78a2e15b2e", + "sha256": "e19c93f548baf29442657ec74e5307bccceaccf202491d80f192ed234bb55ce2", + "bytes": 1467 + } + ], + "Cam_parent_and_allocator": "Actual9647ce505658 parent/Refs remains untouched; no content/registration or old-byte result is supplied by this two-file boundary proposal.", + "DW_single_question": { + "url": "https://github.com/tangency-labs/solidcraft/pull/7626#issuecomment-6532370208", + "status": "Answered by Cam6534292604; v3 was sealed before this decision.", + "reply_url": "https://github.com/tangency-labs/solidcraft/pull/7626#issuecomment-6534292604" + }, + "authorship": "Worker #1 and Engineer team original proposal/acceptance; referenced Cam/P2/font code retains existing original authorship and licences. No binary font/asset or new dependency included.", + "owner_DW_decision_now": { + "url": "https://github.com/tangency-labs/solidcraft/pull/7626#issuecomment-6534292604", + "author": "CamWight", + "created_at": "2026-10-30T21:53:12Z", + "policy": "Complete explicit W for every emitted CID, no reliance on DW, no B1 GID0 width. Embedded program .notdef is separate.", + "status": "OWNER_CONTRACT_RESOLVED_SUCCESSOR_IMPLEMENTATION_PENDING", + "archived_v3_product_unchanged": true, + "new_question_posted": false + }, + "archived_v3_implementation_limits": [ + "V3 still refuses missing GID0. The owner has NOW resolved the policy as complete W for every emitted CID without DW fallback; separate v4 implementation/validation is pending. No product change in this payload.", + "Parent module/content/font-resource registration, all-runs-per-font grouping and aggregate budgets remain outside this change.", + "Multi-glyph ActualText/extraction remains explicitly unsupported.", + "Exact integration/dependency/lock/compiler/native/wasm/CI/render/readback/old-vs-new PDF byte acceptance remain unrun.", + "Embedding/package licensing and future Font.embed F2 remain separate; source view certifies only performed checks, not arbitrary outlines or historical origin of all public data." + ] +} diff --git a/proposals/drawings/README.md b/proposals/drawings/README.md index 31448085c..de0c4c18d 100644 --- a/proposals/drawings/README.md +++ b/proposals/drawings/README.md @@ -35,3 +35,14 @@ These folders deliberately remain outside production module registration. Each R owned width-provider and actual #9647 Refs seam without changing Cam's builder. Mixed per-file bases, strict DW/trust blockers and79 unrun source declarations are explicit. This is not a registered, tested or merged implementation. + +## P2 F0 checked font-plan source — v3 + +[Source-only F0 v3 packet](2026-10-30/F0-textplan-fontobjects/README.md) binds the +actual font-ID/used-font-list contract at 9512`16c9e911` / 9513`a46d46e9`. It preserves +two product proposals, exact before/candidate/alternative deltas, 46 ordinary +declarations and 4 separate negative compile obligations, all unrun/unregistered. +The narrow acceptance-accessor source finding is closed. Cam has resolved DW +as full emitted-CID W coverage; this historical v3 still refuses absent GID 0 +while its separate successor, F2, parent integration and real acceptance remain pending. Earlier archives +and contributor windows are preserved; this is not an integrated or ready head.