Embed hinted Type 1C subsets for XeTeX PDF output
This commit is contained in:
1 parent
4ae4275cf3
commit
01c6f1d4bd
9 files changed
+629
-26
No files matched your search
@@ -624,7 +624,7 @@ fn resolve_physical_fonts(
|
||||
descriptor_flags: outline.descriptor_flags,
|
||||
xdv_descriptor: if xdv {
|
||||
Some(decoded.xdv_descriptor.get_or_init(|| {
|
||||
decoded.outlines.xdv_descriptor(program.bbox)
|
||||
decoded.outlines.xdv_descriptor()
|
||||
}).clone()?)
|
||||
} else {
|
||||
None
|
||||
|
||||
@@ -1881,7 +1881,17 @@ fn write_native_font(
|
||||
})
|
||||
.collect::<Result<Vec<_>, String>>()?
|
||||
.join(" ");
|
||||
let xdv_type1 = paint.xdv_descriptor.is_some() && matches!(paint.program, NativeFontProgram::Type1(_));
|
||||
let (subtype, descriptor, name, widths, encoding, has_glyph_unicode) = match &paint.program {
|
||||
NativeFontProgram::Type1(font) if xdv_type1 => {
|
||||
let slots = used.keys().map(|&slot| (slot, paint.encoding[usize::from(slot)].as_str())).collect();
|
||||
let (descriptor, name) = type1_fonts::write_xdv(
|
||||
objects, font, &native_type1_parameters(font, paint, m), &slots, compression,
|
||||
subset_tags, options.is_some_and(|options| options.omit_charset),
|
||||
).map_err(|error| format!("cannot embed XeTeX Type1 font {}: {error}", face.name))?;
|
||||
let encoding = mapped_encoding.map_or_else(String::new, |id| format!(" /Encoding {id} 0 R"));
|
||||
("Type1", descriptor, name, format!("[{widths}]"), encoding, true)
|
||||
}
|
||||
NativeFontProgram::Type1(font) => {
|
||||
let descriptor = reference.map_or_else(
|
||||
|| type1_fonts::write_full(objects, font, &native_type1_parameters(font, paint, m), compression),
|
||||
@@ -1953,6 +1963,14 @@ fn write_native_font(
|
||||
let unicode = objects.len() + 1;
|
||||
let cmap = if !has_glyph_unicode {
|
||||
None
|
||||
} else if xdv_type1 {
|
||||
let names = options.and_then(|options| options.xdv_glyph_names);
|
||||
// The XDV driver only writes a simple-font cmap when every used
|
||||
// slot can be recovered from the job's glyph lists or name syntax.
|
||||
used.keys().map(|&slot| {
|
||||
opentype_unicode::glyph_text(&paint.encoding[usize::from(slot)], names)
|
||||
.map(|text| (slot, text))
|
||||
}).collect::<Option<BTreeMap<_, _>>>().map(|texts| type1_tounicode_texts(&texts))
|
||||
} else if let Some(options) = options {
|
||||
if options.fonts.pdf_settings(face.id).is_some_and(|settings| settings.omit_builtin_unicode) {
|
||||
None
|
||||
@@ -2500,6 +2518,9 @@ fn write_pdf(
|
||||
let crate::native_font::NativeFontProgram::Type1(program) = &paint.program else {
|
||||
continue;
|
||||
};
|
||||
if paint.xdv_descriptor.is_some() {
|
||||
continue;
|
||||
}
|
||||
let Some(key) = paint.type1_program_key() else {
|
||||
continue;
|
||||
};
|
||||
@@ -2530,7 +2551,7 @@ fn write_pdf(
|
||||
let encoding = if matches!(
|
||||
paint.program,
|
||||
crate::native_font::NativeFontProgram::OpenTypeCff(_) | crate::native_font::NativeFontProgram::DeviceType1(_)
|
||||
) {
|
||||
) || paint.xdv_descriptor.is_some() {
|
||||
mapped_encodings.mark(&mut objects, paint, used.keys().copied())
|
||||
} else {
|
||||
None
|
||||
|
||||
@@ -4,10 +4,10 @@ use crate::{
|
||||
native_font::Type1ProgramKey,
|
||||
pdf_image::ImportedType1Use,
|
||||
type1::Type1Font,
|
||||
type1_outline::{subset_tag, write_subset},
|
||||
type1_outline::{subset_tag, write_subset, write_type1c},
|
||||
};
|
||||
use std::{
|
||||
collections::{BTreeSet, HashMap},
|
||||
collections::{BTreeMap, BTreeSet, HashMap},
|
||||
fmt::Write as _,
|
||||
};
|
||||
|
||||
@@ -163,6 +163,45 @@ pub(super) fn write_full(
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn write_xdv(
|
||||
objects: &mut Vec<Vec<u8>>,
|
||||
font: &Type1Font,
|
||||
parameters: &str,
|
||||
slots: &BTreeMap<u8, &str>,
|
||||
compression: u8,
|
||||
subset_tags: &mut BTreeSet<String>,
|
||||
omit_charset: bool,
|
||||
) -> Result<(usize, String), String> {
|
||||
let marked = slots.values().map(|&name| name.to_owned()).collect();
|
||||
let tag = (0..100)
|
||||
.map(|salt| subset_tag(&font.name, &marked, salt))
|
||||
.find(|tag| subset_tags.insert(tag.clone()))
|
||||
.ok_or("Type1C subset name collision limit exceeded")?;
|
||||
let name = format!("{tag}+{}", font.name);
|
||||
let (program, glyphs) = write_type1c(font, &name, slots)?;
|
||||
let file = objects.len() + 1;
|
||||
objects.push(objects::stream("/Subtype /Type1C", &program, compression));
|
||||
let name = native_pdf_name(&name);
|
||||
let mut descriptor = format!("<< /Type /FontDescriptor /FontName /{name} {parameters}");
|
||||
if !omit_charset {
|
||||
append_charset(&mut descriptor, &glyphs);
|
||||
}
|
||||
write!(descriptor, " /FontFile3 {file} 0 R >>").unwrap();
|
||||
objects.push(descriptor.into_bytes());
|
||||
Ok((objects.len(), name))
|
||||
}
|
||||
|
||||
fn append_charset(body: &mut String, glyphs: &BTreeSet<String>) {
|
||||
body.push_str(" /CharSet <");
|
||||
for glyph in glyphs {
|
||||
body.push_str("2F");
|
||||
for byte in glyph.bytes() {
|
||||
write!(body, "{byte:02X}").unwrap();
|
||||
}
|
||||
}
|
||||
body.push('>');
|
||||
}
|
||||
|
||||
fn write_embedding(
|
||||
objects: &mut Vec<Vec<u8>>,
|
||||
name: &str,
|
||||
@@ -190,14 +229,7 @@ fn write_embedding(
|
||||
};
|
||||
let mut body = format!("<< /Type /FontDescriptor /FontName {font_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('>');
|
||||
append_charset(&mut body, glyphs);
|
||||
}
|
||||
write!(body, " /FontFile {file} 0 R >>").unwrap();
|
||||
objects[descriptor - 1] = body.into_bytes();
|
||||
|
||||
@@ -243,7 +243,7 @@ fn for_covered(coverage: Coverage<'_>, mut visit: impl FnMut(u16, GlyphId)) {
|
||||
}
|
||||
}
|
||||
|
||||
fn glyph_text(name: &str, names: Option<&XdvGlyphNames>) -> Option<String> {
|
||||
pub(super) fn glyph_text(name: &str, names: Option<&XdvGlyphNames>) -> Option<String> {
|
||||
let name = name.split('.').next()?;
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
//! Type1 eexec/charstring execution for unhinted vector output. The PDF keeps
|
||||
//! the original hinted program; SVG executes its actual paths and components.
|
||||
//! Type 1 eexec and charstring execution for vector outlines and CFF subsets.
|
||||
use crate::type1::{Type1Font, font_matrix, standard_encoding};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
mod subset;
|
||||
mod cff;
|
||||
pub(crate) use cff::write_type1c;
|
||||
pub(crate) use subset::{subset_tag, write_subset};
|
||||
use subset::{GlyphUse, ProgramRanges, SubrRange};
|
||||
fn decrypt(data: &[u8], mut key: u16, skip: usize) -> Result<Vec<u8>, String> {
|
||||
@@ -427,11 +428,11 @@ impl Type1Outlines {
|
||||
result[3].ceil() as i32,
|
||||
]
|
||||
}
|
||||
pub(crate) fn xdv_descriptor(&self, bbox: [i32; 4]) -> Result<XdvDescriptor, String> {
|
||||
let height = |names: &[&str], top: bool, fallback: i32| -> Result<f64, String> {
|
||||
let Some(name) = names.iter().find(|name| self.has_glyph(name)) else {
|
||||
return Ok(f64::from(fallback));
|
||||
};
|
||||
pub(crate) fn xdv_descriptor(&self) -> Result<XdvDescriptor, String> {
|
||||
let height = |name: &str, top: bool| -> Result<f64, String> {
|
||||
// The reference device's CFF name lookup returns glyph zero
|
||||
// for a name absent from the font.
|
||||
let name = if self.has_glyph(name) { name } else { ".notdef" };
|
||||
let mut budget = 1_000_000;
|
||||
let mut bound: Option<f64> = None;
|
||||
let mut include = |y: f64| {
|
||||
@@ -450,9 +451,9 @@ impl Type1Outlines {
|
||||
}
|
||||
Ok(bound.unwrap_or(0.))
|
||||
};
|
||||
let cap = height(&["H", "P", "Pi", "Rho"], true, bbox[3])?;
|
||||
let ascent = height(&["b", "h", "lambda"], true, bbox[3])?;
|
||||
let descent = height(&["p", "q", "mu", "eta"], false, bbox[1])?;
|
||||
let cap = height("H", true)?;
|
||||
let ascent = height("b", true)?;
|
||||
let descent = height("p", false)?;
|
||||
let stem = self.std_vw.unwrap_or(88.);
|
||||
Ok(XdvDescriptor {
|
||||
metrics: [ascent, descent, cap, stem].map(f64::to_bits),
|
||||
@@ -464,11 +465,22 @@ impl Type1Outlines {
|
||||
self.glyphs.contains_key(name)
|
||||
}
|
||||
fn glyph(
|
||||
&self,
|
||||
name: &str,
|
||||
depth: usize,
|
||||
budget: &mut usize,
|
||||
usage: Option<&mut GlyphUse>,
|
||||
) -> Result<Type1Glyph, String> {
|
||||
self.run_glyph(name, depth, budget, usage, None)
|
||||
}
|
||||
|
||||
fn run_glyph(
|
||||
&self,
|
||||
name: &str,
|
||||
depth: usize,
|
||||
budget: &mut usize,
|
||||
mut usage: Option<&mut GlyphUse>,
|
||||
cff: Option<cff::GlyphTrace>,
|
||||
) -> Result<Type1Glyph, String> {
|
||||
if depth > 32 {
|
||||
return Err("Type1 composite recursion capacity exceeded".into());
|
||||
@@ -488,10 +500,12 @@ impl Type1Outlines {
|
||||
x: 0.,
|
||||
y: 0.,
|
||||
sbx: 0.,
|
||||
sby: 0.,
|
||||
width: 0.,
|
||||
open: false,
|
||||
flex: false,
|
||||
other_results: 0,
|
||||
cff,
|
||||
};
|
||||
if !run.execute(code, depth, budget)? {
|
||||
return Err("Type1 glyph program has no endchar/seac".into());
|
||||
@@ -499,6 +513,7 @@ impl Type1Outlines {
|
||||
Ok(Type1Glyph {
|
||||
commands: run.commands,
|
||||
width: run.width,
|
||||
cff: run.cff,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -550,6 +565,7 @@ impl Type1Outlines {
|
||||
struct Type1Glyph {
|
||||
commands: Vec<Command>,
|
||||
width: f64,
|
||||
cff: Option<cff::GlyphTrace>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -586,10 +602,12 @@ struct Runner<'a, 'u> {
|
||||
x: f64,
|
||||
y: f64,
|
||||
sbx: f64,
|
||||
sby: f64,
|
||||
width: f64,
|
||||
open: bool,
|
||||
flex: bool,
|
||||
other_results: usize,
|
||||
cff: Option<cff::GlyphTrace>,
|
||||
}
|
||||
impl Runner<'_, '_> {
|
||||
fn pop(&mut self) -> Result<f64, String> {
|
||||
@@ -673,6 +691,9 @@ impl Runner<'_, '_> {
|
||||
if self.stack.len() % 2 != 0 {
|
||||
return Err("invalid Type1 stem operands".into());
|
||||
}
|
||||
if let Some(trace) = &mut self.cff {
|
||||
trace.stems(self.commands.len(), op == 3, [self.sbx, self.sby], &self.stack)?;
|
||||
}
|
||||
self.stack.clear();
|
||||
}
|
||||
4 | 21 | 22 => {
|
||||
@@ -758,11 +779,21 @@ impl Runner<'_, '_> {
|
||||
0 => {
|
||||
self.args(0)?;
|
||||
}
|
||||
1 | 2 => {
|
||||
self.args(6)?;
|
||||
stem @ (1 | 2) => {
|
||||
let args = self.args(6)?;
|
||||
if let Some(trace) = &mut self.cff {
|
||||
trace.stems(self.commands.len(), stem == 1, [self.sbx, self.sby], &args)?;
|
||||
}
|
||||
}
|
||||
6 => {
|
||||
let v = self.args(5)?;
|
||||
if let Some(trace) = &mut self.cff {
|
||||
if v[3..].iter().any(|i| !(0. ..=255.).contains(i) || i.fract() != 0.) {
|
||||
return Err("invalid Type1 seac code".into());
|
||||
}
|
||||
trace.seac = Some([v[1] + self.sbx - v[0], v[2] + self.sby, v[3], v[4]]);
|
||||
return Ok(true);
|
||||
}
|
||||
for (i, dx, dy) in [(v[3], 0., 0.), (v[4], v[1] + self.sbx - v[0], v[2])] {
|
||||
if !(0. ..=255.).contains(&i) || i.fract() != 0. {
|
||||
return Err("invalid Type1 seac code".into());
|
||||
@@ -782,6 +813,7 @@ impl Runner<'_, '_> {
|
||||
7 => {
|
||||
let v = self.args(4)?;
|
||||
self.sbx = v[0];
|
||||
self.sby = v[1];
|
||||
self.x = v[0];
|
||||
self.y = v[1];
|
||||
self.width = v[2];
|
||||
@@ -805,12 +837,19 @@ impl Runner<'_, '_> {
|
||||
return Err("missing Type1 hint-replacement argument".into());
|
||||
}
|
||||
self.other_results = 1;
|
||||
if let Some(trace) = &mut self.cff {
|
||||
trace.replaces_hints = true;
|
||||
}
|
||||
}
|
||||
(0, 3) => {
|
||||
if !self.flex || self.stack.len() < 17 {
|
||||
return Err("invalid Type1 flex state".into());
|
||||
}
|
||||
let v = self.stack.split_off(self.stack.len() - 17);
|
||||
if self.cff.is_some() {
|
||||
self.start();
|
||||
self.cff.as_mut().unwrap().flex.insert(self.commands.len(), v[14]);
|
||||
}
|
||||
self.curve(&[v[2] + v[0], v[3] + v[1], v[4], v[5], v[6], v[7]]);
|
||||
self.curve(&v[8..14]);
|
||||
self.stack.extend([v[15], v[16]]);
|
||||
|
||||
@@ -0,0 +1,439 @@
|
||||
//! Name-keyed CFF subsets for the XDV PDF device.
|
||||
use super::{
|
||||
Command, Tokens, Type1Font, Type1Glyph, Type1Outlines, private_dictionary, standard_encoding,
|
||||
};
|
||||
use read_fonts::ps::Sid;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Stem {
|
||||
vertical: bool,
|
||||
position: f64,
|
||||
width: f64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct GlyphTrace {
|
||||
stems: Vec<(usize, Stem)>,
|
||||
pub(super) replaces_hints: bool,
|
||||
pub(super) flex: BTreeMap<usize, f64>,
|
||||
pub(super) seac: Option<[f64; 4]>,
|
||||
}
|
||||
|
||||
impl GlyphTrace {
|
||||
pub(super) fn stems(
|
||||
&mut self,
|
||||
at: usize,
|
||||
vertical: bool,
|
||||
[sbx, sby]: [f64; 2],
|
||||
values: &[f64],
|
||||
) -> Result<(), String> {
|
||||
let offset = if vertical { sbx } else { sby };
|
||||
for pair in values.chunks_exact(2) {
|
||||
let position = offset + pair[0];
|
||||
if !position.is_finite() || !pair[1].is_finite() {
|
||||
return Err("nonfinite Type1 stem".into());
|
||||
}
|
||||
self.stems.push((
|
||||
at,
|
||||
Stem {
|
||||
vertical,
|
||||
position,
|
||||
width: pair[1],
|
||||
},
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
const STANDARD_STRING_COUNT: u16 = 391;
|
||||
|
||||
// Both DICTs and Type 2 charstrings use this short integer representation.
|
||||
fn short_integer(output: &mut Vec<u8>, value: i16) {
|
||||
match value {
|
||||
-107..=107 => output.push((value + 139) as u8),
|
||||
108..=1131 => {
|
||||
let n = value - 108;
|
||||
output.extend([247 + (n >> 8) as u8, n as u8]);
|
||||
}
|
||||
-1131..=-108 => {
|
||||
let n = -value - 108;
|
||||
output.extend([251 + (n >> 8) as u8, n as u8]);
|
||||
}
|
||||
_ => {
|
||||
output.push(28);
|
||||
output.extend(value.to_be_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn operands(output: &mut Vec<u8>, values: &[f64]) -> Result<(), String> {
|
||||
for &value in values {
|
||||
let fixed = (value * 65536.).round();
|
||||
if !fixed.is_finite() || fixed < f64::from(i32::MIN) || fixed > f64::from(i32::MAX) {
|
||||
return Err("Type 2 charstring operand exceeds the signed 16.16 range".into());
|
||||
}
|
||||
let fixed = fixed as i32;
|
||||
if fixed & 0xffff == 0 {
|
||||
short_integer(output, (fixed >> 16) as i16);
|
||||
} else {
|
||||
output.push(255);
|
||||
output.extend(fixed.to_be_bytes());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn charstring(glyph: Type1Glyph) -> Result<(Vec<u8>, Option<[f64; 4]>), String> {
|
||||
let trace = glyph
|
||||
.cff
|
||||
.expect("Type 2 conversion captures glyph operations");
|
||||
let mut stems: Vec<_> = trace.stems.iter().map(|&(_, stem)| stem).collect();
|
||||
stems.sort_by(|a, b| {
|
||||
a.vertical
|
||||
.cmp(&b.vertical)
|
||||
.then(a.position.total_cmp(&b.position))
|
||||
.then(a.width.total_cmp(&b.width))
|
||||
});
|
||||
stems.dedup();
|
||||
if stems.len() > 96 {
|
||||
return Err("Type 2 stem capacity exceeded".into());
|
||||
}
|
||||
let masks = trace.replaces_hints && !stems.is_empty();
|
||||
let mut output = Vec::new();
|
||||
if glyph.width != 0. {
|
||||
operands(&mut output, &[glyph.width])?;
|
||||
}
|
||||
let horizontal = stems.partition_point(|stem| !stem.vertical);
|
||||
for (axis, slice) in [&stems[..horizontal], &stems[horizontal..]]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
for group in slice.chunks(23) {
|
||||
let mut last = 0.;
|
||||
for stem in group {
|
||||
operands(&mut output, &[stem.position - last, stem.width])?;
|
||||
last = stem.position + stem.width;
|
||||
}
|
||||
output.push(match (axis, masks) {
|
||||
(0, false) => 1,
|
||||
(0, true) => 18,
|
||||
(_, false) => 3,
|
||||
(_, true) => 23,
|
||||
});
|
||||
}
|
||||
}
|
||||
let mut marks = trace.stems.into_iter().peekable();
|
||||
let mut index = 0;
|
||||
let mut point = [0., 0.];
|
||||
let mut delta = |[x, y]: [f64; 2]| {
|
||||
let offset = [x - point[0], y - point[1]];
|
||||
point = [x, y];
|
||||
offset
|
||||
};
|
||||
while index < glyph.commands.len() {
|
||||
if masks && marks.peek().is_some_and(|(at, _)| *at == index) {
|
||||
let mut mask = vec![0; stems.len().div_ceil(8)];
|
||||
while let Some((_, stem)) = marks.next_if(|(at, _)| *at == index) {
|
||||
let bit = stems
|
||||
.iter()
|
||||
.position(|known| *known == stem)
|
||||
.expect("all Type 1 stem declarations are indexed");
|
||||
mask[bit / 8] |= 0x80 >> (bit % 8);
|
||||
}
|
||||
output.push(19);
|
||||
output.extend(mask);
|
||||
}
|
||||
if let Some(depth) = trace.flex.get(&index) {
|
||||
for segment in &glyph.commands[index..index + 2] {
|
||||
let Command::Curve(a, b, c, d, x, y) = *segment else {
|
||||
return Err("Type1 flex did not produce two curves".into());
|
||||
};
|
||||
for point in [[a, b], [c, d], [x, y]] {
|
||||
operands(&mut output, &delta(point))?;
|
||||
}
|
||||
}
|
||||
operands(&mut output, &[*depth])?;
|
||||
output.extend([12, 35]);
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
match glyph.commands[index] {
|
||||
Command::Move(x, y) => {
|
||||
operands(&mut output, &delta([x, y]))?;
|
||||
output.push(21);
|
||||
}
|
||||
Command::Line(x, y) => {
|
||||
operands(&mut output, &delta([x, y]))?;
|
||||
output.push(5);
|
||||
}
|
||||
Command::Curve(a, b, c, d, x, y) => {
|
||||
for point in [[a, b], [c, d], [x, y]] {
|
||||
operands(&mut output, &delta(point))?;
|
||||
}
|
||||
output.push(8);
|
||||
}
|
||||
// Type 2 closes contours implicitly, with the current point
|
||||
// still at the end of the previous Type 1 contour.
|
||||
Command::Close => {}
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
if let Some(seac) = trace.seac {
|
||||
operands(&mut output, &seac)?;
|
||||
}
|
||||
output.push(14);
|
||||
Ok((output, trace.seac))
|
||||
}
|
||||
|
||||
fn dict_long(output: &mut Vec<u8>, value: i32) {
|
||||
output.push(29);
|
||||
output.extend(value.to_be_bytes());
|
||||
}
|
||||
|
||||
fn dict_number(output: &mut Vec<u8>, value: f64) -> Result<(), String> {
|
||||
if !value.is_finite() {
|
||||
return Err("nonfinite CFF dictionary operand".into());
|
||||
}
|
||||
if value.fract() == 0. && value.abs() <= f64::from(i32::MAX) {
|
||||
if let Ok(short) = i16::try_from(value as i32) {
|
||||
short_integer(output, short);
|
||||
} else {
|
||||
dict_long(output, value as i32);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let decimal = value.to_string();
|
||||
let mut nibbles: Vec<_> = decimal
|
||||
.bytes()
|
||||
.map(|b| match b {
|
||||
b'0'..=b'9' => b - b'0',
|
||||
b'-' => 0xe,
|
||||
b'.' => 0xa,
|
||||
_ => unreachable!("Display for f64 emits a decimal"),
|
||||
})
|
||||
.collect();
|
||||
nibbles.push(0xf);
|
||||
if nibbles.len() % 2 != 0 {
|
||||
nibbles.push(0xf);
|
||||
}
|
||||
output.push(30);
|
||||
output.extend(nibbles.chunks_exact(2).map(|n| n[0] << 4 | n[1]));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn private_dict(private: &[u8]) -> Result<Vec<u8>, String> {
|
||||
let mut tokens = Tokens::new(private);
|
||||
let mut previous = None;
|
||||
let mut entries = BTreeMap::new();
|
||||
while let Some(token) = tokens.next()? {
|
||||
let (operator, array) = match token.as_str() {
|
||||
"/BlueValues" => (&[6][..], true),
|
||||
"/OtherBlues" => (&[7][..], true),
|
||||
"/FamilyBlues" => (&[8][..], true),
|
||||
"/FamilyOtherBlues" => (&[9][..], true),
|
||||
"/StdHW" => (&[10][..], false),
|
||||
"/StdVW" => (&[11][..], false),
|
||||
"/BlueScale" => (&[12, 9][..], false),
|
||||
"/BlueShift" => (&[12, 10][..], false),
|
||||
"/BlueFuzz" => (&[12, 11][..], false),
|
||||
"/StemSnapH" => (&[12, 12][..], true),
|
||||
"/StemSnapV" => (&[12, 13][..], true),
|
||||
"/ForceBold" => (&[12, 14][..], false),
|
||||
"/LanguageGroup" => (&[12, 17][..], false),
|
||||
"/ExpansionFactor" => (&[12, 18][..], false),
|
||||
"/CharStrings" => break,
|
||||
"RD" | "-|" if previous.is_some() => {
|
||||
tokens.binary_data(previous.take().unwrap())?;
|
||||
continue;
|
||||
}
|
||||
_ => {
|
||||
previous = token.parse::<usize>().ok();
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut value = tokens.required()?;
|
||||
let end = match value.as_str() {
|
||||
"[" => Some("]"),
|
||||
"{" => Some("}"),
|
||||
_ => None,
|
||||
};
|
||||
let mut last = 0.;
|
||||
let mut data = Vec::new();
|
||||
if end.is_some() {
|
||||
value = tokens.required()?;
|
||||
}
|
||||
while Some(value.as_str()) != end || end.is_none() {
|
||||
let number = match value.as_str() {
|
||||
"true" => 1.,
|
||||
"false" => 0.,
|
||||
_ => value
|
||||
.parse::<f64>()
|
||||
.map_err(|_| format!("invalid Type1 {token} hint"))?,
|
||||
};
|
||||
dict_number(&mut data, number - last)?;
|
||||
if end.is_none() {
|
||||
break;
|
||||
}
|
||||
last = if array { number } else { 0. };
|
||||
value = tokens.required()?;
|
||||
}
|
||||
if !data.is_empty() {
|
||||
data.extend_from_slice(operator);
|
||||
entries.insert(operator, data);
|
||||
}
|
||||
previous = None;
|
||||
}
|
||||
Ok(entries.into_values().flatten().collect())
|
||||
}
|
||||
|
||||
fn index(items: &[impl AsRef<[u8]>]) -> Result<Vec<u8>, String> {
|
||||
let count = u16::try_from(items.len()).map_err(|_| "CFF INDEX capacity exceeded")?;
|
||||
let mut output = count.to_be_bytes().to_vec();
|
||||
if count == 0 {
|
||||
return Ok(output);
|
||||
}
|
||||
output.push(4);
|
||||
let mut offset = 1u32;
|
||||
for item in items {
|
||||
output.extend(offset.to_be_bytes());
|
||||
let length = u32::try_from(item.as_ref().len()).map_err(|_| "CFF INDEX item too large")?;
|
||||
offset = offset
|
||||
.checked_add(length)
|
||||
.ok_or("CFF INDEX size overflow")?;
|
||||
}
|
||||
output.extend(offset.to_be_bytes());
|
||||
for item in items {
|
||||
output.extend_from_slice(item.as_ref());
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
pub(crate) fn write_type1c(
|
||||
font: &Type1Font,
|
||||
subset_name: &str,
|
||||
slots: &BTreeMap<u8, &str>,
|
||||
) -> Result<(Vec<u8>, BTreeSet<String>), String> {
|
||||
let private = private_dictionary(font)?;
|
||||
let outlines = Type1Outlines::from_private(font, &private, None)?;
|
||||
let mut glyphs = vec![".notdef"];
|
||||
let mut included = BTreeSet::from([".notdef"]);
|
||||
let mut codes = Vec::new();
|
||||
let mut aliases = Vec::new();
|
||||
for (&code, &name) in slots {
|
||||
if included.insert(name) {
|
||||
glyphs.push(name);
|
||||
codes.push(code);
|
||||
} else if name != ".notdef" {
|
||||
aliases.push((code, name));
|
||||
}
|
||||
}
|
||||
let mut programs = Vec::new();
|
||||
let mut budget = 2_000_000;
|
||||
while let Some(&name) = glyphs.get(programs.len()) {
|
||||
let glyph = outlines.run_glyph(name, 0, &mut budget, None, Some(GlyphTrace::default()))?;
|
||||
let (program, seac) = charstring(glyph)?;
|
||||
programs.push(program);
|
||||
if let Some([_, _, base, accent]) = seac {
|
||||
for code in [base, accent] {
|
||||
let name =
|
||||
standard_encoding(code as u8).ok_or("unassigned seac StandardEncoding slot")?;
|
||||
if included.insert(name) {
|
||||
glyphs.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut strings = Vec::new();
|
||||
let mut sids = BTreeMap::new();
|
||||
let mut charset = vec![0];
|
||||
for name in glyphs.into_iter().skip(1) {
|
||||
let sid = (0..STANDARD_STRING_COUNT)
|
||||
.find(|&sid| Sid::new(sid).resolve_standard().ok() == Some(name.as_bytes()))
|
||||
.unwrap_or_else(|| {
|
||||
let sid = STANDARD_STRING_COUNT + strings.len() as u16;
|
||||
strings.push(name.as_bytes());
|
||||
sid
|
||||
});
|
||||
charset.extend(sid.to_be_bytes());
|
||||
sids.insert(name, sid);
|
||||
}
|
||||
let mut ranges: Vec<[u8; 2]> = Vec::new();
|
||||
for code in codes {
|
||||
if let Some([start, length]) = ranges.last_mut()
|
||||
&& u16::from(*start) + u16::from(*length) + 1 == u16::from(code)
|
||||
{
|
||||
*length += 1;
|
||||
} else {
|
||||
ranges.push([code, 0]);
|
||||
}
|
||||
}
|
||||
let mut encoding = vec![
|
||||
if aliases.is_empty() { 1 } else { 0x81 },
|
||||
ranges.len() as u8,
|
||||
];
|
||||
encoding.extend(ranges.into_iter().flatten());
|
||||
if !aliases.is_empty() {
|
||||
encoding.push(aliases.len() as u8);
|
||||
for (code, name) in aliases {
|
||||
encoding.push(code);
|
||||
encoding.extend(sids[name].to_be_bytes());
|
||||
}
|
||||
}
|
||||
let private = private_dict(&private)?;
|
||||
let name = index(&[subset_name])?;
|
||||
let strings = index(&strings)?;
|
||||
let programs = index(&programs)?;
|
||||
let mut attributes = Vec::new();
|
||||
for value in font.bbox {
|
||||
dict_number(&mut attributes, f64::from(value))?;
|
||||
}
|
||||
attributes.push(5); // FontBBox
|
||||
for value in outlines.matrix {
|
||||
dict_number(&mut attributes, value)?;
|
||||
}
|
||||
attributes.extend([12, 7]); // FontMatrix
|
||||
if font.is_fixed_pitch {
|
||||
attributes.extend([140, 12, 1]); // isFixedPitch
|
||||
}
|
||||
let angle = font
|
||||
.italic_angle
|
||||
.parse::<f64>()
|
||||
.map_err(|_| "invalid Type1 ItalicAngle")?;
|
||||
dict_number(&mut attributes, angle)?;
|
||||
attributes.extend([12, 2]);
|
||||
let top = |offset: usize| -> Result<Vec<u8>, String> {
|
||||
let mut dict = attributes.clone();
|
||||
let mut position = offset;
|
||||
for (op, bytes) in [(16, &encoding), (15, &charset), (17, &programs)] {
|
||||
dict_long(
|
||||
&mut dict,
|
||||
i32::try_from(position).map_err(|_| "CFF offset overflow")?,
|
||||
);
|
||||
dict.push(op);
|
||||
position += bytes.len();
|
||||
}
|
||||
dict_long(
|
||||
&mut dict,
|
||||
i32::try_from(private.len()).map_err(|_| "CFF private size overflow")?,
|
||||
);
|
||||
dict_long(
|
||||
&mut dict,
|
||||
i32::try_from(position).map_err(|_| "CFF offset overflow")?,
|
||||
);
|
||||
dict.push(18);
|
||||
index(&[dict])
|
||||
};
|
||||
let offset = 4 + name.len() + top(0)?.len() + strings.len() + 2;
|
||||
let mut output = vec![1, 0, 4, 4];
|
||||
output.extend(name);
|
||||
output.extend(top(offset)?);
|
||||
output.extend(strings);
|
||||
output.extend([0, 0]); // Global Subrs INDEX; Type 1 subroutines were expanded.
|
||||
for part in [encoding, charset, programs, private] {
|
||||
output.extend(part);
|
||||
}
|
||||
included.remove(".notdef");
|
||||
Ok((output, included.into_iter().map(str::to_owned).collect()))
|
||||
}
|
||||
Reference in new issue
Block a user