Preserve pdfTeX text positioning across direct color changes

This commit is contained in:
gloamxun committed 2026-11-26 15:19:17 +08:00
1 parent 0f6aa1f33d
commit f88a16d101
15 files changed
+193 -44

No files matched your search

+43 -4
View File
@@ -1,3 +1,4 @@
use super::PdfLiteralMode;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
@@ -100,19 +101,55 @@ pub enum PdfColorStackAction {
Pop,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub(crate) enum ShippedColor {
WithMode {
program: Arc<PdfColorProgram>,
mode: PdfLiteralMode,
},
Page(Arc<PdfColorProgram>),
}
impl ShippedColor {
pub(crate) fn display_item(&self, x: i64, y: i64) -> crate::render::DisplayItem {
let (program, mode) = match self {
Self::WithMode { program, mode } => (program, *mode),
Self::Page(program) => (program, PdfLiteralMode::Page),
};
crate::render::DisplayItem::PdfColor {
x,
y,
program: program.clone(),
mode,
}
}
}
#[derive(Clone, Debug)]
struct Stack {
mode: PdfLiteralMode,
replay_on_page: bool,
current: Arc<PdfColorProgram>,
saved: Vec<Arc<PdfColorProgram>>,
}
impl Stack {
fn shipped_color(&self) -> ShippedColor {
ShippedColor::WithMode {
program: self.current.clone(),
mode: self.mode,
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct PdfColorStacks(Vec<Stack>);
impl Default for PdfColorStacks {
fn default() -> Self {
Self(vec![Stack {
mode: PdfLiteralMode::Direct,
replay_on_page: true,
current: Arc::new(PdfColorProgram {
literal: "0 g 0 G".into(),
@@ -126,7 +163,7 @@ impl Default for PdfColorStacks {
}
pub(crate) enum ColorResult {
Applied(Option<Arc<PdfColorProgram>>),
Applied(Option<ShippedColor>),
EmptyStack,
UnknownStack,
}
@@ -135,6 +172,7 @@ impl PdfColorStacks {
pub(crate) fn allocate(
&mut self,
initial: PdfColorProgram,
mode: PdfLiteralMode,
replay_on_page: bool,
) -> Result<usize, String> {
let number = self.0.len();
@@ -142,6 +180,7 @@ impl PdfColorStacks {
return Err("too many PDF color stacks".into());
}
self.0.push(Stack {
mode,
replay_on_page,
current: Arc::new(initial),
saved: Vec::new(),
@@ -153,12 +192,12 @@ impl PdfColorStacks {
number < self.0.len()
}
pub(crate) fn start_page(&self) -> Vec<Arc<PdfColorProgram>> {
pub(crate) fn start_page(&self) -> Vec<ShippedColor> {
self.0
.iter()
.filter_map(|stack| {
(stack.replay_on_page && !matches!(stack.current.literal(), "" | "0 g 0 G"))
.then(|| stack.current.clone())
.then(|| stack.shipped_color())
})
.collect()
}
@@ -180,6 +219,6 @@ impl PdfColorStacks {
None => return ColorResult::EmptyStack,
},
}
ColorResult::Applied((!stack.current.literal().is_empty()).then(|| stack.current.clone()))
ColorResult::Applied((!stack.current.literal().is_empty()).then(|| stack.shipped_color()))
}
}