diff --git a/crates/texrra-tex-core/src/native_font.rs b/crates/texrra-tex-core/src/native_font.rs index 9a58f9d..f0a073b 100644 --- a/crates/texrra-tex-core/src/native_font.rs +++ b/crates/texrra-tex-core/src/native_font.rs @@ -25,6 +25,10 @@ pub struct NativeFontPaint { pub glyph_paths: BTreeMap, pub bbox: [i32; 4], pub stem_v: i32, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub(crate) subset: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) descriptor_flags: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) xdv_descriptor: Option, pub resources: Vec, @@ -34,6 +38,20 @@ pub struct NativeFontPaint { pub(crate) type Type1ProgramKey<'a> = (&'a ResourceVersion, Type1Transform); +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub(crate) struct MappedType1 { + pub version: ResourceVersion, + pub font: Arc, + pub flags: i32, + pub subset: bool, +} + +impl MappedType1 { + pub(crate) fn key(&self) -> Type1ProgramKey<'_> { + (&self.version, self.font.transform) + } +} + impl NativeFontPaint { pub(crate) fn has_pdf_space(&self, font: &NativeFont) -> bool { // pdfTeX requires the space name in an actual map re-encoding. @@ -440,6 +458,8 @@ fn resolve_physical_fonts( glyph_paths, bbox: bbox.unwrap(), stem_v: 0, + subset: false, + descriptor_flags: None, xdv_descriptor: None, resources: entry.as_ref().and_then(|entry| entry.version.as_ref()) .or(default_version).cloned().into_iter() @@ -457,6 +477,8 @@ fn resolve_physical_fonts( file.to_owned(), outline.encoding.clone(), outline.transform, + outline.subset, + outline.descriptor_flags, ); if !cache.contains_key(&key) { let from = outline.from.to_string_lossy(); @@ -490,6 +512,8 @@ fn resolve_physical_fonts( glyph_paths: BTreeMap::new(), bbox: decoded.bbox, stem_v: decoded.stem_v, + subset: outline.subset && !xdv, + descriptor_flags: outline.descriptor_flags, xdv_descriptor: if xdv { Some(decoded.xdv_descriptor.get_or_init(|| { decoded.outlines.xdv_descriptor(program.bbox) diff --git a/crates/texrra-tex-core/src/native_font/map.rs b/crates/texrra-tex-core/src/native_font/map.rs index 05c07a9..d0d7ddb 100644 --- a/crates/texrra-tex-core/src/native_font/map.rs +++ b/crates/texrra-tex-core/src/native_font/map.rs @@ -1,5 +1,5 @@ //! PDF font map entries, lookup bindings, and the lifetime of the default map. -use super::{NativeFont, verify_resource}; +use super::{MappedType1, NativeFont, verify_resource}; use crate::{ execution::{FontId, SourceProvider}, resources::{LoadedResource, ResourceKind, ResourceVersion}, @@ -17,13 +17,13 @@ pub(super) struct MapEntry { pub version: Option, file: Option, #[serde(default, skip_serializing_if = "std::ops::Not::not")] - subset: bool, + pub(super) subset: bool, pub encoding: Option, postscript_name: bool, #[serde(default, skip_serializing_if = "Option::is_none")] ps_name: Option, #[serde(default, skip_serializing_if = "Option::is_none")] - descriptor_flags: Option, + pub(super) descriptor_flags: Option, #[serde(default, skip_serializing_if = "Type1Transform::is_identity")] pub transform: Type1Transform, } @@ -268,7 +268,7 @@ impl JobFontMap { pub(super) fn imported_type1_program( &mut self, name: &str, from: &Path, files: &mut impl SourceProvider, - ) -> Result, String> { + ) -> Result, String> { let (name, transform) = imported_postscript_name(name); if self.bindings.is_none() { self.initialize(true, from, files)?; @@ -286,7 +286,12 @@ impl JobFontMap { self.used_names.insert(tfm.clone()); } self.used_postscript.insert(key); - Ok(Some((font, entry.descriptor_flags.unwrap_or(4), entry.subset))) + Ok(Some(MappedType1 { + version: resource.version, + font: Arc::new(font), + flags: entry.descriptor_flags.unwrap_or(4), + subset: entry.subset, + })) } pub(super) fn command( diff --git a/crates/texrra-tex-core/src/native_font/virtual_paint.rs b/crates/texrra-tex-core/src/native_font/virtual_paint.rs index 9927167..ffc6a5a 100644 --- a/crates/texrra-tex-core/src/native_font/virtual_paint.rs +++ b/crates/texrra-tex-core/src/native_font/virtual_paint.rs @@ -408,7 +408,7 @@ impl JobVirtualFonts { pub(crate) fn imported_type1_program( &mut self, name: &str, from: &std::path::Path, files: &mut impl SourceProvider, - ) -> Result, String> { + ) -> Result, String> { self.font_map.imported_type1_program(name, from, files) } diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index b86990b..06a3dcb 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -21,6 +21,7 @@ use crate::render::{DisplayItem, DisplayList, FontFace}; use crate::type1::Type1Font; #[path = "pdf_text.rs"] pub(crate) mod native_text; +pub(crate) mod type1_fonts; #[path = "pdf_objects.rs"] pub(crate) mod objects; #[path = "pdf_pk.rs"] @@ -1653,21 +1654,11 @@ fn native_pdf_name(name: &str) -> String { }) .collect() } -struct NativeType1Descriptor<'a> { - metrics: &'a crate::tfm::TfmMetrics, - object: Option, -} - -fn write_native_type1_descriptor( - objects: &mut Vec>, +fn native_type1_parameters( font: &Type1Font, paint: &crate::native_font::NativeFontPaint, metrics: &crate::tfm::TfmMetrics, - compression: u8, -) -> usize { - let descriptor = objects.len() + 1; - let program = descriptor + 1; - let name = native_pdf_name(&font.name); +) -> String { let [left, bottom, right, top] = paint.bbox; let units = |n: i64| native_font_units(n, native_pdf_font_size(metrics.size_sp()), 1000); // TFM slot conventions of the profile, independent of glyph names in @@ -1683,38 +1674,29 @@ fn write_native_type1_descriptor( } else { font.italic_angle.parse::().unwrap_or(0.).round().to_string() }; - let descriptor_bytes = if let Some(xdv) = paint.xdv_descriptor { + if let Some(xdv) = paint.xdv_descriptor { let [left, bottom, right, top] = font.bbox; let [ascent, descent, cap, stem_v] = xdv.metrics(); let flags = flags | (i32::from(!font.name.contains("Sans")) << 1) | (i32::from(font.name.contains("Caps")) << 17) | (i32::from(xdv.force_bold) << 18); - format!("<< /Type /FontDescriptor /FontName /{name} /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /StemV {stem_v} /FontFile {program} 0 R >>") + format!("/Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /StemV {stem_v}") } else { + let flags = paint.descriptor_flags.unwrap_or(4); let stem_v = paint.stem_v; - format!("<< /Type /FontDescriptor /FontName /{name} /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /XHeight {x_height} /StemV {stem_v} /FontFile {program} 0 R >>") - }; - objects.push(descriptor_bytes.into_bytes()); - objects.push(objects::stream( - &format!( - "/Length1 {} /Length2 {} /Length3 {}", - font.length1, font.length2, font.length3 - ), - &font.program, - compression, - )); - descriptor + format!("/Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /XHeight {x_height} /StemV {stem_v}") + } } -fn write_native_font<'font>( +fn write_native_font( objects: &mut Vec>, face: &crate::native_font::NativeFont, - paint: &'font crate::native_font::NativeFontPaint, + paint: &crate::native_font::NativeFontPaint, used: &BTreeMap, compression: u8, options: Option>, diagnostics: &mut Vec, - descriptors: &mut HashMap, NativeType1Descriptor<'_>>, + reference: Option<&type1_fonts::Reference>, ) -> usize { let font = match &paint.program { crate::native_font::NativeFontProgram::Type1(font) => font, @@ -1725,12 +1707,10 @@ fn write_native_font<'font>( let id = objects.len() + 1; objects.push(Vec::new()); let m = face.metrics(); - let descriptor = match paint.type1_program_key().and_then(|key| descriptors.get_mut(&key)) { - Some(shared) => *shared.object.get_or_insert_with(|| { - write_native_type1_descriptor(objects, font, paint, shared.metrics, compression) - }), - None => write_native_type1_descriptor(objects, font, paint, m, compression), - }; + let descriptor = reference.map_or_else( + || type1_fonts::write_full(objects, font, &native_type1_parameters(font, paint, m), compression), + |shared| shared.object, + ); let unicode = objects.len() + 1; let first = *used.keys().next().unwrap(); let last = *used.keys().next_back().unwrap(); @@ -1791,7 +1771,7 @@ fn write_native_font<'font>( } else { String::new() }; - let name = native_pdf_name(&font.name); + let name = native_pdf_name(reference.map_or(font.name.as_str(), |shared| shared.name.as_str())); objects[id - 1] = format!("<< /Type /Font /Subtype /Type1 /BaseFont /{name} /FirstChar {first} /LastChar {last} /Widths [{widths}] /Encoding << /Type /Encoding /Differences [0 {differences}] >> /FontDescriptor {descriptor} 0 R {unicode_ref} >>").into_bytes(); if let Some(cmap) = cmap { objects.push(objects::stream("", &cmap, compression)); @@ -2095,7 +2075,7 @@ fn write_pdf( } let mut native_used = BTreeMap::new(); let mut type1_names = HashSet::new(); - let mut type1_descriptors = HashMap::new(); + let mut type1_descriptor_faces = HashMap::new(); let mut opentype_used = opentype_fonts::UsedFonts::default(); for page in pages { for item in &page.items { @@ -2117,10 +2097,7 @@ fn write_pdf( // descriptor, while each font keeps its own encoding. if let Some(program) = paint.type1_program_key() { if type1_names.insert((program, font.name.as_str())) { - type1_descriptors.insert( - program, - NativeType1Descriptor { metrics: font.metrics(), object: None }, - ); + type1_descriptor_faces.insert(program, font.id); } } (font.clone(), paint.clone(), BTreeMap::new()) @@ -2150,6 +2127,57 @@ fn write_pdf( )); } } + // Use the form registered by shipout when one exists. A placement + // retains its measured source image and can precede that registration. + let declarations = pages.iter().flat_map(|list| &list.items).filter_map(|item| { + if let DisplayItem::PdfImageObject(object) = item { + Some((object.image.id, object.image.image.as_ref(), object.attributes.as_slice(), object.compression)) + } else { + None + } + }); + let placements = pages.iter().flat_map(|list| { + let compression = list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression); + list.items.iter().filter_map(move |item| { + if let DisplayItem::PdfImage { image, .. } = item { + Some((image.id, image.image.as_ref(), &[][..], compression)) + } else { + None + } + }) + }); + let mut image_ids = HashSet::new(); + let images: Vec<_> = declarations.chain(placements) + .filter(|(id, ..)| image_ids.insert(*id)) + .collect(); + + let compression = final_compression.unwrap_or(0).clamp(0, 9) as u8; + let mut type1_plans = type1_fonts::FontPlans::default(); + // pdfTeX collects included font descriptors as it writes forms. The + // TeX font dictionaries and their glyph marks are finalized afterward. + for (_, image, _, _) in &images { + for font in image.mapped_type1_fonts() { + type1_plans.include(font); + } + } + for (face, paint, used) in native_used.values() { + let crate::native_font::NativeFontProgram::Type1(program) = &paint.program else { + continue; + }; + let Some(key) = paint.type1_program_key() else { + continue; + }; + let (owner, owner_paint) = type1_descriptor_faces.get(&key) + .map_or((face, paint), |id| { + let (face, paint, _) = &native_used[id]; + (face, paint) + }); + let glyphs = used.keys().map(|slot| paint.encoding[usize::from(*slot)].as_str()); + type1_plans.paint(key, program, owner_paint.subset, + || native_type1_parameters(program, owner_paint, owner.metrics()), glyphs); + } + let type1_references = type1_plans.write(&mut objects, compression)?; + let mut native_font_ids = BTreeMap::new(); for (&id, (face, paint, used)) in &native_used { native_font_ids.insert( @@ -2159,10 +2187,10 @@ fn write_pdf( face, paint, used, - final_compression.unwrap_or(0).max(0).min(9) as u8, + compression, unicode, diagnostics, - &mut type1_descriptors, + paint.type1_program_key().and_then(|key| type1_references.get(&key)), ), ); } @@ -2355,31 +2383,9 @@ fn write_pdf( .first() .and_then(|page| page.pdf.as_ref()) .map_or((1, 4), |pdf| (pdf.file.major, i32::from(pdf.file.minor))); - let mut form_ids = BTreeMap::new(); - for list in pages { - for item in &list.items { - if let DisplayItem::PdfImageObject(object) = item { - form_ids.entry(object.image.id).or_insert_with(|| { - object.image.image.append_to( - &mut objects, - &object.attributes, - object.compression, - pdf_version, - ) - }); - } - } - } - for list in pages { - for item in &list.items { - if let DisplayItem::PdfImage { image, .. } = item { - form_ids.entry(image.id).or_insert_with(|| { - let compression = list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression); - image.image.append_to(&mut objects, &[], compression, pdf_version) - }); - } - } - } + let form_ids: BTreeMap<_, _> = images.into_iter().map(|(id, image, attributes, compression)| { + (id, image.append_to(&mut objects, attributes, compression, pdf_version, &type1_references)) + }).collect(); let mut png_group = None; for (page_index, list) in pages.iter().enumerate() { let png_group_ref = if !list.pdf_resources.has_page_group diff --git a/crates/texrra-tex-core/src/pdf/type1_fonts.rs b/crates/texrra-tex-core/src/pdf/type1_fonts.rs new file mode 100644 index 0000000..872375f --- /dev/null +++ b/crates/texrra-tex-core/src/pdf/type1_fonts.rs @@ -0,0 +1,177 @@ +//! Document-wide physical Type 1 embeddings for TeX glyphs and included PDFs. +use super::{native_pdf_name, objects}; +use crate::{ + native_font::Type1ProgramKey, + pdf_image::ImportedType1Use, + type1::Type1Font, + type1_outline::{subset_tag, write_subset}, +}; +use std::{ + collections::{BTreeSet, HashMap}, + fmt::Write as _, +}; + +pub(crate) struct Reference { + pub object: usize, + pub name: String, +} + +pub(crate) type References<'a> = HashMap, Reference>; + +struct FontPlan<'a> { + font: &'a Type1Font, + parameters: String, + subset: bool, + all_glyphs: bool, + glyphs: BTreeSet, +} + +#[derive(Default)] +pub(super) struct FontPlans<'a>(HashMap, FontPlan<'a>>); + +impl<'a> FontPlans<'a> { + pub(super) fn include(&mut self, use_: &'a ImportedType1Use) { + let plan = self.0.entry(use_.mapped.key()).or_insert_with(|| { + let font = &use_.mapped.font; + let [left, bottom, right, top] = font.bbox; + let angle = &font.italic_angle; + let flags = use_.mapped.flags; + let stem_v = use_.stem_v; + FontPlan { + font, + parameters: format!( + "/Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} \ + /Ascent {top} /Descent {bottom} /CapHeight {top} /StemV {stem_v}" + ), + subset: use_.mapped.subset, + all_glyphs: false, + glyphs: BTreeSet::new(), + } + }); + if let Some(glyphs) = &use_.glyphs { + plan.glyphs.extend(glyphs.iter().cloned()); + } else { + plan.all_glyphs = true; + } + } + + pub(super) fn paint( + &mut self, + key: Type1ProgramKey<'a>, + font: &'a Type1Font, + subset: bool, + parameters: impl FnOnce() -> String, + glyphs: impl Iterator, + ) { + let plan = self.0.entry(key).or_insert_with(|| FontPlan { + font, + parameters: parameters(), + subset, + all_glyphs: false, + glyphs: BTreeSet::new(), + }); + if plan.subset { + plan.glyphs.extend( + glyphs + .filter(|glyph| *glyph != ".notdef") + .map(str::to_owned), + ); + } + } + + pub(super) fn write( + self, + objects: &mut Vec>, + compression: u8, + ) -> Result, String> { + let mut plans: Vec<_> = self.0.into_iter().collect(); + plans.sort_unstable_by(|((a, at), _), ((b, bt), _)| { + (a.path.file_name(), at, &a.path, &a.sha256, a.bytes).cmp(&( + b.path.file_name(), + bt, + &b.path, + &b.sha256, + b.bytes, + )) + }); + let mut tags = BTreeSet::new(); + let mut references = HashMap::new(); + for (key, plan) in plans { + let reference = if plan.subset { + let tag = (0..100) + .map(|salt| subset_tag(&plan.font.name, &plan.glyphs, salt)) + .find(|tag| tags.insert(tag.clone())) + .ok_or("Type1 subset name collision limit exceeded")?; + let subset = write_subset(plan.font, &plan.glyphs, plan.all_glyphs, &tag)?; + let lengths = [subset.length1, subset.program.len() - subset.length1, 0]; + Reference { + object: write_embedding( + objects, + &subset.name, + &plan.parameters, + Some(&subset.glyphs), + &subset.program, + lengths, + compression, + ), + name: subset.name, + } + } else { + Reference { + object: write_full(objects, plan.font, &plan.parameters, compression), + name: plan.font.name.clone(), + } + }; + references.insert(key, reference); + } + Ok(references) + } +} + +pub(super) fn write_full( + objects: &mut Vec>, + font: &Type1Font, + parameters: &str, + compression: u8, +) -> usize { + write_embedding( + objects, + &font.name, + parameters, + None, + &font.program, + [font.length1, font.length2, font.length3], + compression, + ) +} + +fn write_embedding( + objects: &mut Vec>, + name: &str, + parameters: &str, + glyphs: Option<&BTreeSet>, + program: &[u8], + lengths: [usize; 3], + compression: u8, +) -> usize { + let descriptor = objects.len() + 1; + let file = descriptor + 1; + let name = native_pdf_name(name); + let mut body = format!("<< /Type /FontDescriptor /FontName /{name} {parameters}"); + if let Some(glyphs) = glyphs { + body.push_str(" /CharSet <"); + for glyph in glyphs { + body.push_str("2F"); + for byte in glyph.bytes() { + write!(body, "{byte:02X}").unwrap(); + } + } + body.push('>'); + } + write!(body, " /FontFile {file} 0 R >>").unwrap(); + objects.push(body.into_bytes()); + let [clear, private, trailer] = lengths; + let keys = format!("/Length1 {clear} /Length2 {private} /Length3 {trailer}"); + objects.push(objects::stream(&keys, program, compression)); + descriptor +} diff --git a/crates/texrra-tex-core/src/pdf_image.rs b/crates/texrra-tex-core/src/pdf_image.rs index ddd4e00..1011966 100644 --- a/crates/texrra-tex-core/src/pdf_image.rs +++ b/crates/texrra-tex-core/src/pdf_image.rs @@ -3,6 +3,7 @@ mod bmp; mod jpeg; mod icc; mod imported_fonts; +pub(crate) use imported_fonts::ImportedType1Use; mod png; use crate::{ pdf_device::Affine, @@ -330,6 +331,7 @@ enum Part { Png(png::SampledImage), Bmp(png::SampledImage), XdvCmykDecode, + MappedType1(Arc), } pub(crate) fn real(value: f64) -> String { @@ -724,6 +726,7 @@ impl PdfImage { attributes: &[u8], compression: u8, pdf_version: (i32, i32), + fonts: &crate::pdf::type1_fonts::References<'_>, ) -> usize { if let Some(samples) = self.sampled_image() { return samples.append(pdf, attributes, compression, pdf_version); @@ -742,6 +745,12 @@ impl PdfImage { match part { Part::Bytes(bytes) | Part::Jpeg { bytes, .. } => body.extend_from_slice(bytes), Part::Ref(id) => write!(body, "{} 0 R", base + id).unwrap(), + Part::MappedType1(font) => { + let reference = &fonts[&font.mapped.key()]; + body.extend_from_slice(b" /BaseFont "); + body.extend(pdf_name(reference.name.as_bytes())); + write!(body, " /FontDescriptor {} 0 R", reference.object).unwrap(); + } Part::Png(_) | Part::Bmp(_) => unreachable!("sampled image owns its objects"), Part::XdvCmykDecode => { if !attributes diff --git a/crates/texrra-tex-core/src/pdf_image/imported_fonts.rs b/crates/texrra-tex-core/src/pdf_image/imported_fonts.rs index 645e9aa..c0c468f 100644 --- a/crates/texrra-tex-core/src/pdf_image/imported_fonts.rs +++ b/crates/texrra-tex-core/src/pdf_image/imported_fonts.rs @@ -1,9 +1,9 @@ //! Replacement of fonts in the root resources of an included pdfTeX page. -use super::{Graph, Part, PdfImage, number, pdf_name, resolved}; -use crate::type1::{Type1Font, builtin_encoding, standard_encoding}; +use super::{Graph, Part, PdfImage, number, resolved}; +use crate::{native_font::MappedType1, type1::{builtin_encoding, standard_encoding}}; use lopdf::{Dictionary, Document, Object, Stream}; use read_fonts::ps::cff::CffFontRef; -use std::{borrow::Cow, collections::BTreeSet}; +use std::{borrow::Cow, collections::BTreeSet, sync::Arc}; #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub(super) struct ImportedType1 { @@ -256,79 +256,51 @@ fn replace_implicit_encoding( Ok(Some(generated)) } +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub(crate) struct ImportedType1Use { + pub mapped: MappedType1, + pub stem_v: i32, + pub glyphs: Option>, +} + impl PdfImage { + pub(crate) fn mapped_type1_fonts(&self) -> impl Iterator { + self.objects.iter().flatten().filter_map(|part| { + if let Part::MappedType1(font) = part { + Some(font.as_ref()) + } else { + None + } + }) + } + pub(crate) fn has_imported_fonts(&self) -> bool { !self.imported_fonts.is_empty() } pub(crate) fn resolve_imported_fonts( &self, - mut load: impl FnMut(&str) -> Result, String>, + mut load: impl FnMut(&str) -> Result, String>, ) -> Result, String> { let mut result: Option = None; for entry in &self.imported_fonts { - let Some((program, flags, allow_subset)) = load(&entry.postscript_name)? else { + let Some(mapped) = load(&entry.postscript_name)? else { continue; }; - let subset = entry.charset.as_deref().filter(|_| allow_subset) + let glyphs = entry.charset.as_deref().filter(|_| mapped.subset) .map(|bytes| { - let charset = std::str::from_utf8(bytes) + let names = std::str::from_utf8(bytes) .map_err(|_| "invalid glyph name in imported Type1 CharSet")?; - let glyphs = charset.split('/').filter(|name| !name.is_empty()).map(str::to_owned).collect(); - crate::type1_outline::write_subset(&program, &glyphs) + Ok::<_, &str>(names.split('/').skip(1) + .filter_map(|part| part.split_ascii_whitespace().next()) + .map(str::to_owned).collect()) }) .transpose()?; - let font_name = subset.as_ref().map_or(program.name.as_str(), |subset| subset.name.as_str()); + let stem_v = crate::type1_outline::pdftex_stem_v(&mapped.font)?.unwrap_or(entry.stem_v); let mut dictionary = entry.dictionary.clone()?; - let mut name = b" /BaseFont ".to_vec(); - name.extend(pdf_name(font_name.as_bytes())); - name.extend(b" /FontDescriptor "); - let image = result.get_or_insert_with(|| self.clone()); - let descriptor = image.objects.len(); - dictionary.push(Part::Bytes(name)); - dictionary.push(Part::Ref(descriptor)); + dictionary.push(Part::MappedType1(Arc::new(ImportedType1Use { mapped, stem_v, glyphs }))); dictionary.push(Part::Bytes(b">>".to_vec())); - image.objects[entry.index] = dictionary; - - let [left, bottom, right, top] = program.bbox; - let angle = &program.italic_angle; - let stem_v = crate::type1_outline::pdftex_stem_v(&program)?.unwrap_or(entry.stem_v); - let mut body = b"<< /Type /FontDescriptor /FontName ".to_vec(); - body.extend(pdf_name(font_name.as_bytes())); - body.extend(format!( - " /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} \ - /Ascent {top} /Descent {bottom} /CapHeight {top} /StemV {stem_v}", - ).into_bytes()); - if let Some(subset) = &subset { - use std::fmt::Write as _; - let mut charset = String::from(" /CharSet <"); - for glyph in &subset.glyphs { - charset.push_str("2F"); - for byte in glyph.bytes() { - write!(charset, "{byte:02X}").unwrap(); - } - } - charset.push('>'); - body.extend(charset.bytes()); - } - body.extend_from_slice(b" /FontFile "); - image.objects.push(vec![ - Part::Bytes(body), - Part::Ref(descriptor + 1), - Part::Bytes(b">>".to_vec()), - ]); - let ([header, private, trailer], bytes) = subset.as_ref().map_or( - ([program.length1, program.length2, program.length3], program.program.as_slice()), - |subset| ([subset.length1, subset.program.len() - subset.length1, 0], subset.program.as_slice()), - ); - let keys = format!("/Length1 {header} /Length2 {private} /Length3 {trailer}"); - image - .objects - .push(vec![Part::Bytes(crate::pdf::objects::stream( - &keys, - bytes, - 0, - ))]); + result.get_or_insert_with(|| self.clone()).objects[entry.index] = dictionary; } if let Some(image) = result.as_mut() { image.imported_fonts.clear(); diff --git a/crates/texrra-tex-core/src/type1_outline.rs b/crates/texrra-tex-core/src/type1_outline.rs index f34fb80..0fc2fb9 100644 --- a/crates/texrra-tex-core/src/type1_outline.rs +++ b/crates/texrra-tex-core/src/type1_outline.rs @@ -4,7 +4,7 @@ use crate::type1::{Type1Font, font_matrix, standard_encoding}; use std::collections::BTreeMap; mod subset; -pub(crate) use subset::write_subset; +pub(crate) use subset::{subset_tag, write_subset}; use subset::{GlyphUse, ProgramRanges, SubrRange}; fn decrypt(data: &[u8], mut key: u16, skip: usize) -> Result, String> { if data.len() < skip { diff --git a/crates/texrra-tex-core/src/type1_outline/subset.rs b/crates/texrra-tex-core/src/type1_outline/subset.rs index 9c1e1d6..c2973f2 100644 --- a/crates/texrra-tex-core/src/type1_outline/subset.rs +++ b/crates/texrra-tex-core/src/type1_outline/subset.rs @@ -37,15 +37,24 @@ pub(crate) struct SubsetProgram { pub(crate) fn write_subset( font: &Type1Font, requested: &BTreeSet, + all_glyphs: bool, + tag: &str, ) -> Result { let private = private_dictionary(font)?; let mut ranges = ProgramRanges::default(); let outlines = Type1Outlines::from_private(font, &private, Some(&mut ranges))?; let mut usage = GlyphUse::default(); - for name in std::iter::once(".notdef").chain(requested.iter().map(String::as_str)) { - if outlines.has_glyph(name) && !usage.names.contains(name) { - let mut budget = 1_000_000; - outlines.commands(name, 0, &mut budget, Some(&mut usage))?; + if all_glyphs { + usage.names.extend(outlines.glyphs.keys().cloned()); + if let Some((count, _)) = &ranges.subr_size { + usage.subrs.extend(0..*count); + } + } else { + for name in std::iter::once(".notdef").chain(requested.iter().map(String::as_str)) { + if outlines.has_glyph(name) && !usage.names.contains(name) { + let mut budget = 1_000_000; + outlines.commands(name, 0, &mut budget, Some(&mut usage))?; + } } } if usage.names.is_empty() { @@ -104,13 +113,15 @@ pub(crate) fn write_subset( } let private = rewrite(&private, edits)?; - let tag = subset_tag(&font.name, requested); let name = format!("{tag}+{}", font.name); let header = std::str::from_utf8(&font.program[..font.length1]) .map_err(|_| "unsupported non-UTF8 Type1 header")?; let mut header = subset_header(header, &name, requested)?; let length1 = header.len(); header.extend(encrypt([0; 4].into_iter().chain(private), 55665)); + if all_glyphs { + usage.names.clone_from(requested); + } usage.names.remove(".notdef"); Ok(SubsetProgram { name, @@ -200,14 +211,14 @@ fn encrypt(data: impl IntoIterator, mut key: u16) -> Vec { .collect() } -fn subset_tag(name: &str, glyphs: &BTreeSet) -> String { +pub(crate) fn subset_tag(name: &str, glyphs: &BTreeSet, salt: u32) -> String { let mut hash = md5::Context::new(); for glyph in glyphs { hash.consume(glyph.as_bytes()); hash.consume(b" "); } hash.consume(name.as_bytes()); - hash.consume(0u32.to_le_bytes()); + hash.consume(salt.to_le_bytes()); let digest = hash.finalize().0; let mut sum: u16 = digest[..13].iter().map(|byte| u16::from(*byte)).sum(); (0..6) diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 9b68925..af72423 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -2175,6 +2175,37 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。 全量编译一致。incremental-receipt.json 的 SHA-256 为 bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。 +### pdfTeX 文档级 Type1 子集与描述符共享 + +PDF 写出时以实际 PFB 的已核验版本和字体变换为键,合并正文与各 +导入页使用的字形。两处字体字典指向同一个字体程序和描述符。 +首个登记者决定子集命名方式。任一导入要求完整程序时保留所有 +字形。正文单独使用的普通映射也实际写出子集。不同实际资源各有 +字体描述符,相同子集哈希按参考的顺序重新分配。 +[pdfTeX 导入页的描述符和字形登记](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/epdf.c#L29-L106) +[pdfTeX 的子集重名处理](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/utils.c#L107-L151) + +九个定向用例共十二页。子集名、CharSet、描述符指向关系、StemV、 +Flags 及解码后的字形与子程序和参考一致。全部页面词框及 144 DPI +灰度图的差异记录已保留。部分 Type1 流仍有 PostScript 空白及 +结尾记录的长度差。单页 XDV 完整字体输出与前版的词框和光栅一致。 + +原样 arXiv 和 Elsevier CAS 双栏各从干净目录完成三轮 LaTeX 与实际 +BibTeX。逐轮 aux、bbl、坐标、词框和灰度图与已冻结的参考一致。 +arXiv 即三页 6918 个字形、1221 个词,导航也一致,PDF 从 686541 +减至 209453 字节。CAS 即六页 10372 个字形、1889 个词,PDF 从 +2348503 减至 957158 字节。两份前版各采用其原样项目已冻结的发布件。 + +三次图像资源编辑改变了全局字体字形集合,包含一次完整嵌入和一次 +恢复。每次复用 159 步,重放 4 次文件调用,只更新第二页。PDF、 +SVG、来源映射及辅助文件与同初态的独立全量一致。 + +回执 target/p3-type1-document-fonts/receipt.json 的 SHA-256 为 +9cf5f566403b39775703b908ddd871f649273fb1f1097a2ee2c1c78534635efe。 +下一项已在出页后赋值的真实 pdfTeX 用例中核实。\pdfomitcharset +改变最终字体字典中的 CharSet,参考仍保留实际子集,当前原生报告 +此控制序列未定义。用例及失败记录保存在同目录 next-omit。 + ### pdfTeX 导入字体的物理子集 字体映射的单小于号与双小于号分别选择子集和完整嵌入。导入页的 diff --git a/docs/PUBLISHER_TEMPLATE_MATRIX.md b/docs/PUBLISHER_TEMPLATE_MATRIX.md index 332af6d..b56672a 100644 --- a/docs/PUBLISHER_TEMPLATE_MATRIX.md +++ b/docs/PUBLISHER_TEMPLATE_MATRIX.md @@ -977,6 +977,16 @@ LuaLaTex、languages 和 argues 的断行与冻结参考一致。PDF 提取的 字形提取仍待对照,当前整页版面门禁保持未通过。 阶段回执 `target/p3-xetex-native-hyphenation/receipt.json`。 +### 文档级字体共享后的 arXiv 与 Elsevier CAS 双栏 + +两份原样交付在同一原生可执行文件上各运行三轮 LaTeX 和一次实际 +BibTeX,沿用各自冻结的参考格式和资源。源码保持指纹,三轮 +aux 和 bbl 与参考逐字节相同。arXiv 的三页 6918 个字形、1221 个 +词框及导航保持一致。CAS 双栏的六页 10372 个字形与 1889 个词框 +保持一致。九页的 144 DPI 灰度图均与参考逐像素相同。全部期刊及 +会议仍按同一冻结版本进入最终统一矩阵。 +[阶段记录](P2_M1_PROGRESS.md#pdftex-文档级-type1-子集与描述符共享) + ### Elsevier CAS 双栏图摘的实际字体子集 从冻结的 30 项原始交付重新运行三轮 LaTeX 与一次实际 BibTeX。