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

181 lines
5.5 KiB
Rust

//! Graphics state produced by PDF extension whatsits and device specials.
use super::PdfDriver;
use crate::render::DisplayUnits;
use std::sync::Arc;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum PdfLiteralMode {
Origin,
Page,
Direct,
XdvOrigin,
XdvDirect,
/// XDV page content relative to the special, inside a local graphics state.
XdvContent,
XdvBeginContent,
XdvEndContent,
XdvCode,
}
impl PdfLiteralMode {
pub(crate) fn xdv_origin(
self,
point: [i64; 2],
page_origin: [i64; 2],
) -> Option<[i64; 2]> {
match self {
Self::XdvOrigin | Self::XdvContent => Some(point),
Self::XdvDirect => Some(page_origin),
_ => None,
}
}
}
/// The XDV device writes content relative to the one-inch page origin.
pub(crate) fn xdv_page_origin(units: DisplayUnits, height: i64, magnification: i32) -> [i64; 2] {
let inch = (72_000. / (units.bp(1) * f64::from(magnification))).round() as i64;
[inch, height - inch]
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum PdfGraphics {
Save,
Matrix(PdfMatrix),
Restore { shift: [i64; 2] },
Literal { mode: PdfLiteralMode, bytes: Arc<[u8]> },
SaveMatrix(PdfMatrix),
/// An XDV special switched the device from text to graphics mode.
TextBoundary,
XdvFormBegin(u32),
XdvFormEnd(u32),
XdvFormUse {
number: u32,
options: super::xdv_navigation::FormOptions,
source: crate::execution::TokenOrigin,
#[serde(default, alias = "imported_available")]
available: bool,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct PdfMatrix([u64; 4]);
impl PdfMatrix {
pub(crate) fn scale(x: f64, y: f64) -> Self {
Self([x, 0.0, 0.0, y].map(f64::to_bits))
}
pub(crate) fn rotation(angle: f64) -> Self {
let (s, c) = angle.to_radians().sin_cos();
Self([c, s, -s, c].map(f64::to_bits))
}
pub(crate) fn parse(text: &str) -> Result<Self, &'static str> {
let mut words = text.split_ascii_whitespace();
let mut coefficients = [0; 4];
for coefficient in &mut coefficients {
*coefficient = words
.next()
.and_then(|word| word.parse::<f64>().ok())
.filter(|value| value.is_finite())
.ok_or("Unrecognized format")?
.to_bits();
}
if words.next().is_some() {
return Err("Unrecognized format");
}
Ok(Self(coefficients))
}
pub(crate) fn about(self, x: f64, y: f64, y_down: bool) -> Affine {
let [a, mut b, mut c, d] = self.0.map(f64::from_bits);
if y_down {
b = -b;
c = -c;
}
Affine([a, b, c, d, (1.0 - a) * x - c * y, (1.0 - d) * y - b * x])
}
}
/// Tracks the logical position represented by the PDF device's translations.
#[derive(Clone, Copy)]
pub(crate) struct DeviceOrigin {
position: [i64; 2],
scale: i64,
precision: u8,
minimum_move: i64,
}
impl DeviceOrigin {
pub(crate) fn new(units: DisplayUnits, digits: u8, driver: PdfDriver) -> Self {
let (scale, precision) = match units {
DisplayUnits::TeX => (6_578_176, digits + 2),
DisplayUnits::PostScript => (65_536, digits),
};
// pdfTeX decides whether to move before rounding either operand.
// If one axis qualifies, the device rounds and emits both axes.
let minimum_move = if units == DisplayUnits::TeX && driver == PdfDriver::PdfTeX {
super::divide_scaled(scale, 10i64.pow(u32::from(precision)), 0).0
} else {
0
};
Self { position: [0, 0], scale, precision, minimum_move }
}
pub(crate) fn position(&self) -> [i64; 2] {
self.position
}
pub(crate) fn move_to(&mut self, point: [i64; 2]) -> Option<[i64; 2]> {
let (operands, advance) = self.translation(point)?;
self.position[0] += advance[0];
self.position[1] += advance[1];
Some(operands)
}
pub(crate) fn temporary_translation(&self, point: [i64; 2]) -> Option<[i64; 2]> {
self.translation(point).map(|(operands, _)| operands)
}
fn translation(&self, point: [i64; 2]) -> Option<([i64; 2], [i64; 2])> {
let delta = [point[0] - self.position[0], point[1] - self.position[1]];
if delta == [0, 0] || delta.iter().all(|d| d.abs() < self.minimum_move) {
return None;
}
let [(h, h_sp), (v, v_sp)] =
delta.map(|value| super::divide_scaled(value, self.scale, self.precision));
(h != 0 || v != 0).then_some(([h, v], [h_sp, v_sp]))
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Affine(pub [f64; 6]);
impl Affine {
pub const IDENTITY: Self = Self([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
pub fn translation(x: f64, y: f64) -> Self {
Self([1.0, 0.0, 0.0, 1.0, x, y])
}
pub fn concatenate(self, incoming: Self) -> Self {
let [a, b, c, d, ..] = self.0;
let [p, q, r, s, t, u] = incoming.0;
let [tx, ty] = self.point(t, u);
Self([
a * p + c * q,
b * p + d * q,
a * r + c * s,
b * r + d * s,
tx,
ty,
])
}
pub fn point(self, x: f64, y: f64) -> [f64; 2] {
let [a, b, c, d, e, f] = self.0;
[a * x + c * y + e, b * x + d * y + f]
}
}