From 7d460e0fa1603b734134c3db4cc6f3681605dd10 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 28 Nov 2026 21:40:17 +0800 Subject: [PATCH] Apply XeLaTeX CMaps to document text and embedded fonts --- .../texrra-tex-core/src/execution/engine.rs | 2 + .../src/execution/engine/page.rs | 10 +- .../src/execution/engine/specials.rs | 18 +- .../src/execution/engine/xdv_annotation.rs | 8 +- crates/texrra-tex-core/src/native_font.rs | 73 ++++- crates/texrra-tex-core/src/native_font/cff.rs | 1 + .../src/native_font/device_type1.rs | 1 + crates/texrra-tex-core/src/native_font/map.rs | 23 ++ .../src/native_font/truetype.rs | 1 + crates/texrra-tex-core/src/pdf.rs | 4 +- crates/texrra-tex-core/src/pdf_device.rs | 1 + crates/texrra-tex-core/src/pdf_device/cmap.rs | 306 ++++++++++++++++++ .../src/pdf_device/xdv_annotation.rs | 7 +- .../src/pdf_device/xdv_document.rs | 129 ++++++-- .../src/pdf_device/xdv_navigation.rs | 15 +- .../src/pdf_device/xdv_object.rs | 87 ++++- crates/texrra-tex-core/src/render.rs | 15 +- crates/texrra-tex-core/src/resources.rs | 7 +- .../tests/execution_xetex_profile.rs | 72 +++++ docs/P2_M1_PROGRESS.md | 32 ++ 20 files changed, 747 insertions(+), 65 deletions(-) create mode 100644 crates/texrra-tex-core/src/pdf_device/cmap.rs diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 274ad07..0454ff5 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -229,6 +229,7 @@ pub struct Executor { pdf_colors: crate::pdf_device::PdfColorStacks, xdv_colors: crate::pdf_device::xdv_color::ColorState, xdv_annotations: crate::pdf_device::xdv_annotation::AnnotationState, + xdv_text: crate::pdf_device::xdv_document::TextEncoding, pdf_link_stack: Vec, pdf_active_thread: Option, pdf_navigation_geometry: pdf_links::NavigationGeometry, @@ -415,6 +416,7 @@ impl Executor { pdf_colors: Default::default(), xdv_colors: Default::default(), xdv_annotations: Default::default(), + xdv_text: Default::default(), pdf_link_stack: Vec::new(), pdf_active_thread: None, pdf_navigation_geometry: Default::default(), diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index 6d83188..57b007b 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -630,7 +630,7 @@ impl Executor { } None } else if xdv && crate::pdf_device::xdv_annotation::Command::recognize(&special.bytes).is_some() { - xdv_annotations.insert(graphics_step, shipout.specials.len()); + xdv_annotations.insert(graphics_step, (shipout.specials.len(), self.xdv_text.clone())); None } else if xdv && crate::pdf_device::xdv_paper::Special::parse(&special.bytes).is_some() { xdv_paper_specials.push(shipout.specials.len()); @@ -643,7 +643,8 @@ impl Executor { (special.position[0] + horizontal_origin) as f64, (special.position[1] + vertical_origin + b.height) as f64, ).map(|coordinate| coordinate.round() as i64); - xdv_navigation.push((shipout.specials.len(), graphics_step, point, *origin, content_origins.last().copied())); + let text = matches!(kind, b"docview" | b"outline").then(|| self.xdv_text.clone()); + xdv_navigation.push((shipout.specials.len(), graphics_step, point, *origin, content_origins.last().copied(), text)); None } else if xdv && self.xdv_setup_special(&special)? { None @@ -860,7 +861,7 @@ impl Executor { origin_x - device.horizontal_origin, device.page_height - origin_y - device.vertical_origin - shipout.box_node.height, ]; - for (index, graphics_step, [x, y], origin, content_origin) in xdv_navigation { + for (index, graphics_step, [x, y], origin, content_origin, text) in xdv_navigation { let special = &shipout.specials[index]; let position = crate::pdf_device::xdv_object::Position { page: self.shipped_pages + 1, @@ -883,7 +884,8 @@ impl Executor { let capture_origin = [x - left, top - y] .map(|coordinate| crate::render::DisplayUnits::TeX.bp(coordinate)); if let Some(operation) = self.ship_xdv_navigation( - special, position, graphics_step, capture_origin, &mut shipout.pdf_links, origin, files, + special, position, graphics_step, capture_origin, &mut shipout.pdf_links, + text.as_ref(), origin, files, )? { shipout.pdf_graphics_steps[graphics_step] = Some(operation); } diff --git a/crates/texrra-tex-core/src/execution/engine/specials.rs b/crates/texrra-tex-core/src/execution/engine/specials.rs index 2e03a03..44553fc 100644 --- a/crates/texrra-tex-core/src/execution/engine/specials.rs +++ b/crates/texrra-tex-core/src/execution/engine/specials.rs @@ -57,6 +57,7 @@ impl Executor { graphics_step: usize, capture_origin: [f64; 2], links: &mut crate::pdf_device::links::PageLinks, + text: Option<&crate::pdf_device::xdv_document::TextEncoding>, origin: Option, files: &mut impl SourceProvider, ) -> Result, Error> { @@ -82,9 +83,9 @@ impl Executor { } else if matches!(kind, b"docview" | b"outline" | b"pageresources" | b"names") { let navigation = Arc::make_mut(self.state.xdv_navigation.get_or_insert_with(Default::default)); if kind == b"docview" { - navigation.merge_catalog(operands, position, self.limits.tokens) + navigation.merge_catalog(operands, position, text.expect("catalog text state"), self.limits.tokens) } else if kind == b"outline" { - navigation.add_outline(operands, position, (position.page, graphics_step, 1), self.limits.tokens) + navigation.add_outline(operands, position, (position.page, graphics_step, 1), text.expect("outline text state"), self.limits.tokens) } else if kind == b"names" { navigation.add_names(operands, position, (position.page, graphics_step, 1), self.limits.tokens) } else { @@ -231,9 +232,20 @@ impl Executor { } } } + if let Some(operands) = body.and_then(|body| xdv_operand(body, b"tounicode")) { + let from = self.source_name(special.span); + self.reads.insert(Dependency::PdfCatalogState); + let warnings = self.xdv_text.apply(operands, &from, files); + self.check_cancellation()?; + for warning in warnings { + files.observe_diagnostic(WriteDestination::TerminalAndLog, &warning) + .map_err(|error| self.error(error, special.span))?; + } + return Ok(None); + } if let Some(dictionary) = body.and_then(|body| xdv_operand(body, b"docinfo")) { use crate::pdf_device::xdv_document::merge_docinfo; - let (entries, warnings) = merge_docinfo(&self.state.pdf_info, dictionary) + let (entries, warnings) = merge_docinfo(&self.state.pdf_info, dictionary, &self.xdv_text) .map_err(|error| self.error(error, special.span))?; if entries.len() > self.limits.tokens { return self.fail("native PDF information payload limit exceeded"); diff --git a/crates/texrra-tex-core/src/execution/engine/xdv_annotation.rs b/crates/texrra-tex-core/src/execution/engine/xdv_annotation.rs index d94ff0e..5beb8a6 100644 --- a/crates/texrra-tex-core/src/execution/engine/xdv_annotation.rs +++ b/crates/texrra-tex-core/src/execution/engine/xdv_annotation.rs @@ -7,6 +7,7 @@ use crate::{ pdf_device::{ Affine, PdfGraphics, xdv_annotation::{Annotation, Bounds, Command, Page}, + xdv_document::TextEncoding, xdv_object::Position, }, }; @@ -16,7 +17,7 @@ impl Executor { pub(super) fn ship_xdv_annotations( &mut self, shipout: &NativeShipout, - commands: &BTreeMap, + commands: &BTreeMap, files: &mut impl SourceProvider, ) -> Result, Error> { let mut state = self.xdv_annotations.clone(); @@ -55,8 +56,8 @@ impl Executor { BoxPaint::PdfGraphics => { let step = graphics; graphics += 1; - if let Some(&index) = commands.get(&step) { - let special = &shipout.specials[index]; + if let Some((index, text)) = commands.get(&step) { + let special = &shipout.specials[*index]; span = special.span; let (command, operands) = Command::recognize(&special.bytes).expect("annotation special"); @@ -76,6 +77,7 @@ impl Executor { frame.transform, position, (page_number, step, 1), + text, ) .and_then(|warnings| { for warning in warnings { diff --git a/crates/texrra-tex-core/src/native_font.rs b/crates/texrra-tex-core/src/native_font.rs index 09fa0ce..f419da0 100644 --- a/crates/texrra-tex-core/src/native_font.rs +++ b/crates/texrra-tex-core/src/native_font.rs @@ -43,11 +43,19 @@ pub struct NativeFontPaint { pub(crate) xdv_widths: BTreeMap, #[serde(default, skip_serializing_if = "XdvFontMatrix::is_identity")] pub(crate) xdv_matrix: XdvFontMatrix, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) xdv_unicode: Option>, pub resources: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] program_index: Option, } +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub(crate) struct XdvFontUnicode { + pub(crate) texts: BTreeMap, + resources: Vec, +} + struct MappedOutline { data: Arc<[u8]>, encoding: Option>, @@ -253,7 +261,7 @@ fn actual_resource( let resource = files.resource(kind, name, from)?; verify_resource(resource, kind, name) } -fn verify_resource( +pub(crate) fn verify_resource( resource: crate::resources::LoadedResource, kind: crate::resources::ResourceKind, name: &str, @@ -439,6 +447,59 @@ pub fn resolve_native_fonts( ) -> Result<(), String> { NativeFontCache::default().resolve(pages, files) } +fn resolve_xdv_unicode( + pages: &[crate::render::DisplayList], + resolved: &mut BTreeMap>, + bindings: &PdfFontBindings, + files: &mut impl crate::execution::SourceProvider, +) -> Result<(), String> { + use crate::render::DisplayItem; + let used: BTreeMap<_, _> = pages.iter().flat_map(|page| &page.items).filter_map(|item| { + match item { + DisplayItem::NativeGlyph { font, .. } => Some((font.id, &font.name)), + _ => None, + } + }).collect(); + let mut maps = std::collections::HashMap::new(); + let mut owners: std::collections::HashMap<_, Option>> = std::collections::HashMap::new(); + for (id, font_name) in used { + let paint = resolved.get_mut(&id).expect("resolved device font"); + // The PDF writer shares one Type 1 resource and encoding among all + // sizes and aliases of the same physical program. + let owner_key = paint.xdv_descriptor.and_then(|_| paint.type1_program_key()) + .map(|(version, transform)| (version.clone(), transform, paint.encoding_version().cloned())); + let texts = if let Some(texts) = owner_key.as_ref().and_then(|key| owners.get(key)) { + texts.clone() + } else { + let texts = if let Some(entry) = bindings.xdv_unicode.get(font_name) { + let name = entry.xdv_to_unicode.as_deref().expect("explicit XDV font CMap"); + let key = (&entry.from, name, &entry.version); + let map = match maps.entry(key) { + std::collections::hash_map::Entry::Occupied(existing) => existing.into_mut(), + std::collections::hash_map::Entry::Vacant(vacant) => { + let from = entry.from.to_string_lossy(); + let map = crate::pdf_device::cmap::CMap::load(name, &from, files)?; + let texts = map.simple_unicode(); + let resources = entry.version.iter().cloned().chain(map.resources).collect(); + vacant.insert(Arc::new(XdvFontUnicode { texts, resources })) + } + }; + Some(map.clone()) + } else { + None + }; + if let Some(key) = owner_key { + owners.insert(key, texts.clone()); + } + texts + }; + if texts.is_some() { + Arc::make_mut(paint).xdv_unicode = texts; + } + } + Ok(()) +} + fn resolve_physical_fonts( pages: &mut [crate::render::DisplayList], files: &mut impl crate::execution::SourceProvider, @@ -558,6 +619,7 @@ fn resolve_physical_fonts( xdv_descriptor: None, xdv_widths: BTreeMap::new(), xdv_matrix: Default::default(), + xdv_unicode: None, resources: entry.as_ref().and_then(|entry| entry.version.as_ref()) .or(default_version).cloned().into_iter() .chain(std::iter::once(resource.version)).collect(), @@ -640,6 +702,7 @@ fn resolve_physical_fonts( }, xdv_widths: BTreeMap::new(), xdv_matrix: matrix, + xdv_unicode: None, resources, program_index, }, @@ -677,6 +740,9 @@ fn resolve_physical_fonts( .map(|(id, key)| (id, cache[&key].clone())) .collect(); resolved.extend(direct_resolved); + if xdv && let Some(bindings) = captured && !bindings.xdv_unicode.is_empty() { + resolve_xdv_unicode(pages, &mut resolved, bindings, files)?; + } for page in pages { for item in &mut page.items { if let DisplayItem::NativeGlyph { @@ -688,7 +754,8 @@ fn resolve_physical_fonts( } = item { let p = resolved[&font.id].clone(); - *character = match &p.program { + *character = p.xdv_unicode.as_ref().and_then(|map| map.texts.get(slot)) + .and_then(|text| text.chars().next()).unwrap_or_else(|| match &p.program { NativeFontProgram::Type1(_) | NativeFontProgram::DeviceType1(_) | NativeFontProgram::TrueType(_) @@ -698,7 +765,7 @@ fn resolve_physical_fonts( .unwrap_or('�') } NativeFontProgram::Pk(_) => '�', - }; + }); *paint = Some(p); } } diff --git a/crates/texrra-tex-core/src/native_font/cff.rs b/crates/texrra-tex-core/src/native_font/cff.rs index 2da03d6..82c12e6 100644 --- a/crates/texrra-tex-core/src/native_font/cff.rs +++ b/crates/texrra-tex-core/src/native_font/cff.rs @@ -134,6 +134,7 @@ pub(super) fn resolve( xdv_descriptor: None, xdv_widths: BTreeMap::new(), xdv_matrix: Default::default(), + xdv_unicode: None, resources, program_index: Some(program_index), }) diff --git a/crates/texrra-tex-core/src/native_font/device_type1.rs b/crates/texrra-tex-core/src/native_font/device_type1.rs index f67afe3..ae0d945 100644 --- a/crates/texrra-tex-core/src/native_font/device_type1.rs +++ b/crates/texrra-tex-core/src/native_font/device_type1.rs @@ -141,6 +141,7 @@ pub(super) fn resolve( xdv_descriptor: None, xdv_widths: BTreeMap::new(), xdv_matrix: Default::default(), + xdv_unicode: None, resources, program_index: None, }) diff --git a/crates/texrra-tex-core/src/native_font/map.rs b/crates/texrra-tex-core/src/native_font/map.rs index a98ebfd..c02d187 100644 --- a/crates/texrra-tex-core/src/native_font/map.rs +++ b/crates/texrra-tex-core/src/native_font/map.rs @@ -32,6 +32,8 @@ pub(super) struct MapEntry { pub transform: Type1Transform, #[serde(default, skip_serializing_if = "XdvFontMatrix::is_identity")] xdv_matrix: XdvFontMatrix, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(super) xdv_to_unicode: Option, } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)] @@ -94,6 +96,7 @@ impl MapEntry { transform: Type1Transform::default(), subset: false, xdv_matrix: XdvFontMatrix::default(), + xdv_to_unicode: None, } } @@ -377,6 +380,11 @@ fn parse_xdv_map_line( while let Some(option) = words.next() { match option { "-r" => {}, // Obsolete remapping option in the reference driver. + "-u" => { + let name = words.next().filter(|value| !value.starts_with('-')) + .ok_or_else(|| format!("missing XDV map ToUnicode name for {name}"))?; + entry.xdv_to_unicode = Some(name.into()); + } "-s" | "-e" => { let number = words.next().and_then(|word| word.parse::().ok()) .filter(|value| value.is_finite()) @@ -402,6 +410,9 @@ fn parse_xdv_map_line( pub struct PdfFontBindings { fonts: BTreeMap>>, pub(super) default_map: Option, + // The PDF device looks up explicit ToUnicode overrides when the font closes. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub(super) xdv_unicode: BTreeMap>, } impl PdfFontBindings { @@ -842,6 +853,17 @@ impl JobFontMap { Arc::make_mut(&mut self.tables.postscript).remove(&key); } let entry = Arc::new(entry); + if self.xdv_loaded.is_some() + && let Some(bindings) = &mut self.bindings + && (entry.xdv_to_unicode.is_some() || bindings.xdv_unicode.contains_key(&name)) + { + let unicode = &mut Arc::make_mut(bindings).xdv_unicode; + if mode != MapMode::Delete && entry.xdv_to_unicode.is_some() { + unicode.insert(name.clone(), entry.clone()); + } else { + unicode.remove(&name); + } + } if mode == MapMode::Delete { Arc::make_mut(&mut self.tables.entries).remove(&name); } else { @@ -950,5 +972,6 @@ pub(super) fn dedicated_space_map(font: &NativeFont) -> MapEntry { transform: Type1Transform::default(), subset: false, xdv_matrix: XdvFontMatrix::default(), + xdv_to_unicode: None, } } diff --git a/crates/texrra-tex-core/src/native_font/truetype.rs b/crates/texrra-tex-core/src/native_font/truetype.rs index d8d8312..527debf 100644 --- a/crates/texrra-tex-core/src/native_font/truetype.rs +++ b/crates/texrra-tex-core/src/native_font/truetype.rs @@ -226,6 +226,7 @@ pub(super) fn resolve( xdv_descriptor: None, xdv_widths: BTreeMap::new(), xdv_matrix: Default::default(), + xdv_unicode: None, resources, program_index: Some(program_index), }) diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index c173ba0..fa77175 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -2026,7 +2026,9 @@ fn write_native_font( NativeFontProgram::Pk(_) => unreachable!(), }; let unicode = objects.len() + 1; - let cmap = if !has_glyph_unicode { + let cmap = if let Some(texts) = &paint.xdv_unicode { + Some(type1_tounicode_texts(&texts.texts)) + } else if !has_glyph_unicode { None } else if xdv_type1 { let names = options.and_then(|options| options.xdv_glyph_names); diff --git a/crates/texrra-tex-core/src/pdf_device.rs b/crates/texrra-tex-core/src/pdf_device.rs index fa60dca..8a06e7d 100644 --- a/crates/texrra-tex-core/src/pdf_device.rs +++ b/crates/texrra-tex-core/src/pdf_device.rs @@ -118,6 +118,7 @@ pub fn print_sp(value: i64, digits: u8) -> String { ) } } +pub(crate) mod cmap; mod color; pub(crate) mod xdv_annotation; pub(crate) mod xdv_color; diff --git a/crates/texrra-tex-core/src/pdf_device/cmap.rs b/crates/texrra-tex-core/src/pdf_device/cmap.rs new file mode 100644 index 0000000..bb94da1 --- /dev/null +++ b/crates/texrra-tex-core/src/pdf_device/cmap.rs @@ -0,0 +1,306 @@ +//! Character-code maps read from actual CMap resources. +use std::{collections::BTreeMap, sync::Arc}; + +use super::xdv_object::{split_string, trim_pdf}; +use crate::{ + execution::SourceProvider, + resources::{ResourceKind, ResourceVersion}, +}; + +const MAX_CMAP_DEPTH: usize = 16; +const MAX_CMAP_BYTES: usize = 16 * 1024 * 1024; + +#[derive(Debug)] +pub(crate) struct CMap { + codespaces: [Vec<[u32; 2]>; 4], + mappings: [BTreeMap; 4], + inherited: Option>, + pub(crate) resources: Vec, +} + +#[derive(Debug)] +struct Mapping { + last: u32, + destination: Destination, +} + +#[derive(Debug)] +enum Destination { + Sequential(Vec), + Explicit(Vec>), +} + +impl CMap { + pub(crate) fn load( + name: &str, + from: &str, + files: &mut impl SourceProvider, + ) -> Result { + Self::load_inner(name, from, files, &mut Vec::new()) + } + + fn load_inner( + name: &str, + from: &str, + files: &mut impl SourceProvider, + stack: &mut Vec, + ) -> Result { + let resource = files + .optional_font_file(ResourceKind::CMap, name, from)? + .ok_or_else(|| format!("CMap {name} was not found"))?; + let resource = crate::native_font::verify_resource(resource, ResourceKind::CMap, name)?; + if stack.len() == MAX_CMAP_DEPTH || stack.iter().any(|v| v.path == resource.version.path) { + return Err(format!("invalid CMap inheritance for {name}")); + } + if resource.data.len() > MAX_CMAP_BYTES { + return Err(format!("CMap {name} exceeds the input limit")); + } + stack.push(resource.version.clone()); + let (mut map, base) = + Self::parse(&resource.data).map_err(|error| format!("{name}: {error}"))?; + map.resources.push(resource.version.clone()); + if let Some(base) = base { + let inherited = Self::load_inner( + &base, + &resource.version.path.to_string_lossy(), + files, + stack, + )?; + map.resources.extend(inherited.resources.iter().cloned()); + map.inherited = Some(Arc::new(inherited)); + } + stack.pop(); + if map.codespaces.iter().all(Vec::is_empty) && map.inherited.is_none() { + return Err(format!("CMap {name} has no code space")); + } + Ok(map) + } + + fn parse(data: &[u8]) -> Result<(Self, Option), String> { + let mut lexer = Lexer(data); + let mut map = Self { + codespaces: Default::default(), + mappings: Default::default(), + inherited: None, + resources: Vec::new(), + }; + let mut previous = &[][..]; + let mut inherits = None; + let mut ended = false; + while let Some(token) = lexer.next()? { + let end = match token { + b"begincodespacerange" => b"endcodespacerange".as_slice(), + b"beginbfchar" => b"endbfchar", + b"beginbfrange" => b"endbfrange", + b"usecmap" => { + let name = previous + .strip_prefix(b"/") + .filter(|name| !name.is_empty()) + .ok_or("missing CMap base name")?; + if inherits.is_some() { + return Err("more than one CMap base".into()); + } + inherits = Some( + std::str::from_utf8(name) + .map_err(|_| "invalid CMap base name")? + .into(), + ); + previous = token; + continue; + } + b"endcmap" => { + ended = true; + break; + } + _ => { + previous = token; + continue; + } + }; + let count = std::str::from_utf8(previous) + .ok() + .and_then(|n| n.parse::().ok()) + .filter(|&n| n <= data.len()) + .ok_or("invalid CMap block count")?; + for _ in 0..count { + let (width, first) = read_code(lexer.required()?)?; + let last = if token == b"beginbfchar" { + first + } else { + let (end_width, last) = read_code(lexer.required()?)?; + if width != end_width || last < first { + return Err("invalid CMap source range".into()); + } + last + }; + if token == b"begincodespacerange" { + map.codespaces[width - 1].push([first, last]); + continue; + } + let value = lexer.required()?; + let destination = if value == b"[" && token == b"beginbfrange" { + let len = u64::from(last) - u64::from(first) + 1; + if len > data.len() as u64 { + return Err("invalid CMap array range".into()); + } + let values = (0..len) + .map(|_| read_hex(lexer.required()?)) + .collect::>()?; + if lexer.required()? != b"]" { + return Err("invalid CMap range array".into()); + } + Destination::Explicit(values) + } else { + Destination::Sequential(read_hex(value)?) + }; + map.mappings[width - 1].insert(first, Mapping { last, destination }); + } + if lexer.required()? != end { + return Err("incorrect CMap block length".into()); + } + previous = &[]; + } + if !ended { + return Err("missing CMap end marker".into()); + } + Ok((map, inherits)) + } + + fn lookup(&self, width: usize, code: u32) -> Option> { + if let Some((&first, mapping)) = self.mappings[width - 1].range(..=code).next_back() + && code <= mapping.last + { + let offset = code - first; + return match &mapping.destination { + Destination::Explicit(values) => values.get(offset as usize).cloned(), + Destination::Sequential(value) => { + let mut carry = u64::from(offset); + let mut bytes = value.clone(); + for byte in bytes.iter_mut().rev() { + if carry == 0 { + break; + } + carry += u64::from(*byte); + *byte = carry as u8; + carry >>= 8; + } + (carry == 0).then_some(bytes) + } + }; + } + self.inherited.as_ref()?.lookup(width, code) + } + + fn in_codespace(&self, width: usize, code: u32) -> bool { + self.codespaces[width - 1] + .iter() + .any(|&[lo, hi]| (lo..=hi).contains(&code)) + || self + .inherited + .as_ref() + .is_some_and(|base| base.in_codespace(width, code)) + } + + pub(crate) fn to_utf16(&self, mut input: &[u8]) -> Result, String> { + let mut output = Vec::with_capacity(2 + input.len()); + output.extend_from_slice(&[0xfe, 0xff]); + while !input.is_empty() { + let mut code = 0; + let mut consumed = 1; + let mut decoded = None; + for (index, &byte) in input.iter().take(4).enumerate() { + code = (code << 8) | u32::from(byte); + let width = index + 1; + if self.in_codespace(width, code) { + consumed = width; + decoded = self.lookup(width, code); + break; + } + } + let bytes = decoded.as_deref().unwrap_or(&[0xff, 0xfd]); + if output.len().saturating_add(bytes.len()) > MAX_CMAP_BYTES { + return Err("CMap output exceeds the text limit".into()); + } + output.extend_from_slice(bytes); + input = &input[consumed..]; + } + Ok(output) + } + + pub(crate) fn simple_unicode(&self) -> BTreeMap { + (0..=255) + .filter_map(|slot| { + let bytes = self.lookup(1, u32::from(slot))?; + if bytes.is_empty() || bytes.len() % 2 != 0 { + return None; + } + let units: Vec<_> = bytes + .chunks_exact(2) + .map(|pair| u16::from_be_bytes([pair[0], pair[1]])) + .collect(); + Some((slot, String::from_utf16(&units).ok()?)) + }) + .collect() + } +} + +fn read_hex(token: &[u8]) -> Result, String> { + let digits = token + .strip_prefix(b"<") + .and_then(|s| s.strip_suffix(b">")) + .ok_or("expected a CMap hexadecimal string")?; + let nibbles = digits + .iter() + .filter(|b| !b.is_ascii_whitespace()) + .map(|&b| { + char::from(b) + .to_digit(16) + .map(|n| n as u8) + .ok_or("invalid CMap hexadecimal digit") + }) + .collect::, _>>()?; + Ok(nibbles + .chunks(2) + .map(|pair| (pair[0] << 4) | pair.get(1).copied().unwrap_or(0)) + .collect()) +} + +fn read_code(token: &[u8]) -> Result<(usize, u32), String> { + let code = read_hex(token)?; + if !(1..=4).contains(&code.len()) { + return Err("invalid CMap code length".into()); + } + Ok(( + code.len(), + code.iter().fold(0, |n, &b| (n << 8) | u32::from(b)), + )) +} + +struct Lexer<'a>(&'a [u8]); + +impl<'a> Lexer<'a> { + fn required(&mut self) -> Result<&'a [u8], String> { + self.next()?.ok_or_else(|| "unexpected end of CMap".into()) + } + + fn next(&mut self) -> Result, String> { + let input = trim_pdf(self.0); + let token = match input { + [] => return Ok(None), + [b'<', b'<', ..] | [b'>', b'>', ..] => &input[..2], + [b'<' | b'(', ..] => split_string(input)?.0, + [b'[' | b']' | b'{' | b'}' | b')' | b'>', ..] => &input[..1], + _ => { + let end = input + .iter() + .enumerate() + .skip(1) + .find(|(_, b)| b.is_ascii_whitespace() || b"[]{}()<>/%".contains(b)) + .map_or(input.len(), |(i, _)| i); + &input[..end] + } + }; + self.0 = &input[token.len()..]; + Ok(Some(token)) + } +} diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_annotation.rs b/crates/texrra-tex-core/src/pdf_device/xdv_annotation.rs index 02f26a6..6638896 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_annotation.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_annotation.rs @@ -3,7 +3,7 @@ use std::{collections::BTreeMap, sync::Arc}; use lopdf::Object; -use super::xdv_navigation::read_fields; +use super::{xdv_document::TextEncoding, xdv_navigation::read_fields}; use super::xdv_object::{ Dictionary, Position, References, atom, encode_device_value, output_with_destination, target_name, trim_pdf, }; @@ -153,6 +153,7 @@ impl Page<'_> { transform: Affine, position: Position, order: Order, + text: &TextEncoding, ) -> Result, String> { match command { Command::Begin => { @@ -162,7 +163,7 @@ impl Page<'_> { .into(), ]); } - let (fields, warnings) = read_fields(operands, position)?; + let (fields, warnings) = read_fields(operands, position, text)?; self.state.active = Some(Active { fields: Arc::new(fields), depth: self.depth, @@ -192,7 +193,7 @@ impl Page<'_> { self.expand(bounds); return Ok(Vec::new()); } - let (fields, warnings) = read_fields(&operands[dictionary..], position)?; + let (fields, warnings) = read_fields(&operands[dictionary..], position, text)?; self.annotations.push(Annotation { order, fields: Arc::new(fields), diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_document.rs b/crates/texrra-tex-core/src/pdf_device/xdv_document.rs index 9b1d2b0..5c29945 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_document.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_document.rs @@ -1,9 +1,14 @@ //! Document dictionary specials executed in XDV page order. use lopdf::{Object, StringFormat}; +use std::{collections::{BTreeMap, BTreeSet}, sync::Arc}; +use crate::execution::SourceProvider; use super::{ PdfInfo, + cmap::CMap, page_resources::{encode_value, parse_entries, parse_value}, + xdv_object::{Position, References, atom, output_dictionary, trim_pdf}, + xdv_navigation::read_fields, }; const TEXT_KEYS: &[&[u8]] = &[ @@ -31,19 +36,102 @@ const INFO_STRING_KEYS: &[&[u8]] = &[ b"ModDate", ]; +#[derive(Clone, Default)] +pub(crate) struct TextEncoding { + map: Option>, + extra_keys: Arc>>, + pub(super) tainted_literals: bool, +} + +impl TextEncoding { + pub(crate) fn apply( + &mut self, operands: &[u8], from: &str, files: &mut impl SourceProvider, + ) -> Vec { + self.map = None; + self.tainted_literals = false; + let (name, rest) = atom(operands); + let Ok(name) = std::str::from_utf8(name) else { + return vec![warning("Invalid ToUnicode mapping name.")]; + }; + if name.is_empty() { + return vec![warning("Missing CMap name for pdf:tounicode.")]; + } + match CMap::load(name, from, files) { + Ok(map) => { + self.tainted_literals = ["RKSJ", "B5", "GBK", "KSC"].iter().any(|tag| name.contains(tag)); + self.map = Some(Arc::new(map)); + } + Err(error) => return vec![warning(&format!("Failed to load ToUnicode mapping: {name} ({error})"))], + } + let mut warnings = Vec::new(); + if !trim_pdf(rest).is_empty() { + match parse_value(rest) { + Ok(Object::Array(keys)) => { + for key in keys { + if let Object::Name(key) = key { + Arc::make_mut(&mut self.extra_keys).insert(key); + } else { + warnings.push(warning("Invalid argument specified in pdf:tounicode special.")); + } + } + } + _ => warnings.push(warning("Invalid argument specified in pdf:tounicode special.")), + } + } + warnings + } + + pub(super) fn normalize(&self, key: &[u8], bytes: &mut Vec, warnings: &mut Vec) -> bool { + if (!TEXT_KEYS.contains(&key) && !self.extra_keys.contains(key)) || bytes.starts_with(&[0xfe, 0xff]) { + return false; + } + let result = if let Some(map) = &self.map { + map.to_utf16(bytes).ok() + } else if bytes.is_ascii() { + return false; + } else { + std::str::from_utf8(bytes).ok().map(|text| [0xfe, 0xff] + .into_iter().chain(text.encode_utf16().flat_map(u16::to_be_bytes)).collect()) + }; + if let Some(result) = result { + *bytes = result; + true + } else { + warnings.push(warning(&format!( + "Input string conversion (to UTF16BE) failed for {}...", String::from_utf8_lossy(key), + ))); + false + } + } +} + +fn warning(message: &str) -> String { + format!("xdvipdfmx: warning: {message}\n") +} + pub(crate) fn merge_docinfo( current: &[u8], special: &[u8], + text: &TextEncoding, ) -> Result<(Vec, Vec), String> { - let Object::Dictionary(additions) = parse_value(special)? else { - return Err("pdf:docinfo requires a PDF dictionary".into()); + let (additions, warnings) = if text.tainted_literals { + let position = Position { page: 0, coordinates: [0, 0], height: 0, magnification: 1000 }; + let (fields, warnings) = read_fields(special, position, text)?; + let refs = References { pages: &[], named: &BTreeMap::new() }; + (output_dictionary(&fields, &refs)?, warnings) + } else { + let Object::Dictionary(mut additions) = parse_value(special)? else { + return Err("pdf:docinfo requires a PDF dictionary".into()); + }; + let mut warnings = Vec::new(); + for (key, value) in additions.iter_mut() { + convert_text(key, value, text, &mut warnings)?; + } + (additions, warnings) }; let mut document = parse_entries(current)?; - let mut warnings = Vec::new(); for (key, value) in &additions { - let mut value = value.clone(); - convert_text(key, &mut value, &mut warnings)?; - document.set(key.clone(), value); + document.set(key.clone(), value.clone()); } let encoded = encode_value(Object::Dictionary(document))?; @@ -55,21 +143,23 @@ pub(crate) fn merge_docinfo( Ok((entries.to_vec(), warnings)) } -fn convert_text(key: &[u8], value: &mut Object, warnings: &mut Vec) -> Result<(), String> { +fn convert_text( + key: &[u8], value: &mut Object, text: &TextEncoding, warnings: &mut Vec, +) -> Result<(), String> { match value { Object::String(bytes, format) => { - if normalize_text(key, bytes, warnings) { + if text.normalize(key, bytes, warnings) { *format = StringFormat::Hexadecimal; } } Object::Array(values) => { for value in values { - convert_text(key, value, warnings)?; + convert_text(key, value, text, warnings)?; } } Object::Dictionary(entries) => { for (key, value) in entries.iter_mut() { - convert_text(key, value, warnings)?; + convert_text(key, value, text, warnings)?; } } Object::Reference(_) => { @@ -80,25 +170,6 @@ fn convert_text(key: &[u8], value: &mut Object, warnings: &mut Vec) -> R Ok(()) } -pub(super) fn normalize_text(key: &[u8], bytes: &mut Vec, warnings: &mut Vec) -> bool { - if !TEXT_KEYS.contains(&key) || bytes.starts_with(&[0xfe, 0xff]) || bytes.is_ascii() { - return false; - } - if let Ok(text) = std::str::from_utf8(bytes) { - *bytes = [0xfe, 0xff] - .into_iter() - .chain(text.encode_utf16().flat_map(u16::to_be_bytes)) - .collect(); - true - } else { - warnings.push(format!( - "xdvipdfmx: warning: Input string conversion (to UTF16BE) failed for {}...\n", - String::from_utf8_lossy(key), - )); - false - } -} - pub(crate) fn information_dictionary( info: PdfInfo<'_>, diagnostics: &mut Vec, diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs b/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs index d6985cf..74dee41 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs @@ -5,9 +5,9 @@ use lopdf::Object; use serde::{Deserialize, Serialize}; use super::page_resources::parse_value; -use super::xdv_annotation::Order; +use super::{xdv_annotation::Order, xdv_document::TextEncoding}; use super::xdv_object::{ - Dictionary, Position, References, Value, atom, dictionary, encode_device_value, output_dictionary, + Dictionary, Position, References, Value, atom, dictionary, dictionary_with_text, encode_device_value, output_dictionary, output_with_destination, target_name, trim_pdf, }; @@ -57,9 +57,10 @@ impl Navigation { &mut self, bytes: &[u8], position: Position, + text: &TextEncoding, limit: usize, ) -> Result, String> { - let (mut additions, warnings) = read_fields(bytes, position)?; + let (mut additions, warnings) = read_fields(bytes, position, text)?; if let (Some(Value::Dictionary(old)), Some(Value::Dictionary(new))) = ( self.catalog.get_mut(b"ViewerPreferences".as_slice()), additions.get_mut(b"ViewerPreferences".as_slice()), @@ -77,6 +78,7 @@ impl Navigation { bytes: &[u8], position: Position, order: Order, + text: &TextEncoding, limit: usize, ) -> Result, String> { let (force_open, rest) = match trim_pdf(bytes) { @@ -97,7 +99,7 @@ impl Navigation { if depth > 256 || depth as usize > previous_depth + 1 { return Err("XDV outline jumps more than one level or exceeds depth limit".into()); } - let (fields, warnings) = read_fields(rest, position)?; + let (fields, warnings) = read_fields(rest, position, text)?; self.add_payload(bytes.len(), limit)?; self.lowest_level = Some(lowest); self.outlines.push(Outline { @@ -356,11 +358,12 @@ struct OutlineLinks { pub(super) fn read_fields( bytes: &[u8], position: Position, + text: &TextEncoding, ) -> Result<(Dictionary, Vec), String> { - let mut fields = dictionary(bytes, position)?; + let mut fields = dictionary_with_text(bytes, position, text.tainted_literals)?; let mut warnings = Vec::new(); for (key, value) in &mut fields { - value.normalize_text(key, &mut warnings); + value.normalize_text(key, text, &mut warnings); } Ok((fields, warnings)) } diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_object.rs b/crates/texrra-tex-core/src/pdf_device/xdv_object.rs index 3182fa4..2ca7bc4 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_object.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_object.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; use std::{collections::BTreeMap, io::Write as _}; use super::page_resources::{encode_value, parse_name, parse_value}; -use super::{magnify, print_sp}; +use super::{magnify, print_sp, xdv_document::TextEncoding}; pub(super) fn trim_pdf(mut bytes: &[u8]) -> &[u8] { loop { @@ -152,9 +152,19 @@ impl Position { } pub(super) fn dictionary(input: &[u8], position: Position) -> Result { - let Value::Dictionary(dictionary) = parse_object(input, position)? else { + dictionary_with_text(input, position, false) +} + +pub(super) fn dictionary_with_text( + input: &[u8], position: Position, tainted: bool, +) -> Result { + let mut parser = Parser { rest: input, position, tainted }; + let Value::Dictionary(dictionary) = parser.value(0)? else { return Err("expected an XDV PDF dictionary".into()); }; + if !trim_pdf(parser.rest).is_empty() { + return Err("unexpected material after XDV PDF object".into()); + } Ok(dictionary) } @@ -167,7 +177,7 @@ pub(super) fn parse_object(bytes: &[u8], position: Position) -> Result Result<(Value, &[u8]), String> { - let mut parser = Parser { rest: bytes, position }; + let mut parser = Parser { rest: bytes, position, tainted: false }; let value = parser.value(0)?; Ok((value, trim_pdf(parser.rest))) } @@ -175,6 +185,7 @@ pub(super) fn parse_object_prefix(bytes: &[u8], position: Position) -> Result<(V struct Parser<'a> { rest: &'a [u8], position: Position, + tainted: bool, } impl Parser<'_> { @@ -217,6 +228,11 @@ impl Parser<'_> { self.rest = rest; return self.position.reference(token); } + if self.tainted && self.rest.starts_with(b"(") { + let (value, rest) = tainted_literal(self.rest)?; + self.rest = rest; + return Ok(Value::String(value)); + } let (token, rest) = match self.rest.first() { Some(b'(' | b'<') => split_string(self.rest)?, Some(_) => atom(self.rest), @@ -235,6 +251,61 @@ impl Parser<'_> { } } +fn tainted_literal(input: &[u8]) -> Result<(Vec, &[u8]), String> { + let mut rest = &input[1..]; + let mut output = Vec::new(); + let mut depth = 0; + while let Some((&byte, tail)) = rest.split_first() { + rest = tail; + if byte == b')' && depth == 0 { + return Ok((output, rest)); + } + if byte >= 0x80 && let Some((&second, tail)) = rest.split_first() { + output.extend_from_slice(&[byte, second]); + rest = tail; + continue; + } + match byte { + b'(' => { depth += 1; output.push(byte); } + b')' => { depth -= 1; output.push(byte); } + b'\r' | b'\n' => { + if byte == b'\r' { + rest = rest.strip_prefix(b"\n").unwrap_or(rest); + } + output.push(b'\n'); + } + b'\\' => { + let (&escaped, tail) = rest.split_first().ok_or("unfinished PDF string escape")?; + rest = tail; + match escaped { + b'\r' | b'\n' => { + if escaped == b'\r' { + rest = rest.strip_prefix(b"\n").unwrap_or(rest); + } + } + b'n' => output.push(b'\n'), + b'r' => output.push(b'\r'), + b't' => output.push(b'\t'), + b'b' => output.push(8), + b'f' => output.push(12), + b'0'..=b'7' => { + let mut code = escaped - b'0'; + for _ in 0..2 { + let Some((&digit @ b'0'..=b'7', tail)) = rest.split_first() else { break }; + rest = tail; + code = code.wrapping_mul(8) + (digit - b'0'); + } + output.push(code); + } + _ => output.push(escaped), + } + } + _ => output.push(byte), + } + } + Err("unterminated PDF literal string".into()) +} + pub(crate) struct References<'a> { pub(crate) pages: &'a [usize], pub(crate) named: &'a BTreeMap, u32>, @@ -305,19 +376,21 @@ impl Value { } } - pub(super) fn normalize_text(&mut self, key: &[u8], warnings: &mut Vec) { + pub(super) fn normalize_text( + &mut self, key: &[u8], text: &TextEncoding, warnings: &mut Vec, + ) { match self { Self::String(bytes) => { - super::xdv_document::normalize_text(key, bytes, warnings); + text.normalize(key, bytes, warnings); } Self::Array(values) => { for value in values { - value.normalize_text(key, warnings); + value.normalize_text(key, text, warnings); } } Self::Dictionary(values) => { for (key, value) in values { - value.normalize_text(key, warnings); + value.normalize_text(key, text, warnings); } } _ => {} diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index 06605fc..e70e194 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -168,6 +168,7 @@ struct NativeSvgGlyph<'a> { slot: u8, font: &'a str, glyph: &'a str, + unicode: Option<&'a str>, path: &'a str, scalable: bool, } @@ -209,6 +210,7 @@ impl DisplayItem { slot: *slot, font: paint.program.name(), glyph: &paint.encoding[usize::from(*slot)], + unicode: paint.xdv_unicode.as_ref().and_then(|map| map.texts.get(slot)).map(String::as_str), path, scalable: !matches!( paint.program, @@ -555,6 +557,7 @@ impl DisplayList { slot, font, glyph, + unicode, path, scalable, } = item @@ -569,11 +572,13 @@ impl DisplayList { } else { scale * f64::from(1000 + expansion) / 1000.0 }; - let label = if scalable { - crate::type1::glyph_unicode_text(glyph).unwrap_or_default() - } else { - String::new() - }; + let label = unicode.map(std::borrow::Cow::Borrowed).unwrap_or_else(|| { + std::borrow::Cow::Owned(if scalable { + crate::type1::glyph_unicode_text(glyph).unwrap_or_default() + } else { + String::new() + }) + }); use std::fmt::Write as _; write!( out, diff --git a/crates/texrra-tex-core/src/resources.rs b/crates/texrra-tex-core/src/resources.rs index 0122ee7..8ce738e 100644 --- a/crates/texrra-tex-core/src/resources.rs +++ b/crates/texrra-tex-core/src/resources.rs @@ -36,6 +36,7 @@ pub enum ResourceKind { FontMapping, PdfImage, Sfd, + CMap, } impl ResourceKind { fn directory(self) -> &'static str { @@ -52,6 +53,7 @@ impl ResourceKind { Self::Format | Self::Config => "web2c", Self::FontMapping => "fonts/misc", Self::Sfd => "fonts/sfd", + Self::CMap => "fonts/cmap", } } fn environment(self) -> &'static str { @@ -69,6 +71,7 @@ impl ResourceKind { Self::Config => "TEXMFCNF", Self::FontMapping => "MISCFONTS", Self::Sfd => "SFDFONTS", + Self::CMap => "CMAPFONTS", } } fn extensions(self) -> &'static [&'static str] { @@ -86,9 +89,10 @@ impl ResourceKind { Self::Config => &["cnf"], Self::FontMapping => &["tec"], Self::Sfd => &["sfd"], + Self::CMap => &[], } } - const ALL: [Self; 13] = [ + const ALL: [Self; 14] = [ Self::Tex, Self::Tfm, Self::Vf, @@ -102,6 +106,7 @@ impl ResourceKind { Self::Config, Self::FontMapping, Self::Sfd, + Self::CMap, ]; } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] diff --git a/crates/texrra-tex-core/tests/execution_xetex_profile.rs b/crates/texrra-tex-core/tests/execution_xetex_profile.rs index 7f2fae4..56aab37 100644 --- a/crates/texrra-tex-core/tests/execution_xetex_profile.rs +++ b/crates/texrra-tex-core/tests/execution_xetex_profile.rs @@ -1329,3 +1329,75 @@ fn xdv_font_map_changes_apply_at_shipout_and_keep_loaded_programs() { assert_eq!(programs, [vec!["CMR10"], vec!["CMR10", "CMTI10"], vec!["CMR10"]]); assert!(pages[2].try_to_svg().unwrap().contains("matrix(0.01200000 0 0.00180000 -0.01000000")); } + +#[test] +fn xdv_text_mapping_uses_the_resource_active_at_each_shipped_special() { + use lopdf::Document; + use sha2::{Digest, Sha256}; + use texrra_tex_core::{ + pdf::shipout_lists_to_native_pdf_document, + resources::{LoadedResource, ResourceKind, ResourceVersion}, + }; + + struct Maps; + impl SourceProvider for Maps { + fn read(&mut self, name: &str, _: &str) -> Result { + Err(format!("unexpected input {name}")) + } + fn default_pk_resolution(&mut self) -> Result { + Ok(600) + } + fn optional_font_file( + &mut self, kind: ResourceKind, name: &str, _: &str, + ) -> Result, String> { + assert_eq!(kind, ResourceKind::CMap); + let data = match name { + "Base" => b"begincmap 1 begincodespacerange <00> endcodespacerange + 1 beginbfrange <41> <42> [<65e5> <672c>] endbfrange endcmap".to_vec(), + "Overlay" => b"begincmap /Base usecmap + 1 beginbfchar <42> <570b> endbfchar endcmap".to_vec(), + _ => return Ok(None), + }; + let version = ResourceVersion { + path: name.into(), + bytes: data.len() as u64, + sha256: format!("{:x}", Sha256::digest(&data)), + }; + Ok(Some(LoadedResource { version, data })) + } + } + + let state = State::initex().with_etex().with_input_profile(InputProfile::XeTeX); + let execution = Executor::new(state, Limits::default()).with_native_pages().run( + source(r"\catcode123=1 \catcode125=2 + \shipout\hbox{% + \special{pdf:tounicode Overlay [/Alt]}% + \special{pdf:outline 1 << /Title (AB) /Dest [@thispage /Fit] >>}% + \special{pdf:tounicode Base}% + \special{pdf:outline 1 << /Title (AB) /Dest [@thispage /Fit] >>}% + \special{pdf:docinfo << /Alt (AB) /Private (AB) /Title >>}% + \vrule width10pt height5pt} + \shipout\hbox{% + \special{pdf:tounicode Missing}% + \special{pdf:outline 1 << /Title (AB) /Dest [@thispage /Fit] >>}% + \vrule width10pt height5pt} + \end"), + &mut Maps, + ).unwrap(); + let pages = execution.shipout_display_lists().unwrap(); + let output = shipout_lists_to_native_pdf_document(&pages, execution.state.pdf_final_options()).unwrap(); + let pdf = Document::load_mem(&output.bytes).unwrap(); + let info = pdf.get_dictionary(pdf.trailer.get(b"Info").unwrap().as_reference().unwrap()).unwrap(); + assert_eq!(info.get(b"Title").unwrap().as_str().unwrap(), b"\xfe\xff\x03\xa9"); + assert_eq!(info.get(b"Alt").unwrap().as_str().unwrap(), b"\xfe\xff\x65\xe5\x67\x2c"); + assert_eq!(info.get(b"Private").unwrap().as_str().unwrap(), b"AB"); + let outlines = pdf.catalog().unwrap().get(b"Outlines").unwrap().as_reference().unwrap(); + let mut item = pdf.get_dictionary(outlines).unwrap().get(b"First").ok(); + let mut titles = Vec::new(); + while let Some(current) = item { + let node = pdf.get_dictionary(current.as_reference().unwrap()).unwrap(); + titles.push(node.get(b"Title").unwrap().as_str().unwrap()); + item = node.get(b"Next").ok(); + } + assert_eq!(titles, [b"\xfe\xff\x65\xe5\x57\x0b".as_slice(), b"\xfe\xff\x65\xe5\x67\x2c", b"AB"]); +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 111ac75..8275ace 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,38 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-28 XeLaTeX CMap 与 PDF Unicode 文本 + +`pdf:tounicode` 按实际出页顺序作用于标题、注释、书签和目录 +字段。它读取带版本的真实 CMap,支持多字节码空间、顺序和数组 +范围、`usecmap` 继承及显式文本键。原始 UTF-16BE 字符串和私有 +字段保持其字节。更换映射只影响随后的特指令,文档结束时的 +`-u` 映射供已嵌入的简单字体使用。那些字形继续来自实际字体, +PDF 提取和 SVG 文字标签使用同一映射。 +[参考文本转换](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/spc_pdfm.c) +[参考字体 ToUnicode](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/pdffont.c) + +原始 Adobe 90ms-RKSJ-UCS2、页内切换及跨页保留、上层映射覆盖、 +四字节 UTF-16 序列、缺失文档映射与简单字体晚绑定均有直接对照。 +标题、注释、书签目标、私有字段及字体提取与参考一致。三个 +设备作业和原样 article.cls、hyperref.sty 共八页,144 DPI 彩色 +逐像素相同。原样 article 的全文提取和 aux 也逐字节一致。 +开发构建和十四项 XDV 定向检查通过。 + +三页会话更换共享 CMap 时只更新第 2 页的文字标签,文档映射 +改动更新 PDF 并保留预览。四个成功修订各复用 65 步,PDF、 +测量页、SVG、来源映射和 aux 与独立全量一致。显式字体 CMap +缺失时会话保留上次发布结果。参考驱动对此发出警告并尝试后续 +映射,原生的对应恢复规则和同名字体映射自动发现仍待补齐。 + +回执在 `target/p3-xdv-unicode-mapping/receipt.json`, +SHA-256 为 `f33d8133bbac7f6b9e01968679fb625927de7c9b35901d71bb524bf483c5c3e7`。下一批接通旧 TFM 经 Unicode 或真实 +CMap 进入复合字体的字码、字形、PDF CID 资源和预览。 +`target/p3-xdv-composite-legacy` 样例已在参考端生成 +真实 NotoSans-Regular CID TrueType、Identity-H,提取为 ABC。 +原生当前报告复合编码缺口。完整出版矩阵和 100 ms 可见时延 +继续按既定门槛验收。 + ## 2026-11-28 XeLaTeX 出页字体映射与资源失效 `pdf:mapfile` 和 `pdf:mapline` 按实际出页顺序追加、替换、删除