Support XeTeX OpenType vertical shaping and PDF writing mode
This commit is contained in:
1 parent
23ec506fa3
commit
e2af618e65
9 files changed
+481
-44
No files matched your search
Generated
+18
@@ -541,6 +541,17 @@ dependencies = [
|
||||
"weezl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "harfbuzz_rs"
|
||||
version = "3.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "53014927fbaf081c5b86332f84c7925b06e7e059d4827ba08a4e813148407ff0"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"cc",
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.2"
|
||||
@@ -988,6 +999,12 @@ version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
||||
|
||||
[[package]]
|
||||
name = "png"
|
||||
version = "0.16.8"
|
||||
@@ -1576,6 +1593,7 @@ name = "texrra-tex-core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"harfbuzz_rs",
|
||||
"hyphenate",
|
||||
"image 0.23.14",
|
||||
"libc",
|
||||
|
||||
@@ -7,6 +7,7 @@ description = "Experimental incremental TeX-compatible typesetting core (route D
|
||||
|
||||
[dependencies]
|
||||
flate2 = "1.1"
|
||||
harfbuzz_rs = "=3.0.1"
|
||||
image = { version = "0.23.12", default-features = false, features = ["bmp"] }
|
||||
lopdf = "0.26"
|
||||
libloading = "=0.8.9"
|
||||
|
||||
@@ -21,6 +21,7 @@ mod character_range;
|
||||
mod font_info;
|
||||
mod graphite;
|
||||
mod tags;
|
||||
pub(crate) mod vertical;
|
||||
pub(crate) use font_info::LayoutTags;
|
||||
mod math_layout;
|
||||
pub(crate) use math_layout::{MathConstants, ScriptSide, Stretch, accent_attachment, script_kern, single_glyph, stretch_glyph};
|
||||
@@ -31,6 +32,8 @@ pub(crate) struct Request {
|
||||
pub index: u32,
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
graphite: bool,
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
vertical: bool,
|
||||
features: Vec<String>,
|
||||
script: Option<String>,
|
||||
language: Option<String>,
|
||||
@@ -126,6 +129,7 @@ impl Request {
|
||||
file: file.to_owned(),
|
||||
index,
|
||||
graphite,
|
||||
vertical: false,
|
||||
features: Vec::new(),
|
||||
script: None,
|
||||
language: None,
|
||||
@@ -170,6 +174,8 @@ impl Request {
|
||||
return Err("invalid OpenType embolden percentage".into());
|
||||
}
|
||||
request.embolden = (value != 0.).then(|| value.to_bits());
|
||||
} else if feature == "vertical" && !graphite {
|
||||
request.vertical = true;
|
||||
} else if let Some(value) = feature.strip_prefix("color=") {
|
||||
request.color = Some(read_color(value)?);
|
||||
} else {
|
||||
@@ -279,6 +285,8 @@ pub struct OpenTypeFont {
|
||||
character_range: OnceLock<Result<[u32; 2], String>>,
|
||||
#[serde(skip)]
|
||||
graphite: OnceLock<Result<Option<Arc<graphite::Font>>, String>>,
|
||||
#[serde(skip)]
|
||||
vertical_shaper: OnceLock<Arc<vertical::Shaper>>,
|
||||
}
|
||||
|
||||
impl PartialEq for OpenTypeFont {
|
||||
@@ -375,6 +383,7 @@ impl OpenTypeFont {
|
||||
mapping,
|
||||
character_range: OnceLock::new(),
|
||||
graphite: OnceLock::new(),
|
||||
vertical_shaper: OnceLock::new(),
|
||||
});
|
||||
// The unmapped space can itself undergo OpenType substitution.
|
||||
// XeTeX adds tracking to its glue even for a single shaped glyph.
|
||||
@@ -445,6 +454,10 @@ impl OpenTypeFont {
|
||||
self.request.index
|
||||
}
|
||||
|
||||
pub(crate) fn is_vertical(&self) -> bool {
|
||||
self.request.vertical
|
||||
}
|
||||
|
||||
pub(crate) fn letter_space(&self) -> i64 {
|
||||
self.request.letter_space(self.size) as i64
|
||||
}
|
||||
@@ -459,6 +472,26 @@ impl OpenTypeFont {
|
||||
self.device_transform().map(|factor| (factor * 100_000.).round() / 100_000.)
|
||||
}
|
||||
|
||||
pub(crate) fn vertical_paint_matrix(
|
||||
&self,
|
||||
face: &ttf_parser::Face<'_>,
|
||||
glyph: u16,
|
||||
size: f64,
|
||||
) -> [f64; 6] {
|
||||
let [extend, slant] = self.paint_transform();
|
||||
let [origin_x, origin_y] = vertical::PdfMetrics::new(face).origin(GlyphId(glyph));
|
||||
let outline_scale = size / f64::from(face.units_per_em());
|
||||
let pdf_scale = size / 1000.;
|
||||
[
|
||||
slant * outline_scale,
|
||||
-outline_scale,
|
||||
-extend * outline_scale,
|
||||
0.,
|
||||
(extend * origin_y - slant * origin_x) * pdf_scale,
|
||||
origin_x * pdf_scale,
|
||||
]
|
||||
}
|
||||
|
||||
pub(crate) fn paint_embolden(&self) -> f64 {
|
||||
let width = self.request.embolden_sp(self.size).max(0) as f64 / 65536.;
|
||||
// The XDV PDF device writes the line width to six decimal places.
|
||||
@@ -592,8 +625,16 @@ impl OpenTypeFont {
|
||||
let slant = self.request.slant.map_or(0., f32::from_bits);
|
||||
let units = face.tables().head.units_per_em;
|
||||
let points = |value: i64| units_to_points(value as f32, self.size, units);
|
||||
// HarfBuzz's vertical offsets are positive upwards.
|
||||
let horizontal = |x: i64, y: i64| points(x) * horizontal_scale - points(-y) * slant;
|
||||
// XeTeX maps vertical glyph motion into the inline coordinate of a TeX box.
|
||||
let vertical = self.is_vertical();
|
||||
let shaper = vertical.then(|| self.vertical_shaper.get_or_init(|| {
|
||||
Arc::new(vertical::Shaper::new(&self.resource, self.face_index(), &face))
|
||||
}));
|
||||
let position = |x: i64, y: i64| {
|
||||
let (inline, down) = if vertical { (-y, x) } else { (x, -y) };
|
||||
let down = points(down);
|
||||
(points(inline) * horizontal_scale - down * slant, down)
|
||||
};
|
||||
for paragraph in &bidi.paragraphs {
|
||||
let (levels, runs) = bidi.visual_runs(paragraph, paragraph.range.clone());
|
||||
for range in runs {
|
||||
@@ -603,7 +644,9 @@ impl OpenTypeFont {
|
||||
Some(font) => font.shape(text, rtl, script, language.as_ref())?,
|
||||
None => None,
|
||||
};
|
||||
let shaped = if let Some(glyphs) = graphite_glyphs {
|
||||
let shaped = if let Some(shaper) = shaper {
|
||||
ShapedGlyphs::Vertical(shaper.shape(text, script, language.as_ref(), &features))
|
||||
} else if let Some(glyphs) = graphite_glyphs {
|
||||
ShapedGlyphs::Graphite(glyphs)
|
||||
} else {
|
||||
let mut buffer = UnicodeBuffer::new();
|
||||
@@ -631,15 +674,17 @@ impl OpenTypeFont {
|
||||
let end = starts[starts.partition_point(|at| *at <= cluster)];
|
||||
let next_x = x + i64::from(glyph.x_advance);
|
||||
let next_y = y + i64::from(glyph.y_advance);
|
||||
if tracking != 0 && points_to_sp(points(i64::from(glyph.x_advance))) == 0 {
|
||||
let inline_advance = if vertical { glyph.y_advance } else { glyph.x_advance };
|
||||
if tracking != 0 && points_to_sp(points(i64::from(inline_advance))) == 0 {
|
||||
tracking -= letter_space;
|
||||
}
|
||||
let x_position = |x, y| point_position_to_sp(x_origin + f64::from(horizontal(x, y)));
|
||||
let glyph_y = y + i64::from(glyph.y_offset);
|
||||
let x_position = |x, y| point_position_to_sp(x_origin + f64::from(position(x, y).0));
|
||||
let x_offset = i64::from(glyph.x_offset) * if vertical { -1 } else { 1 };
|
||||
let (inline, down) = position(x + x_offset, y + i64::from(glyph.y_offset));
|
||||
glyphs.push(OpenTypeGlyph {
|
||||
id: glyph.id,
|
||||
x: x_position(x + i64::from(glyph.x_offset), glyph_y) + tracking,
|
||||
y: point_position_to_sp(y_origin + f64::from(points(-glyph_y))),
|
||||
x: point_position_to_sp(x_origin + f64::from(inline)) + tracking,
|
||||
y: point_position_to_sp(y_origin + f64::from(down)),
|
||||
advance: x_position(next_x, next_y) - x_position(x, y),
|
||||
cluster: cluster..end,
|
||||
cluster_start: cluster != previous,
|
||||
@@ -649,8 +694,9 @@ impl OpenTypeFont {
|
||||
y = next_y;
|
||||
previous = cluster;
|
||||
}
|
||||
x_origin += f64::from(horizontal(x, y));
|
||||
y_origin += f64::from(points(-y));
|
||||
let (inline, down) = position(x, y);
|
||||
x_origin += f64::from(inline);
|
||||
y_origin += f64::from(down);
|
||||
}
|
||||
}
|
||||
let mut width = point_position_to_sp(x_origin);
|
||||
@@ -674,6 +720,7 @@ impl OpenTypeFont {
|
||||
enum ShapedGlyphs {
|
||||
OpenType(rustybuzz::GlyphBuffer),
|
||||
Graphite(Vec<graphite::Glyph>),
|
||||
Vertical(harfbuzz_rs::GlyphBuffer),
|
||||
}
|
||||
|
||||
impl ShapedGlyphs {
|
||||
@@ -681,6 +728,7 @@ impl ShapedGlyphs {
|
||||
let length = match self {
|
||||
Self::OpenType(run) => run.len(),
|
||||
Self::Graphite(glyphs) => glyphs.len(),
|
||||
Self::Vertical(run) => run.get_glyph_infos().len(),
|
||||
};
|
||||
(0..length).map(|index| match self {
|
||||
Self::OpenType(run) => {
|
||||
@@ -696,6 +744,18 @@ impl ShapedGlyphs {
|
||||
}
|
||||
}
|
||||
Self::Graphite(glyphs) => glyphs[index],
|
||||
Self::Vertical(run) => {
|
||||
let info = &run.get_glyph_infos()[index];
|
||||
let position = &run.get_glyph_positions()[index];
|
||||
graphite::Glyph {
|
||||
id: info.codepoint as u16,
|
||||
cluster: info.cluster as usize,
|
||||
x_advance: position.x_advance,
|
||||
y_advance: position.y_advance,
|
||||
x_offset: position.x_offset,
|
||||
y_offset: position.y_offset,
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
//! XeTeX keeps the shaping origin at zero in vertical fonts. The PDF
|
||||
//! device applies the vertical origin independently through the CID font.
|
||||
use super::FontResource;
|
||||
use harfbuzz_rs::{
|
||||
Blob, Direction, Face, Feature, Font, GlyphBuffer, Shared, Tag, UnicodeBuffer,
|
||||
font_funcs::FontFuncs,
|
||||
};
|
||||
use rustybuzz::ttf_parser;
|
||||
use std::fmt;
|
||||
|
||||
pub(super) struct Shaper(Shared<Font<'static>>);
|
||||
|
||||
impl fmt::Debug for Shaper {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("VerticalShaper").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
struct GlyphMetrics {
|
||||
default_advance: Option<i32>,
|
||||
}
|
||||
|
||||
impl FontFuncs for GlyphMetrics {
|
||||
fn get_glyph_v_origin(&self, _: &Font<'_>, _: u32) -> Option<(i32, i32)> {
|
||||
Some((0, 0))
|
||||
}
|
||||
|
||||
fn get_glyph_v_advance(&self, font: &Font<'_>, glyph: u32) -> i32 {
|
||||
self.default_advance.unwrap_or_else(|| {
|
||||
font.parent()
|
||||
.map_or(0, |parent| parent.get_glyph_v_advance(glyph))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Shaper {
|
||||
pub(super) fn new(resource: &FontResource, index: u32, metrics: &ttf_parser::Face<'_>) -> Self {
|
||||
let blob = Blob::with_bytes_owned(resource.data.clone(), |data| data.as_slice());
|
||||
let face = Face::new(blob, index);
|
||||
let mut font = Font::create_sub_font(Font::new(face));
|
||||
let default_advance = metrics.tables().vmtx.is_none().then(|| {
|
||||
// Match FreeType's unscaled fallback when the face has no vmtx.
|
||||
let hhea = metrics.tables().hhea;
|
||||
let (ascent, descent) = metrics
|
||||
.typographic_ascender()
|
||||
.zip(metrics.typographic_descender())
|
||||
.unwrap_or((hhea.ascender, hhea.descender));
|
||||
i32::from(descent) - i32::from(ascent)
|
||||
});
|
||||
font.set_font_funcs(GlyphMetrics { default_advance });
|
||||
Self(font.to_shared())
|
||||
}
|
||||
|
||||
pub(super) fn shape(
|
||||
&self,
|
||||
text: &str,
|
||||
script: Option<rustybuzz::Script>,
|
||||
language: Option<&rustybuzz::Language>,
|
||||
features: &[rustybuzz::Feature],
|
||||
) -> GlyphBuffer {
|
||||
let mut buffer = UnicodeBuffer::new()
|
||||
.add_str(text)
|
||||
.set_direction(Direction::Ttb);
|
||||
if let Some(script) = script {
|
||||
buffer = buffer.set_script(Tag(script.tag().0));
|
||||
}
|
||||
if let Some(language) = language.and_then(|language| language.as_str().parse().ok()) {
|
||||
buffer = buffer.set_language(language);
|
||||
}
|
||||
let features = features
|
||||
.iter()
|
||||
.map(|feature| {
|
||||
Feature::new(
|
||||
Tag(feature.tag.0),
|
||||
feature.value,
|
||||
feature.start as usize..feature.end as usize,
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
harfbuzz_rs::shape(&self.0, buffer, &features)
|
||||
}
|
||||
}
|
||||
|
||||
/// Vertical writing metrics in the PDF device's thousandth-em units.
|
||||
/// XeTeX's shaper does not use these origins for its TeX positions.
|
||||
pub(crate) struct PdfMetrics<'a, 'f> {
|
||||
face: &'a ttf_parser::Face<'f>,
|
||||
pub(crate) origin_y: f64,
|
||||
pub(crate) advance: f64,
|
||||
kind: MetricKind,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum MetricKind {
|
||||
Vorg,
|
||||
TrueType,
|
||||
Default,
|
||||
}
|
||||
|
||||
impl<'a, 'f> PdfMetrics<'a, 'f> {
|
||||
pub(crate) fn new(face: &'a ttf_parser::Face<'f>) -> Self {
|
||||
let typographic = face
|
||||
.typographic_ascender()
|
||||
.zip(face.typographic_descender());
|
||||
let scale = |value| Self::units(face, value);
|
||||
if face.tables().glyf.is_some() {
|
||||
let (ascent, descent) = typographic.unwrap_or((880, -120));
|
||||
return Self {
|
||||
face,
|
||||
origin_y: scale(f64::from(ascent)),
|
||||
advance: scale(f64::from(ascent) - f64::from(descent)),
|
||||
kind: MetricKind::TrueType,
|
||||
};
|
||||
}
|
||||
if let Some(vorg) = face.raw_face().table(ttf_parser::Tag::from_bytes(b"VORG"))
|
||||
&& let Some(bytes) = vorg.get(4..6)
|
||||
{
|
||||
let origin = i16::from_be_bytes([bytes[0], bytes[1]]);
|
||||
return Self {
|
||||
face,
|
||||
origin_y: scale(f64::from(origin)),
|
||||
advance: 1000.,
|
||||
kind: MetricKind::Vorg,
|
||||
};
|
||||
}
|
||||
Self {
|
||||
face,
|
||||
origin_y: 880.,
|
||||
advance: 1000.,
|
||||
kind: MetricKind::Default,
|
||||
}
|
||||
}
|
||||
|
||||
fn units(face: &ttf_parser::Face<'_>, value: f64) -> f64 {
|
||||
(value * 1000. / f64::from(face.units_per_em()) + 0.5).floor()
|
||||
}
|
||||
|
||||
pub(crate) fn override_for(&self, glyph: ttf_parser::GlyphId) -> Option<[f64; 3]> {
|
||||
let scale = |value| Self::units(self.face, value);
|
||||
let advance = self
|
||||
.face
|
||||
.glyph_ver_advance(glyph)
|
||||
.map_or(self.advance, |height| scale(f64::from(height)));
|
||||
let origin_y = match self.kind {
|
||||
MetricKind::Vorg => self
|
||||
.face
|
||||
.glyph_y_origin(glyph)
|
||||
.map_or(self.origin_y, |origin| scale(f64::from(origin))),
|
||||
MetricKind::TrueType => match self.face.glyph_ver_side_bearing(glyph) {
|
||||
Some(bearing) => {
|
||||
let top = self
|
||||
.face
|
||||
.glyph_bounding_box(glyph)
|
||||
.map_or(0, |bounds| bounds.y_max);
|
||||
scale(f64::from(top) + f64::from(bearing))
|
||||
}
|
||||
None => self.origin_y,
|
||||
},
|
||||
MetricKind::Default => return None,
|
||||
};
|
||||
if origin_y == self.origin_y && advance == self.advance {
|
||||
return None;
|
||||
}
|
||||
let width = self.face.glyph_hor_advance(glyph).unwrap_or(0);
|
||||
Some([advance, scale(f64::from(width) / 2.), origin_y])
|
||||
}
|
||||
|
||||
pub(crate) fn origin(&self, glyph: ttf_parser::GlyphId) -> [f64; 2] {
|
||||
if let Some([_, x, y]) = self.override_for(glyph) {
|
||||
[x, y]
|
||||
} else {
|
||||
let width = self
|
||||
.face
|
||||
.glyph_hor_advance(glyph)
|
||||
.or_else(|| self.face.glyph_hor_advance(ttf_parser::GlyphId(0)))
|
||||
.unwrap_or(0);
|
||||
[Self::units(self.face, f64::from(width)) / 2., self.origin_y]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
//! Embedding for glyphs selected by the native OpenType shaper.
|
||||
use super::{PageContent, native_pdf_name, objects, opentype_unicode, to_unicode_map};
|
||||
use crate::{execution::FontId, opentype::OpenTypeFont};
|
||||
use crate::{
|
||||
execution::FontId,
|
||||
opentype::{OpenTypeFont, vertical::PdfMetrics},
|
||||
};
|
||||
use read_fonts::{
|
||||
FileRef, FontData, FontRead,
|
||||
collections::IntSet,
|
||||
@@ -26,12 +29,12 @@ struct EmbeddedGlyph {
|
||||
|
||||
pub(super) struct TextState {
|
||||
run: Option<TextRun>,
|
||||
matrix: [f64; 2],
|
||||
matrix: ([f64; 2], bool),
|
||||
}
|
||||
|
||||
impl Default for TextState {
|
||||
fn default() -> Self {
|
||||
Self { run: None, matrix: [1., 0.] }
|
||||
Self { run: None, matrix: ([1., 0.], false) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +47,7 @@ impl TextState {
|
||||
}
|
||||
|
||||
pub(super) fn reset_matrix(&mut self) {
|
||||
self.matrix = [1., 0.];
|
||||
self.matrix = ([1., 0.], false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,13 +65,16 @@ impl TextRun {
|
||||
output: &mut PageContent,
|
||||
[x, y]: [i64; 2],
|
||||
[extend, slant]: [f64; 2],
|
||||
vertical: bool,
|
||||
bp_per_unit: f64,
|
||||
) {
|
||||
let dy = y - self.start[1];
|
||||
let dx = (((x - self.start[0]) as f64 - dy as f64 * slant) / extend) as i64;
|
||||
let (tx, x_error) = rounded_coordinate(dx, bp_per_unit);
|
||||
let (ty, y_error) = rounded_coordinate(dy, bp_per_unit);
|
||||
let [tx, ty] = if vertical { [dy, -dx] } else { [dx, dy] };
|
||||
let (tx, tx_error) = rounded_coordinate(tx, bp_per_unit);
|
||||
let (ty, ty_error) = rounded_coordinate(ty, bp_per_unit);
|
||||
output.push_str(&format!("{tx:.3} {ty:.3} Td [<"));
|
||||
let [x_error, y_error] = if vertical { [-ty_error, tx_error] } else { [tx_error, ty_error] };
|
||||
self.start = [x - x_error, y - y_error];
|
||||
self.offset = 0;
|
||||
}
|
||||
@@ -221,6 +227,9 @@ fn write_font(
|
||||
) -> Result<EmbeddedFont, String> {
|
||||
let face = font.face()?;
|
||||
let xdv = options.filter(|options| options.xdv_font_unicode);
|
||||
let vertical = font.is_vertical();
|
||||
let vertical_metrics = vertical.then(|| PdfMetrics::new(&face));
|
||||
let encoding = if vertical { "Identity-V" } else { "Identity-H" };
|
||||
let cid_cff = if xdv.is_some() {
|
||||
CidCff::read(&face)?
|
||||
} else {
|
||||
@@ -253,13 +262,13 @@ fn write_font(
|
||||
fingerprint.update(font.face_index().to_be_bytes());
|
||||
let mut widths = String::new();
|
||||
let mut cid_widths = BTreeMap::new();
|
||||
let mut vertical_widths = BTreeMap::new();
|
||||
let device_cid_metrics = cid_cff.is_some() || vertical;
|
||||
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;
|
||||
let default_advance = face.glyph_hor_advance(GlyphId(0)).unwrap_or(0);
|
||||
let width_tenths =
|
||||
|value: u16| (f64::from(value) * 10000. / f64::from(face.units_per_em())).round() as u32;
|
||||
let default_width = width_tenths(default_advance);
|
||||
let default_width = width(i64::from(default_advance));
|
||||
for (glyph, source) in glyphs {
|
||||
let outside_face = glyph >= face.number_of_glyphs();
|
||||
let (cid, advance) = if outside_face {
|
||||
@@ -290,14 +299,20 @@ fn write_font(
|
||||
} else {
|
||||
advance
|
||||
};
|
||||
if cid_cff.is_some() {
|
||||
let pdf_width = width_tenths(pdf_advance);
|
||||
if device_cid_metrics {
|
||||
let pdf_width = width(i64::from(pdf_advance));
|
||||
if pdf_width != default_width {
|
||||
cid_widths.insert(cid, pdf_width);
|
||||
}
|
||||
} else {
|
||||
write!(widths, "{cid} [{}] ", width(i64::from(pdf_advance))).unwrap();
|
||||
}
|
||||
if !outside_face
|
||||
&& let Some(metrics) = &vertical_metrics
|
||||
&& let Some(values) = metrics.override_for(GlyphId(glyph))
|
||||
{
|
||||
vertical_widths.insert(cid, values);
|
||||
}
|
||||
let unicode = if xdv.is_some() {
|
||||
font_unicode
|
||||
.as_ref()
|
||||
@@ -313,7 +328,11 @@ fn write_font(
|
||||
glyph,
|
||||
EmbeddedGlyph {
|
||||
cid,
|
||||
advance,
|
||||
advance: if vertical && !outside_face {
|
||||
face.glyph_ver_advance(GlyphId(glyph)).unwrap_or(advance)
|
||||
} else {
|
||||
advance
|
||||
},
|
||||
cluster_text: xdv.is_none().then(|| source.to_owned()),
|
||||
},
|
||||
);
|
||||
@@ -365,8 +384,8 @@ fn write_font(
|
||||
} else {
|
||||
format!(" /ToUnicode {} 0 R", object + 4)
|
||||
};
|
||||
let (type0_name, system_info, width_entries) = if let Some(cff) = &cid_cff {
|
||||
let mut entries = format!(" /DW {}", f64::from(default_width) / 10.);
|
||||
let mut width_entries = if device_cid_metrics {
|
||||
let mut entries = format!(" /DW {default_width}");
|
||||
if !cid_widths.is_empty() {
|
||||
entries.push_str(" /W [");
|
||||
let mut previous = None;
|
||||
@@ -377,21 +396,38 @@ fn write_font(
|
||||
}
|
||||
write!(entries, "{cid} [").unwrap();
|
||||
}
|
||||
write!(entries, "{} ", f64::from(width) / 10.).unwrap();
|
||||
write!(entries, "{width} ").unwrap();
|
||||
previous = Some(cid);
|
||||
}
|
||||
entries.push_str("]]");
|
||||
}
|
||||
(format!("{name}-Identity-H"), cff.system_info(), entries)
|
||||
entries
|
||||
} else {
|
||||
(
|
||||
name.clone(),
|
||||
"/Registry (Adobe) /Ordering (Identity) /Supplement 0".to_owned(),
|
||||
format!(" /W [{widths}]"),
|
||||
)
|
||||
format!(" /W [{widths}]")
|
||||
};
|
||||
if let Some(metrics) = vertical_metrics {
|
||||
if metrics.origin_y != 880. || metrics.advance != 1000. {
|
||||
write!(width_entries, " /DW2 [{} {}]", metrics.origin_y, -metrics.advance).unwrap();
|
||||
}
|
||||
if !vertical_widths.is_empty() {
|
||||
width_entries.push_str(" /W2 [");
|
||||
for (cid, [advance, x, y]) in vertical_widths {
|
||||
write!(width_entries, "{cid} {cid} {} {x} {y} ", -advance).unwrap();
|
||||
}
|
||||
width_entries.push(']');
|
||||
}
|
||||
}
|
||||
let system_info = cid_cff.as_ref().map_or_else(
|
||||
|| "/Registry (Adobe) /Ordering (Identity) /Supplement 0".to_owned(),
|
||||
CidCff::system_info,
|
||||
);
|
||||
let type0_name = if cid_cff.is_some() || (vertical && cff.is_some()) {
|
||||
format!("{name}-{encoding}")
|
||||
} else {
|
||||
name.clone()
|
||||
};
|
||||
objects.push(format!(
|
||||
"<< /Type /Font /Subtype /Type0 /BaseFont /{type0_name} /Encoding /Identity-H /DescendantFonts [{cid_font} 0 R]{unicode_reference} >>"
|
||||
"<< /Type /Font /Subtype /Type0 /BaseFont /{type0_name} /Encoding /{encoding} /DescendantFonts [{cid_font} 0 R]{unicode_reference} >>"
|
||||
).into_bytes());
|
||||
objects.push(format!(
|
||||
"<< /Type /Font /Subtype /{subtype} /BaseFont /{name} /CIDSystemInfo << {system_info} >> /FontDescriptor {descriptor} 0 R{width_entries}{mapping} >>"
|
||||
@@ -521,6 +557,12 @@ impl EmbeddedFont {
|
||||
let glyph = &self.glyphs[&glyph];
|
||||
let [horizontal_scale, slant] = font.paint_transform();
|
||||
let device = font.device_transform();
|
||||
let vertical = font.is_vertical();
|
||||
let [a, b, c, d] = if vertical {
|
||||
[slant, 1., -horizontal_scale, 0.]
|
||||
} else {
|
||||
[horizontal_scale, 0., slant, 1.]
|
||||
};
|
||||
let embolden = font.paint_embolden();
|
||||
let emboldened = embolden > 0.;
|
||||
let relative = (xdv || device[1] != 0. || emboldened || font_colors) && device[0] != 0.;
|
||||
@@ -540,7 +582,7 @@ impl EmbeddedFont {
|
||||
// Td moves in text space. Precompensate for the shear and
|
||||
// retain the rounded displacement error in device units.
|
||||
output.push_str(">] TJ ");
|
||||
run.place_line(output, [x, y], device, bp_per_unit);
|
||||
run.place_line(output, [x, y], device, vertical, bp_per_unit);
|
||||
repositioned = true;
|
||||
}
|
||||
} else if (horizontal_em == 0. && delh != 0)
|
||||
@@ -554,8 +596,8 @@ impl EmbeddedFont {
|
||||
begin_actual_text(output, text, false);
|
||||
}
|
||||
let first = state.run.is_none();
|
||||
let start_relative = first && (xdv || emboldened || font_colors) && relative && state.matrix == device;
|
||||
state.matrix = device;
|
||||
let start_relative = first && (xdv || emboldened || font_colors) && relative && state.matrix == (device, vertical);
|
||||
state.matrix = (device, vertical);
|
||||
let run = state.run.get_or_insert_with(|| {
|
||||
let size_bp = size as f64 * bp_per_unit;
|
||||
output.push_str(&format!("BT /U{} {size_bp:.4} Tf ", font.id.index()));
|
||||
@@ -574,10 +616,10 @@ impl EmbeddedFont {
|
||||
// matrix at the page origin, then positions the first line.
|
||||
let [tx, ty] = page_origin.map(|coordinate| coordinate as f64 * bp_per_unit);
|
||||
output.push_str(&format!(
|
||||
"{horizontal_scale} 0 {slant} 1 {tx:.3} {ty:.3} Tm ",
|
||||
"{a} {b} {c} {d} {tx:.3} {ty:.3} Tm ",
|
||||
));
|
||||
run.start = page_origin;
|
||||
run.place_line(output, [x, y], device, bp_per_unit);
|
||||
run.place_line(output, [x, y], device, vertical, bp_per_unit);
|
||||
} else {
|
||||
let origin = if xdv { page_origin } else { [0, 0] };
|
||||
let [tx, ty] = std::array::from_fn(|axis| {
|
||||
@@ -586,7 +628,7 @@ impl EmbeddedFont {
|
||||
(rounded_coordinate(origin[axis], bp_per_unit).0 + delta, error)
|
||||
});
|
||||
output.push_str(&format!(
|
||||
"{horizontal_scale} 0 {slant} 1 {:.3} {:.3} Tm [<", tx.0, ty.0,
|
||||
"{a} {b} {c} {d} {:.3} {:.3} Tm [<", tx.0, ty.0,
|
||||
));
|
||||
if xdv || !relative {
|
||||
run.start = [x - tx.1, y - ty.1];
|
||||
@@ -604,7 +646,8 @@ impl EmbeddedFont {
|
||||
((run.start[0] + run.offset - x) as f64 * 1000. / horizontal_em) as i64
|
||||
};
|
||||
if kernel != 0 {
|
||||
output.push_str(&format!("> {kernel} <"));
|
||||
let adjustment = if vertical { -kernel } else { kernel };
|
||||
output.push_str(&format!("> {adjustment} <"));
|
||||
run.offset -= (kernel as f64 * (horizontal_em / 1000.)) as i64;
|
||||
}
|
||||
output.push_str(&format!("{:04X}", glyph.cid));
|
||||
|
||||
@@ -586,10 +586,15 @@ impl DisplayList {
|
||||
let horizontal = scale * extend;
|
||||
// Place the transformed outline in page units before
|
||||
// stroking. The font matrix must not distort the stroke.
|
||||
let transform = (embolden > 0.).then_some([horizontal, scale * slant, -scale]);
|
||||
let vertical = font.is_vertical().then(|| {
|
||||
font.vertical_paint_matrix(face, *glyph, *size as f64 / 65536.)
|
||||
});
|
||||
let transform = (embolden > 0.).then(|| {
|
||||
vertical.unwrap_or([horizontal, 0., scale * slant, -scale, 0., 0.])
|
||||
});
|
||||
let path_size = if transform.is_some() { *size } else { 0 };
|
||||
let path = opentype_paths.entry((font.id, *glyph, path_size))
|
||||
.or_insert_with(|| crate::opentype::outline(face, *glyph, transform));
|
||||
.or_insert_with(|| crate::opentype::outline_matrix(face, *glyph, transform));
|
||||
if !path.is_empty() {
|
||||
use std::fmt::Write as _;
|
||||
write!(
|
||||
@@ -598,7 +603,9 @@ impl DisplayList {
|
||||
escape(&font.name), escape(text),
|
||||
).unwrap();
|
||||
if transform.is_none() {
|
||||
if slant == 0. {
|
||||
if let Some([a, b, c, d, e, f]) = vertical {
|
||||
write!(out, " matrix({a:.9} {b:.9} {c:.9} {d:.9} {e:.9} {f:.9})").unwrap();
|
||||
} else if slant == 0. {
|
||||
write!(out, " scale({horizontal:.9} -{scale:.9})").unwrap();
|
||||
} else {
|
||||
let shear = scale * slant;
|
||||
|
||||
@@ -296,6 +296,7 @@ impl SourceMap {
|
||||
}
|
||||
}
|
||||
let mut mapped_pages = Vec::with_capacity(pages.len());
|
||||
let mut vertical_faces = std::collections::BTreeMap::new();
|
||||
for (page_index, page) in pages.iter().enumerate() {
|
||||
if page.sources.keys().any(|i| *i >= page.items.len()) {
|
||||
return Err("source map paint index outside page".into());
|
||||
@@ -417,11 +418,42 @@ impl SourceMap {
|
||||
let left = top_offset.min(bottom_offset).floor() as i64;
|
||||
let right = top_offset.max(bottom_offset).ceil() as i64;
|
||||
let stroke = (font.paint_embolden() / (2. * page.units.bp(1))).ceil() as i64;
|
||||
Some((PaintKind::OpenTypeGlyph { font: font.id.index(), glyph: *glyph }, Bounds {
|
||||
let mut bounds = Bounds {
|
||||
x: x + advance.min(&0) + left - stroke, y: y - ascent - stroke,
|
||||
width: advance.abs() + right - left + 2 * stroke,
|
||||
height: ascent + descent + 2 * stroke,
|
||||
}))
|
||||
};
|
||||
if font.is_vertical() {
|
||||
let face = match vertical_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(),
|
||||
};
|
||||
if let Some(rect) = face.glyph_bounding_box(rustybuzz::ttf_parser::GlyphId(*glyph)) {
|
||||
let [a, b, c, d, e, f] = font.vertical_paint_matrix(face, *glyph, *size as f64);
|
||||
let mut left = f64::INFINITY;
|
||||
let mut right = f64::NEG_INFINITY;
|
||||
let mut top = f64::INFINITY;
|
||||
let mut bottom = f64::NEG_INFINITY;
|
||||
for gx in [rect.x_min, rect.x_max].map(f64::from) {
|
||||
for gy in [rect.y_min, rect.y_max].map(f64::from) {
|
||||
let px = a * gx + c * gy + e;
|
||||
let py = b * gx + d * gy + f;
|
||||
left = left.min(px);
|
||||
right = right.max(px);
|
||||
top = top.min(py);
|
||||
bottom = bottom.max(py);
|
||||
}
|
||||
}
|
||||
let (left, top) = (left.floor() as i64, top.floor() as i64);
|
||||
bounds = Bounds {
|
||||
x: x + left - stroke,
|
||||
y: y + top - stroke,
|
||||
width: right.ceil() as i64 - left + 2 * stroke,
|
||||
height: bottom.ceil() as i64 - top + 2 * stroke,
|
||||
};
|
||||
}
|
||||
}
|
||||
Some((PaintKind::OpenTypeGlyph { font: font.id.index(), glyph: *glyph }, bounds))
|
||||
}
|
||||
DisplayItem::Rule {
|
||||
x,
|
||||
|
||||
@@ -819,6 +819,35 @@ letterspace-fresh.log 和 device-pdftex-spaced-moved.log。
|
||||
[原版字距虚拟字体构造](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L16400-L16492)
|
||||
[原版格式所写字体字段](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L30627-L30696)
|
||||
|
||||
### XeTeX 的 OpenType 纵排
|
||||
|
||||
字体请求记录文字方向,真实字体版本与纵排请求共同参与会话身份。
|
||||
使用 harfbuzz_rs 3.0.1 内建的 HarfBuzz 14.6 执行 TTB 成形,
|
||||
遵照 XeTeX 的零纵向原点和 FreeType 的未缩放纵向前进。已有的
|
||||
伸缩、倾斜、字距和字形度量作用到 TeX 盒内位置。PDF 使用
|
||||
Identity-V、字形实际横向宽度及纵向 VORG/vmtx 度量,按需写入
|
||||
DW2/W2。SVG 和来源映射使用同一 PDF 纵向原点及旋转方向。
|
||||
[上游成形原点和前进](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/xetexdir/XeTeXFontInst.cpp#L103-L158)
|
||||
[上游盒内位置](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/xetexdir/XeTeXLayoutInterface.cpp#L787-L832)
|
||||
[上游 PDF 纵排度量](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/dvipdfm-x/cidtype0.c#L148-L280)
|
||||
|
||||
六个真实字体对照各一页,包含原样 Harano Aji、横纵混排、
|
||||
不带纵排表的 Liberation Serif TrueType 和 Latin Modern CFF、
|
||||
五项实际 VORG 覆盖及格式重载。词框和 144 DPI 灰度像素全部
|
||||
一致,三个探针的 TeX 盒宽、高、深和空格宽度精确到 sp。
|
||||
格式将选字体命令保存在宏内,加载后再打开实际字体,两端正常
|
||||
出页。两端都拒绝转储已装入原生字体的格式,原诊断保留。
|
||||
TrueType 词框首轮最大坐标差 0.014346 bp,改为参考 PDF 整数
|
||||
单位后对齐。保留首轮 PDF 与回执,子集字节和宽度表表示有别。
|
||||
原有横排定向回归和新增 TrueType 纵排回归均通过。
|
||||
|
||||
四页会话修改真实字形、跨文件编辑和缺字体后恢复,三次成功
|
||||
修订均只更新第 2 页,后两次各复用 66 步。PDF、测量页面、
|
||||
预览 SVG、来源映射和 aux 与独立全量一致。缺字体保留上次
|
||||
已发布预览及 aux。证据在 target/p3-xetex-vertical。
|
||||
receipt.json 的 SHA-256 为 36dc39efac292154f2dcad58ddc333ce61849bd4045c6017ed82f1af66c45d92,
|
||||
revision.log 为 e55443174ab5b28e8f3c03a517b79ba02ae42c59daf4358c4868abba22bfc7d9。
|
||||
|
||||
### XeTeX 直接排版的 CID CFF 字体
|
||||
|
||||
XeTeX profile 从选定 OTF 或字体集合字面读取 CFF 的原始 CID 与
|
||||
|
||||
@@ -707,6 +707,73 @@ fn font_mapping_changes_recover_and_update_the_page_that_used_the_resource() {
|
||||
fs::remove_dir_all(p).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xetex_vertical_font_uses_tex_box_metrics_and_pdf_writing_mode() {
|
||||
use texrra_tex_core::execution::{Event, InputProfile};
|
||||
|
||||
let root = directory("xetex-vertical-font");
|
||||
fs::write(
|
||||
root.join("face.ttf"),
|
||||
include_bytes!("../assets/fonts-subset/LiberationSerif-Regular.ttf"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("main.tex"),
|
||||
br#"\catcode123=1 \catcode125=2
|
||||
\font\turned="[face.ttf]:vertical" at 12pt
|
||||
\XeTeXuseglyphmetrics=1
|
||||
\setbox0=\hbox{\turned AbCd Xyz}
|
||||
\message{VBOX=\number\wd0,\number\ht0,\number\dp0}
|
||||
\message{VSPACE=\number\fontdimen2\turned}
|
||||
\shipout\box0
|
||||
\end"#,
|
||||
)
|
||||
.unwrap();
|
||||
let mut job = request(&root);
|
||||
job.world = WorldConfig::new(&root);
|
||||
job.input_profile = InputProfile::XeTeX;
|
||||
let result = NativeCompiler::default().compile(job).unwrap();
|
||||
|
||||
// Exact values from XeTeX INITEX with the same Liberation Serif face.
|
||||
let messages: Vec<_> = result
|
||||
.execution
|
||||
.execution
|
||||
.events
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
Event::Message { text, .. } => Some(text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(messages, ["VBOX=5720064,545664,169727", "VSPACE=715008"]);
|
||||
|
||||
let pdf = lopdf::Document::load_mem(result.pdf.as_deref().unwrap()).unwrap();
|
||||
let font = pdf
|
||||
.objects
|
||||
.values()
|
||||
.filter_map(|object| object.as_dict().ok())
|
||||
.find(|font| {
|
||||
font.get(b"Encoding").and_then(lopdf::Object::as_name).ok()
|
||||
== Some(b"Identity-V".as_slice())
|
||||
})
|
||||
.unwrap();
|
||||
let descendant = font.get(b"DescendantFonts").unwrap().as_array().unwrap()[0]
|
||||
.as_reference()
|
||||
.unwrap();
|
||||
let metrics = pdf
|
||||
.get_dictionary(descendant)
|
||||
.unwrap()
|
||||
.get(b"DW2")
|
||||
.unwrap()
|
||||
.as_array()
|
||||
.unwrap();
|
||||
let metrics: Vec<_> = metrics.iter().map(|value| value.as_i64().unwrap()).collect();
|
||||
assert_eq!(metrics, [693, -909]);
|
||||
let content = pdf.get_page_content(pdf.get_pages()[&1]).unwrap();
|
||||
assert!(String::from_utf8(content).unwrap().contains("0 1 -1 0 "));
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xetex_glyph_bounds_and_dash_breaks_follow_revision_local_parameters() {
|
||||
use texrra_tex_core::execution::{Event, InputProfile};
|
||||
|
||||
Reference in new issue
Block a user