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

431 lines
16 KiB
Rust

//! 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};
#[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<GeneratedInput>,
}
#[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<Self, String> {
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 {
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,
},
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,
}
#[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<MappedPaint>,
pub unmapped: Vec<UnmappedPaint>,
}
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<Item = &MappedPaint> {
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<SourceRecord>,
pub pages: Vec<PageMap>,
}
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<Item = (usize, &MappedPaint)> {
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, String> {
Self::from_revision_checked(revision, pages, true)
}
pub(crate) fn from_revision_checked(
revision: &RevisionExecution,
pages: &[DisplayList],
verify_source_hashes: bool,
) -> Result<Self, String> {
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::<Result<_, String>>()?;
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 mut transform = Affine::IDENTITY;
let mut graphics_stack = Vec::new();
for (item_index, item) in page.items.iter().enumerate() {
if let DisplayItem::PdfGraphics { x, y, operation } = item {
match operation {
PdfGraphics::Save => graphics_stack.push(transform),
PdfGraphics::Matrix(matrix) => {
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(_)
) {
continue;
}
let geometry = match item {
DisplayItem::NativeGlyph {
x,
y,
size,
slot,
font,
..
} => {
let metrics = font.metrics();
let scale = |n: i64| -> Result<i64, String> {
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::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()),
) {
(Some((kind, bounds)), Some(source)) => map.entries.push(MappedPaint {
item_index,
kind,
bounds: bounds.transformed(transform)?,
source: source.clone(),
}),
(geometry, _) => map.unmapped.push(UnmappedPaint {
item_index,
reason: if geometry.is_some() {
UnmappedReason::MissingProvenance
} else {
UnmappedReason::UnsupportedPrimitive
},
}),
}
}
mapped_pages.push(map);
}
Ok(Self {
revision: revision.revision,
sources,
pages: mapped_pages,
})
}
}