Allocate mapped Type 1 import objects in PDF write order
This commit is contained in:
1 parent
861c9dbfc9
commit
c1c3c25b3f
9 files changed
+466
-95
No files matched your search
@@ -2270,7 +2270,7 @@ fn write_pdf(
|
||||
let registry = unicode.and_then(|options| options.objects);
|
||||
let mut device_objects = BTreeMap::new();
|
||||
if let Some(registry) = registry {
|
||||
for number in registry.font_object_numbers() {
|
||||
for number in registry.font_object_numbers().chain(registry.imported_font_numbers()) {
|
||||
// An unused queried font leaves its reservation free.
|
||||
objects.push(Vec::new());
|
||||
device_objects.insert(number, objects.len() as u32);
|
||||
@@ -2346,8 +2346,8 @@ fn write_pdf(
|
||||
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.image.mapped_type1_fonts() {
|
||||
for (image, _, _, _, imports) in &images {
|
||||
for font in image.image.mapped_type1_fonts(*imports) {
|
||||
type1_plans.include(font);
|
||||
}
|
||||
}
|
||||
@@ -2368,7 +2368,11 @@ fn write_pdf(
|
||||
|| native_type1_parameters(program, owner_paint, owner.metrics()), glyphs);
|
||||
}
|
||||
let omit_charset = unicode.is_some_and(|options| options.omit_charset);
|
||||
let type1_references = type1_plans.write(&mut objects, compression, omit_charset)?;
|
||||
let type1_references = type1_plans.write(&mut objects, compression, omit_charset, |key| {
|
||||
let (descriptor, name) = registry?.imported_type1_slots(key)?;
|
||||
let physical = |number| device_objects[&number] as usize;
|
||||
Some((physical(descriptor), name.map(physical)))
|
||||
})?;
|
||||
|
||||
let mut native_font_ids = BTreeMap::new();
|
||||
for (&id, (face, paint, used)) in &native_used {
|
||||
|
||||
@@ -14,6 +14,7 @@ use std::{
|
||||
pub(crate) struct Reference {
|
||||
pub object: usize,
|
||||
pub name: String,
|
||||
pub name_object: Option<usize>,
|
||||
}
|
||||
|
||||
pub(crate) type References<'a> = HashMap<Type1ProgramKey<'a>, Reference>;
|
||||
@@ -84,6 +85,7 @@ impl<'a> FontPlans<'a> {
|
||||
objects: &mut Vec<Vec<u8>>,
|
||||
compression: u8,
|
||||
omit_charset: bool,
|
||||
reserved: impl Fn(Type1ProgramKey<'a>) -> Option<(usize, Option<usize>)>,
|
||||
) -> Result<References<'a>, String> {
|
||||
let mut plans: Vec<_> = self.0.into_iter().collect();
|
||||
plans.sort_unstable_by(|((a, at), _), ((b, bt), _)| {
|
||||
@@ -98,6 +100,8 @@ impl<'a> FontPlans<'a> {
|
||||
let mut tags = BTreeSet::new();
|
||||
let mut references = HashMap::new();
|
||||
for (key, plan) in plans {
|
||||
let slots = reserved(key);
|
||||
let name_object = slots.and_then(|(_, name)| name);
|
||||
let reference = if plan.subset {
|
||||
let tag = (0..100)
|
||||
.map(|salt| subset_tag(&plan.font.name, &plan.glyphs, salt))
|
||||
@@ -114,13 +118,25 @@ impl<'a> FontPlans<'a> {
|
||||
&subset.program,
|
||||
lengths,
|
||||
compression,
|
||||
slots,
|
||||
),
|
||||
name: subset.name,
|
||||
name_object,
|
||||
}
|
||||
} else {
|
||||
Reference {
|
||||
object: write_full(objects, plan.font, &plan.parameters, compression),
|
||||
object: write_embedding(
|
||||
objects,
|
||||
&plan.font.name,
|
||||
&plan.parameters,
|
||||
None,
|
||||
&plan.font.program,
|
||||
[plan.font.length1, plan.font.length2, plan.font.length3],
|
||||
compression,
|
||||
slots,
|
||||
),
|
||||
name: plan.font.name.clone(),
|
||||
name_object,
|
||||
}
|
||||
};
|
||||
references.insert(key, reference);
|
||||
@@ -143,6 +159,7 @@ pub(super) fn write_full(
|
||||
&font.program,
|
||||
[font.length1, font.length2, font.length3],
|
||||
compression,
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -154,11 +171,24 @@ fn write_embedding(
|
||||
program: &[u8],
|
||||
lengths: [usize; 3],
|
||||
compression: u8,
|
||||
slots: Option<(usize, Option<usize>)>,
|
||||
) -> usize {
|
||||
let descriptor = objects.len() + 1;
|
||||
let file = descriptor + 1;
|
||||
let descriptor = slots.map_or_else(
|
||||
|| {
|
||||
objects.push(Vec::new());
|
||||
objects.len()
|
||||
},
|
||||
|(descriptor, _)| descriptor,
|
||||
);
|
||||
let file = objects.len() + 1;
|
||||
let name = native_pdf_name(name);
|
||||
let mut body = format!("<< /Type /FontDescriptor /FontName /{name} {parameters}");
|
||||
let font_name = if let Some((_, Some(name_id))) = slots {
|
||||
objects[name_id - 1] = format!("/{name}").into_bytes();
|
||||
format!("{name_id} 0 R")
|
||||
} else {
|
||||
format!("/{name}")
|
||||
};
|
||||
let mut body = format!("<< /Type /FontDescriptor /FontName {font_name} {parameters}");
|
||||
if let Some(glyphs) = glyphs {
|
||||
body.push_str(" /CharSet <");
|
||||
for glyph in glyphs {
|
||||
@@ -170,7 +200,7 @@ fn write_embedding(
|
||||
body.push('>');
|
||||
}
|
||||
write!(body, " /FontFile {file} 0 R >>").unwrap();
|
||||
objects.push(body.into_bytes());
|
||||
objects[descriptor - 1] = body.into_bytes();
|
||||
let [clear, private, trailer] = lengths;
|
||||
let keys = format!("/Length1 {clear} /Length2 {private} /Length3 {trailer}");
|
||||
objects.push(objects::stream(&keys, program, compression));
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
//! Native PDF objects and extra resources captured at page shipout.
|
||||
use crate::{execution::FontId, resources::ResourceVersion};
|
||||
use crate::{
|
||||
execution::FontId, native_font::Type1ProgramKey, resources::ResourceVersion,
|
||||
type1::Type1Transform,
|
||||
};
|
||||
use super::links::DestinationId;
|
||||
use lopdf::{
|
||||
Dictionary, Object, ObjectId, Stream,
|
||||
@@ -40,6 +43,7 @@ pub(crate) enum ObjectBody {
|
||||
ObjectStream,
|
||||
Destination,
|
||||
ImportedImage,
|
||||
ImportedFont,
|
||||
}
|
||||
|
||||
impl ObjectBody {
|
||||
@@ -48,7 +52,7 @@ impl ObjectBody {
|
||||
Self::Page | Self::Link | Self::FormatLink | Self::Form
|
||||
| Self::FormResources | Self::Image(_) | Self::Font(_) | Self::PageResources | Self::PageContents
|
||||
| Self::Pages | Self::PngGroup | Self::PngAuxiliary | Self::ObjectStream
|
||||
| Self::Destination | Self::ImportedImage | Self::DiscardedAtDump => 0,
|
||||
| Self::Destination | Self::ImportedImage | Self::ImportedFont | Self::DiscardedAtDump => 0,
|
||||
Self::Direct(bytes) => bytes.len(),
|
||||
Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()),
|
||||
Self::File {
|
||||
@@ -68,7 +72,7 @@ impl ObjectBody {
|
||||
Self::Page | Self::Link | Self::FormatLink | Self::Form | Self::FormResources
|
||||
| Self::Image(_) | Self::Font(_) | Self::PageResources | Self::PageContents
|
||||
| Self::Pages | Self::PngGroup | Self::PngAuxiliary | Self::ObjectStream
|
||||
| Self::Destination | Self::ImportedImage => {
|
||||
| Self::Destination | Self::ImportedImage | Self::ImportedFont => {
|
||||
Err("expected a generic native PDF object".into())
|
||||
}
|
||||
Self::DiscardedAtDump => Err("PDF object belongs to the format job and cannot be reused".into()),
|
||||
@@ -135,6 +139,8 @@ pub struct PdfObjects {
|
||||
// Source object numbers belong to one particular version of one file.
|
||||
#[serde(skip)]
|
||||
imported_images: BTreeMap<PathBuf, BTreeMap<String, BTreeMap<ObjectId, u32>>>,
|
||||
#[serde(skip)]
|
||||
imported_type1: BTreeMap<(PathBuf, String, Type1Transform), (u32, Option<u32>)>,
|
||||
}
|
||||
|
||||
impl PdfObjects {
|
||||
@@ -268,21 +274,67 @@ impl PdfObjects {
|
||||
self.written_png_group
|
||||
}
|
||||
|
||||
pub(crate) fn imported_image_number(&self, version: &ResourceVersion, source: ObjectId) -> Option<u32> {
|
||||
self.imported_images.get(&version.path)?.get(&version.sha256)?.get(&source).copied()
|
||||
}
|
||||
|
||||
pub(crate) fn bind_imported_image(&mut self, version: &ResourceVersion, source: ObjectId, number: u32) {
|
||||
self.imported_images.entry(version.path.clone()).or_default()
|
||||
.entry(version.sha256.clone()).or_default().entry(source).or_insert(number);
|
||||
}
|
||||
|
||||
pub(crate) fn import_image_object(
|
||||
&mut self, version: &ResourceVersion, source: ObjectId, limit: usize,
|
||||
) -> Result<(u32, bool), String> {
|
||||
if let Some(&number) = self.imported_images.get(&version.path)
|
||||
.and_then(|versions| versions.get(&version.sha256))
|
||||
.and_then(|objects| objects.get(&source))
|
||||
{
|
||||
if let Some(number) = self.imported_image_number(version, source) {
|
||||
return Ok((number, false));
|
||||
}
|
||||
let number = self.allocate(Some(Arc::new(ObjectBody::ImportedImage)), limit)?;
|
||||
self.imported_images.entry(version.path.clone()).or_default()
|
||||
.entry(version.sha256.clone()).or_default().insert(source, number);
|
||||
self.bind_imported_image(version, source, number);
|
||||
Ok((number, true))
|
||||
}
|
||||
|
||||
pub(crate) fn reserve_imported_font_part(&mut self, limit: usize) -> Result<u32, String> {
|
||||
self.allocate(Some(Arc::new(ObjectBody::ImportedFont)), limit)
|
||||
}
|
||||
|
||||
pub(crate) fn imported_font_numbers(&self) -> impl Iterator<Item = u32> + '_ {
|
||||
self.values.iter().enumerate().filter_map(|(index, entry)| {
|
||||
matches!(entry.as_deref(), Some(ObjectBody::ImportedFont)).then_some(index as u32 + 1)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn imported_type1_slots(&self, key: Type1ProgramKey<'_>) -> Option<(u32, Option<u32>)> {
|
||||
let (version, transform) = key;
|
||||
self.imported_type1.get(&(version.path.clone(), version.sha256.clone(), transform)).copied()
|
||||
}
|
||||
|
||||
pub(crate) fn reserve_imported_type1_descriptor(
|
||||
&mut self, key: Type1ProgramKey<'_>, limit: usize,
|
||||
) -> Result<u32, String> {
|
||||
if let Some((descriptor, _)) = self.imported_type1_slots(key) {
|
||||
return Ok(descriptor);
|
||||
}
|
||||
let number = self.reserve_imported_font_part(limit)?;
|
||||
let (version, transform) = key;
|
||||
self.imported_type1.insert((version.path.clone(), version.sha256.clone(), transform), (number, None));
|
||||
Ok(number)
|
||||
}
|
||||
|
||||
pub(crate) fn reserve_imported_type1_name(
|
||||
&mut self, key: Type1ProgramKey<'_>, limit: usize,
|
||||
) -> Result<(), String> {
|
||||
let descriptor = self.reserve_imported_type1_descriptor(key, limit)?;
|
||||
if self.imported_type1_slots(key).is_some_and(|(_, name)| name.is_some()) {
|
||||
return Ok(());
|
||||
}
|
||||
let number = self.reserve_imported_font_part(limit)?;
|
||||
let (version, transform) = key;
|
||||
self.imported_type1.insert((version.path.clone(), version.sha256.clone(), transform),
|
||||
(descriptor, Some(number)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn imported_image_numbers(&self) -> impl Iterator<Item = u32> + '_ {
|
||||
self.values.iter().enumerate().filter_map(|(index, entry)| {
|
||||
matches!(entry.as_deref(), Some(ObjectBody::ImportedImage)).then_some(index as u32 + 1)
|
||||
@@ -388,7 +440,7 @@ impl PdfObjects {
|
||||
Some(ObjectBody::Page | ObjectBody::FormResources | ObjectBody::PageResources
|
||||
| ObjectBody::PageContents | ObjectBody::Pages | ObjectBody::Font(_)
|
||||
| ObjectBody::PngAuxiliary | ObjectBody::ObjectStream | ObjectBody::Destination
|
||||
| ObjectBody::ImportedImage) => {
|
||||
| ObjectBody::ImportedImage | ObjectBody::ImportedFont) => {
|
||||
ObjectBody::DiscardedAtDump
|
||||
}
|
||||
_ if self.written.contains(&number) => ObjectBody::DiscardedAtDump,
|
||||
@@ -409,6 +461,7 @@ impl PdfObjects {
|
||||
self.destination_numbers.clear();
|
||||
self.shipped_links.clear();
|
||||
self.imported_images.clear();
|
||||
self.imported_type1.clear();
|
||||
!self.values.is_empty()
|
||||
}
|
||||
|
||||
@@ -574,7 +627,7 @@ pub(crate) fn font_attributes_affect_paint(bytes: &[u8]) -> Result<bool, String>
|
||||
Ok(attributes.iter().any(|(name, _)| name != b"ToUnicode"))
|
||||
}
|
||||
|
||||
pub(super) fn encode_value(object: Object) -> Result<Vec<u8>, String> {
|
||||
pub(crate) fn encode_value(object: Object) -> Result<Vec<u8>, String> {
|
||||
if let Object::Stream(stream) = object {
|
||||
let mut output = encode_value(Object::Dictionary(stream.dict))?;
|
||||
output.extend_from_slice(b"\nstream\n");
|
||||
@@ -869,7 +922,7 @@ impl ResourceOutput {
|
||||
|| device_objects.contains(&number) || objects.font_owner(number).is_some()
|
||||
|| matches!(objects.entry(number).and_then(Option::as_deref),
|
||||
Some(ObjectBody::PngGroup | ObjectBody::PngAuxiliary | ObjectBody::ObjectStream
|
||||
| ObjectBody::Destination | ObjectBody::ImportedImage))
|
||||
| ObjectBody::Destination | ObjectBody::ImportedImage | ObjectBody::ImportedFont))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -963,8 +963,19 @@ impl PdfImage {
|
||||
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();
|
||||
if let Some(name) = reference.name_object {
|
||||
write!(body, "{name} 0 R").unwrap();
|
||||
} else {
|
||||
body.extend(pdf_name(reference.name.as_bytes()));
|
||||
}
|
||||
write!(body, " /FontDescriptor {} 0 R /Encoding ", reference.object).unwrap();
|
||||
if let Some((allocation, numbers)) = targets.imports {
|
||||
let encoding = numbers[&allocation.font_encodings[&index]];
|
||||
pdf[encoding as usize - 1].clone_from(&font.encoding);
|
||||
write!(body, "{encoding} 0 R").unwrap();
|
||||
} else {
|
||||
body.extend_from_slice(&font.encoding);
|
||||
}
|
||||
}
|
||||
Part::Png(_) | Part::Bmp(_) => unreachable!("sampled image owns its objects"),
|
||||
Part::XdvCmykDecode => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Replacement of fonts in the root resources of an included pdfTeX page.
|
||||
use super::{Graph, Part, PdfImage, number, resolved};
|
||||
use super::{Graph, ImportWrite, Part, PdfImage, number, resolved};
|
||||
use crate::{native_font::MappedType1, type1::{builtin_encoding, standard_encoding}};
|
||||
use lopdf::{Dictionary, Document, Object, Stream};
|
||||
use lopdf::{Dictionary, Document, Object, ObjectId, Stream};
|
||||
use read_fonts::ps::cff::CffFontRef;
|
||||
use std::{borrow::Cow, collections::BTreeSet, sync::Arc};
|
||||
|
||||
@@ -12,7 +12,8 @@ pub(super) struct ImportedType1 {
|
||||
stem_v: i32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
charset: Option<Vec<u8>>,
|
||||
dictionary: Result<Vec<Part>, String>,
|
||||
descriptor: ObjectId,
|
||||
dictionary: Result<(Vec<Part>, Vec<u8>), String>,
|
||||
}
|
||||
|
||||
pub(super) fn capture(
|
||||
@@ -68,9 +69,9 @@ pub(super) fn capture(
|
||||
let Ok(descriptor) = dict.get(b"FontDescriptor") else {
|
||||
continue;
|
||||
};
|
||||
if descriptor.as_reference().is_err() {
|
||||
let Ok(descriptor_id) = descriptor.as_reference() else {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let Ok(descriptor) = resolved(doc, descriptor)?.as_dict() else {
|
||||
continue;
|
||||
};
|
||||
@@ -96,6 +97,7 @@ pub(super) fn capture(
|
||||
postscript_name: postscript_name.to_owned(),
|
||||
stem_v,
|
||||
charset,
|
||||
descriptor: descriptor_id,
|
||||
dictionary,
|
||||
});
|
||||
}
|
||||
@@ -172,88 +174,90 @@ fn font_template(
|
||||
graph: &mut Graph<'_>,
|
||||
dict: &Dictionary,
|
||||
file: EmbeddedType1<'_>,
|
||||
) -> Result<Vec<Part>, String> {
|
||||
) -> Result<(Vec<Part>, Vec<u8>), String> {
|
||||
let doc = graph.doc;
|
||||
let mut replacement = dict.clone();
|
||||
replacement.remove(b"BaseFont");
|
||||
replacement.remove(b"FontDescriptor");
|
||||
if let Some(encoding) = replace_implicit_encoding(doc, dict, file)? {
|
||||
replacement.set("Encoding", encoding);
|
||||
}
|
||||
replacement.remove(b"Encoding");
|
||||
let encoding = imported_encoding(doc, dict, file)?;
|
||||
let encoding = crate::pdf_device::page_resources::encode_value(Object::Dictionary(encoding))?;
|
||||
let mut parts = Vec::new();
|
||||
graph.render(&Object::Dictionary(replacement), &mut parts, 0)?;
|
||||
let Some(Part::Bytes(end)) = parts.last_mut() else {
|
||||
return Err("missing imported font dictionary end".into());
|
||||
};
|
||||
end.truncate(end.len() - 2);
|
||||
Ok(parts)
|
||||
Ok((parts, encoding))
|
||||
}
|
||||
|
||||
fn replace_implicit_encoding(
|
||||
fn imported_encoding(
|
||||
doc: &Document,
|
||||
font: &Dictionary,
|
||||
program: EmbeddedType1<'_>,
|
||||
) -> Result<Option<Dictionary>, String> {
|
||||
let encoding = font
|
||||
.get(b"Encoding")
|
||||
.ok()
|
||||
.map(|object| resolved(doc, object))
|
||||
.transpose()?;
|
||||
let differences = match encoding {
|
||||
Some(Object::Name(_)) => return Ok(None),
|
||||
Some(Object::Dictionary(dict)) if dict.has(b"BaseEncoding") => return Ok(None),
|
||||
Some(Object::Dictionary(dict)) => dict.get(b"Differences").ok(),
|
||||
None | Some(Object::Null) => None,
|
||||
) -> Result<Dictionary, String> {
|
||||
let source = font.get(b"Encoding").ok().map(|value| resolved(doc, value)).transpose()?;
|
||||
let (base, differences) = match source {
|
||||
Some(Object::Name(name)) => (Some(name.as_slice()), None),
|
||||
Some(Object::Dictionary(dict)) => (
|
||||
dict.get(b"BaseEncoding").ok()
|
||||
.map(|value| resolved(doc, value)?.as_name().map_err(|error| error.to_string()))
|
||||
.transpose()?,
|
||||
dict.get(b"Differences").ok(),
|
||||
),
|
||||
None | Some(Object::Null) => (None, None),
|
||||
_ => return Err("invalid Type1 encoding in included PDF".into()),
|
||||
};
|
||||
let mut names = program.glyph_names(doc)?;
|
||||
if let Some(differences) = differences {
|
||||
let differences = resolved(doc, differences)?
|
||||
.as_array()
|
||||
.map_err(|error| error.to_string())?;
|
||||
let mut slot = 0usize;
|
||||
for value in differences {
|
||||
match resolved(doc, value)? {
|
||||
Object::Integer(code) => {
|
||||
slot = usize::try_from(*code)
|
||||
.ok()
|
||||
.filter(|&slot| slot < names.len())
|
||||
.ok_or("invalid Type1 encoding difference index")?;
|
||||
}
|
||||
Object::Name(glyph) => {
|
||||
*names
|
||||
.get_mut(slot)
|
||||
.ok_or("Type1 encoding difference exceeds 256 slots")? = glyph.clone();
|
||||
slot += 1;
|
||||
}
|
||||
_ => return Err("invalid Type1 encoding difference".into()),
|
||||
let differences = differences.map(|value| {
|
||||
let values = resolved(doc, value)?.as_array().map_err(|error| error.to_string())?;
|
||||
values.iter().map(|value| match resolved(doc, value)? {
|
||||
value @ (Object::Integer(_) | Object::Name(_)) => Ok(value.clone()),
|
||||
_ => Err("invalid Type1 encoding difference".to_owned()),
|
||||
}).collect::<Result<Vec<_>, String>>()
|
||||
}).transpose()?.unwrap_or_default();
|
||||
let mut encoding = Dictionary::new();
|
||||
encoding.set("Type", Object::Name(b"Encoding".to_vec()));
|
||||
if let Some(base) = base.filter(|base| *base != b"StandardEncoding") {
|
||||
encoding.set("BaseEncoding", Object::Name(base.to_vec()));
|
||||
if !differences.is_empty() {
|
||||
encoding.set("Differences", Object::Array(differences));
|
||||
}
|
||||
return Ok(encoding);
|
||||
}
|
||||
|
||||
let mut names = if base.is_some() {
|
||||
(0..=255u8).map(|slot| standard_encoding(slot).unwrap_or(".notdef").as_bytes().to_vec()).collect()
|
||||
} else {
|
||||
program.glyph_names(doc)?
|
||||
};
|
||||
let mut slot = 0usize;
|
||||
for value in differences {
|
||||
match value {
|
||||
Object::Integer(code) => {
|
||||
slot = usize::try_from(code).ok().filter(|&slot| slot < names.len())
|
||||
.ok_or("invalid Type1 encoding difference index")?;
|
||||
}
|
||||
Object::Name(glyph) => {
|
||||
*names.get_mut(slot).ok_or("Type1 encoding difference exceeds 256 slots")? = glyph;
|
||||
slot += 1;
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
let mut generated = Dictionary::new();
|
||||
generated.set("Type", Object::Name(b"Encoding".to_vec()));
|
||||
let first = font
|
||||
.get(b"FirstChar")
|
||||
.ok()
|
||||
.and_then(|object| resolved(doc, object).ok())
|
||||
.and_then(|object| object.as_i64().ok())
|
||||
.unwrap_or(0)
|
||||
.clamp(0, 255);
|
||||
let last = font
|
||||
.get(b"LastChar")
|
||||
.ok()
|
||||
.and_then(|object| resolved(doc, object).ok())
|
||||
.and_then(|object| object.as_i64().ok())
|
||||
.unwrap_or(255)
|
||||
.clamp(first, 255);
|
||||
let mut differences = vec![Object::Integer(first)];
|
||||
differences.extend(
|
||||
names
|
||||
.drain(first as usize..=last as usize)
|
||||
.map(Object::Name),
|
||||
);
|
||||
generated.set("Differences", Object::Array(differences));
|
||||
Ok(Some(generated))
|
||||
let mut differences = Vec::new();
|
||||
let mut next = None;
|
||||
for (slot, name) in names.into_iter().enumerate() {
|
||||
if name == b".notdef" {
|
||||
continue;
|
||||
}
|
||||
if next != Some(slot) {
|
||||
differences.push(Object::Integer(slot as i64));
|
||||
}
|
||||
differences.push(Object::Name(name));
|
||||
next = Some(slot + 1);
|
||||
}
|
||||
encoding.set("Differences", Object::Array(differences));
|
||||
Ok(encoding)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
@@ -261,11 +265,18 @@ pub(crate) struct ImportedType1Use {
|
||||
pub mapped: MappedType1,
|
||||
pub stem_v: i32,
|
||||
pub glyphs: Option<BTreeSet<String>>,
|
||||
pub(super) descriptor: ObjectId,
|
||||
pub(super) encoding: Vec<u8>,
|
||||
}
|
||||
|
||||
impl PdfImage {
|
||||
pub(crate) fn mapped_type1_fonts(&self) -> impl Iterator<Item = &ImportedType1Use> {
|
||||
self.objects.iter().flatten().filter_map(|part| {
|
||||
pub(crate) fn mapped_type1_fonts<'a>(
|
||||
&'a self,
|
||||
imports: Option<&'a ImportWrite>,
|
||||
) -> impl Iterator<Item = &'a ImportedType1Use> {
|
||||
self.objects.iter().enumerate().filter(move |(index, _)| {
|
||||
imports.is_none_or(|import| import.font_encodings.contains_key(index))
|
||||
}).flat_map(|(_, parts)| parts).filter_map(|part| {
|
||||
if let Part::MappedType1(font) = part {
|
||||
Some(font.as_ref())
|
||||
} else {
|
||||
@@ -297,8 +308,10 @@ impl PdfImage {
|
||||
})
|
||||
.transpose()?;
|
||||
let stem_v = crate::type1_outline::pdftex_stem_v(&mapped.font)?.unwrap_or(entry.stem_v);
|
||||
let mut dictionary = entry.dictionary.clone()?;
|
||||
dictionary.push(Part::MappedType1(Arc::new(ImportedType1Use { mapped, stem_v, glyphs })));
|
||||
let (mut dictionary, encoding) = entry.dictionary.clone()?;
|
||||
dictionary.push(Part::MappedType1(Arc::new(ImportedType1Use {
|
||||
mapped, stem_v, glyphs, descriptor: entry.descriptor, encoding,
|
||||
})));
|
||||
dictionary.push(Part::Bytes(b">>".to_vec()));
|
||||
result.get_or_insert_with(|| self.clone()).objects[entry.index] = dictionary;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,10 @@ use super::{Graph, Part, PdfImage, resolved};
|
||||
use crate::{pdf_device::page_resources::PdfObjects, resources::ResourceVersion};
|
||||
use lopdf::{Dictionary, Object, ObjectId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{collections::VecDeque, io::Write};
|
||||
use std::{
|
||||
collections::{BTreeMap, VecDeque},
|
||||
io::Write,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub(super) struct SourceGraph {
|
||||
@@ -22,6 +25,8 @@ struct SourceObject {
|
||||
pub(crate) struct ImportWrite {
|
||||
pub(crate) objects: Vec<Option<ImportedObject>>,
|
||||
pub(super) form_entries: Vec<Part>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub(super) font_encodings: BTreeMap<usize, u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
@@ -138,6 +143,8 @@ impl PdfImage {
|
||||
let mut numbering = ImportNumbering {
|
||||
source,
|
||||
version: &self.version,
|
||||
bodies: &self.objects,
|
||||
font_encodings: BTreeMap::new(),
|
||||
registry,
|
||||
limit,
|
||||
};
|
||||
@@ -146,6 +153,15 @@ impl PdfImage {
|
||||
&mut objects,
|
||||
&mut queue,
|
||||
)?;
|
||||
// Encodings are emitted in reverse registration order before source
|
||||
// dictionaries, including when they start a new object stream.
|
||||
if compression > 0 {
|
||||
let mut encodings: Vec<_> = numbering.font_encodings.values().copied().collect();
|
||||
encodings.sort_unstable_by(|left, right| right.cmp(left));
|
||||
for number in encodings {
|
||||
numbering.registry.pack_object(number, limit)?;
|
||||
}
|
||||
}
|
||||
while let Some(index) = queue.pop_front() {
|
||||
let object = source.nodes[index].expect("indirect source object");
|
||||
if compression >= 2 && !object.stream {
|
||||
@@ -154,10 +170,21 @@ impl PdfImage {
|
||||
.pack_object(objects[index].unwrap().number, limit)?;
|
||||
}
|
||||
numbering.references(self.objects[index].iter(), &mut objects, &mut queue)?;
|
||||
// A mapped font's /BaseFont name is requested after the other
|
||||
// font dictionary entries, including indirect widths.
|
||||
if let Some(Part::MappedType1(font)) = self.objects[index]
|
||||
.iter()
|
||||
.find(|part| matches!(part, Part::MappedType1(_)))
|
||||
{
|
||||
numbering
|
||||
.registry
|
||||
.reserve_imported_type1_name(font.mapped.key(), limit)?;
|
||||
}
|
||||
}
|
||||
Ok(ImportWrite {
|
||||
objects,
|
||||
form_entries,
|
||||
font_encodings: numbering.font_encodings,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -165,6 +192,8 @@ impl PdfImage {
|
||||
struct ImportNumbering<'a> {
|
||||
source: &'a SourceGraph,
|
||||
version: &'a ResourceVersion,
|
||||
bodies: &'a [Vec<Part>],
|
||||
font_encodings: BTreeMap<usize, u32>,
|
||||
registry: &'a mut PdfObjects,
|
||||
limit: usize,
|
||||
}
|
||||
@@ -182,6 +211,28 @@ impl ImportNumbering<'_> {
|
||||
continue;
|
||||
}
|
||||
let source = self.source.nodes[index].expect("indirect source object");
|
||||
if self
|
||||
.registry
|
||||
.imported_image_number(self.version, source.id)
|
||||
.is_none()
|
||||
&& let Some(Part::MappedType1(font)) = self.bodies[index]
|
||||
.iter()
|
||||
.find(|part| matches!(part, Part::MappedType1(_)))
|
||||
{
|
||||
if self
|
||||
.registry
|
||||
.imported_image_number(self.version, font.descriptor)
|
||||
.is_none()
|
||||
{
|
||||
let descriptor = self
|
||||
.registry
|
||||
.reserve_imported_type1_descriptor(font.mapped.key(), self.limit)?;
|
||||
self.registry
|
||||
.bind_imported_image(self.version, font.descriptor, descriptor);
|
||||
}
|
||||
let encoding = self.registry.reserve_imported_font_part(self.limit)?;
|
||||
self.font_encodings.insert(index, encoding);
|
||||
}
|
||||
let (number, write) =
|
||||
self.registry
|
||||
.import_image_object(self.version, source.id, self.limit)?;
|
||||
|
||||
@@ -1012,6 +1012,35 @@ revision-settled.log 为 89e96d66430120a969f2896ffac35aa68953d19d138e8d2c043548b
|
||||
target/p3-imported-pdf-objects/font-ids-default 和 font-ids-copy。
|
||||
[原样 sigconf 的稳定辅助文件](PUBLISHER_TEMPLATE_MATRIX.md#2026-11-28-sigconf-导入图编号复验)
|
||||
|
||||
### pdfTeX 替换导入 Type 1 字体的间接对象
|
||||
|
||||
替换导入字体时,在登记字体字典前分配实际 PFB 的共享描述符和
|
||||
该源字体的编码对象。写出字体字典的源引用(包括 Widths)后,
|
||||
分配实际字体名。编码按登记的相反顺序加入允许的压缩对象流,
|
||||
渲染器写出的 FontDescriptor、Encoding 和 BaseFont 引用指向
|
||||
相应内容。按源文件版本和源字体对象复用每份编码,按 PFB 版本和
|
||||
变换共享描述符、字体名以及最终字形子集。正文使用同一物理字体时
|
||||
与导入页共享描述符和字形程序。
|
||||
[参考字体登记和输出顺序](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftoepdf.cc#L332-L354)
|
||||
[参考编码写出](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/writeenc.c#L86-L110)
|
||||
|
||||
发布版十一项图像回归通过。七份独立 pdfTeX 定向对照涵盖普通和
|
||||
立即导入、压缩等级 0–3、原样复制和重复声明,编号、词框和两页
|
||||
光栅逐项一致。四页回归确认同一源字体复用,同一 PFB 不同源字体
|
||||
分别有实际编码且共享描述符和字体名。正文也共享该描述符。
|
||||
|
||||
共享字体的三页会话,修改第二页导入的 PDF 再恢复。两次各复用
|
||||
998 步,辅助文件中的实际编号 21、22、21。两版的 PDF、测量页、
|
||||
SVG、来源映射及生成文件与独立零复用全量一致。预览两次都重发
|
||||
第 1、2 页。第 1 页 144 DPI 像素不变,其 PDF 物理页对象从
|
||||
23 变为 24 并在撤销时恢复。当前预览依赖指纹纳入物理引用编号,
|
||||
还需验证对象重新编号后能安全复用未改动页面。
|
||||
|
||||
回执在 target/p3-imported-type1-objects。paired.json 的 SHA-256 为
|
||||
fef9fa7c976862eb367b3856ba1eb4da238a4c9ce89acb02aa395ee291861aaf,
|
||||
preview-audit.json 为 e5321a9a1967ecbbb975df8c47dc3de591cd576f51fa25d55ca29b949b6234b6。
|
||||
[原样 CAS 双栏复验](PUBLISHER_TEMPLATE_MATRIX.md#2026-11-28-cas-双栏的导入字体复验)
|
||||
|
||||
### 行内数学字符参与 pdfTeX 字宽伸缩
|
||||
|
||||
行内数学结束后,实际未装盒的传统字体字符进入段落水平列表。
|
||||
|
||||
@@ -1216,6 +1216,20 @@ variants.json 的 SHA-256 为
|
||||
receipt.json 的 SHA-256 为 230c29ff12658a9aaa768f00cd95acffcf7d73a43967d8052eb4267177ca26c0,
|
||||
pass-7/comparison.json 为 7ff193a7ba1b183c9813667d97e2947188998ff26e8102c66c9eb7f3056c74ca。
|
||||
|
||||
### 2026-11-28 CAS 双栏的导入字体复验
|
||||
|
||||
以本轮 Type 1 导入改动的发布候选,在固定 schema51、
|
||||
实际字体映射和原版 30 项交付文件上复验 Elsevier CAS 双栏。
|
||||
从空辅助文件开始,独立运行真实 BibTeX 和三轮 LaTeX。
|
||||
逐轮 aux、最终 bbl 与参考逐字节相同。
|
||||
6 页的 10,372 个字形、1,889 个词及词框、命名目的地与参考一致,
|
||||
144 DPI 灰度光栅逐像素相同。
|
||||
|
||||
证据在 target/p3-imported-type1-objects/elsevier-cas-dc,
|
||||
receipt.json 的 SHA-256 为 3f591a83c53dc505331cc248323e8dec538fee0bdf265800ddb83e11af6f71f2,
|
||||
pass-3/comparison.json 为 64f656d0968bab4b26602bbf8690eabcbc365d094ec89a38a982a38fe116a91d。
|
||||
[Type 1 编号与增量对照](P2_M1_PROGRESS.md#pdftex-替换导入-type-1-字体的间接对象)
|
||||
|
||||
单纯生成 PDF 或 DVI 只说明编译路径可达。完整验收要在参考环境闭合后比较页数、
|
||||
双栏位置及跨栏材料、实际字体/字形、图表浮动、引用收敛、词框及墨迹;测试源
|
||||
与容差都不得为通过而替换。类 Typst 的编辑延迟另用同批原样项目分规模测量,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#[path = "support/native_fonts.rs"]
|
||||
mod native_fonts;
|
||||
use lopdf::{Document, Object, Stream, dictionary};
|
||||
use std::{fs, path::Path, process::Command, sync::Arc};
|
||||
use texrra_engine::native::{
|
||||
@@ -1137,3 +1139,167 @@ fn imported_pdf_indirect_objects_share_the_device_registry_at_write_time() {
|
||||
}
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapped_type1_import_allocates_encoding_descriptor_and_name() {
|
||||
fn resolve_dict<'a>(pdf: &'a Document, value: &'a Object) -> &'a lopdf::Dictionary {
|
||||
pdf.dereference(value).unwrap().1.as_dict().unwrap()
|
||||
}
|
||||
|
||||
let root = std::env::temp_dir().join(format!("texrra-mapped-image-{}", std::process::id()));
|
||||
fs::create_dir(&root).unwrap();
|
||||
let run_reference = |entry| {
|
||||
let output = Command::new("pdftex")
|
||||
.args([
|
||||
"-ini",
|
||||
"-etex",
|
||||
"-interaction=nonstopmode",
|
||||
"-halt-on-error",
|
||||
entry,
|
||||
])
|
||||
.current_dir(&root)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stdout)
|
||||
);
|
||||
};
|
||||
fs::write(
|
||||
root.join("figure.tex"),
|
||||
r"\catcode123=1 \catcode125=2
|
||||
\pdfoutput=1 \pdfobjcompresslevel=0
|
||||
\font\body=cmr10 \body
|
||||
\shipout\hbox{One 1}
|
||||
\end
|
||||
",
|
||||
)
|
||||
.unwrap();
|
||||
run_reference("figure.tex");
|
||||
fs::copy(root.join("figure.pdf"), root.join("separate.pdf")).unwrap();
|
||||
fs::write(
|
||||
root.join("probe.tex"),
|
||||
r"\catcode123=1 \catcode125=2
|
||||
\pdfoutput=1 \pdfminorversion=7 \pdfobjcompresslevel=3
|
||||
\def\trace{\pdfobj reserveobjnum\message{[object=\the\pdflastobj]}}
|
||||
\pdfximage{figure.pdf}
|
||||
\shipout\hbox{\pdfrefximage\pdflastximage}\trace
|
||||
\immediate\pdfximage{figure.pdf}\trace
|
||||
\shipout\hbox{\pdfrefximage\pdflastximage}\trace
|
||||
\immediate\pdfximage{separate.pdf}\trace
|
||||
\shipout\hbox{\pdfrefximage\pdflastximage}\trace
|
||||
\font\body=cmr10 \body \shipout\hbox{Two 2}
|
||||
\end
|
||||
",
|
||||
)
|
||||
.unwrap();
|
||||
run_reference("probe.tex");
|
||||
let compiled = native_fonts::command()
|
||||
.args([
|
||||
"native",
|
||||
"--job",
|
||||
"--initex",
|
||||
"--etex",
|
||||
"probe.tex",
|
||||
"native.pdf",
|
||||
])
|
||||
.current_dir(&root)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
compiled.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&compiled.stderr)
|
||||
);
|
||||
let numbers = |log| {
|
||||
fs::read_to_string(root.join(log))
|
||||
.unwrap()
|
||||
.replace('\n', "")
|
||||
.split("[object=")
|
||||
.skip(1)
|
||||
.map(|part| part.split_once(']').unwrap().0.parse::<u32>().unwrap())
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let expected = numbers("probe.log");
|
||||
assert_eq!(expected.len(), 5);
|
||||
assert_eq!(numbers("native.log"), expected);
|
||||
|
||||
for filename in ["probe.pdf", "native.pdf"] {
|
||||
let pdf = Document::load(root.join(filename)).unwrap();
|
||||
let parents = pdf.get_pages();
|
||||
assert_eq!(parents.len(), 4);
|
||||
let page_resources = |page| {
|
||||
resolve_dict(
|
||||
&pdf,
|
||||
pdf.get_dictionary(parents[&page])
|
||||
.unwrap()
|
||||
.get(b"Resources")
|
||||
.unwrap(),
|
||||
)
|
||||
};
|
||||
let only_font = |resources: &lopdf::Dictionary| {
|
||||
resolve_dict(&pdf, resources.get(b"Font").unwrap())
|
||||
.iter()
|
||||
.next()
|
||||
.unwrap()
|
||||
.1
|
||||
.as_reference()
|
||||
.unwrap()
|
||||
};
|
||||
let mut included = Vec::new();
|
||||
for page in 1..=3 {
|
||||
let xobjects = resolve_dict(&pdf, page_resources(page).get(b"XObject").unwrap());
|
||||
let form = pdf
|
||||
.dereference(xobjects.iter().next().unwrap().1)
|
||||
.unwrap()
|
||||
.1
|
||||
.as_stream()
|
||||
.unwrap();
|
||||
included.push(only_font(resolve_dict(
|
||||
&pdf,
|
||||
form.dict.get(b"Resources").unwrap(),
|
||||
)));
|
||||
}
|
||||
assert_eq!(included[0], included[1]);
|
||||
assert_ne!(included[0], included[2]);
|
||||
let first = pdf.get_dictionary(included[0]).unwrap();
|
||||
let second = pdf.get_dictionary(included[2]).unwrap();
|
||||
let body = pdf.get_dictionary(only_font(page_resources(4))).unwrap();
|
||||
let descriptor = first
|
||||
.get(b"FontDescriptor")
|
||||
.unwrap()
|
||||
.as_reference()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
second
|
||||
.get(b"FontDescriptor")
|
||||
.unwrap()
|
||||
.as_reference()
|
||||
.unwrap(),
|
||||
descriptor
|
||||
);
|
||||
assert_eq!(
|
||||
body.get(b"FontDescriptor").unwrap().as_reference().unwrap(),
|
||||
descriptor
|
||||
);
|
||||
let name = first.get(b"BaseFont").unwrap().as_reference().unwrap();
|
||||
assert_eq!(
|
||||
second.get(b"BaseFont").unwrap().as_reference().unwrap(),
|
||||
name
|
||||
);
|
||||
let descriptor_name = pdf.get_dictionary(descriptor).unwrap().get(b"FontName").unwrap();
|
||||
assert_eq!(
|
||||
pdf.dereference(descriptor_name).unwrap().1.as_name().unwrap(),
|
||||
pdf.get_object(name).unwrap().as_name().unwrap(),
|
||||
);
|
||||
let first_encoding = first.get(b"Encoding").unwrap().as_reference().unwrap();
|
||||
let second_encoding = second.get(b"Encoding").unwrap().as_reference().unwrap();
|
||||
assert_ne!(first_encoding, second_encoding);
|
||||
assert_eq!(
|
||||
format!("{:?}", pdf.get_object(first_encoding).unwrap()),
|
||||
format!("{:?}", pdf.get_object(second_encoding).unwrap())
|
||||
);
|
||||
}
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
Reference in new issue
Block a user