diff --git a/crates/texrra-tex-core/src/execution/boxes.rs b/crates/texrra-tex-core/src/execution/boxes.rs index 2d3666f..a5ae227 100644 --- a/crates/texrra-tex-core/src/execution/boxes.rs +++ b/crates/texrra-tex-core/src/execution/boxes.rs @@ -3,6 +3,8 @@ use super::*; use crate::{HorizontalBox, HorizontalItem, Paragraph, ParagraphFont}; mod tail; pub(super) use tail::TailNodeRef; +mod leaders; +pub use leaders::{LeaderGlue, LeaderMode, LeaderPattern}; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum BoxKind { @@ -65,6 +67,7 @@ pub enum NativeVerticalNode { Line(Box), Glue(Glue), NamedGlue(Glue, Parameter), + Leaders(LeaderGlue), Kern(i32), /// A normal (engine-generated) kern, distinct from an explicit user kern. ImplicitKern(i32), @@ -90,7 +93,7 @@ impl NativeVerticalNode { Self::Insertion(_) => 4, Self::Mark(_) => 5, Self::Output(_) => 9, - Self::Glue(_) | Self::NamedGlue(_, _) => 11, + Self::Glue(_) | Self::NamedGlue(_, _) | Self::Leaders(_) => 11, Self::Kern(_) | Self::ImplicitKern(_) => 12, Self::Penalty(_) => 13, } @@ -109,6 +112,7 @@ impl NativeVerticalNode { Self::Box(b) => b.node_count(), Self::Line(b) => b.node_count(), Self::Insertion(n) => 1 + n.nodes.iter().map(Self::node_count).sum::(), + Self::Leaders(leader) => 1 + leader.pattern.node_count(), _ => 1, } } @@ -130,6 +134,7 @@ fn text_node_count(nodes: &[TextNode]) -> usize { TextNode::Insertion(value) => { value.nodes.iter().map(NativeVerticalNode::node_count).sum() } + TextNode::Leaders(leader) => leader.pattern.node_count(), _ => 0, } }) @@ -137,9 +142,8 @@ fn text_node_count(nodes: &[TextNode]) -> usize { } enum PackedHorizontal<'a> { Item(HorizontalItem), - PdfColor, - PdfGraphics, - PdfLink(&'a OutputNode), + Leaders(&'a LeaderGlue, i64), + Output(&'a OutputNode), } pub(super) enum BoxPaint<'a> { @@ -148,6 +152,47 @@ pub(super) enum BoxPaint<'a> { PdfGraphics, RowStart(RowLayout), PdfLink(&'a OutputNode, Option), + Output(&'a OutputNode), +} + +struct WalkBudget<'a> { + remaining: usize, + cancellation: Option<&'a Cancellation>, + leader_depth: usize, +} + +impl WalkBudget<'_> { + fn for_geometry() -> Self { + Self { + remaining: usize::MAX, + cancellation: None, + leader_depth: 0, + } + } + + fn charge(&mut self, count: usize) -> Result<(), &'static str> { + if self.cancellation.is_some_and(Cancellation::is_cancelled) { + return Err("native compilation cancelled"); + } + self.remaining = self + .remaining + .checked_sub(count) + .ok_or("native leader placement or material capacity exceeded")?; + Ok(()) + } + + fn inside_leader(&mut self, count: usize) -> Result<(), &'static str> { + if self.leader_depth > 0 { + self.charge(count)?; + } + Ok(()) + } +} + +pub(super) struct LeaderEffects { + pub outputs: Vec, + pub graphics_positions: Vec<[i64; 2]>, + pub work: usize, } #[derive(Clone, Copy)] @@ -167,8 +212,8 @@ pub(super) enum GeometryItem { } impl NativeBox { - pub(super) fn output_nodes(&self) -> Vec<&OutputNode> { - fn walk<'a>(b: &'a NativeBox, out: &mut Vec<&'a OutputNode>) { + pub(super) fn output_nodes(&self) -> (Vec<&OutputNode>, bool) { + fn walk<'a>(b: &'a NativeBox, out: &mut Vec<&'a OutputNode>, leaders: &mut bool) { if b.kind.is_unset() { return; } @@ -177,11 +222,12 @@ impl NativeBox { for n in nodes { match n { TextNode::Output(o) => out.push(o), + TextNode::Leaders(_) => *leaders = true, TextNode::Box(b) | TextNode::MathChar(b) | TextNode::Glyph { glyph: b, .. } => { if let Some(b) = &b.native_box { - walk(b, out) + walk(b, out, leaders) } } _ => {} @@ -192,8 +238,9 @@ impl NativeBox { for n in nodes { match n { NativeVerticalNode::Output(o) => out.push(o), + NativeVerticalNode::Leaders(_) => *leaders = true, NativeVerticalNode::Box(b) | NativeVerticalNode::Line(b) => { - walk(b, out) + walk(b, out, leaders) } _ => {} } @@ -202,8 +249,48 @@ impl NativeBox { } } let mut out = Vec::new(); - walk(self, &mut out); - out + let mut leaders = false; + walk(self, &mut out, &mut leaders); + (out, leaders) + } + + pub(super) fn leader_effects( + &self, + limit: usize, + cancellation: Option<&Cancellation>, + ) -> Result { + let mut outputs = Vec::new(); + let mut graphics_positions = Vec::new(); + let mut budget = WalkBudget { + remaining: limit, + cancellation, + leader_depth: 0, + }; + self.walk_at(0, 0, 0, false, &mut budget, &mut |x, y, item| { + if let BoxPaint::Output(o) = item { + if o.is_pdf_graphics() { + graphics_positions.push([x, y]); + } + outputs.push(o.clone()); + } + })?; + Ok(LeaderEffects { + outputs, + graphics_positions, + work: limit - budget.remaining, + }) + } + + pub(super) fn contains_output(&self) -> Result { + let (nodes, leaders) = self.output_nodes(); + if !nodes.is_empty() { + return Ok(true); + } + Ok(leaders + && !self + .leader_effects(Limits::default().tokens, None)? + .outputs + .is_empty()) } /// Derive positioned material from the original owned list and glue set. /// The box never stores a second recursive copy of its children for paint. @@ -213,8 +300,13 @@ impl NativeBox { .into_iter() .filter_map(|item| match item { PackedHorizontal::Item(value) => Some(value), - PackedHorizontal::PdfColor | PackedHorizontal::PdfGraphics - | PackedHorizontal::PdfLink(_) => None, + PackedHorizontal::Leaders(_, width) => Some(HorizontalItem::Glue { + width, + stretch: 0, + shrink: 0, + order: 0, + }), + PackedHorizontal::Output(node) => node.image_box().map(HorizontalItem::Box), }) .collect(), ) @@ -256,25 +348,16 @@ impl NativeBox { shrink: 0, order: 0, }, - TextNode::Output(node) - if matches!(node.operation, OutputOperation::PdfColor { .. }) => - { - items.push(PackedHorizontal::PdfColor); - continue; - } - TextNode::Output(node) if node.is_pdf_graphics() => { - items.push(PackedHorizontal::PdfGraphics); - continue; - } - TextNode::Output(node) if node.is_pdf_link() => { - items.push(PackedHorizontal::PdfLink(node)); + TextNode::Leaders(leader) => { + let g = leader.glue; + let width = i64::from(g.width) + + self.setting.adjustment(g, &mut cumulative, &mut previous); + items.push(PackedHorizontal::Leaders(leader, width)); continue; } TextNode::Output(node) => { - let Some(image) = node.image_box() else { - continue; - }; - HorizontalItem::Box(image) + items.push(PackedHorizontal::Output(node)); + continue; } _ => continue, }; @@ -443,6 +526,13 @@ pub(super) fn vpack( depth = 0; flex(*g, &mut stretch, &mut shrink); } + NativeVerticalNode::Leaders(leader) => { + let g = leader.glue; + height += depth + i64::from(g.width); + depth = 0; + width = width.max(leader.pattern_dimensions().0); + flex(g, &mut stretch, &mut shrink); + } NativeVerticalNode::Kern(n) | NativeVerticalNode::ImplicitKern(n) => { height += depth + *n as i64; depth = 0; @@ -527,6 +617,13 @@ pub(super) fn hpack( width += g.width as i64; flex(*g, &mut stretch, &mut shrink); } + TextNode::Leaders(leader) => { + width += i64::from(leader.glue.width); + let (_, h, d) = leader.pattern_dimensions(); + height = height.max(h); + depth = depth.max(d); + flex(leader.glue, &mut stretch, &mut shrink); + } _ => {} } } @@ -597,7 +694,8 @@ impl NativeBox { font: crate::render::FontFace::Roman, }); } - }); + }) + .expect("paint traversal of an already measured list"); } /// Walk original packed lists in TeX sp, before the single display export. pub fn geometry(&self) -> Result { @@ -632,7 +730,7 @@ impl NativeBox { emit(GeometryItem::PdfGraphics { x, y }); return; } - BoxPaint::RowStart(_) | BoxPaint::PdfLink(_, _) => return, + BoxPaint::RowStart(_) | BoxPaint::PdfLink(_, _) | BoxPaint::Output(_) => return, }; if let Some(child) = &b.math_geometry { for p in &child.items { @@ -646,7 +744,7 @@ impl NativeBox { } else if b.character.is_some() { unsupported = true; } - }); + })?; if unsupported { Err("native math box requires actual native glyph geometry".into()) } else { @@ -660,49 +758,100 @@ impl NativeBox { if matches!(node, BoxPaint::PdfGraphics) { all.push([x, y]); } - }); + }) + .expect("graphics traversal of an already measured list"); all } - fn walk(&self, x: i64, y: i64, emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>)) { - self.walk_at(x, y, 0, false, emit); + fn walk( + &self, + x: i64, + y: i64, + emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>), + ) -> Result<(), &'static str> { + self.walk_at(x, y, 0, false, &mut WalkBudget::for_geometry(), emit) } pub(super) fn walk_pdf_links(&self, emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>)) { - self.walk_at(0, 0, 0, true, emit); + self.walk_at(0, 0, 0, true, &mut WalkBudget::for_geometry(), emit) + .expect("link traversal of an already measured list"); } - fn walk_at(&self, x: i64, y: i64, level: usize, links: bool, - emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>)) { + fn walk_at( + &self, + x: i64, + y: i64, + level: usize, + links: bool, + budget: &mut WalkBudget<'_>, + emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>), + ) -> Result<(), &'static str> { if self.kind.is_unset() { - return; + return Ok(()); } match &self.content { - BoxContent::Horizontal(_) => { + BoxContent::Horizontal(nodes) => { + budget.inside_leader(nodes.len())?; let row = RowLayout { left: x, baseline: y, width: self.width, height: self.height, depth: self.depth, level }; if links { emit(x, y, BoxPaint::RowStart(row)); } - walk_row(&self.packed_horizontal().unwrap(), row, links, emit); + walk_row(&self.packed_horizontal().unwrap(), row, links, budget, emit)?; } BoxContent::Vertical(nodes) => { let mut cursor = y - self.height; let (mut cumulative, mut previous) = (0, 0); for node in nodes { + budget.inside_leader(1)?; match node { NativeVerticalNode::Box(b) | NativeVerticalNode::Line(b) => { if b.kind.is_unset() { continue; } cursor += b.height; - b.walk_at(x + b.shift, cursor, level + 1, links, emit); + b.walk_at(x + b.shift, cursor, level + 1, links, budget, emit)?; cursor += b.depth; } NativeVerticalNode::Glue(g) | NativeVerticalNode::NamedGlue(g, _) => { cursor += i64::from(g.width) + self.setting.adjustment(*g, &mut cumulative, &mut previous) } + NativeVerticalNode::Leaders(leader) => { + let g = leader.glue; + let length = i64::from(g.width) + + self.setting.adjustment(g, &mut cumulative, &mut previous); + match &leader.pattern { + LeaderPattern::Box(b) => { + for pos in leader.positions( + y - self.height, + cursor, + length, + b.height + b.depth, + ) { + b.walk_leader( + x + b.shift, + pos + b.height, + level + 1, + links, + budget, + emit, + )?; + } + } + LeaderPattern::Rule(r) if length > 0 => { + let r = NativeRule { + height: Some(length as i32), + depth: Some(0), + ..*r + }; + let paint = r.horizontal_item(self.width, 0, 0); + emit(x, cursor + length, BoxPaint::Box(&paint)); + } + _ => {} + } + cursor += length; + } NativeVerticalNode::Kern(n) | NativeVerticalNode::ImplicitKern(n) => { cursor += i64::from(*n) } @@ -712,20 +861,8 @@ impl NativeBox { emit(x, cursor, BoxPaint::Box(&b)); cursor += b.depth; } - NativeVerticalNode::Output(node) - if matches!(node.operation, OutputOperation::PdfColor { .. }) => - { - emit(x, cursor, BoxPaint::PdfColor); - } - NativeVerticalNode::Output(node) if node.is_pdf_graphics() => { - emit(x, cursor, BoxPaint::PdfGraphics); - } - NativeVerticalNode::Output(node) if node.is_pdf_link() => { - if links { - emit(x, cursor, BoxPaint::PdfLink(node, None)); - } - } NativeVerticalNode::Output(node) => { + walk_output(node, x, cursor, None, links, emit); if let Some(image) = node.image_box() { cursor += image.height; emit(x, cursor, BoxPaint::Box(&image)); @@ -737,6 +874,28 @@ impl NativeBox { } } } + Ok(()) + } + + fn walk_leader( + &self, + x: i64, + y: i64, + level: usize, + links: bool, + budget: &mut WalkBudget<'_>, + emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>), + ) -> Result<(), &'static str> { + budget.charge(1)?; + budget.leader_depth += 1; + let result = self.walk_at(x, y, level, links, budget, &mut |x, y, paint| { + if !matches!(paint, BoxPaint::Output(o) if matches!(o.operation, + OutputOperation::Open { .. } | OutputOperation::Write { .. } | OutputOperation::Close { .. })) { + emit(x, y, paint); + } + }); + budget.leader_depth -= 1; + result } } pub(super) fn bp(n: i64) -> i64 { @@ -750,27 +909,73 @@ fn walk_row( items: &[PackedHorizontal<'_>], row: RowLayout, links: bool, + budget: &mut WalkBudget<'_>, emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>), -) { +) -> Result<(), &'static str> { let mut x = row.left; let y = row.baseline; for item in items { match item { PackedHorizontal::Item(HorizontalItem::Box(b)) => { if let Some(child) = &b.native_box { - child.walk_at(x, y + child.shift, row.level + 1, links, emit); + child.walk_at(x, y + child.shift, row.level + 1, links, budget, emit)?; } else { + if let Some(geometry) = &b.math_geometry { + budget.inside_leader(geometry.items.len())?; + } emit(x, y, BoxPaint::Box(b)); } x += b.width; } PackedHorizontal::Item(HorizontalItem::Glue { width, .. }) => x += width, - PackedHorizontal::PdfColor => emit(x, y, BoxPaint::PdfColor), - PackedHorizontal::PdfGraphics => emit(x, y, BoxPaint::PdfGraphics), - PackedHorizontal::PdfLink(node) if links => emit(x, y, BoxPaint::PdfLink(node, Some(row))), + PackedHorizontal::Leaders(leader, width) => { + match &leader.pattern { + LeaderPattern::Box(b) => { + for pos in leader.positions(row.left, x, *width, b.width) { + b.walk_leader(pos, y + b.shift, row.level + 1, links, budget, emit)?; + } + } + LeaderPattern::Rule(r) if *width > 0 => { + let r = NativeRule { + width: Some(*width as i32), + ..*r + }; + let paint = r.horizontal_item(row.width, row.height, row.depth); + emit(x, y, BoxPaint::Box(&paint)); + } + _ => {} + } + x += width; + } + PackedHorizontal::Output(node) => { + walk_output(node, x, y, Some(row), links, emit); + if let Some(image) = node.image_box() { + emit(x, y, BoxPaint::Box(&image)); + x += image.width; + } + } _ => {} } } + Ok(()) +} + +fn walk_output( + node: &OutputNode, + x: i64, + y: i64, + row: Option, + links: bool, + emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>), +) { + emit(x, y, BoxPaint::Output(node)); + if matches!(node.operation, OutputOperation::PdfColor { .. }) { + emit(x, y, BoxPaint::PdfColor); + } else if node.is_pdf_graphics() { + emit(x, y, BoxPaint::PdfGraphics); + } else if links && node.is_pdf_link() { + emit(x, y, BoxPaint::PdfLink(node, row)); + } } pub(super) fn box_paragraph(mut b: NativeBox) -> Paragraph { let (width, height, depth, shift) = (b.width, b.height, b.depth, b.shift); diff --git a/crates/texrra-tex-core/src/execution/boxes/leaders.rs b/crates/texrra-tex-core/src/execution/boxes/leaders.rs new file mode 100644 index 0000000..e0faf05 --- /dev/null +++ b/crates/texrra-tex-core/src/execution/boxes/leaders.rs @@ -0,0 +1,74 @@ +//! Owned leader glue. The pattern is kept once even when it paints many times. +use super::*; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub enum LeaderMode { + Aligned, + Centered, + Expanded, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub enum LeaderPattern { + Box(Box), + Rule(NativeRule), +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct LeaderGlue { + pub glue: Glue, + pub mode: LeaderMode, + pub pattern: LeaderPattern, +} + +impl LeaderGlue { + pub(super) fn pattern_dimensions(&self) -> (i64, i64, i64) { + match &self.pattern { + LeaderPattern::Box(b) => (b.width, b.height - b.shift, b.depth + b.shift), + LeaderPattern::Rule(r) => r.dimensions(), + } + } + + pub(super) fn positions( + &self, + origin: i64, + start: i64, + available: i64, + tile: i64, + ) -> impl Iterator { + let (first, stride, count) = if tile <= 0 || available <= 0 { + (start, 0, 0) + } else { + // TeX includes 10 sp in its fit check to absorb glue rounding. + // The caller still advances by the original adjusted glue length. + let length = available + 10; + let copies = length / tile; + let remaining = length % tile; + let (offset, gap) = match self.mode { + LeaderMode::Aligned => ((origin - start).rem_euclid(tile), 0), + LeaderMode::Centered => (remaining / 2, 0), + LeaderMode::Expanded => { + let gap = remaining / (copies + 1); + ((remaining - (copies - 1) * gap) / 2, gap) + } + }; + let stride = tile + gap; + let count = if length - offset >= tile { + 1 + (length - offset - tile) / stride + } else { + 0 + }; + (start + offset, stride, count) + }; + (0..count).map(move |copy| first + copy * stride) + } +} + +impl LeaderPattern { + pub(in crate::execution) fn node_count(&self) -> usize { + match self { + Self::Box(b) => b.node_count(), + Self::Rule(_) => 1, + } + } +} diff --git a/crates/texrra-tex-core/src/execution/boxes/tail.rs b/crates/texrra-tex-core/src/execution/boxes/tail.rs index 43d959a..e6bf16c 100644 --- a/crates/texrra-tex-core/src/execution/boxes/tail.rs +++ b/crates/texrra-tex-core/src/execution/boxes/tail.rs @@ -80,6 +80,7 @@ fn horizontal(n: NativeVerticalNode) -> TextNode { }), NativeVerticalNode::Glue(g) => TextNode::Glue(g), NativeVerticalNode::NamedGlue(g, p) => TextNode::NamedGlue(g, p), + NativeVerticalNode::Leaders(l) => TextNode::Leaders(l), NativeVerticalNode::Kern(width) => TextNode::Kern { width, explicit: true, diff --git a/crates/texrra-tex-core/src/execution/diagnostics.rs b/crates/texrra-tex-core/src/execution/diagnostics.rs index a15f975..f2b3e57 100644 --- a/crates/texrra-tex-core/src/execution/diagnostics.rs +++ b/crates/texrra-tex-core/src/execution/diagnostics.rs @@ -15,6 +15,11 @@ pub enum DiagnosticNode { value: Glue, name: Option, }, + Leaders { + value: Glue, + mode: LeaderMode, + pattern: Box, + }, Kern { width: i32, explicit: bool, @@ -74,6 +79,18 @@ pub(super) fn box_view(b: &NativeBox) -> DiagnosticBox { nodes, } } + +fn leader_node(leader: &LeaderGlue) -> DiagnosticNode { + let pattern = match &leader.pattern { + LeaderPattern::Box(b) => DiagnosticNode::Box(box_view(b)), + LeaderPattern::Rule(r) => DiagnosticNode::Rule(*r), + }; + DiagnosticNode::Leaders { + value: leader.glue, + mode: leader.mode, + pattern: Box::new(pattern), + } +} fn vertical_nodes(nodes: &[NativeVerticalNode]) -> Vec { nodes .iter() @@ -88,6 +105,7 @@ fn vertical_nodes(nodes: &[NativeVerticalNode]) -> Vec { value: *g, name: Some(*p), }, + NativeVerticalNode::Leaders(leader) => leader_node(leader), NativeVerticalNode::Kern(k) => DiagnosticNode::Kern { width: *k, explicit: true, @@ -190,6 +208,7 @@ pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec { value: *g, name: None, }, + TextNode::Leaders(leader) => leader_node(leader), TextNode::Kern { width, explicit } => DiagnosticNode::Kern { width: *width, explicit: *explicit, @@ -435,6 +454,23 @@ impl Printer<'_> { self.number(*w as i64); } DiagnosticNode::Glue { value, name } => self.glue(*value, *name), + DiagnosticNode::Leaders { + value, + mode, + pattern, + } => { + self.command(match mode { + LeaderMode::Aligned => "leaders", + LeaderMode::Centered => "cleaders", + LeaderMode::Expanded => "xleaders", + }); + self.literal(" "); + self.glue_spec(*value); + self.nodes( + std::slice::from_ref(pattern.as_ref()), + &format!("{prefix}."), + )?; + } DiagnosticNode::Kern { width, explicit } => { self.command("kern"); if *explicit { diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 98e64b2..59f20d0 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -167,6 +167,8 @@ pub struct Executor { pdf_colors: crate::pdf_device::PdfColorStacks, pdf_link_stack: Vec, pdf_catalog_tokens: Vec, + pdf_outlines: Vec>>, + pdf_outline_payload: usize, pdf_info_tokens: Vec, pdf_images: Vec, input_position: Option<(usize, usize)>, @@ -294,6 +296,8 @@ impl Executor { pdf_colors: Default::default(), pdf_link_stack: Vec::new(), pdf_catalog_tokens: Vec::new(), + pdf_outlines: Vec::new(), + pdf_outline_payload: 0, pdf_info_tokens: Vec::new(), pdf_images: Vec::new(), input_position: None, @@ -3460,6 +3464,7 @@ impl Executor { Unskip | Unkern | Unpenalty => self.delete_last(primitive)?, ItalicCorrection => self.append_italic_correction()?, Shipout => self.scan_box(boxes::Destination::Shipout, files)?, + Leaders | Cleaders | Xleaders => self.scan_leaders(primitive, files)?, Vrule => { let r = self.scan_rule(false, TokenOrigin::from(&token), files)?; let p = self.paragraph.as_mut().unwrap(); @@ -3550,6 +3555,7 @@ impl Executor { self.scan_pdf_link(primitive, token.span, files)?; } Pdfcatalog => self.scan_pdf_catalog(files)?, + Pdfoutline => self.scan_pdf_outline(files)?, Pdfinfo => self.scan_pdf_info(files)?, Pdfximage => self.scan_pdf_image(&token, false, files)?, Pdfrefximage => self.reference_pdf_image(&token, files)?, diff --git a/crates/texrra-tex-core/src/execution/engine/alignment.rs b/crates/texrra-tex-core/src/execution/engine/alignment.rs index 1113319..313c36a 100644 --- a/crates/texrra-tex-core/src/execution/engine/alignment.rs +++ b/crates/texrra-tex-core/src/execution/engine/alignment.rs @@ -817,14 +817,20 @@ fn set_alignment_cell( match &cell.content { BoxContent::Horizontal(v) => { for n in v { - if let TextNode::Glue(g) | TextNode::NamedGlue(g, _) = n { + if let TextNode::Glue(g) + | TextNode::NamedGlue(g, _) + | TextNode::Leaders(LeaderGlue { glue: g, .. }) = n + { add(*g) } } } BoxContent::Vertical(v) => { for n in v { - if let NativeVerticalNode::Glue(g) | NativeVerticalNode::NamedGlue(g, _) = n { + if let NativeVerticalNode::Glue(g) + | NativeVerticalNode::NamedGlue(g, _) + | NativeVerticalNode::Leaders(LeaderGlue { glue: g, .. }) = n + { add(*g) } } @@ -985,14 +991,20 @@ fn mark_unset(b: &mut NativeBox, span: u8) -> Result<(), String> { match &b.content { BoxContent::Horizontal(v) => { for n in v { - if let TextNode::Glue(g) | TextNode::NamedGlue(g, _) = n { + if let TextNode::Glue(g) + | TextNode::NamedGlue(g, _) + | TextNode::Leaders(LeaderGlue { glue: g, .. }) = n + { add(*g); } } } BoxContent::Vertical(v) => { for n in v { - if let NativeVerticalNode::Glue(g) | NativeVerticalNode::NamedGlue(g, _) = n { + if let NativeVerticalNode::Glue(g) + | NativeVerticalNode::NamedGlue(g, _) + | NativeVerticalNode::Leaders(LeaderGlue { glue: g, .. }) = n + { add(*g); } } diff --git a/crates/texrra-tex-core/src/execution/engine/boxes.rs b/crates/texrra-tex-core/src/execution/engine/boxes.rs index 5cae254..a7d2c47 100644 --- a/crates/texrra-tex-core/src/execution/engine/boxes.rs +++ b/crates/texrra-tex-core/src/execution/engine/boxes.rs @@ -6,6 +6,7 @@ pub(super) enum Destination { Register(u16, bool), Shift(i32), Shipout, + Leaders(LeaderMode), Adjustment { pre: bool }, Insertion { class: u8 }, } @@ -340,6 +341,74 @@ impl Executor { .ok_or_else(|| self.error("expected native box constructor", token.span))?; self.box_command(p, destination, token.span, files) } + + pub(super) fn scan_leaders( + &mut self, + primitive: Primitive, + files: &mut impl SourceProvider, + ) -> Result<(), Error> { + let mode = match primitive { + Primitive::Leaders => LeaderMode::Aligned, + Primitive::Cleaders => LeaderMode::Centered, + Primitive::Xleaders => LeaderMode::Expanded, + _ => unreachable!("leader primitive"), + }; + let token = loop { + let t = self.expanded_non_space(files)?.token; + if self.primitive(&t) != Some(Primitive::Relax) { + break t; + } + }; + match self.primitive(&token) { + Some(rule @ (Primitive::Hrule | Primitive::Vrule)) => { + let rule = + self.scan_rule(rule == Primitive::Hrule, TokenOrigin::from(&token), files)?; + self.finish_leaders(mode, Some(LeaderPattern::Rule(rule)), files) + } + Some(p) => self.box_command(p, Destination::Leaders(mode), token.span, files), + None => self.fail("a box or rule is required for native leaders"), + } + } + + fn finish_leaders( + &mut self, + mode: LeaderMode, + pattern: Option, + files: &mut impl SourceProvider, + ) -> Result<(), Error> { + use Primitive::*; + let vertical = self.paragraph.is_none() && self.math.is_empty(); + let token = self.expanded_non_space(files)?.token; + let glue = match self.primitive(&token) { + Some(p @ (Vskip | Vfil | Vfill | Vss | Vfilneg)) if vertical => { + self.skip_glue(p, files)? + } + Some(p @ (Hskip | Hfil | Hfill | Hss | Hfilneg)) if !vertical => { + self.skip_glue(p, files)? + } + _ => return Err(self.error("leaders not followed by proper glue", token.span)), + }; + let leader = pattern.map(|pattern| LeaderGlue { + glue, + mode, + pattern, + }); + if let Some(math) = self.math.last_mut() { + math.nodes + .push(leader.map_or(MathNode::ExplicitSpace(glue, None), MathNode::Leaders)); + } else if let Some(paragraph) = self.paragraph.as_mut() { + paragraph + .nodes + .push(leader.map_or(TextNode::Glue(glue), TextNode::Leaders)); + } else { + let start = self.vertical.nodes.len(); + self.vertical + .push(leader.map_or(NativeVerticalNode::Glue(glue), NativeVerticalNode::Leaders)); + self.emit_vertical(start); + self.request_page(); + } + Ok(()) + } pub(super) fn box_command( &mut self, p: Primitive, @@ -853,6 +922,9 @@ impl Executor { self.pending_shipouts.push_back(b); } } + Destination::Leaders(mode) => { + self.finish_leaders(mode, b.map(|b| LeaderPattern::Box(Box::new(b))), files)?; + } Destination::Append | Destination::Shift(_) => { if let Some(b) = b { if !self.math.is_empty() { diff --git a/crates/texrra-tex-core/src/execution/engine/display.rs b/crates/texrra-tex-core/src/execution/engine/display.rs index d27b885..c4a50aa 100644 --- a/crates/texrra-tex-core/src/execution/engine/display.rs +++ b/crates/texrra-tex-core/src/execution/engine/display.rs @@ -152,7 +152,10 @@ impl Executor { if b.width + q > width { let mut shrink = [0i64; 4]; for node in &material { - if let TextNode::Glue(g) | TextNode::NamedGlue(g, _) = node { + if let TextNode::Glue(g) + | TextNode::NamedGlue(g, _) + | TextNode::Leaders(LeaderGlue { glue: g, .. }) = node + { shrink[usize::from(g.shrink.order)] += i64::from(g.shrink.amount); } } @@ -177,7 +180,7 @@ impl Executor { displacement = (width - b.width - e + 1).div_euclid(2); if matches!( material.first(), - Some(TextNode::Glue(_) | TextNode::NamedGlue(_, _)) + Some(TextNode::Glue(_) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_)) ) { displacement = 0; } diff --git a/crates/texrra-tex-core/src/execution/engine/list_tail.rs b/crates/texrra-tex-core/src/execution/engine/list_tail.rs index 01d34cb..00ffa25 100644 --- a/crates/texrra-tex-core/src/execution/engine/list_tail.rs +++ b/crates/texrra-tex-core/src/execution/engine/list_tail.rs @@ -17,7 +17,9 @@ impl Tail { } fn text(node: &TextNode) -> Self { match node { - TextNode::Glue(g) | TextNode::NamedGlue(g, _) => Self::Glue(*g, false), + TextNode::Glue(g) + | TextNode::NamedGlue(g, _) + | TextNode::Leaders(LeaderGlue { glue: g, .. }) => Self::Glue(*g, false), TextNode::Kern { width, .. } => Self::Kern(*width), TextNode::Penalty(n) => Self::Penalty(*n), TextNode::Glyph { ligature, .. } => Self::Other(if *ligature { 7 } else { 0 }), @@ -43,9 +45,9 @@ impl Tail { } fn vertical(node: &NativeVerticalNode) -> Self { match node { - NativeVerticalNode::Glue(g) | NativeVerticalNode::NamedGlue(g, _) => { - Self::Glue(*g, false) - } + NativeVerticalNode::Glue(g) + | NativeVerticalNode::NamedGlue(g, _) + | NativeVerticalNode::Leaders(LeaderGlue { glue: g, .. }) => Self::Glue(*g, false), NativeVerticalNode::Kern(n) | NativeVerticalNode::ImplicitKern(n) => Self::Kern(*n), NativeVerticalNode::Penalty(n) => Self::Penalty(*n), _ => Self::Other(node.node_type()), @@ -53,6 +55,7 @@ impl Tail { } fn math(node: &MathNode) -> Self { match node { + MathNode::Leaders(leader) => Self::Glue(leader.glue, false), MathNode::Glue(g) => Self::Glue(*g, true), MathNode::ExplicitSpace(g, _) => Self::Glue(*g, false), MathNode::Kern { amount, .. } => Self::Kern(*amount), diff --git a/crates/texrra-tex-core/src/execution/engine/math.rs b/crates/texrra-tex-core/src/execution/engine/math.rs index 48f418a..8a46a03 100644 --- a/crates/texrra-tex-core/src/execution/engine/math.rs +++ b/crates/texrra-tex-core/src/execution/engine/math.rs @@ -547,7 +547,7 @@ impl Executor { Vcenter => self.box_command(*p, boxes::Destination::Append, token.span, files)?, Hbox | Vbox | Vtop | Box | Copy | Setbox | Wd | Ht | Dp | Lastbox | Raise | Lower | Vsplit | Mark | Marks | Vadjust | Insert | Shipout | Openout - | Closeout | Write | Pdfcolorstack | Pdfsave | Pdfsetmatrix | Pdfrestore | Pdfcatalog + | Closeout | Write | Pdfcolorstack | Pdfsave | Pdfsetmatrix | Pdfrestore | Pdfcatalog | Pdfoutline | Ignorespaces | Unskip | Unkern | Unpenalty => { return Ok(false); } @@ -690,6 +690,7 @@ impl Executor { .nodes .push(MathNode::ExplicitSpace(g, None)); } + Leaders | Cleaders | Xleaders => self.scan_leaders(*p, files)?, Mskip => { let g = self.skip_glue(*p, files)?; self.math.last_mut().unwrap().nodes.push(MathNode::Glue(g)); diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index c2c63ea..f6cade2 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -272,10 +272,29 @@ impl Executor { let mut pdf_color_steps = Vec::new(); let mut pdf_graphics_steps = Vec::new(); let mut graphics_stack = Vec::new(); - let outputs = b.output_nodes(); + let (mut outputs, has_leaders) = b.output_nodes(); + let leader_effects = if has_leaders { + let limit = self + .limits + .steps + .saturating_sub(self.steps) + .min(self.limits.tokens); + let effects = b + .leader_effects(limit, self.cancellation.as_ref()) + .map_err(|error| self.error(error, b.span))?; + self.steps += effects.work; + Some(effects) + } else { + None + }; + if let Some(effects) = &leader_effects { + outputs = effects.outputs.iter().collect(); + } let mut link_depth = self.pdf_link_stack.len(); let has_link_material = link_depth != 0 || outputs.iter().any(|node| node.is_pdf_link()); - let mut graphics_positions = if outputs.iter().any(|node| node.is_pdf_graphics()) { + let mut graphics_positions = if let Some(effects) = &leader_effects { + effects.graphics_positions.clone().into_iter() + } else if outputs.iter().any(|node| node.is_pdf_graphics()) { b.pdf_graphics_positions().into_iter() } else { Vec::new().into_iter() diff --git a/crates/texrra-tex-core/src/execution/engine/pdf_catalog.rs b/crates/texrra-tex-core/src/execution/engine/pdf_catalog.rs index a5a1324..929d7a1 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_catalog.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_catalog.rs @@ -1,6 +1,6 @@ use super::*; use crate::pdf_device::{ - catalog::{CatalogAction, CatalogTarget}, + catalog::{CatalogAction, CatalogTarget, PdfOutline}, links::DestinationId, }; @@ -204,7 +204,49 @@ impl Executor { Ok(()) } + pub(super) fn scan_pdf_outline(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> { + if self.read_parameter(Parameter::Pdfoutput).width() <= 0 { + return self.fail("\\pdfoutline not allowed in DVI mode"); + } + let attributes = if self.keyword("attr", files)? { + self.scan_pdf_tokens(files)? + } else { + Vec::new() + }; + let action = self.scan_catalog_action(files)?; + let count = if self.keyword("count", files)? { + self.integer(files)? + } else { + 0 + }; + let title = self.scan_pdf_bytes(files)?; + let payload = 1 + title.len() + attributes.len() + action.payload_len(); + if payload.saturating_add(self.pdf_outline_payload) > self.limits.tokens { + return self.fail("native PDF outline material limit exceeded"); + } + self.pdf_page_data(files)?; + self.pdf_outline_payload += payload; + self.pdf_outlines.push(PdfOutline { title, attributes, action, count }); + Ok(()) + } + pub(super) fn finish_pdf_dictionaries(&mut self) -> Result<(), Error> { + if !self.pdf_outlines.is_empty() { + let pending = std::mem::take(&mut self.pdf_outlines); + let mut outlines = Vec::with_capacity(pending.len()); + for PdfOutline { title, attributes, action, count } in pending { + outlines.push(PdfOutline { + title, + attributes: self.pdf_token_bytes(&attributes)?, + action, + count, + }); + } + self.state + .pdf_catalog + .get_or_insert_with(Default::default) + .outlines.extend(outlines); + } if !self.pdf_catalog_tokens.is_empty() { let tokens = std::mem::take(&mut self.pdf_catalog_tokens); let bytes = self.pdf_token_bytes(&tokens)?; diff --git a/crates/texrra-tex-core/src/execution/engine/statistics.rs b/crates/texrra-tex-core/src/execution/engine/statistics.rs index c910afa..b834181 100644 --- a/crates/texrra-tex-core/src/execution/engine/statistics.rs +++ b/crates/texrra-tex-core/src/execution/engine/statistics.rs @@ -88,7 +88,8 @@ impl Executor { if self.after_assignment.is_some() { c.usage.token_list_cells += 1; } - c.usage.token_list_cells += self.pdf_catalog_tokens.len(); + c.usage.token_list_cells += self.pdf_catalog_tokens.len() + + self.pdf_outlines.iter().map(|entry| entry.attributes.len()).sum::(); for input in &self.inputs { match input { InputFrame::Source { mouth, .. } => { diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index 7359150..9042f0e 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -7,7 +7,7 @@ use std::{ path::Path, }; -const SCHEMA: u32 = 25; +const SCHEMA: u32 = 27; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); #[derive(serde::Serialize, serde::Deserialize)] diff --git a/crates/texrra-tex-core/src/execution/math.rs b/crates/texrra-tex-core/src/execution/math.rs index 90afaa0..e0be55b 100644 --- a/crates/texrra-tex-core/src/execution/math.rs +++ b/crates/texrra-tex-core/src/execution/math.rs @@ -164,6 +164,7 @@ pub enum MathNode { Glue(Glue), /// Normal-unit glue, including explicit spaces and horizontal skip commands. ExplicitSpace(Glue, Option), + Leaders(LeaderGlue), Kern { amount: i32, mu: bool, @@ -441,7 +442,7 @@ impl Converter<'_> { } pub(super) fn clean(&self, nodes: &[TextNode]) -> Result { let b = self.measure(nodes)?; - if !b.output_nodes().is_empty() { + if b.contains_output()? { return Err("deferred output in flattened native math fields requires retained semantic math boxes".into()); } b.geometry() @@ -462,7 +463,7 @@ impl Converter<'_> { self.clean(&[TextNode::Box(math_box(g))]) } MathField::Box(b) => { - if !b.output_nodes().is_empty() { + if b.contains_output()? { return Err("deferred output in flattened native math fields requires retained semantic math boxes".into()); } if b.shift == 0 { @@ -701,6 +702,7 @@ impl Converter<'_> { Some(parameter) => TextNode::NamedGlue(*glue, *parameter), None => TextNode::Glue(*glue), }], + MathNode::Leaders(leader) => vec![TextNode::Leaders(leader.clone())], MathNode::Glue(g) => vec![TextNode::Glue(self.glue(*g, style)?)], MathNode::Kern { amount, diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index 6249a78..7c28040 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -46,7 +46,10 @@ pub use statistics::{ use std::collections::BTreeSet; use std::fmt; -pub use boxes::{BoxContent, BoxKind, GlueSetting, NativeBox, NativeVerticalNode}; +pub use boxes::{ + BoxContent, BoxKind, GlueSetting, LeaderGlue, LeaderMode, LeaderPattern, NativeBox, + NativeVerticalNode, +}; pub use cancellation::Cancellation; pub use case::CaseCode; pub use context::{ContextFrame, ContextKind, InputContext}; @@ -744,7 +747,9 @@ impl Execution { &boxes::box_paragraph(*b.clone()), ))); } - NativeVerticalNode::Glue(g) | NativeVerticalNode::NamedGlue(g, _) => { + NativeVerticalNode::Glue(g) + | NativeVerticalNode::NamedGlue(g, _) + | NativeVerticalNode::Leaders(LeaderGlue { glue: g, .. }) => { items.push(VerticalItem::StretchGlue(VerticalGlue::with_order( bp(g.width as i64), bp(g.stretch.amount as i64), diff --git a/crates/texrra-tex-core/src/execution/page_builder.rs b/crates/texrra-tex-core/src/execution/page_builder.rs index 1e36aa7..8c46cdc 100644 --- a/crates/texrra-tex-core/src/execution/page_builder.rs +++ b/crates/texrra-tex-core/src/execution/page_builder.rs @@ -184,7 +184,9 @@ impl NativePageState { return Err("native page construction step limit exceeded".into()); } self.last_glue = match front { - NativeVerticalNode::Glue(g) | NativeVerticalNode::NamedGlue(g, _) => Some(*g), + NativeVerticalNode::Glue(g) + | NativeVerticalNode::NamedGlue(g, _) + | NativeVerticalNode::Leaders(LeaderGlue { glue: g, .. }) => Some(*g), _ => None, }; self.last_node_type = Some(front.node_type()); @@ -202,6 +204,7 @@ impl NativePageState { front, NativeVerticalNode::Glue(_) | NativeVerticalNode::NamedGlue(_, _) + | NativeVerticalNode::Leaders(_) | NativeVerticalNode::Kern(_) | NativeVerticalNode::ImplicitKern(_) | NativeVerticalNode::Penalty(_) @@ -226,29 +229,34 @@ impl NativePageState { continue; } let penalty = match front { - NativeVerticalNode::Glue(_) | NativeVerticalNode::NamedGlue(_, _) => { - self.nodes - .last() - .filter(|n| { - matches!( - n, - NativeVerticalNode::Box(_) - | NativeVerticalNode::Line(_) - | NativeVerticalNode::Rule(_) - | NativeVerticalNode::Mark(_) - | NativeVerticalNode::Insertion(_) - | NativeVerticalNode::Output(_) - ) - }) - .map(|_| 0) - } + NativeVerticalNode::Glue(_) + | NativeVerticalNode::NamedGlue(_, _) + | NativeVerticalNode::Leaders(_) => self + .nodes + .last() + .filter(|n| { + matches!( + n, + NativeVerticalNode::Box(_) + | NativeVerticalNode::Line(_) + | NativeVerticalNode::Rule(_) + | NativeVerticalNode::Mark(_) + | NativeVerticalNode::Insertion(_) + | NativeVerticalNode::Output(_) + ) + }) + .map(|_| 0), NativeVerticalNode::Kern(_) | NativeVerticalNode::ImplicitKern(_) => { if self.contributions.len() == 1 { return Ok(None); } matches!( self.contributions.get(1), - Some(NativeVerticalNode::Glue(_) | NativeVerticalNode::NamedGlue(_, _)) + Some( + NativeVerticalNode::Glue(_) + | NativeVerticalNode::NamedGlue(_, _) + | NativeVerticalNode::Leaders(_) + ) ) .then_some(0) } @@ -347,7 +355,9 @@ impl NativePageState { self.dimensions[7] = depth; } else { match &n { - NativeVerticalNode::Glue(g) | NativeVerticalNode::NamedGlue(g, _) => { + NativeVerticalNode::Glue(g) + | NativeVerticalNode::NamedGlue(g, _) + | NativeVerticalNode::Leaders(LeaderGlue { glue: g, .. }) => { if g.shrink.order != 0 && g.shrink.amount != 0 { return Err( "infinite glue shrinkage found on native current page".into() diff --git a/crates/texrra-tex-core/src/execution/paragraph.rs b/crates/texrra-tex-core/src/execution/paragraph.rs index 28a47b8..723a614 100644 --- a/crates/texrra-tex-core/src/execution/paragraph.rs +++ b/crates/texrra-tex-core/src/execution/paragraph.rs @@ -53,6 +53,7 @@ pub enum TextNode { }, Glue(Glue), NamedGlue(Glue, Parameter), + Leaders(LeaderGlue), Kern { width: i32, explicit: bool, @@ -365,6 +366,7 @@ fn discardable(n: &TextNode) -> bool { n, TextNode::Glue(_) | TextNode::NamedGlue(_, _) + | TextNode::Leaders(_) | TextNode::Kern { .. } | TextNode::MathBoundary { .. } | TextNode::Penalty(_) @@ -375,7 +377,9 @@ fn width(n: &TextNode) -> i64 { TextNode::Glyph { glyph, .. } | TextNode::Box(glyph) | TextNode::MathChar(glyph) => { glyph.width } - TextNode::Glue(g) | TextNode::NamedGlue(g, _) => g.width as i64, + TextNode::Glue(g) + | TextNode::NamedGlue(g, _) + | TextNode::Leaders(LeaderGlue { glue: g, .. }) => g.width as i64, TextNode::Rule(r) => r.dimensions().0, TextNode::Output(node) => node.dimensions().map_or(0, |(width, _, _)| width), TextNode::Kern { width: n, .. } @@ -516,7 +520,10 @@ fn metrics(nodes: &[TextNode], left: Glue, right: Glue) -> (i64, [i64; 4], i64) let mut shrink = 0; for g in std::iter::once(left) .chain(nodes.iter().filter_map(|n| { - if let TextNode::Glue(g) | TextNode::NamedGlue(g, _) = n { + if let TextNode::Glue(g) + | TextNode::NamedGlue(g, _) + | TextNode::Leaders(LeaderGlue { glue: g, .. }) = n + { Some(*g) } else { None @@ -530,7 +537,12 @@ fn metrics(nodes: &[TextNode], left: Glue, right: Glue) -> (i64, [i64; 4], i64) } natural += nodes .iter() - .filter(|n| !matches!(n, TextNode::Glue(_) | TextNode::NamedGlue(_, _))) + .filter(|n| { + !matches!( + n, + TextNode::Glue(_) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_) + ) + }) .map(width) .sum::(); (natural, stretch, shrink) @@ -968,7 +980,10 @@ fn pre_display_line_size( | TextNode::Indent(_) | TextNode::Rule(_) ); - if let TextNode::Glue(g) | TextNode::NamedGlue(g, _) = n { + if let TextNode::Glue(g) + | TextNode::NamedGlue(g, _) + | TextNode::Leaders(LeaderGlue { glue: g, .. }) = n + { let f = if set.sign > 0 { g.stretch } else { g.shrink }; if set.sign != 0 && f.order == set.order && f.amount != 0 { v = 1073741823; @@ -996,10 +1011,12 @@ pub(super) fn finish( cache: Option<&LineBreakCache>, ) -> Result { b.finish_text(true)?; - if b.nodes - .last() - .is_some_and(|n| matches!(n, TextNode::Glue(_) | TextNode::NamedGlue(_, _))) - { + if b.nodes.last().is_some_and(|n| { + matches!( + n, + TextNode::Glue(_) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_) + ) + }) { b.nodes.pop(); } for n in &b.nodes { @@ -1020,7 +1037,9 @@ pub(super) fn finish( .collect(); let shape = state.paragraph_shape(); for n in &b.nodes { - if let TextNode::Glue(g) | TextNode::NamedGlue(g, _) = n + if let TextNode::Glue(g) + | TextNode::NamedGlue(g, _) + | TextNode::Leaders(LeaderGlue { glue: g, .. }) = n && g.shrink.order != 0 && g.shrink.amount != 0 { @@ -1260,7 +1279,12 @@ fn add_hyphens( .is_some_and(|c| state.case_code(super::CaseCode::Lower, c) != 0), _ => true, }) - .is_some_and(|n| matches!(n, TextNode::Glue(_) | TextNode::NamedGlue(_, _))) + .is_some_and(|n| { + matches!( + n, + TextNode::Glue(_) | TextNode::NamedGlue(_, _) | TextNode::Leaders(_) + ) + }) && !word.is_empty() && (state.parameter(Parameter::Uchyph).width() > 0 || word @@ -1290,6 +1314,7 @@ fn add_hyphens( | TextNode::Output(_) | TextNode::Glue(_) | TextNode::NamedGlue(_, _) + | TextNode::Leaders(_) | TextNode::Penalty(_) | TextNode::Kern { explicit: true, .. } ) diff --git a/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs b/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs index 282614b..7152482 100644 --- a/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs +++ b/crates/texrra-tex-core/src/execution/paragraph/break_cache.rs @@ -143,7 +143,9 @@ impl BreakNode { | TextNode::Output(_) | TextNode::MathChar(_) | TextNode::Indent(_) => Self::Content(width(node)), - TextNode::Glue(glue) | TextNode::NamedGlue(glue, _) => Self::Glue(*glue), + TextNode::Glue(glue) + | TextNode::NamedGlue(glue, _) + | TextNode::Leaders(LeaderGlue { glue, .. }) => Self::Glue(*glue), TextNode::Kern { width, explicit } => Self::Kern { width: *width, explicit: *explicit, diff --git a/crates/texrra-tex-core/src/execution/paragraph_trace.rs b/crates/texrra-tex-core/src/execution/paragraph_trace.rs index 958a79e..e8c328f 100644 --- a/crates/texrra-tex-core/src/execution/paragraph_trace.rs +++ b/crates/texrra-tex-core/src/execution/paragraph_trace.rs @@ -212,7 +212,9 @@ impl<'a> Tracer<'a> { | TextNode::Mark(_) | TextNode::Output(_) => out.push_str("[]"), TextNode::Rule(_) => out.push('|'), - TextNode::Glue(g) | TextNode::NamedGlue(g, _) => { + TextNode::Glue(g) + | TextNode::NamedGlue(g, _) + | TextNode::Leaders(LeaderGlue { glue: g, .. }) => { if !g.canonical_zero { out.push(' '); } diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 668b869..55c3d8a 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -109,6 +109,7 @@ pub enum Primitive { Pdfendlink, Pdfdest, Pdfcatalog, + Pdfoutline, Pdfinfo, Pdfsetmatrix, Pdfrestore, @@ -162,6 +163,9 @@ pub enum Primitive { Indent, Noindent, Hskip, + Leaders, + Cleaders, + Xleaders, Hfil, Hfill, Hss, @@ -862,6 +866,7 @@ impl Default for State { ("pdfendlink", Pdfendlink), ("pdfdest", Pdfdest), ("pdfcatalog", Pdfcatalog), + ("pdfoutline", Pdfoutline), ("pdfinfo", Pdfinfo), ("pdfsetmatrix", Pdfsetmatrix), ("pdfrestore", Pdfrestore), @@ -870,6 +875,9 @@ impl Default for State { ("indent", Indent), ("noindent", Noindent), ("hskip", Hskip), + ("leaders", Leaders), + ("cleaders", Cleaders), + ("xleaders", Xleaders), ("hfil", Hfil), ("hfill", Hfill), ("hss", Hss), diff --git a/crates/texrra-tex-core/src/execution/statistics.rs b/crates/texrra-tex-core/src/execution/statistics.rs index 8a7ee5b..a88c907 100644 --- a/crates/texrra-tex-core/src/execution/statistics.rs +++ b/crates/texrra-tex-core/src/execution/statistics.rs @@ -194,6 +194,12 @@ impl Collector { self.material(o).geometry_items += g.items.len(); } } + fn leader_pattern(&mut self, leader: &LeaderGlue, o: Ownership) { + match &leader.pattern { + LeaderPattern::Box(b) => self.native_box(b, o), + LeaderPattern::Rule(_) => self.material(o).geometry_items += 1, + } + } pub fn text(&mut self, nodes: &[TextNode], o: Ownership) { self.material(o).horizontal_nodes += nodes.len(); for n in nodes { @@ -213,6 +219,7 @@ impl Collector { TextNode::Adjustment(value) => self.vertical(&value.nodes, o), TextNode::Insertion(n) => self.vertical(&n.nodes, o), TextNode::Output(v) => self.output(v), + TextNode::Leaders(leader) => self.leader_pattern(leader, o), _ => {} } } @@ -229,6 +236,7 @@ impl Collector { NativeVerticalNode::Mark(m) => self.shared_tokens(&m.tokens), NativeVerticalNode::Insertion(n) => self.vertical(&n.nodes, o), NativeVerticalNode::Output(v) => self.output(v), + NativeVerticalNode::Leaders(leader) => self.leader_pattern(leader, o), _ => {} } } @@ -264,6 +272,7 @@ impl Collector { MathNode::Adjustment(value) => self.vertical(&value.nodes, o), MathNode::Insertion(n) => self.vertical(&n.nodes, o), MathNode::Output(v) => self.output(v), + MathNode::Leaders(leader) => self.leader_pattern(leader, o), _ => {} } } @@ -292,6 +301,9 @@ impl Collector { for n in nodes { match n { D::Box(b) => self.diagnostics(&b.nodes, o), + D::Leaders { pattern, .. } => { + self.diagnostics(std::slice::from_ref(pattern.as_ref()), o) + } D::Discretionary { pre, post, .. } => { self.diagnostics(pre, o); self.diagnostics(post, o); diff --git a/crates/texrra-tex-core/src/execution/vertical_break.rs b/crates/texrra-tex-core/src/execution/vertical_break.rs index 9fff17e..51bee83 100644 --- a/crates/texrra-tex-core/src/execution/vertical_break.rs +++ b/crates/texrra-tex-core/src/execution/vertical_break.rs @@ -41,7 +41,11 @@ pub(super) fn find_break( depth = d; None } - Some(NativeVerticalNode::Glue(_) | NativeVerticalNode::NamedGlue(_, _)) => (i > 0 + Some( + NativeVerticalNode::Glue(_) + | NativeVerticalNode::NamedGlue(_, _) + | NativeVerticalNode::Leaders(_), + ) => (i > 0 && matches!( nodes[i - 1], NativeVerticalNode::Box(_) @@ -54,7 +58,11 @@ pub(super) fn find_break( .then_some(0), Some(NativeVerticalNode::Kern(_) | NativeVerticalNode::ImplicitKern(_)) => matches!( nodes.get(i + 1), - Some(NativeVerticalNode::Glue(_) | NativeVerticalNode::NamedGlue(_, _)) + Some( + NativeVerticalNode::Glue(_) + | NativeVerticalNode::NamedGlue(_, _) + | NativeVerticalNode::Leaders(_) + ) ) .then_some(0), Some(NativeVerticalNode::Penalty(p)) => Some(*p), @@ -98,7 +106,11 @@ pub(super) fn find_break( } } match node { - Some(NativeVerticalNode::Glue(g) | NativeVerticalNode::NamedGlue(g, _)) => { + Some( + NativeVerticalNode::Glue(g) + | NativeVerticalNode::NamedGlue(g, _) + | NativeVerticalNode::Leaders(LeaderGlue { glue: g, .. }), + ) => { if g.shrink.order != 0 && g.shrink.amount != 0 { return Err("infinite glue shrinkage found in native box being split".into()); } diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index e570bcc..651bf60 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -14,7 +14,7 @@ use rusttype::Font; use crate::cmr10::Cmr10Metrics; use crate::pdf_device::{ - catalog::{CatalogAction, CatalogTarget}, + catalog::{CatalogAction, CatalogTarget, PdfOutline}, links::DestinationId, }; use crate::render::{DisplayItem, DisplayList, FontFace}; @@ -1520,12 +1520,12 @@ fn write_catalog_action( action: &CatalogAction, page_ids: &[usize], destinations: &mut BTreeMap, - numbers: &BTreeMap, + numbers: &mut BTreeMap, + threads: &mut BTreeMap, usize>, objects: &mut Vec>, diagnostics: &mut Vec, -) -> (usize, Option) { +) -> usize { let mut output = b"<< ".to_vec(); - let mut threads = None; match action { CatalogAction::User(object) => output.clone_from(object), CatalogAction::GoTo { @@ -1554,7 +1554,7 @@ fn write_catalog_action( output.extend_from_slice(pdf_text(name).as_bytes()); } CatalogTarget::Destination(DestinationId::Number(number)) => { - let id = numbers.get(number).copied().unwrap_or_else(|| { + let id = numbers.entry(*number).or_insert_with(|| { diagnostics.push(format!( "destination num{number} has been referenced but does not exist, replaced by a fixed one" )); @@ -1596,21 +1596,20 @@ fn write_catalog_action( DestinationId::Name(name) => (name.clone(), format!("name{{{name}}}")), DestinationId::Number(number) => (number.to_string(), format!("num{number}")), }; - diagnostics.push(format!( - "thread destination {identifier} has been referenced but does not exist, replaced by a fixed one" - )); - // There are no thread definitions yet. As pdfTeX does for an - // undefined thread, link its single empty bead to the first page. - let thread = objects.len() + 1; - let bead = thread + 1; - objects.push(format!("<< /I << /Title {} >> /F {bead} 0 R >>", pdf_text(&title)).into_bytes()); - objects.push(format!( - "<< /T {thread} 0 R /V {bead} 0 R /N {bead} 0 R /P {} 0 R /R [0 0 0 0] >>", - page_ids[0] - ).into_bytes()); - objects.push(format!("[{thread} 0 R]").into_bytes()); - local_id = Some(thread); - threads = Some(objects.len()); + local_id = Some(*threads.entry(destination.clone()).or_insert_with(|| { + diagnostics.push(format!( + "thread destination {identifier} has been referenced but does not exist, replaced by a fixed one" + )); + // Link the missing thread's single empty bead to the first page. + let thread = objects.len() + 1; + let bead = thread + 1; + objects.push(format!("<< /I << /Title {} >> /F {bead} 0 R >>", pdf_text(&title)).into_bytes()); + objects.push(format!( + "<< /T {thread} 0 R /V {bead} 0 R /N {bead} 0 R /P {} 0 R /R [0 0 0 0] >>", + page_ids[0] + ).into_bytes()); + thread + })); } output.extend_from_slice(b"/S /Thread /D "); match destination { @@ -1627,7 +1626,101 @@ fn write_catalog_action( } } objects.push(output); - (objects.len(), threads) + objects.len() +} + +#[derive(Clone, Default)] +struct OutlinePosition { + parent: usize, + first: Option, + last: Option, + previous: Option, + next: Option, + visible_children: usize, +} + +fn write_pdf_outlines( + outlines: &[PdfOutline>], + action_ids: &[usize], + objects: &mut Vec>, +) -> usize { + let mut positions = vec![OutlinePosition::default(); outlines.len() + 1]; + let mut parents = vec![(0, usize::MAX)]; + for (offset, outline) in outlines.iter().enumerate() { + let index = offset + 1; + let (parent, remaining) = parents.last_mut().unwrap(); + let parent = *parent; + *remaining -= 1; + positions[parent].first.get_or_insert(index); + if let Some(previous) = positions[parent].last.replace(index) { + positions[previous].next = Some(index); + positions[index].previous = Some(previous); + } + positions[index].parent = parent; + if outline.count != 0 { + parents.push((index, outline.count.unsigned_abs() as usize)); + } else { + while parents.last().is_some_and(|(_, remaining)| *remaining == 0) { + parents.pop(); + } + } + } + + for (offset, outline) in outlines.iter().enumerate().rev() { + let position = &positions[offset + 1]; + let visible = if outline.count > 0 { position.visible_children } else { 0 }; + let parent = position.parent; + positions[parent].visible_children += visible + 1; + } + + let root_id = objects.len() + 1; + objects.resize_with(root_id + outlines.len(), Vec::new); + let root = &positions[0]; + // pdfTeX uses the current sibling at the end of input as the root's Last. + let last = positions[parents.last().unwrap().0].last.map_or(0, |index| root_id + index); + objects[root_id - 1] = format!( + "<< /Type /Outlines /First {} 0 R /Last {last} 0 R /Count {} >>", + root_id + root.first.unwrap(), + root.visible_children, + ) + .into_bytes(); + + for (offset, (outline, action_id)) in outlines.iter().zip(action_ids).enumerate() { + let position = &positions[offset + 1]; + let mut title = Vec::with_capacity(outline.title.len() + 2); + title.push(b'('); + title.extend_from_slice(&outline.title); + title.push(b')'); + objects.push(title); + let mut entry = format!( + "<< /Title {} 0 R /A {action_id} 0 R /Parent {} 0 R", + objects.len(), + root_id + position.parent, + ) + .into_bytes(); + for (key, index) in [ + ("Prev", position.previous), + ("Next", position.next), + ("First", position.first), + ("Last", position.last), + ] { + if let Some(index) = index { + write!(&mut entry, " /{key} {} 0 R", root_id + index).unwrap(); + } + } + if position.visible_children != 0 { + let sign = if outline.count < 0 { "-" } else { "" }; + write!(&mut entry, " /Count {sign}{}", position.visible_children).unwrap(); + } + if !outline.attributes.is_empty() { + entry.push(b'\n'); + entry.extend_from_slice(&outline.attributes); + entry.push(b'\n'); + } + entry.extend_from_slice(b" >>"); + objects[root_id + offset] = entry; + } + root_id } fn write_pdf( @@ -2209,13 +2302,29 @@ fn write_pdf( catalog.push_str(&format!(" /Outlines {root_id} 0 R")); } let extra = unicode.and_then(|options| options.catalog); + let mut threads = BTreeMap::new(); let action = extra.and_then(|extra| extra.open_action.as_ref()).map(|action| { write_catalog_action( - action, &page_ids, &mut destinations, &numbers, &mut objects, diagnostics, + action, &page_ids, &mut destinations, &mut numbers, &mut threads, &mut objects, + diagnostics, ) }); - if let Some((_, Some(threads))) = action { - catalog.push_str(&format!(" /Threads {threads} 0 R")); + if let Some(extra) = extra.filter(|extra| !extra.outlines.is_empty()) { + let action_ids: Vec<_> = extra.outlines.iter().map(|outline| { + write_catalog_action( + &outline.action, &page_ids, &mut destinations, &mut numbers, &mut threads, + &mut objects, diagnostics, + ) + }).collect(); + let outlines = write_pdf_outlines(&extra.outlines, &action_ids, &mut objects); + catalog.push_str(&format!(" /Outlines {outlines} 0 R")); + } + if !threads.is_empty() { + let mut ids: Vec<_> = threads.into_values().collect(); + ids.sort_unstable_by(|left, right| right.cmp(left)); + let references: Vec<_> = ids.iter().map(|id| format!("{id} 0 R")).collect(); + objects.push(format!("[{}]", references.join(" ")).into_bytes()); + catalog.push_str(&format!(" /Threads {} 0 R", objects.len())); } if !destinations.is_empty() { let mut entries = Vec::with_capacity(destinations.len()); @@ -2236,7 +2345,7 @@ fn write_pdf( catalog.extend_from_slice(&extra.entries); catalog.push(b'\n'); } - if let Some((id, _)) = action { + if let Some(id) = action { write!(&mut catalog, " /OpenAction {id} 0 R").unwrap(); } } diff --git a/crates/texrra-tex-core/src/pdf_device/catalog.rs b/crates/texrra-tex-core/src/pdf_device/catalog.rs index 6168627..a61df64 100644 --- a/crates/texrra-tex-core/src/pdf_device/catalog.rs +++ b/crates/texrra-tex-core/src/pdf_device/catalog.rs @@ -5,6 +5,15 @@ use super::links::DestinationId; pub struct PdfCatalog { pub(crate) entries: Vec, pub(crate) open_action: Option, + pub(crate) outlines: Vec>>, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub(crate) struct PdfOutline { + pub(crate) title: Vec, + pub(crate) attributes: A, + pub(crate) action: CatalogAction, + pub(crate) count: i32, } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] @@ -22,6 +31,32 @@ pub(crate) enum CatalogAction { }, } +impl CatalogAction { + pub(crate) fn payload_len(&self) -> usize { + fn destination_len(destination: &DestinationId) -> usize { + match destination { + DestinationId::Name(name) => name.len(), + DestinationId::Number(_) => 0, + } + } + + match self { + Self::User(bytes) => bytes.len(), + Self::GoTo { target, file, structure, .. } => { + let target_len = match target { + CatalogTarget::Destination(destination) => destination_len(destination), + CatalogTarget::Page { view, .. } => view.len(), + }; + target_len + file.as_ref().map_or(0, Vec::len) + + structure.as_ref().map_or(0, Vec::len) + } + Self::Thread { destination, file } => { + destination_len(destination) + file.as_ref().map_or(0, Vec::len) + } + } + } +} + #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub(crate) enum CatalogTarget { Destination(DestinationId), diff --git a/crates/texrra-tex-core/tests/execution_fractions.rs b/crates/texrra-tex-core/tests/execution_fractions.rs index 079d4cd..28f4aab 100644 --- a/crates/texrra-tex-core/tests/execution_fractions.rs +++ b/crates/texrra-tex-core/tests/execution_fractions.rs @@ -246,7 +246,7 @@ fn genuine_fraction_primitives_and_retained_boxes_survive_format_roundtrip() { let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); let payload: serde_json::Value = serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); - assert_eq!(payload["schema"], 25); + assert_eq!(payload["schema"], 27); let state = State::initex().with_etex(); let loaded = FormatImage::decode(&bytes) .unwrap() diff --git a/crates/texrra-tex-core/tests/execution_leaders.rs b/crates/texrra-tex-core/tests/execution_leaders.rs new file mode 100644 index 0000000..b28745f --- /dev/null +++ b/crates/texrra-tex-core/tests/execution_leaders.rs @@ -0,0 +1,178 @@ +//! Reference material copied from the independent pdfTeX DVI run. +use serde_json::Value; +use std::{fs, io::Write, path::PathBuf}; +use texrra_tex_core::{execution::*, math_engine_tex::MathItem}; + +struct Host { + cwd: PathBuf, + stream: Option, +} + +impl SourceProvider for Host { + fn read(&mut self, name: &str, _: &str) -> Result { + let path = self.cwd.join(name); + fs::read(&path) + .map(|data| SourceFile { + name: path.display().to_string(), + data, + }) + .map_err(|err| err.to_string()) + } + fn open_out(&mut self, stream: u8, name: &str, _: &str) -> Result { + assert_eq!(stream, 7); + let path = self.cwd.join(name); + self.stream = Some(fs::File::create(&path).map_err(|err| err.to_string())?); + Ok(path.display().to_string()) + } + fn write_out(&mut self, stream: u8, text: &str) -> Result<(), String> { + assert_eq!(stream, 7); + self.stream + .as_mut() + .unwrap() + .write_all(text.as_bytes()) + .map_err(|err| err.to_string()) + } + fn close_out(&mut self, stream: u8) -> Result<(), String> { + assert_eq!(stream, 7); + self.stream.take(); + Ok(()) + } +} + +fn execute(source: &[u8], host: &mut impl SourceProvider) -> Result { + Executor::new(State::initex().with_etex(), Limits::default()) + .with_native_pages() + .run( + SourceFile { + name: "placement.tex".into(), + data: source.to_vec(), + }, + host, + ) +} + +#[test] +fn owned_leaders_match_three_real_dvi_pages_and_suppress_repeated_writes() { + let cwd = std::env::temp_dir().join(format!("texrra-leader-fixture-{}", std::process::id())); + fs::create_dir(&cwd).unwrap(); + let mut host = Host { + cwd: cwd.clone(), + stream: None, + }; + let result = execute(include_bytes!("fixtures/leaders/placement.tex"), &mut host).unwrap(); + assert_eq!(fs::read(cwd.join("effects.aux")).unwrap(), b"OUTSIDE\n"); + let messages: Vec<_> = result + .events + .iter() + .filter_map(|event| match event { + Event::Message { text, .. } => Some(text.as_str()), + _ => None, + }) + .collect(); + assert_eq!(messages, ["BAND=[24.0pt,3.0pt,1.0pt]", "TAIL=[11,13.0pt]"]); + + let expected: Vec = + serde_json::from_str(include_str!("fixtures/leaders/reference-layout.json")).unwrap(); + let pages: Vec<_> = result + .events + .iter() + .filter_map(|event| match event { + Event::Shipout(page) => Some(&page.box_node), + _ => None, + }) + .collect(); + assert_eq!(pages.len(), 3); + for (index, (page, reference)) in pages.iter().zip(expected).enumerate() { + let actual: Vec<_> = page.geometry().unwrap().items.into_iter().map(|record| { + let MathItem::Rule { width, height } = record.item else { panic!("unexpected glyph") }; + serde_json::json!({"x": record.x, "y": record.y + page.height, "width": width, "height": height}) + }).collect(); + assert_eq!( + actual, + reference["rules"].as_array().unwrap().to_owned(), + "page {}", + index + 1 + ); + } + fs::remove_dir_all(cwd).unwrap(); +} + +#[test] +fn empty_leader_becomes_plain_glue_and_an_axis_mismatch_is_rejected() { + let result = execute( + br"\catcode123=1\catcode125=2\setbox0=\hbox{\leaders\box9\hskip3pt}\end", + &mut NoFiles, + ) + .unwrap(); + let BoxContent::Horizontal(nodes) = &result.state.box_register(0).unwrap().content else { + panic!("horizontal box") + }; + assert!(matches!(nodes.as_slice(), [TextNode::Glue(glue)] if glue.width == 3 * 65_536)); + let error = execute( + br"\catcode123=1\catcode125=2\setbox0=\hbox{\leaders\hbox{}\vskip3pt}\end", + &mut NoFiles, + ) + .unwrap_err(); + assert!( + error + .message + .contains("leaders not followed by proper glue") + ); +} + +#[test] +fn repeated_device_effects_follow_the_paint_order_and_obey_placement_budget() { + let color = br"\pdfoutput=1\pdfcompresslevel=0\pdfpkresolution=600\catcode123=1\catcode125=2 +\shipout\hbox{\cleaders\hbox to2pt{\pdfcolorstack0 push{1 0 0 rg}\vrule width1pt height2pt\pdfcolorstack0 pop\hss}\hskip6pt} +\end"; + let e = execute(color, &mut NoFiles).unwrap(); + let pages = e.shipout_display_lists().unwrap(); + let pdf = + texrra_tex_core::pdf::shipout_lists_to_native_pdf(&pages, e.state.pdf_final_options()) + .unwrap(); + let pdf = String::from_utf8_lossy(&pdf); + assert_eq!(pdf.matches("1 0 0 rg").count(), 3); + assert_eq!(pdf.matches("0 g 0 G").count(), 3); + + for leader in [ + r"\leaders\hbox to1sp{}\hskip100000sp".to_owned(), + format!( + r"\leaders\hbox to5pt{{{}\hss}}\hskip50pt", + r"\kern1sp".repeat(20) + ), + ] { + let failed = Executor::new( + State::initex().with_etex(), + Limits { + tokens: 128, + ..Limits::default() + }, + ) + .with_native_pages() + .run_detailed( + SourceFile { + name: "bounded-leaders.tex".into(), + data: format!( + r"\catcode123=1\catcode125=2 +\shipout\hbox{{{leader}\write0{{FAIL}}}}\end" + ) + .into_bytes(), + }, + &mut NoFiles, + ) + .unwrap_err(); + assert!( + failed + .error + .message + .contains("native leader placement or material capacity exceeded") + ); + assert!( + !failed + .evidence + .events + .iter() + .any(|event| matches!(event, Event::Shipout(_))) + ); + } +} diff --git a/crates/texrra-tex-core/tests/execution_pdf_catalog.rs b/crates/texrra-tex-core/tests/execution_pdf_catalog.rs index 5e522b5..012224a 100644 --- a/crates/texrra-tex-core/tests/execution_pdf_catalog.rs +++ b/crates/texrra-tex-core/tests/execution_pdf_catalog.rs @@ -461,3 +461,157 @@ fn pdf_info_ignores_dvi_and_does_not_freeze_pdf_settings() { assert_eq!(reference.version, "1.5"); assert_eq!(native.version, reference.version); } + +#[test] +fn outline_tree_keeps_actions_titles_and_visible_counts() { + let (reference, native, diagnostics) = pair( + r"\pdfoutline attr{/F 2/C [1 0 0]} goto name{one} count -2{Root (closed)} + \pdfoutline goto num 7 count 1 {First child (open)} + \pdfoutline goto page 2 {/FitH 120} {Nested (one)} + \pdfoutline goto name{two} {\detokenize{\376\377\000R\000u\000s\000t}} + \pdfoutline user{<< /S /URI /URI (https://example.org/) >>}{External} + \shipout\hbox{\pdfdest name{one} fit\pdfdest num 7 fit\vrule width8pt height6pt} + \shipout\hbox{\pdfdest name{two} fit\vrule width8pt height6pt}", + ); + assert!(diagnostics.is_empty(), "{diagnostics:?}"); + for pdf in [&reference, &native] { + let catalog = pdf.catalog().unwrap(); + let outline_id = catalog.get(b"Outlines").unwrap().as_reference().unwrap(); + let root = get(pdf, catalog, b"Outlines").as_dict().unwrap(); + assert_eq!(root.get(b"Type").unwrap().as_name().unwrap(), b"Outlines"); + assert_eq!(root.get(b"Count").unwrap().as_i64().unwrap(), 2); + let first_id = root.get(b"First").unwrap().as_reference().unwrap(); + let last_id = root.get(b"Last").unwrap().as_reference().unwrap(); + let first = get(pdf, root, b"First").as_dict().unwrap(); + let last = get(pdf, root, b"Last").as_dict().unwrap(); + assert_eq!(first.get(b"Parent").unwrap().as_reference().unwrap(), outline_id); + assert_eq!(last.get(b"Parent").unwrap().as_reference().unwrap(), outline_id); + assert_eq!(first.get(b"Next").unwrap().as_reference().unwrap(), last_id); + assert_eq!(last.get(b"Prev").unwrap().as_reference().unwrap(), first_id); + assert!(first.get(b"Prev").is_err() && last.get(b"Next").is_err()); + assert_eq!(first.get(b"Count").unwrap().as_i64().unwrap(), -3); + assert_eq!(first.get(b"F").unwrap().as_i64().unwrap(), 2); + assert_eq!( + first.get(b"C").unwrap().as_array().unwrap().iter() + .map(|v| v.as_i64().unwrap()).collect::>(), + [1, 0, 0], + ); + assert_eq!(get(pdf, first, b"Title").as_str().unwrap(), b"Root (closed)"); + let first_action = get(pdf, first, b"A").as_dict().unwrap(); + assert_eq!(first_action.get(b"S").unwrap().as_name().unwrap(), b"GoTo"); + assert_eq!(first_action.get(b"D").unwrap().as_str().unwrap(), b"one"); + let child = get(pdf, first, b"First").as_dict().unwrap(); + let last_child = get(pdf, first, b"Last").as_dict().unwrap(); + assert_eq!(child.get(b"Parent").unwrap().as_reference().unwrap(), first_id); + assert_eq!(last_child.get(b"Parent").unwrap().as_reference().unwrap(), first_id); + assert_eq!( + child.get(b"Next").unwrap().as_reference().unwrap(), + first.get(b"Last").unwrap().as_reference().unwrap(), + ); + assert_eq!( + last_child.get(b"Prev").unwrap().as_reference().unwrap(), + first.get(b"First").unwrap().as_reference().unwrap(), + ); + assert_eq!(child.get(b"Count").unwrap().as_i64().unwrap(), 1); + assert_eq!(get(pdf, child, b"Title").as_str().unwrap(), b"First child (open)"); + let child_action = get(pdf, child, b"A").as_dict().unwrap(); + let number = get(pdf, child_action, b"D").as_array().unwrap(); + assert_eq!(number[0].as_reference().unwrap(), pdf.get_pages()[&1]); + assert_eq!(number[1].as_name().unwrap(), b"Fit"); + assert_eq!( + child.get(b"First").unwrap().as_reference().unwrap(), + child.get(b"Last").unwrap().as_reference().unwrap(), + ); + let nested = get(pdf, child, b"First").as_dict().unwrap(); + assert_eq!( + nested.get(b"Parent").unwrap().as_reference().unwrap(), + first.get(b"First").unwrap().as_reference().unwrap(), + ); + assert_eq!(get(pdf, nested, b"Title").as_str().unwrap(), b"Nested (one)"); + let nested_action = get(pdf, nested, b"A").as_dict().unwrap(); + let page = nested_action.get(b"D").unwrap().as_array().unwrap(); + assert_eq!(page[0].as_reference().unwrap(), pdf.get_pages()[&2]); + assert_eq!(page[1].as_name().unwrap(), b"FitH"); + assert_eq!(page[2].as_i64().unwrap(), 120); + assert_eq!( + get(pdf, last_child, b"Title").as_str().unwrap(), + b"\xfe\xff\0R\0u\0s\0t", + ); + let last_child_action = get(pdf, last_child, b"A").as_dict().unwrap(); + assert_eq!(last_child_action.get(b"D").unwrap().as_str().unwrap(), b"two"); + assert_eq!(get(pdf, last, b"Title").as_str().unwrap(), b"External"); + let last_action = get(pdf, last, b"A").as_dict().unwrap(); + assert_eq!(last_action.get(b"S").unwrap().as_name().unwrap(), b"URI"); + assert_eq!(last_action.get(b"URI").unwrap().as_str().unwrap(), b"https://example.org/"); + } +} + +#[test] +fn outline_uses_the_scan_time_title_and_final_attribute_printing() { + let (reference, native, _) = pair(&format!( + r"\def\A{{old}} + \pdfoutline attr{{/Note (\A:\noexpand\literal)}} user{{<< /S /Named /N /NextPage >>}} + {{\A:\noexpand\literal}}\def\A{{new}}\escapechar=33 {PAGE}", + )); + for pdf in [&reference, &native] { + let root = get(pdf, pdf.catalog().unwrap(), b"Outlines").as_dict().unwrap(); + let first = get(pdf, root, b"First").as_dict().unwrap(); + assert_eq!(get(pdf, first, b"Title").as_str().unwrap(), b"old:literal "); + assert_eq!(first.get(b"Note").unwrap().as_str().unwrap(), b"old:!literal "); + } +} + +#[test] +fn incomplete_outline_child_list_uses_actual_entries_and_cursor() { + let (reference, native, _) = pair(&format!( + r"\pdfoutline user{{<< /S /Named /N /NextPage >>}} count 3{{}} + \pdfoutline user{{<< /S /Named /N /NextPage >>}}{{child}} {PAGE}", + )); + for pdf in [&reference, &native] { + let root = get(pdf, pdf.catalog().unwrap(), b"Outlines").as_dict().unwrap(); + let first = get(pdf, root, b"First").as_dict().unwrap(); + assert_eq!(root.get(b"Count").unwrap().as_i64().unwrap(), 2); + assert_eq!(first.get(b"Count").unwrap().as_i64().unwrap(), 1); + assert_eq!( + first.get(b"First").unwrap().as_reference().unwrap(), + root.get(b"Last").unwrap().as_reference().unwrap(), + ); + assert_eq!( + first.get(b"First").unwrap().as_reference().unwrap(), + first.get(b"Last").unwrap().as_reference().unwrap(), + ); + assert_eq!(get(pdf, first, b"Title").as_str().unwrap(), b""); + } +} + +#[test] +fn outline_rejects_dvi_and_missing_action_before_creating_an_entry() { + for (input, expected) in [ + (r"\pdfoutput=0 \pdfoutline goto name{x}{title}", "DVI mode"), + (r"\pdfoutline {title}", "action type missing"), + (r"\pdfoutline goto num 0 {title}", "must be positive"), + ] { + let error = run_native(&format!("{SETUP}{input}{PAGE}\\end")).unwrap_err(); + assert!(error.message.contains(expected), "{}", error.message); + } +} + +#[test] +fn outline_and_open_action_share_a_missing_numeric_destination() { + let (reference, native, messages) = pair(&format!( + r"\pdfcatalog{{}} openaction goto num 23 + \pdfoutline goto num 23 {{same missing destination}} {PAGE}", + )); + for pdf in [&reference, &native] { + let root = get(pdf, pdf.catalog().unwrap(), b"Outlines").as_dict().unwrap(); + let first = get(pdf, root, b"First").as_dict().unwrap(); + let bookmark_action = get(pdf, first, b"A").as_dict().unwrap(); + assert_eq!( + bookmark_action.get(b"D").unwrap().as_reference().unwrap(), + action(pdf).get(b"D").unwrap().as_reference().unwrap(), + ); + let destination = get(pdf, bookmark_action, b"D").as_array().unwrap(); + assert_eq!(destination[0].as_reference().unwrap(), pdf.get_pages()[&1]); + } + assert_eq!(messages.iter().filter(|text| text.contains("num23")).count(), 1); +} diff --git a/crates/texrra-tex-core/tests/execution_pdf_unicode.rs b/crates/texrra-tex-core/tests/execution_pdf_unicode.rs index 73682a7..91d0b3d 100644 --- a/crates/texrra-tex-core/tests/execution_pdf_unicode.rs +++ b/crates/texrra-tex-core/tests/execution_pdf_unicode.rs @@ -334,7 +334,7 @@ fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums() let envelope: serde_json::Value = serde_json::from_slice(&encoded).unwrap(); let original: serde_json::Value = serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); - assert_eq!(original["schema"], 25); + assert_eq!(original["schema"], 27); for (schema, expected) in [ (1, "incompatible native format"), (2, "incompatible native format"), @@ -360,7 +360,9 @@ fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums() (22, "incompatible native format"), (23, "incompatible native format"), (24, "incompatible native format"), - (25, "glyph_unicode"), + (25, "incompatible native format"), + (26, "incompatible native format"), + (27, "glyph_unicode"), ] { let mut payload = original.clone(); payload["schema"] = schema.into(); diff --git a/crates/texrra-tex-core/tests/execution_vcenter.rs b/crates/texrra-tex-core/tests/execution_vcenter.rs index e114b3d..f7d6cc6 100644 --- a/crates/texrra-tex-core/tests/execution_vcenter.rs +++ b/crates/texrra-tex-core/tests/execution_vcenter.rs @@ -164,7 +164,7 @@ fn new_format_owns_vcenter_and_boxed_math_without_reinjecting_old_meanings() { let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); let payload: serde_json::Value = serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); - assert_eq!(payload["schema"], 25); + assert_eq!(payload["schema"], 27); let executor = FormatImage::decode(&bytes) .unwrap() .new_job( diff --git a/crates/texrra-tex-core/tests/fixtures/leaders/placement.tex b/crates/texrra-tex-core/tests/fixtures/leaders/placement.tex new file mode 100644 index 0000000..d28b315 --- /dev/null +++ b/crates/texrra-tex-core/tests/fixtures/leaders/placement.tex @@ -0,0 +1,21 @@ +\pdfoutput=0 +\catcode123=1 \catcode125=2 \catcode35=6 +\immediate\openout7=effects.aux +\def\tile{\hbox to5pt{\vrule width2pt height3pt depth1pt\write7{REPEATED}\hfil}} +\def\band#1{\hbox to24pt{\kern3pt#1\tile\hfill\kern1pt}} +\setbox0=\band\leaders +\setbox1=\band\cleaders +\setbox2=\band\xleaders +\message{BAND=[\the\wd0,\the\ht0,\the\dp0]} +\setbox3=\hbox{\leaders\vrule height2pt depth1pt\hskip13pt + \message{TAIL=[\the\lastnodetype,\the\lastskip]}\write7{OUTSIDE}} +\shipout\vbox{\baselineskip0pt\lineskip0pt\lineskiplimit0pt + \box0\box1\box2\box3} +\def\vband#1{\vbox to24pt{\kern3pt#1\vbox to5pt{\hrule width2pt height2pt\vfil}\vfill\kern1pt}} +\shipout\hbox{\vband\leaders\kern2pt\vband\cleaders\kern2pt\vband\xleaders + \kern2pt\vbox{\leaders\hrule width2pt\vskip11pt}} +\setbox4=\hbox to4pt{\vrule width1pt height1pt\hfil} +\shipout\hbox{\kern1pt\leaders\copy4\hskip11.9999pt\kern2pt + \leaders\copy4\hskip-1pt\leaders\box4\hskip12pt} +\immediate\closeout7 +\end diff --git a/crates/texrra-tex-core/tests/fixtures/leaders/reference-layout.json b/crates/texrra-tex-core/tests/fixtures/leaders/reference-layout.json new file mode 100644 index 0000000..93826f7 --- /dev/null +++ b/crates/texrra-tex-core/tests/fixtures/leaders/reference-layout.json @@ -0,0 +1 @@ +[{"glyphs": [], "rules": [{"x": 327680, "y": 0, "width": 131072, "height": 262144}, {"x": 655360, "y": 0, "width": 131072, "height": 262144}, {"x": 983040, "y": 0, "width": 131072, "height": 262144}, {"x": 196613, "y": 262144, "width": 131072, "height": 262144}, {"x": 524293, "y": 262144, "width": 131072, "height": 262144}, {"x": 851973, "y": 262144, "width": 131072, "height": 262144}, {"x": 1179653, "y": 262144, "width": 131072, "height": 262144}, {"x": 196610, "y": 524288, "width": 131072, "height": 262144}, {"x": 524292, "y": 524288, "width": 131072, "height": 262144}, {"x": 851974, "y": 524288, "width": 131072, "height": 262144}, {"x": 1179656, "y": 524288, "width": 131072, "height": 262144}, {"x": 0, "y": 786432, "width": 851968, "height": 196608}], "paint_order": [["rule", 0], ["rule", 1], ["rule", 2], ["rule", 3], ["rule", 4], ["rule", 5], ["rule", 6], ["rule", 7], ["rule", 8], ["rule", 9], ["rule", 10], ["rule", 11]]}, {"glyphs": [], "rules": [{"x": 0, "y": 327680, "width": 131072, "height": 131072}, {"x": 0, "y": 655360, "width": 131072, "height": 131072}, {"x": 0, "y": 983040, "width": 131072, "height": 131072}, {"x": 262144, "y": 196613, "width": 131072, "height": 131072}, {"x": 262144, "y": 524293, "width": 131072, "height": 131072}, {"x": 262144, "y": 851973, "width": 131072, "height": 131072}, {"x": 262144, "y": 1179653, "width": 131072, "height": 131072}, {"x": 524288, "y": 196610, "width": 131072, "height": 131072}, {"x": 524288, "y": 524292, "width": 131072, "height": 131072}, {"x": 524288, "y": 851974, "width": 131072, "height": 131072}, {"x": 524288, "y": 1179656, "width": 131072, "height": 131072}, {"x": 786432, "y": 851968, "width": 131072, "height": 720896}], "paint_order": [["rule", 0], ["rule", 1], ["rule", 2], ["rule", 3], ["rule", 4], ["rule", 5], ["rule", 6], ["rule", 7], ["rule", 8], ["rule", 9], ["rule", 10], ["rule", 11]]}, {"glyphs": [], "rules": [{"x": 262144, "y": 0, "width": 65536, "height": 65536}, {"x": 524288, "y": 0, "width": 65536, "height": 65536}, {"x": 1048576, "y": 0, "width": 65536, "height": 65536}, {"x": 1310720, "y": 0, "width": 65536, "height": 65536}], "paint_order": [["rule", 0], ["rule", 1], ["rule", 2], ["rule", 3]]}] diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 8059aad..1d6208c 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -211,12 +211,24 @@ SHA-256 为 `a0c3b9929508e8bfbb8f33fe177fc662c4eca0cc7d5c41ac52503a39e337ab1b` 覆盖同步失败后原 PDF、日志、辅助文件和账本保留,以及共享会话取消、失败 恢复和发布顺序。报告 `target/p4-parallel-sync-main-reconcile/directed.log` 的 SHA-256 为 `2bb2dd465e5a7f1c94f834d305b2405a03efadb2382db5c64cdfc9b151fcfdfc`。 -上面的30次浏览器配对对应此前隔离构建,合并版仍需在固定条件下测量。 +合并版也使用原样8页 A3 和真实 schema25 格式完成两轮增量及两轮独立全量对照。 +每轮复用794348/870724步,重放61次宿主调用,只替换第7页。PDF、SVG、来源 +映射、aux 和日志通过原门禁。浏览器30次配对对应此前隔离构建,合并版仍需 +在固定条件下测量。 大规模错误报告按原 JSON 格式直接写入缓冲暂存文件,再完整同步并按新文件 发布。集成测试核对 11 种失败路径,包含原序列化字节、原有报告保护、错误 保留及暂存清理。真实 CVPR 大报告的峰值内存还需重新测量。 +### schema27 与主线兼容性 + +合并了真实重复盒及 PDF 书签布局,并保留主线的宏参数分隔符和流式失败报告。 +按483项源码和测试指纹核对的工作区回归通过1617项,零失败。日志 +`target/p3-schema27-main-reconcile/workspace.log` 的 SHA-256 为 +`561766e409640fa3d407a365b4e3e88885bcc2a7e7f9bfc49f680ad92b7370f4`。 +独立 schema27 候选已使用真实 LaTeX 格式通过七份原样 article 的21轮 PDF 及 +版面对照,合并后的优化构建将单独复验。 + ### schema25 主干验收 容量、PDF 信息和 JPEG 的合并版本已核对 479 项冻结源码。完整工作区通过