Skip to main content

latexml_post/
graphics.rs

1//! Graphics postprocessing.
2//!
3//! Port of `LaTeXML::Post::Graphics`.
4//! Finds `<ltx:graphics>` elements without `imagesrc`, locates the source
5//! graphic file, applies transformations (scaling, cropping, format conversion),
6//! and sets the `imagesrc`, `imagewidth`, `imageheight` attributes.
7
8use std::{
9  path::{Path, PathBuf},
10  sync::LazyLock,
11};
12
13use latexml_core::util::image::{GraphicContent, GraphicxOp};
14use libxml::tree::Node;
15use rustc_hash::FxHashMap as HashMap;
16
17use crate::{
18  document::{DocCache, PostDocument},
19  processor::{ProcessResult, Processor},
20  resource_cache::{Output, Proposal, Request, ResourceName},
21};
22
23thread_local! {
24  /// The most recent converter-subprocess diagnostic on this thread: the program
25  /// name plus its captured stderr (or the spawn error). Surfaced into the
26  /// `imageprocessing:failed_to_convert` Error so an ENVIRONMENT failure is
27  /// self-explaining in the log instead of needing a strace — e.g. `gs` not
28  /// installed (`could not start … No such file or directory`), an AppArmor
29  /// denial (`gs: … /undefinedfilename …` while gs exits 0), or an ImageMagick
30  /// policy block. Set by `run_with_timeout`, cleared per node in `process`'s
31  /// worker loop, read+cleared at the Error site. Worker-thread-local — it rides
32  /// the same `logger::capture`/`replay_captured` fold to the main thread as the
33  /// Error itself.
34  static LAST_CONVERTER_DIAG: std::cell::RefCell<Option<String>> =
35    const { std::cell::RefCell::new(None) };
36}
37
38/// Record (overwrite) the latest converter diagnostic on this thread.
39fn record_converter_diag(msg: String) { LAST_CONVERTER_DIAG.with(|c| *c.borrow_mut() = Some(msg)); }
40
41/// Take (read + clear) this thread's latest converter diagnostic.
42fn take_converter_diag() -> Option<String> { LAST_CONVERTER_DIAG.with(|c| c.borrow_mut().take()) }
43
44/// Whether a converter child, between fork and exec, has lost the process that spawned it: its parent is no
45/// longer `spawner`. Comparing against PID 1 instead is wrong where the spawner is PID 1 (a container's entrypoint)
46/// and where a subreaper adopts orphans.
47#[cfg(target_os = "linux")]
48fn reparented(spawner: libc::pid_t, parent_now: libc::pid_t) -> bool { parent_now != spawner }
49
50/// Whether `path` names an existing file or directory this conversion may read: a confined one asks only inside its
51/// roots, never the file system first (`pathname::read_allowed`).
52fn readable(path: &str) -> bool {
53  latexml_core::util::pathname::read_allowed(path) && Path::new(path).exists()
54}
55
56/// Program name for the ImageMagick CLI delegate. On Windows, `convert.exe`
57/// is the system FAT→NTFS conversion utility in `System32`, which shadows
58/// ImageMagick's legacy name — invoking bare `convert` there runs the wrong
59/// program. ImageMagick 7's unified `magick` front-end accepts the same
60/// argument syntax, so use it on Windows. Unix keeps `convert` (matching
61/// Perl's Image::Magick-era delegate chain and ImageMagick 6 installs).
62fn im_convert_program() -> &'static str { if cfg!(windows) { "magick" } else { "convert" } }
63
64/// Program name for the Ghostscript CLI delegate. Unix installs `gs`.
65/// Windows Ghostscript ships the console binary as `gswin64c.exe`
66/// (32-bit: `gswin32c.exe`), MiKTeX bundles its own as `mgs.exe`, and
67/// TeX Live for Windows bundles one behind the `rungs.exe` wrapper
68/// (`tlpkg/tlgs`, same CLI) on the same bin dir as `kpsewhich` — so a
69/// TL-only box still gets a working EPS/PS chain with no extra install.
70/// Probed once per process, in that order, falling back to `gs` so a
71/// failure surfaces as the usual could-not-start converter diagnostic.
72fn gs_program() -> &'static str {
73  if cfg!(windows) {
74    // `which` applies the platform's own lookup rules (PATHEXT, so `.exe`/
75    // `.bat`/`.cmd` all resolve) — the same crate + semantics the kpathsea
76    // backend uses to find `kpsewhich`.
77    static GS: LazyLock<&'static str> = LazyLock::new(|| {
78      ["gswin64c", "gswin32c", "mgs", "rungs"]
79        .into_iter()
80        .find(|candidate| which::which(candidate).is_ok())
81        .unwrap_or("gs")
82    });
83    *GS
84  } else {
85    "gs"
86  }
87}
88
89/// Map a graphics-converter executable to a "what to install" hint, so a
90/// "not installed" diagnostic tells the user how to fix it rather than just
91/// naming a missing binary. Covers the optional tools the graphics cascade
92/// shells out to — none are bundled; the host TeX/graphics ecosystem provides
93/// them. Returns `None` for an unrecognized program (no hint appended).
94/// The Windows Ghostscript aliases (`gswin64c`/`gswin32c`/`mgs`/`rungs`, from
95/// `gs_program`) map to the same Ghostscript hint.
96fn missing_tool_hint(prog: &str) -> Option<&'static str> {
97  Some(match prog {
98    "gs" | "gswin64c" | "gswin32c" | "mgs" | "rungs" | "ps2pdf" => {
99      "install Ghostscript (apt `ghostscript`, brew `ghostscript`) for PDF/PostScript conversion"
100    },
101    "mutool" => "install MuPDF (apt `mupdf-tools`, brew `mupdf-tools`) for fast PDF rendering",
102    "pdftocairo" | "pdftoppm" => {
103      "install Poppler (apt `poppler-utils`, brew `poppler`) for vector-SVG PDF conversion"
104    },
105    "convert" | "magick" => {
106      "install ImageMagick (apt `imagemagick`, brew `imagemagick`) for raster image conversion"
107    },
108    "dvisvgm" => {
109      "install dvisvgm (apt `dvisvgm`, brew `texlive`) for vector-SVG LaTeX-image output"
110    },
111    "dvipng" => "install dvipng (apt `dvipng`, brew `texlive`) for raster LaTeX-image output",
112    "latex" | "pdflatex" | "kpsewhich" | "tftopl" => {
113      "install TeX Live (apt `texlive-latex-base`, brew `texlive` / MacTeX) — the TeX ecosystem \
114       must be present at runtime"
115    },
116    _ => return None,
117  })
118}
119
120// Diagnostic emission: `Error!` (and friends) live in
121// `crate::diag` and are exposed crate-wide via `#[macro_use] pub mod
122// diag;` in `lib.rs`. They emit harness-compatible structured Error
123// lines (`Error:<class>:<object> <msg>`) matching what
124// `latexml_core::common::error::Error!` produces.
125
126// Process-once cached env var (see WISDOM #56 — getenv hot-path race).
127// Parsed-and-validated at init: only positive integer values are
128// honored; everything else (unset, empty, "0", malformed) leaves
129// `SVG_CONVERT_TIMEOUT_SECS` at None and the caller falls back to the
130// 15-second default in `svg_convert_timeout_secs`.
131static SVG_CONVERT_TIMEOUT_SECS: LazyLock<Option<u64>> = LazyLock::new(|| {
132  std::env::var("LATEXML_SVG_CONVERT_TIMEOUT_SECS")
133    .ok()
134    .and_then(|s| s.parse::<u64>().ok())
135    .filter(|&n| n > 0)
136});
137
138/// An SVG's lengths are CSS px, 96 to the inch.
139const SVG_PPI: (f64, f64) = (96.0, 96.0);
140
141/// Wall-clock timeout for the `convert` (ImageMagick / gs) subprocess.
142/// Defaults to 60 s; override via `LATEXML_CONVERT_TIMEOUT_SECS`. Same
143/// pattern as `SVG_CONVERT_TIMEOUT_SECS` — see WISDOM #56.
144static CONVERT_TIMEOUT_SECS: LazyLock<Option<u64>> = LazyLock::new(|| {
145  std::env::var("LATEXML_CONVERT_TIMEOUT_SECS")
146    .ok()
147    .and_then(|s| s.parse::<u64>().ok())
148    .filter(|&n| n > 0)
149});
150
151/// Properties for a graphics file type.
152#[derive(Debug, Clone)]
153pub struct TypeProperties {
154  pub destination_type: Option<String>,
155  pub transparent:      bool,
156  pub prescale:         bool,
157  pub ncolors:          Option<String>,
158  pub quality:          Option<u32>,
159  pub unit:             String,
160  pub raster:           Option<bool>,
161  pub autocrop:         bool,
162  pub desirability:     u32,
163}
164
165impl Default for TypeProperties {
166  fn default() -> Self {
167    TypeProperties {
168      destination_type: None,
169      transparent:      false,
170      prescale:         false,
171      ncolors:          None,
172      quality:          None,
173      unit:             "pixel".to_string(),
174      raster:           None,
175      autocrop:         false,
176      desirability:     0,
177    }
178  }
179}
180
181/// One conversion to run (phase 2 of [`Graphics::process`]).
182#[derive(Clone)]
183struct ConvertJob {
184  job_id:       usize,
185  source:       String,
186  /// The source's content digest, read at planning: the cache keys come from it.
187  digest:       Option<crate::graphics_cache::SourceDigest>,
188  page:         Option<u32>,
189  rel_dest:     String,
190  abs_dest_str: String,
191  /// `Some((rel_svg, abs_svg_str))` when the worker should
192  /// first attempt the vector-SVG path and only fall back
193  /// to the raster `convert` path on failure. `None` means
194  /// the classic raster-only path.
195  svg_paths:    Option<(String, String)>,
196  /// A web-native raster that only needs its pixels cropped or turned:
197  /// copied to `abs_dest_str` rather than converted.
198  copy_source:  bool,
199  /// The ops to apply to the raster's pixels ([`Graphics::physical_ops`]).
200  ops:          Vec<GraphicxOp>,
201  /// The density the source is rendered at ([`Graphics::raster_density_for_source`]), read once for the render, its
202  /// cache key and the crop.
203  density:      u32,
204  /// The raster's pixels per inch, x and y: a drawn source's (PDF, PostScript by content) render density, a raster's
205  /// own resolution (72 dpi when it states none, as pdfTeX takes it).
206  ppi:          (f64, f64),
207  /// The scaling ops (`width`, `height`, `scale`) a vector render's root `width`/`height` are set by, at `dpi`
208  /// ([`Graphics::size_svg`]); empty when the render keeps its own size.
209  sizing:       Vec<GraphicxOp>,
210  dpi:          u32,
211}
212
213/// What a conversion produced.
214#[derive(Clone)]
215struct ConvertOutcome {
216  job_id:   usize,
217  /// Path to write into `imagesrc`; `None` if both convert and copy-fallback failed.
218  imagesrc: Option<String>,
219  /// Raw (pre-transform) dimensions read from whichever file we ended up
220  /// with; after a crop, the cropped size (still before any turn).
221  raw_dims: Option<(u32, u32)>,
222  /// The pixels per inch of `raw_dims`: the job's `ppi` for a raster, 96 for an SVG's CSS px.
223  ppi:      (f64, f64),
224}
225
226/// What phase 3 of [`Graphics::process`] does for one `ltx:graphics` node.
227enum Plan {
228  /// Apply the fallback on the main thread.
229  NotFound { idx: usize, graphic: String },
230  /// Point at a copy of the source (cheap, on the main thread).
231  Copy {
232    idx:     usize,
233    source:  String,
234    options: String,
235    /// The copy's destination, relative to the destination directory.
236    rel:     String,
237    /// Whether this page makes the copy (no earlier page of this process did).
238    copy:    bool,
239  },
240  /// Point at a conversion's outcome (run in parallel, or an earlier page's).
241  Convert {
242    idx:     usize,
243    options: String,
244    job_id:  usize,
245  },
246}
247
248/// The directories a page's images are placed by ([`Graphics::page_dirs`]).
249struct PageDirs {
250  search_paths: Vec<String>,
251  source_dir:   String,
252  dest_dir:     String,
253  site_dir:     String,
254  /// The page's destination directory, whose cache store holds its names (`None`: in memory).
255  cache_dir:    Option<String>,
256}
257
258/// Phase 1 of [`Graphics::process`] ([`Graphics::plan_page`]).
259struct PagePlan {
260  plans: Vec<Plan>,
261  /// The conversions this page runs.
262  jobs:  Vec<ConvertJob>,
263  /// The outcomes an earlier page's conversions produced.
264  known: Vec<ConvertOutcome>,
265}
266
267/// What one `ltx:graphics` node needs ([`Graphics::describe`]).
268enum NodeDesc {
269  NotFound(String),
270  Copy {
271    source:  String,
272    options: String,
273    request: Box<Request>,
274  },
275  Convert(Box<ConvertDesc>),
276}
277
278/// A node whose image is converted, or a raster whose pixels change (cropped, turned).
279struct ConvertDesc {
280  source:           String,
281  options:          String,
282  digest:           Option<crate::graphics_cache::SourceDigest>,
283  page:             Option<u32>,
284  needs_conversion: bool,
285  ops:              Vec<GraphicxOp>,
286  /// Whether the source is drawn (PDF or PostScript by its content, else a `unit: "point"` type), so its pixels are the
287  /// render density's.
288  drawn:            bool,
289  /// The scaling ops a vector render's root is sized by ([`ConvertJob::sizing`]).
290  sizing:           Vec<GraphicxOp>,
291  request:          Request,
292}
293
294impl NodeDesc {
295  fn request(&self) -> Option<&Request> {
296    match self {
297      NodeDesc::NotFound(_) => None,
298      NodeDesc::Copy { request, .. } => Some(request.as_ref()),
299      NodeDesc::Convert(desc) => Some(&desc.request),
300    }
301  }
302}
303
304/// The run's resource names ([`crate::resource_cache`] over Perl's document cache, which every split page shares,
305/// `Post.pm` L192-200, L687-690, persisted as `LaTeXML-oxide.cache`) and what this process did with them. Per page,
306/// Ch1 and Ch2 each wrote `x1.svg` (issue 995).
307#[derive(Default)]
308struct ResourceNames {
309  /// Perl's `resource_prefix` (`x` unless set).
310  prefix:    Option<String>,
311  /// The run's cache ([`Graphics::with_doc_cache`]), else each page's own.
312  cache:     Option<DocCache>,
313  /// (destination directory, key) → the name planned before the render ([`Graphics::plan_names`]); a render worker
314  /// gets the parent's.
315  planned:   HashMap<(String, String), ResourceName>,
316  /// The planned pages' requests, not named yet.
317  pending:   Vec<PendingPage>,
318  /// Whether the run named its images before the render, so a name handed out while rendering is a gap.
319  planning:  bool,
320  /// (destination directory, destination) → the URL a copy took once this process copied it.
321  copies:    HashMap<(String, String), String>,
322  /// (destination directory, destination) → the conversion made into it, and its outcome once it succeeded in this
323  /// process: Perl's `cacheLookup($key)` reuses a converted image on every later page (`Post/Graphics.pm` L249-260).
324  converted: HashMap<(String, String), (ConvertJob, Option<ConvertOutcome>)>,
325  /// Source → its content digest, read once per run.
326  digests:   HashMap<String, Option<crate::graphics_cache::SourceDigest>>,
327}
328
329/// A planned page: its cache, its directories and the requests that name its images.
330struct PendingPage {
331  cache:    DocCache,
332  dirs:     PageDirs,
333  requests: Vec<Request>,
334}
335
336impl ResourceNames {
337  fn digest(&mut self, source: &str) -> Option<crate::graphics_cache::SourceDigest> {
338    self
339      .digests
340      .entry(source.to_string())
341      .or_insert_with(|| Graphics::digest_file_content(source))
342      .clone()
343  }
344}
345
346/// Graphics post-processor.
347///
348/// Port of `LaTeXML::Post::Graphics`.
349pub struct Graphics {
350  name:             String,
351  dpi:              Option<u32>,
352  magnify:          f64,
353  zoomout:          f64,
354  trivial_scaling:  bool,
355  graphics_types:   Vec<String>,
356  type_properties:  HashMap<String, TypeProperties>,
357  background:       String,
358  /// Vector-SVG path for PDF graphics. When > 0, PDFs under this many KB are
359  /// first attempted via the vector converters (mutool, then pdftocairo);
360  /// 0 (the default) does so for PDFs up to 500 KiB (`should_try_svg_path`).
361  /// Either way the raster (`convert`/`gs` → PNG) path takes over on
362  /// failure, timeout, oversized output or an enlarged raster (OD #1034).
363  /// Tracks upstream brucemiller/LaTeXML#902.
364  svg_threshold_kb: u32,
365  /// Whether conversions may be served from the shared, host-persistent
366  /// graphics cache. Threaded explicitly (rather than read from a global)
367  /// so a caller can guarantee its conversions actually run — see
368  /// [`crate::graphics_cache::CachePolicy`] and `with_cache_policy`.
369  cache_policy:     crate::graphics_cache::CachePolicy,
370  names:            ResourceNames,
371}
372
373impl Graphics {
374  // 120 dpi: a compromise between Perl's `$DPI = 100`
375  // (Util/Image.pm:37) and our prior 150. Empirically (1910.01256
376  // measured 2026-05-12) the dominant graphics-phase cost is vector
377  // primitive iteration in matplotlib/pgfplots PDFs, NOT pixel count
378  // — so density 100..150 produce near-identical wall on those
379  // papers. 120 keeps text and thin strokes legible on hidpi displays
380  // (Retina 144-192 dpi target) while shaving ~20-30% off the output
381  // PNG byte count.
382  // Override via `LATEXML_RASTER_DENSITY=<dpi>` for explicit control.
383  const DEFAULT_RASTER_DENSITY: u32 = 120;
384  const MAX_RASTER_DIMENSION_PX: u32 = 2048;
385
386  pub fn new(dpi: Option<u32>, trivial_scaling: bool) -> Self {
387    let mut type_properties = HashMap::default();
388
389    // Default type properties matching Perl.
390    // `.epsi` (EPS Interchange — EPS with optional embedded TIFF
391    // preview, e.g. HIGZ / CERN PAW output) and `.epsf` are EPS
392    // variants browsers can't render natively but `gs` rasterises
393    // identically to plain `.eps`. SURPASS-PERL: Perl LaTeXML also
394    // omits these from its type_properties so the files were copied
395    // verbatim and rendered as broken images. Witness:
396    // hep-ph0608319 Fig 1 (refit_av_extra.epsi, HIGZ 1.29/04 output).
397    // `unit: "point"`: drawn, so a crop is cut at the render density (2011.13011).
398    for ext in &["ai", "pdf", "ps", "eps", "epsi", "epsf"] {
399      type_properties.insert(ext.to_string(), TypeProperties {
400        destination_type: Some("png".to_string()),
401        transparent: true,
402        prescale: true,
403        ncolors: Some("400%".to_string()),
404        quality: Some(90),
405        unit: "point".to_string(),
406        ..Default::default()
407      });
408    }
409    for ext in &["jpg", "jpeg"] {
410      type_properties.insert(ext.to_string(), TypeProperties {
411        destination_type: Some(ext.to_string()),
412        ncolors: Some("400%".to_string()),
413        unit: "pixel".to_string(),
414        ..Default::default()
415      });
416    }
417    type_properties.insert("gif".to_string(), TypeProperties {
418      destination_type: Some("gif".to_string()),
419      transparent: true,
420      ncolors: Some("400%".to_string()),
421      unit: "pixel".to_string(),
422      ..Default::default()
423    });
424    type_properties.insert("png".to_string(), TypeProperties {
425      destination_type: Some("png".to_string()),
426      transparent: true,
427      ncolors: Some("400%".to_string()),
428      unit: "pixel".to_string(),
429      ..Default::default()
430    });
431    type_properties.insert("svg".to_string(), TypeProperties {
432      destination_type: Some("svg".to_string()),
433      raster: Some(false),
434      desirability: 11,
435      ..Default::default()
436    });
437
438    Graphics {
439      name: "Graphics".to_string(),
440      dpi,
441      magnify: 1.0,
442      zoomout: 1.0,
443      trivial_scaling,
444      graphics_types: vec![
445        "svg",
446        "png",
447        "gif",
448        "jpg",
449        "jpeg",
450        "eps",
451        "epsi",
452        "epsf",
453        "ps",
454        "postscript",
455        "ai",
456        "pdf",
457      ]
458      .into_iter()
459      .map(String::from)
460      .collect(),
461      type_properties,
462      background: "#FFFFFF".to_string(),
463      svg_threshold_kb: 0,
464      cache_policy: crate::graphics_cache::CachePolicy::default(),
465      names: ResourceNames::default(),
466    }
467  }
468
469  /// Name generated resources `<prefix>N` instead of `xN` (Perl's `resource_prefix` option, `Post.pm` L195).
470  #[must_use]
471  pub fn with_resource_prefix(mut self, prefix: &str) -> Self {
472    self.names.prefix = Some(prefix.to_string());
473    self
474  }
475
476  /// Choose whether conversions may be served from the shared,
477  /// host-persistent graphics cache. Defaults to
478  /// [`CachePolicy::Shared`](crate::graphics_cache::CachePolicy::Shared).
479  ///
480  /// Pass [`CachePolicy::Bypass`](crate::graphics_cache::CachePolicy::Bypass)
481  /// when the conversion *itself* is what matters — e.g. a test asserting
482  /// on how many converter subprocesses ran, which a cache hit would
483  /// silently satisfy without running any. The builder returns `self` so
484  /// it composes with `Graphics::new(...)`.
485  #[must_use]
486  pub fn with_cache_policy(mut self, policy: crate::graphics_cache::CachePolicy) -> Self {
487    self.cache_policy = policy;
488    self
489  }
490
491  /// Enable the vector-SVG path for PDFs under `kb` KB. When `kb == 0`
492  /// (default), the SVG path is fully disabled and all PDFs go through
493  /// ImageMagick `convert`. The builder returns `self` so it composes with
494  /// `Graphics::new(...)`.
495  pub fn with_svg_threshold_kb(mut self, kb: u32) -> Self {
496    self.svg_threshold_kb = kb;
497    self
498  }
499
500  /// Find the graphics source file for a node; a confined conversion looks only inside its roots ([`readable`]).
501  ///
502  /// Port of `Graphics::findGraphicFile`. A file `ours` names (an earlier run's output in the destination) ranks below
503  /// every other: converted in place, our `<stem>.svg` outranked the author's PDF (OD #1157 (7)).
504  fn find_graphic_file(
505    &self,
506    _doc: &PostDocument,
507    node: &Node,
508    search_paths: &[String],
509    ours: &dyn Fn(&str) -> bool,
510  ) -> Option<String> {
511    let source = node.get_attribute("graphic")?;
512
513    // Check candidates attribute first (comma-separated list of found files)
514    // Perl: findGraphicFile checks each candidate path, resolving relative to search paths.
515    if let Some(candidates) = node.get_attribute("candidates") {
516      // Pick the best candidate by desirability
517      let mut best: Option<(String, (bool, i32))> = None;
518      for path in candidates.split(',') {
519        let path = path.trim();
520        if path.is_empty() {
521          continue;
522        }
523        // Try the path directly, then in each search directory
524        let resolved = if readable(path) {
525          Some(path.to_string())
526        } else {
527          search_paths.iter().find_map(|sp| {
528            let candidate = format!("{}/{}", sp, path);
529            if readable(&candidate) {
530              Some(candidate)
531            } else {
532              None
533            }
534          })
535        };
536        if let Some(resolved_path) = resolved {
537          let ext = Path::new(&resolved_path)
538            .extension()
539            .and_then(|e| e.to_str())
540            .unwrap_or("")
541            .to_lowercase();
542          // Skip candidates whose extension is NOT a known graphics type.
543          // Perl's `findGraphicFile` re-searches with `types =>
544          // getGraphicsSourceTypes` (Post/Graphics.pm L150-151), which excludes
545          // non-graphics types — notably `.pdf_tex`, the inkscape "PDF+LaTeX"
546          // wrapper that is `\input`'d (it itself does `\includegraphics{grid}`),
547          // NOT a raster/vector image. `image_candidates` is deliberately
548          // unfiltered (matching Perl's `types => ['*']`), so a sibling
549          // `grid.pdf_tex` lands in the `candidates` attribute next to the real
550          // `grid.pdf`/`grid.eps`; without this filter it sorts first and gets
551          // picked, then fails to convert (`pdf_tex` has no destination_type).
552          // Empty ext is kept (the file may carry no extension but known content).
553          // Witness 1907.12308 (`\input{grid.pdf_tex}` → `\includegraphics{grid}`).
554          if !ext.is_empty() && !self.graphics_types.iter().any(|t| t == &ext) {
555            continue;
556          }
557          let props = self.type_properties.get(&ext);
558          let d = props.map(|p| p.desirability as i32).unwrap_or(0);
559          let is_same_type = props
560            .and_then(|p| p.destination_type.as_ref())
561            .map(|dt| dt == &ext)
562            .unwrap_or(false);
563          let desirability = (!ours(&resolved_path), if is_same_type { 10 } else { d });
564          if best.as_ref().is_none_or(|(_, bd)| desirability > *bd) {
565            best = Some((resolved_path, desirability));
566          }
567        }
568      }
569      if let Some((path, _)) = best {
570        return Some(path);
571      }
572    }
573
574    // Search for the file in search paths
575    let path = Path::new(&source);
576    let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or(&source);
577    let dir = path.parent().and_then(|p| p.to_str()).unwrap_or("");
578
579    let file_base = if dir.is_empty() {
580      name.to_string()
581    } else {
582      format!("{}/{}", dir, name)
583    };
584
585    // Try each type in search paths
586    let mut best_desirability = (false, -1);
587    let mut best_path: Option<String> = None;
588
589    let types: Vec<String> = self
590      .graphics_types
591      .iter()
592      .flat_map(|t| vec![t.clone(), t.to_uppercase()])
593      .collect();
594
595    for search_path in search_paths {
596      // Try without extension first (source might already have one)
597      let candidate = if search_path.is_empty() {
598        source.clone()
599      } else {
600        format!("{}/{}", search_path, source)
601      };
602      if readable(&candidate) {
603        let ext = Path::new(&candidate)
604          .extension()
605          .and_then(|e| e.to_str())
606          .unwrap_or("")
607          .to_lowercase();
608        let props = self.type_properties.get(&ext);
609        let d = (
610          !ours(&candidate),
611          props.map(|p| p.desirability as i32).unwrap_or(5),
612        );
613        if d > best_desirability {
614          best_desirability = d;
615          best_path = Some(candidate);
616        }
617      }
618      // Try each extension
619      for ext in &types {
620        let candidate = format!("{}/{}.{}", search_path, file_base, ext);
621        if readable(&candidate) {
622          let props = self.type_properties.get(&ext.to_lowercase());
623          let d = props.map(|p| p.desirability as i32).unwrap_or(0);
624          let is_same_type = props
625            .and_then(|p| p.destination_type.as_ref())
626            .map(|dt| dt == &ext.to_lowercase())
627            .unwrap_or(false);
628          let desirability = (!ours(&candidate), if is_same_type { 10 } else { d });
629          if desirability > best_desirability {
630            best_desirability = desirability;
631            best_path = Some(candidate);
632          }
633        }
634      }
635    }
636    if best_path.is_some() {
637      return best_path;
638    }
639
640    // kpathsea-parity casefold fallback (`texmf_casefold_search`, default ON
641    // since TL2018): pdflatex finds `images/NLPOptNet.jpg` even when the
642    // file on disk is `images/NLPOPtNet.jpg`, so an author case-typo that
643    // builds fine on arXiv must not lose the figure here (witness
644    // 2605.00260, Figure 1). Like kpathsea, this fires only AFTER every
645    // exact search misses; only the filename component is folded, and an
646    // ambiguous directory (two case-variants) refuses to guess.
647    for sp in std::iter::once(String::new()).chain(search_paths.iter().cloned()) {
648      let cand = if sp.is_empty() {
649        source.clone()
650      } else {
651        format!("{}/{}", sp, source)
652      };
653      if let Some(found) = Self::casefold_resolve(&cand, &source) {
654        Info!(
655          "graphics",
656          "casefold",
657          "Graphic '{}' resolved case-insensitively to '{}' (kpathsea casefold parity)",
658          source,
659          found
660        );
661        return Some(found);
662      }
663    }
664    None
665  }
666
667  /// Case-insensitive filename resolution within the path's directory.
668  /// Returns the unique match, or None when absent or ambiguous. Confined, the match is judged as the system opens it
669  /// (`lsec.png` for `LSEC.png`, a link out of the folder): a refused one is the graphic `source`'s refusal.
670  fn casefold_resolve(path: &str, source: &str) -> Option<String> {
671    if !latexml_core::util::pathname::read_allowed(path) {
672      return None;
673    }
674    let p = Path::new(path);
675    if p.exists() {
676      return Some(path.to_string());
677    }
678    let parent = match p.parent() {
679      Some(d) if !d.as_os_str().is_empty() => d,
680      _ => Path::new("."),
681    };
682    let want = p.file_name()?.to_str()?;
683    let mut hit: Option<String> = None;
684    for entry in std::fs::read_dir(parent).ok()? {
685      let entry = entry.ok()?;
686      let name = entry.file_name();
687      let Some(name) = name.to_str() else { continue };
688      if name.eq_ignore_ascii_case(want) && entry.path().is_file() {
689        if hit.is_some() {
690          return None; // ambiguous — never guess between case-variants
691        }
692        hit = Some(entry.path().to_string_lossy().to_string());
693      }
694    }
695    if hit
696      .as_deref()
697      .is_some_and(|hit| !latexml_core::util::pathname::read_allowed(hit))
698    {
699      latexml_core::util::pathname::refuse(source);
700      return None;
701    }
702    hit
703  }
704
705  /// Set the image source attributes on a graphics node.
706  ///
707  /// Port of `Graphics::setGraphicSrc`.
708  fn set_graphic_src(node: &mut Node, src: &str, width: Option<u32>, height: Option<u32>) {
709    // A `:` in the first segment reads as a URL scheme (`png:c.svg` from a source's `png:c.pdf`): led by `./`, the file.
710    let src = match src.split('/').next() {
711      Some(first) if first.contains(':') => format!("./{src}"),
712      _ => src.to_string(),
713    };
714    node.set_attribute("imagesrc", &src).ok();
715    // HTML width/height are in pixels (unitless)
716    if let Some(w) = width {
717      node.set_attribute("imagewidth", &w.to_string()).ok();
718    }
719    if let Some(h) = height {
720      node.set_attribute("imageheight", &h.to_string()).ok();
721    }
722    // Set aspect ratio class
723    if let (Some(w), Some(h)) = (width, height) {
724      let class = if w as f64 > 1.24 * h as f64 {
725        "ltx_img_landscape"
726      } else if h as f64 > 1.24 * w as f64 {
727        "ltx_img_portrait"
728      } else {
729        "ltx_img_square"
730      };
731      let existing = node.get_attribute("class").unwrap_or_default();
732      let new_class = if existing.is_empty() {
733        class.to_string()
734      } else {
735        format!("{} {}", existing, class)
736      };
737      node.set_attribute("class", &new_class).ok();
738      // brucemiller/LaTeXML#2392: also emit the REQUESTED aspect ratio explicitly.
739      // The coarse `ltx_img_{square,portrait,landscape}` bucket is enough to pick a
740      // flex layout, but the flex CSS caps `max-width`, changing the width and not
741      // the height — so a square picture renders as a vertical ellipsoid. An
742      // `aspect-ratio:W/H` on the img lets a width-only cap (paired with
743      // `height:auto` in the flex rules) preserve the ratio, and the *requested*
744      // ratio (from `\includegraphics`), not the file's. Beyond Perl 0.8.8, which
745      // emits no aspect-ratio (OXIDIZED_DESIGN #139).
746      let ar = format!("aspect-ratio:{w}/{h}");
747      let cssstyle = match node.get_attribute("cssstyle") {
748        Some(s) if !s.is_empty() => format!("{s};{ar}"),
749        _ => ar,
750      };
751      node.set_attribute("cssstyle", &cssstyle).ok();
752    }
753  }
754
755  /// Find graphicspath from processing instructions.
756  fn find_graphics_paths(&self, doc: &PostDocument) -> Vec<String> {
757    // Perl `Post/Graphics.pm:91`:
758    //   [map { pathname_canonical($_) }
759    //    $self->findGraphicsPaths($doc), $doc->getSearchPaths]
760    // — the search paths are the union of graphicspath PIs PLUS the
761    // document's own search paths (typically the source directory). The
762    // prior Rust port included only the PI half, which left every paper
763    // with raw `.ps`/`.eps`/etc. files in the source directory (and no
764    // explicit `\graphicspath{...}`) emitting `Error:expected:source`
765    // for every figure, even though the source files are present.
766    // Driver: astro-ph0002170 (8 .ps figures in the zip, all "not found").
767    use std::sync::LazyLock;
768    static GRAPHICSPATH_RE: LazyLock<regex::Regex> =
769      LazyLock::new(|| regex::Regex::new(r#"^\s*graphicspath\s*=\s*[\"'](.*?)[\"']\s*$"#).unwrap());
770    let mut paths = Vec::new();
771    for pi in doc.findnodes("//processing-instruction('latexml')") {
772      let text = pi.get_content();
773      if let Some(cap) = GRAPHICSPATH_RE.captures(&text)
774        && latexml_core::util::pathname::search_dir_allowed(&cap[1], &cap[1])
775      {
776        paths.push(cap[1].to_string());
777      }
778    }
779    paths.extend(doc.get_search_paths().iter().cloned());
780    paths
781  }
782
783  /// Read a named parameter from processing instructions.
784  /// Port of Perl's `Graphics::getParameter`.
785  /// Checks both direct PI (`<?latexml DPI="100"?>`) and
786  /// latexml.sty package options (`<?latexml package="latexml" options="magnify=1.2"?>`).
787  fn get_parameter(&self, doc: &PostDocument, param: &str) -> Option<f64> {
788    let direct_re = regex::Regex::new(&format!(
789      r#"^\s*{}\s*=\s*[\"']?([\d.]+)[\"']?\s*$"#,
790      regex::escape(param)
791    ))
792    .ok()?;
793    let options_re =
794      regex::Regex::new(r#"package\s*=\s*[\"']latexml[\"'].*options\s*=\s*[\"'](.*?)[\"']"#)
795        .ok()?;
796    let param_in_options_re =
797      regex::Regex::new(&format!(r#"\b{}\s*=\s*([\d.]+)"#, regex::escape(param))).ok()?;
798
799    for pi in doc.findnodes("//processing-instruction('latexml')") {
800      let text = pi.get_content();
801      if let Some(cap) = direct_re.captures(&text) {
802        return cap[1].parse().ok();
803      }
804      if let Some(cap) = options_re.captures(&text) {
805        if let Some(inner) = param_in_options_re.captures(&cap[1]) {
806          return inner[1].parse().ok();
807        }
808      }
809    }
810    None
811  }
812
813  /// The pixels per inch a size is shown at: DPI × magnify / zoomout, each from the document's processing
814  /// instructions (set by latexml.sty), else the processor's (Perl `transformGraphic`, `Post/Graphics.pm` L232-236).
815  /// DPI defaults to the CSS inch's 96 px (OXIDIZED_DESIGN_DIVERGENCES #1189; Perl `$DPI = 100`, Util/Image.pm:37).
816  fn effective_dpi(&self, doc: &PostDocument) -> u32 {
817    let dpi = self
818      .get_parameter(doc, "DPI")
819      .map(|v| v as u32)
820      .or(self.dpi)
821      .unwrap_or(96);
822    let magnify = self.get_parameter(doc, "magnify").unwrap_or(self.magnify);
823    let zoomout = self.get_parameter(doc, "zoomout").unwrap_or(self.zoomout);
824    ((dpi as f64) * magnify / zoomout) as u32
825  }
826
827  /// Read image dimensions using imagesize crate.
828  /// Returns (width, height) in pixels.
829  fn read_image_dimensions(path: &str) -> Option<(u32, u32)> {
830    match imagesize::size(path) {
831      Ok(dim) => Some((dim.width as u32, dim.height as u32)),
832      Err(_) => None,
833    }
834  }
835
836  /// Read a *source* graphic's intrinsic dimensions, dispatching on type.
837  ///
838  /// Port of Perl `Util/Image.pm:image_size` (L86-97), which sizes ANY
839  /// supported source type — there Image::Magick covers SVG. The
840  /// `imagesize` crate is raster-only, so SVG dispatches to
841  /// `read_svg_dimensions` (already the SVG-dims reader on the PDF→SVG
842  /// convert path). Without this, a web-native SVG going through the
843  /// trivial-copy path got NO imagewidth/imageheight and rendered at
844  /// intrinsic size, ignoring `\includegraphics[width=…]` (issue 498).
845  fn read_source_dimensions(path: &str) -> Option<(u32, u32)> {
846    let is_svg = Path::new(path)
847      .extension()
848      .and_then(|e| e.to_str())
849      .is_some_and(|e| e.eq_ignore_ascii_case("svg"));
850    if is_svg {
851      Self::read_svg_dimensions(path)
852    } else {
853      Self::read_image_dimensions(path)
854    }
855  }
856
857  /// Apply the graphicx options to a measured pixel size.
858  ///
859  /// Delegates to the shared algebra in `latexml_core::util::image` — the port
860  /// of Perl `image_graphicx_size` (`Util/Image.pm` L221-256) — so the pixel
861  /// count written into the HTML and the box the engine reserved come from one
862  /// implementation. Pixel space, hence `DPI/72.27` per bp and Perl's `ceil` at
863  /// each step.
864  ///
865  /// Two behaviours changed when this stopped being its own implementation, both
866  /// toward Perl:
867  ///
868  /// * **Option values now go through `to_bp` first.** The local parser stripped
869  ///   a `pt` suffix and used the number as-is, skipping Perl's pt->bp step, so
870  ///   every explicit size came out up to one pixel wider than the engine's box
871  ///   for the same request (`width=100pt`: 139 px here vs 138 in the engine).
872  ///   It also silently ignored every unit that was not `pt`/`px`.
873  /// * **Rotation is the true bounding box**, not a 90/270 axis swap. That
874  ///   matches what `convert -rotate` actually writes to disk for an oblique
875  ///   angle. It is ordered relative to scaling by key order, as Perl and
876  ///   graphicx do — see `parse_graphicx_options`. Witness for the rotation
877  ///   mattering at all: 1303.5091 Figs 5-7, `[angle=90,scale=0.75]`, which
878  ///   rendered upside-down before any of it — still correct here: a uniform
879  ///   scale commutes with a rotation, so its order does not change the box.
880  ///
881  /// Witness for the width-only path: astro-ph0005397 Fig 11 (sfh_burst), where
882  /// feeding the unscaled raw height back through displayed square sources as
883  /// 4:1 ribbons.
884  fn apply_graphicx_transforms(raw_w: u32, raw_h: u32, options: &str, dpi: u32) -> (u32, u32) {
885    let ops = latexml_core::util::image::parse_graphicx_options(options);
886    Self::apply_graphicx_op_list(raw_w, raw_h, (72.0, 72.0), &ops, dpi)
887  }
888
889  /// [`Self::apply_graphicx_transforms`] over an already-parsed op list, for pixels at `ppi` per inch: shown at `dpi`,
890  /// the box pdfTeX sets (the pixels at their own density, OD #1188) is `dpi` px per inch, and so is an option's bp
891  /// (`dpi / 72`; Perl's `DPI/72.27`, Util/Image.pm:223, takes the bp for a pt, KNOWN_PERL_ERRORS #1142).
892  fn apply_graphicx_op_list(
893    raw_w: u32,
894    raw_h: u32,
895    ppi: (f64, f64),
896    ops: &[GraphicxOp],
897    dpi: u32,
898  ) -> (u32, u32) {
899    let dpi = dpi as f64;
900    let (w, h) = latexml_core::util::image::apply_graphicx_ops(
901      raw_w as f64 * dpi / ppi.0,
902      raw_h as f64 * dpi / ppi.1,
903      ops,
904      dpi / 72.0,
905      true,
906    );
907    // The nearest pixel; an image attribute of 0 is useless to a browser, so at least one.
908    (w.round().max(1.0) as u32, h.round().max(1.0) as u32)
909  }
910
911  /// Content fingerprint for graphics-asset deduplication: the SHA-256 of the
912  /// file's bytes ([`crate::graphics_cache::SourceDigest`], whose state also
913  /// keys the conversion cache, so a converted source is read once). Returns
914  /// `None` if the file can't be opened.
915  ///
916  /// Purpose: byte-identical files `x1.pdf` and `x2.pdf` (e.g. shared
917  /// figures across subsections, or duplicated by the author) should
918  /// share one rasterized PNG/SVG in the output bundle. Both `<img>`
919  /// tags then reference the first-seen filename's stem — saves both
920  /// conversion time AND output-bundle disk space.
921  fn digest_file_content(path: &str) -> Option<crate::graphics_cache::SourceDigest> {
922    crate::graphics_cache::SourceDigest::of_file(Path::new(path))
923  }
924
925  /// The graphicx ops that change a raster's pixels, in order: a
926  /// `trim`/`viewport` crop and an `angle=` turn — Perl's non-trivial ops
927  /// (`image_graphicx_is_trivial`, `Util/Image.pm` L282-284), less `page`,
928  /// which only picks the source page, and `reflect`, which Rust never applied.
929  fn physical_ops(options: &str) -> Vec<GraphicxOp> {
930    latexml_core::util::image::parse_graphicx_options(options)
931      .into_iter()
932      .filter(|op| match op {
933        // `trim=0 0 0 0` (common with `clip`) and negative amounts crop nothing.
934        GraphicxOp::Trim { l, b, r, t } => [l, b, r, t].iter().any(|v| **v > 0.0),
935        GraphicxOp::Clip { .. } => true,
936        GraphicxOp::Rotate(angle) => angle.abs() > 0.5,
937        _ => false,
938      })
939      .collect()
940  }
941
942  /// Crop a vector render of a PDF page to a `trim`/`viewport` box: the
943  /// vector counterpart of [`Self::transform_raster_inplace`]'s `-crop`. The
944  /// render's root `viewBox` spans the page in bp (`mutool`, `pdftocairo`), so
945  /// the box narrows the `viewBox`, and `width`/`height` shrink with it in
946  /// their own units. Clamped to the page, never padded, as the raster crop.
947  /// `Ok(None)` when the box keeps the whole page; `Err` when the root lacks a
948  /// usable `viewBox`, `width` or `height`, and the caller renders a raster to
949  /// crop instead. Witness 2605.06510 (`trim=0cm 0.25cm 0cm 0.1cm,clip` on PDF legends).
950  fn crop_svg(text: &str, op: &GraphicxOp) -> Result<Option<String>, String> {
951    use latexml_core::util::image::{svg_attr_value, svg_root_tag};
952    let tag = svg_root_tag(text).ok_or("no <svg> root")?;
953    let view: Vec<f64> = svg_attr_value(tag, "viewBox")
954      .ok_or("no viewBox")?
955      .split(|c: char| c.is_whitespace() || c == ',')
956      .filter(|v| !v.is_empty())
957      .filter_map(|v| v.parse().ok())
958      .collect();
959    let [vx, vy, vw, vh] = view[..] else {
960      return Err("unreadable viewBox".to_string());
961    };
962    // The kept box, from the page's top-left corner, in bp.
963    let (x0, y0, x1, y1) = match *op {
964      GraphicxOp::Trim { l, b, r, t } => (l.max(0.0), t.max(0.0), vw - r.max(0.0), vh - b.max(0.0)),
965      GraphicxOp::Clip { l, b, r, t } => {
966        (l.max(0.0), (vh - t).max(0.0), r.min(vw), (vh - b).min(vh))
967      },
968      _ => return Ok(None),
969    };
970    if x1 - x0 <= 0.0 || y1 - y0 <= 0.0 {
971      return Err("the box keeps nothing".to_string());
972    }
973    if x0 <= 0.0 && y0 <= 0.0 && x1 >= vw && y1 >= vh {
974      return Ok(None);
975    }
976    let number = |v: f64| {
977      let v = format!("{v:.4}");
978      v.trim_end_matches('0').trim_end_matches('.').to_string()
979    };
980    // `width`/`height` scaled in their own unit (`432` or `432pt`).
981    let scaled = |name: &str, ratio: f64| -> Option<String> {
982      let raw = svg_attr_value(tag, name)?.trim();
983      let split = raw
984        .find(|c: char| c.is_ascii_alphabetic() || c == '%')
985        .unwrap_or(raw.len());
986      let (num, unit) = raw.split_at(split);
987      if unit == "%" {
988        return None;
989      }
990      Some(format!(
991        "{}{unit}",
992        number(num.parse::<f64>().ok()? * ratio)
993      ))
994    };
995    let width = scaled("width", (x1 - x0) / vw).ok_or("no usable width")?;
996    let height = scaled("height", (y1 - y0) / vh).ok_or("no usable height")?;
997    let view_box = [vx + x0, vy + y0, x1 - x0, y1 - y0].map(number).join(" ");
998    Self::with_svg_root_attrs(text, &[
999      ("viewBox", view_box),
1000      ("width", width),
1001      ("height", height),
1002    ])
1003    .map(Some)
1004  }
1005
1006  /// Size a vector render's root to its display size in pixels, as Perl scales its raster to it (`Util/Image.pm`
1007  /// L382-389): `width`/`height` set, the `viewBox` kept (made from the old size when the root has none). A drawing
1008  /// graphicx scales x and y apart (`stretch`) fills the box (`preserveAspectRatio="none"`); any other keeps its ratio.
1009  fn size_svg(text: &str, width: u32, height: u32, stretch: bool) -> Result<String, String> {
1010    use latexml_core::util::image::{svg_attr_len_px, svg_attr_value, svg_root_tag};
1011    let tag = svg_root_tag(text).ok_or("no <svg> root")?;
1012    let mut attrs = vec![("width", width.to_string()), ("height", height.to_string())];
1013    if stretch {
1014      attrs.push(("preserveAspectRatio", "none".to_string()));
1015    }
1016    if svg_attr_value(tag, "viewBox").is_none() {
1017      let w = svg_attr_len_px(tag, "width").ok_or("no viewBox and no usable width")?;
1018      let h = svg_attr_len_px(tag, "height").ok_or("no viewBox and no usable height")?;
1019      attrs.push(("viewBox", format!("0 0 {w} {h}")));
1020    }
1021    Self::with_svg_root_attrs(text, &attrs)
1022  }
1023
1024  /// `text` with its root `<svg>` start tag given `attrs`: each value replaced, or appended when absent.
1025  fn with_svg_root_attrs(text: &str, attrs: &[(&str, String)]) -> Result<String, String> {
1026    use latexml_core::util::image::{svg_attr_value, svg_root_tag};
1027    let tag = svg_root_tag(text).ok_or("no <svg> root")?;
1028    let at = tag.as_ptr() as usize - text.as_ptr() as usize;
1029    let mut new_tag = tag.to_string();
1030    for (name, value) in attrs {
1031      match svg_attr_value(&new_tag, name) {
1032        Some(old) => {
1033          let start = old.as_ptr() as usize - new_tag.as_ptr() as usize;
1034          new_tag.replace_range(start..start + old.len(), value);
1035        },
1036        None => {
1037          let end = new_tag.trim_end().trim_end_matches('/').trim_end().len();
1038          new_tag.insert_str(end, &format!(r#" {name}="{value}""#));
1039        },
1040      }
1041    }
1042    Ok(format!(
1043      "{}{new_tag}{}",
1044      &text[..at],
1045      &text[at + tag.len()..]
1046    ))
1047  }
1048
1049  /// Crop and turn the raster at `dest` in one `convert` run, as Perl's
1050  /// `image_graphicx_complex` does with `Crop` then `Rotate` (`Util/Image.pm`
1051  /// L390-418; witness 2510.17772): the crop first, whatever the key order,
1052  /// and the graphicx angle
1053  /// (counter-clockwise) negated for `-rotate` (clockwise). `px_per_bp` is the
1054  /// raster's own pixels per bp. Returns the cropped size before the turn —
1055  /// the size the remaining (scaling and turning) ops then apply to — or
1056  /// `None` when nothing was cropped.
1057  ///
1058  /// The result replaces `dest` by rename, never by writing through it: a `dest`
1059  /// an older binary wrote may be a hard link to a graphics-cache entry.
1060  fn transform_raster_inplace(
1061    dest: &str,
1062    ops: &[GraphicxOp],
1063    px_per_bp: f64,
1064  ) -> Result<Option<(u32, u32)>, String> {
1065    take_converter_diag(); // this run's diagnostic only
1066    let (w, h) = Self::read_image_dimensions(dest)
1067      .ok_or_else(|| format!("couldn't read the size of {dest}"))?;
1068    let crop = ops
1069      .iter()
1070      .find_map(|op| latexml_core::util::image::graphicx_crop_rect(w, h, op, px_per_bp));
1071    let angle: f64 = ops
1072      .iter()
1073      .map(|op| {
1074        if let GraphicxOp::Rotate(a) = op {
1075          *a
1076        } else {
1077          0.0
1078        }
1079      })
1080      .sum();
1081    if crop.is_none() && angle.abs() <= 0.5 {
1082      return Ok(None);
1083    }
1084    // `convert` picks the output format from the extension, which the staged name keeps last.
1085    let staged = crate::writer::Staged::beside(Path::new(dest));
1086    let tmp = staged.path();
1087    let mut cmd = std::process::Command::new(im_convert_program());
1088    cmd.arg(dest);
1089    if let Some((x, y, cw, ch)) = crop {
1090      // `+repage` first as well: a PNG `oFFs` or GIF page offset would
1091      // otherwise place the crop on the virtual canvas.
1092      cmd
1093        .arg("+repage")
1094        .arg("-crop")
1095        .arg(format!("{cw}x{ch}+{x}+{y}"))
1096        .arg("+repage");
1097    }
1098    if angle.abs() > 0.5 {
1099      cmd.arg("-rotate").arg(format!("{}", -angle));
1100    }
1101    cmd.arg(tmp);
1102    let timeout = std::time::Duration::from_secs(Self::convert_timeout_secs());
1103    let ran = Self::run_with_timeout(cmd, timeout)
1104      .map(|status| status.success())
1105      .unwrap_or(false);
1106    if !ran || !tmp.exists() || staged.install(Path::new(dest)).is_err() {
1107      let why = take_converter_diag().unwrap_or_else(|| "no converter diagnostic".to_string());
1108      return Err(format!(
1109        "`{}` could not crop or turn {dest}: {why}",
1110        im_convert_program()
1111      ));
1112    }
1113    Ok(crop.map(|(_, _, cw, ch)| (cw, ch)))
1114  }
1115
1116  /// The directories a page's images are placed by: the search paths, the source directory, the destination's and
1117  /// the site directory (Perl `Post.pm` L698-706: the destination's unless `--sitedirectory`).
1118  fn page_dirs(&self, doc: &PostDocument) -> PageDirs {
1119    let mut search_paths = self.find_graphics_paths(doc);
1120    search_paths.extend(doc.get_search_paths().iter().cloned());
1121    // Also add source directory
1122    let source_dir = doc.get_source_directory().to_string();
1123    if !source_dir.is_empty() && !search_paths.contains(&source_dir) {
1124      search_paths.push(source_dir.clone());
1125    }
1126    // Add current directory as fallback (never for a confined conversion, unless it is one of the roots)
1127    if !search_paths.iter().any(|p| p == ".") && latexml_core::util::pathname::cwd_allowed() {
1128      search_paths.push(".".to_string());
1129    }
1130    let dest_dir = doc.get_destination_directory().unwrap_or(".").to_string();
1131    let site_dir = doc.get_site_directory().unwrap_or(&dest_dir).to_string();
1132    PageDirs {
1133      search_paths,
1134      source_dir,
1135      dest_dir,
1136      site_dir,
1137      cache_dir: doc.get_destination_directory().map(String::from),
1138    }
1139  }
1140
1141  /// Name the images of one page before any page is rendered, writing nothing; [`Self::commit_names`] then stores the
1142  /// names of every planned page, in page order. The serial and the parallel render (`render_workers.rs`) both look
1143  /// them up, so a page's names never depend on which process renders it, nor on CrossRef's copies of other pages'
1144  /// titles into its navigation, which meet an image before its own page does (issue 995). Whether the page has
1145  /// images to name.
1146  pub fn plan_names(&mut self, doc: &PostDocument) -> bool {
1147    let nodes = self.to_process(doc);
1148    if nodes.is_empty() {
1149      return false;
1150    }
1151    let dirs = self.page_dirs(doc);
1152    let mut names = std::mem::take(&mut self.names);
1153    let requests = self
1154      .describe(doc, &nodes, &dirs, &mut names, self.effective_dpi(doc))
1155      .iter()
1156      .filter_map(|desc| desc.request().cloned())
1157      .collect();
1158    let cache = names.cache.clone().unwrap_or_else(|| doc.cache().clone());
1159    names.pending.push(PendingPage { cache, dirs, requests });
1160    names.planning = true;
1161    self.names = names;
1162    true
1163  }
1164
1165  /// Whether a page's names were planned ([`Self::plan_names`]).
1166  pub fn planned(&self) -> bool { self.names.planning }
1167
1168  /// Store the planned pages' names: one transaction per destination directory, so runs writing into one folder at
1169  /// once never hand out one name twice.
1170  pub fn commit_names(&mut self) {
1171    let names = &mut self.names;
1172    names.planning = true;
1173    let pending = std::mem::take(&mut names.pending);
1174    let prefix = names.prefix.clone().unwrap_or_else(|| "x".to_string());
1175    let mut done: Vec<String> = Vec::new();
1176    for first in &pending {
1177      let dir = &first.dirs.dest_dir;
1178      if done.contains(dir) {
1179        continue;
1180      }
1181      done.push(dir.clone());
1182      let pages: Vec<Vec<Request>> = pending
1183        .iter()
1184        .filter(|p| p.dirs.dest_dir == *dir)
1185        .map(|p| p.requests.clone())
1186        .collect();
1187      let resolved = Self::resolve_names(
1188        &first.cache,
1189        &first.dirs,
1190        &prefix,
1191        &pages,
1192        self.cache_policy,
1193      );
1194      for (requests, resolved) in pages.iter().zip(resolved) {
1195        for (request, resolved) in requests.iter().zip(resolved) {
1196          names
1197            .planned
1198            .insert((dir.clone(), request.key.clone()), resolved.name);
1199        }
1200      }
1201    }
1202  }
1203
1204  /// The planned names, as (destination directory, key, destination, vector render), for the render workers.
1205  pub fn planned_names(&self) -> Vec<(String, String, String, Option<String>)> {
1206    let mut list: Vec<_> = self
1207      .names
1208      .planned
1209      .iter()
1210      .map(|((dir, key), name)| {
1211        (
1212          dir.clone(),
1213          key.clone(),
1214          name.dest.clone(),
1215          name.alt.clone(),
1216        )
1217      })
1218      .collect();
1219    list.sort();
1220    list
1221  }
1222
1223  /// A render worker's Graphics: the parent's planned names ([`Self::planned_names`]).
1224  #[must_use]
1225  pub fn with_planned_names(mut self, list: Vec<(String, String, String, Option<String>)>) -> Self {
1226    self.names.planning = true;
1227    self.names.planned = list
1228      .into_iter()
1229      .map(|(dir, key, dest, alt)| ((dir, key), ResourceName { dest, alt }))
1230      .collect();
1231    self
1232  }
1233
1234  /// Name images in `cache`, the run's (every page's [`PostDocument::cache`] is the run's too, unless a page was made
1235  /// apart from the run's options).
1236  #[must_use]
1237  pub fn with_doc_cache(mut self, cache: DocCache) -> Self {
1238    self.names.cache = Some(cache);
1239    self
1240  }
1241
1242  /// What each node needs: its source, and the request that names its image (Perl `transformGraphic`'s key,
1243  /// `Post/Graphics.pm` L240-245, with the source's content digest). `dpi` is the page's ([`Self::effective_dpi`]).
1244  fn describe(
1245    &self,
1246    doc: &PostDocument,
1247    nodes: &[Node],
1248    dirs: &PageDirs,
1249    names: &mut ResourceNames,
1250    dpi: u32,
1251  ) -> Vec<NodeDesc> {
1252    let PageDirs {
1253      search_paths,
1254      source_dir,
1255      dest_dir,
1256      site_dir,
1257      ..
1258    } = dirs;
1259    let mut descs = Vec::with_capacity(nodes.len());
1260    let cache = names.cache.clone().unwrap_or_else(|| doc.cache().clone());
1261    let ours = |path: &str| Self::our_output(&cache, dirs, path);
1262    for node in nodes {
1263      let options = node.get_attribute("options").unwrap_or_default();
1264      let Some(source) = self.find_graphic_file(doc, node, search_paths, &ours) else {
1265        let graphic = node
1266          .get_attribute("graphic")
1267          .unwrap_or_else(|| "none".to_string());
1268        descs.push(NodeDesc::NotFound(graphic));
1269        continue;
1270      };
1271      let src_ext = Path::new(&source)
1272        .extension()
1273        .and_then(|e| e.to_str())
1274        .unwrap_or("")
1275        .to_lowercase();
1276      // A single-page format has no page to select, as pdfTeX ignores `page=` on a PNG: copied as it is (#791, OD #1026).
1277      const SINGLE_PAGE: &[&str] = &["svg", "png", "jpg", "jpeg"];
1278      let page =
1279        Self::parse_page_option(&options).filter(|_| !SINGLE_PAGE.contains(&src_ext.as_str()));
1280      let props = self.type_properties.get(&src_ext).cloned();
1281      // Robustness guard (surpass-Perl; user directive 2026-06-22). A source
1282      // type with no explicit `destination_type` defaults to a WEB-NATIVE
1283      // target: keep web-native sources (svg/png/gif/jpg/jpeg) as-is, but
1284      // rasterize anything else to `png`. This guarantees a non-web-native
1285      // source is ALWAYS routed through Plan::Convert and never Plan::Copy'd
1286      // verbatim — closing the hole for the unmapped `.postscript` graphics
1287      // type (and any future addition) where a raw .ps/.eps/.pdf/.ai could
1288      // otherwise reach the web. Perl defaults dest_type to srctype here
1289      // (Graphics.pm:244, `$type = $properties{destination_type} || $srctype`),
1290      // which would copy such a source raw; we deliberately diverge so the web
1291      // output is never a raw .eps/.ps/.pdf the browser can't render.
1292      const WEB_NATIVE: &[&str] = &["svg", "png", "gif", "jpg", "jpeg"];
1293      let dest_type = props
1294        .as_ref()
1295        .and_then(|p| p.destination_type.as_ref())
1296        .cloned()
1297        .unwrap_or_else(|| {
1298          if WEB_NATIVE.contains(&src_ext.as_str()) {
1299            src_ext.clone()
1300          } else {
1301            "png".to_string()
1302          }
1303        });
1304      let needs_conversion = dest_type != src_ext;
1305      let has_page = page.is_some();
1306      // A raster whose pixels are cropped (`trim`/`viewport`) or turned
1307      // (`angle=`) gets a file of its own, as Perl gives a complex transform a
1308      // new resource name (`Post/Graphics.pm` L318-323): transforming the plain
1309      // copy in place changed every other use of the same source (2510.17772: ten
1310      // `trim=…,clip` figures). A non-raster source keeps Perl's refusal
1311      // (warned in `Plan::Copy` below).
1312      let raster = props.as_ref().and_then(|p| p.raster).unwrap_or(true);
1313      // Perl's `raster` is "may be transformed as pixels" (`Post/Graphics.pm` L266), true for a PDF; its pixels are
1314      // drawn at the render density when it is a PDF or PostScript by its content, whatever its name (a `.pstex`,
1315      // cond-mat0603250's `loop.pstex`), else when its type's size is in points (`unit`, L40).
1316      let drawn = match latexml_core::util::image::graphic_content(Path::new(&source)) {
1317        Some(GraphicContent::Pdf | GraphicContent::PostScript) => true,
1318        Some(GraphicContent::Raster) => false,
1319        None => props.as_ref().is_some_and(|p| p.unit == "point"),
1320      };
1321      let ops = if needs_conversion || raster {
1322        Self::physical_ops(&options)
1323      } else {
1324        Vec::new()
1325      };
1326      let transform = !ops.is_empty();
1327      // What the file's bytes depend on besides the source, its page and type: the crop and the turn. A scale or a
1328      // size (`width=0.5\textwidth`) sizes the `<img>` only, so two widths share one file, and a width edited keeps it,
1329      // unless it sizes a vector render's root (`sized` below).
1330      let made = if transform {
1331        format!("{ops:?}")
1332      } else {
1333        String::new()
1334      };
1335      // Perl's key (`ref($self):reldir/name.srctype.type|transform`) and the content the destination holds: one
1336      // file per content, a changed image a new key. Unreadable, a source is known by its path.
1337      let rel = latexml_core::util::pathname::relative(&source, source_dir);
1338      // The source as the names it owns record it: relative to the destination, so a moved folder keeps them.
1339      let owned_source = {
1340        use latexml_core::util::pathname::{absolute, relative};
1341        relative(&absolute(&source), &absolute(dest_dir))
1342      };
1343      let digest = names.digest(&source);
1344      let identity = digest.as_ref().map_or_else(
1345        || format!("path:{source}"),
1346        |d| d.content().iter().map(|b| format!("{b:02x}")).collect(),
1347      );
1348      let key = format!("LaTeXML::Post::Graphics:{rel}.{dest_type}|{options}|{identity}");
1349      if needs_conversion || has_page || transform {
1350        // A vector render is cropped through its `viewBox` (`crop_svg`); only a turn needs the raster. The
1351        // vector-SVG path is tried for small PDFs only (`should_try_svg_path`), into `<name>.svg` beside the raster.
1352        let turned = ops.iter().any(|op| matches!(op, GraphicxOp::Rotate(_)));
1353        let svg_alt = !turned && Self::should_try_svg_path(&source, self.svg_threshold_kb);
1354        // A vector render is shown at its own size where a stylesheet sizes the object `auto` (ar5iv.css): sized, its
1355        // root is the display size, as Perl's raster is (`Util/Image.pm` L382-389), so each size is a file of its own
1356        // (Perl's key holds the transform, `Post/Graphics.pm` L244-245). Witnesses 1605.07806, 2403.09205, 1104.5392,
1357        // 1509.02249, 1601.05000. A non-positive factor (`scale=-1` turns the figure at full size, `width=-100pt`
1358        // reflects it at 100pt) keeps the render's own size, as the object's 1x1 would hide it.
1359        let mut sizing: Vec<GraphicxOp> = if svg_alt {
1360          latexml_core::util::image::parse_graphicx_options(&options)
1361            .into_iter()
1362            .filter(|op| matches!(op, GraphicxOp::Scale { .. } | GraphicxOp::ScaleTo { .. }))
1363            .collect()
1364        } else {
1365          Vec::new()
1366        };
1367        if sizing.iter().any(|op| match *op {
1368          GraphicxOp::Scale { x, y } => x <= 0.0 || y <= 0.0,
1369          GraphicxOp::ScaleTo { w, h, .. } => {
1370            w.is_some_and(|w| w <= 0.0) || h.is_some_and(|h| h <= 0.0)
1371          },
1372          _ => false,
1373        }) {
1374          sizing.clear();
1375        }
1376        let sized = if sizing.is_empty() {
1377          String::new()
1378        } else {
1379          format!("|{sizing:?}@{dpi}")
1380        };
1381        // The first conversion of a source keeps its stem, for readable URLs (`figures/mock1/plot.pdf` →
1382        // `plot.png`; witness 2606.30620, arXiv/html_feedback#6922: Figures 2/4/5 all used
1383        // `figures/{mock1,mock3,jackpot}/chi2_residuals.pdf`), a sized one too (its other sizes take `xN`), unless the
1384        // stem lands beside its source, where a run without the cache reads it back as the figure; a page or a
1385        // transform is a generated name, as Perl's every conversion is (`Post/Graphics.pm` L318-319).
1386        let stem = Path::new(&source)
1387          .file_stem()
1388          .and_then(|s| s.to_str())
1389          .unwrap_or("image")
1390          .to_string();
1391        let page_key = page.map_or(String::new(), |p| p.to_string());
1392        let request = Request {
1393          key,
1394          bytes: format!("{dest_type}|{identity}|{page_key}|{made}{sized}"),
1395          owner: format!("{dest_type}|{page_key}|{made}{sized}|{owned_source}"),
1396          source: owned_source,
1397          identity,
1398          proposal: if has_page
1399            || transform
1400            || (!sizing.is_empty() && Self::beside(&source, dest_dir))
1401          {
1402            Proposal::Generated
1403          } else {
1404            Proposal::Stem(stem)
1405          },
1406          ext: dest_type,
1407          svg_alt,
1408          copy: false,
1409          output: if transform || !sizing.is_empty() {
1410            Output::Made
1411          } else {
1412            Output::Render(page)
1413          },
1414        };
1415        descs.push(NodeDesc::Convert(Box::new(ConvertDesc {
1416          source,
1417          options,
1418          digest,
1419          page,
1420          needs_conversion,
1421          ops,
1422          drawn,
1423          sizing,
1424          request,
1425        })));
1426      } else {
1427        let ext = Path::new(&source)
1428          .extension()
1429          .map(|ext| ext.to_string_lossy().into_owned())
1430          .unwrap_or_default();
1431        let request = Request {
1432          key,
1433          bytes: format!("copy|{identity}"),
1434          owner: format!("copy|{owned_source}"),
1435          source: owned_source,
1436          identity,
1437          proposal: Self::kept_path(&rel, dest_dir, site_dir)
1438            .map_or(Proposal::Generated, Proposal::Kept),
1439          ext,
1440          svg_alt: false,
1441          copy: true,
1442          output: Output::Source,
1443        };
1444        descs.push(NodeDesc::Copy {
1445          source,
1446          options,
1447          request: Box::new(request),
1448        });
1449      }
1450    }
1451    descs
1452  }
1453
1454  /// The names of a page's requests: the planned ones, else named now (a gap when the run planned, warned: the name
1455  /// then depends on the page render order).
1456  fn names_for(
1457    doc: &PostDocument,
1458    descs: &[NodeDesc],
1459    dirs: &PageDirs,
1460    names: &mut ResourceNames,
1461    policy: crate::graphics_cache::CachePolicy,
1462  ) -> Vec<Option<ResourceName>> {
1463    let mut out: Vec<Option<ResourceName>> = descs
1464      .iter()
1465      .map(|desc| {
1466        let request = desc.request()?;
1467        names
1468          .planned
1469          .get(&(dirs.dest_dir.clone(), request.key.clone()))
1470          .cloned()
1471      })
1472      .collect();
1473    let misses: Vec<usize> = (0..descs.len())
1474      .filter(|&i| out[i].is_none() && descs[i].request().is_some())
1475      .collect();
1476    if misses.is_empty() {
1477      return out;
1478    }
1479    let requests: Vec<Request> = misses
1480      .iter()
1481      .filter_map(|&i| descs[i].request().cloned())
1482      .collect();
1483    let planning = names.planning;
1484    let prefix = names.prefix.clone().unwrap_or_else(|| "x".to_string());
1485    let cache = names.cache.clone().unwrap_or_else(|| doc.cache().clone());
1486    let resolved = Self::resolve_names(&cache, dirs, &prefix, &[requests], policy)
1487      .into_iter()
1488      .next()
1489      .unwrap_or_default();
1490    for (&i, resolved) in misses.iter().zip(resolved) {
1491      if planning && resolved.allocated {
1492        Warn!(
1493          "unexpected",
1494          "resource_name",
1495          "Graphics: {} was not named before the pages were rendered; {} depends on the render order",
1496          descs[i].request().map_or("", |r| r.key.as_str()),
1497          resolved.name.dest
1498        );
1499      }
1500      out[i] = Some(resolved.name);
1501    }
1502    out
1503  }
1504
1505  /// Phase 1 of [`Processor::process`]: each node's image, named by the resource cache, and the conversions to run.
1506  /// It writes nothing.
1507  fn plan_page(
1508    &self,
1509    doc: &PostDocument,
1510    nodes: &[Node],
1511    dirs: &PageDirs,
1512    names: &mut ResourceNames,
1513    dpi: u32,
1514  ) -> PagePlan {
1515    let descs = self.describe(doc, nodes, dirs, names, dpi);
1516    let resolved = Self::names_for(doc, &descs, dirs, names, self.cache_policy);
1517    let dest_dir = &dirs.dest_dir;
1518    let mut plans: Vec<Plan> = Vec::with_capacity(nodes.len());
1519    let mut convert_jobs: Vec<ConvertJob> = Vec::new();
1520    // A job id per conversion this page runs or reuses; the page's own repeats share one.
1521    let mut next_job_id = 0usize;
1522    let mut convert_job_ids: HashMap<String, usize> = HashMap::default();
1523    // Outcomes an earlier page's conversion already produced (`ResourceNames::converted`).
1524    let mut known: Vec<ConvertOutcome> = Vec::new();
1525    for (idx, (desc, name)) in descs.into_iter().zip(resolved).enumerate() {
1526      let name = name.unwrap_or_else(|| ResourceName {
1527        dest: String::new(),
1528        alt:  None,
1529      });
1530      match desc {
1531        NodeDesc::NotFound(graphic) => plans.push(Plan::NotFound { idx, graphic }),
1532        NodeDesc::Copy { source, options, .. } => {
1533          // One copy per destination file: a byte-identical source points at the same one.
1534          let memo = (dest_dir.clone(), name.dest.clone());
1535          let (rel, copy) = match names.copies.get(&memo) {
1536            Some(rel) => (rel.clone(), false),
1537            None => {
1538              names.copies.insert(memo, name.dest.clone());
1539              (name.dest, true)
1540            },
1541          };
1542          plans.push(Plan::Copy {
1543            idx,
1544            source,
1545            options,
1546            rel,
1547            copy,
1548          });
1549        },
1550        NodeDesc::Convert(desc) => {
1551          let ConvertDesc {
1552            source,
1553            options,
1554            digest,
1555            page,
1556            needs_conversion,
1557            ops,
1558            drawn,
1559            sizing,
1560            ..
1561          } = *desc;
1562          let memo = (dest_dir.clone(), name.dest.clone());
1563          let job_id = if let Some(&job_id) = convert_job_ids.get(&name.dest) {
1564            job_id
1565          } else {
1566            let job_id = next_job_id;
1567            next_job_id += 1;
1568            convert_job_ids.insert(name.dest.clone(), job_id);
1569            match names.converted.get(&memo) {
1570              // An earlier page made this image: it again (Perl's `cacheLookup`).
1571              Some((_, Some(outcome))) => known.push(ConvertOutcome { job_id, ..outcome.clone() }),
1572              // An earlier page's conversion failed: tried again, into the same file.
1573              Some((job, None)) => convert_jobs.push(ConvertJob { job_id, ..job.clone() }),
1574              None => {
1575                let abs = |rel: &str| {
1576                  PathBuf::from(dest_dir)
1577                    .join(rel)
1578                    .to_string_lossy()
1579                    .to_string()
1580                };
1581                let svg_paths = name
1582                  .alt
1583                  .as_ref()
1584                  .map(|rel_svg| (rel_svg.clone(), abs(rel_svg)));
1585                // A drawn source is cropped at the density it is rendered at (2011.13011 fig3.pdf, 26 dpi, was cropped
1586                // at 72); a raster in its own pixels (a TIFF converted to PNG keeps them: `-density` does not resample).
1587                let density = Self::raster_density_for_source(&source);
1588                let ppi = if drawn {
1589                  (density as f64, density as f64)
1590                } else {
1591                  Self::raster_ppi(&source)
1592                };
1593                let job = ConvertJob {
1594                  job_id,
1595                  copy_source: !needs_conversion && page.is_none(),
1596                  source,
1597                  digest,
1598                  page,
1599                  abs_dest_str: abs(&name.dest),
1600                  rel_dest: name.dest.clone(),
1601                  svg_paths,
1602                  ops,
1603                  density,
1604                  ppi,
1605                  sizing,
1606                  dpi,
1607                };
1608                names.converted.insert(memo, (job.clone(), None));
1609                convert_jobs.push(job);
1610              },
1611            }
1612            job_id
1613          };
1614          plans.push(Plan::Convert { idx, options, job_id });
1615        },
1616      }
1617    }
1618    PagePlan {
1619      plans,
1620      jobs: convert_jobs,
1621      known,
1622    }
1623  }
1624
1625  /// Name `pages` in `cache`'s store of the destination directory, in one transaction ([`crate::resource_cache`]).
1626  fn resolve_names(
1627    cache: &DocCache,
1628    dirs: &PageDirs,
1629    prefix: &str,
1630    pages: &[Vec<Request>],
1631    policy: crate::graphics_cache::CachePolicy,
1632  ) -> Vec<Vec<crate::resource_cache::Resolved>> {
1633    let cache_file = Path::new(&dirs.dest_dir)
1634      .join(crate::document::CACHE_FILE)
1635      .display()
1636      .to_string();
1637    let usable =
1638      |name: &ResourceName| Self::kept_path(&name.dest, &dirs.dest_dir, &dirs.site_dir).is_some();
1639    // Emitted once the transaction is done: one that fails runs again in memory and meets the same entries.
1640    let warnings = std::cell::RefCell::new(Vec::<String>::new());
1641    let warn = |w: String| {
1642      let mut warnings = warnings.borrow_mut();
1643      if !warnings.contains(&w) {
1644        warnings.push(w);
1645      }
1646    };
1647    // Each file read once per call: a store in memory asks of every `xN` in the folder for every image.
1648    let digests = Digests::default();
1649    let vouch = |r: &Request, name: &ResourceName, source: &str| {
1650      Self::vouch(r, name, source, dirs, &cache_file, &warn, &digests)
1651    };
1652    // The file a name writes is at its lexical path, as a copy is written (`copy_target`).
1653    let file = |part: &str| PathBuf::from(Self::copy_target(&dirs.dest_dir, part));
1654    let present = |part: &str| std::fs::symlink_metadata(file(part)).is_ok();
1655    // A store on its file knows the files it named: any other in the folder is not `r`'s (a document's whose cache was
1656    // deleted; an author's, converting in place), but a copy's kept path that is its source (in place).
1657    let not_owned = |r: &Request, name: &ResourceName| {
1658      std::iter::once(&name.dest).chain(&name.alt).any(|part| {
1659        present(part) && !(r.copy && part == &name.dest && Self::is_source(r, part, dirs))
1660      })
1661    };
1662    // A store in memory in place of its file does not: a file of the name holding what `r` writes is the one an
1663    // earlier run wrote for it, which a rerun takes again.
1664    let holds_other = |r: &Request, name: &ResourceName| {
1665      std::iter::once(&name.dest).chain(&name.alt).any(|part| {
1666        present(part)
1667          && !Self::holds_output(r, &file(part), part == &name.dest, dirs, policy, &digests)
1668      })
1669    };
1670    let names = cache.with_store(dirs.cache_dir.as_deref(), |store| {
1671      let on_file = store.wants_file();
1672      // Whether the store runs in memory is known only inside the transaction: a file that fails in it is
1673      // replaced by memory, and the names are planned again there.
1674      store.immediate(|tx, fell_back| {
1675        warnings.borrow_mut().clear();
1676        let on_disk: Option<crate::resource_cache::OnDisk> = if fell_back {
1677          Some(&holds_other)
1678        } else if on_file {
1679          Some(&not_owned)
1680        } else {
1681          None
1682        };
1683        let checks = crate::resource_cache::Checks {
1684          prefix,
1685          usable: &usable,
1686          vouch: &vouch,
1687          on_disk,
1688          cache: &cache_file,
1689          warn: &warn,
1690        };
1691        crate::resource_cache::resolve(tx, &checks, pages)
1692      })
1693    });
1694    for w in warnings.into_inner() {
1695      Warn!("unexpected", "cache", "{}", w);
1696    }
1697    // A transaction that failed in memory too (reported, an Error) names nothing: each page asks again as it renders.
1698    names.unwrap_or_default()
1699  }
1700
1701  /// Whether the file at `path` is one an earlier run wrote into the destination directory: its cache names an owner for
1702  /// it, and it is no copy kept at its own path (an author's file, converted in place), whose `_source_` is itself.
1703  fn our_output(cache: &DocCache, dirs: &PageDirs, path: &str) -> bool {
1704    use latexml_core::util::pathname::{absolute, relative};
1705    let rel = relative(&absolute(path), &absolute(&dirs.dest_dir));
1706    let entry = |key: &str| cache.lookup(dirs.cache_dir.as_deref(), &format!("_{key}_{rel}"));
1707    entry("owner").is_some() && entry("source").as_deref() != Some(rel.as_str())
1708  }
1709
1710  /// Whether `source` lies in `dir` itself (converting in place), so a file named after it there is its sibling.
1711  fn beside(source: &str, dir: &str) -> bool {
1712    let source = latexml_core::util::pathname::absolute(source);
1713    Path::new(&source)
1714      .parent()
1715      .is_some_and(|parent| latexml_core::util::pathname::same_file(parent, dir))
1716  }
1717
1718  /// Whether `part` in the destination directory is `r`'s source itself (a copy's kept path, converting in place).
1719  fn is_source(r: &Request, part: &str, dirs: &PageDirs) -> bool {
1720    let (target, source) = (
1721      Self::copy_target(&dirs.dest_dir, part),
1722      Self::copy_target(&dirs.dest_dir, &r.source),
1723    );
1724    target == source || latexml_core::util::pathname::same_file(&target, &source)
1725  }
1726
1727  /// Whether the file at `path` holds what `r` writes there: a copy its source's bytes; a render (`raster`, else the
1728  /// vector `.svg` beside it) the graphics cache's entry for its source. A cropped or turned image is never known.
1729  fn holds_output(
1730    r: &Request,
1731    path: &Path,
1732    raster: bool,
1733    dirs: &PageDirs,
1734    policy: crate::graphics_cache::CachePolicy,
1735    digests: &Digests,
1736  ) -> bool {
1737    use latexml_core::util::pathname::absolute;
1738    let Some(held) = digests.content(path) else {
1739      return false;
1740    };
1741    let source = absolute(&Path::new(&dirs.dest_dir).join(&r.source).to_string_lossy());
1742    match r.output {
1743      Output::Source => hex(&held) == r.identity,
1744      Output::Render(page) => {
1745        let key = crate::graphics_cache::RenderKey {
1746          page,
1747          density: if raster {
1748            Self::raster_density_for_source(&source)
1749          } else {
1750            0
1751          },
1752          ext: if raster {
1753            ext_from_path(&path.to_string_lossy())
1754          } else {
1755            "svg"
1756          },
1757        };
1758        let digest = digests.of(Path::new(&source));
1759        crate::graphics_cache::cached_output(policy, &source, digest.as_ref(), key)
1760          .and_then(|cached| digests.content(&cached))
1761          .is_some_and(|cached| cached == held)
1762      },
1763      Output::Made => false,
1764    }
1765  }
1766
1767  /// Whether `name`, stored for the source at `source` (relative to the destination directory), is the name that
1768  /// source takes (its kept path, or its stem) and the source holds `r`'s bytes, so `r` may share its file. The name
1769  /// is matched first, and only then is a relative path to a regular file (a link followed to one) read: an absolute
1770  /// path, which no run stores, or a device or a FIFO, whose read may never end, is reported once (Warning). A source
1771  /// is not bound to the source directory: a converted image's may lie outside it (issue 995, `\subimport{../A/}`).
1772  fn vouch(
1773    r: &Request,
1774    name: &ResourceName,
1775    source: &str,
1776    dirs: &PageDirs,
1777    cache_file: &str,
1778    warn: &dyn Fn(String),
1779    digests: &Digests,
1780  ) -> bool {
1781    use latexml_core::util::pathname::{absolute, relative};
1782    if source.is_empty() {
1783      return false;
1784    }
1785    let relative_path = Path::new(source).components().all(|part| {
1786      matches!(
1787        part,
1788        std::path::Component::Normal(_) | std::path::Component::ParentDir
1789      )
1790    });
1791    let abs = absolute(&Path::new(&dirs.dest_dir).join(source).to_string_lossy());
1792    let unusable = || {
1793      warn(format!(
1794        "The cache {cache_file} gives {} the source {source}, not a file relative to the destination; it is ignored",
1795        name.dest
1796      ));
1797      false
1798    };
1799    if !relative_path {
1800      return unusable();
1801    }
1802    let its_name = if r.copy {
1803      relative(&abs, &absolute(&dirs.source_dir)) == name.dest
1804    } else {
1805      Path::new(&abs)
1806        .file_stem()
1807        .is_some_and(|stem| format!("{}.{}", stem.to_string_lossy(), r.ext) == name.dest)
1808    };
1809    if !its_name {
1810      return false;
1811    }
1812    match std::fs::metadata(&abs).map(|meta| meta.is_file()) {
1813      Ok(false) => unusable(),
1814      Ok(true) => digests
1815        .content(Path::new(&abs))
1816        .is_some_and(|d| hex(&d) == r.identity),
1817      Err(_) => false,
1818    }
1819  }
1820
1821  /// A copy's path relative to `dest_dir` when it keeps the source's path relative to the source directory: taken
1822  /// from the destination directory, it must stay in the site directory (Perl `Post/Graphics.pm` L292-300:
1823  /// `--sitedirectory`, else `--dest`'s; OXIDIZED_DESIGN_DIVERGENCES #1081, issue 995). Else a generated `xN`.
1824  fn kept_path(rel: &str, dest_dir: &str, site_dir: &str) -> Option<String> {
1825    // `rel` is relative like Perl's pathname_relative (→ File::Spec->abs2rel): a
1826    // source OUTSIDE source_dir comes back as `../…`, never the raw absolute
1827    // path. A bare `strip_prefix` used to leak the absolute path for a graphic
1828    // reached through `\subimport*{../A/child/}` (issue #698 class).
1829    // In the site as written or resolved: a relative `dest_dir` is completed from the working directory, which the OS
1830    // reports resolved, so a site named through a link holds it only once both are resolved (KNOWN_PERL_ERRORS #1334).
1831    use latexml_core::util::pathname::{is_contained, is_contained_resolved};
1832    let target = Self::copy_target(dest_dir, rel);
1833    ((is_contained(&target, site_dir).is_some()
1834      || is_contained_resolved(&target, site_dir).is_some())
1835      && Self::resolves_inside_site_or_dest(&target, site_dir, dest_dir))
1836    .then(|| rel.to_string())
1837  }
1838
1839  /// Where a copy named `rel` is written: the absolute lexical path, as Perl's `pathname_absolute` and
1840  /// `pathname_copy` make it (`Util/Pathname.pm` L264-266). Joined raw, the system resolved `out/../children`
1841  /// through a linked `out`.
1842  fn copy_target(dest_dir: &str, rel: &str) -> String {
1843    latexml_core::util::pathname::absolute(&PathBuf::from(dest_dir).join(rel).to_string_lossy())
1844  }
1845
1846  /// Whether `target`'s real directory (symbolic links resolved, 8.3 names expanded, a directory not made yet resolved
1847  /// through its existing parent) stays in the real site directory or the real destination directory, both resolved
1848  /// the same way: a link inside the site directory would otherwise carry the copy out of both (Perl writes through
1849  /// it; OXIDIZED_DESIGN_DIVERGENCES #1081). Resolving only the target, a destination not made yet stayed lexical and
1850  /// a Windows `RUNNER~1` destination held none of its own images.
1851  fn resolves_inside_site_or_dest(target: &str, site_dir: &str, dest_dir: &str) -> bool {
1852    use latexml_core::util::pathname::is_contained_resolved;
1853    is_contained_resolved(target, site_dir).is_some()
1854      || is_contained_resolved(target, dest_dir).is_some()
1855  }
1856
1857  /// Copy `source` to `rel` in `dest_dir` ([`Self::copy_target`]), unless it is the source itself.
1858  fn copy_file(source: &str, dest_dir: &str, rel: &str) -> Option<()> {
1859    let abs_dest = PathBuf::from(Self::copy_target(dest_dir, rel));
1860    if let Some(parent) = abs_dest.parent() {
1861      std::fs::create_dir_all(parent).ok()?;
1862    }
1863    // Copy the file atomically (skip if same path) so parallel render workers
1864    // referencing the same image never race on a truncated destination.
1865    if !crate::writer::same_file(Path::new(source), &abs_dest) {
1866      crate::writer::copy_atomic(Path::new(source), &abs_dest).ok()?;
1867    }
1868    Some(())
1869  }
1870
1871  /// Extract `page=N` from graphicx options string.
1872  /// Returns 1-based page number (matching graphicx convention), or None.
1873  fn parse_page_option(options: &str) -> Option<u32> {
1874    for opt in options.split(',') {
1875      let opt = opt.trim();
1876      if let Some((key, val)) = opt.split_once('=') {
1877        if key.trim() == "page" {
1878          // Strip braces: page={2} → 2
1879          let val = val.trim().trim_matches('{').trim_matches('}');
1880          return val.parse::<u32>().ok();
1881        }
1882      }
1883    }
1884    None
1885  }
1886
1887  /// Try to convert a PDF to plain SVG, preserving vector content. Returns
1888  /// `true` on success. Tracks upstream brucemiller/LaTeXML#902.
1889  ///
1890  /// Caller decides when to attempt this — only for PDF sources below a
1891  /// file-size threshold (`should_try_svg_path`), because vector converters
1892  /// on large or path-heavy PDFs can produce massive output (>100 MB).
1893  /// On any failure the function returns `false` and the worker falls back
1894  /// to the raster (PNG) path — so a PDF that no vector tool can handle is
1895  /// never lost, just rasterized instead.
1896  ///
1897  /// `page` is 1-based (graphicx convention); `dest` is the job's private staged file.
1898  ///
1899  /// Each converter is guarded by a **hard timeout** (15 s default; see
1900  /// `svg_convert_timeout_secs`) and an output-size cap
1901  /// (`MAX_SVG_OUTPUT_BYTES`): a converter still running after the deadline
1902  /// is SIGKILLed, and oversized output is discarded — either way we fall
1903  /// through to the next converter, then to raster.
1904  fn convert_image_svg(source: &str, dest: &str, page: Option<u32>) -> bool {
1905    let alias = Self::reachable_source(source);
1906    let source = Self::file_arg(
1907      alias
1908        .as_ref()
1909        .and_then(|a| a.path().to_str())
1910        .unwrap_or(source),
1911    );
1912    let source = &*source;
1913    // Try the two fast vector converters in order of measured speed +
1914    // gzip-compressibility on the canvas slow-tail. Each is gated by
1915    // `MAX_SVG_OUTPUT_BYTES`; pathological vector-heavy PDFs (e.g.
1916    // R-Graphics `W.pdf`) can emit >100 MB SVG which we discard so the
1917    // caller falls back to raster.
1918    //
1919    // Order (subprocess; library license doesn't propagate):
1920    //   1. mutool (MuPDF CLI) — fastest, plus ~4× more gzip-compressible SVG output than pdftocairo
1921    //      (1.5 MB vs 6.0 MB gz on matplotlib scatter).
1922    //   2. pdftocairo (poppler) — universally available with TeX Live; parses vector PDFs directly,
1923    //      so it's fast even on the inputs that make ImageMagick/gs rasterization crawl.
1924    //
1925    // A heavyweight third resort (inkscape) was removed deliberately: it
1926    // pulls a GTK/X11 stack, is 20-40× slower, and is timeout-prone, while
1927    // adding no real coverage — when both converters above fail, the worker
1928    // rasterizes to PNG anyway.
1929    Self::convert_image_svg_mutool(source, dest, page)
1930      || Self::convert_image_svg_pdftocairo(source, dest, page)
1931  }
1932
1933  /// Maximum acceptable SVG output size from a vector conversion. Above
1934  /// this we discard the SVG and force the raster fallback — it's nearly
1935  /// always cheaper to ship a 30 KB PNG than a 100 MB SVG even when both
1936  /// are technically valid. Tuned from observed cases: well-behaved
1937  /// matplotlib plots are ~500 KB - 2 MB; W.pdf-class explodes to
1938  /// 70-115 MB across all known PDF→SVG tools.
1939  const MAX_SVG_OUTPUT_BYTES: u64 = 8 * 1024 * 1024; // 8 MB
1940
1941  fn svg_output_too_large(path: &str) -> bool {
1942    std::fs::metadata(path)
1943      .map(|md| md.len() > Self::MAX_SVG_OUTPUT_BYTES)
1944      .unwrap_or(false)
1945  }
1946  /// `mutool convert -F svg` (MuPDF CLI) — first-choice SVG vector
1947  /// converter. Faster than `pdftocairo -svg` on vector-heavy PDFs
1948  /// (~2×), AND produces output that gzip-compresses ~4× better when
1949  /// served as `.svgz`. Subprocess invocation — no MuPDF code linked.
1950  ///
1951  /// Measured 2026-05-12 on matplotlib AugmentedMSRA10K…pos.pdf:
1952  ///   pdftocairo -svg: 1.17 s, 29.9 MB raw, 6.0 MB gz
1953  ///   mutool convert:  0.52 s, 29.7 MB raw, 1.5 MB gz
1954  ///
1955  /// mutool's `convert` names its output by a printf-style `%d`, its OUTPUT page counter from 1
1956  /// (mutool 1.27: `-o pg%d.svg f.pdf 2` writes `pg1.svg`; without `%d` it inserts the counter
1957  /// anyway), so the one page lands in `page1.svg` of a private directory beside `dest` (same
1958  /// filesystem: the rename stays atomic), removed whatever mutool wrote. Naming the file for
1959  /// the source page left page ≥ 2 in the destination and to pdftocairo (2305.12780, 1906.10268,
1960  /// 2406.07459, 2406.14311, 1709.02311). The directory is named after `dest`'s
1961  /// [bounded](crate::writer::bounded_name) name: a long one took it past NAME_MAX, and pdftocairo
1962  /// drew the figure instead.
1963  fn convert_image_svg_mutool(source: &str, dest: &str, page: Option<u32>) -> bool {
1964    let dest_path = Path::new(dest);
1965    let parent = dest_path.parent().unwrap_or_else(|| Path::new("."));
1966    let stem = crate::writer::bounded_name(
1967      dest_path
1968        .file_name()
1969        .and_then(|s| s.to_str())
1970        .unwrap_or("image"),
1971    );
1972    // `create_dir`, not `create_dir_all`: an existing directory is another job's or a killed
1973    // run's, and the next tag is tried (a failure here would hand the figure to pdftocairo).
1974    let tmp_dir = loop {
1975      let dir = parent.join(format!(
1976        ".{}.{}.mutool_svg",
1977        stem,
1978        Self::unique_staging_tag()
1979      ));
1980      match std::fs::create_dir(&dir) {
1981        Ok(()) => break dir,
1982        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
1983        Err(_) => return false,
1984      }
1985    };
1986    let _on_exit = latexml_core::watchdog::remove_on_exit(&tmp_dir);
1987    let tmp_actual = tmp_dir.join("page1.svg");
1988    let p1 = page.map(|p| p.max(1)).unwrap_or(1);
1989    let mut cmd = std::process::Command::new("mutool");
1990    cmd
1991      .arg("convert")
1992      .arg("-F")
1993      .arg("svg")
1994      .arg("-o")
1995      .arg(tmp_dir.join("page%d.svg"))
1996      .arg(source)
1997      .arg(p1.to_string());
1998    let timeout = std::time::Duration::from_secs(Self::svg_convert_timeout_secs());
1999    let ok = Self::run_with_timeout(cmd, timeout).is_some_and(|status| status.success())
2000      && std::fs::metadata(&tmp_actual).is_ok_and(|md| md.len() <= Self::MAX_SVG_OUTPUT_BYTES);
2001    let installed = ok && std::fs::rename(&tmp_actual, dest).is_ok();
2002    let _ = std::fs::remove_dir_all(&tmp_dir);
2003    installed
2004  }
2005
2006  /// `pdftocairo -svg` rasterizes the page's vector content to SVG via
2007  /// poppler/cairo — the second-choice vector converter after mutool, and
2008  /// universally available with TeX Live. Returns true ONLY if the output
2009  /// is reasonably-sized; otherwise we discard it and the caller falls
2010  /// through to the raster (PNG) path.
2011  fn convert_image_svg_pdftocairo(source: &str, dest: &str, page: Option<u32>) -> bool {
2012    let mut cmd = std::process::Command::new("pdftocairo");
2013    cmd.arg("-svg");
2014    if let Some(p) = page {
2015      let p1 = p.max(1);
2016      cmd
2017        .arg("-f")
2018        .arg(p1.to_string())
2019        .arg("-l")
2020        .arg(p1.to_string());
2021    } else {
2022      cmd.arg("-f").arg("1").arg("-l").arg("1");
2023    }
2024    cmd.arg(source).arg(dest);
2025    let timeout = std::time::Duration::from_secs(Self::svg_convert_timeout_secs());
2026    match Self::run_with_timeout(cmd, timeout) {
2027      Some(status) => {
2028        if !(status.success() && Path::new(dest).exists()) {
2029          let _ = std::fs::remove_file(dest);
2030          return false;
2031        }
2032        if Self::svg_output_too_large(dest) {
2033          let _ = std::fs::remove_file(dest);
2034          return false;
2035        }
2036        true
2037      },
2038      None => {
2039        let _ = std::fs::remove_file(dest);
2040        false
2041      },
2042    }
2043  }
2044
2045  /// Hard timeout (seconds) for a vector-SVG converter subprocess (mutool /
2046  /// pdftocairo). Overridable via the `LATEXML_SVG_CONVERT_TIMEOUT_SECS`
2047  /// environment variable for debugging; defaults to 15 s — enough for all
2048  /// benign vector-authored plots we've measured (< 1 s typical), strict
2049  /// enough to cut off the Fade.pdf-class 40 s+ runaway cases.
2050  fn svg_convert_timeout_secs() -> u64 { SVG_CONVERT_TIMEOUT_SECS.unwrap_or(15) }
2051
2052  /// Run `cmd` and enforce a wall-clock timeout. Returns `Some(status)` on
2053  /// clean exit, `None` if the child was killed on timeout or spawn
2054  /// failed. Polls every 50 ms — cheap compared to the subprocess cost.
2055  ///
2056  /// On Unix, each child runs in its OWN session (setsid via pre_exec)
2057  /// so a timeout kill targets the entire process group with `killpg`.
2058  /// Without that, ImageMagick's `convert` was spawning `gs` and dying
2059  /// on SIGKILL while leaving gs orphaned — those gs processes held on
2060  /// for 10+ minutes per pathological PDF and stalled large sandbox
2061  /// runs. The same hardening protects mutool / pdftocairo / ps2pdf.
2062  fn run_with_timeout(
2063    mut cmd: std::process::Command,
2064    timeout: std::time::Duration,
2065  ) -> Option<std::process::ExitStatus> {
2066    // Capture the program name for the failure diagnostic before `cmd` is moved.
2067    let prog = cmd.get_program().to_string_lossy().into_owned();
2068    // stdout is uninteresting (null); stderr is PIPED so a converter's error text
2069    // (gs `/undefinedfilename`, an ImageMagick policy block, a missing delegate)
2070    // can be surfaced into the failed_to_convert Error. A draining reader thread
2071    // (below) keeps the child from blocking on a full stderr pipe.
2072    cmd
2073      .stdout(std::process::Stdio::null())
2074      .stderr(std::process::Stdio::piped());
2075    #[cfg(unix)]
2076    {
2077      use std::os::unix::process::CommandExt;
2078      // The spawning process, read before the fork: the child below checks it is still its parent.
2079      #[cfg(target_os = "linux")]
2080      let spawner = std::process::id() as libc::pid_t;
2081      // SAFETY: setsid(2) is async-signal-safe and is the documented way
2082      // to make a child process group leader between fork() and exec().
2083      unsafe {
2084        cmd.pre_exec(move || {
2085          // SAFETY: same as above — async-signal-safe call permitted here.
2086          if libc::setsid() == -1 {
2087            // Fall back: setpgid(0, 0). If both fail we proceed anyway.
2088            let _ = libc::setpgid(0, 0);
2089          }
2090          // Die-with-watcher: `setsid` detaches this converter from every
2091          // process group, so if the process running `run_with_timeout` is
2092          // itself killed (e.g. the LSP server SIGKILLs a preempted body
2093          // child mid-post-processing), nothing would ever time out or kill
2094          // a runaway gs/convert — the exact orphan pathology this
2095          // function's group-kill solves, reintroduced one level up.
2096          // PR_SET_PDEATHSIG makes the kernel SIGKILL the converter when its
2097          // spawning thread dies; it survives execve, so setting it here
2098          // (between fork and exec) covers the exec'd tool. Linux-only —
2099          // elsewhere the orphan window simply remains. prctl is
2100          // async-signal-safe. Guard the fork→prctl race: if the watcher
2101          // died before prctl took effect we are already reparented (to
2102          // init or a subreaper) — exit instead of running unwatched. The
2103          // test is "is my parent still the spawner", not "is my parent 1":
2104          // as a container's entrypoint `latexml_oxide` is itself PID 1, and
2105          // `== 1` made every converter exit 127 there, so every PDF/EPS
2106          // figure failed to convert in the 0.8.0 images (witness 1805.04904);
2107          // a subreaper is not PID 1 either.
2108          #[cfg(target_os = "linux")]
2109          {
2110            libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL);
2111            if reparented(spawner, libc::getppid()) {
2112              libc::_exit(127);
2113            }
2114          }
2115          Ok(())
2116        });
2117      }
2118    }
2119    let mut child = match cmd.spawn() {
2120      Ok(c) => c,
2121      Err(e) => {
2122        // Spawn failure is the "converter not installed / not on PATH" case
2123        // (e.g. `gs` absent in a minimal image): record it so the Error names
2124        // the missing tool instead of a bare "failed to convert". When the
2125        // binary is simply absent, append the package/install hint so the user
2126        // learns which dependency to install (these tools are NOT bundled — the
2127        // host provides them).
2128        let mut msg = format!("could not start `{prog}`: {e}");
2129        if e.kind() == std::io::ErrorKind::NotFound {
2130          if let Some(hint) = missing_tool_hint(&prog) {
2131            msg.push_str(" — ");
2132            msg.push_str(hint);
2133          }
2134        }
2135        record_converter_diag(msg);
2136        return None;
2137      },
2138    };
2139    // Drain stderr concurrently into a bounded (8 KiB) buffer so the child never
2140    // blocks on a full pipe; joined after it exits.
2141    // The drained text comes back over a channel so the parent can WAIT
2142    // BOUNDED: a converter descendant that survives the kill while holding
2143    // stderr open must not hang the worker past the timeout (the reader
2144    // thread is simply abandoned; it exits at pipe EOF).
2145    let (stderr_tx, stderr_rx) = std::sync::mpsc::channel::<String>();
2146    // BUILDER + handled error, never a bare `spawn` (which panics on EAGAIN
2147    // under fleet thread exhaustion — the `worker_panicked` regression that
2148    // aborted graphics on ~10 sandbox papers). A failed drain is harmless:
2149    // the drained text is delivered over `stderr_rx`, and this handle is only
2150    // read as `.is_some()` below, so `None` just means "no captured stderr".
2151    let stderr_reader = child.stderr.take().and_then(|mut se| {
2152      std::thread::Builder::new()
2153        .name("gfx-stderr-drain".into())
2154        .spawn(move || {
2155          use std::io::Read;
2156          let mut kept: Vec<u8> = Vec::new();
2157          let mut chunk = [0u8; 4096];
2158          loop {
2159            match se.read(&mut chunk) {
2160              Ok(0) => break,
2161              Ok(n) => {
2162                if kept.len() < 8192 {
2163                  let room = 8192 - kept.len();
2164                  kept.extend_from_slice(&chunk[..n.min(room)]);
2165                }
2166              },
2167              // EINTR is not EOF — treating it as terminal stopped the drain
2168              // and let a chatty converter block on the full pipe.
2169              Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
2170              Err(_) => break,
2171            }
2172          }
2173          let _ = stderr_tx.send(String::from_utf8_lossy(&kept).trim().to_string());
2174        })
2175        // A failed spawn (EAGAIN under fleet thread exhaustion) must not panic
2176        // as the bare `spawn` did (the `worker_panicked` regression). Flag it
2177        // (`Warn!` is captured on this worker and replayed by the main thread)
2178        // and degrade to None: the child still runs and the conversion is
2179        // unaffected, only its stderr goes uncaptured.
2180        .map_err(|e| {
2181          Warn!(
2182            "imageprocessing",
2183            "stderr_drain",
2184            "Graphics: stderr capture thread not spawned ({}); converter stderr not captured",
2185            e
2186          );
2187        })
2188        .ok()
2189    });
2190    let pid = child.id();
2191    let kill_on_exit = latexml_core::watchdog::kill_pid_on_exit(pid, true);
2192    let kill_group = || {
2193      #[cfg(unix)]
2194      {
2195        // SIGTERM the whole group first (graceful), then SIGKILL after
2196        // a brief grace if the leader is still alive. This matches what
2197        // `timeout(1) --kill-after` does for the bench script's outer
2198        // guard.
2199        latexml_core::watchdog::signal_group_term(pid);
2200        std::thread::sleep(std::time::Duration::from_millis(200));
2201        latexml_core::watchdog::kill_pid(pid, true);
2202      }
2203      #[cfg(windows)]
2204      {
2205        // Windows analogue of the killpg group-kill: `taskkill /T` walks
2206        // the child-process tree from the given PID, so a timed-out
2207        // `magick` also takes down the `gs` it spawned (the exact orphan
2208        // scenario the Unix setsid+killpg design exists for).
2209        latexml_core::watchdog::kill_pid(pid, true);
2210      }
2211      #[cfg(not(any(unix, windows)))]
2212      {
2213        // Other platforms: best-effort PID kill only (child.kill() below).
2214        let _ = pid;
2215      }
2216    };
2217    let start = std::time::Instant::now();
2218    let status = loop {
2219      match child.try_wait() {
2220        Ok(Some(status)) => break Some(status),
2221        Ok(None) => {
2222          if start.elapsed() >= timeout {
2223            kill_group();
2224            let _ = child.kill();
2225            let _ = child.wait();
2226            break None;
2227          }
2228          std::thread::sleep(std::time::Duration::from_millis(50));
2229        },
2230        Err(_) => {
2231          kill_group();
2232          let _ = child.kill();
2233          let _ = child.wait();
2234          break None;
2235        },
2236      }
2237    };
2238    // Child is now reaped on every exit path of the loop above; unregister its
2239    // PID before waiting up to 10 s on stderr drain so a reused PID/PGID cannot
2240    // be signaled if the watchdog fires during drain.
2241    drop(kill_on_exit);
2242    // Join the stderr drainer and record a diagnostic. gs can print a fatal
2243    // error (e.g. `/undefinedfilename` under an AppArmor denial) to stderr yet
2244    // still exit 0, so a non-empty stderr is always worth surfacing — not only
2245    // on a non-zero exit.
2246    let stderr_text = if stderr_reader.is_some() {
2247      // Exited child → EOF imminent; killed child → give the drain a short
2248      // grace, then abandon the reader rather than hang the worker.
2249      let grace = if status.is_some() {
2250        std::time::Duration::from_secs(10)
2251      } else {
2252        std::time::Duration::from_secs(2)
2253      };
2254      stderr_rx.recv_timeout(grace).unwrap_or_default()
2255    } else {
2256      String::new()
2257    };
2258    if !stderr_text.is_empty() {
2259      // Flatten newlines: gs prints `Error: ...` at column 0 mid-diagnostic,
2260      // which would inflate line-anchored ^Error: log counts.
2261      let flat = stderr_text.replace('\n', "; ");
2262      record_converter_diag(format!("`{prog}`: {flat}"));
2263    } else if status.map(|s| !s.success()).unwrap_or(true) {
2264      let how = match status {
2265        Some(s) => format!("exited {s}"),
2266        None => format!("timed out after {}s / killed", timeout.as_secs()),
2267      };
2268      record_converter_diag(format!("`{prog}`: {how}, no stderr"));
2269    }
2270    status
2271  }
2272
2273  /// The SVG viewport in pixels — the root `width`/`height`, else the `viewBox`
2274  /// extent (issue #696). `None` when the geometry can't be recovered, so
2275  /// callers omit the dimension attributes entirely (a browser then sizes the
2276  /// image itself, which beats writing a wrong number).
2277  ///
2278  /// Delegates to `latexml_core::util::image`, which owns the SVG root-tag
2279  /// parsing for both the engine and this pass — Perl likewise keeps one
2280  /// `Util::Image` shared by `Core` and `Post`. The former local parser read
2281  /// only double-quoted attributes, matched `stroke-width` as `width`, and
2282  /// truncated units (`10cm` → 10 px); it also slurped the entire file to find
2283  /// a root tag that lives in its first few hundred bytes. Witness for the
2284  /// bounded, lossy read: 1307.4573 (xfig-pstex_t paper, multi-byte characters
2285  /// in the SVG preamble) — a FATAL_101 panic when a fixed 2048-byte slice cut
2286  /// a UTF-8 sequence.
2287  fn read_svg_dimensions(path: &str) -> Option<(u32, u32)> {
2288    latexml_core::util::image::read_svg_viewport_px(Path::new(path))
2289  }
2290
2291  /// A raster's pixels per inch as pdfTeX sizes it: the resolution it states and pdfTeX keeps for its pixel count, else
2292  /// 72 (`\pdfimageresolution`; the core's sizer gives pdfTeX's Warning).
2293  fn raster_ppi(source: &str) -> (f64, f64) {
2294    use latexml_core::util::image;
2295    image::read_image_dimensions(Path::new(source))
2296      .and_then(|(w, h)| image::raster_resolution_dpi(source, (f64::from(w), f64::from(h))))
2297      .unwrap_or((72.0, 72.0))
2298  }
2299
2300  /// Decide whether the vector-SVG path should be attempted for this PDF
2301  /// source.
2302  ///
2303  /// Two modes, in priority order:
2304  ///
2305  /// 1. **Explicit threshold** (`threshold_kb > 0`): legacy `--graphics-svg-threshold-kb N`
2306  ///    behaviour — try SVG for PDFs at most `N` KB. Preserved for back-compat and as the manual
2307  ///    override of the automatic bound.
2308  /// 2. **Auto default** (`threshold_kb == 0`): try SVG for PDFs at most 500 KiB, raster-bearing
2309  ///    ones included: their labels, axes and curves stay vector and the image is embedded at its
2310  ///    own resolution (after PR 816; a raster-only PDF becomes an SVG wrapping its image).
2311  ///
2312  /// `LATEXML_GRAPHICS_VECTOR_AUTO_OFF=1` disables the auto default only;
2313  /// the explicit-threshold path stays active.
2314  ///
2315  /// Safety net: a converter that fails, times out or emits more than
2316  /// `MAX_SVG_OUTPUT_BYTES` (8 MB) of SVG falls back to the raster path, as does an SVG
2317  /// that draws a raster larger than its pixels (`svg_enlarged_raster`).
2318  fn should_try_svg_path(source: &str, threshold_kb: u32) -> bool {
2319    if !source.to_lowercase().ends_with(".pdf") {
2320      return false;
2321    }
2322    if threshold_kb > 0 {
2323      // Legacy explicit-threshold path: bytes-only decision.
2324      return match std::fs::metadata(source) {
2325        Ok(md) => md.len() <= (threshold_kb as u64) * 1024,
2326        Err(_) => false,
2327      };
2328    }
2329    // Auto-detect path. Honour the opt-out.
2330    if Self::vector_auto_detect_disabled() {
2331      return false;
2332    }
2333    let len = match std::fs::metadata(source) {
2334      Ok(md) => md.len(),
2335      Err(_) => return false,
2336    };
2337    // The 500 KiB input cap bounds the conversion work; the converters'
2338    // timeout and the output cap bound the rest.
2339    const AUTO_MAX_BYTES: u64 = 500 * 1024;
2340    len <= AUTO_MAX_BYTES
2341  }
2342
2343  /// Has `LATEXML_GRAPHICS_VECTOR_AUTO_OFF` been set? Memoised on
2344  /// first call so the env var is read once.
2345  fn vector_auto_detect_disabled() -> bool {
2346    use std::sync::OnceLock;
2347    static CELL: OnceLock<bool> = OnceLock::new();
2348    *CELL.get_or_init(|| {
2349      matches!(
2350        std::env::var("LATEXML_GRAPHICS_VECTOR_AUTO_OFF")
2351          .ok()
2352          .as_deref()
2353          .map(|s| s.trim()),
2354        Some("1") | Some("true") | Some("yes")
2355      )
2356    })
2357  }
2358
2359  fn raster_density_for_source(source: &str) -> u32 {
2360    // `LATEXML_RASTER_DENSITY` overrides the default DPI globally for
2361    // benchmarking and quality/perf tradeoff exploration. Clamped to
2362    // [50, 600]. Unset → `DEFAULT_RASTER_DENSITY` (120; Perl's `$DPI` is 100, `Util/Image.pm` L37).
2363    let base = std::env::var("LATEXML_RASTER_DENSITY")
2364      .ok()
2365      .and_then(|s| s.parse::<u32>().ok())
2366      .map(|d| d.clamp(50, 600))
2367      .unwrap_or(Self::DEFAULT_RASTER_DENSITY);
2368    // The page box of a drawn source by its content, as `drawn` is decided (a PDF saved as `.pstex` is capped too),
2369    // else by its name.
2370    let source_lc = source.to_lowercase();
2371    let content = latexml_core::util::image::graphic_content(Path::new(source)).or_else(|| {
2372      if [".eps", ".epsi", ".epsf", ".ps", ".ai"]
2373        .iter()
2374        .any(|ext| source_lc.ends_with(ext))
2375      {
2376        Some(GraphicContent::PostScript)
2377      } else if source_lc.ends_with(".pdf") {
2378        Some(GraphicContent::Pdf)
2379      } else {
2380        None
2381      }
2382    });
2383    let page_box = match content {
2384      Some(GraphicContent::PostScript) => read_postscript_bounding_box(source),
2385      Some(GraphicContent::Pdf) => latexml_core::util::image::read_pdf_page_box(Path::new(source)),
2386      _ => None,
2387    };
2388    let Some((w_pt, h_pt)) = page_box else {
2389      return base;
2390    };
2391    let max_pt = w_pt.max(h_pt);
2392    if max_pt <= 0.0 {
2393      return base;
2394    }
2395
2396    let max_density = ((Self::MAX_RASTER_DIMENSION_PX as f64) * 72.0 / max_pt).floor() as u32;
2397    base.min(max_density.max(1))
2398  }
2399
2400  /// Returns true when the PS / EPS file's DSC header declares
2401  /// `%%Orientation: Landscape`. PGPLOT and a handful of older
2402  /// scientific renderers emit landscape PS files with a portrait
2403  /// `%%BoundingBox` — content is drawn rotated 90° on the page, and
2404  /// PS-level renderers (gs, IM) ignore the Orientation hint, producing
2405  /// visibly upside-down output. ps2pdf is the one tool in the chain
2406  /// that honors the comment by writing `/Rotate 90` into the PDF
2407  /// header; pdftocairo then renders the rotated PDF correctly.
2408  ///
2409  /// Witness: astro-ph0103041 NickMorgan.fig2.ps. Only the first ~80
2410  /// lines of the DSC prologue are scanned because all conforming PS
2411  /// files emit `%%Orientation:` early.
2412  fn postscript_is_landscape(source: &str) -> bool {
2413    let Ok(file) = std::fs::File::open(source) else {
2414      return false;
2415    };
2416    use std::io::BufRead;
2417    let reader = std::io::BufReader::new(file);
2418    for line in reader.lines().take(80).map_while(Result::ok) {
2419      if let Some(rest) = line.strip_prefix("%%Orientation:") {
2420        return rest.trim().eq_ignore_ascii_case("Landscape");
2421      }
2422    }
2423    false
2424  }
2425
2426  fn should_try_eps_pdf_path(source: &str, page: Option<u32>) -> bool {
2427    // DISABLED 2026-05-12 after 1303.5091 regression.
2428    //
2429    // The `ps2pdf -dEPSCrop` step injects `/Rotate N` PDF annotations
2430    // based on EPS internal orientation hints. PDF's `/Rotate` is
2431    // CLOCKWISE (per PDF spec), but graphicx `angle=N` is
2432    // COUNTER-CLOCKWISE — these are OPPOSITE conventions. After
2433    // pdftocairo respects /Rotate, applying our `angle` rotation on
2434    // top yields content that's 180° off (upside-down).
2435    //
2436    // Perl LaTeXML doesn't use ps2pdf — it uses ImageMagick `convert`
2437    // (which spawns Ghostscript via the EPS delegate) directly, and
2438    // ImageMagick's Rotate takes degrees in CCW = matches graphicx.
2439    //
2440    // Match that: route EPS through the `convert` path, which is
2441    // slower than ps2pdf+pdftocairo but produces correctly-oriented
2442    // output. The performance hit only affects EPS-source documents
2443    // (rare in the canvas — PDF dominates modern arXiv).
2444    let _ = (source, page);
2445    false
2446  }
2447
2448  /// Whether to attempt the poppler `pdftocairo --png` fast-path for a PDF
2449  /// source. The page argument cooperates with pdftocairo's 1-based
2450  /// `-f`/`-l` page selector. Empirical: for vector-heavy PDFs (e.g.
2451  /// R-Graphics output) `pdftocairo` rasterizes 25× faster than
2452  /// ImageMagick-via-Ghostscript and produces a clean PNG, where the
2453  /// vector-SVG path explodes to >100 MB and `convert`/`gs` runs into
2454  /// tens of seconds on a single page.
2455  fn should_try_pdf_cairo_path(source: &str) -> bool { source.to_lowercase().ends_with(".pdf") }
2456
2457  /// Process- and thread-unique tag for dotfile staging paths beside `dest`.
2458  /// Using PID + monotonic counter avoids same-tick collisions under parallel
2459  /// graphics workers or coarse OS clocks.
2460  fn unique_staging_tag() -> String {
2461    static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2462    let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2463    format!("{}-{}", std::process::id(), seq)
2464  }
2465
2466  /// Rasterize a PDF via the `mutool draw` subprocess (MuPDF CLI).
2467  /// ~1.7× faster than `pdftocairo` on vector-heavy matplotlib /
2468  /// pgfplots scatter PDFs (the canvas slow-tail).
2469  ///
2470  /// Subprocess invocation only — we do NOT link the MuPDF C library
2471  /// or the `mupdf-rs` Rust crate into our binary, so MuPDF's AGPL-3.0
2472  /// license does not propagate. Same legal pattern as invoking
2473  /// `/bin/git` or `ffmpeg` from a non-GPL program.
2474  ///
2475  /// Measured 2026-05-12 on AugmentedMSRA10KExperimentVIIIpos.pdf
2476  /// (894 KB matplotlib scatter):
2477  ///   mutool draw:    0.48 s
2478  ///   pdftocairo:     0.86 s
2479  ///
2480  /// Returns true only when the destination file was actually written.
2481  /// Optional dep: graceful fallthrough when `mutool` is not on PATH.
2482  fn convert_pdf_via_mutool(source: &str, dest: &str, density: u32, page: Option<u32>) -> bool {
2483    let dest_path = Path::new(dest);
2484    let parent = dest_path.parent().unwrap_or_else(|| Path::new("."));
2485    let stem = crate::writer::bounded_name(
2486      dest_path
2487        .file_name()
2488        .and_then(|s| s.to_str())
2489        .unwrap_or("image"),
2490    );
2491    let unique = Self::unique_staging_tag();
2492    let tmp = parent.join(format!(".{}.{}.mutool.png", stem, unique));
2493    let _on_exit = latexml_core::watchdog::remove_on_exit(&tmp);
2494    let timeout = std::time::Duration::from_secs(20);
2495
2496    let mut cmd = std::process::Command::new("mutool");
2497    cmd
2498      .arg("draw")
2499      .arg("-o")
2500      .arg(&tmp)
2501      .arg("-r")
2502      .arg(density.to_string())
2503      .arg("-F")
2504      .arg("png");
2505    let p1 = page.map(|p| p.max(1)).unwrap_or(1);
2506    cmd.arg(source).arg(p1.to_string());
2507
2508    let mutool_ok = Self::run_with_timeout(cmd, timeout)
2509      .map(|status| status.success())
2510      .unwrap_or(false)
2511      && tmp.exists();
2512    if !mutool_ok {
2513      let _ = std::fs::remove_file(&tmp);
2514      return false;
2515    }
2516
2517    let installed = std::fs::rename(&tmp, dest).is_ok();
2518    let _ = std::fs::remove_file(&tmp);
2519    installed
2520  }
2521
2522  /// Rasterize a PDF directly via `pdftocairo --png`. Much faster than
2523  /// `convert`/Ghostscript for vector-heavy PDFs. Returns true only when
2524  /// the destination file was actually written.
2525  fn convert_pdf_via_pdftocairo(source: &str, dest: &str, density: u32, page: Option<u32>) -> bool {
2526    let dest_path = Path::new(dest);
2527    let parent = dest_path.parent().unwrap_or_else(|| Path::new("."));
2528    let stem = crate::writer::bounded_name(
2529      dest_path
2530        .file_name()
2531        .and_then(|s| s.to_str())
2532        .unwrap_or("image"),
2533    );
2534    let unique = Self::unique_staging_tag();
2535    let tmp_prefix = parent.join(format!(".{}.{}.pdftocairo", stem, unique));
2536    let tmp_png = PathBuf::from(format!("{}.png", tmp_prefix.to_string_lossy()));
2537    let _on_exit = latexml_core::watchdog::remove_on_exit(&tmp_png);
2538    let timeout = std::time::Duration::from_secs(20);
2539
2540    let cleanup = |tmp_png: &Path| {
2541      let _ = std::fs::remove_file(tmp_png);
2542    };
2543
2544    let mut pdftocairo = std::process::Command::new("pdftocairo");
2545    pdftocairo
2546      .arg("-singlefile")
2547      .arg("-png")
2548      .arg("-r")
2549      .arg(density.to_string());
2550    // graphicx page is 1-based; pdftocairo also uses 1-based.
2551    if let Some(p) = page {
2552      let p1 = p.max(1);
2553      pdftocairo
2554        .arg("-f")
2555        .arg(p1.to_string())
2556        .arg("-l")
2557        .arg(p1.to_string());
2558    } else {
2559      // Default to first page (matches Perl/`convert` `[0]` behavior).
2560      pdftocairo.arg("-f").arg("1").arg("-l").arg("1");
2561    }
2562    pdftocairo.arg(source).arg(&tmp_prefix);
2563
2564    let cairo_ok = Self::run_with_timeout(pdftocairo, timeout)
2565      .map(|status| status.success())
2566      .unwrap_or(false)
2567      && tmp_png.exists();
2568    if !cairo_ok {
2569      cleanup(&tmp_png);
2570      return false;
2571    }
2572
2573    let installed = std::fs::rename(&tmp_png, dest).is_ok();
2574    cleanup(&tmp_png);
2575    installed
2576  }
2577
2578  /// Some EPS files make ImageMagick/Ghostscript spend tens of seconds in
2579  /// direct rasterization. Converting EPS to a cropped PDF first and then
2580  /// rasterizing the PDF via poppler is much faster for those cases, while
2581  /// still falling back to ImageMagick if either helper is unavailable.
2582  fn convert_eps_via_pdf(source: &str, dest: &str, density: u32) -> bool {
2583    let dest_path = Path::new(dest);
2584    let parent = dest_path.parent().unwrap_or_else(|| Path::new("."));
2585    let stem = crate::writer::bounded_name(
2586      dest_path
2587        .file_name()
2588        .and_then(|s| s.to_str())
2589        .unwrap_or("image"),
2590    );
2591    let unique = Self::unique_staging_tag();
2592    let tmp_pdf = parent.join(format!(".{}.{}.pdf", stem, unique));
2593    let tmp_prefix = parent.join(format!(".{}.{}.pdftocairo", stem, unique));
2594    let tmp_png = PathBuf::from(format!("{}.png", tmp_prefix.to_string_lossy()));
2595    let _on_exit_pdf = latexml_core::watchdog::remove_on_exit(&tmp_pdf);
2596    let _on_exit_png = latexml_core::watchdog::remove_on_exit(&tmp_png);
2597    let timeout = std::time::Duration::from_secs(20);
2598
2599    let cleanup = |tmp_pdf: &Path, tmp_png: &Path| {
2600      let _ = std::fs::remove_file(tmp_pdf);
2601      let _ = std::fs::remove_file(tmp_png);
2602    };
2603
2604    let mut ps2pdf = std::process::Command::new("ps2pdf");
2605    ps2pdf.arg("-dEPSCrop").arg(source).arg(&tmp_pdf);
2606    let ps2pdf_ok = Self::run_with_timeout(ps2pdf, timeout)
2607      .map(|status| status.success())
2608      .unwrap_or(false)
2609      && tmp_pdf.exists();
2610    if !ps2pdf_ok {
2611      cleanup(&tmp_pdf, &tmp_png);
2612      return false;
2613    }
2614
2615    let mut pdftocairo = std::process::Command::new("pdftocairo");
2616    pdftocairo
2617      .arg("-singlefile")
2618      .arg("-png")
2619      .arg("-r")
2620      .arg(density.to_string())
2621      .arg(&tmp_pdf)
2622      .arg(&tmp_prefix);
2623    let cairo_ok = Self::run_with_timeout(pdftocairo, timeout)
2624      .map(|status| status.success())
2625      .unwrap_or(false)
2626      && tmp_png.exists();
2627    if !cairo_ok {
2628      cleanup(&tmp_pdf, &tmp_png);
2629      return false;
2630    }
2631
2632    let installed = std::fs::rename(&tmp_png, dest).is_ok();
2633    cleanup(&tmp_pdf, &tmp_png);
2634    installed
2635  }
2636
2637  /// Direct Ghostscript rasterization for EPS/PS sources, bypassing
2638  /// ImageMagick's wrapper.
2639  ///
2640  /// `convert` for EPS already shells out to `gs` internally, so by
2641  /// invoking `gs` ourselves we save the IM read-pipeline overhead
2642  /// (~50-200 ms per image on the canvas). gs's `Rotate` direction is
2643  /// CCW — same as graphicx and IM — so this matches the Perl
2644  /// `image_graphicx_complex` semantics exactly. No /Rotate metadata
2645  /// is produced (gs writes PNG/JPG directly), so we don't inherit
2646  /// the rotation-mismatch bug from the disabled ps2pdf path.
2647  fn convert_eps_via_gs(source: &str, dest: &str, density: u32) -> bool {
2648    let dest_path = Path::new(dest);
2649    let parent = dest_path.parent().unwrap_or_else(|| Path::new("."));
2650    let stem = crate::writer::bounded_name(
2651      dest_path
2652        .file_name()
2653        .and_then(|s| s.to_str())
2654        .unwrap_or("image"),
2655    );
2656    let unique = Self::unique_staging_tag();
2657    // gs picks its output extension from the device, not the path, so
2658    // we pass it whatever name and rename atomically at the end.
2659    let tmp = parent.join(format!(".{}.{}.gs", stem, unique));
2660    let _on_exit = latexml_core::watchdog::remove_on_exit(&tmp);
2661    let timeout = std::time::Duration::from_secs(30);
2662    let dest_lc = dest.to_lowercase();
2663    // pngalpha matches IM's `ps:alpha` delegate (the default EPS→PNG
2664    // path). It produces an RGBA PNG where blank canvas is transparent
2665    // — important for plot backgrounds matching document background.
2666    // png16m would force a white background regardless of source.
2667    let device = if dest_lc.ends_with(".jpg") || dest_lc.ends_with(".jpeg") {
2668      "jpeg"
2669    } else {
2670      "pngalpha"
2671    };
2672
2673    let mut cmd = std::process::Command::new(gs_program());
2674    cmd
2675      .arg("-q")
2676      .arg("-dNOPAUSE")
2677      .arg("-dBATCH")
2678      .arg("-dSAFER")
2679      // Antialiasing — IM passes these through its delegate by
2680      // default. Without them gs produces aliased, jagged output
2681      // that's visibly worse than `convert`. 4 = max quality;
2682      // 2 = balanced; 1 = off. Matches IM's delegate.xml defaults.
2683      .arg("-dTextAlphaBits=4")
2684      .arg("-dGraphicsAlphaBits=4")
2685      // Render the entire page in memory rather than band-by-band.
2686      // Eliminates seam artifacts on large pages. Mirrors IM's
2687      // delegate.xml: -dMaxBitmap=500000000.
2688      .arg("-dMaxBitmap=500000000")
2689      .arg("-dAlignToPixels=0")
2690      .arg("-dGridFitTT=2")
2691      // -dEPSCrop here means "honor the EPS BoundingBox when rendering"
2692      // (a gs rendering flag), NOT the ps2pdf flag that injected
2693      // /Rotate in the earlier disabled path. gs writing PNG never
2694      // produces PDF metadata, so this is safe.
2695      .arg("-dEPSCrop");
2696    // When the EPS declares a `%%BoundingBox`, force the device
2697    // page-size to match it AND lock it via `-dFIXEDMEDIA`. Some EPS
2698    // files (notably `pswrite`-output, e.g. AFPL Ghostscript-generated
2699    // figures like astro-ph0503029/figure7.eps) embed their own
2700    // `setpagedevice` calls that override `-dEPSCrop` and force a full
2701    // US-Letter page (612 × 792 pt), so the content lands at the bottom
2702    // of a 1020 × 1320 px canvas with a 968-pixel blank above it.
2703    // `-dFIXEDMEDIA` makes gs ignore the embedded `setpagedevice` and
2704    // honour our explicit dimensions. Witness: astro-ph0503029 fig 7.
2705    //
2706    // When the BoundingBox is offset from origin (e.g.
2707    // `%%BoundingBox: 117 242 524 567` in hep-ph0608319/data6.ps),
2708    // FIXED page-size alone isn't enough — content drawn at PS
2709    // (117, 242) lands OUTSIDE a (407, 325) page. Translate via
2710    // PostScript `-c "<x0_neg> <y0_neg> translate"` BEFORE the EPS
2711    // file is interpreted, shifting the content to origin (0, 0).
2712    // PS `-c` snippet executes after the device init but before the
2713    // file load. Witness: hep-ph0608319/data6.ps (`(atend)` header,
2714    // real BBox `117 242 524 567`) — without translate the rendered
2715    // 992 × 1403 letter page has a tiny content blob; with translate
2716    // we get a tight 407 × 325 pt crop matching what convert produces.
2717    // Device init flags must precede `-c` / `-f` because gs `-f`
2718    // takes the NEXT argument as a file to interpret; anything after
2719    // `-f` is no longer parsed as an option.
2720    cmd
2721      .arg(format!("-sDEVICE={}", device))
2722      .arg(format!("-r{}", density))
2723      .arg(format!("-sOutputFile={}", tmp.display()));
2724    let bbox_full = read_postscript_bounding_box_full(source);
2725    if let Some((x0, y0, w_pt, h_pt)) = bbox_full {
2726      let w = w_pt.max(1.0).ceil() as u32;
2727      let h = h_pt.max(1.0).ceil() as u32;
2728      cmd
2729        .arg("-dFIXEDMEDIA")
2730        .arg(format!("-dDEVICEWIDTHPOINTS={}", w))
2731        .arg(format!("-dDEVICEHEIGHTPOINTS={}", h));
2732      if x0.abs() > 0.5 || y0.abs() > 0.5 {
2733        cmd
2734          .arg("-c")
2735          .arg(format!("{} {} translate", -x0, -y0))
2736          .arg("-f");
2737      }
2738    }
2739    cmd.arg(source);
2740    let gs_ok = Self::run_with_timeout(cmd, timeout)
2741      .map(|s| s.success())
2742      .unwrap_or(false)
2743      && tmp.exists();
2744    if !gs_ok {
2745      let _ = std::fs::remove_file(&tmp);
2746      return false;
2747    }
2748    let installed = std::fs::rename(&tmp, dest).is_ok();
2749    let _ = std::fs::remove_file(&tmp);
2750    installed
2751  }
2752
2753  /// On Windows, a short-named link (or copy) of `source` in the temporary directory, never the user's project, when
2754  /// its full path reaches MAX_PATH (260): the converters (ImageMagick, mutool, Ghostscript) cannot open such a path,
2755  /// and a figure name of ~220 characters in a temp directory reaches it. Removed when dropped, or by an exit's sweep.
2756  #[cfg(windows)]
2757  fn reachable_source(source: &str) -> Option<crate::writer::Staged> {
2758    const MAX_PATH: usize = 260;
2759    if std::path::absolute(source).map_or(true, |p| p.as_os_str().len() < MAX_PATH) {
2760      return None;
2761    }
2762    let alias = crate::writer::Staged::alias(Path::new(source)).ok()?;
2763    // A temporary directory that long leaves the long path, as before: no shorter one is ours to write.
2764    (alias.path().as_os_str().len() < MAX_PATH).then_some(alias)
2765  }
2766
2767  /// Elsewhere a path of any length opens: `None`.
2768  #[cfg(not(windows))]
2769  fn reachable_source(_source: &str) -> Option<crate::writer::Staged> { None }
2770
2771  /// `source` as a converter's argument: a relative name led by `./`, so that a source file named `-o.pdf` or
2772  /// `|cmd.pdf` is a file to mutool, pdftocairo, Ghostscript and ps2pdf (no option) and to ImageMagick (no pipe).
2773  fn file_arg(source: &str) -> std::borrow::Cow<'_, str> {
2774    match Path::new(source).components().next() {
2775      Some(std::path::Component::Normal(_)) => Path::new(".")
2776        .join(source)
2777        .to_string_lossy()
2778        .into_owned()
2779        .into(),
2780      _ => source.into(),
2781    }
2782  }
2783
2784  /// Convert a graphics file using ImageMagick's `convert` command.
2785  /// Perl: image_graphicx_complex via Image::Magick / convert CLI.
2786  /// `page` is 1-based (graphicx convention); converted to 0-based for ImageMagick.
2787  /// `dest` is the job's private staged file (`writer::Staged`), as for [`Self::convert_image_svg`]:
2788  /// the converters write and remove it freely, and the worker installs it.
2789  fn convert_image(source: &str, dest: &str, density: u32, page: Option<u32>) -> bool {
2790    let alias = Self::reachable_source(source);
2791    let source = Self::file_arg(
2792      alias
2793        .as_ref()
2794        .and_then(|a| a.path().to_str())
2795        .unwrap_or(source),
2796    );
2797    let source = &*source;
2798    // A MetaPost figure that leaves its fonts to dvips is converted from a copy that holds them, as dvips would give
2799    // them (`postscript_fonts`, OXIDIZED_DESIGN #587; gr-qc0001079, math0102124).
2800    let with_fonts = crate::postscript_fonts::with_downloaded_fonts(source, dest);
2801    // (the copy is removed when `with_fonts` drops, on every path)
2802    Self::convert_image_from(
2803      with_fonts
2804        .as_ref()
2805        .and_then(|copy| copy.path().to_str())
2806        .unwrap_or(source),
2807      dest,
2808      density,
2809      page,
2810    )
2811  }
2812
2813  /// [`Self::convert_image`] of the file `source` as it is, a drawn one at `density`.
2814  fn convert_image_from(source: &str, dest: &str, density: u32, page: Option<u32>) -> bool {
2815    // Build the source argument with optional page selector
2816    // Perl: image_read reads "$source[$page]" where $page = ($page // 1) - 1
2817    let source_arg = if let Some(p) = page {
2818      format!("{}[{}]", source, p.saturating_sub(1))
2819    } else {
2820      // No page specified: use [0] for PDFs to avoid converting all pages
2821      if source.to_lowercase().ends_with(".pdf") {
2822        format!("{}[0]", source)
2823      } else {
2824        source.to_string()
2825      }
2826    };
2827    // Shell out to convert (matching Perl's approach)
2828    // -define pdf:use-cropbox=true matches Perl's Image::Magick option (line 466)
2829    if Self::should_try_eps_pdf_path(source, page)
2830      && Self::convert_eps_via_pdf(source, dest, density)
2831    {
2832      return true;
2833    }
2834    // Fast EPS/PS path: skip the ImageMagick wrapper and call `gs`
2835    // directly. Same renderer, same CCW Rotate convention; ~50-200 ms
2836    // saved per image. Falls through to `convert` on any failure.
2837    // Only attempted when no page selector is present (EPS is
2838    // single-page; PS multi-page handled by `convert`'s `[N]` syntax).
2839    //
2840    // EXCEPT: when the PS file declares `%%Orientation: Landscape` in
2841    // its header comments — typical of PGPLOT output, e.g.
2842    // astro-ph0103041 NickMorgan.fig2.ps. Direct gs / convert ignore
2843    // the Orientation comment and render at literal portrait BBox
2844    // coordinates, producing visibly upside-down output. ps2pdf
2845    // honors %%Orientation and writes `/Rotate 90` into the resulting
2846    // PDF; pdftocairo then honors the PDF rotation and emits
2847    // correctly-oriented landscape pixels. Route those through the
2848    // pdf-intermediate path. The earlier disabled `should_try_eps_pdf_path`
2849    // was about an ORTHOGONAL bug (graphicx angle= compounding with
2850    // ps2pdf-injected /Rotate on portrait files) — the 1303.5091 EPS
2851    // files have NO `%%Orientation:` comment, so they go through the
2852    // gs path as before.
2853    let src_lc = source.to_lowercase();
2854    let is_postscript = src_lc.ends_with(".eps")
2855      || src_lc.ends_with(".epsi")
2856      || src_lc.ends_with(".epsf")
2857      || src_lc.ends_with(".ps");
2858    if is_postscript && page.is_none() {
2859      if Self::postscript_is_landscape(source) && Self::convert_eps_via_pdf(source, dest, density) {
2860        return true;
2861      }
2862      if Self::convert_eps_via_gs(source, dest, density) {
2863        return true;
2864      }
2865    }
2866    // For PDF sources, try fast subprocess rasterizers in measured-
2867    // speed order. Subprocess (not linked) so library license doesn't
2868    // propagate — same legal pattern as invoking `git` or `ffmpeg`.
2869    // In-process Rust crates were evaluated 2026-05-12 and rejected
2870    // (mupdf-rs AGPL, poppler-rs GPL, pdfium-render single-threaded).
2871    //
2872    //   1. mutool (MuPDF CLI) — ~1.7× faster than pdftocairo on the canvas slow-tail
2873    //      (matplotlib/pgfplots scatter PDFs).
2874    //   2. pdftocairo (poppler) — universally available with TeX Live; 25× faster than convert/gs.
2875    //   3. convert/gs — last-resort, hard-timeout-bounded.
2876    if Self::should_try_pdf_cairo_path(source) && dest.to_lowercase().ends_with(".png") {
2877      if Self::convert_pdf_via_mutool(source, dest, density, page) {
2878        return true;
2879      }
2880      if Self::convert_pdf_via_pdftocairo(source, dest, density, page) {
2881        return true;
2882      }
2883    }
2884    // Wall-clock timeout to bound `gs`-via-`convert` runaways on
2885    // pathological PDFs (raster-heavy or with broken xref tables).
2886    // Matches the vector-SVG path's defensive bound; without this, an
2887    // arbitrary `convert` invocation could run for minutes and stall
2888    // the entire post-processing phase. 60 s is enough for any
2889    // reasonably-sized graphic; tune via `LATEXML_CONVERT_TIMEOUT_SECS`.
2890    //
2891    // Crucially: `run_with_timeout` puts convert in its own process
2892    // group via setsid+pre_exec (Unix), so killing convert on timeout
2893    // also kills the gs grandchild. Without that, gs orphaned by a
2894    // dying convert kept running 10+ min and stalled the sandbox.
2895    let mut cmd = std::process::Command::new(im_convert_program());
2896    cmd
2897      .arg("-define")
2898      .arg("pdf:use-cropbox=true")
2899      .arg("-density")
2900      .arg(density.to_string())
2901      .arg(&source_arg)
2902      .arg(dest);
2903    let timeout = std::time::Duration::from_secs(Self::convert_timeout_secs());
2904    match Self::run_with_timeout(cmd, timeout) {
2905      Some(status) => {
2906        // A clean exit is NOT sufficient: ImageMagick `convert` (and the `gs`
2907        // it drives) exits 0 on some corrupt/unrenderable inputs while writing
2908        // no file. Require an actual non-empty output so a genuine "no image"
2909        // failure surfaces (returns false → the caller's imageprocessing
2910        // Error) instead of being mistaken for success and emitting a
2911        // broken/empty <img>. The fast PDF/EPS paths already verify their
2912        // output (mutool/pdftocairo check `dest.exists()`); this brings the
2913        // final `convert` fallback in line.
2914        if status.success() && Self::produced_output(dest) {
2915          true
2916        } else {
2917          let _ = std::fs::remove_file(dest); // drop any partial/empty output
2918          false
2919        }
2920      },
2921      None => {
2922        Warn!(
2923          "shell",
2924          "convert",
2925          "Graphics: convert/gs for {} exceeded {} s — killed",
2926          source,
2927          timeout.as_secs()
2928        );
2929        let _ = std::fs::remove_file(dest);
2930        false
2931      },
2932    }
2933  }
2934
2935  /// True iff `dest` was actually written as a usable (non-empty) file. Used to
2936  /// validate a subprocess conversion whose exit code alone is unreliable
2937  /// (`convert`/`gs` can exit 0 having produced nothing). A 0-byte file counts
2938  /// as failure — it would render as a broken image.
2939  fn produced_output(dest: &str) -> bool {
2940    std::fs::metadata(dest)
2941      .map(|m| m.len() > 0)
2942      .unwrap_or(false)
2943  }
2944
2945  /// Hard timeout (seconds) for the `convert` subprocess. Mirrors
2946  /// `svg_convert_timeout_secs`; default 60 s. Override via
2947  /// `LATEXML_CONVERT_TIMEOUT_SECS` for debugging.
2948  fn convert_timeout_secs() -> u64 { CONVERT_TIMEOUT_SECS.unwrap_or(60) }
2949}
2950
2951/// An element of an SVG text, as [`svg_elements`] reads it: its name, its start tag (up to the
2952/// `>`) and its child elements.
2953struct SvgElement<'a> {
2954  name:     &'a str,
2955  tag:      &'a str,
2956  children: Vec<usize>,
2957}
2958
2959/// The elements of an SVG text in document order (the root first), skipping comments,
2960/// processing instructions, CDATA and the DOCTYPE; `None` when the tags do not nest.
2961fn svg_elements(text: &str) -> Option<Vec<SvgElement<'_>>> {
2962  let mut elements: Vec<SvgElement> = Vec::new();
2963  let mut open: Vec<usize> = Vec::new();
2964  let mut at = 0;
2965  while let Some(offset) = text[at..].find('<') {
2966    let start = at + offset;
2967    let rest = &text[start..];
2968    let skip = [
2969      ("<!--", "-->"),
2970      ("<![CDATA[", "]]>"),
2971      ("<?", "?>"),
2972      ("<!", ">"),
2973    ]
2974    .iter()
2975    .find(|(opener, _)| rest.starts_with(opener));
2976    if let Some((_, closer)) = skip {
2977      at = start + rest.find(closer)? + closer.len();
2978      continue;
2979    }
2980    let tag = latexml_core::util::image::xml_start_tag(rest)?;
2981    at = start + tag.len() + 1;
2982    if let Some(name) = tag.strip_prefix("</") {
2983      let top = open.pop()?;
2984      if elements[top].name != name.trim() {
2985        return None;
2986      }
2987      continue;
2988    }
2989    let name = tag[1..]
2990      .split(|c: char| c.is_whitespace() || c == '/')
2991      .next()
2992      .unwrap_or_default();
2993    let index = elements.len();
2994    if let Some(&parent) = open.last() {
2995      elements[parent].children.push(index);
2996    }
2997    elements.push(SvgElement {
2998      name,
2999      tag,
3000      children: Vec::new(),
3001    });
3002    if !tag.ends_with('/') {
3003      open.push(index);
3004    }
3005  }
3006  open.is_empty().then_some(elements)
3007}
3008
3009/// The linear part `[a, b, c, d]` of an SVG transform (a `matrix(a b c d e f)`); `None` for a
3010/// function it does not read.
3011fn svg_transform_linear(list: &str) -> Option<[f64; 4]> {
3012  let mut m = [1.0, 0.0, 0.0, 1.0];
3013  let mut rest = list.trim();
3014  while !rest.is_empty() {
3015    let (name, tail) = rest.split_once('(')?;
3016    let (args, tail) = tail.split_once(')')?;
3017    let args: Vec<f64> = args
3018      .split(|c: char| c.is_whitespace() || c == ',')
3019      .filter(|v| !v.is_empty())
3020      .map(str::parse)
3021      .collect::<Result<_, _>>()
3022      .ok()?;
3023    let f = match (name.trim(), args.as_slice()) {
3024      ("matrix", [a, b, c, d, _, _]) => [*a, *b, *c, *d],
3025      ("translate", [_] | [_, _]) => [1.0, 0.0, 0.0, 1.0],
3026      ("scale", [s]) => [*s, 0.0, 0.0, *s],
3027      ("scale", [sx, sy]) => [*sx, 0.0, 0.0, *sy],
3028      ("rotate", [deg, ..]) => {
3029        let (sin, cos) = deg.to_radians().sin_cos();
3030        [cos, sin, -sin, cos]
3031      },
3032      _ => return None,
3033    };
3034    m = linear_compose(m, f);
3035    rest = tail.trim_start_matches(|c: char| c.is_whitespace() || c == ',');
3036  }
3037  Some(m)
3038}
3039
3040/// `m` then `f`, as SVG nests transforms (`[a, b, c, d]`, the columns of the linear part).
3041fn linear_compose(m: [f64; 4], f: [f64; 4]) -> [f64; 4] {
3042  [
3043    m[0] * f[0] + m[2] * f[1],
3044    m[1] * f[0] + m[3] * f[1],
3045    m[0] * f[2] + m[2] * f[3],
3046    m[1] * f[2] + m[3] * f[3],
3047  ]
3048}
3049
3050/// A raster an SVG render draws larger than its own pixels: its size in pixels and its largest
3051/// scale in user units (the PDF's bp, as mutool and pdftocairo keep them) per pixel; `None`
3052/// where unreadable.
3053#[derive(Debug, PartialEq)]
3054struct EnlargedRaster {
3055  pixels: Option<(usize, usize)>,
3056  scale:  Option<f64>,
3057}
3058
3059/// The first `<image>` in `text` drawn larger than its pixels (beyond float noise, 1 %) on any
3060/// placement, directly or through `<use>` (pdftocairo). An image whose size, pixels or
3061/// placement it cannot read (a `<pattern>`, a `<symbol>`, a skew) counts as enlarged.
3062fn svg_enlarged_raster(text: &str) -> Option<EnlargedRaster> {
3063  use latexml_core::util::image::svg_attr_value;
3064  const TOLERANCE: f64 = 1.01;
3065  fn href(tag: &str) -> Option<&str> {
3066    svg_attr_value(tag, "xlink:href").or_else(|| svg_attr_value(tag, "href"))
3067  }
3068  fn pixels(tag: &str) -> Option<(usize, usize)> { href(tag).and_then(data_uri_pixels) }
3069  /// User units per pixel along the image's wider-drawn axis, under the linear map `m`.
3070  fn scale(tag: &str, m: [f64; 4]) -> Option<f64> {
3071    let length = |name| svg_attr_value(tag, name).and_then(|v| v.trim().parse::<f64>().ok());
3072    let (w, h, (pw, ph)) = (length("width")?, length("height")?, pixels(tag)?);
3073    let sx = w * m[0].hypot(m[1]) / pw as f64;
3074    let sy = h * m[2].hypot(m[3]) / ph as f64;
3075    Some(sx.max(sy)).filter(|s| s.is_finite())
3076  }
3077  struct Walk<'a> {
3078    elements: &'a [SvgElement<'a>],
3079    ids:      HashMap<&'a str, usize>,
3080    /// Each reached image's largest scale; `None` once a placement is unreadable.
3081    scales:   HashMap<usize, Option<f64>>,
3082  }
3083  impl Walk<'_> {
3084    fn element(&mut self, at: usize, m: Option<[f64; 4]>, depth: usize) {
3085      let elements = self.elements;
3086      let e = &elements[at];
3087      let own =
3088        svg_attr_value(e.tag, "transform").map_or(Some([1.0, 0.0, 0.0, 1.0]), svg_transform_linear);
3089      let m = m.zip(own).map(|(m, f)| linear_compose(m, f));
3090      // A nested `<svg>` scales by its own viewBox, which this does not read.
3091      let m =
3092        m.filter(|_| at == 0 || e.name != "svg" || svg_attr_value(e.tag, "viewBox").is_none());
3093      // A soft mask's image (both tools) is drawn in the masked element's user space.
3094      let mask = svg_attr_value(e.tag, "mask")
3095        .and_then(|v| v.trim().strip_prefix("url(#")?.strip_suffix(')'))
3096        .and_then(|id| self.ids.get(id).copied())
3097        .filter(|&target| elements[target].name == "mask" && depth < 8);
3098      if let Some(target) = mask {
3099        let units = svg_attr_value(elements[target].tag, "maskContentUnits");
3100        let m = m.filter(|_| units.is_none_or(|u| u.trim() == "userSpaceOnUse"));
3101        for &child in &elements[target].children {
3102          self.element(child, m, depth + 1);
3103        }
3104      }
3105      match e.name {
3106        "image" => {
3107          let s = m.and_then(|m| scale(e.tag, m));
3108          let worst = self.scales.entry(at).or_insert(s);
3109          *worst = worst.zip(s).map(|(a, b)| a.max(b));
3110        },
3111        "use" if depth < 8 => {
3112          if let Some(&target) = href(e.tag).and_then(|h| self.ids.get(h.trim_start_matches('#'))) {
3113            // A `<symbol>` scales by its own viewBox, which this does not read.
3114            let m = m.filter(|_| elements[target].name != "symbol");
3115            self.element(target, m, depth + 1);
3116          }
3117        },
3118        _ => {
3119          for &child in &e.children {
3120            if !matches!(
3121              elements[child].name,
3122              "defs" | "clipPath" | "mask" | "pattern" | "symbol" | "marker"
3123            ) {
3124              self.element(child, m, depth);
3125            }
3126          }
3127        },
3128      }
3129    }
3130  }
3131  if !text.contains("<image") {
3132    return None;
3133  }
3134  let Some(elements) = svg_elements(text) else {
3135    return Some(EnlargedRaster { pixels: None, scale: None });
3136  };
3137  let ids = elements
3138    .iter()
3139    .enumerate()
3140    .filter_map(|(i, e)| Some((svg_attr_value(e.tag, "id")?, i)))
3141    .collect();
3142  let mut walk = Walk {
3143    elements: &elements,
3144    ids,
3145    scales: HashMap::default(),
3146  };
3147  if !elements.is_empty() {
3148    walk.element(0, Some([1.0, 0.0, 0.0, 1.0]), 0);
3149  }
3150  // An image the walk never reached is drawn some way it does not read. A 1×1 raster is never enlarged, however it
3151  // is drawn: a browser cannot blur a single pixel (DG 2026-11-14; 1503.05958's figures carry several).
3152  elements.iter().enumerate().find_map(|(i, e)| {
3153    let scale = walk.scales.get(&i).copied().flatten();
3154    let single_pixel = pixels(e.tag) == Some((1, 1));
3155    (e.name == "image" && !single_pixel && scale.is_none_or(|s| s > TOLERANCE))
3156      .then(|| EnlargedRaster { pixels: pixels(e.tag), scale })
3157  })
3158}
3159
3160/// The pixel size of a base64 `data:` URI's image, from its header.
3161fn data_uri_pixels(uri: &str) -> Option<(usize, usize)> {
3162  let (meta, data) = uri.strip_prefix("data:")?.split_once(',')?;
3163  if !meta.ends_with(";base64") {
3164    return None;
3165  }
3166  // A PNG names its size in the first bytes; a JPEG's frame header may sit past its metadata.
3167  [4096, usize::MAX].into_iter().find_map(|limit| {
3168    let size = imagesize::blob_size(&base64_prefix(data, limit)).ok()?;
3169    Some((size.width, size.height))
3170  })
3171}
3172
3173/// Decode base64 `data` (whitespace skipped) up to `limit` bytes.
3174fn base64_prefix(data: &str, limit: usize) -> Vec<u8> {
3175  let mut out = Vec::new();
3176  let (mut acc, mut bits) = (0u32, 0u32);
3177  for c in data.bytes() {
3178    let v = match c {
3179      b'A'..=b'Z' => c - b'A',
3180      b'a'..=b'z' => c - b'a' + 26,
3181      b'0'..=b'9' => c - b'0' + 52,
3182      b'+' => 62,
3183      b'/' => 63,
3184      _ if c.is_ascii_whitespace() => continue,
3185      _ => break,
3186    };
3187    acc = (acc << 6 | u32::from(v)) & 0xffff;
3188    bits += 6;
3189    if bits >= 8 {
3190      bits -= 8;
3191      out.push((acc >> bits) as u8);
3192      if out.len() >= limit {
3193        break;
3194      }
3195    }
3196  }
3197  out
3198}
3199
3200/// The content digests of the files one naming call reads, each read once.
3201#[derive(Default)]
3202struct Digests(std::cell::RefCell<HashMap<PathBuf, Option<crate::graphics_cache::SourceDigest>>>);
3203
3204impl Digests {
3205  /// The digest of the file at `path` (`None`: unreadable).
3206  fn of(&self, path: &Path) -> Option<crate::graphics_cache::SourceDigest> {
3207    self
3208      .0
3209      .borrow_mut()
3210      .entry(path.to_path_buf())
3211      .or_insert_with(|| crate::graphics_cache::SourceDigest::of_file(path))
3212      .clone()
3213  }
3214
3215  /// The file's content digest.
3216  fn content(&self, path: &Path) -> Option<[u8; 32]> { self.of(path).map(|d| d.content()) }
3217}
3218
3219fn hex(digest: &[u8; 32]) -> String { digest.iter().map(|b| format!("{b:02x}")).collect() }
3220
3221/// Map a destination path to a `&'static str` extension suitable for
3222/// `graphics_cache::RenderKey::ext`. Only common image targets need to
3223/// round-trip through the cache; anything else collapses to `""` and
3224/// still keys correctly (the cache file simply lacks an extension).
3225fn ext_from_path(path: &str) -> &'static str {
3226  let lower = path.rsplit('/').next().unwrap_or(path);
3227  if let Some(idx) = lower.rfind('.') {
3228    let tail = &lower[idx + 1..];
3229    if tail.eq_ignore_ascii_case("png") {
3230      "png"
3231    } else if tail.eq_ignore_ascii_case("svg") {
3232      "svg"
3233    } else if tail.eq_ignore_ascii_case("jpg") || tail.eq_ignore_ascii_case("jpeg") {
3234      "jpg"
3235    } else if tail.eq_ignore_ascii_case("gif") {
3236      "gif"
3237    } else if tail.eq_ignore_ascii_case("webp") {
3238      "webp"
3239    } else {
3240      ""
3241    }
3242  } else {
3243    ""
3244  }
3245}
3246
3247/// Returns the EPS BoundingBox as `(x0, y0, w, h)` where (x0, y0) is
3248/// the lower-left corner of the content in PS coords and (w, h) is
3249/// the content extent. Callers needing only the extent can ignore the
3250/// origin via `_`-destructuring or `.map(|(_, _, w, h)| (w, h))`.
3251///
3252/// The DSC comments are read by `latexml_core`'s byte scanner
3253/// ([`latexml_core::util::image::read_postscript_boxes`]: `(atend)` trailers,
3254/// DOS EPS headers, CR line ends, non-UTF-8 neighbours). `%%BoundingBox:` wins
3255/// here; `%%HiResBoundingBox:` is the fallback when it is missing.
3256fn read_postscript_bounding_box_full(source: &str) -> Option<(f64, f64, f64, f64)> {
3257  let boxes = latexml_core::util::image::read_postscript_boxes(Path::new(source))?;
3258  let (x0, y0, x1, y1) = boxes.bounding_box.or(boxes.hires_bounding_box)?;
3259  Some((x0, y0, (x1 - x0).abs(), (y1 - y0).abs()))
3260}
3261
3262/// Legacy width/height-only accessor for callers that don't need the
3263/// origin offset. Use `read_postscript_bounding_box_full` when you
3264/// need to translate the content to PS origin (0, 0).
3265fn read_postscript_bounding_box(source: &str) -> Option<(f64, f64)> {
3266  read_postscript_bounding_box_full(source).map(|(_, _, w, h)| (w, h))
3267}
3268
3269impl Processor for Graphics {
3270  fn get_name(&self) -> &str { &self.name }
3271
3272  fn resource_prefix(&self) -> Option<&str> { self.names.prefix.as_deref() }
3273
3274  fn to_process(&self, doc: &PostDocument) -> Vec<Node> {
3275    doc.findnodes("//ltx:graphics[not(@imagesrc)]")
3276  }
3277
3278  fn process(&mut self, doc: PostDocument, nodes: Vec<Node>) -> ProcessResult {
3279    let dirs = self.page_dirs(&doc);
3280    let dest_dir = dirs.dest_dir.clone();
3281    let source_dir = dirs.source_dir.clone();
3282    let effective_dpi = self.effective_dpi(&doc);
3283    let n_to_process = nodes.len();
3284    latexml_core::telemetry::set_graphics_assets(n_to_process as u32);
3285
3286    // The run's resource names, handed back below: every page allocates from one sequence (issue 995).
3287    let mut names = std::mem::take(&mut self.names);
3288
3289    // Two-phase plan so the slow per-image `convert` subprocess and
3290    // `read_image_dimensions` calls can run in parallel without touching
3291    // the libxml DOM off-thread.
3292    //
3293    // Phase 1 (serial, `plan_page`): read each node's attributes, resolve source path,
3294    // decide the conversion kind, and allocate resource names.
3295    //   - `Plan::NotFound` — apply fallback on the main thread later
3296    //   - `Plan::Copy { .. }` — apply on the main thread later (cheap)
3297    //   - `Plan::Convert { .. }` — independent; run in parallel.
3298    // Phase 2 (parallel): run convert_image + read_image_dimensions for
3299    // `Plan::Convert` entries. Produces `JobResult`s keyed by node index.
3300    // Phase 3 (serial): apply DOM mutations on the main thread in original
3301    // node order so attribute writes happen on the libxml-owning thread.
3302    let PagePlan {
3303      plans,
3304      jobs: convert_jobs,
3305      known,
3306    } = self.plan_page(&doc, &nodes, &dirs, &mut names, effective_dpi);
3307
3308    // Phase 2: parallel conversions. Bounded worker count to avoid
3309    // oversubscribing when many images are in flight. `convert` itself
3310    // is single-threaded per invocation, so the ceiling is useful CPU
3311    // parallelism — capped at a reasonable limit to avoid fork/memory
3312    // storms with many-image papers.
3313    let convert_count = convert_jobs.len();
3314    for job in &convert_jobs {
3315      if let Some(parent) = Path::new(&job.abs_dest_str).parent() {
3316        std::fs::create_dir_all(parent).ok();
3317      }
3318    }
3319    // Worker cap controls fork-fan-out of mutool / pdftocairo / convert.
3320    // Each spawn pulls libgs + libpoppler + libpng into a fresh
3321    // address space (~30 ms ambient), so on graphics-heavy papers
3322    // (e.g. LHCb 2402.01336 with 17 unique PDFs) sub-batches at
3323    // cap = 8 added wasted batch boundaries on a 28-CPU host. 22 is
3324    // a measured sweet spot on 28-core machines under the canvas
3325    // sweep workload: high enough to one-shot the typical tail-
3326    // paper graphics fan, low enough to leave headroom for the
3327    // outer cortex_worker pool (12-16 workers) without the kernel
3328    // scheduler thrashing — 12 × 32 ≈ 384 inflight subprocs trips
3329    // the internal 60 s watchdog and produces the "sweep flake"
3330    // pattern in stages 2/4/5. 12 × 22 ≈ 264 stays under the
3331    // measured starvation threshold. The 1910.01256 mini-bench
3332    // (5 PDFs) is unaffected because it is already <= cap.
3333    let worker_cap = std::thread::available_parallelism()
3334      .map(|n| n.get())
3335      .unwrap_or(4)
3336      .clamp(1, 22);
3337    let n_workers = convert_count.min(worker_cap).max(1);
3338    let mut outcomes: Vec<ConvertOutcome> = Vec::with_capacity(convert_count);
3339    if convert_count > 0 {
3340      use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
3341      let next = AtomicUsize::new(0);
3342      // Subprocess tally: telemetry's thread_local! STATE is per-thread,
3343      // and worker threads exit before `phase_us[graphics]` aggregation,
3344      // so worker increments would be lost. Accumulate in a shared
3345      // AtomicU32 here and merge into telemetry once the scope joins.
3346      // One increment per `Self::convert_image_svg` / `Self::convert_image`
3347      // call (the EPS-via-PDF internal pair counts as one).
3348      let subproc_count = AtomicU32::new(0);
3349      let subproc_ref = &subproc_count;
3350      // Copy out of `self` before the scope: the worker closures must not
3351      // borrow `self` (it is `&mut` here), and `CachePolicy` is `Copy`.
3352      let cache_policy = self.cache_policy;
3353      // Unique conversion jobs only. Repeated nodes with the same
3354      // source/page/options share one subprocess result, while distinct
3355      // options keep separate outputs.
3356      let jobs: Vec<&ConvertJob> = convert_jobs.iter().collect();
3357      // Each worker accumulates into a thread-local Vec returned from
3358      // its closure; the main thread merges them after scope join. No
3359      // shared mutable state during the parallel phase — replaces the
3360      // previous `Mutex<Vec<…>>` per project policy (thread_local-only
3361      // for in-memory state, no `Mutex`).
3362      // R35.C: spawn workers with a small (2 MB) stack via
3363      // `spawn_scoped`, which returns Result; if a spawn fails with
3364      // EAGAIN/WouldBlock (canvas + 6 GB ulimit can run out of address
3365      // space on graphics-heavy papers — witness hep-ph0012156, 12778
3366      // formulas, R35.C), drop the failure and let the surviving
3367      // workers pick up the remaining jobs via the shared `next`
3368      // counter. If every spawn fails, run all jobs on the current
3369      // thread instead of crashing.
3370      type WorkerResult = (
3371        Vec<ConvertOutcome>,
3372        latexml_core::util::logger::CapturedDiagnostics,
3373      );
3374      let worker_outcomes: Vec<WorkerResult> = std::thread::scope(|s| {
3375        let handles: Vec<_> = (0..n_workers)
3376          .filter_map(|_| {
3377            std::thread::Builder::new()
3378              .stack_size(2 * 1024 * 1024)
3379              .spawn_scoped(s, || {
3380                // Capture this worker's diagnostics and hand them back on join.
3381                // LOG_BUFFER + REPORT are per-thread, so an Error!/Warn! a
3382                // conversion raises on this worker would otherwise be lost from
3383                // cortex.log AND from status_code. The main thread replays them
3384                // (text + count deltas) in worker order after the scope joins.
3385                latexml_core::util::logger::capture(|| {
3386                  let mut local = Vec::<ConvertOutcome>::new();
3387                  loop {
3388                    let i = next.fetch_add(1, Ordering::Relaxed);
3389                    if i >= jobs.len() {
3390                      break;
3391                    }
3392                    let ConvertJob {
3393                      job_id,
3394                      source,
3395                      digest,
3396                      page,
3397                      rel_dest,
3398                      abs_dest_str,
3399                      svg_paths,
3400                      copy_source,
3401                      ops,
3402                      density,
3403                      ppi,
3404                      sizing,
3405                      dpi,
3406                    } = jobs[i];
3407                    // Fresh converter-diagnostic slate for this node, so the
3408                    // failed_to_convert Error (if it fires) reports THIS asset's
3409                    // converter error, not a previous job's.
3410                    take_converter_diag();
3411                    // Each output is made in a private staged file beside its destination and
3412                    // installed by one rename (`writer::Staged`): parallel page-render workers
3413                    // convert a figure their pages share into the same destination, and a worker
3414                    // that judged or removed a sibling's half-written `fig.svg` switched pages to a
3415                    // PNG and deleted the file under the rest. The cache layer (graphics_cache)
3416                    // links a matching cached output into the staged file before any subprocess
3417                    // fires and round-trips the dimensions through a .dims sidecar; misses fall
3418                    // through to the real conversion + measure and write back on success. Disable
3419                    // via LATEXML_GRAPHICS_CACHE_OFF=1.
3420                    let svg_outcome = 'svg: {
3421                      let Some((rel_svg, abs_svg)) = svg_paths else {
3422                        break 'svg None;
3423                      };
3424                      let staged = crate::writer::Staged::beside(Path::new(abs_svg));
3425                      let stage = staged.path().to_string_lossy().into_owned();
3426                      let svg_key = crate::graphics_cache::RenderKey {
3427                        page:    *page,
3428                        density: 0,
3429                        ext:     "svg",
3430                      };
3431                      let svg_res = crate::graphics_cache::with_cache_dims(
3432                        cache_policy,
3433                        source,
3434                        digest.as_ref(),
3435                        &stage,
3436                        svg_key,
3437                        || {
3438                          subproc_ref.fetch_add(1, Ordering::Relaxed);
3439                          Self::convert_image_svg(source, &stage, *page)
3440                        },
3441                        || {
3442                          Self::read_svg_dimensions(&stage).map(|(w, h)| {
3443                            crate::graphics_cache::CachedDims { width: w, height: h }
3444                          })
3445                        },
3446                      );
3447                      let crate::graphics_cache::ConvertResult::Ok { dims } = svg_res else {
3448                        Warn!(
3449                          "shell",
3450                          "svg",
3451                          "Graphics: vector-SVG path failed for {}, falling back to raster",
3452                          source
3453                        );
3454                        break 'svg None;
3455                      };
3456                      // Judged on this job's own render, past the cache, so a cached render is
3457                      // too: a raster drawn larger than its pixels takes the PNG path (DG
3458                      // 2026-11-14, OD #1034).
3459                      let bytes = match std::fs::read(&stage) {
3460                        Ok(bytes) => bytes,
3461                        Err(e) => {
3462                          Warn!(
3463                            "shell",
3464                            "svg",
3465                            "Graphics: can't read the vector render of {} ({}); using a raster",
3466                            source,
3467                            e
3468                          );
3469                          break 'svg None;
3470                        },
3471                      };
3472                      // A browser refuses an SVG that is not UTF-8.
3473                      let Ok(mut text) = String::from_utf8(bytes) else {
3474                        Warn!(
3475                          "shell",
3476                          "svg",
3477                          "Graphics: the vector render of {} is not UTF-8; using a raster",
3478                          source
3479                        );
3480                        break 'svg None;
3481                      };
3482                      if let Some(EnlargedRaster { pixels, scale }) = svg_enlarged_raster(&text) {
3483                        Info!(
3484                          "shell",
3485                          "svg",
3486                          "Graphics: {} draws a {} raster at {} bp per pixel; using a PNG",
3487                          source,
3488                          pixels.map_or("?".to_string(), |(w, h)| format!("{w}x{h}")),
3489                          scale.map_or("?".to_string(), |s| format!("{s:.2}"))
3490                        );
3491                        break 'svg None;
3492                      }
3493                      // The crop and the display size rewrite the root in memory; the file is replaced once, by
3494                      // rename (`writer::write_atomic`): the staged render may be a hard link to a cache entry.
3495                      let crop = ops
3496                        .iter()
3497                        .find(|op| matches!(op, GraphicxOp::Trim { .. } | GraphicxOp::Clip { .. }));
3498                      let mut rewritten = false;
3499                      let raw_dims = match crop.map(|op| Self::crop_svg(&text, op)) {
3500                        None | Some(Ok(None)) => dims.map(|d| (d.width, d.height)),
3501                        Some(Ok(Some(cropped))) => {
3502                          text = cropped;
3503                          rewritten = true;
3504                          latexml_core::util::image::svg_viewport_px(&text)
3505                        },
3506                        Some(Err(why)) => {
3507                          Warn!(
3508                            "shell",
3509                            "svg",
3510                            "Graphics: can't crop the vector render of {} ({}); cropping a \
3511                             raster instead",
3512                            source,
3513                            why
3514                          );
3515                          break 'svg None;
3516                        },
3517                      };
3518                      // The display size Plan::Convert gives the object, from the same size and ops.
3519                      if let Some((rw, rh)) = raw_dims.filter(|_| !sizing.is_empty()) {
3520                        let (w, h) = Self::apply_graphicx_op_list(rw, rh, SVG_PPI, sizing, *dpi);
3521                        // graphicx's two scales differ: `xscale`/`yscale`, or a box without `keepaspectratio`.
3522                        let stretch = sizing.iter().any(|op| match *op {
3523                          GraphicxOp::Scale { x, y } => x != y,
3524                          GraphicxOp::ScaleTo { w, h, keep_aspect } => {
3525                            w.is_some() && h.is_some() && !keep_aspect
3526                          },
3527                          _ => false,
3528                        });
3529                        match Self::size_svg(&text, w, h, stretch) {
3530                          Ok(sized) => {
3531                            text = sized;
3532                            rewritten = true;
3533                          },
3534                          Err(why) => {
3535                            Warn!(
3536                              "shell",
3537                              "svg",
3538                              "Graphics: can't size the vector render of {} ({}); using a raster",
3539                              source,
3540                              why
3541                            );
3542                            break 'svg None;
3543                          },
3544                        }
3545                      }
3546                      if rewritten
3547                        && let Err(e) =
3548                          crate::writer::write_atomic(Path::new(&stage), text.as_bytes())
3549                      {
3550                        Warn!(
3551                          "shell",
3552                          "svg",
3553                          "Graphics: can't rewrite the vector render of {} ({}); using a raster",
3554                          source,
3555                          e
3556                        );
3557                        break 'svg None;
3558                      }
3559                      drop(text);
3560                      if let Err(e) = staged.install(Path::new(abs_svg)) {
3561                        Warn!(
3562                          "shell",
3563                          "svg",
3564                          "Graphics: can't install the vector render of {} as {} ({}); falling \
3565                           back to raster",
3566                          source,
3567                          abs_svg,
3568                          e
3569                        );
3570                        break 'svg None;
3571                      }
3572                      Some(ConvertOutcome {
3573                        job_id: *job_id,
3574                        imagesrc: Some(rel_svg.clone()),
3575                        raw_dims,
3576                        ppi: SVG_PPI,
3577                      })
3578                    };
3579                    // The raster: converted (or, for a web-native raster whose pixels change,
3580                    // copied) into its staged file, cropped or turned there, then installed —
3581                    // never over its own source (the resource cache names no file another source claimed).
3582                    let raster_dims = if svg_outcome.is_some() {
3583                      None
3584                    } else {
3585                      let staged = crate::writer::Staged::beside(Path::new(abs_dest_str));
3586                      let stage = staged.path().to_string_lossy().into_owned();
3587                      let raster_res = if *copy_source {
3588                        match std::fs::copy(source, &stage)
3589                          .inspect_err(|e| record_converter_diag(format!("copy {source}: {e}")))
3590                        {
3591                          Ok(_) => crate::graphics_cache::ConvertResult::Ok {
3592                            dims: Self::read_image_dimensions(&stage).map(|(w, h)| {
3593                              crate::graphics_cache::CachedDims { width: w, height: h }
3594                            }),
3595                          },
3596                          Err(_) => crate::graphics_cache::ConvertResult::Failed,
3597                        }
3598                      } else {
3599                        let raster_key = crate::graphics_cache::RenderKey {
3600                          page:    *page,
3601                          density: *density,
3602                          ext:     ext_from_path(abs_dest_str),
3603                        };
3604                        crate::graphics_cache::with_cache_dims(
3605                          cache_policy,
3606                          source,
3607                          digest.as_ref(),
3608                          &stage,
3609                          raster_key,
3610                          || {
3611                            subproc_ref.fetch_add(1, Ordering::Relaxed);
3612                            Self::convert_image(source, &stage, *density, *page)
3613                          },
3614                          || {
3615                            Self::read_image_dimensions(&stage).map(|(w, h)| {
3616                              crate::graphics_cache::CachedDims { width: w, height: h }
3617                            })
3618                          },
3619                        )
3620                      };
3621                      if let crate::graphics_cache::ConvertResult::Ok { dims } = raster_res {
3622                        let mut raw_dims = dims.map(|d| (d.width, d.height));
3623                        if !ops.is_empty() {
3624                          match Self::transform_raster_inplace(&stage, ops, ppi.0 / 72.0) {
3625                            Ok(Some(size)) => raw_dims = Some(size),
3626                            Ok(None) => {},
3627                            Err(why) => Error!(
3628                              "imageprocessing",
3629                              "transform",
3630                              "Graphics: {}; {} is shown untransformed",
3631                              why,
3632                              source
3633                            ),
3634                          }
3635                        }
3636                        let dest = Path::new(abs_dest_str);
3637                        let installed = if crate::writer::same_file(Path::new(source), dest) {
3638                          Err(std::io::Error::other(format!(
3639                            "{abs_dest_str} is the source itself"
3640                          )))
3641                        } else {
3642                          staged.install(dest)
3643                        };
3644                        match installed {
3645                          Ok(()) => Some(raw_dims),
3646                          Err(e) => {
3647                            record_converter_diag(format!("install {abs_dest_str}: {e}"));
3648                            None
3649                          },
3650                        }
3651                      } else {
3652                        None
3653                      }
3654                    };
3655                    let outcome = if let Some(o) = svg_outcome {
3656                      o
3657                    } else if let Some(raw_dims) = raster_dims {
3658                      ConvertOutcome {
3659                        job_id: *job_id,
3660                        imagesrc: Some(rel_dest.clone()),
3661                        raw_dims,
3662                        ppi: *ppi,
3663                      }
3664                    } else {
3665                      // Final-failure: every conversion path exhausted. Mirror
3666                      // Perl Graphics.pm L324-329 (Error + `return` with NO
3667                      // imagesrc) — do NOT fall back to copying the raw source.
3668                      // A raw .eps/.ps/.pdf is never usable on the web; copying it
3669                      // would emit a broken `<img src="fig.eps">`. Leaving
3670                      // @imagesrc unset makes the HTML5 XSLT
3671                      // (LaTeXML-misc-xhtml.xsl L154) render the node as
3672                      // `class="ltx_missing ltx_missing_image"` (empty src) — the
3673                      // correct "couldn't render" signal. (User directive
3674                      // 2026-06-22; raw .eps/.pdf are never web-native.)
3675                      // Error class/object mirror Perl Graphics.pm:274 so the
3676                      // harness aggregates with engine/package emissions.
3677                      // Object is the failure TYPE (not the filename) so the
3678                      // harness can aggregate by failure mode. The message marks
3679                      // the SOURCE asset (the input that failed) as the subject —
3680                      // NOT the target — so the log clearly identifies which
3681                      // input could not be rendered; the intended target is
3682                      // secondary context.
3683                      // Surface the last converter's stderr / spawn error so an
3684                      // environment failure (gs not installed, AppArmor denial,
3685                      // ImageMagick policy block) is self-diagnosing in the log.
3686                      let why = take_converter_diag()
3687                        .unwrap_or_else(|| "no converter diagnostic captured".to_string());
3688                      Error!(
3689                        "imageprocessing",
3690                        "failed_to_convert",
3691                        "Graphics: failed to convert source asset {} — every converter \
3692                         failed, no usable image produced (intended target {}); last \
3693                         converter error: {}",
3694                        source,
3695                        abs_dest_str,
3696                        why
3697                      );
3698                      ConvertOutcome {
3699                        job_id:   *job_id,
3700                        imagesrc: None,
3701                        raw_dims: None,
3702                        ppi:      *ppi,
3703                      }
3704                    };
3705                    local.push(outcome);
3706                  }
3707                  local
3708                })
3709              })
3710              .ok()
3711          })
3712          .collect();
3713        // Note: if EVERY spawn failed (extreme memory pressure), no
3714        // jobs run and graphics will be missing from the output. That
3715        // is much less destructive than panicking the whole worker
3716        // and losing the entire conversion. Surviving workers always
3717        // race for the same `next` counter, so a single survivor is
3718        // enough to complete all jobs.
3719        //
3720        // The same degradation policy applies to a worker that PANICS
3721        // mid-run (observed under fleet memory pressure: 15 papers in
3722        // the 2026-07 full-arXiv run, where join().unwrap() escalated
3723        // a thread panic into a whole-conversion Fatal). Surface the
3724        // payload as a conversion Error and keep the survivors'
3725        // outcomes — a casualty's unfinished job stays unconverted
3726        // (the outcomes_by_job lookups below tolerate missing ids).
3727        handles
3728          .into_iter()
3729          .filter_map(|h| match h.join() {
3730            Ok(res) => Some(res),
3731            Err(payload) => {
3732              let msg = payload
3733                .downcast_ref::<&'static str>()
3734                .map(|s| (*s).to_string())
3735                .or_else(|| payload.downcast_ref::<String>().cloned())
3736                .unwrap_or_else(|| "opaque panic payload".to_string());
3737              Error!(
3738                "imageprocessing",
3739                "worker_panicked",
3740                "Graphics: a conversion worker thread panicked ({}); its \
3741                 unfinished jobs are skipped and their graphics left \
3742                 unconverted",
3743                msg
3744              );
3745              None
3746            },
3747          })
3748          .collect()
3749      });
3750      // Merge each worker's outcomes AND replay its captured diagnostics on the
3751      // main thread (in worker order), so any conversion Error!/Warn! reaches the
3752      // bound cortex.log and registers in the main REPORT / status_code.
3753      for (v, diags) in worker_outcomes {
3754        outcomes.extend(v);
3755        latexml_core::util::logger::replay_captured(diags);
3756      }
3757      outcomes.sort_by_key(|o| o.job_id);
3758      latexml_core::telemetry::add_graphics_subprocess(subproc_count.load(Ordering::Relaxed));
3759    }
3760    // A converted image every later page reuses (Perl's `cacheStore`, `Post/Graphics.pm` L331); a failed one is
3761    // tried again, as Perl's is.
3762    for outcome in outcomes.iter().filter(|o| o.imagesrc.is_some()) {
3763      if let Some(job) = convert_jobs.iter().find(|job| job.job_id == outcome.job_id)
3764        && let Some(entry) = names
3765          .converted
3766          .get_mut(&(dest_dir.clone(), job.rel_dest.clone()))
3767      {
3768        entry.1 = Some(outcome.clone());
3769      }
3770    }
3771    let outcomes_by_job: HashMap<usize, ConvertOutcome> = outcomes
3772      .into_iter()
3773      .chain(known)
3774      .map(|o| (o.job_id, o))
3775      .collect();
3776
3777    // Phase 3: serial DOM mutations. Preserves original node order.
3778    for plan in &plans {
3779      match plan {
3780        Plan::NotFound { idx: _, graphic } => {
3781          // Perl `Post/Graphics.pm:216-219`: Warn + `return` WITHOUT setting
3782          // @imagesrc. An earlier Rust-only promotion to Error (2026-05-08)
3783          // was reverted once the missing `doc.get_search_paths()` half of
3784          // `find_graphics_paths` was fixed; with sources findable this branch
3785          // hits only when the .tex references a genuinely non-existent file.
3786          // We must NOT then set `imagesrc` to the raw `graphic` path: that
3787          // emits a broken `<img src="missing.eps">` (and leaks a raw
3788          // .eps/.pdf to the web). Leaving @imagesrc unset makes the HTML5
3789          // XSLT (LaTeXML-misc-xhtml.xsl L154) render the node as
3790          // `class="ltx_missing ltx_missing_image"` (empty src) — the correct
3791          // "couldn't render" signal, matching Perl (user directive
3792          // 2026-06-22; raw .eps/.pdf are never web-native).
3793          Warn!(
3794            "expected",
3795            "source",
3796            "No graphic source found; skipping (source was '{}')",
3797            graphic
3798          );
3799        },
3800        Plan::Copy {
3801          idx,
3802          source,
3803          options,
3804          rel,
3805          copy,
3806        } => {
3807          let mut node_mut = nodes[*idx].clone();
3808          let mut rel = rel.clone();
3809          if *copy && Self::copy_file(source, &dest_dir, &rel).is_none() {
3810            // If the copy itself failed, still emit a RELATIVE URL (abs2rel),
3811            // never the raw absolute source path (issue #698 class).
3812            let planned = std::mem::replace(
3813              &mut rel,
3814              latexml_core::util::pathname::relative(source, &source_dir),
3815            );
3816            names
3817              .copies
3818              .insert((dest_dir.clone(), planned), rel.clone());
3819          }
3820          let raw_dims = Self::read_source_dimensions(source);
3821          let ppi = if ext_from_path(source).eq_ignore_ascii_case("svg") {
3822            SVG_PPI
3823          } else {
3824            Self::raster_ppi(source)
3825          };
3826          // Plan::Copy fires for web-native sources whose pixels stay as they
3827          // are: a raster to crop or turn took Plan::Convert above, so any trim
3828          // left here crops nothing (`trim=0 0 0 0`, or negative: Perl pads
3829          // nothing either). A non-raster source keeps Perl's refusal
3830          // (`Post/Graphics.pm` L264-271): it warns `limitation` and keeps only
3831          // the scaling (`image_graphicx_trivialize`, `Util/Image.pm`
3832          // L290-292). Handing an SVG to `convert` would write a raster under
3833          // the `.svg` name.
3834          let is_raster = self
3835            .type_properties
3836            .get(ext_from_path(source))
3837            .and_then(|p| p.raster)
3838            .unwrap_or(true);
3839          let all_ops = latexml_core::util::image::parse_graphicx_options(options);
3840          let ops: Vec<GraphicxOp> = if is_raster {
3841            all_ops
3842              .into_iter()
3843              .filter(|op| !matches!(op, GraphicxOp::Trim { .. } | GraphicxOp::Clip { .. }))
3844              .collect()
3845          } else {
3846            let refused: Vec<String> = all_ops
3847              .iter()
3848              .filter_map(|op| match op {
3849                GraphicxOp::Rotate(a) if a.abs() > 0.5 => Some(format!("angle={a}")),
3850                GraphicxOp::Trim { .. } => Some("trim".to_string()),
3851                GraphicxOp::Clip { .. } => Some("viewport".to_string()),
3852                _ => None,
3853              })
3854              .collect();
3855            if !refused.is_empty() {
3856              Warn!(
3857                "limitation",
3858                "graphics",
3859                "Cannot (yet) apply complex transforms to non-raster images: dropping {} for {}",
3860                refused.join(", "),
3861                source
3862              );
3863            }
3864            all_ops
3865              .into_iter()
3866              .filter(|op| matches!(op, GraphicxOp::Scale { .. } | GraphicxOp::ScaleTo { .. }))
3867              .collect()
3868          };
3869          if raw_dims.is_none() {
3870            // Perl Graphics.pm L310-312 (triv_scaling, image module present
3871            // but size unusable): warn rather than silently omitting.
3872            Warn!(
3873              "expected",
3874              "image",
3875              "Couldn't get usable image size for {}",
3876              source
3877            );
3878          }
3879          let (w, h) = match raw_dims {
3880            Some((rw, rh)) => {
3881              let (tw, th) = Self::apply_graphicx_op_list(rw, rh, ppi, &ops, effective_dpi);
3882              (Some(tw), Some(th))
3883            },
3884            None => (None, None),
3885          };
3886          Self::set_graphic_src(&mut node_mut, &rel, w, h);
3887        },
3888        Plan::Convert { idx, options, job_id } => {
3889          if let Some(out) = outcomes_by_job.get(job_id) {
3890            let mut node_mut = nodes[*idx].clone();
3891            if let Some(imagesrc) = &out.imagesrc {
3892              // The worker cropped and turned the pixels once per job
3893              // (`transform_raster_inplace`, `crop_svg`); `raw_dims` is
3894              // the cropped size before the turn, so the display size applies
3895              // every op but the crop, in key order. A trim that crops nothing
3896              // (the whole image, or a negative one) sizes nothing either: Perl
3897              // shows the processed image at its own size.
3898              let ops: Vec<GraphicxOp> = latexml_core::util::image::parse_graphicx_options(options)
3899                .into_iter()
3900                .filter(|op| !matches!(op, GraphicxOp::Trim { .. } | GraphicxOp::Clip { .. }))
3901                .collect();
3902              let (w, h) = match out.raw_dims {
3903                Some((rw, rh)) => {
3904                  let (tw, th) = Self::apply_graphicx_op_list(rw, rh, out.ppi, &ops, effective_dpi);
3905                  (Some(tw), Some(th))
3906                },
3907                None => (None, None),
3908              };
3909              Self::set_graphic_src(&mut node_mut, imagesrc, w, h);
3910            }
3911          }
3912        },
3913      }
3914    }
3915
3916    Info!(
3917      "graphics",
3918      "process",
3919      "Graphics {} {} to process",
3920      doc.get_destination().unwrap_or("?"),
3921      n_to_process
3922    );
3923    self.names = names;
3924    Ok(vec![doc])
3925  }
3926}
3927
3928#[cfg(test)]
3929mod tests {
3930  use super::*;
3931  // `EnvGuard` (env mutation, serialised + restored) and `TempDir` (unique
3932  // name, removed on drop including on panic) are shared with
3933  // `graphics_cache::tests`; see that module for the rationale. `EnvGuard` is
3934  // used by the `#[cfg(unix)]` density test and by the platform-independent
3935  // raster crop test, so its import is ungated (the Windows `cargo check`).
3936  use crate::test_env::EnvGuard;
3937  use crate::test_env::TempDir;
3938
3939  /// A figure whose full path reaches MAX_PATH is converted from an alias the converters can open: shorter, not in the
3940  /// figure's directory (the user's project), the same bytes, gone when dropped. A short path takes none.
3941  #[cfg(windows)]
3942  #[test]
3943  fn a_figure_path_past_max_path_is_reached_through_a_short_alias() {
3944    let tmp = TempDir::new("reachable-source");
3945    let dir = tmp.path().join("d".repeat(120)).join("e".repeat(120));
3946    std::fs::create_dir_all(&dir).unwrap();
3947    let figure = dir.join("figure.pdf");
3948    std::fs::write(&figure, b"%PDF-1.4 figure").unwrap();
3949    let source = std::path::absolute(&figure).unwrap();
3950    assert!(source.as_os_str().len() >= 260, "{}", source.display());
3951    let alias = Graphics::reachable_source(source.to_str().unwrap()).expect("an alias");
3952    let path = alias.path().to_path_buf();
3953    assert!(path.as_os_str().len() < 260, "{}", path.display());
3954    assert_ne!(path.parent(), Some(dir.as_path()));
3955    assert_eq!(std::fs::read(&path).unwrap(), b"%PDF-1.4 figure");
3956    drop(alias);
3957    assert!(!path.exists(), "the alias outlived its drop");
3958    let short = tmp.path().join("figure.pdf");
3959    std::fs::write(&short, b"%PDF-1.4").unwrap();
3960    assert!(Graphics::reachable_source(short.to_str().unwrap()).is_none());
3961  }
3962
3963  /// A source file named like an option or an ImageMagick pipe (`-o.pdf`, `|x.pdf`, `png:c.pdf`) reaches the converters
3964  /// led by `./` (head 427e6ac8095 handed mutool `-o.pdf`, an option); a name already led by a directory is kept.
3965  #[test]
3966  fn a_relative_source_reaches_the_converters_as_a_file() {
3967    let dot = |name: &str| Path::new(".").join(name).to_string_lossy().into_owned();
3968    for name in ["-o.pdf", "|x.pdf", "png:c.pdf", "fig.eps", "a>b/x.pdf"] {
3969      assert_eq!(Graphics::file_arg(name), dot(name), "{name}");
3970    }
3971    let absolute = std::env::temp_dir().join("-o.pdf");
3972    for name in ["./-o.pdf", "../|x.pdf", absolute.to_str().unwrap()] {
3973      assert_eq!(Graphics::file_arg(name), name, "{name}");
3974    }
3975  }
3976
3977  /// A conversion request for `source` to `ext` (no page, no transform: its stem is proposed).
3978  fn stem_request(source: &str, ext: &str) -> Request {
3979    let stem = Path::new(source)
3980      .file_stem()
3981      .unwrap()
3982      .to_string_lossy()
3983      .into_owned();
3984    Request {
3985      key:      format!("LaTeXML::Post::Graphics:{source}.{ext}||{source}"),
3986      bytes:    format!("{ext}|{source}||"),
3987      owner:    format!("{ext}|||{source}"),
3988      source:   source.to_string(),
3989      identity: source.to_string(),
3990      proposal: Proposal::Stem(stem),
3991      ext:      ext.to_string(),
3992      svg_alt:  false,
3993      copy:     false,
3994      output:   Output::Render(None),
3995    }
3996  }
3997
3998  fn dests_of(requests: Vec<Request>) -> Vec<String> {
3999    let pages = [requests];
4000    let checks = crate::resource_cache::Checks {
4001      prefix:  "x",
4002      usable:  &|_| true,
4003      vouch:   &|_, _, _| true,
4004      on_disk: None,
4005      cache:   crate::document::CACHE_FILE,
4006      warn:    &|_| {},
4007    };
4008    DocCache::new(true)
4009      .with_store(None, |store| {
4010        store.immediate(|tx, _| crate::resource_cache::resolve(tx, &checks, &pages))
4011      })
4012      .unwrap()[0]
4013      .iter()
4014      .map(|r| r.name.dest.clone())
4015      .collect()
4016  }
4017
4018  /// #6922: two DIFFERENT sources that share a basename must map to DISTINCT
4019  /// converted-output files. Before the fix, the first job of each source used
4020  /// its `file_stem()`, so `figs/a/plot.pdf` and `figs/b/plot.pdf` both became
4021  /// `plot.png` and the first write won — one figure silently replaced by the
4022  /// other (arXiv 2606.30620, Figures 2/4/5). The colliding second source now
4023  /// falls back to a unique `xN`; a distinct stem, or the same stem to another
4024  /// type, keeps its readable name; the same source again is no collision.
4025  #[test]
4026  fn convert_dest_names_avoid_basename_collision() {
4027    let names = dests_of(vec![
4028      stem_request("figs/a/plot.pdf", "png"),
4029      stem_request("figs/b/plot.pdf", "png"),
4030      stem_request("figs/c/other.pdf", "png"),
4031      stem_request("figs/d/plot.eps", "svg"),
4032      stem_request("figs/a/plot.pdf", "png"),
4033    ]);
4034    assert_eq!(names, [
4035      "plot.png",
4036      "x1.png",
4037      "other.png",
4038      "plot.svg",
4039      "plot.png"
4040    ]);
4041    let names = dests_of(vec![
4042      stem_request("m1/chi2.pdf", "png"),
4043      stem_request("m3/chi2.pdf", "png"),
4044      stem_request("jk/chi2.pdf", "png"),
4045    ]);
4046    assert_eq!(names, ["chi2.png", "x1.png", "x2.png"]);
4047  }
4048
4049  /// #6922 finding (reviewer): the `xN` fallback must not clobber a real source
4050  /// literally named `xN`. The tricky ordering is when the GENERATED `x1` is
4051  /// claimed FIRST (by a basename collision) and a real `figs/a/x1.pdf` arrives
4052  /// LAST — its stem `x1` is already taken, so it too must fall through to a
4053  /// fresh name rather than overwrite the generated `x1.png`.
4054  #[test]
4055  fn generated_xn_survives_a_later_literal_xn_source() {
4056    let names = dests_of(vec![
4057      stem_request("figs/b/plot.pdf", "png"),
4058      stem_request("figs/c/plot.pdf", "png"),
4059      stem_request("figs/a/x1.pdf", "png"),
4060    ]);
4061    assert_eq!(names, ["plot.png", "x1.png", "x2.png"]);
4062  }
4063
4064  // ---- cross-platform child-process fixtures for run_with_timeout ----
4065  // Unix `true`/`sh`/`sleep` don't exist on Windows; use cmd/ping there so the
4066  // kill / exit-status / stderr-capture logic gets real coverage on both.
4067
4068  /// A child that runs far longer than any test deadline (so the timeout kills
4069  /// it). `ping` is a bare exe — no shell wrapper — so `kill()` reaps it with no
4070  /// orphaned grandchild.
4071  fn spawn_slow_child() -> std::process::Command {
4072    let mut cmd;
4073    if cfg!(windows) {
4074      cmd = std::process::Command::new("ping");
4075      cmd.args(["-n", "11", "127.0.0.1"]);
4076    } else {
4077      cmd = std::process::Command::new("sleep");
4078      cmd.arg("10");
4079    }
4080    cmd
4081  }
4082
4083  /// A child that exits 0 immediately (Unix `true` / Windows `cmd /C exit 0`).
4084  fn spawn_fast_ok() -> std::process::Command {
4085    let mut cmd = std::process::Command::new(if cfg!(windows) { "cmd" } else { "true" });
4086    if cfg!(windows) {
4087      cmd.args(["/C", "exit 0"]);
4088    }
4089    cmd
4090  }
4091
4092  /// A child that writes to stderr and exits non-zero. Returns the command and
4093  /// its program name (for the diagnostic assertion).
4094  fn spawn_stderr_fail() -> (std::process::Command, &'static str) {
4095    if cfg!(windows) {
4096      let mut cmd = std::process::Command::new("cmd");
4097      cmd.args(["/C", "echo boom on stderr 1>&2 & exit 3"]);
4098      (cmd, "cmd")
4099    } else {
4100      let mut cmd = std::process::Command::new("sh");
4101      cmd.arg("-c").arg("echo 'boom on stderr' >&2; exit 3");
4102      (cmd, "sh")
4103    }
4104  }
4105
4106  /// `run_with_timeout` kills the child and returns `None` when the
4107  /// process exceeds the deadline. The slow child stands in for any
4108  /// runaway subprocess (convert, gs, mutool, …).
4109  #[test]
4110  fn run_with_timeout_kills_slow_child() {
4111    let start = std::time::Instant::now();
4112    let cmd = spawn_slow_child();
4113    let result = Graphics::run_with_timeout(cmd, std::time::Duration::from_millis(200));
4114    let elapsed = start.elapsed();
4115    assert!(
4116      result.is_none(),
4117      "run_with_timeout should return None on kill"
4118    );
4119    // We expect around 200 ms (+ ≤ 50 ms poll interval + SIGKILL reap
4120    // overhead). Give it 2 s of slack for CI noise.
4121    assert!(
4122      elapsed < std::time::Duration::from_secs(2),
4123      "killed run should return quickly, took {:?}",
4124      elapsed
4125    );
4126  }
4127
4128  /// Fast-completing child returns its real exit status, not a kill.
4129  #[test]
4130  fn run_with_timeout_returns_status_for_fast_child() {
4131    let cmd = spawn_fast_ok();
4132    let result = Graphics::run_with_timeout(cmd, std::time::Duration::from_secs(5));
4133    let status = result.expect("expected clean exit");
4134    assert!(status.success(), "a fast child should exit successfully");
4135  }
4136
4137  /// Missing binary → `None`, not a panic.
4138  #[test]
4139  fn run_with_timeout_handles_spawn_failure() {
4140    let cmd = std::process::Command::new("/this/binary/does/not/exist/12345");
4141    let result = Graphics::run_with_timeout(cmd, std::time::Duration::from_secs(1));
4142    assert!(result.is_none());
4143  }
4144
4145  /// Explicit-threshold heuristic: PDF under threshold triggers SVG
4146  /// attempt, large PDF does not, non-PDF is always skipped.
4147  #[test]
4148  fn should_try_svg_path_explicit_threshold() {
4149    let tmp = TempDir::new("svg_gate");
4150    let small_pdf = tmp.join("small.pdf");
4151    let big_pdf = tmp.join("big.pdf");
4152    let png = tmp.join("raster.png");
4153    std::fs::write(&small_pdf, vec![0u8; 10 * 1024]).unwrap(); // 10 KB
4154    std::fs::write(&big_pdf, vec![0u8; 500 * 1024]).unwrap(); // 500 KB
4155    std::fs::write(&png, vec![0u8; 10 * 1024]).unwrap(); // PNG, irrelevant size
4156
4157    // Under explicit threshold → true.
4158    assert!(Graphics::should_try_svg_path(
4159      small_pdf.to_str().unwrap(),
4160      200
4161    ));
4162    // At/over explicit threshold → false.
4163    assert!(!Graphics::should_try_svg_path(
4164      big_pdf.to_str().unwrap(),
4165      200
4166    ));
4167    // Non-PDF → always false even under threshold.
4168    assert!(!Graphics::should_try_svg_path(png.to_str().unwrap(), 200));
4169    // Missing file → false, not panic.
4170    assert!(!Graphics::should_try_svg_path("/no/such/file.pdf", 200));
4171  }
4172
4173  /// Auto path (`threshold_kb == 0`): every PDF up to 500 KiB tries SVG,
4174  /// raster-bearing ones included (after PR 816). Uses the
4175  /// real fixtures (`cifar10_vector.pdf`, `pathological_vector.pdf`,
4176  /// `raster_with_image.pdf`) under `latexml_post/tests/fixtures/`.
4177  #[test]
4178  fn should_try_svg_path_auto_detect() {
4179    let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
4180    let cifar = fixtures.join("cifar10_vector.pdf");
4181    let pathological = fixtures.join("pathological_vector.pdf");
4182    let raster = fixtures.join("raster_with_image.pdf");
4183    assert!(cifar.exists(), "fixture missing: {}", cifar.display());
4184    assert!(
4185      pathological.exists(),
4186      "fixture missing: {}",
4187      pathological.display()
4188    );
4189    assert!(raster.exists(), "fixture missing: {}", raster.display());
4190
4191    // Vector PDFs → SVG path activated.
4192    assert!(
4193      Graphics::should_try_svg_path(cifar.to_str().unwrap(), 0),
4194      "vector-only PDF must trigger SVG path under auto-detect"
4195    );
4196    assert!(
4197      Graphics::should_try_svg_path(pathological.to_str().unwrap(), 0),
4198      "pgfplots-style vector PDF must trigger SVG path under auto-detect"
4199    );
4200
4201    // A PDF with an image XObject tries SVG too (it may carry vector labels).
4202    assert!(
4203      Graphics::should_try_svg_path(raster.to_str().unwrap(), 0),
4204      "raster-bearing PDF must try the SVG path under the auto default"
4205    );
4206
4207    // The 500 KiB bound is now the auto default's whole gate.
4208    let tmp = TempDir::new("auto_svg_bound");
4209    let at_bound = tmp.join("at_bound.pdf");
4210    std::fs::write(&at_bound, vec![0u8; 500 * 1024]).unwrap();
4211    assert!(Graphics::should_try_svg_path(at_bound.to_str().unwrap(), 0));
4212    let over_bound = tmp.join("over_bound.pdf");
4213    std::fs::write(&over_bound, vec![0u8; 500 * 1024 + 1]).unwrap();
4214    assert!(!Graphics::should_try_svg_path(
4215      over_bound.to_str().unwrap(),
4216      0
4217    ));
4218  }
4219
4220  #[test]
4221  fn postscript_density_caps_huge_bounding_box() {
4222    let tmp = TempDir::new("ps_density");
4223    let normal = tmp.join("normal.eps");
4224    let huge = tmp.join("huge.eps");
4225    std::fs::write(
4226      &normal,
4227      "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 567 567\n",
4228    )
4229    .unwrap();
4230    std::fs::write(
4231      &huge,
4232      "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 14 14 11353 11353\n",
4233    )
4234    .unwrap();
4235
4236    assert_eq!(
4237      Graphics::raster_density_for_source(normal.to_str().unwrap()),
4238      Graphics::DEFAULT_RASTER_DENSITY
4239    );
4240    assert_eq!(
4241      Graphics::raster_density_for_source(huge.to_str().unwrap()),
4242      13
4243    );
4244    assert_eq!(
4245      read_postscript_bounding_box(huge.to_str().unwrap()),
4246      Some((11339.0, 11339.0))
4247    );
4248  }
4249
4250  #[test]
4251  fn pdf_density_caps_huge_page_box() {
4252    let dir = TempDir::new("pdf_density");
4253    let tmp = dir.join("page.pdf");
4254    std::fs::write(
4255      &tmp,
4256      b"%PDF-1.4
42571 0 obj
4258<< /Type /Page /MediaBox [0 0 4218 2437] >>
4259endobj
4260",
4261    )
4262    .unwrap();
4263
4264    assert_eq!(
4265      latexml_core::util::image::read_pdf_page_box(Path::new(tmp.to_str().unwrap())),
4266      Some((4218.0, 2437.0))
4267    );
4268    assert_eq!(
4269      Graphics::raster_density_for_source(tmp.to_str().unwrap()),
4270      34
4271    );
4272  }
4273
4274  /// The viewport dimensions come from the root `width`/`height`, the way a
4275  /// browser sizes an SVG — the `viewBox` is only a fallback (issue #696). Here
4276  /// `10cm`/`7.5cm` convert to 378×283 px (96 dpi); the disagreeing `viewBox`
4277  /// `0 0 640 480` is ignored for sizing. When the root carries no lengths, the
4278  /// viewBox is what remains.
4279  #[test]
4280  fn read_svg_dimensions_sizes_from_root_lengths() {
4281    let dir = TempDir::new("svg_dim");
4282    let tmp = dir.join("dims.svg");
4283    std::fs::write(
4284      &tmp,
4285      r#"<?xml version="1.0"?>
4286<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 480" width="10cm" height="7.5cm">
4287  <rect width="640" height="480" fill="black"/>
4288</svg>"#,
4289    )
4290    .unwrap();
4291    let dims = Graphics::read_svg_dimensions(tmp.to_str().unwrap()).expect("dims");
4292    assert_eq!(dims, (378, 283));
4293    // No root lengths → the viewBox is the fallback.
4294    let vb = dir.join("vb.svg");
4295    std::fs::write(
4296      &vb,
4297      r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 480"><rect/></svg>"#,
4298    )
4299    .unwrap();
4300    assert_eq!(
4301      Graphics::read_svg_dimensions(vb.to_str().unwrap()).expect("viewbox fallback"),
4302      (640, 480)
4303    );
4304  }
4305
4306  /// A unit-bearing root length must be **converted**, not truncated. `123.7pt`
4307  /// is 123.7/72 in = 164.9 px; the previous reader dropped the `pt` and called
4308  /// it 124 px, so a `\includegraphics` of this file rendered at three quarters
4309  /// of its size (and, for `cm`/`in` sources, at a small fraction of it — issue
4310  /// 498 follow-up).
4311  #[test]
4312  fn read_svg_dimensions_falls_back_to_width_height() {
4313    let dir = TempDir::new("svg_dim_fallback");
4314    let tmp = dir.join("dims.svg");
4315    std::fs::write(
4316      &tmp,
4317      r#"<svg xmlns="http://www.w3.org/2000/svg" width="123.7pt" height="99.4pt">
4318  <rect/>
4319</svg>"#,
4320    )
4321    .unwrap();
4322    let dims = Graphics::read_svg_dimensions(tmp.to_str().unwrap()).expect("dims");
4323    assert_eq!(dims, (165, 133));
4324  }
4325
4326  /// The no-usable-geometry case must stay `None` all the way through, so the
4327  /// caller writes no `imagewidth`/`imageheight` at all. Emitting a bogus
4328  /// number here is worse than emitting nothing: with no attributes the browser
4329  /// uses the SVG's own intrinsic size, which is right.
4330  #[test]
4331  fn read_svg_dimensions_declines_a_percentage_sized_root() {
4332    let dir = TempDir::new("svg_dim_pct");
4333    let tmp = dir.join("dims.svg");
4334    std::fs::write(
4335      &tmp,
4336      r#"<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%"><rect/></svg>"#,
4337    )
4338    .unwrap();
4339    assert_eq!(Graphics::read_svg_dimensions(tmp.to_str().unwrap()), None);
4340  }
4341
4342  /// Three `<graphics>` nodes over one source: two differ only in their
4343  /// width, which sizes the `<img>` and not the file, one picks a page.
4344  /// `process` must coalesce the two widths into a single conversion and file
4345  /// and run a second one for the page — proven by counting the lines a fake
4346  /// `convert` on `PATH` appends to its log. A width edited and run again
4347  /// keeps the file's name (issue 995 review: `x1.png`, then `x2.png`, after
4348  /// each layout tweak).
4349  ///
4350  /// **The cache must be bypassed for this to mean anything.** The
4351  /// observable here is "how many converter subprocesses ran", and
4352  /// `graphics_cache` is content-addressed against a *host-persistent* root
4353  /// (`$XDG_CACHE_HOME/latexml-oxide/graphics`). With the cache live this
4354  /// test was self-poisoning: the first run stored the shim's output under a
4355  /// key derived from these fixed source bytes, and every later run was
4356  /// served from that entry, spawned nothing, and died on a missing log
4357  /// (issue 401). The two jobs also share one cache key — same bytes, page,
4358  /// density and extension, differing only in destination name — so even a
4359  /// pristine cache could serve job two from job one and see a single log
4360  /// line. `CachePolicy::Bypass` removes both, without touching any env var.
4361  #[test]
4362  #[cfg(unix)]
4363  fn process_coalesces_only_matching_conversion_options() {
4364    use std::os::unix::fs::PermissionsExt;
4365
4366    use crate::{
4367      document::{PostDocument, PostDocumentOptions},
4368      graphics_cache::CachePolicy,
4369    };
4370
4371    let tmp = TempDir::new("graphics_dedupe");
4372    let source = tmp.join("plot.ai");
4373    std::fs::write(&source, "%!PS-Adobe-3.0\n%%BoundingBox: 0 0 100 100\n").unwrap();
4374    let log = tmp.join("convert.log");
4375    let fake_convert = tmp.join("convert");
4376    // Log the args AND write a non-empty file at the dest (the last positional
4377    // arg) — `convert_image` now requires actual output, not just exit 0.
4378    // The log path is derived from `$0` (the kernel hands a shebang script its
4379    // resolved path, so PATH lookup still yields an absolute `dirname`) rather
4380    // than from an env var: one less process-global to synchronise.
4381    std::fs::write(
4382      &fake_convert,
4383      "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$(dirname \"$0\")/convert.log\"\n\
4384       for a in \"$@\"; do d=\"$a\"; done\nprintf x > \"$d\"\nexit 0\n",
4385    )
4386    .unwrap();
4387    let mut perms = std::fs::metadata(&fake_convert).unwrap().permissions();
4388    perms.set_mode(0o755);
4389    std::fs::set_permissions(&fake_convert, perms).unwrap();
4390
4391    let old_path = std::env::var("PATH").unwrap_or_default();
4392    let mut env = EnvGuard::acquire();
4393    env.set("PATH", &format!("{}:{}", tmp.path().display(), old_path));
4394    let xml = format!(
4395      r#"<?xml version="1.0"?>
4396<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="d">
4397  <graphics graphic="plot.ai" candidates="{0}" options="width=20pt"/>
4398  <graphics graphic="plot.ai" candidates="{0}" options="width=40pt"/>
4399  <graphics graphic="plot.ai" candidates="{0}" options="width=20pt,page=2"/>
4400</document>"#,
4401      source.display()
4402    );
4403    let doc_opts = PostDocumentOptions {
4404      destination: Some(tmp.join("out.html").display().to_string()),
4405      source_directory: Some(tmp.path().display().to_string()),
4406      ..Default::default()
4407    };
4408    let doc = PostDocument::new_from_string(&xml, doc_opts).unwrap();
4409    let mut graphics = Graphics::new(None, true).with_cache_policy(CachePolicy::Bypass);
4410    let nodes = graphics.to_process(&doc);
4411    assert_eq!(nodes.len(), 3);
4412
4413    let docs = graphics.process(doc, nodes).unwrap();
4414    let out = docs[0].to_xml_string();
4415    let log_contents = std::fs::read_to_string(&log).unwrap_or_else(|e| {
4416      panic!(
4417        "fake `convert` never ran: no log at {} ({e}). The shim is on PATH and the cache is \
4418         bypassed, so `process` should have spawned it.",
4419        log.display()
4420      )
4421    });
4422    assert_eq!(
4423      log_contents.lines().count(),
4424      2,
4425      "two widths of one source and page should coalesce, but another page needs a conversion \
4426       of its own; convert log was:\n{log_contents}"
4427    );
4428    assert_eq!(out.matches(r#"imagesrc="plot.png""#).count(), 2);
4429    assert_eq!(out.matches(r#"imagesrc="x1.png""#).count(), 1);
4430    // The width edited, a second run into the folder: the same names.
4431    let edited = xml
4432      .replace("width=40pt", "width=30pt")
4433      .replace("width=20pt", "width=25pt");
4434    let doc_opts = PostDocumentOptions {
4435      destination: Some(tmp.join("out.html").display().to_string()),
4436      source_directory: Some(tmp.path().display().to_string()),
4437      ..Default::default()
4438    };
4439    let doc = PostDocument::new_from_string(&edited, doc_opts).unwrap();
4440    let mut graphics = Graphics::new(None, true).with_cache_policy(CachePolicy::Bypass);
4441    let nodes = graphics.to_process(&doc);
4442    let out = graphics.process(doc, nodes).unwrap()[0].to_xml_string();
4443    assert_eq!(out.matches(r#"imagesrc="plot.png""#).count(), 2);
4444    assert_eq!(out.matches(r#"imagesrc="x1.png""#).count(), 1);
4445  }
4446
4447  /// A vector render is cropped through its root `viewBox`, which spans the
4448  /// PDF page in bp; `width`/`height` shrink with it in their own units
4449  /// (`mutool` writes them unitless, `pdftocairo` in `pt`). A box keeping the
4450  /// whole page leaves the file alone. 2605.06510 `trim=0cm 0.25cm 0cm 0cm`.
4451  #[test]
4452  fn crop_svg_narrows_the_view_box() {
4453    let root = |w: &str, h: &str| {
4454      format!(
4455        r#"<?xml version="1.0"?>
4456<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="{w}" height="{h}" viewBox="0 0 200 100">
4457<rect width="200" height="100"/>
4458</svg>
4459"#
4460      )
4461    };
4462    let trim = GraphicxOp::Trim {
4463      l: 100.0,
4464      b: 0.0,
4465      r: 0.0,
4466      t: 50.0,
4467    };
4468    let text = Graphics::crop_svg(&root("200", "100"), &trim)
4469      .unwrap()
4470      .unwrap();
4471    assert_eq!(
4472      latexml_core::util::image::svg_root_tag(&text),
4473      Some(
4474        r#"<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100" height="50" viewBox="100 50 100 50""#
4475      ),
4476      "{text}"
4477    );
4478    assert!(
4479      text.contains(r#"<rect width="200" height="100"/>"#),
4480      "{text}"
4481    );
4482    let viewport = GraphicxOp::Clip {
4483      l: 0.0,
4484      b: 0.0,
4485      r: 100.0,
4486      t: 50.0,
4487    };
4488    let text = Graphics::crop_svg(&root("200pt", "100pt"), &viewport)
4489      .unwrap()
4490      .unwrap();
4491    assert_eq!(
4492      latexml_core::util::image::svg_root_tag(&text),
4493      Some(
4494        r#"<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100pt" height="50pt" viewBox="0 50 100 50""#
4495      ),
4496      "{text}"
4497    );
4498    let whole = GraphicxOp::Clip {
4499      l: 0.0,
4500      b: 0.0,
4501      r: 200.0,
4502      t: 100.0,
4503    };
4504    assert_eq!(Graphics::crop_svg(&root("200", "100"), &whole), Ok(None));
4505  }
4506
4507  /// `trim=`/`viewport=` crop a raster's pixels (Perl `Util/Image.pm` L400-418
4508  /// `Crop`; with or without `clip`, as Perl's "we'll just clip in all cases",
4509  /// L180-185), and the cropped or rotated raster gets a file of its own: the
4510  /// plain use keeps the untouched copy, which `angle=` used to rotate in place.
4511  /// Before, the uncropped image was squeezed into the trimmed box (2510.17772
4512  /// Fig 7). Needs ImageMagick; without it the test says so and returns.
4513  #[test]
4514  fn trim_and_viewport_crop_the_raster_into_its_own_file() {
4515    use crate::{
4516      document::{PostDocument, PostDocumentOptions},
4517      graphics_cache::CachePolicy,
4518    };
4519    // Sibling tests put a fake `convert` on PATH under this lock.
4520    let _env = EnvGuard::acquire();
4521    let convert = im_convert_program();
4522    let magick = |args: &[&str]| {
4523      std::process::Command::new(convert)
4524        .args(args)
4525        .output()
4526        .ok()
4527        .filter(|o| o.status.success())
4528        .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
4529    };
4530    if magick(&["-version"]).is_none() {
4531      eprintln!("SKIP trim_and_viewport_crop_the_raster_into_its_own_file: no `{convert}`");
4532      return;
4533    }
4534    let tmp = TempDir::new("graphics_trim_crop");
4535    let img = tmp.join("img.png");
4536    // 200×100 with no resolution chunk, so 72 dpi (1 px = 1 bp): red and lime
4537    // over blue and yellow.
4538    magick(&[
4539      "-size",
4540      "100x50",
4541      "xc:red",
4542      "xc:lime",
4543      "+append",
4544      "(",
4545      "-size",
4546      "100x50",
4547      "xc:blue",
4548      "xc:yellow",
4549      "+append",
4550      ")",
4551      "-append",
4552      "-define",
4553      "png:exclude-chunk=pHYs,date,time",
4554      img.to_str().unwrap(),
4555    ])
4556    .expect("make the quadrant PNG");
4557    let dest = tmp.join("out").join("out.html");
4558    std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
4559    let trim = "trim=100.375pt 0.0pt 0.0pt 50.1875pt";
4560    let viewport = "viewport=0.0pt 0.0pt 100.375pt 50.1875pt";
4561    let xml = format!(
4562      r#"<?xml version="1.0"?>
4563<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="d">
4564  <graphics graphic="img" candidates="{0}" options="{trim},clip=true" xml:id="g1"/>
4565  <graphics graphic="img" candidates="{0}" options="{viewport},clip=true" xml:id="g2"/>
4566  <graphics graphic="img" candidates="{0}" options="{trim}" xml:id="g3"/>
4567  <graphics graphic="img" candidates="{0}" options="angle=90" xml:id="g4"/>
4568  <graphics graphic="img" candidates="{0}" xml:id="g5"/>
4569</document>"#,
4570      img.display()
4571    );
4572    let doc_opts = PostDocumentOptions {
4573      destination: Some(dest.display().to_string()),
4574      source_directory: Some(tmp.path().display().to_string()),
4575      ..Default::default()
4576    };
4577    let doc = PostDocument::new_from_string(&xml, doc_opts).unwrap();
4578    let mut graphics = Graphics::new(None, true).with_cache_policy(CachePolicy::Bypass);
4579    let nodes = graphics.to_process(&doc);
4580    let out = graphics.process(doc, nodes).unwrap()[0].to_xml_string();
4581    let attr = |id: &str, name: &str| -> String {
4582      let at = out.find(&format!(r#"xml:id="{id}""#)).expect(id);
4583      let start = out[..at].rfind('<').unwrap();
4584      let element = &out[start..at + out[at..].find('>').unwrap()];
4585      let key = format!(r#" {name}=""#);
4586      let value = &element[element
4587        .find(&key)
4588        .unwrap_or_else(|| panic!("{name}: {out}"))
4589        + key.len()..];
4590      value[..value.find('"').unwrap()].to_string()
4591    };
4592    // The size and the colours of each use's output raster.
4593    let raster = |id: &str| {
4594      let file = dest.parent().unwrap().join(attr(id, "imagesrc"));
4595      let file = file.to_str().unwrap();
4596      let size = magick(&[file, "-format", "%wx%h", "info:"]).unwrap();
4597      let histogram = magick(&[file, "-format", "%c", "histogram:info:-"]).unwrap();
4598      let mut colours: Vec<String> = histogram
4599        .split_whitespace()
4600        .filter(|w| w.starts_with('#') && w.len() >= 7)
4601        .map(|w| w[..7].to_string())
4602        .collect();
4603      colours.sort();
4604      (size, colours)
4605    };
4606    let one = |c: &str| vec![c.to_string()];
4607    assert_eq!(raster("g1"), ("100x50".into(), one("#FFFF00")), "{out}");
4608    assert_eq!(raster("g2"), ("100x50".into(), one("#0000FF")), "{out}");
4609    assert_eq!(raster("g3"), ("100x50".into(), one("#FFFF00")), "{out}");
4610    assert_eq!(raster("g4").0, "100x200", "{out}");
4611    let all: Vec<String> = ["#0000FF", "#00FF00", "#FF0000", "#FFFF00"]
4612      .map(String::from)
4613      .to_vec();
4614    assert_eq!(raster("g5"), ("200x100".into(), all), "{out}");
4615    assert_eq!(attr("g5", "imagesrc"), "img.png", "{out}");
4616    for id in ["g1", "g2", "g3", "g4"] {
4617      assert_ne!(
4618        attr(id, "imagesrc"),
4619        "img.png",
4620        "{id} must not share the plain copy: {out}"
4621      );
4622    }
4623    let size = |id: &str| (attr(id, "imagewidth"), attr(id, "imageheight"));
4624    // 72 dpi pixels shown at 96: 100x50 px is 133.33x66.67.
4625    assert_eq!(size("g1"), ("133".into(), "67".into()), "{out}");
4626    assert_eq!(size("g4"), ("133".into(), "267".into()), "{out}");
4627  }
4628
4629  /// A converter is reparented only when its parent is no longer the process that spawned it: a spawner that is
4630  /// itself PID 1 (`latexml_oxide` as a container's entrypoint) keeps its converters (every one exited 127 in the
4631  /// 0.8.0 images, witness 1805.04904), and an orphan adopted by init or by a subreaper is caught.
4632  #[cfg(target_os = "linux")]
4633  #[test]
4634  fn a_converter_whose_spawner_is_pid_one_runs() {
4635    assert!(!reparented(1, 1), "a converter spawned by PID 1 must run");
4636    assert!(!reparented(4242, 4242));
4637    assert!(
4638      reparented(4242, 1),
4639      "an orphan adopted by init must not run unwatched"
4640    );
4641    assert!(
4642      reparented(4242, 77),
4643      "an orphan adopted by a subreaper must not run unwatched"
4644    );
4645  }
4646
4647  /// A PDF or EPS is cropped in the pixels it is rendered at, its render density over 72 per bp, and a raster in its
4648  /// own (its dpi over 72), as pdfTeX trims the box in bp (2011.13011 fig3.pdf: 5669 bp at 26 dpi was cropped at 72,
4649  /// keeping 998×639 pixels of 2048×2048 for 1669×1539). Fixtures `tests/fixtures/trim_quadrants{,_huge}.tex`; each
4650  /// row keeps one quadrant. Needs ImageMagick and Ghostscript; without them the test says so and returns.
4651  #[test]
4652  fn a_vector_render_is_cropped_at_its_density() {
4653    use crate::{
4654      document::{PostDocument, PostDocumentOptions},
4655      graphics_cache::CachePolicy,
4656    };
4657    let _env = EnvGuard::acquire();
4658    let convert = im_convert_program();
4659    let run = |program: &str, args: &[&str]| {
4660      std::process::Command::new(program)
4661        .args(args)
4662        .output()
4663        .ok()
4664        .filter(|o| o.status.success())
4665        .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
4666    };
4667    for (program, probe) in [(convert, "-version"), (gs_program(), "--version")] {
4668      if run(program, &[probe]).is_none() {
4669        eprintln!("SKIP a_vector_render_is_cropped_at_its_density: no `{program}`");
4670        return;
4671      }
4672    }
4673    let tmp = TempDir::new("graphics_vector_crop");
4674    let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
4675    for name in ["trim_quadrants.pdf", "trim_quadrants_huge.pdf"] {
4676      std::fs::copy(fixtures.join(name), tmp.join(name)).unwrap();
4677    }
4678    // trim_quadrants.pdf's page 1 as an EPS, and a 300-dpi PNG of 144x72 bp.
4679    let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 216 108\n%%EndComments\n\
4680               1 0 0 setrgbcolor 0 54 108 54 rectfill 0 1 0 setrgbcolor 108 54 108 54 rectfill\n\
4681               0 0 1 setrgbcolor 0 0 108 54 rectfill 1 1 0 setrgbcolor 108 0 108 54 rectfill\nshowpage\n";
4682    std::fs::write(tmp.join("trim_quadrants.eps"), eps).unwrap();
4683    let png = tmp.join("q300.png");
4684    run(convert, &[
4685      "-size",
4686      "300x150",
4687      "xc:red",
4688      "xc:lime",
4689      "+append",
4690      "(",
4691      "-size",
4692      "300x150",
4693      "xc:blue",
4694      "xc:yellow",
4695      "+append",
4696      ")",
4697      "-append",
4698      "-units",
4699      "PixelsPerInch",
4700      "-density",
4701      "300",
4702      png.to_str().unwrap(),
4703    ])
4704    .expect("make the 300-dpi PNG");
4705    // graphicx's lengths in pt, as the engine writes them: 108bp = 108.405pt, 54bp = 54.2025pt.
4706    let rows = [
4707      (
4708        "pdf",
4709        "trim_quadrants.pdf",
4710        "trim=108.405pt 0.0pt 0.0pt 54.2025pt,clip=true",
4711        "180x90",
4712        "#FFFF00",
4713      ),
4714      (
4715        "viewport",
4716        "trim_quadrants.pdf",
4717        "viewport=0.0pt 0.0pt 108.405pt 54.2025pt,clip=true",
4718        "180x90",
4719        "#0000FF",
4720      ),
4721      (
4722        "page2",
4723        "trim_quadrants.pdf",
4724        "page=2,trim=0.0pt 108.405pt 54.2025pt 0.0pt,clip=true",
4725        "90x180",
4726        "#00FFFF",
4727      ),
4728      (
4729        "angle",
4730        "trim_quadrants.pdf",
4731        "trim=108.405pt 0.0pt 0.0pt 54.2025pt,clip=true,angle=90",
4732        "90x180",
4733        "#FFFF00",
4734      ),
4735      (
4736        "huge",
4737        "trim_quadrants_huge.pdf",
4738        "trim=3011.25pt 0.0pt 0.0pt 1505.625pt,clip=true",
4739        "1000x500",
4740        "#FFFF00",
4741      ),
4742      (
4743        "eps",
4744        "trim_quadrants.eps",
4745        "trim=108.405pt 0.0pt 0.0pt 54.2025pt,clip=true",
4746        "180x90",
4747        "#FFFF00",
4748      ),
4749      (
4750        "png300",
4751        "q300.png",
4752        "trim=72.27pt 0.0pt 0.0pt 36.135pt,clip=true",
4753        "300x150",
4754        "#FFFF00",
4755      ),
4756    ];
4757    // A PDF is rasterized by mutool or pdftocairo; without either, only the ImageMagick/Ghostscript fallback is
4758    // left, which the PDF rows do not exercise (on Windows CI it left them unconverted). Those rows then SKIP visibly,
4759    // and fail where `LATEXML_SVG_TESTS` says the converters are installed (Linux CI); the EPS and PNG rows still run.
4760    let pdf_rasterizer = ["mutool", "pdftocairo"].iter().any(|tool| {
4761      std::process::Command::new(tool)
4762        .arg("--version")
4763        .output()
4764        .is_ok()
4765    });
4766    if !pdf_rasterizer {
4767      assert!(
4768        std::env::var_os("LATEXML_SVG_TESTS").is_none(),
4769        "LATEXML_SVG_TESTS is set but neither mutool nor pdftocairo is on PATH"
4770      );
4771      eprintln!(
4772        "SKIP a_vector_render_is_cropped_at_its_density, PDF rows: neither mutool nor pdftocairo on PATH"
4773      );
4774    }
4775    let rows: Vec<_> = rows
4776      .into_iter()
4777      .filter(|(_, file, ..)| pdf_rasterizer || !file.ends_with(".pdf"))
4778      .collect();
4779    let nodes: String = rows
4780      .iter()
4781      .map(|(id, file, options, ..)| {
4782        let path = tmp.join(file);
4783        format!(
4784          r#"<graphics graphic="{file}" candidates="{}" options="{options}" xml:id="{id}"/>"#,
4785          path.display()
4786        )
4787      })
4788      .collect();
4789    let xml = format!(
4790      r#"<?xml version="1.0"?><document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="d">{nodes}</document>"#
4791    );
4792    let dest = tmp.join("out").join("out.html");
4793    std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
4794    let doc_opts = PostDocumentOptions {
4795      destination: Some(dest.display().to_string()),
4796      source_directory: Some(tmp.path().display().to_string()),
4797      ..Default::default()
4798    };
4799    let doc = PostDocument::new_from_string(&xml, doc_opts).unwrap();
4800    // A PDF over the 1 KiB threshold is rasterized, as a large or raster-bearing one is.
4801    let mut graphics = Graphics::new(None, true)
4802      .with_svg_threshold_kb(1)
4803      .with_cache_policy(CachePolicy::Bypass);
4804    let nodes = graphics.to_process(&doc);
4805    let out = graphics.process(doc, nodes).unwrap()[0].to_xml_string();
4806    let kept = |id: &str| {
4807      let at = out.find(&format!(r#"xml:id="{id}""#)).expect(id);
4808      let element = &out[out[..at].rfind('<').unwrap()..at + out[at..].find('>').unwrap()];
4809      let src = element
4810        .split(r#"imagesrc=""#)
4811        .nth(1)
4812        .unwrap_or_else(|| panic!("{element}"));
4813      let file = dest.parent().unwrap().join(&src[..src.find('"').unwrap()]);
4814      let file = file.to_str().unwrap();
4815      let got = run(convert, &[file, "-format", "%wx%h", "info:"]).unwrap();
4816      let histogram = run(convert, &[file, "-format", "%c", "histogram:info:-"]).unwrap();
4817      let mut colours: Vec<&str> = histogram
4818        .split_whitespace()
4819        .filter(|w| w.starts_with('#') && w.len() >= 7)
4820        .map(|w| &w[..7])
4821        .collect();
4822      colours.sort();
4823      format!("{id} {} {}", got, colours.join(","))
4824    };
4825    let got: Vec<String> = rows.iter().map(|row| kept(row.0)).collect();
4826    let want: Vec<String> = rows
4827      .iter()
4828      .map(|(id, _, _, size, colour)| format!("{id} {size} {colour}"))
4829      .collect();
4830    assert_eq!(got, want, "{out}");
4831  }
4832
4833  /// Post-process `rows` (id, candidates joined by `,`, options) from `src` into `dest`, as `<graphics>` nodes; per
4834  /// row the object's file and size, and an SVG's root `width`x`height`, `viewBox` and `preserveAspectRatio`, or for
4835  /// another file whether it holds its first candidate's bytes. `None` when neither SVG tool is installed.
4836  fn sized_render_rows(
4837    test: &str,
4838    src: &Path,
4839    dest: &Path,
4840    rows: &[(&str, &str, &str)],
4841  ) -> Option<Vec<(String, bool)>> {
4842    use latexml_core::util::image::{svg_attr_value, svg_root_tag};
4843
4844    use crate::{
4845      document::{PostDocument, PostDocumentOptions},
4846      graphics_cache::CachePolicy,
4847    };
4848    if !["mutool", "pdftocairo"]
4849      .iter()
4850      .any(|tool| svg_tool_or_skip(tool, test))
4851    {
4852      return None;
4853    }
4854    let nodes: String = rows
4855      .iter()
4856      .map(|(id, files, options)| {
4857        let candidates: Vec<String> = files
4858          .split(',')
4859          .map(|f| src.join(f).display().to_string())
4860          .collect();
4861        format!(
4862          r#"<graphics graphic="{}" candidates="{}" options="{options}" xml:id="{id}"/>"#,
4863          files.split(',').next().unwrap(),
4864          candidates.join(",")
4865        )
4866      })
4867      .collect();
4868    let xml = format!(
4869      r#"<?xml version="1.0"?><document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="d">{nodes}</document>"#
4870    );
4871    std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
4872    let doc_opts = PostDocumentOptions {
4873      destination: Some(dest.display().to_string()),
4874      source_directory: Some(src.display().to_string()),
4875      ..Default::default()
4876    };
4877    let doc = PostDocument::new_from_string(&xml, doc_opts).unwrap();
4878    let mut graphics = Graphics::new(None, true).with_cache_policy(CachePolicy::Bypass);
4879    let nodes = graphics.to_process(&doc);
4880    let out = graphics.process(doc, nodes).unwrap()[0].to_xml_string();
4881    let attr = |element: &str, name: &str| {
4882      svg_attr_value(element, name)
4883        .map(str::to_string)
4884        .unwrap_or_default()
4885    };
4886    let seen = |&(id, files, _): &(&str, &str, &str)| {
4887      let at = out.find(&format!(r#"xml:id="{id}""#)).expect(id);
4888      let element = &out[out[..at].rfind('<').unwrap()..at + out[at..].find('>').unwrap()];
4889      let file_src = attr(element, "imagesrc");
4890      let object = format!(
4891        "{file_src} {}x{}",
4892        attr(element, "imagewidth"),
4893        attr(element, "imageheight")
4894      );
4895      let file = std::fs::read(dest.parent().unwrap().join(&file_src)).unwrap();
4896      if !file_src.ends_with(".svg") {
4897        let first = files.split(',').next().unwrap();
4898        return (object, file == std::fs::read(src.join(first)).unwrap());
4899      }
4900      let text = String::from_utf8(file).unwrap();
4901      let root = svg_root_tag(&text).unwrap();
4902      let root = format!(
4903        "{} {}x{} viewBox={} par={}",
4904        file_src,
4905        attr(root, "width"),
4906        attr(root, "height"),
4907        attr(root, "viewBox"),
4908        attr(root, "preserveAspectRatio")
4909      );
4910      (format!("{object} | {root}"), true)
4911    };
4912    Some(rows.iter().map(seen).collect())
4913  }
4914
4915  /// A sized vector render is its display size, as Perl's raster is (`Util/Image.pm` L382-389): the SVG root's
4916  /// `width`/`height` are the `<object>`'s, its `viewBox` the render's, and each size is a file of its own, the first
4917  /// the stem. A stylesheet that sizes the object `auto` (ar5iv.css) otherwise showed the render's own size (1605.07806).
4918  /// A non-positive factor (`scale=-1` turns the figure, `width=-100pt` reflects it) keeps the natural render: its root
4919  /// sized 1x1 hid the figure.
4920  #[test]
4921  fn a_sized_vector_render_carries_its_display_size() {
4922    let tmp = TempDir::new("graphics_svg_size");
4923    let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
4924    for name in ["trim_quadrants.pdf", "grid64.png"] {
4925      std::fs::copy(fixtures.join(name), tmp.join(name)).unwrap();
4926    }
4927    // (id, source, options); trim_quadrants.pdf's page 1 is 216x108 bp.
4928    let rows = [
4929      (
4930        "height",
4931        "trim_quadrants.pdf",
4932        "height=170.0pt,keepaspectratio=true",
4933      ),
4934      (
4935        "again",
4936        "trim_quadrants.pdf",
4937        "height=170.0pt,keepaspectratio=true",
4938      ),
4939      (
4940        "width",
4941        "trim_quadrants.pdf",
4942        "width=345.0pt,keepaspectratio=true",
4943      ),
4944      ("natural", "trim_quadrants.pdf", ""),
4945      (
4946        "trim",
4947        "trim_quadrants.pdf",
4948        "trim=108.405pt 0.0pt 0.0pt 54.2025pt,clip=true,width=100.0pt",
4949      ),
4950      (
4951        "stretch",
4952        "trim_quadrants.pdf",
4953        "width=100.0pt,height=100.0pt",
4954      ),
4955      ("scale", "trim_quadrants.pdf", "scale=0.5"),
4956      ("xscale", "trim_quadrants.pdf", "xscale=0.5"),
4957      ("raster", "grid64.png", "width=100.0pt,keepaspectratio=true"),
4958      ("negscale", "trim_quadrants.pdf", "scale=-1"),
4959      (
4960        "negwidth",
4961        "trim_quadrants.pdf",
4962        "width=-100.0pt,keepaspectratio=true",
4963      ),
4964    ];
4965    let dest = tmp.join("out").join("out.html");
4966    let Some(got) = sized_render_rows(
4967      "a_sized_vector_render_carries_its_display_size",
4968      tmp.path(),
4969      &dest,
4970      &rows,
4971    ) else {
4972      return;
4973    };
4974    // The unsized render keeps the converter's root: mutool's `216` bp read as px, pdftocairo's `216pt` (SVGSIZE).
4975    let natural = &got[3].0;
4976    let (nw, nh, ow, oh) = if natural.contains(" 216ptx108pt ") {
4977      ("216pt", "108pt", 288, 144)
4978    } else {
4979      ("216", "108", 216, 108)
4980    };
4981    // A non-positive factor's object is 1x1 (pre-existing); its file is the natural render.
4982    let natural = format!("x2.svg {nw}x{nh} viewBox=0 0 216 108 par=");
4983    let want: Vec<(String, bool)> = [
4984      "trim_quadrants.svg 452x226 | trim_quadrants.svg 452x226 viewBox=0 0 216 108 par="
4985        .to_string(),
4986      "trim_quadrants.svg 452x226 | trim_quadrants.svg 452x226 viewBox=0 0 216 108 par="
4987        .to_string(),
4988      "x1.svg 459x230 | x1.svg 459x230 viewBox=0 0 216 108 par=".to_string(),
4989      format!("x2.svg {ow}x{oh} | {natural}"),
4990      "x3.svg 133x67 | x3.svg 133x67 viewBox=108 54 108 54 par=".to_string(),
4991      "x4.svg 133x133 | x4.svg 133x133 viewBox=0 0 216 108 par=none".to_string(),
4992      format!(
4993        "x5.svg {0}x{1} | x5.svg {0}x{1} viewBox=0 0 216 108 par=",
4994        ow / 2,
4995        oh / 2
4996      ),
4997      format!(
4998        "x6.svg {0}x{1} | x6.svg {0}x{1} viewBox=0 0 216 108 par=none",
4999        ow / 2,
5000        oh
5001      ),
5002      "grid64.png 133x133".to_string(),
5003      format!("x2.svg 1x1 | {natural}"),
5004      format!("x2.svg 1x1 | {natural}"),
5005    ]
5006    .into_iter()
5007    .map(|row| (row, true))
5008    .collect();
5009    assert_eq!(got, want);
5010  }
5011
5012  /// Converted again in place (the destination the source's directory), a figure reads the author's PDF, not the
5013  /// `<stem>.svg` our first run wrote beside it (its cache records it, OD #1157 (7)): every run gives the same names
5014  /// and roots, and a crop stays cropped (it was copied uncropped, with a Warning). The stem beside the source is the
5015  /// natural render's, so a run without the cache, which reads it back, still shows the natural figure at its size.
5016  #[test]
5017  fn a_figure_converted_in_place_again_reads_the_authors_source() {
5018    let tmp = TempDir::new("graphics_svg_inplace");
5019    let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
5020    std::fs::copy(
5021      fixtures.join("trim_quadrants.pdf"),
5022      tmp.join("trim_quadrants.pdf"),
5023    )
5024    .unwrap();
5025    let test = "a_figure_converted_in_place_again_reads_the_authors_source";
5026    let dest = tmp.join("inplace.html");
5027    // graphicx lists every `trim_quadrants.*` it finds, the earlier runs' outputs too.
5028    let run = || {
5029      let files: Vec<&str> = ["pdf", "png", "svg"]
5030        .into_iter()
5031        .filter(|ext| tmp.join(&format!("trim_quadrants.{ext}")).exists())
5032        .map(|ext| match ext {
5033          "pdf" => "trim_quadrants.pdf",
5034          "png" => "trim_quadrants.png",
5035          _ => "trim_quadrants.svg",
5036        })
5037        .collect();
5038      let files = files.join(",");
5039      sized_render_rows(test, tmp.path(), &dest, &[
5040        ("wide", &files, "width=200.0pt,keepaspectratio=true"),
5041        ("natural", &files, ""),
5042        ("low", &files, "height=40.0pt,keepaspectratio=true"),
5043        (
5044          "trim",
5045          &files,
5046          "trim=108.405pt 0.0pt 0.0pt 54.2025pt,clip=true",
5047        ),
5048      ])
5049    };
5050    let Some(first) = run() else {
5051      return;
5052    };
5053    let (nw, nh, ow, oh) = if first[1].0.contains(" 216ptx108pt ") {
5054      ("216pt", "108pt", 288, 144)
5055    } else {
5056      ("216", "108", 216, 108)
5057    };
5058    let (cw, ch) = if nw == "216pt" {
5059      ("108pt", "54pt")
5060    } else {
5061      ("108", "54")
5062    };
5063    let want: Vec<(String, bool)> = [
5064      "x1.svg 266x133 | x1.svg 266x133 viewBox=0 0 216 108 par=".to_string(),
5065      format!(
5066        "trim_quadrants.svg {ow}x{oh} | trim_quadrants.svg {nw}x{nh} viewBox=0 0 216 108 par="
5067      ),
5068      "x2.svg 107x54 | x2.svg 107x54 viewBox=0 0 216 108 par=".to_string(),
5069      format!(
5070        "x3.svg {}x{} | x3.svg {cw}x{ch} viewBox=108 54 108 54 par=",
5071        ow / 2,
5072        oh / 2
5073      ),
5074    ]
5075    .into_iter()
5076    .map(|row| (row, true))
5077    .collect();
5078    assert_eq!(first, want);
5079    assert_eq!(run().unwrap(), want, "the second run");
5080    assert_eq!(run().unwrap(), want, "the third run");
5081    let mut files: Vec<String> = std::fs::read_dir(tmp.path())
5082      .unwrap()
5083      .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
5084      .filter(|name| !name.starts_with("LaTeXML-oxide.cache") && !name.starts_with("inplace"))
5085      .collect();
5086    files.sort();
5087    assert_eq!(files, [
5088      "trim_quadrants.pdf",
5089      "trim_quadrants.svg",
5090      "x1.svg",
5091      "x2.svg",
5092      "x3.svg"
5093    ]);
5094    for side in ["", "-wal", "-shm"] {
5095      let _ = std::fs::remove_file(tmp.join(&format!("LaTeXML-oxide.cache{side}")));
5096    }
5097    let natural = &run().unwrap()[1].0;
5098    assert!(
5099      natural.contains(&format!(" {ow}x{oh} | "))
5100        && natural.ends_with(&format!(" {nw}x{nh} viewBox=0 0 216 108 par=")),
5101      "without the cache: {natural}"
5102    );
5103  }
5104
5105  /// A crop's routing and size, with a fake `convert` that logs its arguments
5106  /// and writes a placeholder: a 200×100 PNG with `trim=100 0 0 50,clip` gets a
5107  /// file of its own, cropped `100x50+100+50` and shown 100×50 — `x2.png`, as
5108  /// the author's own plain `x1.png` is copied beside it and must not be
5109  /// overwritten. `trim=0 0 0 0` (with `clip`, a common idiom) crops nothing,
5110  /// so that PNG is only copied — no `convert` run, and no warning: a raster is
5111  /// never refused.
5112  #[test]
5113  #[cfg(unix)]
5114  fn a_crop_gets_its_own_file_and_a_zero_trim_none() {
5115    use std::os::unix::fs::PermissionsExt;
5116
5117    use latexml_core::common::error::{LogStatus, get_status};
5118
5119    use crate::{
5120      document::{PostDocument, PostDocumentOptions},
5121      graphics_cache::CachePolicy,
5122    };
5123
5124    let tmp = TempDir::new("graphics_crop_route");
5125    // A PNG signature and IHDR: all the size readers consult.
5126    let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
5127    png.extend_from_slice(&13u32.to_be_bytes());
5128    png.extend_from_slice(b"IHDR");
5129    png.extend_from_slice(&200u32.to_be_bytes());
5130    png.extend_from_slice(&100u32.to_be_bytes());
5131    png.extend_from_slice(&[8, 2, 0, 0, 0, 0, 0, 0, 0]);
5132    png.extend_from_slice(&[0u8; 16]);
5133    let img = tmp.join("img.png");
5134    std::fs::write(&img, &png).unwrap();
5135    // The author's own `x1.png`, another picture (a byte past its header).
5136    let authors_png = [png.clone(), vec![1]].concat();
5137    let authors_x1 = tmp.join("x1.png");
5138    std::fs::write(&authors_x1, &authors_png).unwrap();
5139    let log = tmp.join("convert.log");
5140    let fake_convert = tmp.join("convert");
5141    std::fs::write(
5142      &fake_convert,
5143      "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$(dirname \"$0\")/convert.log\"\n\
5144       for a in \"$@\"; do d=\"$a\"; done\nprintf x > \"$d\"\nexit 0\n",
5145    )
5146    .unwrap();
5147    let mut perms = std::fs::metadata(&fake_convert).unwrap().permissions();
5148    perms.set_mode(0o755);
5149    std::fs::set_permissions(&fake_convert, perms).unwrap();
5150    let mut env = EnvGuard::acquire();
5151    let old_path = std::env::var("PATH").unwrap_or_default();
5152    env.set("PATH", &format!("{}:{}", tmp.path().display(), old_path));
5153
5154    let dest = tmp.join("out").join("out.html");
5155    std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
5156    let xml = format!(
5157      r#"<?xml version="1.0"?>
5158<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="d">
5159  <graphics graphic="img" candidates="{0}" options="trim=100.375pt 0.0pt 0.0pt 50.1875pt,clip=true" xml:id="g1"/>
5160  <graphics graphic="img" candidates="{0}" options="trim=0.0pt 0.0pt 0.0pt 0.0pt,clip=true" xml:id="g2"/>
5161  <graphics graphic="x1" candidates="{1}" xml:id="g3"/>
5162</document>"#,
5163      img.display(),
5164      authors_x1.display()
5165    );
5166    let doc_opts = PostDocumentOptions {
5167      destination: Some(dest.display().to_string()),
5168      source_directory: Some(tmp.path().display().to_string()),
5169      ..Default::default()
5170    };
5171    let doc = PostDocument::new_from_string(&xml, doc_opts).unwrap();
5172    let mut graphics = Graphics::new(None, true).with_cache_policy(CachePolicy::Bypass);
5173    let nodes = graphics.to_process(&doc);
5174    let warnings = get_status(LogStatus::Warning);
5175    let out = graphics.process(doc, nodes).unwrap()[0].to_xml_string();
5176    assert_eq!(get_status(LogStatus::Warning), warnings, "{out}");
5177    let invocations = std::fs::read_to_string(&log).unwrap_or_default();
5178    assert_eq!(invocations.lines().count(), 1, "{invocations}");
5179    assert!(
5180      invocations.contains("-crop 100x50+100+50 +repage"),
5181      "{invocations}"
5182    );
5183    // 72 dpi pixels shown at 96.
5184    for (id, src, w, h) in [
5185      ("g1", "x2.png", 133, 67),
5186      ("g2", "img.png", 267, 133),
5187      ("g3", "x1.png", 267, 133),
5188    ] {
5189      let at = out.find(&format!(r#"xml:id="{id}""#)).unwrap();
5190      let element = &out[out[..at].rfind('<').unwrap()..at + out[at..].find('>').unwrap()];
5191      for attr in [
5192        format!(r#"imagesrc="{src}""#),
5193        format!(r#"imagewidth="{w}""#),
5194        format!(r#"imageheight="{h}""#),
5195      ] {
5196        assert!(element.contains(&attr), "{id}: {attr} missing in {element}");
5197      }
5198    }
5199    let copied = std::fs::read(dest.parent().unwrap().join("x1.png")).unwrap();
5200    assert_eq!(
5201      copied, authors_png,
5202      "the author's x1.png must reach the output unchanged"
5203    );
5204  }
5205
5206  /// #791: `page=` on a single-page format (SVG, PNG, JPEG) selects nothing, as pdfTeX ignores it on a PNG:
5207  /// the source is copied as it is, with its size, exactly as without `page=` — never re-encoded by `convert`.
5208  #[test]
5209  #[cfg(unix)]
5210  fn a_single_page_source_ignores_page() {
5211    use std::os::unix::fs::PermissionsExt;
5212
5213    use crate::{
5214      document::{PostDocument, PostDocumentOptions},
5215      graphics_cache::CachePolicy,
5216    };
5217
5218    let tmp = TempDir::new("graphics_single_page");
5219    let svg_body = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100pt" height="50pt" viewBox="0 0 100 50"><rect/></svg>"#;
5220    let svg = tmp.join("draw.svg");
5221    std::fs::write(&svg, svg_body).unwrap();
5222    let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
5223    png.extend_from_slice(&13u32.to_be_bytes());
5224    png.extend_from_slice(b"IHDR");
5225    png.extend_from_slice(&200u32.to_be_bytes());
5226    png.extend_from_slice(&100u32.to_be_bytes());
5227    png.extend_from_slice(&[8, 2, 0, 0, 0, 0, 0, 0, 0]);
5228    png.extend_from_slice(&[0u8; 16]);
5229    let img = tmp.join("img.png");
5230    std::fs::write(&img, &png).unwrap();
5231    // A baseline JPEG's SOF0 frame header: 200 x 100.
5232    let jpg_bytes: &[u8] = &[
5233      0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x11, 0x08, 0x00, 0x64, 0x00, 0xC8, 0x03, 0x01, 0x22, 0x00,
5234      0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xFF, 0xD9,
5235    ];
5236    let jpg = tmp.join("pic.jpg");
5237    std::fs::write(&jpg, jpg_bytes).unwrap();
5238
5239    let log = tmp.join("convert.log");
5240    let fake_convert = tmp.join("convert");
5241    std::fs::write(
5242      &fake_convert,
5243      "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$(dirname \"$0\")/convert.log\"\n\
5244       for a in \"$@\"; do d=\"$a\"; done\nprintf x > \"$d\"\nexit 0\n",
5245    )
5246    .unwrap();
5247    let mut perms = std::fs::metadata(&fake_convert).unwrap().permissions();
5248    perms.set_mode(0o755);
5249    std::fs::set_permissions(&fake_convert, perms).unwrap();
5250    let mut env = EnvGuard::acquire();
5251    let old_path = std::env::var("PATH").unwrap_or_default();
5252    env.set("PATH", &format!("{}:{}", tmp.path().display(), old_path));
5253
5254    let dest = tmp.join("out").join("out.html");
5255    std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
5256    let xml = format!(
5257      r#"<?xml version="1.0"?>
5258<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="d">
5259  <graphics graphic="draw" candidates="{0}" options="page=1" xml:id="g1"/>
5260  <graphics graphic="draw" candidates="{0}" xml:id="g2"/>
5261  <graphics graphic="draw" candidates="{0}" options="page=2" xml:id="g3"/>
5262  <graphics graphic="img" candidates="{1}" options="page=2" xml:id="g4"/>
5263  <graphics graphic="pic" candidates="{2}" options="page=1" xml:id="g5"/>
5264</document>"#,
5265      svg.display(),
5266      img.display(),
5267      jpg.display()
5268    );
5269    let doc_opts = PostDocumentOptions {
5270      destination: Some(dest.display().to_string()),
5271      source_directory: Some(tmp.path().display().to_string()),
5272      ..Default::default()
5273    };
5274    let doc = PostDocument::new_from_string(&xml, doc_opts).unwrap();
5275    let mut graphics = Graphics::new(None, true).with_cache_policy(CachePolicy::Bypass);
5276    let nodes = graphics.to_process(&doc);
5277    let out = graphics.process(doc, nodes).unwrap()[0].to_xml_string();
5278    let invocations = std::fs::read_to_string(&log).unwrap_or_default();
5279    assert_eq!(invocations, "", "no single-page source reaches `convert`");
5280    let element = |id: &str| {
5281      let at = out.find(&format!(r#"xml:id="{id}""#)).unwrap();
5282      let tag = &out[out[..at].rfind('<').unwrap()..at + out[at..].find('>').unwrap()];
5283      let attr = |name: &str| {
5284        let at = tag.find(&format!(" {name}=\""))? + name.len() + 3;
5285        Some(tag[at..at + tag[at..].find('"')?].to_string())
5286      };
5287      (attr("imagesrc"), attr("imagewidth"), attr("imageheight"))
5288    };
5289    let svg_size = element("g2");
5290    assert_eq!(svg_size.0.as_deref(), Some("draw.svg"), "{out}");
5291    assert!(svg_size.1.is_some() && svg_size.2.is_some(), "{out}");
5292    for id in ["g1", "g3"] {
5293      assert_eq!(element(id), svg_size, "{id}: as without page=; {out}");
5294    }
5295    // 200x100 px stating no resolution: 72 dpi, shown at 96.
5296    let raster = |src: &str| {
5297      (
5298        Some(src.to_string()),
5299        Some("267".to_string()),
5300        Some("133".to_string()),
5301      )
5302    };
5303    assert_eq!(element("g4"), raster("img.png"), "{out}");
5304    assert_eq!(element("g5"), raster("pic.jpg"), "{out}");
5305    let out_dir = dest.parent().unwrap();
5306    assert_eq!(
5307      std::fs::read_to_string(out_dir.join("draw.svg")).unwrap(),
5308      svg_body
5309    );
5310    assert_eq!(std::fs::read(out_dir.join("img.png")).unwrap(), png);
5311    assert_eq!(std::fs::read(out_dir.join("pic.jpg")).unwrap(), jpg_bytes);
5312  }
5313
5314  /// `angle=` on a **non-raster** source must not reach `convert`.
5315  ///
5316  /// Perl `Post/Graphics.pm` L264-271 refuses non-scaling transforms on a type
5317  /// whose `raster` property is false, warns `limitation`, and trivializes the
5318  /// transform. Rust's `svg` entry carries `raster: Some(false)` but nothing
5319  /// read it, so `Plan::Copy` handed IM a vector source and a `.svg`
5320  /// destination — IM rasterizes via its SVG delegate and writes the raster
5321  /// back under the `.svg` name, leaving the bundle with a file that is no
5322  /// longer the drawing it claims to be.
5323  ///
5324  /// A fake `convert` on PATH makes this observable without ImageMagick: it
5325  /// logs its arguments and overwrites its destination, so "never invoked" is
5326  /// the absence of a log AND an unchanged destination file. The raster half of
5327  /// the contract still has to hold, so the same document rotates a PNG.
5328  #[test]
5329  #[cfg(unix)]
5330  fn rotation_is_dropped_for_non_raster_sources_but_kept_for_raster() {
5331    use std::os::unix::fs::PermissionsExt;
5332
5333    use crate::{
5334      document::{PostDocument, PostDocumentOptions},
5335      graphics_cache::CachePolicy,
5336    };
5337
5338    let tmp = TempDir::new("graphics_nonraster_rotate");
5339    let svg_body = r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40"><rect/></svg>"#;
5340    let svg = tmp.join("draw.svg");
5341    std::fs::write(&svg, svg_body).unwrap();
5342    // A 1×1 PNG: enough for `imagesize`, and a raster type, so it MUST rotate.
5343    let png = tmp.join("dot.png");
5344    std::fs::write(&png, ONE_PIXEL_PNG).unwrap();
5345
5346    let log = tmp.join("convert.log");
5347    let fake_convert = tmp.join("convert");
5348    std::fs::write(
5349      &fake_convert,
5350      "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$(dirname \"$0\")/convert.log\"\n\
5351       for a in \"$@\"; do d=\"$a\"; done\nprintf x > \"$d\"\nexit 0\n",
5352    )
5353    .unwrap();
5354    let mut perms = std::fs::metadata(&fake_convert).unwrap().permissions();
5355    perms.set_mode(0o755);
5356    std::fs::set_permissions(&fake_convert, perms).unwrap();
5357
5358    let old_path = std::env::var("PATH").unwrap_or_default();
5359    let mut env = EnvGuard::acquire();
5360    env.set("PATH", &format!("{}:{}", tmp.path().display(), old_path));
5361
5362    let dest = tmp.join("sub").join("out.html");
5363    std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
5364    let xml = format!(
5365      r#"<?xml version="1.0"?>
5366<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="d">
5367  <graphics graphic="draw" candidates="{}" options="angle=90" xml:id="g1"/>
5368  <graphics graphic="dot" candidates="{}" options="angle=90" xml:id="g2"/>
5369</document>"#,
5370      svg.display(),
5371      png.display()
5372    );
5373    let doc_opts = PostDocumentOptions {
5374      destination: Some(dest.display().to_string()),
5375      source_directory: Some(tmp.path().display().to_string()),
5376      ..Default::default()
5377    };
5378    let doc = PostDocument::new_from_string(&xml, doc_opts).unwrap();
5379    let mut graphics = Graphics::new(None, true).with_cache_policy(CachePolicy::Bypass);
5380    let nodes = graphics.to_process(&doc);
5381    assert_eq!(nodes.len(), 2);
5382    graphics.process(doc, nodes).unwrap();
5383
5384    let out_svg = dest.parent().unwrap().join("draw.svg");
5385    assert_eq!(
5386      std::fs::read_to_string(&out_svg).ok().as_deref(),
5387      Some(svg_body),
5388      "the copied SVG must be the original drawing, not a `convert` rewrite"
5389    );
5390    // One line per invocation; the turn line names its source AND its scratch
5391    // file, so match lines rather than occurrences.
5392    let invocations = std::fs::read_to_string(&log).unwrap_or_default();
5393    let calls_for = |name: &str| invocations.lines().filter(|l| l.contains(name)).count();
5394    assert_eq!(
5395      calls_for("draw.svg"),
5396      0,
5397      "`convert` must not be invoked for a non-raster source; log was:\n{invocations}"
5398    );
5399    // The rotated raster is a file of its own (`xN.png`), turned once.
5400    assert_eq!(
5401      calls_for("-rotate"),
5402      1,
5403      "a raster source with angle= must still be rotated; log was:\n{invocations}"
5404    );
5405  }
5406
5407  /// Characterization matrix for the post-side graphicx algebra.
5408  ///
5409  /// `apply_graphicx_transforms` works in device pixels at the effective DPI (96, the CSS inch, unless a
5410  /// `<?latexml DPI=?>` PI says otherwise; Perl's 100 until OD #1189). Each row is the box pdfTeX sets x 96/72.27, up to
5411  /// Perl's `ceil` at a sizing step and the nearest pixel at the end.
5412  ///
5413  /// Source is 200x100 px at 72 dpi (it states none), so 200.75pt x 100.375pt as pdfTeX sets it. Notes on rows:
5414  ///
5415  /// * `width=100pt` -> 133 px: 100pt = 99.6264bp, x 96/72 = 132.84, ceil. A bp is 1/72 in: Perl's `DPI/72.27`
5416  ///   (Util/Image.pm:223) made it 137.85 at DPI 100, 72/72.27 of the box (KNOWN_PERL_ERRORS #1142).
5417  /// * `width=1in` -> 96 px, the CSS inch. `width=1in` / `width=2cm` are unreachable from ordinary LaTeX —
5418  ///   `graphicx_sty` normalizes to pt first (`width=2cm` arrives as `width=56.9055pt`) — pinned to stay honest about
5419  ///   what the parser accepts.
5420  /// * `angle=90` swaps the box via the true rotated bounding box, which is also what `convert -rotate` writes for an
5421  ///   oblique angle.
5422  /// * The `width=137.9979pt` row is issue 498's own witness: 184 px (191 at Perl's 100 DPI and bp-as-pt).
5423  #[test]
5424  fn apply_graphicx_transforms_matrix() {
5425    #[rustfmt::skip]
5426    let matrix: &[(&str, u32, u32)] = &[
5427      ("",                                     267, 133), // 200.75pt x 96/72.27 = 266.67
5428      ("width=100pt",                          133,  67),
5429      ("width=100pt,keepaspectratio=true",     133,  67),
5430      ("scale=0.5",                            134,  67), // ceil(133.33)
5431      ("height=25pt,keepaspectratio=true",      67,  34),
5432      ("width=100pt,height=80pt",              133, 107),
5433      ("width=1in,keepaspectratio=true",        96,  48), // the CSS inch
5434      ("width=2cm",                             76,  38), // 2cm = 0.787in
5435      ("angle=90",                             133, 267),
5436      ("width=137.9979pt,keepaspectratio=true", 184,  92), // issue 498 witness
5437    ];
5438    // Report every divergence at once: when this matrix moves it is normally
5439    // because a shared rule changed, and the whole delta is the signal.
5440    let mut deltas = Vec::new();
5441    for (opts, want_w, want_h) in matrix {
5442      let got = Graphics::apply_graphicx_transforms(200, 100, opts, 96);
5443      if got != (*want_w, *want_h) {
5444        deltas.push(format!(
5445          "  [{opts}] pinned ({want_w}, {want_h})  got {got:?}"
5446        ));
5447      }
5448    }
5449    assert!(
5450      deltas.is_empty(),
5451      "{} of {} pinned rows moved:\n{}",
5452      deltas.len(),
5453      matrix.len(),
5454      deltas.join("\n")
5455    );
5456  }
5457
5458  /// One inch is 96 px whatever the source (OD #1189): a densityless PNG's 72 px (72 dpi, as pdfTeX sizes it), a 300 dpi
5459  /// PNG's 300 px, an SVG's `1in`, and a PNG sized `width=72.27pt`; a `<?latexml DPI="100"?>` makes it 100. Red
5460  /// (D4UNITS0, DPI 100 and a raster's natural size its pixel count): 72, 300, 96, 100.
5461  #[test]
5462  fn one_inch_is_96_px_whatever_the_source() {
5463    use crate::{
5464      document::{PostDocument, PostDocumentOptions},
5465      graphics_cache::CachePolicy,
5466    };
5467    let tmp = TempDir::new("graphics_one_inch");
5468    // A PNG head: IHDR, then a pHYs chunk when `per_metre` is given (CRCs are not read).
5469    let png = |name: &str, w: u32, h: u32, per_metre: Option<u32>| {
5470      let mut v = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
5471      v.extend_from_slice(&13u32.to_be_bytes());
5472      v.extend_from_slice(b"IHDR");
5473      v.extend_from_slice(&w.to_be_bytes());
5474      v.extend_from_slice(&h.to_be_bytes());
5475      v.extend_from_slice(&[8, 2, 0, 0, 0, 0, 0, 0, 0]);
5476      if let Some(m) = per_metre {
5477        v.extend_from_slice(&9u32.to_be_bytes());
5478        v.extend_from_slice(b"pHYs");
5479        v.extend_from_slice(&m.to_be_bytes());
5480        v.extend_from_slice(&m.to_be_bytes());
5481        v.extend_from_slice(&[1, 0, 0, 0, 0]);
5482      }
5483      v.extend_from_slice(&[0u8; 16]);
5484      let path = tmp.join(name);
5485      std::fs::write(&path, v).unwrap();
5486      path.display().to_string()
5487    };
5488    let p72 = png("p72.png", 72, 36, None);
5489    let p300 = png("p300.png", 300, 150, Some(11811));
5490    let wide = png("wide.png", 200, 100, None);
5491    let svg = tmp.join("inch.svg");
5492    std::fs::write(
5493      &svg,
5494      r#"<svg xmlns="http://www.w3.org/2000/svg" width="1in" height="0.5in"><rect/></svg>"#,
5495    )
5496    .unwrap();
5497    let dest = tmp.join("out").join("out.html");
5498    std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
5499    let sizes = |pi: &str| {
5500      let xml = format!(
5501        r#"<?xml version="1.0"?>{pi}
5502<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="d">
5503  <graphics graphic="p72" candidates="{p72}" xml:id="g1"/>
5504  <graphics graphic="p300" candidates="{p300}" xml:id="g2"/>
5505  <graphics graphic="inch" candidates="{}" xml:id="g3"/>
5506  <graphics graphic="wide" candidates="{wide}" options="width=72.27pt,keepaspectratio=true" xml:id="g4"/>
5507</document>"#,
5508        svg.display()
5509      );
5510      let doc_opts = PostDocumentOptions {
5511        destination: Some(dest.display().to_string()),
5512        source_directory: Some(tmp.path().display().to_string()),
5513        ..Default::default()
5514      };
5515      let doc = PostDocument::new_from_string(&xml, doc_opts).unwrap();
5516      let mut graphics = Graphics::new(None, true).with_cache_policy(CachePolicy::Bypass);
5517      let nodes = graphics.to_process(&doc);
5518      let doc = graphics.process(doc, nodes).unwrap().remove(0);
5519      doc
5520        .findnodes("//ltx:graphics")
5521        .iter()
5522        .map(|n| {
5523          format!(
5524            "{}x{}",
5525            n.get_attribute("imagewidth").unwrap_or_default(),
5526            n.get_attribute("imageheight").unwrap_or_default()
5527          )
5528        })
5529        .collect::<Vec<_>>()
5530    };
5531    assert_eq!(sizes(""), ["96x48", "96x48", "96x48", "96x48"]);
5532    assert_eq!(sizes(r#"<?latexml DPI="100"?>"#), [
5533      "100x50", "100x50", "100x50", "100x50"
5534    ]);
5535  }
5536
5537  /// A resolution pdfTeX ignores as too small for the pixel count (pdftex.web:34495-34505: one inch, 226 px, or more
5538  /// per stated dot on either axis) is read at 72 dpi, as pdflatex sizes the box: a 300x150 PNG stating 1 dpi is
5539  /// 400x200 px, as is one stating 0 x 300 dpi, where a 2 dpi one keeps its 2 dpi (300/226 < 2). Red (31b1d854284):
5540  /// ["28800x14400", "400x200", "14400x7200"].
5541  #[test]
5542  fn a_too_small_resolution_is_read_at_72_dpi() {
5543    use crate::{
5544      document::{PostDocument, PostDocumentOptions},
5545      graphics_cache::CachePolicy,
5546    };
5547    let tmp = TempDir::new("graphics_too_small_resolution");
5548    // A 300x150 PNG head: IHDR, then a pHYs chunk (CRCs are not read).
5549    let png = |name: &str, x: u32, y: u32| {
5550      let mut v = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
5551      v.extend_from_slice(&13u32.to_be_bytes());
5552      v.extend_from_slice(b"IHDR");
5553      v.extend_from_slice(&300u32.to_be_bytes());
5554      v.extend_from_slice(&150u32.to_be_bytes());
5555      v.extend_from_slice(&[8, 2, 0, 0, 0, 0, 0, 0, 0]);
5556      v.extend_from_slice(&9u32.to_be_bytes());
5557      v.extend_from_slice(b"pHYs");
5558      v.extend_from_slice(&x.to_be_bytes());
5559      v.extend_from_slice(&y.to_be_bytes());
5560      v.extend_from_slice(&[1, 0, 0, 0, 0]);
5561      v.extend_from_slice(&[0u8; 16]);
5562      let path = tmp.join(name);
5563      std::fs::write(&path, v).unwrap();
5564      path.display().to_string()
5565    };
5566    let (one, zero, two) = (
5567      png("one.png", 39, 39),
5568      png("zero.png", 0, 11811),
5569      png("two.png", 79, 79),
5570    );
5571    let dest = tmp.join("out").join("out.html");
5572    std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
5573    let xml = format!(
5574      r#"<?xml version="1.0"?>
5575<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="d">
5576  <graphics graphic="one" candidates="{one}" xml:id="g1"/>
5577  <graphics graphic="zero" candidates="{zero}" xml:id="g2"/>
5578  <graphics graphic="two" candidates="{two}" xml:id="g3"/>
5579</document>"#
5580    );
5581    let doc_opts = PostDocumentOptions {
5582      destination: Some(dest.display().to_string()),
5583      source_directory: Some(tmp.path().display().to_string()),
5584      ..Default::default()
5585    };
5586    let doc = PostDocument::new_from_string(&xml, doc_opts).unwrap();
5587    let mut graphics = Graphics::new(None, true).with_cache_policy(CachePolicy::Bypass);
5588    let nodes = graphics.to_process(&doc);
5589    let doc = graphics.process(doc, nodes).unwrap().remove(0);
5590    let sizes: Vec<String> = doc
5591      .findnodes("//ltx:graphics")
5592      .iter()
5593      .map(|n| {
5594        format!(
5595          "{}x{}",
5596          n.get_attribute("imagewidth").unwrap_or_default(),
5597          n.get_attribute("imageheight").unwrap_or_default()
5598        )
5599      })
5600      .collect();
5601    assert_eq!(sizes, ["400x200", "400x200", "14400x7200"]);
5602  }
5603
5604  /// A source is drawn or a raster by its content, not its name (D4UNITS review B1): a PDF or an EPS saved as `.pstex`
5605  /// (cond-mat0603250's xfig `loop.pstex`, 446x202 bp) is rendered at the density and its pixels read at it, so its hint
5606  /// is its box at 96 px/in (a 200x100 bp PDF at `scale=0.5` is 133 px, as pdflatex's 100.375pt box); a big one has its
5607  /// density capped as a `.pdf` has (`raster_density_for_source`: 2000 bp is 73 dpi); a 300 dpi PNG under an unknown
5608  /// name keeps its own density. The stub `convert` copies `<source>.render`, the pixels a real one writes at 120 dpi.
5609  /// Red (b8358aa0b28): ["222x112", "991x449", "2704x1352", "192x96"] (the big one at `-density 120`).
5610  #[test]
5611  #[cfg(unix)]
5612  fn a_drawn_source_is_read_at_its_render_density_whatever_its_name() {
5613    use std::os::unix::fs::PermissionsExt;
5614
5615    use crate::{
5616      document::{PostDocument, PostDocumentOptions},
5617      graphics_cache::CachePolicy,
5618    };
5619    let tmp = TempDir::new("graphics_drawn_by_content");
5620    // A PNG head: IHDR, then a pHYs chunk when `per_metre` is given (CRCs are not read).
5621    let png = |w: u32, h: u32, per_metre: Option<u32>| {
5622      let mut v = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
5623      v.extend_from_slice(&13u32.to_be_bytes());
5624      v.extend_from_slice(b"IHDR");
5625      v.extend_from_slice(&w.to_be_bytes());
5626      v.extend_from_slice(&h.to_be_bytes());
5627      v.extend_from_slice(&[8, 2, 0, 0, 0, 0, 0, 0, 0]);
5628      if let Some(m) = per_metre {
5629        v.extend_from_slice(&9u32.to_be_bytes());
5630        v.extend_from_slice(b"pHYs");
5631        v.extend_from_slice(&m.to_be_bytes());
5632        v.extend_from_slice(&m.to_be_bytes());
5633        v.extend_from_slice(&[1, 0, 0, 0, 0]);
5634      }
5635      v.extend_from_slice(&[0u8; 16]);
5636      v
5637    };
5638    let write = |name: &str, bytes: &[u8]| {
5639      let path = tmp.join(name);
5640      std::fs::write(&path, bytes).unwrap();
5641      path.display().to_string()
5642    };
5643    let figx = write("figx.pstex", b"%PDF-1.4\n<< /MediaBox [0 0 200 100] >>\n");
5644    write("figx.pstex.render", &png(333, 167, None));
5645    let eps = b"%!PS-Adobe-2.0 EPSF-2.0\n%%BoundingBox: 0 0 446 202\n%%EndComments\n";
5646    let lp = write("loop.pstex", eps);
5647    write("loop.pstex.render", &png(743, 337, None));
5648    let big = write("big.pstex", b"%PDF-1.4\n<< /MediaBox [0 0 2000 1000] >>\n");
5649    write("big.pstex.render", &png(2028, 1014, None));
5650    let scan = write("scan.dat", &png(600, 300, Some(11811)));
5651    write("scan.dat.render", &png(600, 300, Some(11811)));
5652    let fake_convert = tmp.join("convert");
5653    std::fs::write(
5654      &fake_convert,
5655      "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$(dirname \"$0\")/convert.log\"\n\
5656       for a in \"$@\"; do s=\"$d\"; d=\"$a\"; done\ncp \"$s.render\" \"$d\"\n",
5657    )
5658    .unwrap();
5659    let mut perms = std::fs::metadata(&fake_convert).unwrap().permissions();
5660    perms.set_mode(0o755);
5661    std::fs::set_permissions(&fake_convert, perms).unwrap();
5662    let mut env = EnvGuard::acquire();
5663    let old_path = std::env::var("PATH").unwrap_or_default();
5664    env.set("PATH", &format!("{}:{}", tmp.path().display(), old_path));
5665    let dest = tmp.join("out").join("out.html");
5666    std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
5667    let xml = format!(
5668      r#"<?xml version="1.0"?>
5669<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="d">
5670  <graphics graphic="figx.pstex" candidates="{figx}" options="scale=0.5" xml:id="g1"/>
5671  <graphics graphic="loop.pstex" candidates="{lp}" xml:id="g2"/>
5672  <graphics graphic="big.pstex" candidates="{big}" xml:id="g3"/>
5673  <graphics graphic="scan.dat" candidates="{scan}" xml:id="g4"/>
5674</document>"#
5675    );
5676    let doc_opts = PostDocumentOptions {
5677      destination: Some(dest.display().to_string()),
5678      source_directory: Some(tmp.path().display().to_string()),
5679      ..Default::default()
5680    };
5681    let doc = PostDocument::new_from_string(&xml, doc_opts).unwrap();
5682    let mut graphics = Graphics::new(None, true).with_cache_policy(CachePolicy::Bypass);
5683    let nodes = graphics.to_process(&doc);
5684    let doc = graphics.process(doc, nodes).unwrap().remove(0);
5685    let sizes: Vec<String> = doc
5686      .findnodes("//ltx:graphics")
5687      .iter()
5688      .map(|n| {
5689        format!(
5690          "{}x{}",
5691          n.get_attribute("imagewidth").unwrap_or_default(),
5692          n.get_attribute("imageheight").unwrap_or_default()
5693        )
5694      })
5695      .collect();
5696    // 333 px at 120 dpi shown at 96, halved: ceil(133.2); 743x337 at 120 is 594x270 (the box: 595x269); 2028 px at
5697    // 73 dpi is 2667x1333 (the box: 2000 bp, 2667x1333); 600 px at 300 dpi is 192.
5698    assert_eq!(sizes, ["134x67", "594x270", "2667x1333", "192x96"]);
5699    let log = std::fs::read_to_string(tmp.join("convert.log")).unwrap_or_default();
5700    let density_of = |name: &str| {
5701      let line = log.lines().find(|l| l.contains(name)).unwrap_or_default();
5702      line
5703        .split("-density ")
5704        .nth(1)
5705        .and_then(|r| r.split(' ').next())
5706        .map(str::to_string)
5707    };
5708    assert_eq!(
5709      ["figx", "loop", "big"].map(density_of),
5710      [
5711        Some("120".to_string()),
5712        Some("120".to_string()),
5713        Some("73".to_string())
5714      ],
5715      "{log}"
5716    );
5717  }
5718
5719  /// brucemiller/LaTeXML#2392: a graphics `<img>` carries width/height that
5720  /// give the *requested* aspect ratio (from `\includegraphics`). The flex
5721  /// subfigure CSS caps `max-width`, which changes the width but not the
5722  /// height, so a square picture renders as a vertical ellipsoid. `set_graphic_src`
5723  /// now also emits an explicit `aspect-ratio:W/H` in `cssstyle`, so a width-only
5724  /// CSS cap (paired with `height:auto`) preserves the requested ratio — and the
5725  /// *requested* ratio, not the file's, per Bruce Miller's requirement in the
5726  /// thread. Beyond Perl 0.8.8, which emits no aspect-ratio (OXIDIZED_DESIGN #139).
5727  #[test]
5728  fn set_graphic_src_emits_requested_aspect_ratio_2392() {
5729    let doc = libxml::tree::Document::new().unwrap();
5730    for (w, h, bucket) in [
5731      (200u32, 100u32, "ltx_img_landscape"),
5732      (476, 476, "ltx_img_square"),
5733    ] {
5734      let mut node = Node::new("graphics", None, &doc).unwrap();
5735      Graphics::set_graphic_src(&mut node, "fig.png", Some(w), Some(h));
5736      let style = node.get_attribute("cssstyle").unwrap_or_default();
5737      assert!(
5738        style.contains(&format!("aspect-ratio:{w}/{h}")),
5739        "expected the requested aspect-ratio {w}/{h} in cssstyle, got {style:?}"
5740      );
5741      assert!(
5742        node
5743          .get_attribute("class")
5744          .unwrap_or_default()
5745          .contains(bucket)
5746      );
5747    }
5748  }
5749
5750  /// The #2392 fix is two coupled halves: the emitted `aspect-ratio` (guarded
5751  /// above) and `height:auto` on flex/minipage images, so that ratio governs
5752  /// when the `flex_size` `max-width` caps the width. Guard the CSS half — the
5753  /// embedded `LaTeXML.css` — so removing it can't silently re-introduce the
5754  /// distortion while the emission test stays green.
5755  #[test]
5756  fn flex_graphics_css_frees_height_for_aspect_ratio_2392() {
5757    let css = include_str!("../resources/CSS/LaTeXML.css");
5758    assert!(
5759      css.contains(".ltx_flex_figure .ltx_graphics { height: auto; }"),
5760      "the flex-graphics height:auto companion to #2392's aspect-ratio is missing from LaTeXML.css"
5761    );
5762  }
5763
5764  /// Which reader a source reaches, and what it can measure. EPS answers
5765  /// `None` here: the post raster reader is the `imagesize` crate, which has no
5766  /// PostScript support, so an EPS is never sized on the trivial-copy path — it
5767  /// always goes through `Plan::Convert` and is measured from the produced PNG.
5768  #[test]
5769  fn read_source_dimensions_dispatch_matrix() {
5770    let tmp = TempDir::new("post_dispatch");
5771    let svg = tmp.join("a.svg");
5772    std::fs::write(&svg, r#"<svg viewBox="0 0 200 100"><rect/></svg>"#).unwrap();
5773    let svg_upper = tmp.join("B.SVG");
5774    std::fs::write(&svg_upper, r#"<svg viewBox="0 0 60 40"><rect/></svg>"#).unwrap();
5775    let png = tmp.join("c.png");
5776    std::fs::write(&png, ONE_PIXEL_PNG).unwrap();
5777    let eps = tmp.join("d.eps");
5778    std::fs::write(
5779      &eps,
5780      "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 200 100\n",
5781    )
5782    .unwrap();
5783
5784    let dims = |p: &Path| Graphics::read_source_dimensions(p.to_str().unwrap());
5785    assert_eq!(dims(&svg), Some((200, 100)), "svg via viewBox");
5786    assert_eq!(
5787      dims(&svg_upper),
5788      Some((60, 40)),
5789      "extension match is case-insensitive"
5790    );
5791    assert_eq!(dims(&png), Some((1, 1)), "png via imagesize");
5792    assert_eq!(dims(&eps), None, "EPS is unmeasurable here, by design");
5793  }
5794
5795  /// The three `%%BoundingBox` shapes the PS reader accepts. Values are bp; the
5796  /// two-value form returns the extent, the full form the raw corners.
5797  #[test]
5798  fn postscript_bounding_box_forms() {
5799    let tmp = TempDir::new("post_psbbox");
5800    let offset = tmp.join("o.eps");
5801    std::fs::write(
5802      &offset,
5803      "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 210 120\n",
5804    )
5805    .unwrap();
5806    assert_eq!(
5807      read_postscript_bounding_box(offset.to_str().unwrap()),
5808      Some((200.0, 100.0)),
5809      "extent, not corners"
5810    );
5811    assert_eq!(
5812      read_postscript_bounding_box_full(offset.to_str().unwrap()),
5813      Some((10.0, 20.0, 200.0, 100.0)),
5814      "full form is (llx, lly, width, height) — NOT (llx,lly,urx,ury)"
5815    );
5816    // The deferred `(atend)` form: the real numbers appear later in the file.
5817    let atend = tmp.join("a.eps");
5818    std::fs::write(
5819      &atend,
5820      "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: (atend)\nstuff\n%%BoundingBox: 0 0 300 150\n",
5821    )
5822    .unwrap();
5823    assert_eq!(
5824      read_postscript_bounding_box(atend.to_str().unwrap()),
5825      Some((300.0, 150.0))
5826    );
5827  }
5828
5829  /// Rasterization density is a *quality* knob, independent of the sizing DPI:
5830  /// `DEFAULT_RASTER_DENSITY` (120) unless the source's own box is large enough
5831  /// that rendering at 120 would exceed `MAX_RASTER_DIMENSION_PX`.
5832  #[test]
5833  fn raster_density_is_capped_by_source_box_size() {
5834    let tmp = TempDir::new("post_density");
5835    let small = tmp.join("s.eps");
5836    std::fs::write(
5837      &small,
5838      "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 200 100\n",
5839    )
5840    .unwrap();
5841    assert_eq!(
5842      Graphics::raster_density_for_source(small.to_str().unwrap()),
5843      120
5844    );
5845
5846    let pdf = tmp.join("s.pdf");
5847    std::fs::write(&pdf, "%PDF-1.4\n<< /MediaBox [0 0 200 100] >>\n").unwrap();
5848    assert_eq!(
5849      Graphics::raster_density_for_source(pdf.to_str().unwrap()),
5850      120
5851    );
5852
5853    // No measurable box (a raster source) — the default stands.
5854    let png = tmp.join("s.png");
5855    std::fs::write(&png, ONE_PIXEL_PNG).unwrap();
5856    assert_eq!(
5857      Graphics::raster_density_for_source(png.to_str().unwrap()),
5858      120
5859    );
5860
5861    // A 2000bp-wide source at 120 dpi would be 3333 px, over the 2048 cap, so
5862    // the density drops to floor(2048 * 72 / 2000) = 73.
5863    let big = tmp.join("b.eps");
5864    std::fs::write(
5865      &big,
5866      "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 2000 1000\n",
5867    )
5868    .unwrap();
5869    assert_eq!(
5870      Graphics::raster_density_for_source(big.to_str().unwrap()),
5871      73
5872    );
5873  }
5874
5875  /// Smallest valid PNG: 1×1, 8-bit RGB. `imagesize` reads its IHDR, so the
5876  /// sizing half of `Plan::Copy` succeeds and no `expected:image` warn fires.
5877  const ONE_PIXEL_PNG: &[u8] = &[
5878    0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, // signature
5879    0x00, 0x00, 0x00, 0x0d, b'I', b'H', b'D', b'R', // IHDR length + type
5880    0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, // 1 × 1
5881    0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53, 0xde, // bit depth/colour + CRC
5882    0x00, 0x00, 0x00, 0x0c, b'I', b'D', b'A', b'T', // IDAT length + type
5883    0x08, 0xd7, 0x63, 0xf8, 0xcf, 0xc0, 0x00, 0x00, 0x03, 0x01, 0x01, 0x00, 0x18, 0xdd, 0x8d,
5884    0xb0, // deflate stream + CRC
5885    0x00, 0x00, 0x00, 0x00, b'I', b'E', b'N', b'D', 0xae, 0x42, 0x60, 0x82,
5886  ];
5887
5888  /// A post-processing diagnostic raised on a WORKER THREAD must reach the MAIN
5889  /// thread's bound log AND register in the main `REPORT` status counters — both
5890  /// `LOG_BUFFER` and `REPORT` are per-thread, so a worker's `Error!`
5891  /// would otherwise be lost from cortex.log and from `status_code`. This
5892  /// exercises the exact "thread join + fold" the graphics pool uses: each
5893  /// worker returns its [`CapturedDiagnostics`] from `logger::capture`, and the
5894  /// main thread folds them in via `replay_captured` after join — no shared
5895  /// writeable state, no lock, no env mutation. (Companion: the real pipeline is
5896  /// validated end-to-end by converting a document with an unconvertible image;
5897  /// see docs and the manual `--preload`/`--dest` smoke.)
5898  #[test]
5899  fn worker_diagnostics_fold_into_main_thread_on_join() {
5900    // The `log` macros are inert until a logger + level are installed (the
5901    // CLI/cortex do this at startup). `init` is process-global + idempotent
5902    // across tests; force the level since `init` skips it if already installed.
5903    let _ = latexml_core::util::logger::init(log::LevelFilter::Info);
5904    log::set_max_level(log::LevelFilter::Info);
5905
5906    latexml_core::util::logger::bind_log();
5907    let before = latexml_core::common::error::snapshot_report_counts();
5908
5909    // Two workers, each emitting a post Error! under capture (so the diagnostic
5910    // lands in the worker's own thread-local buffer + REPORT), returning their
5911    // CapturedDiagnostics on join — exactly the graphics pool's pattern.
5912    let captured: Vec<latexml_core::util::logger::CapturedDiagnostics> = std::thread::scope(|s| {
5913      (0..2)
5914        .map(|i| {
5915          s.spawn(move || {
5916            latexml_core::util::logger::capture(|| {
5917              Error!(
5918                "imageprocessing",
5919                "failed_to_convert",
5920                "Graphics: Failed to convert {} to {}",
5921                format!("w{i}.pdf"),
5922                format!("w{i}.png")
5923              );
5924            })
5925            .1
5926          })
5927        })
5928        .collect::<Vec<_>>()
5929        .into_iter()
5930        .map(|h| h.join().unwrap())
5931        .collect()
5932    });
5933
5934    // Fold the per-worker diagnostics into the main thread.
5935    for diags in captured {
5936      latexml_core::util::logger::replay_captured(diags);
5937    }
5938
5939    let after = latexml_core::common::error::snapshot_report_counts();
5940    let log = latexml_core::util::logger::flush_log();
5941
5942    assert!(
5943      log.contains("imageprocessing:failed_to_convert") && log.contains("Failed to convert"),
5944      "worker Error! must reach the main-thread log; got: {log:?}"
5945    );
5946    assert_eq!(
5947      log
5948        .matches("Error:imageprocessing:failed_to_convert")
5949        .count(),
5950      2,
5951      "{log}"
5952    );
5953    assert_eq!(
5954      after.error,
5955      before.error + 2,
5956      "both workers' Error! must increment the main REPORT error count via the fold"
5957    );
5958  }
5959
5960  /// `produced_output` is the guard that turns a `convert`/`gs` exit-0-but-no-file
5961  /// into a reported failure: a usable conversion is a non-empty file, not just a
5962  /// clean exit. Missing OR empty (0-byte) => not output.
5963  #[test]
5964  fn produced_output_requires_a_nonempty_file() {
5965    let tmp = std::env::temp_dir().join(format!("latexml_produced_{}", std::process::id()));
5966    std::fs::create_dir_all(&tmp).unwrap();
5967    let missing = tmp.join("missing.png");
5968    let empty = tmp.join("empty.png");
5969    let real = tmp.join("real.png");
5970    std::fs::write(&empty, b"").unwrap();
5971    std::fs::write(&real, b"\x89PNG").unwrap();
5972    assert!(
5973      !Graphics::produced_output(&missing.to_string_lossy()),
5974      "a missing file is not usable output"
5975    );
5976    assert!(
5977      !Graphics::produced_output(&empty.to_string_lossy()),
5978      "a 0-byte file is not usable output (would render as a broken image)"
5979    );
5980    assert!(
5981      Graphics::produced_output(&real.to_string_lossy()),
5982      "a non-empty file is usable output"
5983    );
5984    std::fs::remove_dir_all(&tmp).ok();
5985  }
5986
5987  /// A converter that fails must leave its stderr in the thread-local diagnostic,
5988  /// so the failed_to_convert Error can name WHY (e.g. gs `/undefinedfilename`).
5989  #[test]
5990  fn run_with_timeout_captures_stderr_into_diag() {
5991    take_converter_diag(); // clear
5992    let (cmd, prog) = spawn_stderr_fail();
5993    let status = Graphics::run_with_timeout(cmd, std::time::Duration::from_secs(5));
5994    assert!(
5995      status.map(|s| !s.success()).unwrap_or(false),
5996      "command should report failure"
5997    );
5998    let diag = take_converter_diag().expect("a diagnostic must be recorded");
5999    assert!(
6000      diag.contains("boom on stderr") && diag.contains(prog),
6001      "diag should name the program + its stderr; got: {diag}"
6002    );
6003  }
6004
6005  /// A converter that can't be spawned (not installed / not on PATH — e.g. `gs`
6006  /// missing in a minimal image) must record a "could not start" diagnostic.
6007  #[test]
6008  fn run_with_timeout_records_spawn_failure() {
6009    take_converter_diag();
6010    let cmd = std::process::Command::new("definitely_not_a_real_binary_xyz_123");
6011    let status = Graphics::run_with_timeout(cmd, std::time::Duration::from_secs(5));
6012    assert!(status.is_none(), "spawn failure returns None");
6013    let diag = take_converter_diag().expect("a spawn diagnostic must be recorded");
6014    assert!(
6015      diag.contains("could not start") && diag.contains("definitely_not_a_real_binary_xyz_123"),
6016      "diag should name the missing tool; got: {diag}"
6017    );
6018  }
6019
6020  /// Every graphics/image tool the cascade shells out to maps to an install
6021  /// hint that names the OS package, so a missing-dependency diagnostic is
6022  /// self-fixing; an unknown program yields no hint.
6023  #[test]
6024  fn missing_tool_hint_names_packages() {
6025    assert!(missing_tool_hint("mutool").unwrap().contains("mupdf-tools"));
6026    assert!(
6027      missing_tool_hint("pdftocairo")
6028        .unwrap()
6029        .contains("poppler-utils")
6030    );
6031    assert!(missing_tool_hint("gs").unwrap().contains("ghostscript"));
6032    assert!(missing_tool_hint("ps2pdf").unwrap().contains("ghostscript"));
6033    assert!(
6034      missing_tool_hint("convert")
6035        .unwrap()
6036        .contains("imagemagick")
6037    );
6038    assert!(missing_tool_hint("dvisvgm").unwrap().contains("dvisvgm"));
6039    assert!(missing_tool_hint("dvipng").unwrap().contains("dvipng"));
6040    assert!(missing_tool_hint("kpsewhich").unwrap().contains("TeX Live"));
6041    assert!(missing_tool_hint("some_unknown_tool").is_none());
6042  }
6043
6044  /// What an SVG draws, in order: each `<image>` as `image WxH <media type>` and each glyph or
6045  /// path as `glyph`/`path`, resolving `<use>` through its `xlink:href` (mutool draws the image
6046  /// inline, pdftocairo through a `<use>` of a `<defs>` entry; both draw glyphs as `<use>`).
6047  fn svg_drawn_shape(svg: &str) -> Vec<String> {
6048    const XLINK: &str = "http://www.w3.org/1999/xlink";
6049    fn index(node: &Node, ids: &mut HashMap<String, Node>) {
6050      if let Some(id) = node.get_property("id") {
6051        ids.insert(id, node.clone());
6052      }
6053      for child in node.get_child_elements() {
6054        index(&child, ids);
6055      }
6056    }
6057    fn image(node: &Node) -> String {
6058      let href = node.get_property_ns("href", XLINK).unwrap_or_default();
6059      let media = href
6060        .strip_prefix("data:")
6061        .and_then(|rest| rest.split(';').next())
6062        .unwrap_or("external");
6063      format!(
6064        "image {}x{} {media}",
6065        node.get_property("width").unwrap_or_default(),
6066        node.get_property("height").unwrap_or_default()
6067      )
6068    }
6069    fn walk(node: &Node, ids: &HashMap<String, Node>, out: &mut Vec<String>) {
6070      for child in node.get_child_elements() {
6071        match child.get_name().as_str() {
6072          "defs" | "clipPath" | "mask" => {},
6073          "image" => out.push(image(&child)),
6074          "path" => out.push("path".to_string()),
6075          "use" => {
6076            let target = child.get_property_ns("href", XLINK).unwrap_or_default();
6077            match ids.get(target.trim_start_matches('#')) {
6078              Some(def) if def.get_name() == "image" => out.push(image(def)),
6079              Some(_) => out.push("glyph".to_string()),
6080              None => out.push(format!("dangling {target}")),
6081            }
6082          },
6083          _ => walk(&child, ids, out),
6084        }
6085      }
6086    }
6087    let doc = libxml::parser::Parser::default()
6088      .parse_string(svg)
6089      .expect("SVG parses");
6090    let root = doc.get_root_element().expect("SVG root");
6091    assert_eq!(root.get_name(), "svg");
6092    let mut ids = HashMap::default();
6093    index(&root, &mut ids);
6094    let mut out = Vec::new();
6095    walk(&root, &ids, &mut out);
6096    out
6097  }
6098
6099  /// Whether `tool` spawns. A missing one is a visible SKIP, or a failure where
6100  /// `LATEXML_SVG_TESTS` is set (CI installs both converters).
6101  fn svg_tool_or_skip(tool: &str, test: &str) -> bool {
6102    // Spawning is the signal, not the exit status: both tools exit non-zero on `--version`.
6103    let found = std::process::Command::new(tool)
6104      .arg("--version")
6105      .output()
6106      .is_ok();
6107    if !found {
6108      assert!(
6109        std::env::var_os("LATEXML_SVG_TESTS").is_none(),
6110        "LATEXML_SVG_TESTS is set but {tool} is not on PATH ({test})"
6111      );
6112      eprintln!("SKIP {test} with {tool}: not on PATH");
6113    }
6114    found
6115  }
6116
6117  /// The decision of OD #1034 on hand-written SVG: an image drawn larger than its pixels on any
6118  /// placement (inline, nested `<g>`, through `<use>` or a soft mask), or drawn in a way it does
6119  /// not read, sends the figure to the PNG path. Scales in user units (bp) per pixel.
6120  #[test]
6121  fn svg_enlarged_raster_reads_every_placement() {
6122    // A 4×4 PNG (`tests/fixtures/tile.png`).
6123    const PNG: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAEAQMAAACTPww9AAAABlBMVEXgQCAtZLS26lm/AAAADklEQVQI12MoYPgAhA8AC3gDMY2nLXUAAAAASUVORK5CYII=";
6124    // A 1×1 PNG.
6125    const PIXEL: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";
6126    let img = |attrs: &str| format!(r#"<image{attrs} width="4" height="4" xlink:href="{PNG}"/>"#);
6127    let enlarged = |scale: Option<f64>| Some(EnlargedRaster { pixels: Some((4, 4)), scale });
6128    let rows: Vec<(String, Option<EnlargedRaster>)> = vec![
6129      ("<path d=\"M0 0h1\"/>".into(), None),
6130      (
6131        format!(r#"<g transform="matrix(7,0,0,7,1,1)">{}</g>"#, img("")),
6132        enlarged(Some(7.0)),
6133      ),
6134      (
6135        format!(r#"<g transform="matrix(.5,0,0,.5,1,1)">{}</g>"#, img("")),
6136        None,
6137      ),
6138      (
6139        format!(
6140          r#"<g transform="matrix(1.005,0,0,1.005,0,0)">{}</g>"#,
6141          img("")
6142        ),
6143        None,
6144      ),
6145      (
6146        format!(r#"<g transform="scale(.5,2)">{}</g>"#, img("")),
6147        enlarged(Some(2.0)),
6148      ),
6149      (
6150        format!(
6151          r#"<g transform="scale(2)"><g transform="translate(3 4) scale(.25)">{}</g></g>"#,
6152          img("")
6153        ),
6154        None,
6155      ),
6156      (
6157        format!(
6158          r#"<g transform="scale(2)"><g transform="scale(.75)">{}</g></g>"#,
6159          img("")
6160        ),
6161        enlarged(Some(1.5)),
6162      ),
6163      (
6164        format!(
6165          r##"<defs>{}</defs><use xlink:href="#a" transform="matrix(.5, 0, 0, .5, 50, 1)"/>"##,
6166          img(r#" id="a""#)
6167        ),
6168        None,
6169      ),
6170      (
6171        format!(
6172          r##"<defs>{}</defs><use xlink:href="#a" transform="scale(.5)"/><use xlink:href="#a" transform="scale(7)"/>"##,
6173          img(r#" id="a""#)
6174        ),
6175        enlarged(Some(7.0)),
6176      ),
6177      (
6178        format!(
6179          r##"<defs><mask id="m"><g transform="scale(.5)">{}</g></mask></defs><g mask="url(#m)"><g transform="scale(.5)">{}</g></g>"##,
6180          img(""),
6181          img("")
6182        ),
6183        None,
6184      ),
6185      (
6186        format!(
6187          r##"<defs><mask id="m"><g transform="scale(7)">{}</g></mask></defs><g mask="url(#m)"><g transform="scale(.5)">{}</g></g>"##,
6188          img(""),
6189          img("")
6190        ),
6191        enlarged(Some(7.0)),
6192      ),
6193      (
6194        format!(
6195          r##"<defs><mask id="m" maskContentUnits="objectBoundingBox">{}</mask></defs><g mask="url(#m)"/>"##,
6196          img("")
6197        ),
6198        enlarged(None),
6199      ),
6200      (
6201        format!(
6202          r##"<defs><pattern id="p">{}</pattern></defs><path fill="url(#p)" d="M0 0h1"/>"##,
6203          img("")
6204        ),
6205        enlarged(None),
6206      ),
6207      (
6208        format!(
6209          r##"<defs><symbol id="s" viewBox="0 0 1 1">{}</symbol></defs><use xlink:href="#s"/>"##,
6210          img("")
6211        ),
6212        enlarged(None),
6213      ),
6214      (
6215        format!(r#"<g transform="skewX(10)">{}</g>"#, img("")),
6216        enlarged(None),
6217      ),
6218      (
6219        r#"<image width="4" height="4" xlink:href="data:image/png;base64,AAAA"/>"#.into(),
6220        Some(EnlargedRaster { pixels: None, scale: None }),
6221      ),
6222      // A 1×1 raster cannot blur (DG 2026-11-14): drawn at 500 bp per pixel, and under a skew, it keeps the SVG.
6223      (
6224        format!(r#"<image width="500" height="500" xlink:href="{PIXEL}"/>"#),
6225        None,
6226      ),
6227      (
6228        format!(
6229          r#"<g transform="skewX(10)"><image width="9" height="9" xlink:href="{PIXEL}"/></g>"#
6230        ),
6231        None,
6232      ),
6233    ];
6234    for (body, expected) in rows {
6235      let svg = format!(
6236        r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 90 30">{body}</svg>"#
6237      );
6238      assert_eq!(svg_enlarged_raster(&svg), expected, "{body}");
6239    }
6240  }
6241
6242  /// A small PDF figure carrying a raster AND vector text takes the vector-SVG path under the
6243  /// auto default (after PR 816), its label five vector glyphs and its 64×64 raster drawn at
6244  /// 48 bp; the same figure with a 4×4 tile drawn at 1 cm takes the PNG path (DG 2026-11-14:
6245  /// a browser would blur what the PDF shows in pixel blocks). Each converter, then the
6246  /// pipeline. Fixtures: `tests/fixtures/{native,mixed}_raster_vector.tex`.
6247  #[test]
6248  fn small_raster_pdf_keeps_vector_labels_unless_enlarged() {
6249    let fixture = |name: &str| format!("{}/tests/fixtures/{name}.pdf", env!("CARGO_MANIFEST_DIR"));
6250    let expected = [
6251      "image 64x64 image/png",
6252      "glyph",
6253      "glyph",
6254      "glyph",
6255      "glyph",
6256      "glyph",
6257    ];
6258    let tmp = TempDir::new("small_raster_pdf");
6259    type Converter = fn(&str, &str, Option<u32>) -> bool;
6260    let converters: [(&str, Converter); 2] = [
6261      ("mutool", Graphics::convert_image_svg_mutool),
6262      ("pdftocairo", Graphics::convert_image_svg_pdftocairo),
6263    ];
6264    let mut any = false;
6265    for (tool, convert) in converters {
6266      if !svg_tool_or_skip(tool, "small_raster_pdf") {
6267        continue;
6268      }
6269      any = true;
6270      let native = tmp.join(&format!("{tool}_native.svg"));
6271      let native = native.to_str().unwrap();
6272      assert!(
6273        convert(&fixture("native_raster_vector"), native, None),
6274        "{tool} converts"
6275      );
6276      let svg = std::fs::read_to_string(native).unwrap();
6277      assert_eq!(svg_drawn_shape(&svg), expected, "{tool}");
6278      assert_eq!(svg_enlarged_raster(&svg), None, "{tool}");
6279      let tile = tmp.join(&format!("{tool}_tile.svg"));
6280      let tile = tile.to_str().unwrap();
6281      assert!(
6282        convert(&fixture("mixed_raster_vector"), tile, None),
6283        "{tool} converts"
6284      );
6285      let decision = svg_enlarged_raster(&std::fs::read_to_string(tile).unwrap());
6286      // 1 cm over 4 pixels: 7.09 bp per pixel in mutool, 6.95 in pdftocairo (2 % smaller).
6287      let scale = decision.as_ref().and_then(|d| d.scale).unwrap_or_default();
6288      assert!(
6289        decision.as_ref().is_some_and(|d| d.pixels == Some((4, 4))) && (6.9..7.1).contains(&scale),
6290        "{tool}: {decision:?}"
6291      );
6292    }
6293    if !any {
6294      return;
6295    }
6296    let pipeline = |name: &str| {
6297      let dir = tmp.join(name);
6298      std::fs::create_dir_all(&dir).unwrap();
6299      let src = dir.join(format!("{name}.pdf"));
6300      std::fs::copy(fixture(name), &src).unwrap();
6301      let xml = format!(
6302        r#"<document xmlns="http://dlmf.nist.gov/LaTeXML"><graphics graphic="{name}.pdf" candidates="{}"/></document>"#,
6303        src.display()
6304      );
6305      let doc_opts = crate::document::PostDocumentOptions {
6306        destination: Some(dir.join("out.html").display().to_string()),
6307        source_directory: Some(dir.display().to_string()),
6308        ..Default::default()
6309      };
6310      let doc = PostDocument::new_from_string(&xml, doc_opts).expect("parse");
6311      let mut graphics =
6312        Graphics::new(None, true).with_cache_policy(crate::graphics_cache::CachePolicy::Bypass);
6313      let nodes = graphics.to_process(&doc);
6314      assert_eq!(nodes.len(), 1);
6315      let out = graphics.process(doc, nodes).expect("graphics process")[0].to_xml_string();
6316      (out, dir)
6317    };
6318    let (out, dir) = pipeline("native_raster_vector");
6319    assert!(
6320      out.contains(r#" imagesrc="native_raster_vector.svg" "#),
6321      "{out}"
6322    );
6323    let svg = std::fs::read_to_string(dir.join("native_raster_vector.svg")).unwrap();
6324    assert_eq!(svg_drawn_shape(&svg), expected);
6325    // The enlarged tile's SVG is dropped whatever the PNG path can do; main's PNG path rasterizes the PDF
6326    // through Ghostscript (not ImageMagick), which a minimal CI image may lack.
6327    let raster = std::process::Command::new(gs_program())
6328      .arg("--version")
6329      .output()
6330      .is_ok_and(|o| o.status.success());
6331    let _ = latexml_core::util::logger::init(log::LevelFilter::Info);
6332    log::set_max_level(log::LevelFilter::Info);
6333    latexml_core::util::logger::bind_log();
6334    let before = latexml_core::common::error::snapshot_report_counts();
6335    let (out, dir) = pipeline("mixed_raster_vector");
6336    let after = latexml_core::common::error::snapshot_report_counts();
6337    assert!(
6338      !out.contains(r#" imagesrc="mixed_raster_vector.svg" "#),
6339      "{out}"
6340    );
6341    assert!(!dir.join("mixed_raster_vector.svg").exists());
6342    if raster {
6343      assert!(
6344        out.contains(r#" imagesrc="mixed_raster_vector.png" "#),
6345        "{out}"
6346      );
6347      assert_eq!(after.error, before.error, "{out}");
6348    } else {
6349      eprintln!(
6350        "SKIP small_raster_pdf's PNG output check: {} not on PATH (the SVG drop is still checked)",
6351        gs_program()
6352      );
6353    }
6354  }
6355
6356  /// A sibling page-render worker writes and removes the same `fig.svg` (`render_workers`): a
6357  /// destination missing or half-written when this job looks at it must never switch the figure to
6358  /// a PNG. The job judges its own staged render and installs it by rename; a thread here plays the
6359  /// sibling, truncating, rewriting and removing the destination throughout.
6360  #[test]
6361  fn a_sibling_clobbering_the_destination_never_switches_to_png() {
6362    use std::sync::atomic::{AtomicBool, Ordering};
6363    if !["mutool", "pdftocairo"]
6364      .iter()
6365      .any(|tool| svg_tool_or_skip(tool, "a_sibling_clobbering_the_destination"))
6366    {
6367      return;
6368    }
6369    let tmp = TempDir::new("sibling_clobber");
6370    let dir = tmp.join("out");
6371    std::fs::create_dir_all(&dir).unwrap();
6372    let src = dir.join("fig.pdf");
6373    std::fs::copy(
6374      format!(
6375        "{}/tests/fixtures/two_page_sizes.pdf",
6376        env!("CARGO_MANIFEST_DIR")
6377      ),
6378      &src,
6379    )
6380    .unwrap();
6381    let shared = dir.join("fig.svg");
6382    let stop = AtomicBool::new(false);
6383    let mut renders: Vec<String> = Vec::new();
6384    std::thread::scope(|s| {
6385      s.spawn(|| {
6386        while !stop.load(Ordering::Relaxed) {
6387          let _ = std::fs::write(&shared, b"<svg xmlns=\"http://www.w3.org/2000/svg\"");
6388          let _ = std::fs::remove_file(&shared);
6389        }
6390      });
6391      for round in 0..20 {
6392        let xml = format!(
6393          r#"<document xmlns="http://dlmf.nist.gov/LaTeXML"><graphics graphic="fig.pdf" candidates="{}"/></document>"#,
6394          src.display()
6395        );
6396        let doc_opts = crate::document::PostDocumentOptions {
6397          destination: Some(dir.join("out.html").display().to_string()),
6398          source_directory: Some(dir.display().to_string()),
6399          ..Default::default()
6400        };
6401        let doc = PostDocument::new_from_string(&xml, doc_opts).expect("parse");
6402        let mut graphics =
6403          Graphics::new(None, true).with_cache_policy(crate::graphics_cache::CachePolicy::Bypass);
6404        let nodes = graphics.to_process(&doc);
6405        let out = graphics.process(doc, nodes).expect("graphics process")[0].to_xml_string();
6406        // A vector render, whatever its name: since issue 995 a destination holding other bytes
6407        // (the sibling's) is never written over, so the figure may be named `x1.svg` instead.
6408        let src = out
6409          .split(r#" imagesrc=""#)
6410          .nth(1)
6411          .and_then(|rest| rest.split('"').next())
6412          .unwrap_or_default()
6413          .to_string();
6414        if !src.ends_with(".svg") {
6415          stop.store(true, Ordering::Relaxed);
6416          panic!("round {round}: the figure left its vector render:\n{out}");
6417        }
6418        renders.push(src);
6419      }
6420      stop.store(true, Ordering::Relaxed);
6421    });
6422    let mut left: Vec<String> = std::fs::read_dir(&dir)
6423      .unwrap()
6424      .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
6425      // The cache file, `LaTeXML-oxide.cache`, closed with its document.
6426      .filter(|name| {
6427        name != "fig.pdf"
6428          && name != "fig.svg"
6429          && name != "LaTeXML-oxide.cache"
6430          && !renders.contains(name)
6431      })
6432      .collect();
6433    left.sort();
6434    assert!(
6435      left.is_empty(),
6436      "no PNG and no staged file is left: {left:?}"
6437    );
6438  }
6439
6440  /// `\includegraphics[page=2]` of a vector PDF renders page 2 (100×300 bp; page 1 is 300×100) and leaves
6441  /// no temp file: mutool's `%d` counts OUTPUT pages from 1, so a temp named for the source page was
6442  /// never found — pdftocairo drew the image and mutool's SVG stayed in the destination (witnesses
6443  /// 2305.12780, 1906.10268, 2406.07459, 2406.14311, 1709.02311). Each converter, then the pipeline.
6444  /// Fixture: `tests/fixtures/two_page_sizes.tex`.
6445  #[test]
6446  fn vector_svg_of_page_two_is_page_two() {
6447    use latexml_core::util::image::{svg_attr_value, svg_root_tag};
6448    let fixture = format!(
6449      "{}/tests/fixtures/two_page_sizes.pdf",
6450      env!("CARGO_MANIFEST_DIR")
6451    );
6452    let view_box = |path: &Path| {
6453      let text = std::fs::read_to_string(path).unwrap();
6454      svg_root_tag(&text)
6455        .and_then(|tag| svg_attr_value(tag, "viewBox"))
6456        .map(|v| v.split_whitespace().collect::<Vec<_>>().join(" "))
6457    };
6458    let listing = |dir: &Path| {
6459      let mut names: Vec<String> = std::fs::read_dir(dir)
6460        .unwrap()
6461        .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
6462        .collect();
6463      names.sort();
6464      names
6465    };
6466    let tmp = TempDir::new("svg_page_two");
6467    type Converter = fn(&str, &str, Option<u32>) -> bool;
6468    let converters: [(&str, Converter); 2] = [
6469      ("mutool", Graphics::convert_image_svg_mutool),
6470      ("pdftocairo", Graphics::convert_image_svg_pdftocairo),
6471    ];
6472    let mut mutool = false;
6473    for (tool, convert) in converters {
6474      if !svg_tool_or_skip(tool, "svg_page_two") {
6475        continue;
6476      }
6477      mutool |= tool == "mutool";
6478      let dir = tmp.join(tool);
6479      std::fs::create_dir_all(&dir).unwrap();
6480      for (page, expected) in [(2, "0 0 100 300"), (1, "0 0 300 100")] {
6481        let dest = dir.join(format!("p{page}.svg"));
6482        assert!(
6483          convert(&fixture, dest.to_str().unwrap(), Some(page)),
6484          "{tool} converts page {page}"
6485        );
6486        assert_eq!(
6487          view_box(&dest).as_deref(),
6488          Some(expected),
6489          "{tool} page {page}"
6490        );
6491      }
6492      assert_eq!(listing(&dir), ["p1.svg", "p2.svg"], "{tool}");
6493    }
6494    // The pipeline: page=1 and page=2 of one source, each its own page's SVG, and nothing else.
6495    if !mutool {
6496      return;
6497    }
6498    let src = tmp.join("two_page_sizes.pdf");
6499    std::fs::copy(&fixture, &src).unwrap();
6500    let dest = tmp.join("out").join("out.html");
6501    std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
6502    let xml = format!(
6503      r#"<document xmlns="http://dlmf.nist.gov/LaTeXML">
6504  <graphics graphic="two_page_sizes.pdf" candidates="{0}" options="page=1" xml:id="g1"/>
6505  <graphics graphic="two_page_sizes.pdf" candidates="{0}" options="page=2" xml:id="g2"/>
6506</document>"#,
6507      src.display()
6508    );
6509    let doc_opts = crate::document::PostDocumentOptions {
6510      destination: Some(dest.display().to_string()),
6511      source_directory: Some(tmp.path().display().to_string()),
6512      ..Default::default()
6513    };
6514    let doc = PostDocument::new_from_string(&xml, doc_opts).expect("parse");
6515    let mut graphics =
6516      Graphics::new(None, true).with_cache_policy(crate::graphics_cache::CachePolicy::Bypass);
6517    let nodes = graphics.to_process(&doc);
6518    assert_eq!(nodes.len(), 2);
6519    // The page is dropped here, and with it its cache, `LaTeXML-oxide.cache`, closed: no side file is left.
6520    let out = graphics.process(doc, nodes).expect("graphics process")[0].to_xml_string();
6521    let element = |id: &str| {
6522      let at = out.find(&format!(r#"xml:id="{id}""#)).unwrap();
6523      let tag = &out[out[..at].rfind('<').unwrap()..at + out[at..].find('>').unwrap()];
6524      let attr = |name: &str| {
6525        let at = tag.find(&format!(" {name}=\""))? + name.len() + 3;
6526        Some(tag[at..at + tag[at..].find('"')?].to_string())
6527      };
6528      [attr("imagesrc"), attr("imagewidth"), attr("imageheight")]
6529    };
6530    let some = |v: [&str; 3]| v.map(|s| Some(s.to_string()));
6531    assert_eq!(element("g1"), some(["x1.svg", "300", "100"]), "{out}");
6532    assert_eq!(element("g2"), some(["x2.svg", "100", "300"]), "{out}");
6533    let out_dir = dest.parent().unwrap();
6534    assert_eq!(
6535      listing(out_dir),
6536      ["LaTeXML-oxide.cache", "x1.svg", "x2.svg"],
6537      "{out}"
6538    );
6539    assert_eq!(
6540      view_box(&out_dir.join("x2.svg")).as_deref(),
6541      Some("0 0 100 300")
6542    );
6543  }
6544}