Files
texrra-engine/crates/texrra-tex-core/src/pdf_text.rs
T

531 lines
18 KiB
Rust

//! Native pdfTeX text cursor, in original TeX sp, before the page matrix.
use super::PageContent;
use crate::{
execution::FontId,
native_font::NativeFont,
pdf_device::{
PdfGraphics, PdfLiteralMode, divide_scaled, print_decimal, print_sp,
text_spaces::{ResolvedSpaceFont, SpaceOperation, SpacePlan, SpaceUse},
},
render::{DisplayItem, DisplayList},
};
use std::collections::{BTreeMap, BTreeSet};
const ONE_BP: i64 = 65_782;
pub(super) struct NativeText {
font: Option<FontId>,
effective_size: i64,
expansion: i32,
xdv: bool,
v: i64,
start_h: i64,
delta_h: i64,
opened: bool,
}
impl NativeText {
pub(super) fn glyph(
text: &mut Option<Self>,
out: &mut PageContent,
x: i64,
y: i64,
font: &NativeFont,
resource: FontId,
paint: &crate::native_font::NativeFontPaint,
slot: u8,
height: i64,
xdv_origin: Option<i64>,
digits: u8,
space: Option<SpaceUse>,
dedicated: Option<&ResolvedSpaceFont>,
) {
let first = text.is_none();
let state = text.get_or_insert_with(|| {
out.push_str("BT\n");
if let Some(origin) = xdv_origin {
let [h, v] = out.origin.position();
out.push_str(&format!(
"1 0 0 1 {} {} Tm\n",
print_sp(origin - h, digits),
print_sp(height - origin - v, digits),
));
}
Self {
font: None,
effective_size: 0,
expansion: 0,
xdv: xdv_origin.is_some(),
v: xdv_origin.unwrap_or(height),
start_h: xdv_origin.unwrap_or(0),
delta_h: 0,
opened: false,
}
});
if space == Some(SpaceUse::InFont) {
out.push_str("<20>");
let (_, size) = divide_scaled(font.size_sp(), 6_578_176, 6);
state.delta_h += state.char_advance(font, paint, b' ', size);
}
if space == Some(SpaceUse::Dedicated) {
let dedicated = dedicated.expect("resolved PDF space font");
state.select_font(out, &dedicated.font, dedicated.font.id);
out.push_str("( ) Tj\n");
}
state.select_font(out, font, resource);
let expansion_changed = state.expansion != font.expansion;
if state.xdv && expansion_changed {
state.close_string(out);
state.expansion = font.expansion;
if !out.measuring {
out.push_str(&format!(
"{} Tz\n",
print_decimal(i64::from(1000 + font.expansion), 1)
));
}
}
let (mut shift, shift_out) = state.horizontal_move(x, state.effective_size);
let (v, v_out) = state.vertical_move(y, digits);
let reset_line = if state.xdv {
let delta = x - state.start_h - state.delta_h;
!state.opened
|| v != 0
|| delta.abs() > 3 * Self::expanded_size(state.effective_size, state.expansion)
} else {
v != 0 || shift.abs() >= 32768 || expansion_changed
};
if first || reset_line || space == Some(SpaceUse::Dedicated)
{
state.close_string(out);
if !state.xdv && (font.expansion != 0 || state.expansion != 0) {
let (h, h_out) = divide_scaled(x, 6_578_176, digits + 2);
let (v, v_out) = divide_scaled(height - y, 6_578_176, digits + 2);
if !out.measuring {
out.push_str(&format!(
"{} 0 0 1 {} {} Tm\n",
print_decimal(i64::from(1000 + font.expansion), 3),
print_decimal(h, digits),
print_decimal(v, digits),
));
}
state.start_h = h_out;
state.v = height - v_out;
state.expansion = font.expansion;
} else {
let (h, h_out) = divide_scaled(x - state.start_h, 6_578_176, digits + 2);
if !out.measuring {
out.push_str(&format!(
"{} {} Td\n",
print_decimal(h, digits),
print_decimal(v, digits),
));
}
state.start_h += h_out;
state.v -= v_out;
}
state.delta_h = 0;
shift = 0;
}
if !state.opened {
out.push(b'[');
state.opened = true;
}
if shift != 0 {
if !out.measuring {
out.push_str(&format!(" {} ", -shift));
}
state.delta_h += shift_out;
}
if !out.measuring {
out.push_str(&format!("<{slot:02X}>"));
}
state.delta_h += state.char_advance(font, paint, slot, state.effective_size);
}
fn select_font(&mut self, out: &mut PageContent, font: &NativeFont, resource: FontId) {
if self.font != Some(font.id) {
self.close_string(out);
let (number, size) = divide_scaled(font.size_sp(), 6_578_176, 6);
self.effective_size = if self.xdv { font.size_sp() } else { size };
self.font = Some(font.id);
if !out.measuring {
out.push_str(&format!(
"/N{} {} Tf\n",
resource.index(),
print_decimal(number, 4)
));
}
}
}
fn char_advance(
&self,
font: &NativeFont,
paint: &crate::native_font::NativeFontPaint,
slot: u8,
size: i64,
) -> i64 {
if self.xdv {
// xdvipdfmx follows the advances in the DVI/XDV stream. The PDF
// viewer separately uses the embedded font's declared widths.
return crate::pdf_device::magnify(
font.metrics().xdv_width(slot),
1000 + font.expansion,
);
}
let expansion = self.expansion;
let advance = match &paint.program {
crate::native_font::NativeFontProgram::Pk(pk) => pk.advances[&slot],
_ => {
let factor = i64::from(1000 + expansion);
let width = Self::round_scale(font.advance(slot), 1000, factor);
let (units, advance) = divide_scaled(width, size, 4);
if expansion != 0 {
Self::round_scale(size * units, 1, 10_000)
} else {
advance
}
}
};
crate::pdf_device::magnify(advance, 1000 + expansion)
}
fn horizontal_move(&self, x: i64, size: i64) -> (i64, i64) {
let delta = x - self.start_h - self.delta_h;
if self.xdv {
let size = Self::expanded_size(size, self.expansion);
let units = delta * 1000 / size;
return (units, units * size / 1000);
}
if self.expansion == 0 {
return divide_scaled(delta, size, 3);
}
let unscaled = Self::round_scale(delta, 1000, i64::from(1000 + self.expansion));
let (units, _) = divide_scaled(unscaled, size, 3);
let advance = Self::round_scale(size * units, 1, 1000);
(units, crate::pdf_device::magnify(advance, 1000 + self.expansion))
}
fn round_scale(value: i64, multiplier: i64, denominator: i64) -> i64 {
value.signum() * ((value.abs() * multiplier + denominator / 2) / denominator)
}
fn expanded_size(size: i64, expansion: i32) -> i64 {
if expansion == 0 {
size
} else {
crate::pdf_device::magnify(size, 1000 + expansion)
}
}
fn vertical_move(&self, y: i64, digits: u8) -> (i64, i64) {
let minimum = divide_scaled(6_578_176, 10i64.pow(u32::from(digits) + 2), 0).0;
if (self.v - y).abs() >= minimum {
divide_scaled(self.v - y, 6_578_176, digits + 2)
} else {
(0, 0)
}
}
pub(super) fn explicit_space(
text: &mut Option<Self>,
out: &mut PageContent,
x: i64,
y: i64,
height: i64,
digits: u8,
dedicated: &ResolvedSpaceFont,
) {
Self::glyph(
text,
out,
x,
y,
&dedicated.font,
dedicated.font.id,
&dedicated.paint,
b' ',
height,
None,
digits,
None,
None,
);
Self::break_string(text, out);
}
fn close_string(&mut self, out: &mut PageContent) {
if self.opened {
out.push_str("] TJ\n");
self.opened = false;
}
}
pub(super) fn break_string(text: &mut Option<Self>, out: &mut PageContent) {
if let Some(text) = text {
text.close_string(out);
}
}
pub(super) fn finish(text: &mut Option<Self>, out: &mut PageContent) {
if let Some(mut text) = text.take() {
text.close_string(out);
if text.xdv && text.expansion != 0 {
out.push_str("100 Tz\n");
}
out.push_str("ET\n");
}
}
}
#[derive(Clone, Default)]
pub(crate) struct FontHistory {
used: BTreeSet<FontId>,
first_scalable: BTreeMap<String, FontId>,
}
impl FontHistory {
fn record(&mut self, font: &NativeFont, paint: &crate::native_font::NativeFontPaint) {
if self.used.insert(font.id)
&& !matches!(paint.program, crate::native_font::NativeFontProgram::Pk(_))
&& !self.first_scalable.contains_key(&font.name)
{
self.first_scalable.insert(font.name.clone(), font.id);
}
}
fn has_space(&self, font: &NativeFont, paint: &crate::native_font::NativeFontPaint) -> bool {
// Only the first font for a shared scalable TFM gets the space test.
self.first_scalable
.get(&font.name)
.is_none_or(|id| *id == font.id)
&& paint.has_pdf_space(font)
}
}
/// Determine real font use with the same text moves used by the PDF writer.
/// A probe returns None as soon as it would first load the dedicated font.
pub(crate) fn plan_spaces(
page: &DisplayList,
fonts: &mut FontHistory,
load: impl FnOnce() -> Result<Option<ResolvedSpaceFont>, String>,
) -> Result<Option<SpacePlan>, String> {
let Some(settings) = &page.pdf_text_spaces else {
for item in &page.items {
if let DisplayItem::NativeGlyph {
font,
paint: Some(paint),
..
} = item
{
fonts.record(font, paint);
}
}
return Ok(Some(SpacePlan::default()));
};
let digits = page.pdf.as_ref().map_or(3, |pdf| pdf.file.decimal_digits);
let mut automatic = settings.automatic_at_start;
let mut plan = SpacePlan::default();
let mut load = Some(load);
let mut text: Option<NativeText> = None;
let mut out = PageContent::measuring();
for (index, item) in page.items.iter().enumerate() {
match item {
DisplayItem::PdfTextSpace {
operation: SpaceOperation::Automatic(enabled),
..
} => {
automatic = *enabled;
}
DisplayItem::PdfTextSpace {
x,
y,
operation: SpaceOperation::Explicit,
} => {
if plan.dedicated.is_none() {
let Some(font) = load.take().expect("space font loader used once")()? else {
return Ok(None);
};
plan.dedicated = Some(font);
}
let dedicated = plan.dedicated.as_ref().unwrap();
fonts.record(&dedicated.font, &dedicated.paint);
NativeText::explicit_space(
&mut text,
&mut out,
*x,
*y,
page.height,
digits,
dedicated,
);
}
DisplayItem::NativeGlyph {
x,
y,
font,
paint,
slot,
..
} => {
let paint = paint
.as_ref()
.ok_or("native font was not resolved before planning PDF text spaces")?;
let (_, size) = divide_scaled(font.size_sp(), 6_578_176, 6);
if NativeText::expanded_size(size, font.expansion) <= 0 {
return Err("native PDF font size rounds to zero in the pdfTeX profile".into());
}
let already_used = fonts.used.contains(&font.id);
fonts.record(font, paint);
let mut space = None;
if let Some(cursor) = &text
&& automatic
{
let (width, shrink) = settings
.parameters
.get(font.id.index() as usize)
.copied()
.unwrap_or_else(|| {
(
font.metrics().param(1) as i32,
font.metrics().param(3) as i32,
)
});
let prior_size = NativeText::expanded_size(size, cursor.expansion);
let movement = if prior_size > 0 {
cursor.horizontal_move(*x, size).1
} else {
0
};
if i64::from(width) > ONE_BP
&& movement > i64::from(width) - i64::from(shrink) - ONE_BP / 10
&& cursor.vertical_move(*y, digits).0 == 0
{
if fonts.has_space(font, paint) {
if cursor.opened && (cursor.font == Some(font.id) || already_used) {
space = Some(SpaceUse::InFont);
let previous = cursor.font.expect("open text string has a font");
plan.in_font.insert(previous);
plan.spaces_in_previous_font |= previous != font.id;
}
} else {
space = Some(SpaceUse::Dedicated);
if plan.dedicated.is_none() {
let Some(font) = load.take().expect("space font loader used once")()? else {
return Ok(None);
};
plan.dedicated = Some(font);
}
let dedicated = plan.dedicated.as_ref().unwrap();
fonts.record(&dedicated.font, &dedicated.paint);
}
}
}
if let Some(space) = space {
plan.before_glyph.insert(index, space);
}
NativeText::glyph(
&mut text,
&mut out,
*x,
*y,
font,
font.id,
paint,
*slot,
page.height,
None,
digits,
space,
plan.dedicated.as_ref(),
);
}
DisplayItem::PdfGraphics {
operation:
PdfGraphics::Literal {
mode: PdfLiteralMode::Direct,
..
},
..
}
| DisplayItem::PdfColor {
mode: PdfLiteralMode::Direct,
..
} => {
NativeText::break_string(&mut text, &mut out);
}
_ => NativeText::finish(&mut text, &mut out),
}
}
Ok(Some(plan))
}
pub(super) fn rule(
out: &mut PageContent,
x: i64,
top: i64,
w: i64,
h: i64,
page_height: i64,
digits: u8,
) {
if w <= 0 || h <= 0 {
return;
}
let bottom = page_height - top - h;
out.push_str("q\n");
if h <= 65_782 {
out.push_str(&format!(
"1 0 0 1 {} {} cm []0 d 0 J {} w 0 0 m {} 0 l S\n",
print_sp(x, digits),
print_sp(bottom + (h + 1) / 2, digits),
print_sp(h, digits),
print_sp(w, digits)
));
} else if w <= 65_782 {
out.push_str(&format!(
"1 0 0 1 {} {} cm []0 d 0 J {} w 0 0 m 0 {} l S\n",
print_sp(x + (w + 1) / 2, digits),
print_sp(bottom, digits),
print_sp(w, digits),
print_sp(h, digits)
));
} else {
out.push_str(&format!(
"1 0 0 1 {} {} cm 0 0 {} {} re f\n",
print_sp(x, digits),
print_sp(bottom, digits),
print_sp(w, digits),
print_sp(h, digits)
));
}
out.push_str("Q\n");
}
pub(super) fn xdv_rule(
out: &mut PageContent,
x: i64,
y: i64,
width: i64,
height: i64,
digits: u8,
) {
if width <= 0 || height <= 0 {
return;
}
out.push_str("q\n");
// The XDV driver strokes rules up to 5 bp wide and fills thicker rules.
if width.min(height) <= 5 * 6_578_176 / 100 {
let (thickness, points) = if width > height {
(height, [x, y + height / 2, x + width, y + height / 2])
} else {
(width, [x + width / 2, y, x + width / 2, y + height])
};
let [x1, y1, x2, y2] = points.map(|value| print_sp(value, digits));
let thickness = print_sp(thickness, digits + 1);
out.push_str(&format!("{thickness} w {x1} {y1} m {x2} {y2} l S\n"));
} else {
let [x, y, width, height] = [x, y, width, height].map(|value| print_sp(value, digits));
out.push_str(&format!("{x} {y} {width} {height} re f\n"));
}
out.push_str("Q\n");
}