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,174 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A device-color program. The PDF receives the original operators and
|
||||
/// component precision. SVG projects the same device colors to screen RGB.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(try_from = "String", into = "String")]
|
||||
pub struct PdfColorProgram {
|
||||
literal: String,
|
||||
pub(crate) fill: Option<[u8; 3]>,
|
||||
pub(crate) stroke: Option<[u8; 3]>,
|
||||
}
|
||||
|
||||
impl PdfColorProgram {
|
||||
pub(crate) fn parse(literal: String) -> Result<Self, String> {
|
||||
let mut fill = None;
|
||||
let mut stroke = None;
|
||||
let mut operands = Vec::with_capacity(4);
|
||||
for token in literal.split_ascii_whitespace() {
|
||||
if matches!(token, "g" | "G" | "rg" | "RG" | "k" | "K") {
|
||||
let rgb = match (token, operands.as_slice()) {
|
||||
("g" | "G", [gray]) => [*gray; 3],
|
||||
("rg" | "RG", [r, g, b]) => [*r, *g, *b],
|
||||
("k" | "K", [c, m, y, k]) => {
|
||||
// The SVG device has no CMYK output profile.
|
||||
[*c, *m, *y].map(|ink| (1.0 - ink) * (1.0 - k))
|
||||
}
|
||||
_ => return Err(format!("invalid operands for PDF device color {token}")),
|
||||
};
|
||||
let target = if token.as_bytes()[0].is_ascii_lowercase() {
|
||||
&mut fill
|
||||
} else {
|
||||
&mut stroke
|
||||
};
|
||||
*target = Some(rgb.map(|v: f64| (v * 255.0).round() as u8));
|
||||
operands.clear();
|
||||
} else {
|
||||
let number = token.strip_prefix(['+', '-']).unwrap_or(token);
|
||||
if operands.len() == 4
|
||||
|| !number
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_digit() || byte == b'.')
|
||||
{
|
||||
return Err(
|
||||
"unsupported PDF color program; expected device-color operators".into(),
|
||||
);
|
||||
}
|
||||
let number = token
|
||||
.parse::<f64>()
|
||||
.ok()
|
||||
.filter(|v| v.is_finite())
|
||||
.ok_or("invalid PDF color component")?;
|
||||
operands.push(number.clamp(0.0, 1.0));
|
||||
}
|
||||
}
|
||||
if !operands.is_empty() {
|
||||
return Err("PDF color program ends with unconsumed operands".into());
|
||||
}
|
||||
Ok(Self {
|
||||
literal,
|
||||
fill,
|
||||
stroke,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn literal(&self) -> &str {
|
||||
&self.literal
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<String> for PdfColorProgram {
|
||||
type Error = String;
|
||||
|
||||
fn try_from(literal: String) -> Result<Self, Self::Error> {
|
||||
Self::parse(literal)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PdfColorProgram> for String {
|
||||
fn from(program: PdfColorProgram) -> Self {
|
||||
program.literal
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum PdfColorStackAction {
|
||||
Set(Arc<PdfColorProgram>),
|
||||
Push(Arc<PdfColorProgram>),
|
||||
Current,
|
||||
Pop,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct Stack {
|
||||
replay_on_page: bool,
|
||||
current: Arc<PdfColorProgram>,
|
||||
saved: Vec<Arc<PdfColorProgram>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct PdfColorStacks(Vec<Stack>);
|
||||
|
||||
impl Default for PdfColorStacks {
|
||||
fn default() -> Self {
|
||||
Self(vec![Stack {
|
||||
replay_on_page: true,
|
||||
current: Arc::new(PdfColorProgram {
|
||||
literal: "0 g 0 G".into(),
|
||||
fill: Some([0; 3]),
|
||||
stroke: Some([0; 3]),
|
||||
}),
|
||||
saved: Vec::new(),
|
||||
}])
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum ColorResult {
|
||||
Applied(Option<Arc<PdfColorProgram>>),
|
||||
EmptyStack,
|
||||
UnknownStack,
|
||||
}
|
||||
|
||||
impl PdfColorStacks {
|
||||
pub(crate) fn allocate(
|
||||
&mut self,
|
||||
initial: PdfColorProgram,
|
||||
replay_on_page: bool,
|
||||
) -> Result<usize, String> {
|
||||
let number = self.0.len();
|
||||
if number >= 32_768 {
|
||||
return Err("too many PDF color stacks".into());
|
||||
}
|
||||
self.0.push(Stack {
|
||||
replay_on_page,
|
||||
current: Arc::new(initial),
|
||||
saved: Vec::new(),
|
||||
});
|
||||
Ok(number)
|
||||
}
|
||||
|
||||
pub(crate) fn contains(&self, number: usize) -> bool {
|
||||
number < self.0.len()
|
||||
}
|
||||
|
||||
pub(crate) fn start_page(&self) -> Vec<Arc<PdfColorProgram>> {
|
||||
self.0
|
||||
.iter()
|
||||
.filter_map(|stack| {
|
||||
(stack.replay_on_page && !matches!(stack.current.literal(), "" | "0 g 0 G"))
|
||||
.then(|| stack.current.clone())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn apply(&mut self, number: usize, action: &PdfColorStackAction) -> ColorResult {
|
||||
let Some(stack) = self.0.get_mut(number) else {
|
||||
return ColorResult::UnknownStack;
|
||||
};
|
||||
match action {
|
||||
PdfColorStackAction::Set(value) => stack.current = value.clone(),
|
||||
PdfColorStackAction::Push(value) => {
|
||||
stack
|
||||
.saved
|
||||
.push(std::mem::replace(&mut stack.current, value.clone()));
|
||||
}
|
||||
PdfColorStackAction::Current => {}
|
||||
PdfColorStackAction::Pop => match stack.saved.pop() {
|
||||
Some(value) => stack.current = value,
|
||||
None => return ColorResult::EmptyStack,
|
||||
},
|
||||
}
|
||||
ColorResult::Applied((!stack.current.literal().is_empty()).then(|| stack.current.clone()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
//! Graphics state produced by the pdfTeX extension whatsits.
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum PdfGraphics {
|
||||
Save,
|
||||
Matrix(PdfMatrix),
|
||||
Restore { shift: [i64; 2] },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PdfMatrix([u64; 4]);
|
||||
|
||||
impl PdfMatrix {
|
||||
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])
|
||||
}
|
||||
}
|
||||
|
||||
#[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]
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user