Bind shipped XeLaTeX font maps to native font resources
This commit is contained in:
1 parent
dcc6a3984c
commit
af6466cd98
11 files changed
+482
-25
No files matched your search
@@ -133,6 +133,7 @@ pub(super) fn resolve(
|
||||
descriptor_flags: outline.descriptor_flags,
|
||||
xdv_descriptor: None,
|
||||
xdv_widths: BTreeMap::new(),
|
||||
xdv_matrix: Default::default(),
|
||||
resources,
|
||||
program_index: Some(program_index),
|
||||
})
|
||||
|
||||
@@ -140,6 +140,7 @@ pub(super) fn resolve(
|
||||
descriptor_flags: entry.descriptor_flags,
|
||||
xdv_descriptor: None,
|
||||
xdv_widths: BTreeMap::new(),
|
||||
xdv_matrix: Default::default(),
|
||||
resources,
|
||||
program_index: None,
|
||||
})
|
||||
|
||||
@@ -30,6 +30,27 @@ pub(super) struct MapEntry {
|
||||
pub(super) descriptor_flags: Option<i32>,
|
||||
#[serde(default, skip_serializing_if = "Type1Transform::is_identity")]
|
||||
pub transform: Type1Transform,
|
||||
#[serde(default, skip_serializing_if = "XdvFontMatrix::is_identity")]
|
||||
xdv_matrix: XdvFontMatrix,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) struct XdvFontMatrix {
|
||||
slant: i32,
|
||||
extend: i32,
|
||||
}
|
||||
|
||||
impl XdvFontMatrix {
|
||||
pub(crate) fn is_identity(&self) -> bool {
|
||||
*self == Self::default()
|
||||
}
|
||||
|
||||
pub(crate) fn coefficients(self) -> [f64; 2] {
|
||||
[
|
||||
1.0 + f64::from(self.extend) / 1_000_000.0,
|
||||
f64::from(self.slant) / 1_000_000.0,
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
type PostscriptKey = (String, i32, i32);
|
||||
@@ -59,6 +80,42 @@ impl OutlineFiles {
|
||||
}
|
||||
|
||||
impl MapEntry {
|
||||
fn empty(from: &Path, version: Option<&ResourceVersion>) -> Self {
|
||||
Self {
|
||||
from: from.to_owned(),
|
||||
version: version.cloned(),
|
||||
file: None,
|
||||
encoding: None,
|
||||
subfont: None,
|
||||
cmap: None,
|
||||
postscript_name: false,
|
||||
ps_name: None,
|
||||
descriptor_flags: None,
|
||||
transform: Type1Transform::default(),
|
||||
subset: false,
|
||||
xdv_matrix: XdvFontMatrix::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn xdv_text_matrix(&self) -> XdvFontMatrix {
|
||||
self.xdv_matrix
|
||||
}
|
||||
|
||||
fn xdv_matrix(&self) -> XdvFontMatrix {
|
||||
if self.xdv_matrix.is_identity() {
|
||||
XdvFontMatrix {
|
||||
slant: self.transform.slant * 1_000,
|
||||
extend: if self.transform.extend == 0 {
|
||||
0
|
||||
} else {
|
||||
(self.transform.extend - 1_000) * 1_000
|
||||
},
|
||||
}
|
||||
} else {
|
||||
self.xdv_matrix
|
||||
}
|
||||
}
|
||||
|
||||
fn postscript_key(&self) -> Option<PostscriptKey> {
|
||||
Some((self.ps_name.clone()?, self.transform.slant, self.transform.extend))
|
||||
}
|
||||
@@ -183,19 +240,7 @@ fn parse_map_line(
|
||||
if !current.is_empty() {
|
||||
fields.push((false, current));
|
||||
}
|
||||
let mut entry = MapEntry {
|
||||
from: from.to_path_buf(),
|
||||
version: version.cloned(),
|
||||
file: None,
|
||||
subset: false,
|
||||
encoding: None,
|
||||
subfont: None,
|
||||
cmap: None,
|
||||
postscript_name: false,
|
||||
ps_name: None,
|
||||
descriptor_flags: None,
|
||||
transform: Type1Transform::default(),
|
||||
};
|
||||
let mut entry = MapEntry::empty(from, version);
|
||||
let mut fields = fields.into_iter().skip(1).enumerate();
|
||||
while let Some((index, (quote, value))) = fields.next() {
|
||||
if quote {
|
||||
@@ -278,6 +323,80 @@ fn parse_map_line(
|
||||
Ok(Some((name, entry)))
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum XdvMapSyntax {
|
||||
Neutral,
|
||||
Dvips,
|
||||
Dvipdfm,
|
||||
}
|
||||
|
||||
fn xdv_map_syntax(line: &str) -> XdvMapSyntax {
|
||||
if line.contains(['"', '<']) {
|
||||
XdvMapSyntax::Dvips
|
||||
} else if line.split_ascii_whitespace().count() == 2
|
||||
&& !line.split_ascii_whitespace().any(|part| part.starts_with('-'))
|
||||
{
|
||||
XdvMapSyntax::Neutral
|
||||
} else {
|
||||
XdvMapSyntax::Dvipdfm
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_xdv_map_line(
|
||||
line: &str,
|
||||
from: &Path,
|
||||
version: Option<&ResourceVersion>,
|
||||
) -> Result<Option<(String, MapEntry)>, String> {
|
||||
let mut words = line.split_ascii_whitespace().peekable();
|
||||
let Some(name) = words.next() else { return Ok(None) };
|
||||
let mut entry = MapEntry::empty(from, version);
|
||||
let mut fields = (0..2).map(|_| {
|
||||
words.next_if(|field| !field.starts_with('-'))
|
||||
.filter(|field| !matches!(*field, "default" | "none"))
|
||||
});
|
||||
if let Some(encoding) = fields.next().flatten() {
|
||||
if encoding == "unicode" || encoding.starts_with("Identity-") {
|
||||
return Err(format!("unsupported XDV composite map encoding {encoding} for {name}"));
|
||||
}
|
||||
entry.encoding = Some(if encoding.ends_with(".enc") {
|
||||
encoding.to_owned()
|
||||
} else {
|
||||
format!("{encoding}.enc")
|
||||
});
|
||||
}
|
||||
let file = fields.next().flatten().unwrap_or(name);
|
||||
if file.contains([':', ',']) || file.starts_with('!') {
|
||||
return Err(format!("unsupported XDV map font options for {name}: {file}"));
|
||||
}
|
||||
entry.file = Some(if Path::new(file).extension().is_none() {
|
||||
format!("{file}.pfb")
|
||||
} else {
|
||||
file.to_owned()
|
||||
});
|
||||
entry.subset = true;
|
||||
while let Some(option) = words.next() {
|
||||
match option {
|
||||
"-r" => {}, // Obsolete remapping option in the reference driver.
|
||||
"-s" | "-e" => {
|
||||
let number = words.next().and_then(|word| word.parse::<f64>().ok())
|
||||
.filter(|value| value.is_finite())
|
||||
.ok_or_else(|| format!("invalid XDV map option {option} for {name}"))?;
|
||||
let fixed = (number * 1_000_000.0).round();
|
||||
if fixed.abs() > f64::from(i32::MAX) || (option == "-e" && fixed <= 0.0) {
|
||||
return Err(format!("XDV map option {option} out of range for {name}"));
|
||||
}
|
||||
if option == "-s" {
|
||||
entry.xdv_matrix.slant = fixed as i32;
|
||||
} else {
|
||||
entry.xdv_matrix.extend = fixed as i32 - 1_000_000;
|
||||
}
|
||||
}
|
||||
_ => return Err(format!("unsupported XDV map option {option} for {name}")),
|
||||
}
|
||||
}
|
||||
Ok(Some((name.to_owned(), entry)))
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PdfFontBindings {
|
||||
@@ -326,6 +445,9 @@ pub(super) struct JobFontMap {
|
||||
used_names: BTreeSet<String>,
|
||||
used_postscript: BTreeSet<PostscriptKey>,
|
||||
bindings: Option<Arc<PdfFontBindings>>,
|
||||
// XDV fixes a scalable PDF font by its device name on first use.
|
||||
// Later sizes can still pick up a new text matrix for that same program.
|
||||
xdv_loaded: Option<BTreeMap<String, Arc<MapEntry>>>,
|
||||
}
|
||||
|
||||
impl JobFontMap {
|
||||
@@ -371,7 +493,27 @@ impl JobFontMap {
|
||||
if bindings.fonts.contains_key(&id) {
|
||||
return;
|
||||
}
|
||||
let entry = self.tables.entries.get(name).cloned();
|
||||
let mut entry = self.tables.entries.get(name).cloned();
|
||||
if let Some(loaded) = &mut self.xdv_loaded {
|
||||
if let Some(first) = loaded.get(name) {
|
||||
let matrix = entry.as_ref().map_or_else(XdvFontMatrix::default, |entry| entry.xdv_matrix());
|
||||
if matrix == first.xdv_matrix() {
|
||||
entry = Some(first.clone());
|
||||
} else {
|
||||
let mut device = first.as_ref().clone();
|
||||
device.transform = Type1Transform::default();
|
||||
device.xdv_matrix = matrix;
|
||||
entry = Some(Arc::new(device));
|
||||
}
|
||||
} else if let Some(outline) = entry.as_ref().filter(|entry| entry.is_scalable()) {
|
||||
let mut device = outline.as_ref().clone();
|
||||
device.xdv_matrix = device.xdv_matrix();
|
||||
device.transform = Type1Transform::default();
|
||||
let device = Arc::new(device);
|
||||
loaded.insert(name.to_owned(), device.clone());
|
||||
entry = Some(device);
|
||||
}
|
||||
}
|
||||
if let Some(entry) = &entry {
|
||||
self.used_names.insert(name.into());
|
||||
if let Some(key) = entry.postscript_key()
|
||||
@@ -460,6 +602,102 @@ impl JobFontMap {
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn xdv_prefers_physical(&self, name: &str) -> bool {
|
||||
self.xdv_loaded.is_some() && self.tables.entries.contains_key(name)
|
||||
}
|
||||
|
||||
pub(super) fn xdv_command(
|
||||
&mut self,
|
||||
input: &[u8],
|
||||
map_file: bool,
|
||||
from: &Path,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let text = std::str::from_utf8(input).map_err(|_| "XDV font map command is not UTF-8")?;
|
||||
let text = text.trim_ascii_start();
|
||||
if text.is_empty() {
|
||||
return Ok(if map_file { Vec::new() } else { vec!["Empty mapline special?".into()] });
|
||||
}
|
||||
let (mode, item) = match text.as_bytes()[0] {
|
||||
b'+' => (MapMode::Add, &text[1..]),
|
||||
b'-' => (MapMode::Delete, &text[1..]),
|
||||
_ => (MapMode::Replace, text),
|
||||
};
|
||||
self.xdv_loaded.get_or_insert_with(BTreeMap::new);
|
||||
if self.bindings.is_none() {
|
||||
self.initialize(true, from, files)?;
|
||||
}
|
||||
let item = item.trim_ascii_start();
|
||||
let mut warnings = Vec::new();
|
||||
if map_file {
|
||||
let name = if let Some(quoted) = item.strip_prefix('"') {
|
||||
quoted.split_once('"').map(|(name, _)| name)
|
||||
} else {
|
||||
item.split_ascii_whitespace().next()
|
||||
};
|
||||
let Some(name) = name.filter(|name| !name.is_empty()) else {
|
||||
return Ok(vec!["No fontmap file specified.".into()]);
|
||||
};
|
||||
let name = if Path::new(name).extension().is_some() {
|
||||
name.to_owned()
|
||||
} else {
|
||||
format!("{name}.map")
|
||||
};
|
||||
let Some(read) = load_map(files, &name, from)? else {
|
||||
return Ok(vec![format!("Could not open font map file {name:?}.")]);
|
||||
};
|
||||
let body = std::str::from_utf8(&read.data).map_err(|_| "XDV font map is not UTF-8")?;
|
||||
let mut syntax = XdvMapSyntax::Neutral;
|
||||
for (index, line) in body.lines().enumerate() {
|
||||
let line = line.split('%').next().unwrap().trim_ascii();
|
||||
if line.is_empty() || line.starts_with(['#', ';', '*']) {
|
||||
continue;
|
||||
}
|
||||
let shape = xdv_map_syntax(line);
|
||||
if syntax == XdvMapSyntax::Neutral {
|
||||
syntax = shape;
|
||||
} else if shape != XdvMapSyntax::Neutral && syntax != shape {
|
||||
warnings.push(format!("Mismatched fontmap line {} from {name}.", index + 1));
|
||||
continue;
|
||||
}
|
||||
let result = if syntax == XdvMapSyntax::Dvipdfm {
|
||||
parse_xdv_map_line(line, &read.version.path, Some(&read.version))
|
||||
} else {
|
||||
parse_map_line(line, &read.version.path, Some(&read.version))
|
||||
};
|
||||
match result {
|
||||
Ok(Some((name, entry))) => self.install_line(name, entry, mode, true, &mut warnings, files)?,
|
||||
Ok(None) => {},
|
||||
Err(error) => {
|
||||
warnings.push(error);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if mode == MapMode::Delete {
|
||||
if let Some(name) = item.split_ascii_whitespace().next() {
|
||||
self.install_line(name.to_owned(), MapEntry::empty(from, None), mode, true, &mut warnings, files)?;
|
||||
} else {
|
||||
warnings.push("Invalid fontmap line: Missing TFM name.".into());
|
||||
}
|
||||
} else if item.len() >= 1023 {
|
||||
warnings.push("Invalid fontmap line: Too long a line.".into());
|
||||
} else {
|
||||
let item = item.split('%').next().unwrap().trim_ascii();
|
||||
let result = if xdv_map_syntax(item) == XdvMapSyntax::Dvipdfm {
|
||||
parse_xdv_map_line(item, from, None)
|
||||
} else {
|
||||
parse_map_line(item, from, None)
|
||||
};
|
||||
match result {
|
||||
Ok(Some((name, entry))) => self.install_line(name, entry, mode, true, &mut warnings, files)?,
|
||||
Ok(None) => {},
|
||||
Err(error) => warnings.push(error),
|
||||
}
|
||||
}
|
||||
Ok(warnings)
|
||||
}
|
||||
|
||||
pub(super) fn command(
|
||||
&mut self,
|
||||
input: &[u8],
|
||||
@@ -546,6 +784,18 @@ impl JobFontMap {
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
self.install_line(name, entry, mode, suppress_duplicates, warnings, files)
|
||||
}
|
||||
|
||||
fn install_line(
|
||||
&mut self,
|
||||
name: String,
|
||||
entry: MapEntry,
|
||||
mode: MapMode,
|
||||
suppress_duplicates: bool,
|
||||
warnings: &mut Vec<String>,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<(), String> {
|
||||
if let Some((prefix, file)) = sfd::template(&name) {
|
||||
let definition = format!("{file}.sfd");
|
||||
if let Some(definition) = self.subfonts.get(files, &definition, &entry.from)? {
|
||||
@@ -578,22 +828,33 @@ impl JobFontMap {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.used_names.contains(&name) {
|
||||
if self.xdv_loaded.is_none() && self.used_names.contains(&name) {
|
||||
warnings.push(format!(
|
||||
"fontmap entry for '{name}' has been used, replace/delete not allowed"
|
||||
));
|
||||
return;
|
||||
}
|
||||
}
|
||||
if self.xdv_loaded.is_some()
|
||||
&& let Some(key) = self.tables.entries.get(&name).and_then(|old| old.postscript_key())
|
||||
&& self.tables.postscript.get(&key).is_some_and(|(owner, _)| *owner == name)
|
||||
{
|
||||
Arc::make_mut(&mut self.tables.postscript).remove(&key);
|
||||
}
|
||||
let entry = Arc::new(entry);
|
||||
if mode == MapMode::Delete {
|
||||
Arc::make_mut(&mut self.tables.entries).remove(&name);
|
||||
} else {
|
||||
Arc::make_mut(&mut self.tables.entries).insert(name.clone(), entry.clone());
|
||||
}
|
||||
if self.xdv_loaded.is_some() && mode == MapMode::Delete {
|
||||
return;
|
||||
}
|
||||
let Some(key) = entry.postscript_key() else { return };
|
||||
if self.tables.postscript.contains_key(&key) {
|
||||
if mode == MapMode::Add || self.used_postscript.contains(&key) {
|
||||
if mode == MapMode::Add
|
||||
|| (self.xdv_loaded.is_none() && self.used_postscript.contains(&key))
|
||||
{
|
||||
return;
|
||||
}
|
||||
Arc::make_mut(&mut self.tables.postscript).remove(&key);
|
||||
@@ -688,5 +949,6 @@ pub(super) fn dedicated_space_map(font: &NativeFont) -> MapEntry {
|
||||
descriptor_flags: None,
|
||||
transform: Type1Transform::default(),
|
||||
subset: false,
|
||||
xdv_matrix: XdvFontMatrix::default(),
|
||||
}
|
||||
}
|
||||
@@ -225,6 +225,7 @@ pub(super) fn resolve(
|
||||
descriptor_flags: outline.descriptor_flags,
|
||||
xdv_descriptor: None,
|
||||
xdv_widths: BTreeMap::new(),
|
||||
xdv_matrix: Default::default(),
|
||||
resources,
|
||||
program_index: Some(program_index),
|
||||
})
|
||||
|
||||
@@ -406,6 +406,13 @@ impl JobVirtualFonts {
|
||||
self.font_map.command(bytes, map_file, from, suppress_duplicates, files)
|
||||
}
|
||||
|
||||
pub(crate) fn update_xdv_font_map(
|
||||
&mut self, bytes: &[u8], map_file: bool, from: &std::path::Path,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<Vec<String>, String> {
|
||||
self.font_map.xdv_command(bytes, map_file, from, files)
|
||||
}
|
||||
|
||||
pub(crate) fn imported_type1_program(
|
||||
&mut self, name: &str, from: &std::path::Path, files: &mut impl SourceProvider,
|
||||
) -> Result<Option<super::MappedType1>, String> {
|
||||
@@ -471,6 +478,8 @@ impl JobVirtualFonts {
|
||||
}
|
||||
} else if let Some(program) = &font.letter_spacing {
|
||||
Some(Program::Letterspace(program.clone()))
|
||||
} else if self.font_map.xdv_prefers_physical(&font.name) {
|
||||
None
|
||||
} else if let Some(vf) = read_virtual(font, files)? {
|
||||
let mut locals = BTreeMap::new();
|
||||
for id in &vf.program.local_order {
|
||||
|
||||
Reference in new issue
Block a user