Resolve pdfTeX SFD subfonts against actual TrueType cmaps
This commit is contained in:
1 parent
fd5ab59f42
commit
868814288c
10 files changed
+481
-43
No files matched your search
@@ -1,5 +1,8 @@
|
||||
//! Resolve an eight-bit TeX font mapped to a name-keyed OpenType CFF face.
|
||||
use super::{MappedOutline, NativeFont, NativeFontPaint, NativeFontProgram, map::MapEntry};
|
||||
use super::{
|
||||
MappedOutline, NativeFont, NativeFontPaint, NativeFontProgram,
|
||||
map::{MapEntry, OutlineFiles},
|
||||
};
|
||||
use crate::{execution::SourceProvider, resources::ResourceKind};
|
||||
use read_fonts::ps::cff::CffFontRef;
|
||||
use rustybuzz::ttf_parser::{Face, GlyphId, Tag};
|
||||
@@ -20,6 +23,7 @@ impl OpenTypeCffProgram {
|
||||
|
||||
pub(super) fn resolve(
|
||||
files: &mut impl SourceProvider,
|
||||
outlines: &mut OutlineFiles,
|
||||
outline: &MapEntry,
|
||||
file: &str,
|
||||
font: &NativeFont,
|
||||
@@ -33,7 +37,7 @@ pub(super) fn resolve(
|
||||
encoding,
|
||||
resources,
|
||||
program_index,
|
||||
} = outline.read_outline(files, ResourceKind::OpenType, file)?;
|
||||
} = outline.read_outline(files, outlines, ResourceKind::OpenType, file)?;
|
||||
let face =
|
||||
Face::parse(&data, 0).map_err(|error| format!("invalid OpenType font {file}: {error}"))?;
|
||||
let table = face
|
||||
@@ -89,7 +93,7 @@ pub(super) fn resolve(
|
||||
.map(|value| 1000 * i32::from(value) / i32::from(face.units_per_em()));
|
||||
let program = OpenTypeCffProgram {
|
||||
name: outline.postscript_name().unwrap_or(&font.name).to_owned(),
|
||||
data: data.into(),
|
||||
data,
|
||||
};
|
||||
Ok(NativeFontPaint {
|
||||
program: NativeFontProgram::OpenTypeCff(program),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! PDF font map entries, lookup bindings, and the lifetime of the default map.
|
||||
use super::{MappedOutline, MappedType1, NativeFont, actual_resource, encoding_vector, verify_resource};
|
||||
use super::{MappedOutline, MappedType1, NativeFont, actual_resource, encoding_vector, sfd, verify_resource};
|
||||
use crate::{
|
||||
execution::{FontId, SourceProvider},
|
||||
resources::{LoadedResource, ResourceKind, ResourceVersion},
|
||||
@@ -19,6 +19,10 @@ pub(super) struct MapEntry {
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub(super) subset: bool,
|
||||
pub encoding: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) subfont: Option<sfd::Subfont>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
cmap: Option<[u16; 2]>,
|
||||
postscript_name: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
ps_name: Option<String>,
|
||||
@@ -29,6 +33,30 @@ pub(super) struct MapEntry {
|
||||
}
|
||||
|
||||
type PostscriptKey = (String, i32, i32);
|
||||
type OutlineKey = (ResourceKind, PathBuf, String);
|
||||
|
||||
/// Share the inspected bytes of a physical outline within an output pass.
|
||||
#[derive(Default)]
|
||||
pub(super) struct OutlineFiles(BTreeMap<OutlineKey, (ResourceVersion, Arc<[u8]>)>);
|
||||
|
||||
impl OutlineFiles {
|
||||
fn read(
|
||||
&mut self,
|
||||
files: &mut impl SourceProvider,
|
||||
kind: ResourceKind,
|
||||
file: &str,
|
||||
from: &Path,
|
||||
) -> Result<(ResourceVersion, Arc<[u8]>), String> {
|
||||
let key = (kind, from.to_owned(), file.to_owned());
|
||||
if let Some(found) = self.0.get(&key) {
|
||||
return Ok(found.clone());
|
||||
}
|
||||
let loaded = actual_resource(files, kind, file, &from.to_string_lossy())?;
|
||||
let value = (loaded.version, Arc::from(loaded.data));
|
||||
self.0.insert(key, value.clone());
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl MapEntry {
|
||||
fn postscript_key(&self) -> Option<PostscriptKey> {
|
||||
@@ -60,14 +88,18 @@ impl MapEntry {
|
||||
pub(super) fn read_outline(
|
||||
&self,
|
||||
files: &mut impl SourceProvider,
|
||||
outlines: &mut OutlineFiles,
|
||||
kind: ResourceKind,
|
||||
file: &str,
|
||||
) -> Result<MappedOutline, String> {
|
||||
let from = self.from.to_string_lossy();
|
||||
let program = actual_resource(files, kind, file, &from)?;
|
||||
let (program, data) = outlines.read(files, kind, file, &self.from)?;
|
||||
let mut resources: Vec<_> = self.version.iter().cloned().collect();
|
||||
if let Some(subfont) = &self.subfont {
|
||||
resources.push(subfont.version.as_ref().clone());
|
||||
}
|
||||
let program_index = resources.len();
|
||||
resources.push(program.version);
|
||||
resources.push(program);
|
||||
let encoding = if let Some(name) = &self.encoding {
|
||||
let file = actual_resource(files, ResourceKind::Encoding, name, &from)?;
|
||||
let names = encoding_vector(&file.data)?;
|
||||
@@ -76,7 +108,20 @@ impl MapEntry {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(MappedOutline { data: program.data, encoding, resources, program_index })
|
||||
Ok(MappedOutline { data, encoding, resources, program_index })
|
||||
}
|
||||
|
||||
fn for_subfont(mut self, definition: &sfd::Definition, codes: &sfd::Codes) -> Self {
|
||||
self.ps_name = None;
|
||||
self.postscript_name = false;
|
||||
self.descriptor_flags = None;
|
||||
self.encoding = None;
|
||||
self.subfont = Some(sfd::Subfont {
|
||||
version: definition.version.clone(),
|
||||
codes: codes.clone(),
|
||||
cmap: self.cmap.unwrap_or([3, 1]),
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
pub(super) fn postscript_name(&self) -> Option<&str> {
|
||||
@@ -140,12 +185,15 @@ fn parse_map_line(
|
||||
file: None,
|
||||
subset: false,
|
||||
encoding: None,
|
||||
subfont: None,
|
||||
cmap: None,
|
||||
postscript_name: false,
|
||||
ps_name: None,
|
||||
descriptor_flags: None,
|
||||
transform: Type1Transform::default(),
|
||||
};
|
||||
for (index, (quote, value)) in fields.into_iter().skip(1).enumerate() {
|
||||
let mut fields = fields.into_iter().skip(1).enumerate();
|
||||
while let Some((index, (quote, value))) = fields.next() {
|
||||
if quote {
|
||||
let mut previous = "";
|
||||
for word in value.split_ascii_whitespace() {
|
||||
@@ -166,6 +214,22 @@ fn parse_map_line(
|
||||
}
|
||||
previous = word;
|
||||
}
|
||||
} else if let Some(spec) = value.strip_prefix("PidEid=") {
|
||||
let (platform, encoding) = spec.split_once(',')
|
||||
.ok_or_else(|| format!("invalid PidEid for {name}"))?;
|
||||
let continuation;
|
||||
let encoding = if encoding.is_empty() {
|
||||
continuation = fields.next().and_then(|(_, (quote, value))| (!quote).then_some(value))
|
||||
.ok_or_else(|| format!("invalid PidEid for {name}"))?;
|
||||
&continuation
|
||||
} else {
|
||||
encoding
|
||||
};
|
||||
let parse = |value| sfd::integer(value).and_then(|value| u16::try_from(value).ok());
|
||||
entry.cmap = Some([
|
||||
parse(platform).ok_or_else(|| format!("invalid PidEid for {name}"))?,
|
||||
parse(encoding).ok_or_else(|| format!("invalid PidEid for {name}"))?,
|
||||
]);
|
||||
} else if value.starts_with('<') {
|
||||
let path = value.trim_start_matches('<').trim_start_matches('[');
|
||||
if path.ends_with(".enc") {
|
||||
@@ -202,6 +266,11 @@ fn parse_map_line(
|
||||
"SlantFont/ExtendFont require an embedded Type1 program for {name}"
|
||||
));
|
||||
}
|
||||
if entry.cmap.is_some()
|
||||
&& (entry.true_type_file().is_none() || !entry.subset || entry.encoding.is_some())
|
||||
{
|
||||
return Err(format!("PidEid requires a subsetted non-reencoded TrueType font: {name}"));
|
||||
}
|
||||
Ok(Some((name, entry)))
|
||||
}
|
||||
|
||||
@@ -237,6 +306,7 @@ pub(super) struct JobFontMap {
|
||||
pending_fonts: Vec<(FontId, String)>,
|
||||
pending_ids: BTreeSet<FontId>,
|
||||
entries: Arc<BTreeMap<String, Arc<MapEntry>>>,
|
||||
subfonts: sfd::Files,
|
||||
used_names: BTreeSet<String>,
|
||||
// PDF inclusion addresses the PostScript name independently of the TFM.
|
||||
postscript_entries: Arc<BTreeMap<PostscriptKey, (String, Arc<MapEntry>)>>,
|
||||
@@ -310,7 +380,7 @@ impl JobFontMap {
|
||||
let from = self.first_font_source.as_deref().unwrap_or(from);
|
||||
if let Some(read) = load_map(files, "pdftex.map", from)? {
|
||||
let mut ignored = Vec::new();
|
||||
self.apply_file(&read, MapMode::Add, true, &mut ignored)?;
|
||||
self.apply_file(&read, MapMode::Add, true, &mut ignored, files)?;
|
||||
bindings.default_map = Some(read.version);
|
||||
}
|
||||
}
|
||||
@@ -384,13 +454,13 @@ impl JobFontMap {
|
||||
};
|
||||
match load_map(files, &name, from)? {
|
||||
Some(read) => {
|
||||
self.apply_file(&read, mode, suppress_duplicates, &mut warnings)?
|
||||
self.apply_file(&read, mode, suppress_duplicates, &mut warnings, files)?
|
||||
}
|
||||
None => warnings.push(format!("cannot open font map file {name}")),
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self.apply_line(item, from, None, mode, suppress_duplicates, &mut warnings);
|
||||
self.apply_line(item, from, None, mode, suppress_duplicates, &mut warnings, files)?;
|
||||
}
|
||||
Ok(warnings)
|
||||
}
|
||||
@@ -401,6 +471,7 @@ impl JobFontMap {
|
||||
mode: MapMode,
|
||||
suppress_duplicates: bool,
|
||||
warnings: &mut Vec<String>,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<(), String> {
|
||||
let text = std::str::from_utf8(&read.data).map_err(|_| "font map is not UTF-8/ASCII")?;
|
||||
for line in text.lines() {
|
||||
@@ -411,7 +482,8 @@ impl JobFontMap {
|
||||
mode,
|
||||
suppress_duplicates,
|
||||
warnings,
|
||||
);
|
||||
files,
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -424,15 +496,39 @@ impl JobFontMap {
|
||||
mode: MapMode,
|
||||
suppress_duplicates: bool,
|
||||
warnings: &mut Vec<String>,
|
||||
) {
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<(), String> {
|
||||
let (name, entry) = match parse_map_line(line, from, version) {
|
||||
Ok(Some(entry)) => entry,
|
||||
Ok(None) => return,
|
||||
Ok(None) => return Ok(()),
|
||||
Err(error) => {
|
||||
warnings.push(error);
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
if let Some((prefix, file)) = sfd::template(&name) {
|
||||
let definition = format!("{file}.sfd");
|
||||
if let Some(definition) = self.subfonts.get(files, &definition, &entry.from)? {
|
||||
for (suffix, codes) in &definition.subfonts {
|
||||
let subfont = entry.clone().for_subfont(&definition, codes);
|
||||
self.apply_entry(format!("{prefix}{suffix}"), subfont, mode, suppress_duplicates, warnings);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
warnings.push(format!("cannot open SFD file {definition} for reading"));
|
||||
}
|
||||
self.apply_entry(name, entry, mode, suppress_duplicates, warnings);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_entry(
|
||||
&mut self,
|
||||
name: String,
|
||||
entry: MapEntry,
|
||||
mode: MapMode,
|
||||
suppress_duplicates: bool,
|
||||
warnings: &mut Vec<String>,
|
||||
) {
|
||||
if self.entries.contains_key(&name) {
|
||||
if mode == MapMode::Add {
|
||||
if !suppress_duplicates {
|
||||
@@ -503,15 +599,28 @@ pub(super) fn load_map(
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub(super) fn find_map_entry(map: &LoadedResource, name: &str) -> Result<Option<MapEntry>, String> {
|
||||
pub(super) fn find_map_entry(
|
||||
map: &LoadedResource,
|
||||
name: &str,
|
||||
files: &mut impl SourceProvider,
|
||||
definitions: &mut sfd::Files,
|
||||
) -> Result<Option<MapEntry>, String> {
|
||||
let text = std::str::from_utf8(&map.data).map_err(|_| "font map is not UTF-8/ASCII")?;
|
||||
let Some(line) = text
|
||||
.lines()
|
||||
.find(|line| line.split_ascii_whitespace().next() == Some(name))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(parse_map_line(line, &map.version.path, Some(&map.version))?.map(|(_, entry)| entry))
|
||||
for line in text.lines() {
|
||||
let Some(candidate) = line.split_ascii_whitespace().next() else { continue };
|
||||
if candidate == name {
|
||||
return Ok(parse_map_line(line, &map.version.path, Some(&map.version))?.map(|(_, entry)| entry));
|
||||
}
|
||||
if let Some((prefix, file)) = sfd::template(candidate)
|
||||
&& let Some(suffix) = name.strip_prefix(prefix)
|
||||
&& let Some((_, entry)) = parse_map_line(line, &map.version.path, Some(&map.version))?
|
||||
&& let Some(definition) = definitions.get(files, &format!("{file}.sfd"), &entry.from)?
|
||||
&& let Some((_, codes)) = definition.subfonts.iter().find(|(infix, _)| infix == suffix)
|
||||
{
|
||||
return Ok(Some(entry.for_subfont(&definition, codes)));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(super) fn selected_outline<'a>(
|
||||
@@ -532,6 +641,8 @@ pub(super) fn dedicated_space_map(font: &NativeFont) -> MapEntry {
|
||||
version: None,
|
||||
file: Some("pdftexspace.pfb".into()),
|
||||
encoding: None,
|
||||
subfont: None,
|
||||
cmap: None,
|
||||
postscript_name: false,
|
||||
ps_name: None,
|
||||
descriptor_flags: None,
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
//! Subfont definition files bind 8-bit TeX slots to a TrueType cmap.
|
||||
use crate::{
|
||||
execution::SourceProvider,
|
||||
resources::{ResourceKind, ResourceVersion},
|
||||
};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
pub(super) type Codes = Arc<[Option<u16>]>;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub(super) struct Subfont {
|
||||
pub(super) version: Arc<ResourceVersion>,
|
||||
pub(super) codes: Codes,
|
||||
pub(super) cmap: [u16; 2],
|
||||
}
|
||||
|
||||
pub(super) struct Definition {
|
||||
pub(super) version: Arc<ResourceVersion>,
|
||||
pub(super) subfonts: Vec<(String, Codes)>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct Files(BTreeMap<(PathBuf, String), Arc<Definition>>);
|
||||
|
||||
impl Files {
|
||||
pub(super) fn get(
|
||||
&mut self,
|
||||
files: &mut impl SourceProvider,
|
||||
name: &str,
|
||||
from: &Path,
|
||||
) -> Result<Option<Arc<Definition>>, String> {
|
||||
let key = (from.to_owned(), name.to_owned());
|
||||
if let Some(result) = self.0.get(&key) {
|
||||
return Ok(Some(result.clone()));
|
||||
}
|
||||
let result = files
|
||||
.optional_font_file(ResourceKind::Sfd, name, &from.to_string_lossy())?
|
||||
.map(|resource| {
|
||||
let resource = super::verify_resource(resource, ResourceKind::Sfd, name)?;
|
||||
let subfonts = parse(&resource.data).map_err(|error| {
|
||||
format!(
|
||||
"invalid SFD file {}: {error}",
|
||||
resource.version.path.display()
|
||||
)
|
||||
})?;
|
||||
Ok::<_, String>(Arc::new(Definition {
|
||||
version: Arc::new(resource.version),
|
||||
subfonts,
|
||||
}))
|
||||
})
|
||||
.transpose()?;
|
||||
if let Some(definition) = &result {
|
||||
self.0.insert(key, definition.clone());
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
/// The pdfTeX map spelling is prefix@definition@, with an implicit .sfd.
|
||||
pub(super) fn template(name: &str) -> Option<(&str, &str)> {
|
||||
let (prefix, file) = name.strip_suffix('@')?.split_once('@')?;
|
||||
(!prefix.is_empty() && !file.is_empty() && !file.contains('@')).then_some((prefix, file))
|
||||
}
|
||||
|
||||
fn parse(data: &[u8]) -> Result<Vec<(String, Codes)>, String> {
|
||||
let text = std::str::from_utf8(data).map_err(|_| "expected UTF-8/ASCII")?;
|
||||
let mut lines = text
|
||||
.lines()
|
||||
.enumerate()
|
||||
.map(|(index, line)| (index + 1, line.trim()))
|
||||
.filter(|(_, line)| !line.is_empty() && !line.starts_with('#'));
|
||||
let mut result = Vec::new();
|
||||
while let Some((line, start)) = lines.next() {
|
||||
let mut row = start.to_owned();
|
||||
while row.ends_with('\\') {
|
||||
row.pop();
|
||||
let (_, continuation) = lines
|
||||
.next()
|
||||
.ok_or_else(|| format!("line {line}: unterminated continuation"))?;
|
||||
row.push(' ');
|
||||
row.push_str(continuation);
|
||||
}
|
||||
let (name, input) = row.split_once(char::is_whitespace).unwrap_or((&row, ""));
|
||||
let codes = parse_codes(input).map_err(|error| format!("line {line}: {error}"))?;
|
||||
result.push((name.to_owned(), codes));
|
||||
}
|
||||
// pdfTeX registers subfonts in reverse file order.
|
||||
result.reverse();
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn parse_codes(mut input: &str) -> Result<Codes, String> {
|
||||
let mut codes = [None; 256];
|
||||
let mut offset = 0;
|
||||
while !input.trim().is_empty() {
|
||||
let start = number(&mut input)?;
|
||||
if let Some(rest) = input.strip_prefix(':') {
|
||||
offset = usize::try_from(start)
|
||||
.ok()
|
||||
.filter(|&slot| slot < codes.len())
|
||||
.ok_or("invalid subfont slot offset")?;
|
||||
input = rest;
|
||||
continue;
|
||||
}
|
||||
let end = if let Some(rest) = input.strip_prefix('_') {
|
||||
input = rest;
|
||||
number(&mut input)?
|
||||
} else {
|
||||
start
|
||||
};
|
||||
if start < -1 || end < start || end > i64::from(u16::MAX) {
|
||||
return Err("invalid subfont character range".into());
|
||||
}
|
||||
let count = (end - start + 1) as usize;
|
||||
let range = codes
|
||||
.get_mut(offset..offset + count)
|
||||
.ok_or("subfont slots exceed 255")?;
|
||||
for (code, value) in range.iter_mut().zip(start..=end) {
|
||||
*code = u16::try_from(value).ok();
|
||||
}
|
||||
offset += count;
|
||||
}
|
||||
Ok(codes.into())
|
||||
}
|
||||
|
||||
pub(super) fn integer(token: &str) -> Option<i64> {
|
||||
let (negative, digits) = if let Some(rest) = token.strip_prefix('-') {
|
||||
(true, rest)
|
||||
} else {
|
||||
(false, token.strip_prefix('+').unwrap_or(token))
|
||||
};
|
||||
let (radix, digits) = if let Some(hex) = digits
|
||||
.strip_prefix("0x")
|
||||
.or_else(|| digits.strip_prefix("0X"))
|
||||
{
|
||||
(16, hex)
|
||||
} else if digits.starts_with('0') {
|
||||
(8, digits)
|
||||
} else {
|
||||
(10, digits)
|
||||
};
|
||||
let value = i64::from_str_radix(digits, radix).ok()?;
|
||||
Some(if negative { -value } else { value })
|
||||
}
|
||||
|
||||
fn number(input: &mut &str) -> Result<i64, String> {
|
||||
let text = input.trim_start();
|
||||
let end = text
|
||||
.find(|character: char| character.is_whitespace() || matches!(character, ':' | '_'))
|
||||
.unwrap_or(text.len());
|
||||
let (token, rest) = text.split_at(end);
|
||||
*input = rest.trim_start();
|
||||
integer(token).ok_or_else(|| format!("invalid subfont number {token:?}"))
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
//! The PDF map binds TeX slots to a real TrueType face, independent of the TFM.
|
||||
use super::{MappedOutline, NativeFont, NativeFontPaint, NativeFontProgram, map::MapEntry};
|
||||
use super::{
|
||||
MappedOutline, NativeFont, NativeFontPaint, NativeFontProgram,
|
||||
map::{MapEntry, OutlineFiles},
|
||||
};
|
||||
use crate::{execution::SourceProvider, resources::ResourceKind};
|
||||
use rustybuzz::ttf_parser::{Face, GlyphId, PlatformId, RawFace, Tag, name_id};
|
||||
use std::{
|
||||
@@ -14,6 +17,10 @@ pub struct TrueTypeProgram {
|
||||
data: Arc<[u8]>,
|
||||
glyphs: Vec<u16>,
|
||||
pub(crate) reencoded: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) subfont_codes: Option<Arc<[Option<u16>]>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) missing_subfont_cmap: Option<[u16; 2]>,
|
||||
}
|
||||
|
||||
impl TrueTypeProgram {
|
||||
@@ -53,6 +60,16 @@ impl TrueTypeProgram {
|
||||
.map_err(|error| error.to_string())?
|
||||
.number_of_glyphs();
|
||||
tables.insert(tag(b"cmap"), slot_cmap(&mapping, glyph_count));
|
||||
if self.subfont_codes.is_some()
|
||||
&& let Some(post) = tables.get_mut(&tag(b"post"))
|
||||
{
|
||||
// A numeric subfont leaves extraction to the PDF encoding.
|
||||
if post.len() < 32 {
|
||||
return Err("invalid TrueType post table".into());
|
||||
}
|
||||
post.truncate(32);
|
||||
post[..4].copy_from_slice(&0x0003_0000u32.to_be_bytes());
|
||||
}
|
||||
if let Some(os2) = original.raw_face().table(tag(b"OS/2")) {
|
||||
tables.insert(tag(b"OS/2"), symbol_os2(os2)?);
|
||||
}
|
||||
@@ -65,6 +82,7 @@ impl TrueTypeProgram {
|
||||
|
||||
pub(super) fn resolve(
|
||||
files: &mut impl SourceProvider,
|
||||
outlines: &mut OutlineFiles,
|
||||
outline: &MapEntry,
|
||||
file: &str,
|
||||
font: &NativeFont,
|
||||
@@ -75,13 +93,20 @@ pub(super) fn resolve(
|
||||
encoding,
|
||||
resources,
|
||||
program_index,
|
||||
} = outline.read_outline(files, ResourceKind::TrueType, file)?;
|
||||
} = outline.read_outline(files, outlines, ResourceKind::TrueType, file)?;
|
||||
let face =
|
||||
Face::parse(&data, 0).map_err(|error| format!("invalid TrueType font {file}: {error}"))?;
|
||||
if face.tables().glyf.is_none() || face.number_of_glyphs() < 2 {
|
||||
return Err(format!("invalid TrueType outline tables in {file}"));
|
||||
}
|
||||
if outline.subset && encoding.is_none() {
|
||||
let subfont = outline.subfont.as_ref().filter(|_| outline.subset);
|
||||
let subfont_cmap =
|
||||
subfont.and_then(|subfont| {
|
||||
face.tables().cmap?.subtables.into_iter().find(|table| {
|
||||
[platform_number(table.platform_id), table.encoding_id] == subfont.cmap
|
||||
})
|
||||
});
|
||||
if outline.subset && encoding.is_none() && subfont.is_none() {
|
||||
return Err(format!(
|
||||
"subset TrueType font {} needs a reencoding",
|
||||
font.name
|
||||
@@ -89,7 +114,16 @@ pub(super) fn resolve(
|
||||
}
|
||||
|
||||
let reencoded = encoding.is_some();
|
||||
let glyphs = if outline.subset {
|
||||
let glyphs = if let Some(subfont) = subfont {
|
||||
subfont
|
||||
.codes
|
||||
.iter()
|
||||
.map(|&code| {
|
||||
code.and_then(|code| subfont_cmap?.glyph_index(u32::from(code)))
|
||||
.map_or(0, |glyph| glyph.0)
|
||||
})
|
||||
.collect()
|
||||
} else if outline.subset {
|
||||
let encoding = encoding.as_ref().unwrap();
|
||||
encoding
|
||||
.iter()
|
||||
@@ -108,9 +142,19 @@ pub(super) fn resolve(
|
||||
if let Some(name) = face.glyph_name(GlyphId(glyph)) {
|
||||
return name.to_owned();
|
||||
}
|
||||
let character = win_ansi(slot as u8);
|
||||
if glyph != 0 && face.glyph_index(character) == Some(GlyphId(glyph)) {
|
||||
format!("uni{:04X}", u32::from(character))
|
||||
let unicode = if let Some(subfont) = subfont {
|
||||
subfont.codes[slot]
|
||||
.filter(|_| subfont_cmap.is_some_and(|table| table.is_unicode()))
|
||||
.map(u32::from)
|
||||
} else {
|
||||
let character = win_ansi(slot as u8);
|
||||
(face.glyph_index(character) == Some(GlyphId(glyph)))
|
||||
.then_some(u32::from(character))
|
||||
};
|
||||
if let Some(code) =
|
||||
unicode.filter(|&code| glyph != 0 && char::from_u32(code).is_some())
|
||||
{
|
||||
format!("uni{code:04X}")
|
||||
} else {
|
||||
".notdef".to_owned()
|
||||
}
|
||||
@@ -139,11 +183,16 @@ pub(super) fn resolve(
|
||||
let bbox = face.global_bounding_box();
|
||||
let bbox = [bbox.x_min, bbox.y_min, bbox.x_max, bbox.y_max]
|
||||
.map(|value| 1000 * i32::from(value) / i32::from(face.units_per_em()));
|
||||
let missing_subfont_cmap = subfont
|
||||
.filter(|_| subfont_cmap.is_none())
|
||||
.map(|subfont| subfont.cmap);
|
||||
let program = TrueTypeProgram {
|
||||
name,
|
||||
data: data.into(),
|
||||
data,
|
||||
glyphs,
|
||||
reencoded,
|
||||
subfont_codes: subfont.map(|subfont| subfont.codes.clone()),
|
||||
missing_subfont_cmap,
|
||||
};
|
||||
Ok(NativeFontPaint {
|
||||
program: NativeFontProgram::TrueType(program),
|
||||
@@ -159,6 +208,16 @@ pub(super) fn resolve(
|
||||
})
|
||||
}
|
||||
|
||||
fn platform_number(platform: PlatformId) -> u16 {
|
||||
match platform {
|
||||
PlatformId::Unicode => 0,
|
||||
PlatformId::Macintosh => 1,
|
||||
PlatformId::Iso => 2,
|
||||
PlatformId::Windows => 3,
|
||||
PlatformId::Custom => 4,
|
||||
}
|
||||
}
|
||||
|
||||
fn builtin_glyph(face: &Face<'_>, slot: u8) -> GlyphId {
|
||||
let code = u32::from(slot);
|
||||
if let Some(cmap) = face.tables().cmap {
|
||||
|
||||
Reference in new issue
Block a user