//! Owned native boxes. Packing follows tex.web hpack/vpackage, not page costs. 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 { Horizontal, Vertical, Vtop, Unset { span: u8, stretch: Flex, shrink: Flex, }, } impl BoxKind { pub fn is_unset(self) -> bool { matches!(self, Self::Unset { .. }) } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum PackSpec { Natural, To(i32), Spread(i32), } #[derive( Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, )] pub struct GlueSetting { pub sign: i8, pub order: u8, pub numerator: i64, pub denominator: i64, } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum BoxContent { Horizontal(Vec), Vertical(Vec), } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct NativeBox { pub kind: BoxKind, /// Actual e-TeX dlist subtype of a display math hbox. pub display: bool, pub width: i64, /// TeX shift_amount: horizontal on a vertical list, vertical on a hlist. pub shift: i64, pub height: i64, pub depth: i64, pub content: BoxContent, /// Original horizontal semantics, retained before paint-time glue setting. pub diagnostic: Vec, pub setting: GlueSetting, pub badness: i32, pub diagnostic_eligible: bool, pub excess: i64, pub span: Span, } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum NativeVerticalNode { Box(Box), Line(Box), Glue(Glue), NamedGlue(Glue, Parameter), Leaders(LeaderGlue), Kern(i32), /// A normal (engine-generated) kern, distinct from an explicit user kern. ImplicitKern(i32), Penalty(i32), Rule(NativeRule), Mark(NativeMark), Insertion(NativeInsertion), Output(OutputNode), } impl NativeVerticalNode { pub(super) fn node_type(&self) -> i32 { match self { Self::Box(b) | Self::Line(b) => { if b.kind.is_unset() { 14 } else if b.kind == BoxKind::Horizontal { 1 } else { 2 } } Self::Rule(_) => 3, Self::Insertion(_) => 4, Self::Mark(_) => 5, Self::Output(_) => 9, Self::Glue(_) | Self::NamedGlue(_, _) | Self::Leaders(_) => 11, Self::Kern(_) | Self::ImplicitKern(_) => 12, Self::Penalty(_) => 13, } } pub fn dimensions(&self) -> Option<(i64, i64, i64)> { match self { Self::Box(b) => Some((b.width + b.shift, b.height, b.depth)), Self::Line(b) => Some((b.width + b.shift, b.height, b.depth)), Self::Rule(r) => Some(r.dimensions()), Self::Output(node) => node.dimensions(), _ => None, } } pub(super) fn node_count(&self) -> usize { match self { 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, } } } fn text_node_count(nodes: &[TextNode]) -> usize { nodes .iter() .map(|n| { 1 + match n { TextNode::Discretionary { pre_break, post_break, .. } => text_node_count(pre_break) + text_node_count(post_break), TextNode::Box(b) => b.native_box.as_ref().map_or(0, |b| b.node_count()), TextNode::Adjustment(value) => { value.nodes.iter().map(NativeVerticalNode::node_count).sum() } TextNode::Insertion(value) => { value.nodes.iter().map(NativeVerticalNode::node_count).sum() } TextNode::Leaders(leader) => leader.pattern.node_count(), _ => 0, } }) .sum() } enum PackedHorizontal<'a> { Item(HorizontalItem), Leaders(&'a LeaderGlue, i64), Output(&'a OutputNode), } pub(super) enum BoxPaint<'a> { Box(&'a HorizontalBox), PdfColor, PdfGraphics, PdfTextSpace(crate::pdf_device::text_spaces::SpaceOperation), RowStart(BoxLayout), PdfLink(&'a OutputNode, BoxLayout), 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 output_positions: Vec<[i64; 2]>, pub work: usize, } #[derive(Clone, Copy)] pub(super) struct BoxLayout { pub horizontal: bool, pub left: i64, pub baseline: i64, pub width: i64, pub height: i64, pub depth: i64, pub level: usize, } pub(super) enum GeometryItem { Output, Paint(crate::math_engine_tex::PositionedItem), PdfColor, PdfGraphics { x: i64, y: i64 }, PdfTextSpace { x: i64, y: i64, operation: crate::pdf_device::text_spaces::SpaceOperation }, } impl NativeBox { 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; } match &b.content { BoxContent::Horizontal(nodes) => { 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, leaders) } } _ => {} } } } BoxContent::Vertical(nodes) => { 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, leaders) } _ => {} } } } } } let mut out = Vec::new(); 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 output_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.needs_shipout_position() { output_positions.push([x, y]); } outputs.push(o.clone()); } })?; Ok(LeaderEffects { outputs, output_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. pub fn horizontal_items(&self) -> Option> { Some( self.packed_horizontal()? .into_iter() .filter_map(|item| match item { PackedHorizontal::Item(value) => Some(value), PackedHorizontal::Leaders(_, width) => Some(HorizontalItem::Glue { width, stretch: 0, shrink: 0, order: 0, }), PackedHorizontal::Output(node) => node.image_box().map(HorizontalItem::Box), }) .collect(), ) } fn packed_horizontal(&self) -> Option>> { let BoxContent::Horizontal(nodes) = &self.content else { return None; }; let (mut cumulative, mut previous) = (0, 0); let mut items = Vec::new(); for node in nodes { if matches!(node, TextNode::Box(b) if b.native_box.as_ref().is_some_and(|b| b.kind.is_unset())) { continue; } let item = match node { TextNode::Glyph { glyph, .. } | TextNode::Box(glyph) | TextNode::MathChar(glyph) => HorizontalItem::Box(glyph.clone()), TextNode::Rule(r) => { HorizontalItem::Box(r.horizontal_item(self.width, self.height, self.depth)) } TextNode::Indent(w) | TextNode::MathBoundary { width: w, .. } | TextNode::AccentKern(w) | TextNode::AutoKern(w) | TextNode::MarginKern { width: w, .. } | TextNode::Kern { width: w, .. } => HorizontalItem::Box(HorizontalBox { width: *w as i64, ..HorizontalBox::default() }), TextNode::Penalty(n) => HorizontalItem::Penalty { width: 0, penalty: *n as i64, flagged: false, }, TextNode::Glue(g) | TextNode::NamedGlue(g, _) => HorizontalItem::Glue { width: g.width as i64 + self.setting.adjustment(*g, &mut cumulative, &mut previous), stretch: 0, shrink: 0, order: 0, }, 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) => { items.push(PackedHorizontal::Output(node)); continue; } _ => continue, }; items.push(PackedHorizontal::Item(item)); } Some(items) } pub fn node_count(&self) -> usize { 1 + match &self.content { BoxContent::Vertical(v) => v.iter().map(NativeVerticalNode::node_count).sum(), BoxContent::Horizontal(v) => text_node_count(v), } } pub(super) fn horizontal_item(self) -> HorizontalBox { HorizontalBox { width: self.width, height: self.height, depth: self.depth, native_box: Some(Box::new(self)), ..HorizontalBox::default() } } } #[derive(Clone, Debug)] pub(super) struct VerticalBuilder { pub nodes: Vec, pub prev_depth: i32, pub previous_lines: usize, // The semantic tail may belong to a list inside an already packed box. // Paths preserve ownership without storing unsafe pointers into Vecs. tail_path: Vec, } impl Default for VerticalBuilder { fn default() -> Self { Self { nodes: Vec::new(), prev_depth: -1000 * 65536, previous_lines: 0, tail_path: Vec::new(), } } } impl VerticalBuilder { // A horizontal list can still query and change its enclosing vertical // list's prevgraf. A new vertical list starts with its own zero count. pub fn enter_nested(&mut self, horizontal: bool) -> Self { let outer = std::mem::take(self); if horizontal { self.previous_lines = outer.previous_lines; } outer } pub fn leave_nested(&mut self, mut outer: Self, horizontal: bool) { if horizontal { outer.previous_lines = self.previous_lines; } *self = outer; } pub fn append_box(&mut self, node: NativeVerticalNode, state: &State) -> Result<(), String> { let (_, height, depth) = node.dimensions().expect("box or line"); if self.prev_depth > -1000 * 65536 { let mut label = Parameter::Baselineskip; let mut g = state.parameter(label).glue(); let gap = g.width as i64 - self.prev_depth as i64 - height; if gap < state.parameter(Parameter::Lineskiplimit).width() as i64 { label = Parameter::Lineskip; g = state.parameter(Parameter::Lineskip).glue(); } else { g.width = i32::try_from(gap).map_err(|_| "native interline glue capacity exceeded")?; } self.push(NativeVerticalNode::NamedGlue(g, label)); } self.push(node); self.prev_depth = depth as i32; Ok(()) } } fn target(spec: PackSpec, natural: i64) -> i64 { match spec { PackSpec::Natural => natural, PackSpec::To(n) => n as i64, PackSpec::Spread(n) => natural + n as i64, } } fn flex(g: Glue, stretch: &mut [i64; 4], shrink: &mut [i64; 4]) { stretch[g.stretch.order as usize] += g.stretch.amount as i64; shrink[g.shrink.order as usize] += g.shrink.amount as i64; } /// TeX's last_badness is a packaging result (overfull = 1_000_000), not the /// 10001 sentinel used by the paragraph break search or a page-break cost. pub(super) fn setting( delta: i64, stretch: [i64; 4], shrink: [i64; 4], nonempty: bool, ) -> (GlueSetting, i32, i64) { if delta == 0 { return (GlueSetting::default(), 0, 0); } let totals = if delta > 0 { stretch } else { shrink }; let order = (0..4).rev().find(|o| totals[*o] != 0).unwrap_or(0); let total = totals[order]; let overfull = delta < 0 && order == 0 && -delta > total && nonempty; let badness = if !nonempty || order > 0 { 0 } else if overfull { 1_000_000 } else { paragraph::tex_badness(delta.abs(), total) }; let numerator = if overfull { total } else { delta.abs() }; let set = GlueSetting { sign: if total == 0 { 0 } else if delta > 0 { 1 } else { -1 }, order: order as u8, numerator, denominator: total, }; (set, badness, if overfull { -delta - total } else { 0 }) } impl GlueSetting { pub(super) fn adjustment(self, g: Glue, cumulative: &mut i128, previous: &mut i64) -> i64 { let f = if self.sign > 0 { g.stretch } else { g.shrink }; if self.sign == 0 || f.order != self.order || self.denominator == 0 { return 0; } *cumulative += f.amount as i128; let n = *cumulative * self.numerator as i128 * self.sign as i128; let d = self.denominator as i128; // web2c rounds signed cumulative glue away from zero at half a sp. // TeX's vet_glue clamps the cumulative adjustment before shipping it. let now = (n.signum() * d.signum() * ((n.abs() + d.abs() / 2) / d.abs())) .clamp(-1_000_000_000, 1_000_000_000) as i64; let result = now - *previous; *previous = now; result } } pub(super) fn vpack( nodes: Vec, spec: PackSpec, max_depth: i32, kind: BoxKind, span: Span, ) -> Result { let (mut height, mut depth, mut width) = (0, 0, 0); let (mut stretch, mut shrink) = ([0; 4], [0; 4]); for node in &nodes { if let Some((w, h, d)) = node.dimensions() { height += depth + h; depth = d; width = width.max(w); } else { match node { NativeVerticalNode::Glue(g) | NativeVerticalNode::NamedGlue(g, _) => { height += depth + g.width as i64; 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; } _ => {} } } } if depth > max_depth as i64 { height += depth - max_depth as i64; depth = max_depth as i64; } let desired = target(spec, height); let (set, badness, excess) = setting(desired - height, stretch, shrink, !nodes.is_empty()); let diagnostic_eligible = desired != height && set.order == 0 && !nodes.is_empty(); height = desired; if kind == BoxKind::Vtop { let first = nodes .first() .and_then(NativeVerticalNode::dimensions) .map_or(0, |d| d.1); depth += height - first; height = first; } dimensions_fit(width, height, depth)?; Ok(NativeBox { kind, display: false, width, height, depth, shift: 0, content: BoxContent::Vertical(nodes), diagnostic: Vec::new(), setting: set, badness, diagnostic_eligible, excess, span, }) } pub(super) fn dimensions_fit(w: i64, h: i64, d: i64) -> Result<(), String> { if [w, h, d].iter().any(|n| n.abs() > 1073741823) { Err("native box dimension capacity exceeded".into()) } else { Ok(()) } } pub(super) fn hpack( mut nodes: Vec, spec: PackSpec, span: Span, state: &State, ) -> Result { let (mut width, mut height, mut depth) = (0, 0, 0); let (mut stretch, mut shrink) = ([0; 4], [0; 4]); for node in &nodes { match node { TextNode::Glyph { glyph, .. } | TextNode::Box(glyph) | TextNode::MathChar(glyph) => { width += glyph.width; let shift = glyph.native_box.as_ref().map_or(0, |b| b.shift); height = height.max(glyph.height - shift); depth = depth.max(glyph.depth + shift); } TextNode::Rule(r) => { let (w, h, d) = r.dimensions(); width += w; height = height.max(h); depth = depth.max(d); } TextNode::Output(node) => { if let Some((w, h, d)) = node.dimensions() { width += w; height = height.max(h); depth = depth.max(d); } } TextNode::Indent(w) | TextNode::MathBoundary { width: w, .. } | TextNode::AccentKern(w) | TextNode::AutoKern(w) | TextNode::MarginKern { width: w, .. } | TextNode::Kern { width: w, .. } => width += *w as i64, TextNode::Glue(g) | TextNode::NamedGlue(g, _) => { 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); } _ => {} } } let desired = target(spec, width); let (set, badness, excess) = setting(desired - width, stretch, shrink, !nodes.is_empty()); let diagnostic_eligible = desired != width && set.order == 0 && !nodes.is_empty(); dimensions_fit(desired, height, depth)?; if excess > i64::from(state.parameter(Parameter::Hfuzz).width()) && state.parameter(Parameter::Overfullrule).width() > 0 && badness == 1_000_000 { nodes.push(TextNode::Rule(NativeRule { span, origin: None, derivation: None, width: Some(state.parameter(Parameter::Overfullrule).width()), height: None, depth: None, })); } let diagnostic = super::diagnostics::text_nodes(&nodes); Ok(NativeBox { kind: BoxKind::Horizontal, display: false, width: desired, height, depth, shift: 0, content: BoxContent::Horizontal(nodes), diagnostic, setting: set, badness, diagnostic_eligible, excess, span, }) } /// Flatten already packed native geometry for the common PDF/SVG display list. /// Internal coordinates remain TeX sp until this single export conversion. impl NativeBox { pub(crate) fn paint_display( &self, x: i64, baseline: i64, out: &mut Vec, ) { self.paint_at(0, self.shift, x, baseline, out); } fn paint_at( &self, x: i64, y: i64, ox: i64, oy: i64, out: &mut Vec, ) { self.walk(x, y, &mut |x, y, node| { let BoxPaint::Box(b) = node else { return }; if let Some(g) = &b.math_geometry { super::math::paint_geometry(g, x, y, ox, oy, out); } else if let Some(c) = b.character { out.push(crate::render::DisplayItem::Text { x: ox + bp(x), y: oy + bp(y), size: bp(b.size.unwrap_or(655360)), text: c.to_string(), 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 { use crate::math_engine_tex::MathGeometry; let mut g = MathGeometry { metrics: crate::math::MathBox { width: self.width, height: self.height, depth: self.depth, }, items: Vec::new(), }; self.visit_geometry(|item| { if let GeometryItem::Paint(paint) = item { g.items.push(paint); } })?; Ok(g) } pub(super) fn visit_geometry(&self, mut emit: impl FnMut(GeometryItem)) -> Result<(), String> { use crate::math_engine_tex::PositionedItem; let mut unsupported = false; self.walk(0, 0, &mut |x, y, node| { let b = match node { BoxPaint::Box(b) => b, BoxPaint::PdfColor => { emit(GeometryItem::PdfColor); return; } BoxPaint::PdfGraphics => { emit(GeometryItem::PdfGraphics { x, y }); return; } BoxPaint::PdfTextSpace(operation) => { emit(GeometryItem::PdfTextSpace { x, y, operation }); return; } BoxPaint::Output(_) => { emit(GeometryItem::Output); return; } BoxPaint::RowStart(_) | BoxPaint::PdfLink(_, _) => return, }; if let Some(child) = &b.math_geometry { for p in &child.items { emit(GeometryItem::Paint(PositionedItem { x: x + p.x, y: y + p.y, item: p.item.clone(), source: p.source.clone(), })); } } else if b.character.is_some() { unsupported = true; } })?; if unsupported { Err("native math box requires actual native glyph geometry".into()) } else { Ok(()) } } pub(super) fn positioned_outputs(&self) -> Vec<[i64; 2]> { let mut positions = Vec::new(); self.walk(0, 0, &mut |x, y, node| { if matches!(node, BoxPaint::Output(node) if node.needs_shipout_position()) { positions.push([x, y]); } }) .expect("output traversal of an already measured list"); positions } 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, &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, budget: &mut WalkBudget<'_>, emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>), ) -> Result<(), &'static str> { if self.kind.is_unset() { return Ok(()); } match &self.content { BoxContent::Horizontal(nodes) => { budget.inside_leader(nodes.len())?; let row = BoxLayout { horizontal: true, 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, budget, emit)?; } BoxContent::Vertical(nodes) => { let container = BoxLayout { horizontal: false, left: x, baseline: y, width: self.width, height: self.height, depth: self.depth, level, }; 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, 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) } NativeVerticalNode::Rule(r) => { let b = r.horizontal_item(self.width, 0, 0); cursor += b.height; emit(x, cursor, BoxPaint::Box(&b)); cursor += b.depth; } NativeVerticalNode::Output(node) => { walk_output(node, x, cursor, container, links, emit); if let Some(image) = node.image_box() { cursor += image.height; emit(x, cursor, BoxPaint::Box(&image)); cursor += image.depth; } } _ => {} } } } } 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 { .. })) && !matches!(paint, BoxPaint::PdfLink(node, _) if matches!( node.operation, OutputOperation::PdfLink(crate::pdf_device::links::LinkNode::Destination { .. }) )) { emit(x, y, paint); } }); budget.leader_depth -= 1; result } } pub(super) fn bp(n: i64) -> i64 { if n < 0 { -((-n * 800 + 401) / 803) } else { (n * 800 + 401) / 803 } } fn walk_row( items: &[PackedHorizontal<'_>], row: BoxLayout, 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, 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::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, 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, container: BoxLayout, 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 let OutputOperation::PdfTextSpace(operation) = node.operation { emit(x, y, BoxPaint::PdfTextSpace(operation)); } else if links && node.is_pdf_link() { emit(x, y, BoxPaint::PdfLink(node, container)); } } pub(super) fn box_paragraph(mut b: NativeBox) -> Paragraph { let (width, height, depth, shift) = (b.width, b.height, b.depth, b.shift); b.shift = 0; Paragraph { lines: vec![vec![HorizontalItem::Box(b.horizontal_item())]], width, height: height + depth, depth, font: ParagraphFont::Roman, font_size: 655360, left_skip: 0, line_indents: vec![shift], line_baselines: vec![height], line_scales: Vec::new(), centered: false, right_aligned: false, } }