Match XDV PDF text cursor and Type 1 descriptor metrics

This commit is contained in:
gloamxun committed 2026-11-26 13:49:41 +08:00
1 parent eb0afccc03
commit bd840df538
7 files changed
+144 -19

No files matched your search

+17 -6
View File
@@ -6,11 +6,11 @@ use crate::{
resources::{LoadedResource, ResourceVersion},
tfm::TfmMetrics,
type1::{Type1Font, Type1Transform},
type1_outline::Type1Outlines,
type1_outline::{Type1Outlines, XdvDescriptor},
};
use std::{
collections::{BTreeMap, VecDeque},
sync::{Arc, Mutex},
sync::{Arc, Mutex, OnceLock},
};
mod map;
mod virtual_paint;
@@ -25,6 +25,8 @@ pub struct NativeFontPaint {
pub glyph_paths: BTreeMap<u8, String>,
pub bbox: [i32; 4],
pub stem_v: i32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) xdv_descriptor: Option<XdvDescriptor>,
pub resources: Vec<crate::resources::ResourceVersion>,
#[serde(default, skip_serializing_if = "Option::is_none")]
program_index: Option<usize>,
@@ -200,6 +202,7 @@ struct DecodedType1 {
outlines: Type1Outlines,
bbox: [i32; 4],
stem_v: i32,
xdv_descriptor: OnceLock<Result<XdvDescriptor, String>>,
}
impl DecodedType1 {
@@ -223,6 +226,7 @@ impl DecodedType1 {
outlines,
bbox,
stem_v,
xdv_descriptor: OnceLock::new(),
})
}
}
@@ -363,10 +367,9 @@ fn resolve_physical_fonts(
.or_else(|| default_map.as_ref().map(|map| &map.version));
let mut resolved = BTreeMap::new();
let mut pk_resolved = BTreeMap::new();
let device = pages
.iter()
.find_map(|p| p.pdf.as_ref())
.map(|p| p.file.clone());
let device = pages.iter().find_map(|page| page.pdf.as_ref());
let xdv = device.is_some_and(|pdf| pdf.driver == crate::pdf_device::PdfDriver::Xdv);
let device = device.map(|pdf| pdf.file.clone());
let mut cache: BTreeMap<_, (NativeFontPaint, Arc<DecodedType1>)> = BTreeMap::new();
for (id, (font, slots, expanded)) in used {
let entry = if font.pdf_space_font && font.name == "pdftexspace" {
@@ -437,6 +440,7 @@ fn resolve_physical_fonts(
glyph_paths,
bbox: bbox.unwrap(),
stem_v: 0,
xdv_descriptor: None,
resources: entry.as_ref().and_then(|entry| entry.version.as_ref())
.or(default_version).cloned().into_iter()
.chain(std::iter::once(resource.version)).collect(),
@@ -486,6 +490,13 @@ fn resolve_physical_fonts(
glyph_paths: BTreeMap::new(),
bbox: decoded.bbox,
stem_v: decoded.stem_v,
xdv_descriptor: if xdv {
Some(decoded.xdv_descriptor.get_or_init(|| {
decoded.outlines.xdv_descriptor(program.bbox)
}).clone()?)
} else {
None
},
resources,
program_index,
},
+15 -3
View File
@@ -743,6 +743,7 @@ fn page_content(
let mut opentype_text = opentype_fonts::TextState::default();
let bp_per_unit = list.units.bp(1);
let one_inch = (72_000. / (bp_per_unit * f64::from(list.magnification))).round() as i64;
let xdv = list.pdf.as_ref().is_some_and(|pdf| pdf.driver == PdfDriver::Xdv);
for (index, item) in list.items.iter().enumerate() {
if !matches!(item, DisplayItem::OpenTypeGlyph { .. }) {
opentype_text.finish(&mut content);
@@ -822,6 +823,7 @@ fn page_content(
paint.as_ref().unwrap(),
*slot,
height,
xdv.then_some(one_inch),
digits,
list.pdf_space_plan.as_ref().and_then(|plan| plan.before_glyph.get(&index)).copied(),
list.pdf_space_plan.as_ref().and_then(|plan| plan.dedicated.as_ref()),
@@ -879,7 +881,7 @@ fn page_content(
opentype[&font.id].paint(
&mut opentype_text, &mut content, font, *glyph, text,
*size, *x - h, height - *y - v, bp_per_unit,
[one_inch - h, height - one_inch - v], !font_opacities.is_empty(),
[one_inch - h, height - one_inch - v], xdv, !font_opacities.is_empty(),
);
}
DisplayItem::NativeGlyph {
@@ -1678,8 +1680,18 @@ fn write_native_type1_descriptor(
} else {
font.italic_angle.parse::<f64>().unwrap_or(0.).round().to_string()
};
let stem_v = paint.stem_v;
objects.push(format!("<< /Type /FontDescriptor /FontName /{name} /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /XHeight {x_height} /StemV {stem_v} /FontFile {program} 0 R >>").into_bytes());
let descriptor_bytes = if let Some(xdv) = paint.xdv_descriptor {
let [left, bottom, right, top] = font.bbox;
let [ascent, descent, cap, stem_v] = xdv.metrics();
let flags = flags | (i32::from(!font.name.contains("Sans")) << 1)
| (i32::from(font.name.contains("Caps")) << 17)
| (i32::from(xdv.force_bold) << 18);
format!("<< /Type /FontDescriptor /FontName /{name} /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /StemV {stem_v} /FontFile {program} 0 R >>")
} else {
let stem_v = paint.stem_v;
format!("<< /Type /FontDescriptor /FontName /{name} /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /XHeight {x_height} /StemV {stem_v} /FontFile {program} 0 R >>")
};
objects.push(descriptor_bytes.into_bytes());
objects.push(objects::stream(
&format!(
"/Length1 {} /Length2 {} /Length3 {}",
+15 -8
View File
@@ -337,6 +337,7 @@ impl EmbeddedFont {
y: i64,
bp_per_unit: f64,
page_origin: [i64; 2],
xdv: bool,
font_colors: bool,
) {
let glyph = &self.glyphs[&glyph];
@@ -344,7 +345,7 @@ impl EmbeddedFont {
let device = font.device_transform();
let embolden = font.paint_embolden();
let emboldened = embolden > 0.;
let relative = (device[1] != 0. || emboldened || font_colors) && device[0] != 0.;
let relative = (xdv || device[1] != 0. || emboldened || font_colors) && device[0] != 0.;
let horizontal_em = size as f64 * if relative { device[0] } else { horizontal_scale };
let override_text = glyph
.cluster_text
@@ -375,7 +376,7 @@ impl EmbeddedFont {
begin_actual_text(output, text, false);
}
let first = state.run.is_none();
let start_relative = first && (emboldened || font_colors) && relative && state.matrix == device;
let start_relative = first && (xdv || emboldened || font_colors) && relative && state.matrix == device;
state.matrix = device;
let run = state.run.get_or_insert_with(|| {
let size_bp = size as f64 * bp_per_unit;
@@ -400,14 +401,20 @@ impl EmbeddedFont {
run.start = page_origin;
run.place_line(output, [x, y], device, bp_per_unit);
} else {
let coordinates = [x, y].map(|coordinate| rounded_coordinate(coordinate, bp_per_unit));
let origin = if xdv { page_origin } else { [0, 0] };
let [tx, ty] = std::array::from_fn(|axis| {
let value = [x, y][axis];
let (delta, error) = rounded_coordinate(value - origin[axis], bp_per_unit);
(rounded_coordinate(origin[axis], bp_per_unit).0 + delta, error)
});
output.push_str(&format!(
"{horizontal_scale} 0 {slant} 1 {:.3} {:.3} Tm [<",
coordinates[0].0, coordinates[1].0,
"{horizontal_scale} 0 {slant} 1 {:.3} {:.3} Tm [<", tx.0, ty.0,
));
if !relative {
run.start = [x - coordinates[0].1, y - coordinates[1].1];
run.offset = coordinates[0].1;
if xdv || !relative {
run.start = [x - tx.1, y - ty.1];
}
if !xdv && !relative {
run.offset = tx.1;
}
}
run
+12 -2
View File
@@ -31,6 +31,7 @@ impl NativeText {
paint: &crate::native_font::NativeFontPaint,
slot: u8,
height: i64,
xdv_origin: Option<i64>,
digits: u8,
space: Option<SpaceUse>,
dedicated: Option<&ResolvedSpaceFont>,
@@ -38,12 +39,19 @@ impl NativeText {
let first = text.is_none();
let state = text.get_or_insert_with(|| {
out.push_str("BT\n");
if let Some(origin) = xdv_origin {
out.push_str(&format!(
"1 0 0 1 {} {} Tm\n",
print_sp(origin, digits),
print_sp(height - origin, digits),
));
}
Self {
font: None,
effective_size: 0,
expansion: 0,
v: height,
start_h: 0,
v: xdv_origin.unwrap_or(height),
start_h: xdv_origin.unwrap_or(0),
delta_h: 0,
opened: false,
}
@@ -187,6 +195,7 @@ impl NativeText {
&dedicated.paint,
b' ',
height,
None,
digits,
None,
None,
@@ -375,6 +384,7 @@ pub(crate) fn plan_spaces(
paint,
*slot,
page.height,
None,
digits,
space,
plan.dedicated.as_ref(),
@@ -125,12 +125,25 @@ impl<'a> Tokens<'a> {
Ok(bytes)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(crate) struct XdvDescriptor {
metrics: [u64; 4],
pub(crate) force_bold: bool,
}
impl XdvDescriptor {
pub(crate) fn metrics(self) -> [f64; 4] {
self.metrics.map(f64::from_bits)
}
}
#[derive(Clone, Debug)]
pub struct Type1Outlines {
subrs: Vec<Option<Vec<u8>>>,
glyphs: BTreeMap<String, Vec<u8>>,
matrix: [f64; 6],
std_vw: Option<f64>,
force_bold: bool,
}
impl Type1Outlines {
pub fn parse(font: &Type1Font) -> Result<Self, String> {
@@ -152,6 +165,7 @@ impl Type1Outlines {
let (mut len_iv, mut subrs, mut glyphs, mut in_subrs) =
(4i32, Vec::new(), BTreeMap::new(), false);
let mut std_vw = None;
let mut force_bold = false;
while let Some(token) = tokens.next()? {
match token.as_str() {
"/lenIV" => {
@@ -176,6 +190,7 @@ impl Type1Outlines {
}
std_vw = Some(width);
}
"/ForceBold" => force_bold = tokens.required()? == "true",
"/Subrs" => {
let count = tokens.number()?;
if count > 65536 {
@@ -245,6 +260,7 @@ impl Type1Outlines {
glyphs,
matrix,
std_vw,
force_bold,
})
}
/// PDF uses a 1000-unit glyph space. Zero denotes an unknown stem width.
@@ -284,6 +300,39 @@ impl Type1Outlines {
result[3].ceil() as i32,
]
}
pub(crate) fn xdv_descriptor(&self, bbox: [i32; 4]) -> Result<XdvDescriptor, String> {
let height = |names: &[&str], top: bool, fallback: i32| -> Result<f64, String> {
let Some(name) = names.iter().find(|name| self.has_glyph(name)) else {
return Ok(f64::from(fallback));
};
let mut budget = 1_000_000;
let mut bound: Option<f64> = None;
let mut include = |y: f64| {
bound = Some(bound.map_or(y, |old| if top { old.max(y) } else { old.min(y) }));
};
for command in self.commands(name, 0, &mut budget)? {
match command {
Command::Move(_, y) | Command::Line(_, y) => include(y),
Command::Curve(_, a, _, b, _, c) => {
include(a);
include(b);
include(c);
}
Command::Close => {}
}
}
Ok(bound.unwrap_or(0.))
};
let cap = height(&["H", "P", "Pi", "Rho"], true, bbox[3])?;
let ascent = height(&["b", "h", "lambda"], true, bbox[3])?;
let descent = height(&["p", "q", "mu", "eta"], false, bbox[1])?;
let stem = self.std_vw.unwrap_or(88.);
Ok(XdvDescriptor {
metrics: [ascent, descent, cap, stem].map(f64::to_bits),
force_bold: self.force_bold,
})
}
pub fn has_glyph(&self, name: &str) -> bool {
self.glyphs.contains_key(name)
}