259 lines
9.9 KiB
Rust
259 lines
9.9 KiB
Rust
//! DVI serialization of the same packed lists used by native previews.
|
|
use super::{Cancellation, Event, Execution, NativeShipout, State, boxes::GeometryItem};
|
|
use crate::{math_engine_tex::MathItem, native_font::NativeFont};
|
|
use std::collections::BTreeMap;
|
|
|
|
const ID: u8 = 2;
|
|
const NUMERATOR: i32 = 25_400_000;
|
|
const DENOMINATOR: i32 = 473_628_672;
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
|
pub(super) struct DviPage {
|
|
pub offset: [i64; 2],
|
|
pub counts: [i32; 10],
|
|
/// TeX constructs the preamble comment from the live date at first shipout.
|
|
pub clock: Option<[i32; 4]>,
|
|
}
|
|
|
|
impl Execution {
|
|
/// Serialize raw DVI shipouts without resolving PDF device fonts or
|
|
/// running a DVI driver. An empty job has no output file.
|
|
pub fn dvi_output(&self, cancellation: &Cancellation) -> Result<Option<Vec<u8>>, String> {
|
|
let mut ships = self.events.iter().filter_map(|event| match event {
|
|
Event::Shipout(ship) => Some(ship.as_ref()),
|
|
_ => None,
|
|
});
|
|
let Some(first) = ships.next() else {
|
|
return Ok(None);
|
|
};
|
|
let [year, month, day, time] = first
|
|
.dvi
|
|
.as_ref()
|
|
.and_then(|page| page.clock)
|
|
.ok_or("DVI output requires a captured DVI preamble")?;
|
|
let two_digits = |value: i32| value.unsigned_abs() % 100;
|
|
let (month, day) = (two_digits(month), two_digits(day));
|
|
let (hour, minute) = (two_digits(time / 60), two_digits(time % 60));
|
|
let comment = format!(" TeX output {year}.{month:02}.{day:02}:{hour:02}{minute:02}");
|
|
let mag = first.device.magnification;
|
|
let mut dvi = Writer {
|
|
bytes: vec![247, ID],
|
|
fonts: BTreeMap::new(),
|
|
page_count: 0,
|
|
last_page: -1,
|
|
max_width: 0,
|
|
max_height: 0,
|
|
};
|
|
dvi.scale(mag);
|
|
dvi.bytes.push(comment.len() as u8);
|
|
dvi.bytes.extend_from_slice(comment.as_bytes());
|
|
for ship in std::iter::once(first).chain(ships) {
|
|
if cancellation.is_cancelled() {
|
|
return Err("native compilation cancelled".into());
|
|
}
|
|
if ship.device.magnification != mag {
|
|
return Err("DVI magnification changed during output".into());
|
|
}
|
|
dvi.page(ship, &self.state, cancellation)?;
|
|
}
|
|
dvi.finish(mag).map(Some)
|
|
}
|
|
}
|
|
|
|
struct Writer {
|
|
bytes: Vec<u8>,
|
|
fonts: BTreeMap<u32, Vec<u8>>,
|
|
page_count: u16,
|
|
last_page: i32,
|
|
max_width: i32,
|
|
max_height: i32,
|
|
}
|
|
|
|
impl Writer {
|
|
fn four(&mut self, n: i32) {
|
|
self.bytes.extend_from_slice(&n.to_be_bytes());
|
|
}
|
|
|
|
fn scale(&mut self, magnification: i32) {
|
|
self.four(NUMERATOR);
|
|
self.four(DENOMINATOR);
|
|
self.four(magnification);
|
|
}
|
|
|
|
fn file_offset(&self) -> Result<i32, String> {
|
|
i32::try_from(self.bytes.len()).map_err(|_| "DVI file offset overflow".into())
|
|
}
|
|
|
|
fn page(
|
|
&mut self,
|
|
ship: &NativeShipout,
|
|
state: &State,
|
|
cancellation: &Cancellation,
|
|
) -> Result<(), String> {
|
|
let page = ship
|
|
.dvi
|
|
.as_ref()
|
|
.ok_or("DVI and PDF shipouts cannot share a file")?;
|
|
self.page_count = self
|
|
.page_count
|
|
.checked_add(1)
|
|
.ok_or("DVI page count overflow")?;
|
|
let page_at = self.file_offset()?;
|
|
self.bytes.push(139); // bop
|
|
for count in page.counts {
|
|
self.four(count);
|
|
}
|
|
self.four(self.last_page);
|
|
self.last_page = page_at;
|
|
let b = &ship.box_node;
|
|
let [left, top] = page.offset;
|
|
let baseline = top + b.height;
|
|
self.max_width = self.max_width.max(dimension(left + b.width)?);
|
|
self.max_height = self.max_height.max(dimension(baseline + b.depth)?);
|
|
let mut cursor = [0, 0];
|
|
let mut current_font = None;
|
|
let mut specials = ship.specials.iter();
|
|
let mut result: Result<(), String> = Ok(());
|
|
b.visit_geometry_cancellable(Some(cancellation), |item| {
|
|
if result.is_err() {
|
|
return;
|
|
}
|
|
result = match item {
|
|
GeometryItem::Paint(p) => {
|
|
let position = [left + p.x, baseline + p.y];
|
|
match p.item {
|
|
MathItem::NativeGlyph { font, slot, .. } => (|| {
|
|
let number = self.font(&font, state)?;
|
|
if Some(number) != current_font {
|
|
self.select_font(number);
|
|
current_font = Some(number);
|
|
}
|
|
self.move_to(&mut cursor, position)?;
|
|
// PUT does not consume a TFM advance. The packed
|
|
// list supplies the actual position of every item.
|
|
self.bytes.extend_from_slice(&[133, slot]);
|
|
Ok(())
|
|
})(),
|
|
MathItem::Rule { width, height } => (|| {
|
|
self.move_to(&mut cursor, [position[0], position[1] + height])?;
|
|
self.bytes.push(137); // put_rule
|
|
self.four(dimension(height)?);
|
|
self.four(dimension(width)?);
|
|
Ok(())
|
|
})(),
|
|
_ => Err("DVI requires actual TFM glyphs and rules".into()),
|
|
}
|
|
}
|
|
GeometryItem::Output { special: true } => (|| {
|
|
let special = specials.next().ok_or("missing resolved DVI special")?;
|
|
let [x, y] = special.position;
|
|
self.move_to(&mut cursor, [left + x, baseline + y])?;
|
|
let len = i32::try_from(special.bytes.len())
|
|
.map_err(|_| "DVI special length overflow")?;
|
|
if let Ok(len) = u8::try_from(len) {
|
|
self.bytes.extend_from_slice(&[239, len]);
|
|
} else {
|
|
self.bytes.push(242);
|
|
self.four(len);
|
|
}
|
|
self.bytes.extend_from_slice(&special.bytes);
|
|
Ok(())
|
|
})(),
|
|
_ => Ok(()),
|
|
};
|
|
})?;
|
|
result?;
|
|
if specials.next().is_some() {
|
|
return Err("unmatched resolved DVI specials".into());
|
|
}
|
|
self.bytes.push(140); // eop
|
|
Ok(())
|
|
}
|
|
|
|
fn move_to(&mut self, cursor: &mut [i64; 2], position: [i64; 2]) -> Result<(), String> {
|
|
for (index, opcode) in [143, 157].into_iter().enumerate() {
|
|
let delta = dimension(position[index] - cursor[index])?;
|
|
if delta != 0 {
|
|
let size = match delta {
|
|
-128..=127 => 1,
|
|
-32768..=32767 => 2,
|
|
-8388608..=8388607 => 3,
|
|
_ => 4,
|
|
};
|
|
self.bytes.push(opcode + size as u8 - 1);
|
|
self.bytes
|
|
.extend_from_slice(&delta.to_be_bytes()[4 - size..]);
|
|
}
|
|
}
|
|
*cursor = position;
|
|
Ok(())
|
|
}
|
|
|
|
fn font(&mut self, glyph_font: &NativeFont, state: &State) -> Result<u32, String> {
|
|
use std::collections::btree_map::Entry;
|
|
let number = glyph_font
|
|
.id
|
|
.index()
|
|
.checked_sub(1)
|
|
.ok_or("null DVI glyph font")?;
|
|
if let Entry::Vacant(entry) = self.fonts.entry(number) {
|
|
let instance = state.fonts.font(glyph_font.id)?;
|
|
let area = instance.area().as_bytes();
|
|
let name = instance.name().as_bytes();
|
|
let area_len = u8::try_from(area.len()).map_err(|_| "DVI font area is too long")?;
|
|
let name_len = u8::try_from(name.len()).map_err(|_| "DVI font name is too long")?;
|
|
let metrics = instance.metrics().ok_or("DVI font has no TFM metrics")?;
|
|
let mut definition = Vec::new();
|
|
font_number(&mut definition, 243, number);
|
|
definition.extend_from_slice(&metrics.checksum().to_be_bytes());
|
|
definition.extend_from_slice(&dimension(instance.size_sp())?.to_be_bytes());
|
|
definition.extend_from_slice(&dimension(metrics.design_size_sp())?.to_be_bytes());
|
|
definition.extend_from_slice(&[area_len, name_len]);
|
|
definition.extend_from_slice(area);
|
|
definition.extend_from_slice(name);
|
|
self.bytes.extend_from_slice(&definition);
|
|
entry.insert(definition);
|
|
}
|
|
Ok(number)
|
|
}
|
|
|
|
fn select_font(&mut self, number: u32) {
|
|
if number < 64 {
|
|
self.bytes.push(171 + number as u8);
|
|
} else {
|
|
font_number(&mut self.bytes, 235, number);
|
|
}
|
|
}
|
|
|
|
fn finish(mut self, mag: i32) -> Result<Vec<u8>, String> {
|
|
let post = self.file_offset()?;
|
|
self.bytes.push(248);
|
|
self.four(self.last_page);
|
|
self.scale(mag);
|
|
self.four(self.max_height);
|
|
self.four(self.max_width);
|
|
self.bytes.extend_from_slice(&0u16.to_be_bytes()); // no PUSH instructions
|
|
self.bytes.extend_from_slice(&self.page_count.to_be_bytes());
|
|
for definition in self.fonts.values().rev() {
|
|
self.bytes.extend_from_slice(definition);
|
|
}
|
|
self.bytes.push(249);
|
|
self.four(post);
|
|
self.bytes.push(ID);
|
|
let padding = 4 + (4 - self.bytes.len() % 4) % 4;
|
|
self.bytes.resize(self.bytes.len() + padding, 223);
|
|
self.file_offset()?;
|
|
Ok(self.bytes)
|
|
}
|
|
}
|
|
|
|
fn font_number(output: &mut Vec<u8>, opcode: u8, number: u32) {
|
|
let len = (32 - number.leading_zeros()).max(1).div_ceil(8) as usize;
|
|
output.push(opcode + len as u8 - 1);
|
|
output.extend_from_slice(&number.to_be_bytes()[4 - len..]);
|
|
}
|
|
|
|
fn dimension(value: i64) -> Result<i32, String> {
|
|
i32::try_from(value).map_err(|_| "DVI dimension overflow".into())
|
|
}
|