Support unembedded pdfTeX Type 1 device fonts in export and preview
This commit is contained in:
1 parent
60d67bbb7b
commit
c0970bdbf6
10 files changed
+466
-34
No files matched your search
@@ -13,11 +13,13 @@ use std::{
|
||||
sync::{Arc, Mutex, OnceLock},
|
||||
};
|
||||
mod cff;
|
||||
mod device_type1;
|
||||
mod map;
|
||||
mod sfd;
|
||||
mod truetype;
|
||||
mod virtual_paint;
|
||||
pub use cff::OpenTypeCffProgram;
|
||||
pub use device_type1::DeviceType1Program;
|
||||
pub use truetype::TrueTypeProgram;
|
||||
pub use map::PdfFontBindings;
|
||||
use map::{dedicated_space_map, find_map_entry, load_map, selected_outline};
|
||||
@@ -67,12 +69,15 @@ impl MappedType1 {
|
||||
impl NativeFontPaint {
|
||||
pub(crate) fn has_pdf_space(&self, font: &NativeFont) -> bool {
|
||||
// pdfTeX requires the space name in an actual map re-encoding.
|
||||
matches!(self.program, NativeFontProgram::Type1(_))
|
||||
&& self.resources.len() == self.program_index.unwrap_or(1) + 2
|
||||
self.encoding_version().is_some()
|
||||
&& matches!(self.program, NativeFontProgram::Type1(_) | NativeFontProgram::DeviceType1(_))
|
||||
&& self.encoding[32] == "space"
|
||||
&& font.metrics().width(' ') > 65_782
|
||||
}
|
||||
pub(crate) fn encoding_version(&self) -> Option<&ResourceVersion> {
|
||||
if let NativeFontProgram::DeviceType1(program) = &self.program {
|
||||
return if program.reencoded { self.resources.last() } else { None };
|
||||
}
|
||||
self.resources.get(self.program_index? + 1)
|
||||
}
|
||||
|
||||
@@ -80,7 +85,8 @@ impl NativeFontPaint {
|
||||
match &self.program {
|
||||
NativeFontProgram::Type1(font) => self.resources.get(self.program_index.unwrap_or(1))
|
||||
.map(|version| (version, font.transform)),
|
||||
NativeFontProgram::Pk(_) | NativeFontProgram::TrueType(_) | NativeFontProgram::OpenTypeCff(_) => None,
|
||||
NativeFontProgram::Pk(_) | NativeFontProgram::TrueType(_)
|
||||
| NativeFontProgram::OpenTypeCff(_) | NativeFontProgram::DeviceType1(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -91,6 +97,7 @@ pub enum NativeFontProgram {
|
||||
Pk(crate::pk_font::PkFontProgram),
|
||||
TrueType(TrueTypeProgram),
|
||||
OpenTypeCff(OpenTypeCffProgram),
|
||||
DeviceType1(DeviceType1Program),
|
||||
}
|
||||
impl NativeFontProgram {
|
||||
pub fn name(&self) -> &str {
|
||||
@@ -99,6 +106,7 @@ impl NativeFontProgram {
|
||||
Self::Pk(p) => &p.name,
|
||||
Self::TrueType(p) => &p.name,
|
||||
Self::OpenTypeCff(p) => &p.name,
|
||||
Self::DeviceType1(p) => &p.name,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -266,7 +274,7 @@ pub struct NativeFontCache {
|
||||
}
|
||||
|
||||
struct DecodedType1 {
|
||||
program: Type1Font,
|
||||
program: Arc<Type1Font>,
|
||||
outlines: Type1Outlines,
|
||||
bbox: [i32; 4],
|
||||
stem_v: i32,
|
||||
@@ -286,7 +294,7 @@ impl DecodedType1 {
|
||||
(program.bbox, outlines.raw_stem_v())
|
||||
};
|
||||
Ok(Self {
|
||||
program,
|
||||
program: Arc::new(program),
|
||||
outlines,
|
||||
bbox,
|
||||
stem_v,
|
||||
@@ -517,6 +525,11 @@ fn resolve_physical_fonts(
|
||||
);
|
||||
continue;
|
||||
};
|
||||
if !xdv && let Some(name) = outline.device_type1_name() {
|
||||
let paint = device_type1::resolve(files, font_cache, outline, name, &font, slots)?;
|
||||
direct_resolved.insert(id, Arc::new(paint));
|
||||
continue;
|
||||
}
|
||||
if let Some(file) = outline.true_type_file() {
|
||||
let paint = truetype::resolve(files, &mut outlines, outline, file, &font, slots)?;
|
||||
direct_resolved.insert(id, Arc::new(paint));
|
||||
@@ -565,7 +578,7 @@ fn resolve_physical_fonts(
|
||||
key.clone(),
|
||||
(
|
||||
NativeFontPaint {
|
||||
program: NativeFontProgram::Type1(program.clone()),
|
||||
program: NativeFontProgram::Type1(program.as_ref().clone()),
|
||||
encoding,
|
||||
glyph_paths: BTreeMap::new(),
|
||||
bbox: decoded.bbox,
|
||||
@@ -625,6 +638,7 @@ fn resolve_physical_fonts(
|
||||
let p = resolved[&font.id].clone();
|
||||
*character = match &p.program {
|
||||
NativeFontProgram::Type1(_)
|
||||
| NativeFontProgram::DeviceType1(_)
|
||||
| NativeFontProgram::TrueType(_)
|
||||
| NativeFontProgram::OpenTypeCff(_) => {
|
||||
crate::type1::glyph_unicode_text(&p.encoding[*slot as usize])
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
//! Unembedded pdfTeX Type 1 fonts retain a device name and optional local outlines.
|
||||
use super::{
|
||||
NativeFont, NativeFontCache, NativeFontPaint, NativeFontProgram, actual_resource,
|
||||
encoding_vector, map::MapEntry, verify_resource,
|
||||
};
|
||||
use crate::{
|
||||
execution::SourceProvider,
|
||||
resources::ResourceKind,
|
||||
type1::{Type1Font, Type1Transform, standard_encoding},
|
||||
};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct DeviceType1Program {
|
||||
pub name: String,
|
||||
pub(crate) reencoded: bool,
|
||||
/// This program is used by previews. The device font stays unembedded.
|
||||
pub preview_program: Option<Arc<Type1Font>>,
|
||||
}
|
||||
|
||||
impl DeviceType1Program {
|
||||
pub(crate) fn standard_flags(&self) -> Option<i32> {
|
||||
standard_flags(&self.name)
|
||||
}
|
||||
}
|
||||
|
||||
fn standard_flags(name: &str) -> Option<i32> {
|
||||
Some(match name {
|
||||
"Courier" => 35,
|
||||
"Courier-Bold" => 35 | (1 << 18),
|
||||
"Courier-Oblique" => 35 | 64,
|
||||
"Courier-BoldOblique" => 35 | 64 | (1 << 18),
|
||||
"Helvetica" => 32,
|
||||
"Helvetica-Bold" => 32 | (1 << 18),
|
||||
"Helvetica-Oblique" => 32 | 64,
|
||||
"Helvetica-BoldOblique" => 32 | 64 | (1 << 18),
|
||||
"Times-Roman" => 34,
|
||||
"Times-Bold" => 34 | (1 << 18),
|
||||
"Times-Italic" => 34 | 64,
|
||||
"Times-BoldItalic" => 34 | 64 | (1 << 18),
|
||||
"Symbol" | "ZapfDingbats" => 4,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn resolve(
|
||||
files: &mut impl SourceProvider,
|
||||
cache: &NativeFontCache,
|
||||
entry: &MapEntry,
|
||||
name: &str,
|
||||
font: &NativeFont,
|
||||
slots: BTreeSet<u8>,
|
||||
) -> Result<NativeFontPaint, String> {
|
||||
let from = entry.from.to_string_lossy();
|
||||
let mut resources: Vec<_> = entry.version.iter().cloned().collect();
|
||||
let mut preview = None;
|
||||
let candidates = [name, font.name.as_str()];
|
||||
for (index, candidate) in candidates.into_iter().enumerate() {
|
||||
if index == 1 && candidate == name {
|
||||
break;
|
||||
}
|
||||
for extension in ["pfb", "pfa"] {
|
||||
let file = format!("{candidate}.{extension}");
|
||||
let Some(resource) = files.optional_font_file(ResourceKind::Type1, &file, &from)?
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let resource = verify_resource(resource, ResourceKind::Type1, &file)?;
|
||||
if let Ok(decoded) = cache.type1(&resource, Type1Transform::default())
|
||||
&& decoded.program.name == name
|
||||
{
|
||||
resources.push(resource.version);
|
||||
preview = Some(decoded);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if preview.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let encoding = if let Some(file) = &entry.encoding {
|
||||
let encoding = actual_resource(files, ResourceKind::Encoding, file, &from)?;
|
||||
let vector = encoding_vector(&encoding.data)?;
|
||||
resources.push(encoding.version);
|
||||
vector
|
||||
} else {
|
||||
let standard_latin = standard_flags(name).is_some_and(|flags| flags & 32 != 0);
|
||||
(0..=255u8)
|
||||
.map(|slot| {
|
||||
match &preview {
|
||||
Some(font) => font.program.name_for_code(slot),
|
||||
None if standard_latin => standard_encoding(slot),
|
||||
None => None,
|
||||
}
|
||||
.unwrap_or(".notdef")
|
||||
.to_owned()
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let mut glyph_paths = BTreeMap::new();
|
||||
if let Some(preview) = &preview {
|
||||
for slot in slots {
|
||||
let glyph = &encoding[usize::from(slot)];
|
||||
if preview.outlines.has_glyph(glyph) {
|
||||
glyph_paths.insert(slot, preview.outlines.glyph_path(glyph)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(NativeFontPaint {
|
||||
program: NativeFontProgram::DeviceType1(DeviceType1Program {
|
||||
name: name.to_owned(),
|
||||
reencoded: entry.encoding.is_some(),
|
||||
preview_program: preview.map(|font| font.program.clone()),
|
||||
}),
|
||||
encoding,
|
||||
glyph_paths,
|
||||
bbox: [0; 4],
|
||||
stem_v: 0,
|
||||
subset: false,
|
||||
descriptor_flags: entry.descriptor_flags,
|
||||
xdv_descriptor: None,
|
||||
resources,
|
||||
program_index: None,
|
||||
})
|
||||
}
|
||||
@@ -66,6 +66,10 @@ impl MapEntry {
|
||||
self.file.is_some() || self.postscript_name
|
||||
}
|
||||
|
||||
pub(super) fn device_type1_name(&self) -> Option<&str> {
|
||||
self.ps_name.as_deref().filter(|_| self.file.is_none())
|
||||
}
|
||||
|
||||
pub(super) fn true_type_file(&self) -> Option<&str> {
|
||||
self.outline_file(&["ttf", "ttc"])
|
||||
}
|
||||
|
||||
@@ -1528,7 +1528,8 @@ fn native_pdf(
|
||||
if paint.encoding.len() != 256
|
||||
|| (matches!(paint.program, crate::native_font::NativeFontProgram::Type1(_))
|
||||
&& paint.encoding[usize::from(*slot)] == ".notdef")
|
||||
|| !paint.glyph_paths.contains_key(slot)
|
||||
|| (!matches!(paint.program, crate::native_font::NativeFontProgram::DeviceType1(_))
|
||||
&& !paint.glyph_paths.contains_key(slot))
|
||||
|| !font.has_slot(*slot)
|
||||
{
|
||||
return Err(format!("native font {} has no output encoding for slot {slot}",font.name));
|
||||
@@ -1758,6 +1759,31 @@ fn native_type1_parameters(
|
||||
}
|
||||
}
|
||||
|
||||
fn write_device_type1_descriptor(
|
||||
objects: &mut Vec<Vec<u8>>,
|
||||
metrics: &crate::tfm::TfmMetrics,
|
||||
name: &str,
|
||||
flags: i32,
|
||||
parameters: Option<&[i32]>,
|
||||
) -> usize {
|
||||
let units = |value: i64| native_font_units(value, native_pdf_font_size(metrics.size_sp()), 1000);
|
||||
let ascent = units(metrics.height('h'));
|
||||
let descent = (-units(metrics.depth('y'))).min(0);
|
||||
let cap = units(metrics.height('H'));
|
||||
let param = |index| parameters.and_then(|p| p.get(index)).copied()
|
||||
.map_or_else(|| metrics.param(index), i64::from);
|
||||
let quad = units(param(5));
|
||||
let top = ascent.max(cap);
|
||||
let angle_sp = -(param(0) as f64 / 65_536.).atan().to_degrees() as i64;
|
||||
let angle = units(angle_sp);
|
||||
let stem = units(metrics.width('.') / 3);
|
||||
let x_height = units(param(4));
|
||||
objects.push(format!(
|
||||
"<< /Type /FontDescriptor /FontName /{name} /Flags {flags} /FontBBox [0 {descent} {quad} {top}] /Ascent {ascent} /CapHeight {cap} /Descent {descent} /ItalicAngle {angle} /StemV {stem} /XHeight {x_height} >>"
|
||||
).into_bytes());
|
||||
objects.len()
|
||||
}
|
||||
|
||||
fn write_sfnt_descriptor(
|
||||
objects: &mut Vec<Vec<u8>>,
|
||||
metrics: &crate::tfm::TfmMetrics,
|
||||
@@ -1809,7 +1835,7 @@ fn write_native_font(
|
||||
reference: Option<&type1_fonts::Reference>,
|
||||
target: Option<usize>,
|
||||
subset_tags: &mut BTreeSet<String>,
|
||||
cff_encoding: Option<usize>,
|
||||
mapped_encoding: Option<usize>,
|
||||
) -> Result<usize, String> {
|
||||
use crate::native_font::NativeFontProgram;
|
||||
if let NativeFontProgram::Pk(pk) = &paint.program {
|
||||
@@ -1870,8 +1896,38 @@ fn write_native_font(
|
||||
let width_object = objects.len() + 1;
|
||||
objects.push(format!("[{widths}]").into_bytes());
|
||||
let (descriptor, name) = cff_fonts::write(objects, m, paint, program, compression)?;
|
||||
let encoding = cff_encoding.map_or_else(String::new, |id| format!(" /Encoding {id} 0 R"));
|
||||
("Type1", descriptor, name, format!("{width_object} 0 R"), encoding, cff_encoding.is_some())
|
||||
let encoding = mapped_encoding.map_or_else(String::new, |id| format!(" /Encoding {id} 0 R"));
|
||||
("Type1", descriptor, name, format!("{width_object} 0 R"), encoding, mapped_encoding.is_some())
|
||||
}
|
||||
NativeFontProgram::DeviceType1(program) => {
|
||||
let name = native_pdf_name(&program.name);
|
||||
let standard_flags = program.standard_flags();
|
||||
let flags = paint.descriptor_flags.or(standard_flags).unwrap_or(34);
|
||||
if paint.descriptor_flags.is_none() {
|
||||
diagnostics.push(format!(
|
||||
"No flags specified for non-embedded font '{}' ({}) (I'm using {flags}): fix your map entry.",
|
||||
program.name, face.name
|
||||
));
|
||||
}
|
||||
if standard_flags.is_none() {
|
||||
diagnostics.push(format!(
|
||||
"font '{}' is not a standard font; I suppose it is available to your PDF viewer then",
|
||||
program.name
|
||||
));
|
||||
}
|
||||
let width_object = objects.len() + 1;
|
||||
objects.push(format!("[{widths}]").into_bytes());
|
||||
let parameters = options.and_then(|options| options.fonts.font(face.id).ok())
|
||||
.map(|font| font.parameters());
|
||||
let descriptor = write_device_type1_descriptor(objects, m, &name, flags, parameters);
|
||||
let encoding = mapped_encoding.map_or_else(String::new, |id| format!(" /Encoding {id} 0 R"));
|
||||
if mapped_encoding.is_none() && options.is_some_and(|options|
|
||||
options.generate_unicode > 0
|
||||
&& !options.fonts.pdf_settings(face.id).is_some_and(|settings| settings.omit_builtin_unicode))
|
||||
{
|
||||
return Err("builtin glyph names is empty".into());
|
||||
}
|
||||
("Type1", descriptor, name, format!("{width_object} 0 R"), encoding, mapped_encoding.is_some())
|
||||
}
|
||||
NativeFontProgram::Pk(_) => unreachable!(),
|
||||
};
|
||||
@@ -2448,12 +2504,15 @@ fn write_pdf(
|
||||
.filter_map(|font| font.name.split_once('+').map(|(tag, _)| tag.to_owned()))
|
||||
.collect();
|
||||
let mut native_font_ids = BTreeMap::new();
|
||||
let mut cff_encodings = cff_fonts::Encodings::default();
|
||||
let mut mapped_encodings = cff_fonts::Encodings::default();
|
||||
for (&id, (face, paint, used)) in &native_used {
|
||||
let target = registry.and_then(|objects| objects.font_number(id))
|
||||
.map(|number| device_objects[&number] as usize);
|
||||
let encoding = if matches!(paint.program, crate::native_font::NativeFontProgram::OpenTypeCff(_)) {
|
||||
cff_encodings.mark(&mut objects, paint, used.keys().copied())
|
||||
let encoding = if matches!(
|
||||
paint.program,
|
||||
crate::native_font::NativeFontProgram::OpenTypeCff(_) | crate::native_font::NativeFontProgram::DeviceType1(_)
|
||||
) {
|
||||
mapped_encodings.mark(&mut objects, paint, used.keys().copied())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -2474,7 +2533,7 @@ fn write_pdf(
|
||||
)?,
|
||||
);
|
||||
}
|
||||
cff_encodings.write(&mut objects);
|
||||
mapped_encodings.write(&mut objects);
|
||||
for (font, owner) in aliases {
|
||||
let id = native_font_ids[&owner];
|
||||
native_font_ids.insert(font, id);
|
||||
|
||||
@@ -41,7 +41,7 @@ struct Encoding<'a> {
|
||||
names: BTreeMap<u8, &'a str>,
|
||||
}
|
||||
|
||||
/// A single encoding read is shared by all mapped CFF fonts that use it.
|
||||
/// Fonts using the same encoding resource share its PDF encoding dictionary.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Encodings<'a>(HashMap<&'a ResourceVersion, Encoding<'a>>);
|
||||
|
||||
|
||||
@@ -193,11 +193,12 @@ impl DisplayItem {
|
||||
.glyph_paths
|
||||
.get(slot)
|
||||
.filter(|_| paint.encoding.len() == 256)
|
||||
.ok_or_else(|| {
|
||||
format!(
|
||||
"native SVG outline is not resolved for {} slot {slot}",
|
||||
font.name
|
||||
)
|
||||
.ok_or_else(|| match &paint.program {
|
||||
crate::native_font::NativeFontProgram::DeviceType1(program) => format!(
|
||||
"native preview needs the actual device font {} with glyph {}",
|
||||
program.name, paint.encoding.get(usize::from(*slot)).map_or(".notdef", String::as_str)
|
||||
),
|
||||
_ => format!("native SVG outline is not resolved for {} slot {slot}", font.name),
|
||||
})?;
|
||||
Ok(NativeSvgGlyph {
|
||||
position: [*x, *y],
|
||||
|
||||
Reference in new issue
Block a user