wip(drawings): preserve F0 checked font-plan sources and original acceptance

This commit is contained in:
selune committed 2026-10-30 23:33:09 +01:00
1 parent 5f127aceb0
commit 45286e0489
18 files changed
+5229

No files matched your search

@@ -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<Font>`. 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.
@@ -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;
}
@@ -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<solidcraft_geom::paper::text::TextRun>,
fonts: Vec<solidcraft_geom::paper::text::Font>,
) -> 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");
}
@@ -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::<Vec<_>>(),
[(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));
}
@@ -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::<Vec<_>>(), [(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::<String>(), "AB");
assert_eq!(plan.glyphs().iter().map(|g| g.source_glyph_index).collect::<Vec<_>>(), [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::<Vec<_>>(), [(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}");
}
}
@@ -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::<Vec<_>>(), [(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::<String>(), "AB");
assert_eq!(plan.glyphs().iter().map(|g| g.source_glyph_index).collect::<Vec<_>>(), [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::<Vec<_>>(), [(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}");
}
}
@@ -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::<Vec<_>>(), [(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::<String>(), "AB");
assert_eq!(plan.glyphs().iter().map(|g| g.source_glyph_index).collect::<Vec<_>>(), [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::<Vec<_>>(), [(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}");
}
}
@@ -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<usize>,
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<CodeToGlyph<'a>>,
runs: Vec<PlannedRun<'a>>,
glyphs: Vec<PlannedGlyph<'a>>,
}
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<T>(count: usize) -> Result<Vec<T>> {
let mut values = Vec::new();
values.try_reserve_exact(count).map_err(|_| invalid("cannot allocate bounded plan storage"))?;
Ok(values)
}
fn bytes<T>(count: usize) -> Result<usize> {
count.checked_mul(size_of::<T>()).ok_or_else(|| invalid("plan storage overflow"))
}
fn total(parts: &[usize], limit: usize) -> Result<usize> {
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<u16> {
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<u32> {
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<u16> {
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<DescriptorMetrics> {
// 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<usize> {
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<TextPlan<'a>> {
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<TextPlan<'a>> {
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::<u16>(count)?, bytes::<CodeToGlyph<'_>>(count)?,
bytes::<PlannedGlyph<'_>>(count)?, bytes::<PlannedRun<'_>>(runs.len())?,
], limit)?;
let mut keys = reserve::<(u16, &str)>(count)?;
let mut used = reserve::<u16>(count)?;
let mut codes = reserve::<CodeToGlyph<'_>>(count)?;
let mut planned_runs = reserve::<PlannedRun<'_>>(runs.len())?;
let mut glyphs = reserve::<PlannedGlyph<'_>>(count)?;
total(&[
bytes::<(u16, &str)>(keys.capacity())?, bytes::<u16>(used.capacity())?, bytes::<CodeToGlyph<'_>>(codes.capacity())?,
bytes::<PlannedGlyph<'_>>(glyphs.capacity())?, bytes::<PlannedRun<'_>>(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 })
}
@@ -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<usize>,
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<CodeToGlyph<'a>>,
runs: Vec<PlannedRun<'a>>,
glyphs: Vec<PlannedGlyph<'a>>,
}
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<T>(count: usize) -> Result<Vec<T>> {
let mut values = Vec::new();
values.try_reserve_exact(count).map_err(|_| invalid("cannot allocate bounded plan storage"))?;
Ok(values)
}
fn bytes<T>(count: usize) -> Result<usize> {
count.checked_mul(size_of::<T>()).ok_or_else(|| invalid("plan storage overflow"))
}
fn total(parts: &[usize], limit: usize) -> Result<usize> {
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<u16> {
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<u32> {
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<u16> {
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<DescriptorMetrics> {
// 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<usize> {
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<TextPlan<'a>> {
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::<u16>(count)?, bytes::<CodeToGlyph<'_>>(count)?,
bytes::<PlannedGlyph<'_>>(count)?, bytes::<PlannedRun<'_>>(runs.len())?,
], limit)?;
let mut keys = reserve::<(u16, &str)>(count)?;
let mut used = reserve::<u16>(count)?;
let mut codes = reserve::<CodeToGlyph<'_>>(count)?;
let mut planned_runs = reserve::<PlannedRun<'_>>(runs.len())?;
let mut glyphs = reserve::<PlannedGlyph<'_>>(count)?;
total(&[
bytes::<(u16, &str)>(keys.capacity())?, bytes::<u16>(used.capacity())?, bytes::<CodeToGlyph<'_>>(codes.capacity())?,
bytes::<PlannedGlyph<'_>>(glyphs.capacity())?, bytes::<PlannedRun<'_>>(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 })
}
@@ -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<usize>,
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<CodeToGlyph<'a>>,
runs: Vec<PlannedRun<'a>>,
glyphs: Vec<PlannedGlyph<'a>>,
}
/// 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<T>(count: usize) -> Result<Vec<T>> {
let mut values = Vec::new();
values.try_reserve_exact(count).map_err(|_| invalid("cannot allocate bounded plan storage"))?;
Ok(values)
}
fn bytes<T>(count: usize) -> Result<usize> {
count.checked_mul(size_of::<T>()).ok_or_else(|| invalid("plan storage overflow"))
}
fn total(parts: &[usize], limit: usize) -> Result<usize> {
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<u16> {
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<u32> {
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<u16> {
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<DescriptorMetrics> {
// 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<usize> {
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<TextPlan<'a>> {
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<TextPlan<'a>> {
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::<u16>(count)?, bytes::<CodeToGlyph<'_>>(count)?,
bytes::<PlannedGlyph<'_>>(count)?, bytes::<PlannedRun<'_>>(runs.len())?,
], limit)?;
let mut keys = reserve::<(u16, &str)>(count)?;
let mut used = reserve::<u16>(count)?;
let mut codes = reserve::<CodeToGlyph<'_>>(count)?;
let mut planned_runs = reserve::<PlannedRun<'_>>(runs.len())?;
let mut glyphs = reserve::<PlannedGlyph<'_>>(count)?;
total(&[
bytes::<(u16, &str)>(keys.capacity())?, bytes::<u16>(used.capacity())?, bytes::<CodeToGlyph<'_>>(codes.capacity())?,
bytes::<PlannedGlyph<'_>>(glyphs.capacity())?, bytes::<PlannedRun<'_>>(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 })
}
@@ -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::<Vec<_>>(), [(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]
@@ -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::<Vec<_>>(), [(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::<Vec<_>>(), [(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::<Vec<_>>(), [(1, 1, "A"), (2, 2, "V")]);
+ assert_eq!(a.source.descriptor().flags, pdf_writer::types::FontFlags::NON_SYMBOLIC.bits());
}
#[test]
@@ -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<PlannedGlyph<'a>>,
}
+/// 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<DescriptorMetrics> {
// 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<Self> {
// 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<Prepared<'_>> {
+fn prepare(input: FontObjectParts<'_>) -> Result<Prepared<'_>> {
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<Chunk> {
+ 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<Chunk> {
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,
@@ -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<PlannedGlyph<'a>>,
}
+/// 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<DescriptorMetrics> {
// 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<usize> {
- 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<TextPlan<'a>> {
+ 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<Self> {
// 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<Prepared<'_>> {
+fn prepare(input: FontObjectParts<'_>) -> Result<Prepared<'_>> {
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<Chunk> {
+ 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<Chunk> {
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,
@@ -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<Font>; 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."
]
}
+11
View File
@@ -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.