Apply XeLaTeX CMaps to document text and embedded fonts
This commit is contained in:
1 parent
af6466cd98
commit
7d460e0fa1
20 files changed
+747
-65
No files matched your search
@@ -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_links::ActiveLink>,
|
||||
pdf_active_thread: Option<pdf_links::ActiveThread>,
|
||||
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(),
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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<TokenOrigin>,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<Option<PdfGraphics>, 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");
|
||||
|
||||
@@ -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<usize, usize>,
|
||||
commands: &BTreeMap<usize, (usize, TextEncoding)>,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<Vec<Annotation>, 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 {
|
||||
|
||||
@@ -43,11 +43,19 @@ pub struct NativeFontPaint {
|
||||
pub(crate) xdv_widths: BTreeMap<u8, i64>,
|
||||
#[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<Arc<XdvFontUnicode>>,
|
||||
pub resources: Vec<crate::resources::ResourceVersion>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
program_index: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) struct XdvFontUnicode {
|
||||
pub(crate) texts: BTreeMap<u8, String>,
|
||||
resources: Vec<ResourceVersion>,
|
||||
}
|
||||
|
||||
struct MappedOutline {
|
||||
data: Arc<[u8]>,
|
||||
encoding: Option<Vec<String>>,
|
||||
@@ -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<FontId, Arc<NativeFontPaint>>,
|
||||
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<Arc<XdvFontUnicode>>> = 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
})
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
|
||||
@@ -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<String>,
|
||||
}
|
||||
|
||||
#[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::<f64>().ok())
|
||||
.filter(|value| value.is_finite())
|
||||
@@ -402,6 +410,9 @@ fn parse_xdv_map_line(
|
||||
pub struct PdfFontBindings {
|
||||
fonts: BTreeMap<FontId, Option<Arc<MapEntry>>>,
|
||||
pub(super) default_map: Option<ResourceVersion>,
|
||||
// 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<String, Arc<MapEntry>>,
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
})
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<u32, Mapping>; 4],
|
||||
inherited: Option<Arc<CMap>>,
|
||||
pub(crate) resources: Vec<ResourceVersion>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Mapping {
|
||||
last: u32,
|
||||
destination: Destination,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum Destination {
|
||||
Sequential(Vec<u8>),
|
||||
Explicit(Vec<Vec<u8>>),
|
||||
}
|
||||
|
||||
impl CMap {
|
||||
pub(crate) fn load(
|
||||
name: &str,
|
||||
from: &str,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<Self, String> {
|
||||
Self::load_inner(name, from, files, &mut Vec::new())
|
||||
}
|
||||
|
||||
fn load_inner(
|
||||
name: &str,
|
||||
from: &str,
|
||||
files: &mut impl SourceProvider,
|
||||
stack: &mut Vec<ResourceVersion>,
|
||||
) -> Result<Self, String> {
|
||||
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>), 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::<usize>().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::<Result<_, _>>()?;
|
||||
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<Vec<u8>> {
|
||||
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<Vec<u8>, 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<u8, String> {
|
||||
(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<Vec<u8>, 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::<Result<Vec<_>, _>>()?;
|
||||
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<Option<&'a [u8]>, 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))
|
||||
}
|
||||
}
|
||||
@@ -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<Vec<String>, 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),
|
||||
|
||||
@@ -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<Arc<CMap>>,
|
||||
extra_keys: Arc<BTreeSet<Vec<u8>>>,
|
||||
pub(super) tainted_literals: bool,
|
||||
}
|
||||
|
||||
impl TextEncoding {
|
||||
pub(crate) fn apply(
|
||||
&mut self, operands: &[u8], from: &str, files: &mut impl SourceProvider,
|
||||
) -> Vec<String> {
|
||||
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<u8>, warnings: &mut Vec<String>) -> 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<u8>, Vec<String>), 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<String>) -> Result<(), String> {
|
||||
fn convert_text(
|
||||
key: &[u8], value: &mut Object, text: &TextEncoding, warnings: &mut Vec<String>,
|
||||
) -> 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<String>) -> R
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn normalize_text(key: &[u8], bytes: &mut Vec<u8>, warnings: &mut Vec<String>) -> 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<String>,
|
||||
|
||||
@@ -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<Vec<String>, 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<Vec<String>, 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>), 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))
|
||||
}
|
||||
@@ -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<Dictionary, String> {
|
||||
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<Dictionary, String> {
|
||||
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<Value, St
|
||||
}
|
||||
|
||||
pub(super) fn parse_object_prefix(bytes: &[u8], position: Position) -> 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>, &[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<Vec<u8>, u32>,
|
||||
@@ -305,19 +376,21 @@ impl Value {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn normalize_text(&mut self, key: &[u8], warnings: &mut Vec<String>) {
|
||||
pub(super) fn normalize_text(
|
||||
&mut self, key: &[u8], text: &TextEncoding, warnings: &mut Vec<String>,
|
||||
) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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<SourceFile, String> {
|
||||
Err(format!("unexpected input {name}"))
|
||||
}
|
||||
fn default_pk_resolution(&mut self) -> Result<i32, String> {
|
||||
Ok(600)
|
||||
}
|
||||
fn optional_font_file(
|
||||
&mut self, kind: ResourceKind, name: &str, _: &str,
|
||||
) -> Result<Option<LoadedResource>, String> {
|
||||
assert_eq!(kind, ResourceKind::CMap);
|
||||
let data = match name {
|
||||
"Base" => b"begincmap 1 begincodespacerange <00> <FF> 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 <feff03a9> >>}%
|
||||
\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"]);
|
||||
}
|
||||
Reference in new issue
Block a user