Advance native LaTeX execution and preview
This commit is contained in:
1 parent
91f9d76b16
commit
2741546ca8
414 files changed
+99872
-933
No files matched your search
@@ -0,0 +1,326 @@
|
||||
use super::{NativeFont, actual_resource, verify_resource};
|
||||
use crate::{
|
||||
execution::{FontId, FontResource, SourceProvider},
|
||||
provenance::Derivation,
|
||||
render::{DisplayItem, DisplayList},
|
||||
resources::ResourceKind,
|
||||
tfm::{FontSize, TfmMetrics},
|
||||
virtual_font::{Axis, Command, LocalFont, VirtualFont},
|
||||
};
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
|
||||
struct LoadedVirtual {
|
||||
from: String,
|
||||
program: VirtualFont,
|
||||
}
|
||||
|
||||
struct Expansion<'a, F> {
|
||||
files: &'a mut F,
|
||||
virtuals: BTreeMap<FontId, (Arc<NativeFont>, Option<Arc<LoadedVirtual>>)>,
|
||||
local_fonts: BTreeMap<(String, String, i64), Arc<NativeFont>>,
|
||||
last_id: u32,
|
||||
commands: usize,
|
||||
}
|
||||
|
||||
struct Glyph {
|
||||
x: i64,
|
||||
y: i64,
|
||||
size: i64,
|
||||
font: Arc<NativeFont>,
|
||||
slot: u8,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Position {
|
||||
x: i64,
|
||||
y: i64,
|
||||
registers: [i64; 4],
|
||||
}
|
||||
|
||||
fn offset(point: i64, delta: i64) -> Result<i64, String> {
|
||||
point
|
||||
.checked_add(delta)
|
||||
.ok_or_else(|| "VF position overflow".into())
|
||||
}
|
||||
|
||||
impl<'a, F: SourceProvider> Expansion<'a, F> {
|
||||
fn lookup(&mut self, font: &Arc<NativeFont>) -> Result<Option<Arc<LoadedVirtual>>, String> {
|
||||
if let Some((old, vf)) = self.virtuals.get(&font.id) {
|
||||
if !Arc::ptr_eq(old, font) && old != font {
|
||||
return Err("native font ids from different jobs cannot share output".into());
|
||||
}
|
||||
return Ok(vf.clone());
|
||||
}
|
||||
let name = format!("{}.vf", font.name);
|
||||
let from = font.resource.version.path.to_string_lossy();
|
||||
let vf = self.files.virtual_font(&name, &from)?;
|
||||
let vf = if let Some(loaded) = vf {
|
||||
let loaded = verify_resource(loaded, ResourceKind::Vf, &name)?;
|
||||
let from = loaded.version.path.to_string_lossy().into_owned();
|
||||
let program =
|
||||
VirtualFont::parse(&loaded.data).map_err(|error| format!("{from}: {error}"))?;
|
||||
check_metrics(&font.metrics, program.checksum, program.design_size, &name)?;
|
||||
for (&slot, packet) in &program.packets {
|
||||
if font.has_slot(slot)
|
||||
&& TfmMetrics::scale_fix_word(packet.width, font.size_sp())?
|
||||
!= font.metrics.width(char::from(slot))
|
||||
{
|
||||
return Err(format!("{name} width differs from TFM at slot {slot}"));
|
||||
}
|
||||
}
|
||||
Some(Arc::new(LoadedVirtual { from, program }))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
self.virtuals.insert(font.id, (font.clone(), vf.clone()));
|
||||
Ok(vf)
|
||||
}
|
||||
|
||||
fn local_font(
|
||||
&mut self,
|
||||
from: &str,
|
||||
local: &LocalFont,
|
||||
size: i64,
|
||||
) -> Result<Arc<NativeFont>, String> {
|
||||
let size = TfmMetrics::scale_fix_word(local.scale, size)?;
|
||||
let key = (from.to_owned(), local.name.clone(), size);
|
||||
if let Some(font) = self.local_fonts.get(&key) {
|
||||
check_metrics(
|
||||
&font.metrics,
|
||||
local.checksum,
|
||||
local.design_size,
|
||||
&local.name,
|
||||
)?;
|
||||
return Ok(font.clone());
|
||||
}
|
||||
let name = format!("{}.tfm", local.name);
|
||||
let file = actual_resource(self.files, ResourceKind::Tfm, &name, from)?;
|
||||
let metrics = TfmMetrics::parse_at(&file.data, FontSize::At(size))?;
|
||||
check_metrics(&metrics, local.checksum, local.design_size, &name)?;
|
||||
self.last_id = self
|
||||
.last_id
|
||||
.checked_add(1)
|
||||
.ok_or("native device font capacity exceeded")?;
|
||||
let font = Arc::new(NativeFont {
|
||||
id: FontId::for_device(self.last_id),
|
||||
name: local.name.clone(),
|
||||
metrics,
|
||||
resource: FontResource {
|
||||
version: file.version,
|
||||
data: Arc::new(file.data),
|
||||
},
|
||||
});
|
||||
self.local_fonts.insert(key, font.clone());
|
||||
Ok(font)
|
||||
}
|
||||
|
||||
fn expand(
|
||||
&mut self,
|
||||
glyph: Glyph,
|
||||
output: &mut Vec<DisplayItem>,
|
||||
depth: usize,
|
||||
) -> Result<(), String> {
|
||||
let Some(vf) = self.lookup(&glyph.font)? else {
|
||||
output.push(DisplayItem::NativeGlyph {
|
||||
x: glyph.x,
|
||||
y: glyph.y,
|
||||
size: glyph.size,
|
||||
character: '\u{fffd}',
|
||||
font: glyph.font,
|
||||
slot: glyph.slot,
|
||||
paint: None,
|
||||
});
|
||||
return Ok(());
|
||||
};
|
||||
if depth >= 16 {
|
||||
return Err("VF recursion limit exceeded".into());
|
||||
}
|
||||
FontSize::At(glyph.size).validate()?;
|
||||
let packet =
|
||||
vf.program.packets.get(&glyph.slot).ok_or_else(|| {
|
||||
format!("{} has no VF packet for TFM slot {}", vf.from, glyph.slot)
|
||||
})?;
|
||||
let dimension = |raw| TfmMetrics::scale_fix_word(raw, glyph.size);
|
||||
let mut point = Position {
|
||||
x: glyph.x,
|
||||
y: glyph.y,
|
||||
registers: [0; 4],
|
||||
};
|
||||
let mut stack = Vec::new();
|
||||
let mut local = vf.program.default_font;
|
||||
for command in &packet.commands {
|
||||
self.commands += 1;
|
||||
if self.commands > 5_000_000 {
|
||||
return Err("VF expansion command limit exceeded".into());
|
||||
}
|
||||
match *command {
|
||||
Command::Character { slot, advance } => {
|
||||
let id = local.ok_or("VF character has no selected local font")?;
|
||||
let font =
|
||||
self.local_font(&vf.from, &vf.program.local_fonts[&id], glyph.size)?;
|
||||
if !font.has_slot(slot) {
|
||||
return Err(format!(
|
||||
"VF local font {} has no TFM slot {slot}",
|
||||
font.name
|
||||
));
|
||||
}
|
||||
let width = font.metrics.width(char::from(slot));
|
||||
let size = font.size_sp();
|
||||
self.expand(
|
||||
Glyph {
|
||||
x: point.x,
|
||||
y: point.y,
|
||||
font,
|
||||
size,
|
||||
slot,
|
||||
},
|
||||
output,
|
||||
depth + 1,
|
||||
)?;
|
||||
if advance {
|
||||
point.x = offset(point.x, width)?;
|
||||
}
|
||||
}
|
||||
Command::Rule {
|
||||
height,
|
||||
width,
|
||||
advance,
|
||||
} => {
|
||||
let height = dimension(height)?;
|
||||
let width = dimension(width)?;
|
||||
if height > 0 && width > 0 {
|
||||
output.push(DisplayItem::Rule {
|
||||
x: point.x,
|
||||
y: offset(point.y, -height)?,
|
||||
width,
|
||||
height,
|
||||
});
|
||||
}
|
||||
if advance {
|
||||
point.x = offset(point.x, width)?;
|
||||
}
|
||||
}
|
||||
Command::Right(raw) => point.x = offset(point.x, dimension(raw)?)?,
|
||||
Command::Down(raw) => point.y = offset(point.y, dimension(raw)?)?,
|
||||
Command::Repeat {
|
||||
register,
|
||||
new,
|
||||
axis,
|
||||
} => {
|
||||
if let Some(raw) = new {
|
||||
point.registers[register] = dimension(raw)?;
|
||||
}
|
||||
let delta = point.registers[register];
|
||||
match axis {
|
||||
Axis::Horizontal => point.x = offset(point.x, delta)?,
|
||||
Axis::Vertical => point.y = offset(point.y, delta)?,
|
||||
}
|
||||
}
|
||||
Command::Font(id) => local = Some(id),
|
||||
Command::Push => stack.push(point),
|
||||
Command::Pop => point = stack.pop().expect("validated VF packet stack"),
|
||||
Command::Special => {
|
||||
return Err(format!(
|
||||
"VF packet contains an unsupported DVI special: {}",
|
||||
vf.from
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn check_metrics(
|
||||
metrics: &TfmMetrics,
|
||||
checksum: u32,
|
||||
design: i64,
|
||||
name: &str,
|
||||
) -> Result<(), String> {
|
||||
if metrics.design_size_sp() != design
|
||||
|| (checksum != 0 && metrics.checksum() != 0 && checksum != metrics.checksum())
|
||||
{
|
||||
return Err(format!(
|
||||
"VF font definition disagrees with actual TFM: {name}"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn expand_pages(
|
||||
pages: &[DisplayList],
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<Option<Vec<DisplayList>>, String> {
|
||||
let mut expansion = Expansion {
|
||||
files,
|
||||
virtuals: BTreeMap::new(),
|
||||
local_fonts: BTreeMap::new(),
|
||||
last_id: 0x7fff_ffff,
|
||||
commands: 0,
|
||||
};
|
||||
let mut uses_vf = false;
|
||||
for page in pages {
|
||||
for item in &page.items {
|
||||
if let DisplayItem::NativeGlyph { font, .. } = item {
|
||||
expansion.last_id = expansion.last_id.max(font.id.index());
|
||||
uses_vf |= expansion.lookup(font)?.is_some();
|
||||
}
|
||||
}
|
||||
}
|
||||
if !uses_vf {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut result = Vec::with_capacity(pages.len());
|
||||
for page in pages {
|
||||
let mut resolved = DisplayList {
|
||||
width: page.width,
|
||||
height: page.height,
|
||||
magnification: page.magnification,
|
||||
units: page.units,
|
||||
pdf: page.pdf.clone(),
|
||||
images: page.images.clone(),
|
||||
..DisplayList::default()
|
||||
};
|
||||
for (index, item) in page.items.iter().enumerate() {
|
||||
let start = resolved.items.len();
|
||||
let virtual_glyph = if let DisplayItem::NativeGlyph {
|
||||
x,
|
||||
y,
|
||||
size,
|
||||
font,
|
||||
slot,
|
||||
..
|
||||
} = item
|
||||
&& expansion.lookup(font)?.is_some()
|
||||
{
|
||||
expansion.expand(
|
||||
Glyph {
|
||||
x: *x,
|
||||
y: *y,
|
||||
size: *size,
|
||||
font: font.clone(),
|
||||
slot: *slot,
|
||||
},
|
||||
&mut resolved.items,
|
||||
0,
|
||||
)?;
|
||||
true
|
||||
} else {
|
||||
resolved.items.push(item.clone());
|
||||
false
|
||||
};
|
||||
if let Some(source) = page.sources.get(&index) {
|
||||
let source = if virtual_glyph {
|
||||
source.clone().derived(Derivation::FontProgram)
|
||||
} else {
|
||||
source.clone()
|
||||
};
|
||||
for i in start..resolved.items.len() {
|
||||
resolved.sources.insert(i, source.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
result.push(resolved);
|
||||
}
|
||||
Ok(Some(result))
|
||||
}
|
||||
Reference in new issue
Block a user