Skip to main content

latexml_post/
latex_images.rs

1//! LaTeX-based image generation processor.
2//!
3//! Port of `LaTeXML::Post::LaTeXImages` (539 lines of Perl).
4//! Base class for processors that generate images by running LaTeX + dvipng/dvips
5//! on extracted TeX fragments. Used by MathImages and PictureImages.
6//!
7//! Pipeline:
8//! 1. Collect TeX fragments from document nodes via `extractTeX()`
9//! 2. Deduplicate: same TeX → same image (keyed by processor+type+tex)
10//! 3. Check cache for previously generated images
11//! 4. Generate a LaTeX document with all pending fragments
12//! 5. Run `latex` to produce DVI
13//! 6. Run `dvipng`/`dvips`/`dvisvgm` to produce individual images
14//! 7. Parse dimensions from LaTeX log (LXIMAGE lines)
15//! 8. Optionally convert/crop via ImageMagick
16//! 9. Store results in cache; set node attributes
17
18use libxml::tree::Node;
19use rustc_hash::FxHashMap as HashMap;
20
21use crate::{
22  document::PostDocument,
23  processor::{PostError, ProcessResult, Processor, find_documentclass_and_packages},
24};
25
26/// DVI-to-image conversion method.
27#[derive(Debug, Clone)]
28pub enum DviMethod {
29  /// dvipng (fast, PNG only)
30  DviPng,
31  /// dvisvgm (SVG output)
32  DviSvgm,
33  /// dvips + ImageMagick (general purpose, slow)
34  Dvips,
35}
36
37/// A pending image entry to be generated.
38#[derive(Debug)]
39struct ImageEntry {
40  /// The TeX source fragment.
41  tex:   String,
42  /// Cache key.
43  key:   String,
44  /// Nodes that reference this image.
45  nodes: Vec<Node>,
46  /// Desired destination paths.
47  dests: Vec<String>,
48}
49
50/// LaTeX image generation processor.
51///
52/// Port of `LaTeXML::Post::LaTeXImages`.
53pub struct LaTeXImages {
54  name:               String,
55  resource_directory: String,
56  resource_prefix:    String,
57  image_type:         String,
58  dvi_method:         DviMethod,
59  magnification:      f64,
60  max_width:          u32,
61  dpi:                u32,
62  background:         String,
63  padding:            u32,
64  clipping_fudge:     u32,
65  clipping_rule:      f64,
66}
67
68impl LaTeXImages {
69  pub fn new(resource_directory: &str, resource_prefix: &str, image_type: &str) -> Self {
70    let dvi_method = match image_type {
71      "svg" => DviMethod::DviSvgm,
72      "png" => DviMethod::DviPng,
73      _ => DviMethod::Dvips,
74    };
75
76    LaTeXImages {
77      name: "LaTeXImages".to_string(),
78      resource_directory: resource_directory.to_string(),
79      resource_prefix: resource_prefix.to_string(),
80      image_type: image_type.to_string(),
81      dvi_method,
82      magnification: 1.33333,
83      max_width: 800,
84      // The CSS inch (OXIDIZED_DESIGN_DIVERGENCES #1189; Perl LaTeXImages.pm:50 `DPI || 100`).
85      dpi: 96,
86      background: "#FFFFFF".to_string(),
87      padding: 2,
88      clipping_fudge: 3,
89      clipping_rule: 0.90,
90    }
91  }
92
93  /// Clean a TeX string for image generation.
94  ///
95  /// Port of `LaTeXImages::cleanTeX`.
96  pub fn clean_tex(tex: &str) -> String {
97    let mut s = tex.to_string();
98    let mut style = String::new();
99
100    // Save leading math style
101    for prefix in &[
102      "\\displaystyle",
103      "\\textstyle",
104      "\\scriptstyle",
105      "\\scriptscriptstyle",
106    ] {
107      if let Some(rest) = s.trim_start().strip_prefix(prefix) {
108        style = prefix.to_string();
109        s = rest.to_string();
110        break;
111      }
112    }
113
114    // Trim leading/trailing TeX spacing commands
115    static SPACING_RE: std::sync::LazyLock<regex::Regex> =
116      std::sync::LazyLock::new(|| regex::Regex::new(r"^(?:\\[,!>;:/ ]|\\ )*").unwrap());
117    let spacing_re = &*SPACING_RE;
118    s = spacing_re.replace(&s, "").to_string();
119    static TRAILING_RE: std::sync::LazyLock<regex::Regex> =
120      std::sync::LazyLock::new(|| regex::Regex::new(r"(?:\\[,!>;:/ ]|\\ )*$").unwrap());
121    let trailing_re = &*TRAILING_RE;
122    s = trailing_re.replace(&s, "").to_string();
123
124    // Strip comments (but not escaped %)
125    // Note: Rust regex doesn't support lookbehinds, so we use a simple approach
126    static COMMENT_RE: std::sync::LazyLock<regex::Regex> =
127      std::sync::LazyLock::new(|| regex::Regex::new(r"([^\\])%[^\n]*\n").unwrap());
128    let comment_re = &*COMMENT_RE;
129    s = comment_re.replace_all(&s, "$1").to_string();
130
131    if !style.is_empty() {
132      format!("{} {}", style, s)
133    } else {
134      s
135    }
136  }
137
138  /// Set the image attributes on a node.
139  ///
140  /// Port of `LaTeXImages::setTeXImage`.
141  pub fn set_tex_image(node: &mut Node, path: &str, width: u32, height: u32, depth: Option<u32>) {
142    node.set_attribute("imagesrc", path).ok();
143    node.set_attribute("imagewidth", &width.to_string()).ok();
144    node.set_attribute("imageheight", &height.to_string()).ok();
145    if let Some(d) = depth {
146      node.set_attribute("imagedepth", &d.to_string()).ok();
147    }
148  }
149
150  /// Generate images for the given nodes.
151  ///
152  /// Port of `LaTeXImages::generateImages`.
153  /// This is the main pipeline entry point.
154  pub fn generate_images(
155    &self,
156    doc: &mut PostDocument,
157    nodes: &[Node],
158    extract_tex: &dyn Fn(&PostDocument, &Node) -> Option<String>,
159  ) -> Result<(), PostError> {
160    // Step 1: Collect unique TeX strings
161    let mut table: HashMap<String, ImageEntry> = HashMap::default();
162    let mut n_total = 0u32;
163
164    for node in nodes {
165      let tex = match extract_tex(doc, node) {
166        Some(t) if !t.trim().is_empty() => t,
167        _ => continue,
168      };
169      n_total += 1;
170
171      let key = format!("{}:{}:{}", self.name, self.image_type, tex);
172      let entry = table.entry(key.clone()).or_insert_with(|| ImageEntry {
173        tex:   tex.clone(),
174        key:   key.clone(),
175        nodes: Vec::new(),
176        dests: Vec::new(),
177      });
178      entry.nodes.push(node.clone());
179    }
180
181    let n_unique = table.len();
182    if n_unique == 0 {
183      return Ok(());
184    }
185
186    // Step 2: Check cache for already-generated images
187    let mut pending = Vec::new();
188    for key in table.keys() {
189      if let Some(cached) = doc.cache_lookup(key) {
190        if cached.contains(';') {
191          continue; // Already cached
192        }
193      }
194      pending.push(key.clone());
195    }
196
197    Info!(
198      "latex_images",
199      "count",
200      "LaTeXImages: {} total, {} unique, {} pending",
201      n_total,
202      n_unique,
203      pending.len()
204    );
205
206    if !pending.is_empty() {
207      // Step 3: Generate LaTeX source
208      let (preamble, body_prefix) = self.pre_preamble(doc);
209      let tex_body = self.generate_tex_document(
210        &preamble,
211        &body_prefix,
212        &pending
213          .iter()
214          .map(|k| table[k].tex.as_str())
215          .collect::<Vec<_>>(),
216      );
217
218      Info!(
219        "latex_images",
220        "generate",
221        "LaTeXImages: generated LaTeX document ({} bytes)",
222        tex_body.len()
223      );
224      log::debug!(
225        target: "latex_images:run",
226        "Would run: latex + {} to produce {} images",
227        match self.dvi_method {
228          DviMethod::DviPng => "dvipng",
229          DviMethod::DviSvgm => "dvisvgm",
230          DviMethod::Dvips => "dvips + convert",
231        },
232        pending.len()
233      );
234
235      // Steps 4-8: Would run external commands here
236      // For now, log the intent
237    }
238
239    // Step 9: Apply cached results to nodes
240    for entry in table.values() {
241      if let Some(cached) = doc.cache_lookup(&entry.key) {
242        let parts: Vec<&str> = cached.split(';').collect();
243        if parts.len() == 4 {
244          let (image, width, height, depth) = (parts[0], parts[1], parts[2], parts[3]);
245          let w: u32 = width.parse().unwrap_or(0);
246          let h: u32 = height.parse().unwrap_or(0);
247          let d: u32 = depth.parse().unwrap_or(0);
248          for node in &entry.nodes {
249            let mut node_mut = node.clone();
250            Self::set_tex_image(&mut node_mut, image, w, h, Some(d));
251          }
252        }
253      }
254    }
255
256    Ok(())
257  }
258
259  /// Generate the LaTeX preamble.
260  ///
261  /// Port of `LaTeXImages::pre_preamble`.
262  fn pre_preamble(&self, doc: &PostDocument) -> (String, String) {
263    let (class_info, packages) = find_documentclass_and_packages(doc);
264    let class = &class_info.name;
265    let class_options = &class_info.options;
266    let oldstyle = class_info.oldstyle.is_some();
267    let document_command = if oldstyle {
268      "\\documentstyle"
269    } else {
270      "\\documentclass"
271    };
272
273    let mut pkg_lines = String::new();
274    for pkg in &packages {
275      if oldstyle {
276        pkg_lines.push_str(&format!("\\RequirePackage{{{}}}\n", pkg.name));
277      } else if pkg.name == "english" {
278        pkg_lines.push_str("\\usepackage[english]{babel}\n");
279      } else if pkg.options.is_empty() {
280        pkg_lines.push_str(&format!("\\usepackage{{{}}}\n", pkg.name));
281      } else {
282        pkg_lines.push_str(&format!("\\usepackage[{}]{{{}}}\n", pkg.options, pkg.name));
283      }
284    }
285
286    let pts_per_pixel = 72.27 / self.dpi as f64 / self.magnification;
287    let w = (self.max_width as f64 * pts_per_pixel).ceil() as u32;
288    let gap = (self.padding + self.clipping_fudge) as f64 * pts_per_pixel;
289    let th = match self.dvi_method {
290      DviMethod::DviSvgm => 0.0,
291      _ => self.clipping_rule * pts_per_pixel,
292    };
293
294    let preamble = format!(
295      r"\batchmode
296\def\inlatexml{{true}}
297{document_command}[{class_options}]{{{class}}}
298{pkg_lines}
299\makeatletter
300\setlength{{\hoffset}}{{0pt}}\setlength{{\voffset}}{{0pt}}
301\setlength{{\textwidth}}{{{w}pt}}
302\newcount\lxImageNumber\lxImageNumber=0\relax
303\newbox\lxImageBox
304\newdimen\lxImageBoxSep
305\setlength\lxImageBoxSep{{{gap:.4}pt}}
306\newdimen\lxImageBoxRule
307\setlength\lxImageBoxRule{{{th:.4}pt}}
308\def\lxShowImage{{%
309  \global\advance\lxImageNumber1\relax
310  \@tempdima\wd\lxImageBox
311  \advance\@tempdima-\lxImageBoxSep
312  \advance\@tempdima-\lxImageBoxSep
313  \typeout{{LXIMAGE \the\lxImageNumber\space= \the\@tempdima\space x \the\ht\lxImageBox\space + \the\dp\lxImageBox}}%
314  \@tempdima\lxImageBoxRule
315  \advance\@tempdima\lxImageBoxSep
316  \advance\@tempdima\dp\lxImageBox
317  \hbox{{\lower\@tempdima\hbox{{\vbox{{%
318    \hrule\@height\lxImageBoxRule%
319    \hbox{{\vrule\@width\lxImageBoxRule%
320      \vbox{{\vskip\lxImageBoxSep\box\lxImageBox\vskip\lxImageBoxSep}}%
321      \vrule\@width\lxImageBoxRule}}%
322    \hrule\@height\lxImageBoxRule}}}}}}%
323}}%
324\def\lxBeginImage{{\setbox\lxImageBox\hbox\bgroup\color@begingroup\kern\lxImageBoxSep}}
325\def\lxEndImage{{\kern\lxImageBoxSep\color@endgroup\egroup}}
326\makeatother",
327      document_command = document_command,
328      class_options = class_options,
329      class = class,
330      pkg_lines = pkg_lines,
331      w = w,
332      gap = gap,
333      th = th
334    );
335
336    // Body prefix: neutralize page styles, captions, citations. The kernel's caption constructor reverts as
337    // `\lx@@caption{…}` (sect09.rs; `\@@caption` is its alias, a CUP class's own `\caption` copy), so a fragment's
338    // `tex` holding a subfigure caption gobbles it under either name (Perl LaTeXImages.pm:411 `\let\@@caption\@gobble`).
339    let body_prefix = "\\makeatletter\\thispagestyle{empty}\\pagestyle{empty}\n\
340       \\let\\@@toccaption\\@gobble\n\
341       \\let\\@@caption\\@gobble\n\
342       \\let\\lx@@caption\\@gobble\n\
343       \\let\\cite\\@gobble\n\
344       \\def\\@@bibref#1#2#3#4{}\n\
345       \\renewcommand{\\cite}[2][]{}\n\
346       \\title{}\\date{}\n\
347       \\makeatother\n"
348      .to_string();
349
350    (preamble, body_prefix)
351  }
352
353  /// Build the complete LaTeX document.
354  fn generate_tex_document(
355    &self,
356    preamble: &str,
357    body_prefix: &str,
358    tex_fragments: &[&str],
359  ) -> String {
360    let mut doc = String::new();
361    doc.push_str(preamble);
362    doc.push_str("\n\\begin{document}\n");
363    doc.push_str(body_prefix);
364    for tex in tex_fragments {
365      doc.push_str(tex);
366      doc.push_str("\\clearpage\n");
367    }
368    doc.push_str("\\end{document}\n");
369    doc
370  }
371
372  /// Get the DVI command string.
373  pub fn dvi_command(&self) -> String {
374    let mag = (self.magnification * 1000.0) as u32;
375    let dpi = (self.dpi as f64 * self.magnification) as u32;
376    match self.dvi_method {
377      DviMethod::DviSvgm => format!(
378        "dvisvgm --page=1- --bbox=1pt --scale={} --no-fonts -o imgx-%03p",
379        self.magnification
380      ),
381      DviMethod::DviPng => format!(
382        "dvipng -bg Transparent -T tight -q -D{} -o imgx-%03d.png",
383        dpi
384      ),
385      DviMethod::Dvips => format!("dvips -q -S1 -i -E -j0 -x{} -o imgx", mag),
386    }
387  }
388
389  /// Parse LXIMAGE dimension lines from a LaTeX log file.
390  ///
391  /// Port of the log parsing in `generateImages`.
392  /// Each line has format: `LXIMAGE N = Wpt x Hpt + Dpt`
393  /// Returns a vector indexed by image number: (width_pt, height_pt, depth_pt).
394  pub fn parse_log_dimensions(log_content: &str) -> Vec<Option<(f64, f64, f64)>> {
395    let re = regex::Regex::new(
396      r"^\s*LXIMAGE\s+(\d+)\s*=\s*([\+\-\d\.]+)pt\s*x\s*([\+\-\d\.]+)pt\s*\+\s*([\+\-\d\.]+)pt\s*$",
397    )
398    .unwrap();
399
400    let mut dimensions: Vec<Option<(f64, f64, f64)>> = Vec::new();
401
402    for line in log_content.lines() {
403      if let Some(caps) = re.captures(line) {
404        let index: usize = caps[1].parse().unwrap_or(0);
405        let width: f64 = caps[2].parse().unwrap_or(0.0);
406        let height: f64 = caps[3].parse().unwrap_or(0.0);
407        let depth: f64 = caps[4].parse().unwrap_or(0.0);
408
409        // Ensure vector is large enough
410        while dimensions.len() <= index {
411          dimensions.push(None);
412        }
413        dimensions[index] = Some((width, height, depth));
414      }
415    }
416
417    dimensions
418  }
419
420  /// Compute the output filename for a given image index.
421  ///
422  /// Port of `sprintf($$self{dvicmd_output_name}, $index)`.
423  pub fn output_filename(&self, index: u32) -> String {
424    match self.dvi_method {
425      DviMethod::DviSvgm => format!("imgx-{:03}.svg", index),
426      DviMethod::DviPng => format!("imgx-{:03}.png", index),
427      DviMethod::Dvips => format!("imgx{:03}", index),
428    }
429  }
430
431  /// Get the output image type for the DVI method.
432  pub fn output_type(&self) -> &str {
433    match self.dvi_method {
434      DviMethod::DviSvgm => "svg",
435      DviMethod::DviPng => "png32",
436      DviMethod::Dvips => "eps",
437    }
438  }
439
440  /// Whether the DVI output needs frame-based cropping.
441  pub fn needs_frame_output(&self) -> bool {
442    match self.dvi_method {
443      DviMethod::DviSvgm => false,
444      DviMethod::DviPng | DviMethod::Dvips => true,
445    }
446  }
447
448  /// Convert TeX points to pixels at the configured DPI and magnification.
449  pub fn pt_to_pixels(&self, pt: f64) -> f64 { pt * self.magnification * self.dpi as f64 / 72.27 }
450
451  /// Check whether this processor has the needed external tools.
452  ///
453  /// Port of `LaTeXImages::canProcess`.
454  /// Checks for:
455  /// - Image processing library (ImageMagick or similar)
456  /// - LaTeX command availability
457  pub fn can_process(&self) -> bool {
458    // Check for latex command
459    let latex_available = latexml_core::util::pathname::tex_tool_command("latex")
460      .arg("--version")
461      .output()
462      .is_ok();
463    if !latex_available {
464      // Perl LaTeXImages.pm L134: Error('expected', $LATEXCMD, undef,
465      //   "No latex command ($LATEXCMD) found; Skipping.", ...)
466      Error!(
467        "expected",
468        "latex",
469        "No latex command found; image generation will be skipped"
470      );
471      return false;
472    }
473    // Check for DVI converter
474    let dvi_cmd = match self.dvi_method {
475      DviMethod::DviPng => "dvipng",
476      DviMethod::DviSvgm => "dvisvgm",
477      DviMethod::Dvips => "dvips",
478    };
479    let dvi_available = latexml_core::util::pathname::tex_tool_command(dvi_cmd)
480      .arg("--version")
481      .output()
482      .is_ok();
483    if !dvi_available {
484      // Perl LaTeXImages.pm dvi-converter check: Error('expected',
485      //   $$self{dvicmd}, …) (parallel to the latex check at L134).
486      Error!(
487        "expected",
488        dvi_cmd,
489        "No {} command found; image generation will be skipped",
490        dvi_cmd
491      );
492      return false;
493    }
494    true
495  }
496
497  /// Convert a DVI-output image (EPS/PNG) to final format with cropping.
498  ///
499  /// Port of `LaTeXImages::convert_image`.
500  /// For dvipng output: already cropped, just copy.
501  /// For dvips output (EPS): needs ImageMagick conversion + trim.
502  /// For dvisvgm output (SVG): already in final format.
503  /// Nothing calls it yet; its copies go through [`crate::writer::copy_atomic`].
504  ///
505  /// Returns (width, height) in pixels, or None on failure.
506  pub fn convert_image(&self, src: &str, dest: &str) -> Option<(u32, u32)> {
507    match self.dvi_method {
508      DviMethod::DviSvgm => {
509        // SVG: just copy
510        if let Err(e) =
511          crate::writer::copy_atomic(std::path::Path::new(src), std::path::Path::new(dest))
512        {
513          // Perl LaTeXImages.pm I/O failure: Error('I/O', $dest, …)
514          Error!("I/O", dest, "Failed to copy {} to {}: {}", src, dest, e);
515          return None;
516        }
517        // SVG dimensions from file would need XML parsing
518        Some((0, 0))
519      },
520      DviMethod::DviPng => {
521        // PNG: already cropped by dvipng -T tight
522        if let Err(e) =
523          crate::writer::copy_atomic(std::path::Path::new(src), std::path::Path::new(dest))
524        {
525          Error!("I/O", dest, "Failed to copy {} to {}: {}", src, dest, e);
526          return None;
527        }
528        // Would read PNG dimensions from file header
529        Some((0, 0))
530      },
531      DviMethod::Dvips => {
532        // EPS: needs ImageMagick conversion
533        // Would run: convert -density DPI -trim src dest
534        Info!(
535          "latex_images",
536          "convert",
537          "Would convert EPS {} to {} via ImageMagick",
538          src,
539          dest
540        );
541        // Shave off clipping fudge + rule
542        let fudge = (self.clipping_fudge as f64 + self.clipping_rule).round() as u32;
543        log::debug!(target: "latex_images:shave", "  Shave: {}px from each edge", fudge);
544        Some((0, 0))
545      },
546    }
547  }
548
549  /// Compute pixels-per-point for dimension conversions.
550  pub fn pixels_per_pt(&self) -> f64 { self.magnification * self.dpi as f64 / 72.27 }
551}
552
553impl Processor for LaTeXImages {
554  fn get_name(&self) -> &str { &self.name }
555
556  fn resource_directory(&self) -> Option<&str> { Some(&self.resource_directory) }
557
558  fn resource_prefix(&self) -> Option<&str> { Some(&self.resource_prefix) }
559
560  fn process(&mut self, doc: PostDocument, nodes: Vec<Node>) -> ProcessResult {
561    Info!(
562      "latex_images",
563      "process",
564      "LaTeXImages: {} nodes to process",
565      nodes.len()
566    );
567    Ok(vec![doc])
568  }
569}