//! Owned native boxes. Packing follows tex.web hpack/vpackage, not page costs. use super::*; use crate::{HorizontalBox, HorizontalItem, Paragraph, ParagraphFont}; use std::sync::Arc; mod interword; mod tail; pub(super) use tail::TailNodeRef; mod leaders; mod format_fonts; mod native_words; 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(Arc>), Vertical(Arc>), } #[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, shared by box copies and diagnostic views. pub diagnostic: Arc<[super::diagnostics::DiagnosticNode]>, pub setting: GlueSetting, // Prepared only on the disposable shipout box after its glue is set. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(super) interword_runs: Vec, 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), } impl PackedHorizontal<'_> { fn width(&self) -> i64 { match self { Self::Item(HorizontalItem::Box(b)) => b.width, Self::Item(HorizontalItem::Glue { width, .. }) | Self::Leaders(_, width) => *width, Self::Output(node) => node.dimensions().map_or(0, |(width, _, _)| width), _ => 0, } } } pub(super) enum BoxPaint<'a> { Box(&'a HorizontalBox), PdfColor, PdfGraphics, PdfTextSpace(crate::pdf_device::text_spaces::SpaceOperation), RowStart(BoxLayout), ScopeStart(usize), ScopeEnd(usize), PdfLink(&'a OutputNode, BoxLayout), Output(&'a OutputNode), } struct WalkBudget<'a> { remaining: usize, cancellation: Option<&'a Cancellation>, leader_depth: usize, xdv_annotations: bool, } impl WalkBudget<'_> { fn for_geometry() -> Self { Self { remaining: usize::MAX, cancellation: None, leader_depth: 0, xdv_annotations: false, } } 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)?; } else if self.cancellation.is_some_and(Cancellation::is_cancelled) { return Err("native compilation cancelled"); } 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 { special: bool }, Paint(crate::math_engine_tex::PositionedItem), PdfColor { x: i64, y: i64 }, 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, rtl: bool, out: &mut Vec<&'a OutputNode>, leaders: &mut bool) { if b.kind.is_unset() { return; } match &b.content { BoxContent::Horizontal(nodes) => { let order = b.horizontal_order(nodes, rtl && !b.display); let order = order.as_deref(); for index in 0..order.map_or(nodes.len(), <[_]>::len) { let (index, rtl) = order.map_or((index, false), |order| order[index]); match &nodes[index] { 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, rtl, out, leaders) } } _ => {} } } } BoxContent::Vertical(nodes) => { for n in nodes.iter() { match n { NativeVerticalNode::Output(o) => out.push(o), NativeVerticalNode::Leaders(_) => *leaders = true, NativeVerticalNode::Box(b) | NativeVerticalNode::Line(b) => { walk(b, rtl, out, leaders) } _ => {} } } } } } let mut out = Vec::new(); let mut leaders = false; walk(self, false, &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, xdv_annotations: false, }; self.walk_at(0, 0, 0, false, 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(false)? .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<'a>(&'a self, rtl: bool) -> Option, bool)>> { let BoxContent::Horizontal(nodes) = &self.content else { return None; }; let (mut cumulative, mut previous) = (0, 0); let mut pack = |node: &'a TextNode| { if matches!(node, TextNode::Box(b) if b.native_box.as_ref().is_some_and(|b| b.kind.is_unset())) { return None; } let item = match node { TextNode::Glyph { glyph, .. } | TextNode::Box(glyph) | TextNode::MathChar(glyph) => HorizontalItem::Box(glyph.clone()), TextNode::OpenType(run) | TextNode::ExplicitOpenTypeGlyph(run) => { HorizontalItem::Box(crate::opentype::horizontal_box(run)) } 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::SpaceAdjustment(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::FontSpace(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); return Some(PackedHorizontal::Leaders(leader, width)); } TextNode::Output(node) => { return Some(PackedHorizontal::Output(node)); } _ => return None, }; Some(PackedHorizontal::Item(item)) }; let Some(order) = self.horizontal_order(nodes, rtl) else { return Some(nodes.iter().filter_map(|node| pack(node).map(|item| (item, false))).collect()); }; // Accumulate glue rounding in logical order. Glues included in a // reshaped word were resolved separately and do not update this total. let retained = if self.interword_runs.is_empty() { None } else { let mut retained = vec![false; nodes.len()]; for &(index, _) in &order { retained[index] = true; } Some(retained) }; let mut logical: Vec<_> = nodes.iter().enumerate() .map(|(index, node)| { if retained.as_ref().is_none_or(|retained| retained[index]) { pack(node) } else { None } }) .collect(); for run in &self.interword_runs { logical[run.nodes.start] = Some(PackedHorizontal::Item(HorizontalItem::Box( crate::opentype::horizontal_box(&run.word), ))); } Some(order.into_iter() .filter_map(|(index, rtl)| logical[index].take().map(|item| (item, rtl))) .collect()) } fn horizontal_order(&self, nodes: &[TextNode], rtl: bool) -> Option> { let order = super::direction::visual_order(nodes, rtl); if self.interword_runs.is_empty() { return order; } let order = order.unwrap_or_else(|| (0..nodes.len()).map(|index| (index, false)).collect()); let mut removed = vec![false; nodes.len()]; for run in &self.interword_runs { removed[run.nodes.start + 1..run.nodes.end].fill(true); for &effect in &run.effects { removed[effect] = true; } } let mut prepared = Vec::with_capacity(order.len()); for (index, rtl) in order { if removed[index] { continue; } if let Ok(run) = self.interword_runs.binary_search_by_key(&index, |run| run.nodes.start) { let effects = &self.interword_runs[run].effects; if rtl { prepared.extend(effects.iter().rev().map(|&effect| (effect, rtl))); } prepared.push((index, rtl)); if !rtl { prepared.extend(effects.iter().map(|&effect| (effect, rtl))); } } else { prepared.push((index, rtl)); } } Some(prepared) } 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.into()), diagnostic: Arc::default(), setting: set, interword_runs: Vec::new(), 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( nodes: Vec, spec: PackSpec, span: Span, state: &State, ) -> Result { hpack_with_direction_report(nodes, spec, span, state, None).map(|(packed, _)| packed) } pub(super) fn hpack_with_direction_report( mut nodes: Vec, spec: PackSpec, span: Span, state: &State, shaping_budget: Option<(&mut usize, usize)>, ) -> Result<(NativeBox, (usize, usize)), String> { if state.input_profile() == InputProfile::XeTeX { let glyph_metrics = state.parameter(Parameter::XeTeXuseglyphmetrics).width() > 0; native_words::rejoin(&mut nodes, glyph_metrics, shaping_budget)?; } let direction_problems = super::direction::complete_box(&mut nodes); 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::OpenType(run) | TextNode::ExplicitOpenTypeGlyph(run) => { width += run.width; let [run_height, run_depth] = run.height_depth(); height = height.max(run_height); depth = depth.max(run_depth); } 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::SpaceAdjustment(w) | TextNode::MarginKern { width: w, .. } | TextNode::Kern { width: w, .. } => width += *w as i64, TextNode::Glue(g) | TextNode::FontSpace(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).into(); Ok((NativeBox { kind: BoxKind::Horizontal, display: false, width: desired, height, depth, shift: 0, content: BoxContent::Horizontal(nodes.into()), diagnostic, setting: set, interword_runs: Vec::new(), badness, diagnostic_eligible, excess, span, }, direction_problems)) } /// 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, emit: impl FnMut(GeometryItem)) -> Result<(), String> { self.visit_geometry_cancellable(None, emit) } pub(super) fn visit_geometry_cancellable( &self, cancellation: Option<&Cancellation>, mut emit: impl FnMut(GeometryItem), ) -> Result<(), String> { use crate::math_engine_tex::PositionedItem; let mut unsupported = false; let mut budget = WalkBudget { cancellation, ..WalkBudget::for_geometry() }; self.walk_at(0, 0, 0, false, false, &mut budget, &mut |x, y, node| { let b = match node { BoxPaint::Box(b) => b, BoxPaint::PdfColor => { emit(GeometryItem::PdfColor { x, y }); return; } BoxPaint::PdfGraphics => { emit(GeometryItem::PdfGraphics { x, y }); return; } BoxPaint::PdfTextSpace(operation) => { emit(GeometryItem::PdfTextSpace { x, y, operation }); return; } BoxPaint::Output(node) => { emit(GeometryItem::Output { special: matches!(node.operation, OutputOperation::Special { .. }), }); return; } BoxPaint::RowStart(_) | BoxPaint::ScopeStart(_) | BoxPaint::ScopeEnd(_) | 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 visit_shipout_font_uses( &self, mut emit: impl FnMut(usize, usize, &std::sync::Arc, u8), ) -> Result<(), String> { use crate::math_engine_tex::MathItem; let mut output_count = 0; let mut paint_count = 0; self.walk(0, 0, &mut |_, _, node| match node { BoxPaint::Output(_) => output_count += 1, BoxPaint::Box(b) => { if let Some(geometry) = &b.math_geometry { for item in &geometry.items { if let MathItem::NativeGlyph { font, slot, .. } = &item.item { emit(output_count, paint_count, font, *slot); } } } paint_count += 1; } _ => {} })?; 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, 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, false, true, &mut WalkBudget::for_geometry(), emit) .expect("link traversal of an already measured list"); } pub(super) fn walk_xdv_annotations( &self, cancellation: Option<&Cancellation>, emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>), ) -> Result<(), &'static str> { let mut budget = WalkBudget { cancellation, xdv_annotations: true, ..WalkBudget::for_geometry() }; self.walk_at(0, 0, 0, false, false, &mut budget, emit) } fn walk_at( &self, x: i64, y: i64, level: usize, rtl: bool, links: bool, budget: &mut WalkBudget<'_>, emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>), ) -> Result<(), &'static str> { if self.kind.is_unset() { return Ok(()); } if budget.xdv_annotations { budget.charge(1)?; emit(x, y, BoxPaint::ScopeStart(level)); } match &self.content { BoxContent::Horizontal(nodes) => { budget.inside_leader(nodes.len())?; let rtl = rtl && !self.display; let packed = self.packed_horizontal(rtl).unwrap(); let left = if rtl { x + self.width - packed.iter().map(|(item, _)| item.width()).sum::() } else { x }; let row = BoxLayout { horizontal: true, left, baseline: y, width: self.width, height: self.height, depth: self.depth, level, }; if links { emit(left, y, BoxPaint::RowStart(row)); } walk_row(&packed, row, links, budget, emit)?; } BoxContent::Vertical(nodes) => { let edge = if rtl { x + self.width } else { x }; let container = BoxLayout { horizontal: false, left: edge, 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.iter() { budget.inside_leader(1)?; match node { NativeVerticalNode::Box(b) | NativeVerticalNode::Line(b) => { if b.kind.is_unset() { continue; } cursor += b.height; let child_x = if rtl { edge - b.shift - b.width } else { x + b.shift }; b.walk_at(child_x, cursor, level + 1, rtl, 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( if rtl { edge - b.shift - b.width } else { x + b.shift }, pos + b.height, level + 1, rtl, 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(if rtl { edge - b.width } else { x }, cursor, BoxPaint::Box(&b)); cursor += b.depth; } NativeVerticalNode::Output(node) => { walk_output(node, edge, cursor, container, links, emit); if let Some(image) = node.image_box() { cursor += image.height; emit(if rtl { edge - image.width } else { x }, cursor, BoxPaint::Box(&image)); cursor += image.depth; } } _ => {} } } } } if budget.xdv_annotations { emit(x, y, BoxPaint::ScopeEnd(level)); } Ok(()) } fn walk_leader( &self, x: i64, y: i64, level: usize, rtl: bool, 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, rtl, 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<'_>, bool)], 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, rtl) 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, *rtl, 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, *rtl, 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, } }