Shape and render explicit OpenType fonts in native Unicode jobs
This commit is contained in:
1 parent
3caf1eced2
commit
70822cbd94
33 files changed
+1255
-80
No files matched your search
Generated
+78
@@ -271,6 +271,15 @@ version = "0.8.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
|
||||
|
||||
[[package]]
|
||||
name = "core_maths"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"
|
||||
dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
@@ -740,6 +749,12 @@ version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "libm"
|
||||
version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
||||
|
||||
[[package]]
|
||||
name = "linked-hash-map"
|
||||
version = "0.5.6"
|
||||
@@ -1094,6 +1109,24 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||
|
||||
[[package]]
|
||||
name = "rustybuzz"
|
||||
version = "0.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bytemuck",
|
||||
"core_maths",
|
||||
"log",
|
||||
"smallvec",
|
||||
"ttf-parser",
|
||||
"unicode-bidi-mirroring",
|
||||
"unicode-ccc",
|
||||
"unicode-properties",
|
||||
"unicode-script",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "0.9.0"
|
||||
@@ -1294,6 +1327,15 @@ version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "213701ba3370744dcd1a12960caa4843b3d68b4d1c0a5d575e0d65b2ee9d16c0"
|
||||
|
||||
[[package]]
|
||||
name = "subsetter"
|
||||
version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb6895a12ac5599bb6057362f00e8a3cf1daab4df33f553a55690a44e4fed8d0"
|
||||
dependencies = [
|
||||
"rustc-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "1.0.109"
|
||||
@@ -1442,9 +1484,12 @@ dependencies = [
|
||||
"md5",
|
||||
"png 0.18.1",
|
||||
"rusttype",
|
||||
"rustybuzz",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"subsetter",
|
||||
"unicode-bidi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1513,6 +1558,9 @@ name = "ttf-parser"
|
||||
version = "0.25.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
|
||||
dependencies = [
|
||||
"core_maths",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
@@ -1520,12 +1568,42 @@ version = "1.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-bidi"
|
||||
version = "0.3.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-bidi-mirroring"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ccc"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-properties"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-script"
|
||||
version = "0.5.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa04c955db05429d464c74d495c1ee677e1866e783a4c3747f9c0cef7756cabf"
|
||||
|
||||
[[package]]
|
||||
name = "unty"
|
||||
version = "0.0.4"
|
||||
|
||||
@@ -11,6 +11,9 @@ lopdf = "0.26"
|
||||
md5 = "0.8"
|
||||
png = "0.18.1"
|
||||
rusttype = "0.8.3"
|
||||
rustybuzz = "=0.20.1"
|
||||
subsetter = { version = "=0.2.3", default-features = false }
|
||||
unicode-bidi = "=0.3.18"
|
||||
serde = { version = "1.0", features = ["derive", "rc"] }
|
||||
serde_json = "1.0"
|
||||
sha2 = "=0.10.9"
|
||||
|
||||
@@ -332,6 +332,7 @@ impl NativeBox {
|
||||
TextNode::Glyph { glyph, .. }
|
||||
| TextNode::Box(glyph)
|
||||
| TextNode::MathChar(glyph) => HorizontalItem::Box(glyph.clone()),
|
||||
TextNode::OpenType(run) => HorizontalItem::Box(crate::opentype::horizontal_box(run)),
|
||||
TextNode::Rule(r) => {
|
||||
HorizontalItem::Box(r.horizontal_item(self.width, self.height, self.depth))
|
||||
}
|
||||
@@ -605,6 +606,11 @@ pub(super) fn hpack(
|
||||
height = height.max(glyph.height - shift);
|
||||
depth = depth.max(glyph.depth + shift);
|
||||
}
|
||||
TextNode::OpenType(run) => {
|
||||
width += run.width;
|
||||
height = height.max(run.font.ascent);
|
||||
depth = depth.max(run.font.descent);
|
||||
}
|
||||
TextNode::Rule(r) => {
|
||||
let (w, h, d) = r.dimensions();
|
||||
width += w;
|
||||
|
||||
@@ -133,6 +133,13 @@ impl NativeShipout {
|
||||
}
|
||||
let x = self.device.horizontal_origin + p.x;
|
||||
let y = self.device.vertical_origin + self.box_node.height + p.y;
|
||||
if let MathItem::OpenType(run) = p.item {
|
||||
run.paint(x, y, |value| value, |item, source| {
|
||||
page.sources.insert(page.items.len(), source);
|
||||
page.items.push(item);
|
||||
});
|
||||
return;
|
||||
}
|
||||
page.items.push(match p.item {
|
||||
MathItem::NativeGlyph {
|
||||
font,
|
||||
|
||||
@@ -13,6 +13,7 @@ pub enum DiagnosticNode {
|
||||
expansion: i32,
|
||||
ligature: Option<String>,
|
||||
},
|
||||
OpenType { font: FontId, text: String, glyphs: Vec<u16> },
|
||||
Box(DiagnosticBox),
|
||||
EmptyBox(i32),
|
||||
Glue {
|
||||
@@ -181,6 +182,10 @@ pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec<DiagnosticNode> {
|
||||
)
|
||||
}),
|
||||
},
|
||||
TextNode::OpenType(run) => DiagnosticNode::OpenType {
|
||||
font: run.font.id, text: run.text.clone(),
|
||||
glyphs: run.glyphs.iter().map(|glyph| glyph.id).collect(),
|
||||
},
|
||||
TextNode::Box(b) if b.native_box.is_some() => {
|
||||
DiagnosticNode::Box(box_view(b.native_box.as_ref().unwrap()))
|
||||
}
|
||||
@@ -474,6 +479,12 @@ impl Printer<'_> {
|
||||
self.literal(")");
|
||||
}
|
||||
}
|
||||
DiagnosticNode::OpenType { font, text, .. } => {
|
||||
let name = self.state.fonts.font(*font)?.identifier_text();
|
||||
self.command(&name);
|
||||
self.literal(" ");
|
||||
self.literal(text);
|
||||
}
|
||||
DiagnosticNode::Box(b) => self.box_(b, prefix)?,
|
||||
DiagnosticNode::EmptyBox(w) => {
|
||||
self.command("hbox");
|
||||
|
||||
@@ -1314,10 +1314,17 @@ impl Executor {
|
||||
Iffontchar => {
|
||||
let font = self.font_identifier(files)?;
|
||||
let slot = self.integer(files)?;
|
||||
let slot = u8::try_from(slot).map_err(|_| {
|
||||
self.error("font character code must be in 0..255", self.current)
|
||||
})?;
|
||||
self.state.font_has_slot(font, slot)
|
||||
let instance = self.state.fonts.font(font).map_err(|e| self.error(e, self.current))?;
|
||||
if let Some(font) = instance.opentype() {
|
||||
let character = u32::try_from(slot).ok().and_then(char::from_u32)
|
||||
.ok_or_else(|| self.error("font character code requires a Unicode scalar", self.current))?;
|
||||
font.face().map_err(|e| self.error(e, self.current))?.glyph_index(character).is_some()
|
||||
} else {
|
||||
let slot = u8::try_from(slot).map_err(|_| {
|
||||
self.error("font character code must be in 0..255", self.current)
|
||||
})?;
|
||||
self.state.font_has_slot(font, slot)
|
||||
}
|
||||
}
|
||||
Ifodd => self.integer(files)? % 2 != 0,
|
||||
Ifvmode | Ifhmode | Ifmmode | Ifinner => {
|
||||
@@ -3705,6 +3712,10 @@ impl Executor {
|
||||
return self
|
||||
.fail("PDF image objects require a job-local PDF device");
|
||||
}
|
||||
self.reads.insert(Dependency::FontResources);
|
||||
if self.state.fonts.fonts().iter().any(|font| font.opentype().is_some()) {
|
||||
return self.fail("cannot dump a format with native OpenType fonts");
|
||||
}
|
||||
self.format_dumped = true;
|
||||
}
|
||||
if self.native_page.is_some() {
|
||||
@@ -3782,11 +3793,16 @@ impl Executor {
|
||||
Setlanguage => self.set_language(files)?,
|
||||
Char => {
|
||||
let n = self.integer(files)?;
|
||||
let c = u8::try_from(n)
|
||||
.map_err(|_| self.error("char must be in 0..255", token.span))?;
|
||||
self.text_character(c as char, CatCode::Other, &token, files)?;
|
||||
let c = if self.state.input_profile() == super::InputProfile::UnicodeScalar {
|
||||
u32::try_from(n).ok().and_then(char::from_u32)
|
||||
.ok_or_else(|| self.error("char requires a Unicode scalar", token.span))?
|
||||
} else {
|
||||
char::from(u8::try_from(n)
|
||||
.map_err(|_| self.error("char must be in 0..255", token.span))?)
|
||||
};
|
||||
self.text_character(c, CatCode::Other, &token, files)?;
|
||||
self.events.push(Event::Character(Token {
|
||||
kind: TokenKind::Character(c as char, CatCode::Other),
|
||||
kind: TokenKind::Character(c, CatCode::Other),
|
||||
..token
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -70,6 +70,19 @@ impl Executor {
|
||||
}
|
||||
let font = self.font_identifier(files)?;
|
||||
let slot = self.integer(files)?;
|
||||
if let Some(face) = self.state.fonts.font(font).map_err(|e| self.error(e, self.current))?.opentype() {
|
||||
let character = u32::try_from(slot).ok().and_then(char::from_u32)
|
||||
.ok_or_else(|| self.error("invalid Unicode font character", self.current))?;
|
||||
let metrics = face.glyph_metrics(character)
|
||||
.map_err(|e| self.error(e, self.current))?.unwrap_or([0; 4]);
|
||||
return Ok(match p {
|
||||
Primitive::Fontcharwd => metrics[0],
|
||||
Primitive::Fontcharht => metrics[1],
|
||||
Primitive::Fontchardp => metrics[2],
|
||||
Primitive::Fontcharic => metrics[3],
|
||||
_ => unreachable!(),
|
||||
} as i32);
|
||||
}
|
||||
let slot = u8::try_from(slot)
|
||||
.map_err(|_| self.error("font character index must be in 0..255", self.current))?;
|
||||
let Some(m) = self
|
||||
|
||||
@@ -25,6 +25,7 @@ impl Tail {
|
||||
}
|
||||
TextNode::Penalty(n) => Self::Penalty(*n),
|
||||
TextNode::MarginKern { .. } => Self::Other(15),
|
||||
TextNode::OpenType(_) => Self::Other(9),
|
||||
TextNode::Glyph { ligature, .. } => Self::Other(if *ligature { 7 } else { 0 }),
|
||||
TextNode::MathChar(_) => Self::Other(0),
|
||||
TextNode::Box(b) => Self::Other(b.native_box.as_ref().map_or(1, |b| {
|
||||
|
||||
@@ -284,13 +284,18 @@ impl Executor {
|
||||
i64::from(self.read_parameter(Parameter::Pdfvorigin).width()) + v_offset;
|
||||
let mut page_width = i64::from(self.read_parameter(Parameter::Pdfpagewidth).width());
|
||||
let requested_page_height = i64::from(self.read_parameter(Parameter::Pdfpageheight).width());
|
||||
let unicode_pages = self.state.input_profile() == super::super::InputProfile::UnicodeScalar;
|
||||
// The XeTeX PDF device uses the default letter canvas unless a page size was supplied.
|
||||
let default_canvas = |bp: i64| bp * 803 * 65536 / 800;
|
||||
if page_width == 0 {
|
||||
page_width = b.width + 2 * horizontal_origin;
|
||||
page_width = if unicode_pages { default_canvas(612) } else { b.width + 2 * horizontal_origin };
|
||||
}
|
||||
let page_height = if requested_page_height == 0 {
|
||||
b.height + b.depth + 2 * vertical_origin
|
||||
} else {
|
||||
let page_height = if requested_page_height != 0 {
|
||||
requested_page_height
|
||||
} else if unicode_pages {
|
||||
default_canvas(792)
|
||||
} else {
|
||||
b.height + b.depth + 2 * vertical_origin
|
||||
};
|
||||
let device = ShipoutDevice {
|
||||
magnification,
|
||||
|
||||
@@ -350,15 +350,26 @@ impl Executor {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let slot=u8::try_from(c as u32).map_err(|_|self.error("native text font character requires an 8-bit slot; Unicode shaping is not implemented",token.span))?;
|
||||
let font = self.state.text_font();
|
||||
let opentype = if self.state.input_profile() == super::super::InputProfile::UnicodeScalar {
|
||||
self.state.fonts.font(font).map_err(|e| self.error(e, token.span))?.opentype().cloned()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let slot = u8::try_from(c as u32).ok();
|
||||
if slot.is_none() && opentype.is_none() {
|
||||
return Err(self.error("native TFM text font requires an 8-bit character slot", token.span));
|
||||
}
|
||||
if self.paragraph.is_none() {
|
||||
self.begin_paragraph(token.invocation.unwrap_or(token.span), true)?;
|
||||
}
|
||||
self.reads.insert(Dependency::SfCode(slot));
|
||||
self.paragraph
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.adjust_space_factor(self.state.sfcode(slot));
|
||||
let space_factor = if let Some(slot) = slot {
|
||||
self.reads.insert(Dependency::SfCode(slot));
|
||||
self.state.sfcode(slot)
|
||||
} else {
|
||||
1000
|
||||
};
|
||||
self.paragraph.as_mut().unwrap().adjust_space_factor(space_factor);
|
||||
if !self.restricted() {
|
||||
let language = HyphenationLanguage::from_state(&self.state);
|
||||
let b = self.paragraph.as_mut().unwrap();
|
||||
@@ -375,8 +386,12 @@ impl Executor {
|
||||
}
|
||||
}
|
||||
self.reads.insert(Dependency::FontResources);
|
||||
let font = self.state.text_font();
|
||||
self.reads.insert(Dependency::TextFont);
|
||||
if let Some(font) = opentype {
|
||||
return self.paragraph.as_mut().unwrap()
|
||||
.opentype_character(c, TokenOrigin::from(token), &self.state, font)
|
||||
.map_err(|e| self.error(e, token.invocation.unwrap_or(token.span)));
|
||||
}
|
||||
let missing = self
|
||||
.paragraph
|
||||
.as_mut()
|
||||
@@ -649,11 +664,16 @@ impl Executor {
|
||||
self.reads.insert(Dependency::FontResources);
|
||||
let defaults = self.font_defaults();
|
||||
let from = self.sources[self.current.source].name.clone();
|
||||
let font = self
|
||||
.state
|
||||
.fonts
|
||||
.load(files, &file, &from, size, name.clone(), defaults)
|
||||
.map_err(|e| self.error(e, self.current))?;
|
||||
let request = if self.state.input_profile() == super::super::InputProfile::UnicodeScalar {
|
||||
crate::opentype::Request::parse(&file).map_err(|e| self.error(e, self.current))?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let font = if let Some(request) = request {
|
||||
self.state.fonts.load_opentype(files, &file, request, &from, size, name.clone(), defaults)
|
||||
} else {
|
||||
self.state.fonts.load(files, &file, &from, size, name.clone(), defaults)
|
||||
}.map_err(|e| self.error(e, self.current))?;
|
||||
self.define_traced(name, Meaning::Font(font), global, files)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use super::{CommandName, Flex, FontIntegers, Glue, Parameter, SourceProvider, State};
|
||||
use crate::{
|
||||
native_font::{LetterspaceProgram, NativeFont},
|
||||
opentype::{OpenTypeFont, Request},
|
||||
resources::{LoadedResource, ResourceKind, ResourceVersion},
|
||||
tfm::{FontSize, TfmMetrics},
|
||||
};
|
||||
@@ -26,7 +27,7 @@ impl FontId {
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FontResource {
|
||||
pub version: ResourceVersion,
|
||||
/// Exact TFM bytes; retained for format/dependency validation, not recreated
|
||||
/// Exact font bytes; retained for format/dependency validation, not recreated
|
||||
/// from a font name or the parsed metrics.
|
||||
pub data: Arc<Vec<u8>>,
|
||||
}
|
||||
@@ -37,6 +38,8 @@ pub struct FontInstance {
|
||||
area: String,
|
||||
resource: Option<usize>,
|
||||
glyph_font: Option<Arc<crate::native_font::NativeFont>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
opentype: Option<Arc<OpenTypeFont>>,
|
||||
parameters: Arc<Vec<i32>>,
|
||||
integers: FontIntegers,
|
||||
selector: CommandName,
|
||||
@@ -53,7 +56,10 @@ impl FontInstance {
|
||||
&self.area
|
||||
}
|
||||
pub fn size_sp(&self) -> i64 {
|
||||
self.metrics().map_or(0, TfmMetrics::size_sp)
|
||||
self.opentype.as_ref().map_or_else(|| self.metrics().map_or(0, TfmMetrics::size_sp), |font| font.size)
|
||||
}
|
||||
pub fn opentype(&self) -> Option<&Arc<OpenTypeFont>> {
|
||||
self.opentype.as_ref()
|
||||
}
|
||||
pub fn metrics(&self) -> Option<&TfmMetrics> {
|
||||
self.glyph_font.as_ref().map(|f| f.metrics())
|
||||
@@ -78,13 +84,13 @@ impl FontInstance {
|
||||
}
|
||||
}
|
||||
pub fn fontname(&self) -> String {
|
||||
match self.metrics() {
|
||||
Some(m) if m.size_sp() != m.design_size_sp() => format!(
|
||||
"{} at {}pt",
|
||||
self.name,
|
||||
super::registers::print_scaled(m.size_sp() as i32)
|
||||
),
|
||||
_ => self.name.clone(),
|
||||
let size = self.size_sp();
|
||||
let design = self.opentype.as_ref().map_or_else(
|
||||
|| self.metrics().map_or(size, TfmMetrics::design_size_sp), |font| font.design_size);
|
||||
if size != design {
|
||||
format!("{} at {}pt", self.name, super::registers::print_scaled(size as i32))
|
||||
} else {
|
||||
self.name.clone()
|
||||
}
|
||||
}
|
||||
/// Fresh glue takes the live parameters. Previously returned glue remains
|
||||
@@ -228,6 +234,7 @@ impl FontCatalog {
|
||||
area: String::new(),
|
||||
resource: None,
|
||||
glyph_font: None,
|
||||
opentype: None,
|
||||
parameters: Arc::new(vec![0; 7]),
|
||||
integers: FontIntegers {
|
||||
hyphen: 45,
|
||||
@@ -307,12 +314,11 @@ impl FontCatalog {
|
||||
for (index, f) in self.fonts.iter_mut().enumerate().skip(1) {
|
||||
// A font attached to an expansion family has an internal
|
||||
// identity. A later explicit definition loads a separate font.
|
||||
if f.name == name && f.area == area && f.expansion_origin.is_none() {
|
||||
let m = f.metrics().unwrap();
|
||||
if m.requested_size(size).is_ok_and(|n| n == m.size_sp()) {
|
||||
f.selector = selector;
|
||||
return Ok(FontId(index as u32));
|
||||
}
|
||||
if f.name == name && f.area == area && f.expansion_origin.is_none()
|
||||
&& f.metrics().is_some_and(|m| m.requested_size(size).is_ok_and(|n| n == m.size_sp()))
|
||||
{
|
||||
f.selector = selector;
|
||||
return Ok(FontId(index as u32));
|
||||
}
|
||||
}
|
||||
self.check_font_capacity()?;
|
||||
@@ -320,6 +326,68 @@ impl FontCatalog {
|
||||
self.insert_font((name, area), loaded, metrics, selector, defaults, None)
|
||||
}
|
||||
|
||||
pub(super) fn load_opentype(
|
||||
&mut self,
|
||||
files: &mut impl SourceProvider,
|
||||
spec: &str,
|
||||
request: Request,
|
||||
from: &str,
|
||||
size: FontSize,
|
||||
selector: CommandName,
|
||||
defaults: FontIntegers,
|
||||
) -> Result<FontId, String> {
|
||||
size.validate()?;
|
||||
for (index, instance) in self.fonts.iter_mut().enumerate() {
|
||||
if let Some(font) = &instance.opentype
|
||||
&& instance.name == spec
|
||||
&& font.requested_size(size) == font.size
|
||||
{
|
||||
instance.selector = selector;
|
||||
return Ok(FontId(index as u32));
|
||||
}
|
||||
}
|
||||
self.check_font_capacity()?;
|
||||
if self.limits.parameter_words - self.parameter_words < 8 {
|
||||
return Err("native font parameter capacity exceeded".into());
|
||||
}
|
||||
let names = request.resource_names();
|
||||
let loaded = if let [(kind, name)] = &names[..] {
|
||||
files.resource(*kind, name, from)?
|
||||
} else {
|
||||
let mut selected = None;
|
||||
for (kind, name) in &names {
|
||||
if let Some(resource) = files.optional_font_file(*kind, name, from)? {
|
||||
selected = Some(resource);
|
||||
break;
|
||||
}
|
||||
}
|
||||
selected.ok_or_else(|| format!("OpenType font file not found: {}", request.file))?
|
||||
};
|
||||
if loaded.version.bytes != loaded.data.len() as u64
|
||||
|| loaded.version.sha256 != format!("{:x}", Sha256::digest(&loaded.data))
|
||||
{
|
||||
return Err("font resource version does not match its actual OpenType bytes".into());
|
||||
}
|
||||
let resource = FontResource { version: loaded.version, data: Arc::new(loaded.data) };
|
||||
let id = FontId(self.fonts.len() as u32);
|
||||
let (font, parameters) = OpenTypeFont::new(id, resource, request, size)?;
|
||||
let resource = self.intern_resource(font.resource.clone());
|
||||
self.fonts.push(FontInstance {
|
||||
name: spec.to_owned(),
|
||||
area: String::new(),
|
||||
resource: Some(resource),
|
||||
glyph_font: None,
|
||||
opentype: Some(Arc::new(font)),
|
||||
parameters: Arc::new(parameters.to_vec()),
|
||||
integers: defaults,
|
||||
selector,
|
||||
expansion_origin: None,
|
||||
automatic_expansion: false,
|
||||
});
|
||||
self.parameter_words += parameters.len();
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// The PDF device reads a new design-size font directly, as opposed to
|
||||
/// an explicit font definition which may reuse an existing instance.
|
||||
pub(super) fn load_pdf_space(
|
||||
@@ -411,6 +479,15 @@ impl FontCatalog {
|
||||
Ok((loaded, metrics))
|
||||
}
|
||||
|
||||
fn intern_resource(&mut self, resource: FontResource) -> usize {
|
||||
if let Some(index) = self.resources.iter().position(|current| current.version == resource.version) {
|
||||
return index;
|
||||
}
|
||||
let index = self.resources.len();
|
||||
self.resources.push(resource);
|
||||
index
|
||||
}
|
||||
|
||||
fn insert_font(
|
||||
&mut self,
|
||||
(name, area): (&str, &str),
|
||||
@@ -425,21 +502,10 @@ impl FontCatalog {
|
||||
return Err("native font parameter capacity exceeded".into());
|
||||
}
|
||||
let parameters = (0..count).map(|i| metrics.param(i) as i32).collect();
|
||||
let resource = match self
|
||||
.resources
|
||||
.iter()
|
||||
.position(|r| r.version == loaded.version)
|
||||
{
|
||||
Some(i) => i,
|
||||
None => {
|
||||
let i = self.resources.len();
|
||||
self.resources.push(FontResource {
|
||||
version: loaded.version,
|
||||
data: Arc::new(loaded.data),
|
||||
});
|
||||
i
|
||||
}
|
||||
};
|
||||
let resource = self.intern_resource(FontResource {
|
||||
version: loaded.version,
|
||||
data: Arc::new(loaded.data),
|
||||
});
|
||||
let id = FontId(self.fonts.len() as u32);
|
||||
let glyph_font = Arc::new(NativeFont {
|
||||
id,
|
||||
@@ -456,6 +522,7 @@ impl FontCatalog {
|
||||
area: area.into(),
|
||||
resource: Some(resource),
|
||||
glyph_font: Some(glyph_font),
|
||||
opentype: None,
|
||||
parameters: Arc::new(parameters),
|
||||
integers: defaults,
|
||||
selector,
|
||||
@@ -705,6 +772,7 @@ impl FontCatalog {
|
||||
self.fonts.push(FontInstance {
|
||||
name,
|
||||
glyph_font: Some(glyph_font),
|
||||
opentype: None,
|
||||
expansion_origin: Some((base, amount)),
|
||||
automatic_expansion: true,
|
||||
..font.clone()
|
||||
|
||||
@@ -8,9 +8,9 @@ use std::{
|
||||
sync::{Arc, Mutex, OnceLock, Weak},
|
||||
};
|
||||
|
||||
const SCHEMA: u32 = 55;
|
||||
const COMPATIBLE_SCHEMAS: [u32; 24] = [
|
||||
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, SCHEMA,
|
||||
const SCHEMA: u32 = 56;
|
||||
const COMPATIBLE_SCHEMAS: [u32; 25] = [
|
||||
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, SCHEMA,
|
||||
];
|
||||
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
@@ -132,8 +132,8 @@ impl FormatImage {
|
||||
}
|
||||
if image.schema < 55 {
|
||||
image.state.restore_legacy_font_map_commands();
|
||||
image.schema = SCHEMA;
|
||||
}
|
||||
image.schema = SCHEMA;
|
||||
Ok(image)
|
||||
}
|
||||
|
||||
|
||||
@@ -853,7 +853,12 @@ pub(crate) fn paint_geometry(
|
||||
use super::boxes::bp;
|
||||
use crate::render::DisplayItem;
|
||||
for p in &g.items {
|
||||
if let MathItem::OpenType(run) = &p.item {
|
||||
run.paint(ox + bp(x + p.x), oy + bp(y + p.y), bp, |item, _| out.push(item));
|
||||
continue;
|
||||
}
|
||||
out.push(match &p.item {
|
||||
MathItem::OpenType(_) => unreachable!("OpenType run handled before scalar paint"),
|
||||
MathItem::NativeGlyph {
|
||||
font,
|
||||
slot,
|
||||
|
||||
@@ -250,6 +250,12 @@ pub trait SourceProvider {
|
||||
) -> Result<Option<crate::resources::LoadedResource>, String> {
|
||||
Ok(None)
|
||||
}
|
||||
/// An exact lookup that can report a missing font file before trying another format.
|
||||
fn optional_font_file(
|
||||
&mut self, kind: crate::resources::ResourceKind, name: &str, from: &str,
|
||||
) -> Result<Option<crate::resources::LoadedResource>, String> {
|
||||
self.resource(kind, name, from).map(Some)
|
||||
}
|
||||
/// Read an actual PDF font map. A host that can distinguish missing
|
||||
/// files from other failures can return None for TeX's warning path.
|
||||
fn optional_font_map(
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Native horizontal material and paragraph breaking. No command/string parser.
|
||||
use super::*;
|
||||
use crate::{HorizontalBox, Paragraph, ParagraphFont};
|
||||
use std::collections::BTreeMap;
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
use crate::opentype::{OpenTypeFont, OpenTypeRun};
|
||||
|
||||
mod break_cache;
|
||||
mod expansion;
|
||||
@@ -42,6 +43,7 @@ pub enum TextNode {
|
||||
component_sources: Vec<crate::provenance::PaintSource>,
|
||||
hyphen_char: Option<char>,
|
||||
},
|
||||
OpenType(Arc<OpenTypeRun>),
|
||||
Box(HorizontalBox),
|
||||
Rule(NativeRule),
|
||||
Mark(NativeMark),
|
||||
@@ -118,6 +120,7 @@ pub(super) struct Builder {
|
||||
pub space_factor: i32,
|
||||
pub hyphen_min: (usize, usize),
|
||||
run: Option<FontRun>,
|
||||
opentype: Option<PendingOpenType>,
|
||||
pub cancel_boundary: bool,
|
||||
pub font_steps: usize,
|
||||
pub font_step_limit: usize,
|
||||
@@ -131,14 +134,21 @@ struct FontRun {
|
||||
machine: super::ligature::Machine,
|
||||
hyphen_char: Option<char>,
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
struct PendingOpenType {
|
||||
font: Arc<OpenTypeFont>,
|
||||
text: String,
|
||||
utf16_units: usize,
|
||||
sources: Vec<(usize, crate::provenance::PaintSource)>,
|
||||
}
|
||||
impl Builder {
|
||||
pub(super) fn has_unpacked_text(&self) -> bool {
|
||||
self.run
|
||||
.as_ref()
|
||||
self.opentype.is_some() || self.run.as_ref()
|
||||
.is_some_and(|run| run.machine.has_unpacked_components())
|
||||
}
|
||||
pub(super) fn ligature_work_items(&self) -> usize {
|
||||
self.run.as_ref().map_or(0, |r| r.machine.resource_items())
|
||||
+ self.opentype.as_ref().map_or(0, |run| run.sources.len())
|
||||
}
|
||||
pub fn start(&mut self, state: &State, span: Span, indent: bool) {
|
||||
self.span = span;
|
||||
@@ -227,6 +237,13 @@ impl Builder {
|
||||
missing
|
||||
}
|
||||
pub fn finish_text(&mut self, right_boundary: bool, state: &State) -> Result<(), String> {
|
||||
if let Some(run) = self.opentype.take() {
|
||||
let shaped = run.font.shape(run.text, run.sources)?;
|
||||
self.font_steps = self.font_steps.checked_add(shaped.glyphs.len())
|
||||
.filter(|steps| *steps <= self.font_step_limit)
|
||||
.ok_or("native OpenType shaping step limit exceeded")?;
|
||||
self.nodes.push(TextNode::OpenType(Arc::new(shaped)));
|
||||
}
|
||||
if let Some(mut run) = self.run.take() {
|
||||
run.machine
|
||||
.put_carry(std::mem::take(&mut self.ligature_carry));
|
||||
@@ -245,6 +262,25 @@ impl Builder {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn opentype_character(
|
||||
&mut self, c: char, origin: TokenOrigin, state: &State, font: Arc<OpenTypeFont>,
|
||||
) -> Result<(), String> {
|
||||
if self.run.is_some() || self.opentype.as_ref().is_some_and(|r| r.font.id != font.id) {
|
||||
self.finish_text(true, state)?;
|
||||
}
|
||||
self.cancel_boundary = false;
|
||||
let run = self.opentype.get_or_insert_with(|| PendingOpenType {
|
||||
font, text: String::new(), utf16_units: 0, sources: Vec::new(),
|
||||
});
|
||||
// Native words carry a 16-bit character count in XeTeX.
|
||||
run.utf16_units += c.len_utf16();
|
||||
if run.utf16_units > u16::MAX as usize {
|
||||
return Err("native OpenType word capacity exceeded".into());
|
||||
}
|
||||
run.sources.push((run.text.len(), crate::provenance::PaintSource::token(origin)));
|
||||
run.text.push(c);
|
||||
Ok(())
|
||||
}
|
||||
pub fn character(
|
||||
&mut self,
|
||||
c: char,
|
||||
@@ -253,6 +289,9 @@ impl Builder {
|
||||
font: FontId,
|
||||
hyphen_char: Option<char>,
|
||||
) -> Result<Vec<super::ligature::Component>, String> {
|
||||
if self.opentype.is_some() {
|
||||
self.finish_text(true, state)?;
|
||||
}
|
||||
let c = super::ligature::Component {
|
||||
slot: c as u8,
|
||||
origin: origin.span,
|
||||
@@ -396,6 +435,7 @@ fn width(n: &TextNode) -> i64 {
|
||||
TextNode::Glyph { glyph, .. } | TextNode::Box(glyph) | TextNode::MathChar(glyph) => {
|
||||
glyph.width
|
||||
}
|
||||
TextNode::OpenType(run) => run.width,
|
||||
TextNode::Glue(g)
|
||||
| TextNode::NamedGlue(g, _)
|
||||
| TextNode::Leaders(LeaderGlue { glue: g, .. }) => g.width as i64,
|
||||
@@ -1042,6 +1082,7 @@ fn pre_display_line_size(
|
||||
n,
|
||||
TextNode::Glyph { .. }
|
||||
| TextNode::Box(_)
|
||||
| TextNode::OpenType(_)
|
||||
| TextNode::MathChar(_)
|
||||
| TextNode::Indent(_)
|
||||
| TextNode::Rule(_)
|
||||
|
||||
@@ -142,6 +142,7 @@ impl BreakNode {
|
||||
TextNode::Language(_)
|
||||
| TextNode::Glyph { .. }
|
||||
| TextNode::Box(_)
|
||||
| TextNode::OpenType(_)
|
||||
| TextNode::Rule(_)
|
||||
| TextNode::Mark(_)
|
||||
| TextNode::Adjustment(_)
|
||||
|
||||
@@ -187,6 +187,7 @@ impl Tracer {
|
||||
let character = (*slot as char).to_string();
|
||||
self.character(state, *font, if *ligature { original } else { &character }, out)?;
|
||||
}
|
||||
TextNode::OpenType(run) => self.character(state, run.font.id, &run.text, out)?,
|
||||
TextNode::MathChar(b) => {
|
||||
if let Some(g) = &b.math_geometry
|
||||
&& g.items.len() == 1
|
||||
|
||||
@@ -4,6 +4,7 @@ pub mod execution;
|
||||
pub mod math;
|
||||
pub mod math_engine_tex;
|
||||
pub mod math_font;
|
||||
pub mod opentype;
|
||||
pub mod native_font;
|
||||
pub mod output;
|
||||
pub mod page;
|
||||
|
||||
@@ -192,6 +192,7 @@ impl MathParams {
|
||||
/// alone cannot identify the large CMEX variant or the 7pt/5pt optical masters.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum MathItem {
|
||||
OpenType(std::sync::Arc<crate::opentype::OpenTypeRun>),
|
||||
PdfImage(std::sync::Arc<crate::pdf_image::PdfImageUse>),
|
||||
NativeGlyph {
|
||||
font: std::sync::Arc<crate::native_font::NativeFont>,
|
||||
|
||||
@@ -0,0 +1,461 @@
|
||||
//! Sized OpenType faces and shaped runs for native XeTeX text.
|
||||
use crate::{
|
||||
execution::{FontId, FontResource},
|
||||
provenance::PaintSource,
|
||||
resources::ResourceKind,
|
||||
tfm::FontSize,
|
||||
};
|
||||
use rustybuzz::{
|
||||
Direction, Face, Feature, Language, Script, UnicodeBuffer,
|
||||
ttf_parser::{self, GlyphId, Tag},
|
||||
};
|
||||
use std::{
|
||||
hash::{Hash, Hasher},
|
||||
path::Path,
|
||||
sync::Arc,
|
||||
};
|
||||
use unicode_bidi::BidiInfo;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) struct Request {
|
||||
pub file: String,
|
||||
pub index: u32,
|
||||
features: Vec<String>,
|
||||
script: Option<String>,
|
||||
language: Option<String>,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
pub(crate) fn parse(spec: &str) -> Result<Option<Self>, String> {
|
||||
let Some(bracketed) = spec.strip_prefix('[') else {
|
||||
return Ok(None);
|
||||
};
|
||||
let (file, options) = bracketed
|
||||
.split_once(']')
|
||||
.ok_or("OpenType font requires a closing bracket")?;
|
||||
let (file, index) = match file.rsplit_once(':') {
|
||||
Some((path, index))
|
||||
if !index.is_empty() && index.bytes().all(|c| c.is_ascii_digit()) =>
|
||||
{
|
||||
(
|
||||
path,
|
||||
index
|
||||
.parse::<u32>()
|
||||
.map_err(|_| "OpenType face index is out of range")?,
|
||||
)
|
||||
}
|
||||
_ => (file, 0),
|
||||
};
|
||||
if file.is_empty() {
|
||||
return Err("missing OpenType filename".into());
|
||||
}
|
||||
let options = options.strip_prefix("/OT").unwrap_or(options);
|
||||
let features = if options.is_empty() {
|
||||
""
|
||||
} else {
|
||||
options
|
||||
.strip_prefix(':')
|
||||
.ok_or("unsupported OpenType font selector")?
|
||||
};
|
||||
let mut request = Self {
|
||||
file: file.to_owned(),
|
||||
index,
|
||||
features: Vec::new(),
|
||||
script: None,
|
||||
language: None,
|
||||
};
|
||||
for feature in features
|
||||
.split([';', ','])
|
||||
.map(str::trim)
|
||||
.filter(|part| !part.is_empty())
|
||||
{
|
||||
if let Some(script) = feature.strip_prefix("script=") {
|
||||
if script.len() != 4 || !script.is_ascii() {
|
||||
return Err(format!("invalid OpenType script tag: {script}"));
|
||||
}
|
||||
request.script = Some(script.to_owned());
|
||||
} else if let Some(language) = feature.strip_prefix("language=") {
|
||||
request.language = Some(language.to_owned());
|
||||
} else {
|
||||
feature
|
||||
.parse::<Feature>()
|
||||
.map_err(|_| format!("unsupported OpenType font option: {feature}"))?;
|
||||
request.features.push(feature.to_owned());
|
||||
}
|
||||
}
|
||||
Ok(Some(request))
|
||||
}
|
||||
|
||||
pub(crate) fn resource_names(&self) -> Vec<(ResourceKind, String)> {
|
||||
match Path::new(&self.file)
|
||||
.extension()
|
||||
.and_then(|ext| ext.to_str())
|
||||
{
|
||||
Some(ext)
|
||||
if ["otf", "otc"]
|
||||
.iter()
|
||||
.any(|suffix| ext.eq_ignore_ascii_case(suffix)) =>
|
||||
{
|
||||
vec![(ResourceKind::OpenType, self.file.clone())]
|
||||
}
|
||||
Some(_) => vec![(ResourceKind::TrueType, self.file.clone())],
|
||||
None => vec![
|
||||
(ResourceKind::OpenType, format!("{}.otf", self.file)),
|
||||
(ResourceKind::TrueType, format!("{}.ttf", self.file)),
|
||||
(ResourceKind::TrueType, format!("{}.ttc", self.file)),
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct OpenTypeFont {
|
||||
pub id: FontId,
|
||||
pub resource: FontResource,
|
||||
pub name: String,
|
||||
pub size: i64,
|
||||
pub design_size: i64,
|
||||
pub ascent: i64,
|
||||
pub descent: i64,
|
||||
request: Request,
|
||||
}
|
||||
|
||||
impl PartialEq for OpenTypeFont {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
(self.id, &self.resource.version, &self.request, self.size)
|
||||
== (
|
||||
other.id,
|
||||
&other.resource.version,
|
||||
&other.request,
|
||||
other.size,
|
||||
)
|
||||
}
|
||||
}
|
||||
impl Eq for OpenTypeFont {}
|
||||
impl Hash for OpenTypeFont {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
(self.id, &self.resource.version, &self.request, self.size).hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl OpenTypeFont {
|
||||
pub(crate) fn new(
|
||||
id: FontId,
|
||||
resource: FontResource,
|
||||
request: Request,
|
||||
size: FontSize,
|
||||
) -> Result<(Self, [i32; 8]), String> {
|
||||
let face = ttf_parser::Face::parse(&resource.data, request.index).map_err(|error| {
|
||||
format!(
|
||||
"invalid OpenType face {}: {error}",
|
||||
resource.version.path.display()
|
||||
)
|
||||
})?;
|
||||
let name = face
|
||||
.names()
|
||||
.into_iter()
|
||||
.filter(|name| name.name_id == ttf_parser::name_id::POST_SCRIPT_NAME)
|
||||
.find_map(|name| name.to_string())
|
||||
.ok_or("OpenType face has no PostScript name")?;
|
||||
// Native file fonts use 10pt unless they declare an optical design size.
|
||||
let design_size = 10 * 65_536;
|
||||
let size = match size {
|
||||
FontSize::At(size) => size,
|
||||
FontSize::Design => design_size,
|
||||
FontSize::Scaled(ratio) => design_size * i64::from(ratio) / 1000,
|
||||
};
|
||||
FontSize::At(size).validate()?;
|
||||
let scale = |value| scale_units(value, size, face.units_per_em());
|
||||
let hhea = face.tables().hhea;
|
||||
let ascent = scale(i64::from(hhea.ascender));
|
||||
let descent = -scale(i64::from(hhea.descender));
|
||||
let xheight = |reported: Option<i16>, letter: char, fallback: i64| {
|
||||
reported.map_or_else(
|
||||
|| {
|
||||
face.glyph_index(letter)
|
||||
.and_then(|glyph| face.glyph_bounding_box(glyph))
|
||||
.map_or(fallback, |bounds| scale(i64::from(bounds.y_max)))
|
||||
},
|
||||
|value| scale(i64::from(value)),
|
||||
)
|
||||
};
|
||||
let advance = |character| {
|
||||
face.glyph_index(character)
|
||||
.and_then(|id| face.glyph_hor_advance(id))
|
||||
.map_or(0, |w| scale(i64::from(w)))
|
||||
};
|
||||
let space = advance(' ');
|
||||
let slant = (-f64::from(face.italic_angle()).to_radians().tan() * 65536.).round() as i32;
|
||||
let params = [
|
||||
slant,
|
||||
space as i32,
|
||||
(space / 2) as i32,
|
||||
(space / 3) as i32,
|
||||
xheight(face.x_height(), 'x', ascent / 2) as i32,
|
||||
size as i32,
|
||||
(space / 3) as i32,
|
||||
xheight(face.capital_height(), 'X', ascent) as i32,
|
||||
];
|
||||
Ok((
|
||||
Self {
|
||||
id,
|
||||
resource,
|
||||
name,
|
||||
size,
|
||||
design_size,
|
||||
ascent,
|
||||
descent,
|
||||
request,
|
||||
},
|
||||
params,
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn requested_size(&self, size: FontSize) -> i64 {
|
||||
match size {
|
||||
FontSize::At(size) => size,
|
||||
FontSize::Design => self.design_size,
|
||||
FontSize::Scaled(ratio) => self.design_size * i64::from(ratio) / 1000,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn face(&self) -> Result<ttf_parser::Face<'_>, String> {
|
||||
ttf_parser::Face::parse(&self.resource.data, self.request.index).map_err(|error| {
|
||||
format!(
|
||||
"invalid OpenType face {}: {error}",
|
||||
self.resource.version.path.display()
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn face_index(&self) -> u32 {
|
||||
self.request.index
|
||||
}
|
||||
|
||||
pub(crate) fn glyph_metrics(&self, character: char) -> Result<Option<[i64; 4]>, String> {
|
||||
let face = self.face()?;
|
||||
let Some(id) = face.glyph_index(character) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let bounds = face.glyph_bounding_box(id);
|
||||
let advance = face.glyph_hor_advance(id).unwrap_or(0);
|
||||
let italic = bounds
|
||||
.map_or(0, |bounds| i64::from(bounds.x_max) - i64::from(advance))
|
||||
.max(0);
|
||||
Ok(Some([
|
||||
scale_units(i64::from(advance), self.size, face.units_per_em()),
|
||||
scale_units(
|
||||
i64::from(bounds.map_or(0, |b| b.y_max)),
|
||||
self.size,
|
||||
face.units_per_em(),
|
||||
),
|
||||
-scale_units(
|
||||
i64::from(bounds.map_or(0, |b| b.y_min)),
|
||||
self.size,
|
||||
face.units_per_em(),
|
||||
),
|
||||
scale_units(italic, self.size, face.units_per_em()),
|
||||
]))
|
||||
}
|
||||
|
||||
pub(crate) fn shape(
|
||||
self: &Arc<Self>,
|
||||
text: String,
|
||||
sources: Vec<(usize, PaintSource)>,
|
||||
) -> Result<OpenTypeRun, String> {
|
||||
let face = Face::from_slice(&self.resource.data, self.request.index)
|
||||
.ok_or("invalid OpenType shaping face")?;
|
||||
let features: Vec<_> = self
|
||||
.request
|
||||
.features
|
||||
.iter()
|
||||
.map(|feature| feature.parse::<Feature>())
|
||||
.collect::<Result<_, _>>()
|
||||
.map_err(|_| "invalid OpenType feature in job state")?;
|
||||
let script = self
|
||||
.request
|
||||
.script
|
||||
.as_deref()
|
||||
.and_then(|tag| Script::from_iso15924_tag(Tag::from_bytes_lossy(tag.as_bytes())));
|
||||
let language = self
|
||||
.request
|
||||
.language
|
||||
.as_deref()
|
||||
.and_then(|tag| tag.parse::<Language>().ok());
|
||||
let bidi = BidiInfo::new(&text, None);
|
||||
let mut glyphs = Vec::new();
|
||||
let mut x_origin = 0;
|
||||
let scale = |value: i64| scale_units(value, self.size, face.tables().head.units_per_em);
|
||||
for paragraph in &bidi.paragraphs {
|
||||
let (levels, runs) = bidi.visual_runs(paragraph, paragraph.range.clone());
|
||||
for range in runs {
|
||||
let mut buffer = UnicodeBuffer::new();
|
||||
buffer.push_str(&text[range.clone()]);
|
||||
buffer.set_direction(if levels[range.start].is_rtl() {
|
||||
Direction::RightToLeft
|
||||
} else {
|
||||
Direction::LeftToRight
|
||||
});
|
||||
if let Some(script) = script {
|
||||
buffer.set_script(script);
|
||||
}
|
||||
if let Some(language) = &language {
|
||||
buffer.set_language(language.clone());
|
||||
}
|
||||
buffer.guess_segment_properties();
|
||||
let shaped = rustybuzz::shape(&face, &features, buffer);
|
||||
let mut starts: Vec<_> = shaped
|
||||
.glyph_infos()
|
||||
.iter()
|
||||
.map(|info| range.start + info.cluster as usize)
|
||||
.collect();
|
||||
starts.push(range.end);
|
||||
starts.sort_unstable();
|
||||
starts.dedup();
|
||||
let mut x = 0;
|
||||
let mut y = 0;
|
||||
let mut previous = usize::MAX;
|
||||
for (info, pos) in shaped.glyph_infos().iter().zip(shaped.glyph_positions()) {
|
||||
let cluster = range.start + info.cluster as usize;
|
||||
let end = starts[starts.partition_point(|at| *at <= cluster)];
|
||||
glyphs.push(OpenTypeGlyph {
|
||||
id: info.glyph_id as u16,
|
||||
x: x_origin + scale(x + i64::from(pos.x_offset)),
|
||||
y: scale(-y - i64::from(pos.y_offset)),
|
||||
advance: scale(x + i64::from(pos.x_advance)) - scale(x),
|
||||
cluster: cluster..end,
|
||||
cluster_start: cluster != previous,
|
||||
});
|
||||
x += i64::from(pos.x_advance);
|
||||
y += i64::from(pos.y_advance);
|
||||
previous = cluster;
|
||||
}
|
||||
x_origin += scale(x);
|
||||
}
|
||||
}
|
||||
Ok(OpenTypeRun {
|
||||
font: self.clone(),
|
||||
text,
|
||||
glyphs,
|
||||
width: x_origin,
|
||||
sources,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn scale_units(value: i64, size: i64, units: u16) -> i64 {
|
||||
let points = (value as f32 * (size as f32 / 65536.)) / f32::from(units);
|
||||
// XeTeX converts the float point position by adding 0.5 and truncating.
|
||||
(f64::from(points) * 65536. + 0.5) as i64
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct OpenTypeGlyph {
|
||||
pub id: u16,
|
||||
pub x: i64,
|
||||
pub y: i64,
|
||||
pub advance: i64,
|
||||
pub cluster: std::ops::Range<usize>,
|
||||
pub cluster_start: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct OpenTypeRun {
|
||||
pub font: Arc<OpenTypeFont>,
|
||||
pub text: String,
|
||||
pub glyphs: Vec<OpenTypeGlyph>,
|
||||
pub width: i64,
|
||||
pub sources: Vec<(usize, PaintSource)>,
|
||||
}
|
||||
|
||||
pub(crate) fn horizontal_box(run: &Arc<OpenTypeRun>) -> crate::HorizontalBox {
|
||||
use crate::{
|
||||
math::MathBox,
|
||||
math_engine_tex::{MathGeometry, MathItem, PositionedItem},
|
||||
};
|
||||
let metrics = MathBox {
|
||||
width: run.width,
|
||||
height: run.font.ascent,
|
||||
depth: run.font.descent,
|
||||
};
|
||||
crate::HorizontalBox {
|
||||
width: metrics.width,
|
||||
height: metrics.height,
|
||||
depth: metrics.depth,
|
||||
math_geometry: Some(Box::new(MathGeometry {
|
||||
metrics,
|
||||
items: vec![PositionedItem {
|
||||
x: 0,
|
||||
y: 0,
|
||||
item: MathItem::OpenType(run.clone()),
|
||||
source: PaintSource::default(),
|
||||
}],
|
||||
})),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
impl OpenTypeRun {
|
||||
pub(crate) fn paint(
|
||||
&self,
|
||||
x: i64,
|
||||
y: i64,
|
||||
scale: impl Fn(i64) -> i64,
|
||||
mut emit: impl FnMut(crate::render::DisplayItem, PaintSource),
|
||||
) {
|
||||
for glyph in &self.glyphs {
|
||||
let first = self
|
||||
.sources
|
||||
.partition_point(|(offset, _)| *offset < glyph.cluster.start);
|
||||
let last = self
|
||||
.sources
|
||||
.partition_point(|(offset, _)| *offset < glyph.cluster.end);
|
||||
let mut source = PaintSource::default();
|
||||
for (_, component) in &self.sources[first..last] {
|
||||
source.merge(component);
|
||||
}
|
||||
emit(
|
||||
crate::render::DisplayItem::OpenTypeGlyph {
|
||||
x: x + scale(glyph.x),
|
||||
y: y + scale(glyph.y),
|
||||
size: scale(self.font.size),
|
||||
advance: scale(glyph.advance),
|
||||
font: self.font.clone(),
|
||||
glyph: glyph.id,
|
||||
text: if glyph.cluster_start {
|
||||
self.text[glyph.cluster.clone()].to_owned()
|
||||
} else {
|
||||
String::new()
|
||||
},
|
||||
},
|
||||
source.derived(crate::provenance::Derivation::FontProgram),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct PathBuilder(String);
|
||||
impl ttf_parser::OutlineBuilder for PathBuilder {
|
||||
fn move_to(&mut self, x: f32, y: f32) {
|
||||
self.0.push_str(&format!("M{x} {y}"));
|
||||
}
|
||||
fn line_to(&mut self, x: f32, y: f32) {
|
||||
self.0.push_str(&format!("L{x} {y}"));
|
||||
}
|
||||
fn quad_to(&mut self, a: f32, b: f32, x: f32, y: f32) {
|
||||
self.0.push_str(&format!("Q{a} {b} {x} {y}"));
|
||||
}
|
||||
fn curve_to(&mut self, a: f32, b: f32, c: f32, d: f32, x: f32, y: f32) {
|
||||
self.0.push_str(&format!("C{a} {b} {c} {d} {x} {y}"));
|
||||
}
|
||||
fn close(&mut self) {
|
||||
self.0.push('Z');
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn outline(face: &ttf_parser::Face<'_>, glyph: u16) -> String {
|
||||
let mut path = PathBuilder::default();
|
||||
face.outline_glyph(GlyphId(glyph), &mut path);
|
||||
path.0
|
||||
}
|
||||
@@ -25,6 +25,8 @@ pub(crate) mod native_text;
|
||||
pub(crate) mod objects;
|
||||
#[path = "pdf_pk.rs"]
|
||||
mod pk_fonts;
|
||||
#[path = "pdf_opentype.rs"]
|
||||
mod opentype_fonts;
|
||||
|
||||
const FACE_COUNT: usize = 17;
|
||||
|
||||
@@ -356,14 +358,19 @@ fn type1_tounicode_texts(by_code: &BTreeMap<u8, String>) -> Vec<u8> {
|
||||
type1_tounicode_hex(&hex)
|
||||
}
|
||||
fn type1_tounicode_hex(by_code: &BTreeMap<u8, String>) -> Vec<u8> {
|
||||
let mut map = String::from(
|
||||
"/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<00> <FF>\nendcodespacerange\n",
|
||||
to_unicode_map(by_code, 2)
|
||||
}
|
||||
fn to_unicode_map<T: Ord + std::fmt::UpperHex>(by_code: &BTreeMap<T, String>, digits: usize) -> Vec<u8> {
|
||||
let max_code = "F".repeat(digits);
|
||||
let min_code = "0".repeat(digits);
|
||||
let mut map = format!(
|
||||
"/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<{min_code}> <{max_code}>\nendcodespacerange\n",
|
||||
);
|
||||
let entries: Vec<_> = by_code.iter().collect();
|
||||
for chunk in entries.chunks(100) {
|
||||
map.push_str(&format!("{} beginbfchar\n", chunk.len()));
|
||||
for (slot, text) in chunk {
|
||||
map.push_str(&format!("<{slot:02X}> <{text}>\n"));
|
||||
map.push_str(&format!("<{slot:0digits$X}> <{text}>\n"));
|
||||
}
|
||||
map.push_str("endbfchar\n");
|
||||
}
|
||||
@@ -687,6 +694,7 @@ fn page_content(
|
||||
cm_codes: &[Option<&BTreeMap<char, u8>>],
|
||||
fallback_ids: &[usize; FACE_COUNT],
|
||||
origin: PageOrigin,
|
||||
opentype: &BTreeMap<crate::execution::FontId, opentype_fonts::EmbeddedFont>,
|
||||
) -> Vec<u8> {
|
||||
let digits = list.pdf.as_ref().map_or(3, |p| p.file.decimal_digits);
|
||||
let pt = |n: i64| {
|
||||
@@ -724,7 +732,11 @@ fn page_content(
|
||||
}
|
||||
let mut native_text: Option<NativeTextRun> = None;
|
||||
let mut tex_text: Option<native_text::NativeText> = None;
|
||||
let mut opentype_text = None;
|
||||
for (index, item) in list.items.iter().enumerate() {
|
||||
if opentype_text.is_some() && !matches!(item, DisplayItem::OpenTypeGlyph { .. }) {
|
||||
opentype_fonts::TextRun::finish(&mut opentype_text, &mut content);
|
||||
}
|
||||
if let DisplayItem::PdfTextSpace { x, y, operation } = item {
|
||||
if let Some(dedicated) = list.pdf_space_plan.as_ref().and_then(|plan| plan.dedicated.as_ref())
|
||||
&& *operation == crate::pdf_device::text_spaces::SpaceOperation::Explicit
|
||||
@@ -815,6 +827,12 @@ fn page_content(
|
||||
let px = |x| pt(x - h);
|
||||
let py = |y| pt(height - y - v);
|
||||
match item {
|
||||
DisplayItem::OpenTypeGlyph { x, y, size, font, glyph, text, .. } => {
|
||||
opentype[&font.id].paint(
|
||||
&mut opentype_text, &mut content, font.id, *glyph, text,
|
||||
*size, *x - h, height - *y - v, list.units.bp(1),
|
||||
);
|
||||
}
|
||||
DisplayItem::NativeGlyph {
|
||||
x,
|
||||
y,
|
||||
@@ -1090,6 +1108,7 @@ fn page_content(
|
||||
}
|
||||
}
|
||||
}
|
||||
opentype_fonts::TextRun::finish(&mut opentype_text, &mut content);
|
||||
NativeTextRun::flush(&mut native_text, &mut content);
|
||||
native_text::NativeText::finish(&mut tex_text, &mut content);
|
||||
content.push_str("Q\n");
|
||||
@@ -1231,7 +1250,7 @@ pub fn display_lists_to_pdf_with_paper(
|
||||
None,
|
||||
None,
|
||||
&mut Vec::new(),
|
||||
)
|
||||
).expect("valid PDF display lists")
|
||||
}
|
||||
|
||||
fn descendant_count(children: &HashMap<usize, Vec<usize>>, node: usize) -> usize {
|
||||
@@ -1264,7 +1283,7 @@ pub fn display_lists_to_pdf_with_cm_type1(
|
||||
None,
|
||||
None,
|
||||
&mut Vec::new(),
|
||||
)
|
||||
).expect("valid PDF display lists")
|
||||
}
|
||||
|
||||
/// Strict token-kernel output: every glyph has its measured native resource
|
||||
@@ -1424,7 +1443,7 @@ fn native_pdf(
|
||||
unicode,
|
||||
resources,
|
||||
&mut diagnostics,
|
||||
);
|
||||
)?;
|
||||
Ok(NativePdfDocument { bytes, diagnostics })
|
||||
}
|
||||
|
||||
@@ -1447,7 +1466,7 @@ pub fn display_lists_to_pdf_with_truetype_and_metadata(
|
||||
None,
|
||||
None,
|
||||
&mut Vec::new(),
|
||||
)
|
||||
).expect("valid PDF display lists")
|
||||
}
|
||||
|
||||
/// Write PDFs with Computer Modern Type1 outlines and a document Info dictionary.
|
||||
@@ -1469,7 +1488,7 @@ pub fn display_lists_to_pdf_with_cm_type1_and_metadata(
|
||||
None,
|
||||
None,
|
||||
&mut Vec::new(),
|
||||
)
|
||||
).expect("valid PDF display lists")
|
||||
}
|
||||
|
||||
fn write_math_font(
|
||||
@@ -1947,13 +1966,14 @@ fn write_pdf(
|
||||
unicode: Option<crate::pdf_unicode::PdfFinalOptions<'_>>,
|
||||
resources: Option<crate::pdf_device::page_resources::ResourceOutput>,
|
||||
diagnostics: &mut Vec<String>,
|
||||
) -> Vec<u8> {
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let width = page_width;
|
||||
let height = page_height;
|
||||
|
||||
let mut objects: Vec<Vec<u8>> = Vec::new();
|
||||
objects.push(b"<< /Type /Catalog /Pages 2 0 R >>".to_vec());
|
||||
objects.push(Vec::new()); // pages object filled below
|
||||
|
||||
// Native math uses exact slots and optical masters, independent of the
|
||||
// document's Times/Liberation text backend and Unicode face remapping.
|
||||
let mut math_used: BTreeMap<crate::math_font::MathFontId, BTreeMap<u8, char>> = BTreeMap::new();
|
||||
@@ -1980,6 +2000,7 @@ fn write_pdf(
|
||||
let mut native_used = BTreeMap::new();
|
||||
let mut type1_names = HashSet::new();
|
||||
let mut type1_descriptors = HashMap::new();
|
||||
let mut opentype_used = opentype_fonts::UsedFonts::default();
|
||||
for page in pages {
|
||||
for item in &page.items {
|
||||
if let DisplayItem::NativeGlyph {
|
||||
@@ -2013,9 +2034,12 @@ fn write_pdf(
|
||||
"native font ids from different jobs cannot share a PDF"
|
||||
);
|
||||
entry.2.insert(*slot, *character);
|
||||
} else if let DisplayItem::OpenTypeGlyph { font, glyph, text, .. } = item {
|
||||
opentype_used.observe(font, *glyph, text)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
let opentype = opentype_used.write(&mut objects, final_compression.unwrap_or(0).clamp(0, 9) as u8)?;
|
||||
for plan in pages.iter().filter_map(|page| page.pdf_space_plan.as_ref()) {
|
||||
for id in &plan.in_font {
|
||||
native_used.get_mut(id).expect("painted space font").2.insert(b' ', ' ');
|
||||
@@ -2333,6 +2357,15 @@ fn write_pdf(
|
||||
for (face, id) in &native_font_ids {
|
||||
fonts.push_str(&format!(" /N{} {id} 0 R", face.index()));
|
||||
}
|
||||
if !opentype.is_empty() {
|
||||
let open_fonts: BTreeSet<_> = list.items.iter().filter_map(|item| match item {
|
||||
DisplayItem::OpenTypeGlyph { font, .. } => Some(font.id),
|
||||
_ => None,
|
||||
}).collect();
|
||||
for id in open_fonts {
|
||||
fonts.push_str(&format!(" /U{} {} 0 R", id.index(), opentype[&id].object));
|
||||
}
|
||||
}
|
||||
let resources = if xobjects.is_empty() {
|
||||
format!("<< /Font << {fonts} >> >>")
|
||||
} else {
|
||||
@@ -2421,6 +2454,7 @@ fn write_pdf(
|
||||
&cm_views,
|
||||
&fallback_font_ids,
|
||||
origin,
|
||||
&opentype,
|
||||
);
|
||||
objects.push(objects::stream(
|
||||
"",
|
||||
@@ -2717,7 +2751,7 @@ fn write_pdf(
|
||||
.as_ref()
|
||||
.expect("validated native PDF options")
|
||||
.file;
|
||||
return objects::serialize(&objects, Some(objects.len()), options, level.max(0).min(9) as u8);
|
||||
return Ok(objects::serialize(&objects, Some(objects.len()), options, level.max(0).min(9) as u8));
|
||||
}
|
||||
|
||||
let info_ref = match metadata_object(metadata) {
|
||||
@@ -2751,7 +2785,7 @@ fn write_pdf(
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
pdf
|
||||
Ok(pdf)
|
||||
}
|
||||
|
||||
/// Write one page; kept for the single-page spike and tests.
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
//! Embedding for glyphs selected by the native OpenType shaper.
|
||||
use super::{PageContent, native_pdf_name, objects, to_unicode_map};
|
||||
use crate::{execution::FontId, opentype::OpenTypeFont};
|
||||
use rustybuzz::ttf_parser::{GlyphId, RawFace, Tag};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{collections::BTreeMap, fmt::Write};
|
||||
use subsetter::GlyphRemapper;
|
||||
|
||||
pub(super) struct EmbeddedFont {
|
||||
pub object: usize,
|
||||
glyphs: BTreeMap<u16, EmbeddedGlyph>,
|
||||
units: u16,
|
||||
}
|
||||
|
||||
struct EmbeddedGlyph {
|
||||
cid: u16,
|
||||
advance: u16,
|
||||
text: String,
|
||||
}
|
||||
|
||||
pub(super) struct TextRun {
|
||||
font: FontId,
|
||||
size: i64,
|
||||
start: [i64; 2],
|
||||
offset: i64,
|
||||
}
|
||||
|
||||
impl TextRun {
|
||||
pub(super) fn finish(run: &mut Option<Self>, output: &mut PageContent) {
|
||||
if run.take().is_some() {
|
||||
output.push_str(">] TJ ET\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct UsedFonts<'a>(BTreeMap<FontId, (&'a OpenTypeFont, BTreeMap<u16, &'a str>)>);
|
||||
|
||||
impl<'a> UsedFonts<'a> {
|
||||
pub(super) fn observe(
|
||||
&mut self,
|
||||
font: &'a OpenTypeFont,
|
||||
glyph: u16,
|
||||
text: &'a str,
|
||||
) -> Result<(), String> {
|
||||
let (previous, characters) = self
|
||||
.0
|
||||
.entry(font.id)
|
||||
.or_insert_with(|| (font, BTreeMap::new()));
|
||||
if *previous != font {
|
||||
return Err("inconsistent native OpenType font identity in PDF output".into());
|
||||
}
|
||||
let first = characters.entry(glyph).or_insert(text);
|
||||
if first.is_empty() {
|
||||
*first = text;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn write(
|
||||
self,
|
||||
objects: &mut Vec<Vec<u8>>,
|
||||
compression: u8,
|
||||
) -> Result<BTreeMap<FontId, EmbeddedFont>, String> {
|
||||
self.0
|
||||
.into_iter()
|
||||
.map(|(id, (font, glyphs))| {
|
||||
write_font(objects, font, glyphs, compression).map(|face| (id, face))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn write_font(
|
||||
objects: &mut Vec<Vec<u8>>,
|
||||
font: &OpenTypeFont,
|
||||
glyphs: BTreeMap<u16, &str>,
|
||||
compression: u8,
|
||||
) -> Result<EmbeddedFont, String> {
|
||||
let face = font.face()?;
|
||||
let mut remapper = GlyphRemapper::new();
|
||||
let mut fingerprint = Sha256::new();
|
||||
fingerprint.update(font.resource.version.sha256.as_bytes());
|
||||
fingerprint.update(font.face_index().to_be_bytes());
|
||||
let mut widths = String::new();
|
||||
let mut cmap = BTreeMap::new();
|
||||
let mut embedded = BTreeMap::new();
|
||||
let width = |value: i64| (value as f64 * 1000. / f64::from(face.units_per_em())).round() as i32;
|
||||
for (glyph, source) in glyphs {
|
||||
let advance = face.glyph_hor_advance(GlyphId(glyph)).ok_or_else(|| {
|
||||
format!(
|
||||
"OpenType font {} has no advance for glyph {glyph}",
|
||||
font.name
|
||||
)
|
||||
})?;
|
||||
let cid = remapper.remap(glyph);
|
||||
fingerprint.update(glyph.to_be_bytes());
|
||||
write!(widths, "{cid} [{}] ", width(i64::from(advance))).unwrap();
|
||||
if !source.is_empty() {
|
||||
cmap.insert(cid, utf16_hex(source));
|
||||
}
|
||||
embedded.insert(
|
||||
glyph,
|
||||
EmbeddedGlyph {
|
||||
cid,
|
||||
advance,
|
||||
text: source.to_owned(),
|
||||
},
|
||||
);
|
||||
}
|
||||
let tag: String = fingerprint
|
||||
.finalize()
|
||||
.iter()
|
||||
.take(6)
|
||||
.map(|byte| char::from(b'A' + byte % 26))
|
||||
.collect();
|
||||
let name = format!("{tag}+{}", native_pdf_name(&font.name));
|
||||
|
||||
let subset = subsetter::subset(&font.resource.data, font.face_index(), &remapper)
|
||||
.map_err(|error| format!("failed to embed OpenType font {}: {error}", font.name))?;
|
||||
let raw = RawFace::parse(&subset, 0).map_err(|_| "invalid OpenType subset font")?;
|
||||
let cff = raw.table(Tag::from_bytes(b"CFF "));
|
||||
let (subtype, mapping, file_key, file_options, program) = if let Some(cff) = cff {
|
||||
(
|
||||
"CIDFontType0",
|
||||
"",
|
||||
"FontFile3",
|
||||
"/Subtype /CIDFontType0C".to_owned(),
|
||||
cff,
|
||||
)
|
||||
} else {
|
||||
(
|
||||
"CIDFontType2",
|
||||
" /CIDToGIDMap /Identity",
|
||||
"FontFile2",
|
||||
format!("/Length1 {}", subset.len()),
|
||||
subset.as_slice(),
|
||||
)
|
||||
};
|
||||
|
||||
let object = objects.len() + 1;
|
||||
let cid_font = object + 1;
|
||||
let descriptor = object + 2;
|
||||
let font_file = object + 3;
|
||||
let to_unicode = object + 4;
|
||||
objects.push(format!(
|
||||
"<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /DescendantFonts [{cid_font} 0 R] /ToUnicode {to_unicode} 0 R >>"
|
||||
).into_bytes());
|
||||
objects.push(format!(
|
||||
"<< /Type /Font /Subtype /{subtype} /BaseFont /{name} /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor {descriptor} 0 R /W [{widths}]{mapping} >>"
|
||||
).into_bytes());
|
||||
let rect = face.global_bounding_box();
|
||||
let [left, bottom, right, top] =
|
||||
[rect.x_min, rect.y_min, rect.x_max, rect.y_max].map(|v| width(i64::from(v)));
|
||||
let ascent = width(i64::from(face.tables().hhea.ascender));
|
||||
let descent = width(i64::from(face.tables().hhea.descender));
|
||||
let cap = face
|
||||
.capital_height()
|
||||
.map_or(ascent, |n| width(i64::from(n)));
|
||||
let flags = 4 | i32::from(face.is_monospaced()) | if face.is_italic() { 64 } else { 0 };
|
||||
let angle = face.italic_angle();
|
||||
let stem = f64::from(face.weight().to_number()) / 65.;
|
||||
let stem = (50. + stem * stem).round() as i32;
|
||||
objects.push(format!(
|
||||
"<< /Type /FontDescriptor /FontName /{name} /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /StemV {stem} /{file_key} {font_file} 0 R >>"
|
||||
).into_bytes());
|
||||
objects.push(objects::stream(&file_options, program, compression));
|
||||
objects.push(objects::stream("", &to_unicode_map(&cmap, 4), compression));
|
||||
Ok(EmbeddedFont {
|
||||
object,
|
||||
glyphs: embedded,
|
||||
units: face.units_per_em(),
|
||||
})
|
||||
}
|
||||
|
||||
fn utf16_hex(value: &str) -> String {
|
||||
value
|
||||
.encode_utf16()
|
||||
.map(|unit| format!("{unit:04X}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl EmbeddedFont {
|
||||
pub(super) fn paint(
|
||||
&self,
|
||||
run: &mut Option<TextRun>,
|
||||
output: &mut PageContent,
|
||||
font: FontId,
|
||||
glyph: u16,
|
||||
text: &str,
|
||||
size: i64,
|
||||
x: i64,
|
||||
y: i64,
|
||||
bp_per_unit: f64,
|
||||
) {
|
||||
let glyph = &self.glyphs[&glyph];
|
||||
let override_text = text != glyph.text;
|
||||
if run.as_ref().is_some_and(|state| {
|
||||
override_text
|
||||
|| state.font != font
|
||||
|| state.size != size
|
||||
|| (y - state.start[1]).abs() as f64 * bp_per_unit > 0.001
|
||||
|| (x - state.start[0] - state.offset).abs() > size * 3
|
||||
}) {
|
||||
TextRun::finish(run, output);
|
||||
}
|
||||
if override_text {
|
||||
output.push_str(&format!(
|
||||
"/Span << /ActualText <FEFF{}> >> BDC\n",
|
||||
utf16_hex(text)
|
||||
));
|
||||
}
|
||||
let state = run.get_or_insert_with(|| {
|
||||
let coordinates = [x, y].map(|value| {
|
||||
let exact = value as f64 * bp_per_unit;
|
||||
let rounded = (exact * 1000.).round() / 1000.;
|
||||
let error = ((exact - rounded) / bp_per_unit).round() as i64;
|
||||
(rounded, value - error)
|
||||
});
|
||||
let size_bp = size as f64 * bp_per_unit;
|
||||
output.push_str(&format!(
|
||||
"BT /U{} {size_bp:.4} Tf 1 0 0 1 {:.3} {:.3} Tm [<",
|
||||
font.index(),
|
||||
coordinates[0].0,
|
||||
coordinates[1].0
|
||||
));
|
||||
TextRun {
|
||||
font,
|
||||
size,
|
||||
start: coordinates.map(|(_, origin)| origin),
|
||||
offset: x - coordinates[0].1,
|
||||
}
|
||||
});
|
||||
// Move in PDF's thousandth-em text units, tracking widths in TeX sp.
|
||||
let kernel = ((state.start[0] + state.offset - x) as f64 * 1000. / size as f64) as i64;
|
||||
if kernel != 0 {
|
||||
output.push_str(&format!("> {kernel} <"));
|
||||
state.offset -= (kernel as f64 * (size as f64 / 1000.)) as i64;
|
||||
}
|
||||
output.push_str(&format!("{:04X}", glyph.cid));
|
||||
state.offset += i64::from(glyph.advance) * size / i64::from(self.units);
|
||||
if override_text {
|
||||
TextRun::finish(run, output);
|
||||
output.push_str("EMC\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,15 @@ pub enum DisplayItem {
|
||||
font: std::sync::Arc<crate::native_font::NativeFont>,
|
||||
paint: Option<std::sync::Arc<crate::native_font::NativeFontPaint>>,
|
||||
},
|
||||
OpenTypeGlyph {
|
||||
x: i64,
|
||||
y: i64,
|
||||
size: i64,
|
||||
advance: i64,
|
||||
font: std::sync::Arc<crate::opentype::OpenTypeFont>,
|
||||
glyph: u16,
|
||||
text: String,
|
||||
},
|
||||
/// A native math glyph. `face` preserves the optical master independently
|
||||
/// of the painted size; `slot` preserves CMEX next-larger selection.
|
||||
MathGlyph {
|
||||
@@ -393,7 +402,8 @@ impl DisplayList {
|
||||
match item {
|
||||
DisplayItem::Text { x, y, .. }
|
||||
| DisplayItem::MathGlyph { x, y, .. }
|
||||
| DisplayItem::NativeGlyph { x, y, .. } => {
|
||||
| DisplayItem::NativeGlyph { x, y, .. }
|
||||
| DisplayItem::OpenTypeGlyph { x, y, .. } => {
|
||||
*x += dx;
|
||||
*y += dy;
|
||||
}
|
||||
@@ -448,9 +458,9 @@ impl DisplayList {
|
||||
glyph?;
|
||||
}
|
||||
}
|
||||
Ok(self.svg_with_resolved_fonts())
|
||||
self.svg_with_resolved_fonts()
|
||||
}
|
||||
fn svg_with_resolved_fonts(&self) -> String {
|
||||
fn svg_with_resolved_fonts(&self) -> Result<String, String> {
|
||||
let width = self.width as f64 / 65_536.0;
|
||||
let height = self.height as f64 / 65_536.0;
|
||||
let mag = f64::from(self.magnification) / 1000.0
|
||||
@@ -491,6 +501,8 @@ impl DisplayList {
|
||||
}
|
||||
out.push_str("</defs>\n");
|
||||
}
|
||||
let mut opentype_paths = std::collections::BTreeMap::new();
|
||||
let mut opentype_faces = std::collections::BTreeMap::new();
|
||||
let mut fill = [0u8, 0, 0];
|
||||
let mut rule_fill = [0u8; 3];
|
||||
let mut stroke = [0u8; 3];
|
||||
@@ -530,6 +542,23 @@ impl DisplayList {
|
||||
};
|
||||
out.push_str(&format!("<g data-font=\"{}\" data-glyph=\"{}\" data-slot=\"{slot}\" aria-label=\"{}\"><path d=\"{}\" transform=\"translate({x:.5} {y:.5}) scale({horizontal_scale:.8} -{scale:.8})\" fill=\"#{:02x}{:02x}{:02x}\"{fill_opacity}/></g>\n", escape(font), escape(glyph), escape(&label), path, fill[0],fill[1],fill[2]));
|
||||
}
|
||||
DisplayItem::OpenTypeGlyph { x, y, size, font, glyph, text, .. } => {
|
||||
let face = match opentype_faces.entry(font.id) {
|
||||
std::collections::btree_map::Entry::Vacant(entry) => entry.insert(font.face()?),
|
||||
std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(),
|
||||
};
|
||||
let path = opentype_paths.entry((font.id, *glyph))
|
||||
.or_insert_with(|| crate::opentype::outline(face, *glyph));
|
||||
let x = *x as f64 / 65536.;
|
||||
let y = *y as f64 / 65536.;
|
||||
let scale = *size as f64 / (65536. * f64::from(face.units_per_em()));
|
||||
if !path.is_empty() {
|
||||
out.push_str(&format!(
|
||||
"<g data-font=\\\"{}\\\" data-glyph=\\\"{glyph}\\\" aria-label=\\\"{}\\\"><path d=\\\"{path}\\\" transform=\\\"translate({x:.5} {y:.5}) scale({scale:.9} -{scale:.9})\\\" fill=\\\"#{:02x}{:02x}{:02x}\\\"{fill_opacity}/></g>\n",
|
||||
escape(&font.name), escape(text), fill[0], fill[1], fill[2]
|
||||
));
|
||||
}
|
||||
}
|
||||
DisplayItem::MathGlyph {
|
||||
x,
|
||||
y,
|
||||
@@ -795,7 +824,7 @@ impl DisplayList {
|
||||
out.push_str("</g>\n");
|
||||
}
|
||||
out.push_str("</svg>\n");
|
||||
out
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1560,7 +1589,12 @@ impl Page {
|
||||
for position in &geometry.items {
|
||||
let x = x + scaled(position.x);
|
||||
let y = baseline + scaled(position.y);
|
||||
if let MathItem::OpenType(run) = &position.item {
|
||||
run.paint(x, y, scaled, |item, _| list.push(item));
|
||||
continue;
|
||||
}
|
||||
list.push(match &position.item {
|
||||
MathItem::OpenType(_) => unreachable!("OpenType run handled before scalar paint"),
|
||||
MathItem::NativeGlyph {
|
||||
font,
|
||||
slot,
|
||||
|
||||
@@ -23,6 +23,8 @@ pub enum ResourceKind {
|
||||
Tfm,
|
||||
Vf,
|
||||
Type1,
|
||||
OpenType,
|
||||
TrueType,
|
||||
Pk,
|
||||
Encoding,
|
||||
Map,
|
||||
@@ -36,6 +38,8 @@ impl ResourceKind {
|
||||
Self::Tfm => "fonts/tfm",
|
||||
Self::Vf => "fonts/vf",
|
||||
Self::Type1 => "fonts/type1",
|
||||
Self::OpenType => "fonts/opentype",
|
||||
Self::TrueType => "fonts/truetype",
|
||||
Self::Pk => "fonts/pk",
|
||||
Self::Encoding => "fonts/enc",
|
||||
Self::Map => "fonts/map",
|
||||
@@ -48,6 +52,8 @@ impl ResourceKind {
|
||||
Self::Tfm => "TFMFONTS",
|
||||
Self::Vf => "VFFONTS",
|
||||
Self::Type1 => "T1FONTS",
|
||||
Self::OpenType => "OPENTYPEFONTS",
|
||||
Self::TrueType => "TTFONTS",
|
||||
Self::Pk => "PKFONTS",
|
||||
Self::Encoding => "ENCFONTS",
|
||||
Self::Map => "TEXFONTMAPS",
|
||||
@@ -61,6 +67,8 @@ impl ResourceKind {
|
||||
Self::Tfm => &["tfm"],
|
||||
Self::Vf => &["vf"],
|
||||
Self::Type1 => &["pfb", "pfa"],
|
||||
Self::OpenType => &["otf", "otc"],
|
||||
Self::TrueType => &["ttf", "ttc"],
|
||||
Self::Pk => &["pk"],
|
||||
Self::Encoding => &["enc"],
|
||||
Self::Map => &["map"],
|
||||
@@ -68,11 +76,13 @@ impl ResourceKind {
|
||||
Self::Config => &["cnf"],
|
||||
}
|
||||
}
|
||||
const ALL: [Self; 9] = [
|
||||
const ALL: [Self; 11] = [
|
||||
Self::Tex,
|
||||
Self::Tfm,
|
||||
Self::Vf,
|
||||
Self::Type1,
|
||||
Self::OpenType,
|
||||
Self::TrueType,
|
||||
Self::Pk,
|
||||
Self::Encoding,
|
||||
Self::Map,
|
||||
|
||||
@@ -115,6 +115,7 @@ pub enum PaintKind {
|
||||
#[serde(default, skip_serializing_if = "crate::native_font::unexpanded")]
|
||||
expansion: i32,
|
||||
},
|
||||
OpenTypeGlyph { font: u32, glyph: u16 },
|
||||
Rule,
|
||||
PdfImage { page: usize },
|
||||
}
|
||||
@@ -401,6 +402,14 @@ impl SourceMap {
|
||||
},
|
||||
))
|
||||
}
|
||||
DisplayItem::OpenTypeGlyph { x, y, size, advance, font, glyph, .. } => {
|
||||
let scale = |value: i64| value * size / font.size;
|
||||
let ascent = scale(font.ascent);
|
||||
let descent = scale(font.descent);
|
||||
Some((PaintKind::OpenTypeGlyph { font: font.id.index(), glyph: *glyph }, Bounds {
|
||||
x: *x, y: y - ascent, width: *advance, height: ascent + descent,
|
||||
}))
|
||||
}
|
||||
DisplayItem::Rule {
|
||||
x,
|
||||
y,
|
||||
|
||||
@@ -273,7 +273,7 @@ fn delimiter_variants_recipes_dimensions_and_dvi_positions_match_initex() {
|
||||
x: x + p.x,
|
||||
y: p.y,
|
||||
}),
|
||||
MathItem::Glyph { .. } | MathItem::PdfImage(_) => {
|
||||
MathItem::Glyph { .. } | MathItem::PdfImage(_) | MathItem::OpenType(_) => {
|
||||
panic!("legacy glyph identity in strict native math")
|
||||
}
|
||||
MathItem::Rule { width, height } => {
|
||||
|
||||
@@ -380,7 +380,8 @@ fn sized_math_families_and_live_math_parameters_match_real_initex_boxes() {
|
||||
assert!(font.size_sp() != font.metrics.design_size_sp())
|
||||
}
|
||||
texrra_tex_core::math_engine_tex::MathItem::Glyph { .. }
|
||||
| texrra_tex_core::math_engine_tex::MathItem::PdfImage(_) => {
|
||||
| texrra_tex_core::math_engine_tex::MathItem::PdfImage(_)
|
||||
| texrra_tex_core::math_engine_tex::MathItem::OpenType(_) => {
|
||||
panic!("legacy master leaked into native math")
|
||||
}
|
||||
texrra_tex_core::math_engine_tex::MathItem::Rule { .. } => {}
|
||||
|
||||
@@ -250,7 +250,7 @@ fn math_accent_dimensions_raw_slots_and_dvi_positions_match_real_initex() {
|
||||
x: x + item.x,
|
||||
y: item.y,
|
||||
}),
|
||||
MathItem::Glyph { .. } | MathItem::PdfImage(_) => {
|
||||
MathItem::Glyph { .. } | MathItem::PdfImage(_) | MathItem::OpenType(_) => {
|
||||
panic!("legacy glyph identity in strict native math")
|
||||
}
|
||||
MathItem::Rule { width, height } => {
|
||||
|
||||
@@ -125,6 +125,7 @@ pub fn painted_text(items: &[texrra_tex_core::HorizontalItem]) -> String {
|
||||
MathItem::Rule { .. } => {}
|
||||
MathItem::Glyph { .. } => panic!("legacy font in native test material"),
|
||||
MathItem::PdfImage(_) => panic!("PDF image in a DVI fixture"),
|
||||
MathItem::OpenType(_) => panic!("OpenType paint in a classic DVI fixture"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2175,6 +2175,36 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。
|
||||
全量编译一致。incremental-receipt.json 的 SHA-256 为
|
||||
bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。
|
||||
|
||||
### Unicode 入口的 OpenType 和 TrueType 文本
|
||||
|
||||
Unicode 入口可从版本化资源目录加载显式文件名的 OpenType 和
|
||||
TrueType 字体。实际字体的字符表、字号和特性进入塑形。保留字形
|
||||
编号、原生尺度下的定位和输入字节范围。原生盒及断行接收实测
|
||||
字宽和字体度量,PDF 嵌入真实的 CFF 或 TrueType 字体子集并输出
|
||||
ToUnicode,SVG 使用同一字形编号绘制实际轮廓。
|
||||
[pdfTeX/XeTeX 发行版的 XeTeX 塑形与盒度量](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/XeTeX_ext.c)
|
||||
[xdvipdfmx 的文本游标及千分之一 em 调整](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/dvipdfm-x/pdfdev.c#L897-L1060)
|
||||
[字体子集库](https://docs.rs/subsetter/0.2.3/subsetter/)
|
||||
|
||||
同一 XeTeX 0.999998 与 xdvipdfmx 对照覆盖四个作业、五页、50 个
|
||||
字形。保留冻结的 Latin Modern OTF 输入,另外对照打开和关闭连字、
|
||||
Liberation Sans TrueType 及带组合记号的希伯来文。字形编号、位置、
|
||||
盒宽高深与 XDV 和参考测量一致。五页的 600 dpi 灰度像素一致。
|
||||
原先逐字形写 PDF 的版本在关闭连字时有 345 个差异像素,实测失败
|
||||
保存在 raster-receipt.json。按参考游标分组后通过,排版原始坐标保留。
|
||||
回执目录为 target/p3-native-xetex。
|
||||
|
||||
- shape-export-receipt.json SHA-256 91cc26f69061c3e4f2d69bf5d4a0c20725da46f175483658d9e41df70c1be851
|
||||
- raster-final-receipt.json SHA-256 efd3f1a3fc4644fbfed6fdf9436b97533d19826fc1ed1e201a1a7fa6dcb08a36
|
||||
- incremental-receipt.json SHA-256 395b4303816fbd757998fe54af585dfa4d345b3c0a5937e388e132f4a00c9bc2
|
||||
|
||||
三页工程移除实际 OTF 时保留已发布的 PDF。只恢复字体文件为新的
|
||||
实际版本,复用 1277 步,只替换第二页。增量与独立全量的 PDF、SVG
|
||||
和来源映射一致。格式版本升级为 schema56,实测 schema55 仍能
|
||||
加载原生 PDF 作业。真实 XeTeX 禁止含原生字体的格式转储,同一冻结
|
||||
输入在原生入口也会在 dump 时失败。6 项出页与 4 项格式定向回归通过,
|
||||
全工作区测试代码完成类型检查。
|
||||
|
||||
### 原生段落边缘悬挂
|
||||
|
||||
`\pdfprotrudechars`、`\lpcode`、`\rpcode` 接入实际字体槽和水平
|
||||
|
||||
@@ -131,6 +131,13 @@ impl SourceProvider for RecordingHost<'_> {
|
||||
.map_err(Clone::clone)
|
||||
})
|
||||
}
|
||||
fn optional_font_file(&mut self, kind: ResourceKind, name: &str, from: &str) -> Result<Option<LoadedResource>, String> {
|
||||
let (name, from) = (name.to_owned(), from.to_owned());
|
||||
call!(self, optional_font_file(kind, &name, &from); |result| {
|
||||
result.as_ref().map(|resource| resource.as_ref().map(|item| item.version.clone()))
|
||||
.map_err(Clone::clone)
|
||||
})
|
||||
}
|
||||
fn optional_font_map(&mut self, name: &str, from: &str) -> Result<Option<LoadedResource>, String> {
|
||||
let (name, from) = (name.to_owned(), from.to_owned());
|
||||
call!(self, optional_font_map(&name, &from); |result| {
|
||||
|
||||
@@ -786,6 +786,13 @@ impl Files {
|
||||
json!({"x": x, "y": y, "size": size, "slot": slot, "font": font.name}),
|
||||
);
|
||||
}
|
||||
DisplayItem::OpenTypeGlyph { x, y, size, glyph, text, font, .. } => {
|
||||
paint_order.push(json!(["glyph", glyphs.len()]));
|
||||
glyphs.push(json!({
|
||||
"x": x, "y": y, "size": size, "glyph": glyph,
|
||||
"font": font.name, "text": text, "resource": font.resource.version,
|
||||
}));
|
||||
}
|
||||
DisplayItem::Rule {
|
||||
x,
|
||||
y,
|
||||
@@ -1553,6 +1560,13 @@ impl SourceProvider for Files {
|
||||
}
|
||||
Ok(resource)
|
||||
}
|
||||
fn optional_font_file(&mut self, kind: ResourceKind, name: &str, from: &str) -> Result<Option<LoadedResource>, String> {
|
||||
let resource = self.world.read_optional(kind, name, Path::new(from))?;
|
||||
if let Some(resource) = &resource {
|
||||
self.observe_resource(kind, resource);
|
||||
}
|
||||
Ok(resource)
|
||||
}
|
||||
fn optional_font_map(&mut self, name: &str, from: &str) -> Result<Option<LoadedResource>, String> {
|
||||
let kind = ResourceKind::Map;
|
||||
let resource = self.world.read_optional(kind, name, Path::new(from))?;
|
||||
|
||||
@@ -294,3 +294,46 @@ fn shipped_pdf_spaces_take_a_real_font_slot_in_output_order() {
|
||||
}
|
||||
fs::remove_dir_all(work).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_job_shapes_file_font_and_exports_the_actual_glyphs() {
|
||||
let p = directory();
|
||||
let face = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("vendor/printpdf/assets/fonts/RobotoMedium.ttf");
|
||||
fs::copy(face, p.join("actual.ttf")).unwrap();
|
||||
fs::write(
|
||||
p.join("probe.tex"),
|
||||
r#"\catcode123=1 \catcode125=2
|
||||
\pdfcompresslevel=0 \pdfobjcompresslevel=0
|
||||
\font\body="[actual.ttf]" at 10pt
|
||||
\shipout\hbox{\body AV office naïve}
|
||||
\end"#,
|
||||
)
|
||||
.unwrap();
|
||||
let result = Command::new(env!("CARGO_BIN_EXE_texrra"))
|
||||
.args([
|
||||
"native", "--job", "--initex", "--etex", "--input-profile", "unicode",
|
||||
"--input-policy", "project", "--layout-manifest", "layout.json", "probe.tex",
|
||||
"native.pdf",
|
||||
])
|
||||
.env("TEXRRA_STATE_DIR", p.join("state"))
|
||||
.current_dir(&p)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr));
|
||||
let layout: serde_json::Value =
|
||||
serde_json::from_slice(&fs::read(p.join("layout.json")).unwrap()).unwrap();
|
||||
let glyphs = layout["pages"][0]["glyphs"].as_array().unwrap();
|
||||
let text: String = glyphs.iter().map(|glyph| glyph["text"].as_str().unwrap()).collect();
|
||||
assert_eq!(text, "AVofficenaïve");
|
||||
assert!(glyphs.iter().any(|glyph| glyph["text"] == "fi" && glyph["glyph"] == 420));
|
||||
assert!(glyphs.iter().all(|glyph| glyph["resource"]["path"].as_str().unwrap().ends_with("actual.ttf")));
|
||||
let map = layout["source_map"]["pages"][0]["entries"].as_array().unwrap();
|
||||
assert_eq!(map.len(), glyphs.len());
|
||||
let pdf = fs::read(p.join("native.pdf")).unwrap();
|
||||
let pdf = String::from_utf8_lossy(&pdf);
|
||||
assert!(pdf.contains("/Subtype /CIDFontType2"));
|
||||
assert!(pdf.contains("/FontFile2"));
|
||||
assert!(pdf.contains("/ToUnicode"));
|
||||
fs::remove_dir_all(p).unwrap();
|
||||
}
|
||||
Reference in new issue
Block a user