diff --git a/crates/texrra-tex-core/src/native_font.rs b/crates/texrra-tex-core/src/native_font.rs index cfb0a73..03568a4 100644 --- a/crates/texrra-tex-core/src/native_font.rs +++ b/crates/texrra-tex-core/src/native_font.rs @@ -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 diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index b22e21a..0bc2958 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -1881,7 +1881,17 @@ fn write_native_font( }) .collect::, 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::>>().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 diff --git a/crates/texrra-tex-core/src/pdf/type1_fonts.rs b/crates/texrra-tex-core/src/pdf/type1_fonts.rs index 9a75d6d..3018108 100644 --- a/crates/texrra-tex-core/src/pdf/type1_fonts.rs +++ b/crates/texrra-tex-core/src/pdf/type1_fonts.rs @@ -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>, + font: &Type1Font, + parameters: &str, + slots: &BTreeMap, + compression: u8, + subset_tags: &mut BTreeSet, + 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) { + 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>, 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(); diff --git a/crates/texrra-tex-core/src/pdf_opentype_unicode.rs b/crates/texrra-tex-core/src/pdf_opentype_unicode.rs index a9ac0e5..87f9ade 100644 --- a/crates/texrra-tex-core/src/pdf_opentype_unicode.rs +++ b/crates/texrra-tex-core/src/pdf_opentype_unicode.rs @@ -243,7 +243,7 @@ fn for_covered(coverage: Coverage<'_>, mut visit: impl FnMut(u16, GlyphId)) { } } -fn glyph_text(name: &str, names: Option<&XdvGlyphNames>) -> Option { +pub(super) fn glyph_text(name: &str, names: Option<&XdvGlyphNames>) -> Option { let name = name.split('.').next()?; if name.is_empty() { return None; diff --git a/crates/texrra-tex-core/src/type1_outline.rs b/crates/texrra-tex-core/src/type1_outline.rs index 151f7e0..b18db30 100644 --- a/crates/texrra-tex-core/src/type1_outline.rs +++ b/crates/texrra-tex-core/src/type1_outline.rs @@ -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, String> { @@ -427,11 +428,11 @@ impl Type1Outlines { result[3].ceil() as i32, ] } - pub(crate) fn xdv_descriptor(&self, bbox: [i32; 4]) -> Result { - let height = |names: &[&str], top: bool, fallback: i32| -> Result { - let Some(name) = names.iter().find(|name| self.has_glyph(name)) else { - return Ok(f64::from(fallback)); - }; + pub(crate) fn xdv_descriptor(&self) -> Result { + let height = |name: &str, top: bool| -> Result { + // 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 = 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 { + 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, ) -> Result { 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, width: f64, + cff: Option, } #[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, } impl Runner<'_, '_> { fn pop(&mut self) -> Result { @@ -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]]); diff --git a/crates/texrra-tex-core/src/type1_outline/cff.rs b/crates/texrra-tex-core/src/type1_outline/cff.rs new file mode 100644 index 0000000..80e3cf4 --- /dev/null +++ b/crates/texrra-tex-core/src/type1_outline/cff.rs @@ -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, + 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, 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, 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, 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, value: i32) { + output.push(29); + output.extend(value.to_be_bytes()); +} + +fn dict_number(output: &mut Vec, 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, 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::().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::() + .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, 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, +) -> Result<(Vec, BTreeSet), 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::() + .map_err(|_| "invalid Type1 ItalicAngle")?; + dict_number(&mut attributes, angle)?; + attributes.extend([12, 2]); + let top = |offset: usize| -> Result, 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())) +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index b6ca317..36ed74b 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -819,6 +819,53 @@ letterspace-fresh.log 和 device-pdftex-spaced-moved.log。 [原版字距虚拟字体构造](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L16400-L16492) [原版格式所写字体字段](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L30627-L30696) +### XeTeX 的传统 Type 1 字体子集 + +按 XDV 参考驱动从实际 Type 1 字形选择构建 Type 1C 字体。复用 +现有的 eexec 解码、字形解释与子程序调用。转换为 Type 2 时保留 +字形字幅、轮廓、茎提示、提示替换、flex 和 seac 复合字形;CFF +内写入实际编码、字形名称、FontMatrix 和适用的字体私有提示值。 +未重编码的字体使用 CFF 内建编码,显式编码资源进入 PDF 字典。 +pdfTeX 使用 Type 1 字体流。 + +参考的传统字形度量查询遇到缺失的 H、b 或 p 时会命中字形 0。 +原生从实际 .notdef 取相应边界。ToUnicode 由同一作业实际找到的 +字形表和字形名称生成,用到的字形无法全部映射时省略该字典项。 +[LASY6 同类 Type 1 嵌入与度量](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/dvipdfm-x/type1.c#L495-L551) +[参考驱动的 CFF 字形查找](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/dvipdfm-x/cff.c#L991-L1049) +[Adobe CFF 格式](https://adobe-type-tools.github.io/font-tech-notes/pdfs/5176.CFF.pdf) +[Adobe Type 2 字形格式](https://adobe-type-tools.github.io/font-tech-notes/pdfs/5177.Type2.pdf) + +五份实际 PFB 生成的 CFF 由独立读取器验证,包括 LASY6、CMR10、 +CMMI10、CMSY10 和 CMBX10,保留实际字形数与字体流数据。 +初次正式出页记录在 target/p3-xdv-type1c/before-metadata。原样 +xeCJK 六页 999 个词框、光栅和 aux 一致。保留 LASY6 单页词框 +垂直边界差异及两端 PDF。冻结参考环境记录了 Adobe 字形表缺失, +最终按作业实际查询结果决定 ToUnicode。 + +最终三组单页对照的六个词框和 144 DPI 光栅全部与参考匹配, +包括 LASY6 内建编码、传统文字和数学字体切换,以及显式重编码。 +原样 xeCJK 的六页、999 个词框、光栅和 aux 仍与参考一致。 +实际 LASY6 嵌入为内建编码的 Type 1C 子集,独立单页 PDF 从 +7,633 字节减至 1,458 字节。加载真实 Adobe 字形表的对照中, +两端均生成 ToUnicode,提取文本及光栅相同,原生资源清单记录 +实际字形表指纹。最终 11 项定向共享管线测试通过。 + +三页编辑更换第 2 页的实际字符,子集随之重建。自动检查点 +复用 1,037 步并重放四次宿主调用,只刷新第 2 页。PDF、 +测量页面、SVG、来源映射及 aux 与独立全量一致。第 1、3 页 +用独立光栅确认逐像素相同。 + +最终回执 target/p3-xdv-type1c/receipt.json 的 SHA-256 +为 f109fc7e2ea50d43756875b81b5db81bf658d474d8a13222d07de70964a051ed。 +同目录 revision.log 为 06be61bc635ba23f1591e7c8dc6f93b3dc503e6a883077acc62197f2674c28c8。 +glyph-list/receipt.log 为 127a357b493c0e9fb453f55c07c7945b7210350869a2e02960ae3a0acc57fa61。 + +下一处资源差异已缩成 next-shared-face 的两页 CMR10 对照。 +同一物理字体在两个字号上的光栅均与参考一致,参考共用一份 +字体字典及子集,原生各字号分别嵌入。保留两端 PDF、字体清单 +和原始输入,用于下一轮按物理程序和实际编码共享传统字体资源。 + ### XeTeX 的 PDF 字体资源归并 同一实际 SimSun TTC 的两个字号在参考驱动中使用同一个 Type0 diff --git a/src/native.rs b/src/native.rs index b109eb2..f7c2488 100644 --- a/src/native.rs +++ b/src/native.rs @@ -1201,7 +1201,13 @@ impl CompileJob { let xdv_glyph_names = if request.target == Target::Shipouts && request.input_profile == InputProfile::XeTeX && pages.iter().any(|page| { - page.items.iter().any(|item| matches!(item, DisplayItem::OpenTypeGlyph { .. })) + page.items.iter().any(|item| match item { + DisplayItem::OpenTypeGlyph { .. } => true, + DisplayItem::NativeGlyph { paint: Some(paint), .. } => matches!( + paint.program, texrra_tex_core::native_font::NativeFontProgram::Type1(_) + ), + _ => false, + }) }) { Some(XdvGlyphNames::load(files, &request.input.to_string_lossy()) diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index afb7efa..5868747 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -746,6 +746,25 @@ fn xetex_type1_widths_follow_the_encoded_glyph_program() { .is_ok_and(|base_font| base_font.rsplit(|&byte| byte == b'+').next() == Some(name)) }) .unwrap(); + assert!(font.get(b"Encoding").is_err()); + assert!(font.get(b"ToUnicode").is_err()); + let descriptor = pdf + .dereference(font.get(b"FontDescriptor").unwrap()) + .unwrap() + .1 + .as_dict() + .unwrap(); + assert!(descriptor.get(b"FontFile").is_err()); + let embedded = pdf + .dereference(descriptor.get(b"FontFile3").unwrap()) + .unwrap() + .1 + .as_stream() + .unwrap(); + assert_eq!( + embedded.dict.get(b"Subtype").and_then(Object::as_name).unwrap(), + b"Type1C" + ); let first = font.get(b"FirstChar").unwrap().as_i64().unwrap(); let widths = pdf.dereference(font.get(b"Widths").unwrap()).unwrap().1; match widths.as_array().unwrap()[(i64::from(slot) - first) as usize] {