//! Selectable text for a committed preview. The existing page paint is unchanged. use texrra_engine::native::CompiledDocument; use texrra_tex_core::{ render::{DisplayItem, DisplayList}, source_map::{Bounds, MappedPaint, PageMap}, type1::glyph_unicode_text, }; #[derive(serde::Serialize)] pub(super) struct TextLayer { revision: u64, pages: Vec, } #[derive(serde::Serialize)] struct TextPage { index: usize, width: f64, height: f64, lines: Vec, } #[derive(serde::Serialize)] struct TextLine { x: f64, y: f64, width: f64, height: f64, text: String, } struct Glyph { left: f64, top: f64, right: f64, bottom: f64, baseline: f64, size: f64, text: String, } pub(super) fn for_document(document: &CompiledDocument) -> TextLayer { let pages = document .pages .iter() .zip(&document.source_map.pages) .map(|(page, map)| text_page(page, map)) .collect(); TextLayer { revision: document.revision(), pages, } } fn text_page(page: &DisplayList, map: &PageMap) -> TextPage { let [_, _, width, height] = map.bounds_bp(Bounds { x: 0, y: 0, width: map.width, height: map.height, }); let mut lines = Vec::new(); let mut run = None::; for glyph in map .entries .iter() .filter_map(|entry| glyph_at(page, map, entry)) { if let Some(current) = &mut run && current.continues(&glyph) { current.push(glyph); continue; } if let Some(current) = run.replace(Run::new(glyph)) { lines.push(current.finish()); } } if let Some(current) = run { lines.push(current.finish()); } TextPage { index: map.page_index, width, height, lines, } } fn glyph_at(page: &DisplayList, map: &PageMap, entry: &MappedPaint) -> Option { let from_sp = |value| page.units.bp(value) * f64::from(page.magnification) / 1000.0; let [left, top, width, height] = map.bounds_bp(entry.bounds); let (x, y, size, advance, position_tolerance, text) = match page.items.get(entry.item_index)? { DisplayItem::NativeGlyph { x, y, size, slot, font, paint, character, } => { let text = paint .as_ref() .and_then(|paint| paint.encoding.get(usize::from(*slot))) .and_then(|name| glyph_unicode_text(name)); // For remapped fonts the retained character can be more accurate // than the original glyph name. Prefer a full name-derived ligature // when its first character agrees with the resolved character. let text = match text { Some(text) if text.starts_with(*character) => text, _ if *character != '\u{fffd}' => character.to_string(), _ => return None, }; let design_size = from_sp(font.size_sp()); let size_bp = from_sp(*size); if design_size <= 0.0 { return None; } let advance = from_sp(font.advance(*slot)) * size_bp / design_size; (*x, *y, size_bp, advance, 0.02, text) } DisplayItem::OpenTypeGlyph { x, y, size, advance, text, .. } => { let size = from_sp(*size); (*x, *y, size, from_sp(*advance), 0.2 * size, text.clone()) } _ => return None, }; let baseline = from_sp(y); let bottom = top + height; // The current DOM overlay is horizontal. The source map has already // projected graphics state and crop boxes; exclude glyphs whose final // projected box cannot be identified with the horizontal placement. if size <= 0.0 || width <= 0.0 || height <= 0.0 || height > size * 1.5 || advance <= 0.0 || (left - from_sp(x)).abs() > position_tolerance || (width - advance).abs() > position_tolerance.max(size * 0.03) || baseline < top - 0.02 || baseline > bottom + 0.02 { return None; } let text = copy_text(&text); if text.trim().is_empty() { return None; } Some(Glyph { left, top, right: left + width, bottom, baseline, size, text, }) } fn copy_text(text: &str) -> String { let mut out = String::with_capacity(text.len()); for ch in text.chars() { match ch { 'ff' => out.push_str("ff"), 'fi' => out.push_str("fi"), 'fl' => out.push_str("fl"), 'ffi' => out.push_str("ffi"), 'ffl' => out.push_str("ffl"), 'ſt' => out.push_str("ſt"), 'st' => out.push_str("st"), ch if !ch.is_control() => out.push(ch), _ => {} } } out } struct Run { left: f64, top: f64, right: f64, bottom: f64, baseline: f64, last_left: f64, last_right: f64, last_size: f64, text: String, } impl Run { fn new(glyph: Glyph) -> Self { Self { left: glyph.left, top: glyph.top, right: glyph.right, bottom: glyph.bottom, baseline: glyph.baseline, last_left: glyph.left, last_right: glyph.right, last_size: glyph.size, text: glyph.text, } } fn continues(&self, glyph: &Glyph) -> bool { let em = self.last_size.min(glyph.size); // Long horizontal moves indicate independent blocks or table cells. // Keep paint order across those blocks and therefore across columns. (self.baseline - glyph.baseline).abs() <= 0.02 && glyph.left >= self.last_left - em * 0.2 && glyph.left - self.last_right <= em * 1.25 } fn push(&mut self, glyph: Glyph) { let em = self.last_size.min(glyph.size); // TeX interword glue is between positioned glyphs, not an item. if glyph.left - self.last_right >= em * 0.15 { self.text.push(' '); } self.text.push_str(&glyph.text); self.left = self.left.min(glyph.left); self.top = self.top.min(glyph.top); self.right = self.right.max(glyph.right); self.bottom = self.bottom.max(glyph.bottom); self.last_left = glyph.left; self.last_right = glyph.right; self.last_size = glyph.size; } fn finish(self) -> TextLine { TextLine { x: self.left, y: self.top, width: self.right - self.left, height: self.bottom - self.top, text: self.text, } } } #[cfg(test)] mod tests { use super::*; #[test] fn keeps_interword_glue_and_separates_distant_columns() { let glyph = |left: f64, text: &str| Glyph { left, top: 5.0, right: left + 5.0, bottom: 12.0, baseline: 11.0, size: 10.0, text: copy_text(text), }; let mut run = Run::new(glyph(10.0, "A")); let adjacent = glyph(15.0, "ffi"); assert!(run.continues(&adjacent)); run.push(adjacent); let next_word = glyph(23.0, "x"); assert!(run.continues(&next_word)); run.push(next_word); assert!(!run.continues(&glyph(110.0, "B"))); let line = run.finish(); assert_eq!(line.text, "Affi x"); assert_eq!((line.x, line.width), (10.0, 18.0)); } }