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

@@ -231,7 +231,7 @@ pub(super) struct BoxLayout {
pub(super) enum GeometryItem {
Output,
Paint(crate::math_engine_tex::PositionedItem),
PdfColor,
PdfColor { x: i64, y: i64 },
PdfGraphics { x: i64, y: i64 },
PdfTextSpace { x: i64, y: i64, operation: crate::pdf_device::text_spaces::SpaceOperation },
}
@@ -846,7 +846,7 @@ impl NativeBox {
let b = match node {
BoxPaint::Box(b) => b,
BoxPaint::PdfColor => {
emit(GeometryItem::PdfColor);
emit(GeometryItem::PdfColor { x, y });
return;
}
BoxPaint::PdfGraphics => {
+15 -9
View File
@@ -1,6 +1,6 @@
//! Per-shipout device state. Original TeX boxes remain unscaled semantic lists.
use super::*;
use crate::pdf_device::{PdfColorProgram, PdfGraphics};
use crate::pdf_device::{PdfColorProgram, PdfGraphics, ShippedColor};
use std::{collections::BTreeMap, sync::Arc};
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -35,9 +35,9 @@ pub struct NativeShipout {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) pdf_font_bindings: Option<Arc<crate::native_font::PdfFontBindings>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(super) pdf_color_start: Vec<Arc<PdfColorProgram>>,
pub(super) pdf_color_start: Vec<ShippedColor>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(super) pdf_color_steps: Vec<Option<Arc<PdfColorProgram>>>,
pub(super) pdf_color_steps: Vec<Option<ShippedColor>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(super) pdf_graphics_steps: Vec<Option<PdfGraphics>>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
@@ -91,11 +91,12 @@ impl NativeShipout {
..Default::default()
};
use crate::{math_engine_tex::MathItem, render::DisplayItem};
let left = self.device.horizontal_origin;
let baseline = self.device.vertical_origin + self.box_node.height;
page.items.extend(
self.pdf_color_start
.iter()
.cloned()
.map(DisplayItem::PdfColor),
.map(|color| color.display_item(left, baseline)),
);
let mut color_steps = self.pdf_color_steps.iter();
let mut graphics_steps = self.pdf_graphics_steps.iter().enumerate();
@@ -115,10 +116,10 @@ impl NativeShipout {
return;
}
boxes::GeometryItem::Paint(p) => p,
boxes::GeometryItem::PdfColor => {
boxes::GeometryItem::PdfColor { x, y } => {
match color_steps.next() {
Some(Some(program)) => {
page.items.push(DisplayItem::PdfColor(program.clone()))
Some(Some(color)) => {
page.items.push(color.display_item(left + x, baseline + y))
}
Some(None) => {}
None => missing_color_step = true,
@@ -144,7 +145,12 @@ impl NativeShipout {
});
}
if let Some(program) = self.xdv_color_steps.get(&step) {
page.items.push(DisplayItem::PdfColor(program.clone()));
page.items.push(DisplayItem::PdfColor {
x: left + x,
y: baseline + y,
program: program.clone(),
mode: crate::pdf_device::PdfLiteralMode::Page,
});
}
if let Some((image, origin)) = self.pdf_special_images.get(&step) {
let [left, bottom] = image.xdv.as_ref().unwrap().layout_offset;
@@ -334,7 +334,11 @@ impl Executor {
use crate::pdf_device::PdfDriver;
let xdv = device.pdf.as_ref().is_some_and(|pdf| pdf.driver == PdfDriver::Xdv);
let pdf_color_start = if xdv {
self.xdv_colors.start_page().into_iter().collect()
self.xdv_colors
.start_page()
.into_iter()
.map(crate::pdf_device::ShippedColor::Page)
.collect()
} else if device.pdf.is_some() {
self.pdf_colors.start_page()
} else {
@@ -1,5 +1,5 @@
use super::*;
use crate::pdf_device::{ColorResult, PdfColorProgram, PdfColorStackAction};
use crate::pdf_device::{ColorResult, PdfColorProgram, PdfColorStackAction, PdfLiteralMode, ShippedColor};
impl Executor {
fn scan_pdf_color_program(
@@ -16,13 +16,16 @@ impl Executor {
files: &mut impl SourceProvider,
) -> Result<usize, Error> {
let replay_on_page = self.keyword("page", files)?;
// Device-color operators are independent of the coordinate origin.
if !self.keyword("direct", files)? {
self.keyword("page", files)?;
}
let mode = if self.keyword("direct", files)? {
PdfLiteralMode::Direct
} else if self.keyword("page", files)? {
PdfLiteralMode::Page
} else {
PdfLiteralMode::Origin
};
let initial = self.scan_pdf_color_program(files)?;
self.pdf_colors
.allocate(initial, replay_on_page)
.allocate(initial, mode, replay_on_page)
.map_err(|message| self.error(message, self.current))
}
@@ -62,7 +65,7 @@ impl Executor {
action: &PdfColorStackAction,
span: Span,
files: &mut impl SourceProvider,
) -> Result<Option<Arc<PdfColorProgram>>, Error> {
) -> Result<Option<ShippedColor>, Error> {
self.current = span;
self.tick()?;
let warning = match self.pdf_colors.apply(stack, action) {
+1 -1
View File
@@ -769,7 +769,7 @@ impl Execution {
let mut font_affects_paint = BTreeMap::new();
for page in pages.iter_mut() {
let states = page.items.iter().filter_map(|item| match item {
DisplayItem::PdfColor(program) => Some(&program.graphics_states),
DisplayItem::PdfColor { program, .. } => Some(&program.graphics_states),
_ => None,
}).flatten().cloned().collect();
page.pdf_resources = PageResources::from_page(
+16 -13
View File
@@ -767,23 +767,29 @@ fn page_content(
}
continue;
}
if let DisplayItem::PdfGraphics {
x,
y,
operation: PdfGraphics::Literal { mode, bytes },
} = item
{
let literal = match item {
DisplayItem::PdfGraphics {
x,
y,
operation: PdfGraphics::Literal { mode, bytes },
} => Some((*x, *y, *mode, bytes.as_ref())),
DisplayItem::PdfColor {
x, y, mode, program, ..
} => Some((*x, *y, *mode, program.literal().as_bytes())),
_ => None,
};
if let Some((x, y, mode, bytes)) = literal {
NativeTextRun::flush(&mut native_text, &mut content);
let previous_origin = content.origin.position();
let special_origin = mode.xdv_origin([*x, height - *y], height, list.magnification);
let special_origin = mode.xdv_origin([x, height - y], height, list.magnification);
match mode {
PdfLiteralMode::Direct => {
native_text::NativeText::break_string(&mut tex_text, &mut content);
}
PdfLiteralMode::Page | PdfLiteralMode::Origin => {
native_text::NativeText::finish(&mut tex_text, &mut content);
if *mode == PdfLiteralMode::Origin {
content.move_origin([*x, height - *y], list.units, digits);
if mode == PdfLiteralMode::Origin {
content.move_origin([x, height - y], list.units, digits);
}
}
PdfLiteralMode::XdvOrigin | PdfLiteralMode::XdvDirect => {
@@ -1145,10 +1151,7 @@ fn page_content(
content.push_str(special);
content.push(b'\n');
}
DisplayItem::PdfColor(program) => {
content.push_str(program.literal());
content.push(b'\n');
}
DisplayItem::PdfColor { .. } => unreachable!("color handled before text"),
DisplayItem::PdfGraphics { x, y, operation } => {
let xdv = list.pdf.as_ref().is_some_and(|pdf| pdf.driver == PdfDriver::Xdv);
let device_origin = list.units == DisplayUnits::TeX && !xdv;
+1 -1
View File
@@ -105,7 +105,7 @@ pub(crate) mod xdv_image;
pub(crate) mod xdv_navigation;
pub(crate) mod xdv_object;
mod graphics;
pub(crate) use color::{ColorResult, PdfColorStacks};
pub(crate) use color::{ColorResult, PdfColorStacks, ShippedColor};
pub use color::{PdfColorProgram, PdfColorStackAction};
pub(crate) use graphics::{Affine, DeviceOrigin};
pub use graphics::{PdfGraphics, PdfLiteralMode, PdfMatrix};
+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()))
}
}
+4
View File
@@ -427,6 +427,10 @@ pub(crate) fn plan_spaces(
..
},
..
}
| DisplayItem::PdfColor {
mode: PdfLiteralMode::Direct,
..
} => {
NativeText::break_string(&mut text, &mut out);
}
+9 -4
View File
@@ -135,7 +135,12 @@ pub enum DisplayItem {
Background([u8; 3]),
/// Switch the fill colour for following text (RGB).
Fill([u8; 3]),
PdfColor(std::sync::Arc<crate::pdf_device::PdfColorProgram>),
PdfColor {
x: i64,
y: i64,
program: std::sync::Arc<crate::pdf_device::PdfColorProgram>,
mode: crate::pdf_device::PdfLiteralMode,
},
PdfGraphics {
x: i64,
y: i64,
@@ -435,7 +440,7 @@ impl DisplayList {
*x += dx;
*y += dy;
}
DisplayItem::Fill(_) | DisplayItem::Background(_) | DisplayItem::PdfColor(_) => {}
DisplayItem::Fill(_) | DisplayItem::Background(_) | DisplayItem::PdfColor { .. } => {}
DisplayItem::Special(_) | DisplayItem::PdfImageObject(_)
| DisplayItem::OpenTypeActualText(_) | DisplayItem::OpenTypeColor(_) => {}
}
@@ -455,7 +460,7 @@ impl DisplayList {
return Err("this page requires a PDF renderer".into());
}
for item in &self.items {
if let DisplayItem::PdfColor(program) = item
if let DisplayItem::PdfColor { program, .. } = item
&& program
.graphics_states
.iter()
@@ -775,7 +780,7 @@ impl DisplayList {
escape(content)
));
}
DisplayItem::PdfColor(program) => {
DisplayItem::PdfColor { program, .. } => {
if let Some(rgb) = program.fill {
fill = rgb;
rule_fill = rgb;
+1 -1
View File
@@ -362,7 +362,7 @@ impl SourceMap {
// Color controls change graphics state and occupy no geometry.
if matches!(
item,
DisplayItem::PdfColor(_) | DisplayItem::PdfImageObject(_) | DisplayItem::PdfTextSpace { .. }
DisplayItem::PdfColor { .. } | DisplayItem::PdfImageObject(_) | DisplayItem::PdfTextSpace { .. }
| DisplayItem::OpenTypeColor(_)
) {
continue;