//! 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, effective_size: i64, expansion: i32, v: i64, start_h: i64, delta_h: i64, opened: bool, } impl NativeText { pub(super) fn glyph( text: &mut Option, out: &mut PageContent, x: i64, y: i64, font: &NativeFont, paint: &crate::native_font::NativeFontPaint, slot: u8, height: i64, digits: u8, space: Option, dedicated: Option<&ResolvedSpaceFont>, ) { let first = text.is_none(); let state = text.get_or_insert_with(|| { out.push_str("BT\n"); Self { font: None, effective_size: 0, expansion: 0, v: height, start_h: 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 += Self::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); out.push_str("( ) Tj\n"); } state.select_font(out, font); if state.expansion != font.expansion { 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, font.expansion); let (v, v_out) = state.vertical_move(y, digits); if first || v != 0 || shift.abs() >= 32768 || space == Some(SpaceUse::Dedicated) { state.close_string(out); 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 += Self::char_advance(font, paint, slot, state.effective_size); } fn select_font(&mut self, out: &mut PageContent, font: &NativeFont) { 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 = size; self.font = Some(font.id); if !out.measuring { out.push_str(&format!( "/N{} {} Tf\n", font.id.index(), print_decimal(number, 4) )); } } } fn char_advance( font: &NativeFont, paint: &crate::native_font::NativeFontPaint, slot: u8, size: i64, ) -> i64 { let advance = match &paint.program { crate::native_font::NativeFontProgram::Pk(pk) => pk.advances[&slot], crate::native_font::NativeFontProgram::Type1(_) => { divide_scaled(font.metrics().width(char::from(slot)), size, 4).1 } }; if font.expansion == 0 { advance } else { crate::pdf_device::magnify(advance, 1000 + font.expansion) } } fn horizontal_move(&self, x: i64, size: i64, expansion: i32) -> (i64, i64) { divide_scaled( x - self.start_h - self.delta_h, Self::expanded_size(size, expansion), 3, ) } 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, out: &mut PageContent, x: i64, y: i64, height: i64, digits: u8, dedicated: &ResolvedSpaceFont, ) { Self::glyph( text, out, x, y, &dedicated.font, &dedicated.paint, b' ', height, 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, out: &mut PageContent) { if let Some(text) = text { text.close_string(out); } } pub(super) fn finish(text: &mut Option, out: &mut PageContent) { if let Some(mut text) = text.take() { text.close_string(out); if text.expansion != 0 { out.push_str("100 Tz\n"); } out.push_str("ET\n"); } } } #[derive(Default)] pub(super) struct FontHistory { used: BTreeSet, first_scalable: BTreeMap, } 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::Type1(_) ) && !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. pub(super) fn plan_spaces( page: &DisplayList, fonts: &mut FontHistory, load: impl FnOnce() -> Result, ) -> Result { 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(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 = 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() { plan.dedicated = Some(load.take().expect("space font loader used once")()?); } 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, cursor.expansion).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() { plan.dedicated = Some(load.take().expect("space font loader used once")()?); } 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, paint, *slot, page.height, digits, space, plan.dedicated.as_ref(), ); } DisplayItem::PdfGraphics { operation: PdfGraphics::Literal { mode: PdfLiteralMode::Direct, .. }, .. } => { NativeText::break_string(&mut text, &mut out); } _ => NativeText::finish(&mut text, &mut out), } } Ok(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"); }