//! Revision-local source maps from retained execution provenance and paint. //! //! Bounds describe measured glyph boxes, not outline ink. Unknown origins are //! reported explicitly; text, paragraph spans and neighbouring paint are never //! used to infer an origin. Source IDs are local to this revision, including //! independent opens of the same input stream. use crate::{ execution::{GeneratedInput, RevisionExecution, SourceVersion, Span, TokenOrigin}, pdf_device::{Affine, PdfGraphics}, provenance::PaintSource, render::{DisplayItem, DisplayList, DisplayUnits}, }; use sha2::{Digest, Sha256}; mod pdf_projection; use pdf_projection::PdfProjection; #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum SourceKind { Input, /// The version describes bytes actually consumed, possibly a file prefix. ReadStream, Generated, } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct SourceRecord { pub id: usize, pub name: String, pub version: SourceVersion, pub kind: SourceKind, pub generated: Option, } #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum MapUnits { TeX, PostScript, } #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Bounds { pub x: i64, pub y: i64, pub width: i64, pub height: i64, } impl Bounds { fn transformed(self, transform: Affine) -> Result { if transform == Affine::IDENTITY { return Ok(self); } let x = self.x as f64; let y = self.y as f64; let right = x + self.width as f64; let bottom = y + self.height as f64; let corners = [(x, y), (right, y), (x, bottom), (right, bottom)].map(|(x, y)| transform.point(x, y)); let lower = |i| { corners .iter() .map(|p| p[i]) .fold(f64::INFINITY, f64::min) .floor() }; let upper = |i| { corners .iter() .map(|p| p[i]) .fold(f64::NEG_INFINITY, f64::max) .ceil() }; let [x, y, right, bottom] = [lower(0), lower(1), upper(0), upper(1)]; let extent = [x, y, right - x, bottom - y]; let limit = i64::MAX as f64; if corners.iter().flatten().any(|v| !v.is_finite()) || extent.iter().any(|&v| v < -limit || v >= limit) { return Err("PDF graphics transform exceeds source map dimensions".into()); } Ok(Self { x: x as i64, y: y as i64, width: (right - x) as i64, height: (bottom - y) as i64, }) } } impl Bounds { fn clipped_by(self, width: i64, height: i64) -> Option { let x = self.x.max(0); let y = self.y.max(0); let right = self.x.saturating_add(self.width).min(width); let bottom = self.y.saturating_add(self.height).min(height); (right >= x && bottom >= y && width > 0 && height > 0).then_some(Self { x, y, width: right.saturating_sub(x), height: bottom.saturating_sub(y), }) } pub fn contains(self, x: i64, y: i64) -> bool { let right = i128::from(self.x) + i128::from(self.width); let bottom = i128::from(self.y) + i128::from(self.height); let (x, y) = (i128::from(x), i128::from(y)); x >= right.min(self.x.into()) && x <= right.max(self.x.into()) && y >= bottom.min(self.y.into()) && y <= bottom.max(self.y.into()) } } #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum PaintKind { Glyph { font: u32, slot: u8, #[serde(default, skip_serializing_if = "crate::native_font::unexpanded")] expansion: i32, }, OpenTypeGlyph { font: u32, glyph: u16 }, Rule, PdfImage { page: usize }, } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct MappedPaint { pub item_index: usize, pub kind: PaintKind, /// Original page coordinates, after placement and before magnification. pub bounds: Bounds, pub source: PaintSource, } #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum UnmappedReason { MissingProvenance, UnsupportedPrimitive, ClippedByPage, } #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct UnmappedPaint { pub item_index: usize, pub reason: UnmappedReason, } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct PageMap { pub page_index: usize, pub width: i64, pub height: i64, pub magnification: i32, pub units: MapUnits, pub entries: Vec, pub unmapped: Vec, } impl PageMap { /// Convert a logical map rectangle to physical PDF/preview big points. pub fn bounds_bp(&self, bounds: Bounds) -> [f64; 4] { let units = match self.units { MapUnits::TeX => DisplayUnits::TeX, MapUnits::PostScript => DisplayUnits::PostScript, }; [bounds.x, bounds.y, bounds.width, bounds.height] .map(|n| units.bp(n) * f64::from(self.magnification) / 1000.0) } /// Logical page coordinates; later paint is returned first for overlaps. pub fn hit_test(&self, x: i64, y: i64) -> impl Iterator { self.entries .iter() .rev() .filter(move |entry| entry.bounds.contains(x, y)) } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Projection { Definition, Invocation, } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct SourceMap { pub revision: u64, pub sources: Vec, pub pages: Vec, } fn overlap(a: Span, b: Span) -> bool { a.source == b.source && match (a.start == a.end, b.start == b.end) { (true, true) => a.start == b.start, (true, false) => b.start <= a.start && a.start < b.end, (false, true) => a.start <= b.start && b.start < a.end, (false, false) => a.start < b.end && b.start < a.end, } } impl SourceMap { /// Coverage of these pages only, not completeness of engine support. pub fn is_complete(&self) -> bool { self.pages.iter().all(|p| p.unmapped.is_empty()) } /// Source IDs must come from this map's revision; callers can compare the /// source record's version before reusing an editor selection. pub fn for_span( &self, span: Span, projection: Projection, ) -> impl Iterator { self.pages.iter().flat_map(move |page| { page.entries .iter() .filter(move |entry| { entry.source.tokens.iter().any(|token| { overlap( span, match projection { Projection::Definition => token.span, Projection::Invocation => token.invocation.unwrap_or(token.span), }, ) }) }) .map(move |entry| (page.page_index, entry)) }) } pub fn from_revision( revision: &RevisionExecution, pages: &[DisplayList], ) -> Result { Self::from_revision_checked(revision, pages, true) } pub(crate) fn from_revision_checked( revision: &RevisionExecution, pages: &[DisplayList], verify_source_hashes: bool, ) -> Result { let execution = &revision.execution; if revision.source_versions.len() != execution.sources.len() { return Err("source map version table does not match execution".into()); } let sources: Vec<_> = execution .sources .iter() .zip(&revision.source_versions) .enumerate() .map(|(id, (file, version))| { if version.bytes != file.data.len() as u64 || (verify_source_hashes && version.sha256 != format!("{:x}", Sha256::digest(&file.data))) { return Err(format!("source map version mismatch for source {id}")); } let generated = execution.generated_inputs.get(&id).cloned(); let kind = if generated.is_some() { SourceKind::Generated } else if execution.stream_sources.contains(&id) { SourceKind::ReadStream } else { SourceKind::Input }; Ok(SourceRecord { id, name: file.name.clone(), version: version.clone(), kind, generated, }) }) .collect::>()?; if execution .stream_sources .iter() .chain(execution.generated_inputs.keys()) .any(|id| *id >= sources.len()) { return Err("source map input provenance references an absent source".into()); } let validate_span = |span: Span| -> Result<(), String> { let record = sources .get(span.source) .ok_or_else(|| format!("source map references absent source {}", span.source))?; if span.start > span.end || span.end as u64 > record.version.bytes { return Err(format!( "source map span outside source {}: {}..{}", span.source, span.start, span.end )); } Ok(()) }; let validate_token = |token: &TokenOrigin| -> Result<(), String> { validate_span(token.span)?; if let Some(invocation) = token.invocation { validate_span(invocation)?; } Ok(()) }; for record in &sources { if let Some(generated) = &record.generated { validate_span(generated.origin)?; if generated.origin.source >= record.id { return Err("generated input must refer to an earlier source".into()); } } } let mut mapped_pages = Vec::with_capacity(pages.len()); 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()); } let mut map = PageMap { page_index, width: page.width, height: page.height, magnification: page.magnification, units: match page.units { DisplayUnits::TeX => MapUnits::TeX, DisplayUnits::PostScript => MapUnits::PostScript, }, entries: Vec::new(), unmapped: Vec::new(), }; let viewport = page.pdf_resources.viewport.as_ref().map(|viewport| { let unit = page.units.bp(1) * f64::from(page.magnification) / 1000.0; let dimensions = viewport.dimensions().map(|value| (value / unit).ceil()); if dimensions.iter().any(|value| !value.is_finite() || *value >= i64::MAX as f64) { return Err("native PDF viewport exceeds source map dimensions"); } [map.width, map.height] = dimensions.map(|value| value as i64); let mut transform = viewport.transform(page.height as f64 * unit); for distance in &mut transform.0[4..] { *distance /= unit; } Ok(transform) }).transpose()?; let mut transform = Affine::IDENTITY; let mut graphics_stack = Vec::new(); let mut pdf_projection = PdfProjection::for_page(page); for (item_index, item) in page.items.iter().enumerate() { let placement = pdf_projection .as_mut() .map_or(Some(transform), |projection| projection.observe(item)); let placement = if page.pdf_resources.overrides_paint { None } else { placement.map(|graphics| viewport.map_or(graphics, |frame| frame.concatenate(graphics))) }; if let DisplayItem::PdfGraphics { x, y, operation } = item { if pdf_projection.is_some() { continue; } match operation { PdfGraphics::Literal { .. } => {} PdfGraphics::Save => graphics_stack.push(transform), PdfGraphics::Matrix(matrix) | PdfGraphics::SaveMatrix(matrix) => { if matches!(operation, PdfGraphics::SaveMatrix(_)) { graphics_stack.push(transform); } transform = transform.concatenate(matrix.about(*x as f64, *y as f64, true)); } PdfGraphics::Restore { shift: [dx, dy] } => { if let Some(previous) = graphics_stack.pop() { transform = previous .concatenate(Affine::translation(*dx as f64, *dy as f64)); } } } continue; } // Color controls change graphics state and occupy no geometry. if matches!( item, DisplayItem::PdfColor(_) | DisplayItem::PdfImageObject(_) | DisplayItem::PdfTextSpace { .. } ) { continue; } let geometry = match item { DisplayItem::NativeGlyph { x, y, size, slot, font, .. } => { let metrics = font.layout_metrics(); let scale = |n: i64| -> Result { if metrics.size_sp() == 0 { return Err("source map glyph has zero design size".into()); } i64::try_from( i128::from(n) * i128::from(*size) / i128::from(metrics.size_sp()), ) .map_err(|_| "source map glyph dimension overflow".into()) }; let c = char::from(*slot); let h = scale(metrics.height(c))?; let d = scale(metrics.depth(c))?; Some(( PaintKind::Glyph { font: font.id.index(), slot: *slot, expansion: font.expansion, }, Bounds { x: *x, y: y.checked_sub(h) .ok_or("source map glyph position overflow")?, width: scale(font.advance(*slot))?, height: h .checked_add(d) .ok_or("source map glyph height overflow")?, }, )) } DisplayItem::OpenTypeGlyph { x, y, size, advance, font, glyph, .. } => { let scale = |value: i64| value * size / font.size; let ascent = scale(font.ascent); let descent = scale(font.descent); let [_, slant] = font.paint_transform(); let top_offset = slant * ascent as f64; let bottom_offset = -slant * descent as f64; let left = top_offset.min(bottom_offset).floor() as i64; let right = top_offset.max(bottom_offset).ceil() as i64; Some((PaintKind::OpenTypeGlyph { font: font.id.index(), glyph: *glyph }, Bounds { x: x + advance.min(&0) + left, y: y - ascent, width: advance.abs() + right - left, height: ascent + descent, })) } DisplayItem::Rule { x, y, width, height, } => Some(( PaintKind::Rule, Bounds { x: *x, y: *y, width: *width, height: *height, }, )), DisplayItem::PdfImage { x, y, width, height, image, } => Some(( PaintKind::PdfImage { page: image.image.page, }, Bounds { x: *x, y: *y, width: *width, height: *height, }, )), _ => None, }; if let Some(source) = page.sources.get(&item_index) { for token in &source.tokens { validate_token(token)?; } } match ( geometry, page.sources .get(&item_index) .filter(|s| !s.tokens.is_empty()), placement, ) { (Some((kind, bounds)), Some(source), Some(transform)) => { let bounds = bounds.transformed(transform)?; let visible = if viewport.is_some() { bounds.clipped_by(map.width, map.height) } else { Some(bounds) }; if let Some(bounds) = visible { map.entries.push(MappedPaint { item_index, kind, bounds, source: source.clone(), }); } else { map.unmapped.push(UnmappedPaint { item_index, reason: UnmappedReason::ClippedByPage, }); } } (geometry, _, placement) => map.unmapped.push(UnmappedPaint { item_index, reason: if geometry.is_some() && placement.is_some() { UnmappedReason::MissingProvenance } else { UnmappedReason::UnsupportedPrimitive }, }), } } mapped_pages.push(map); } Ok(Self { revision: revision.revision, sources, pages: mapped_pages, }) } }