Skip to main content

latexml_core/util/
image.rs

1//! Image helpers — port of `LaTeXML::Util::Image`.
2//!
3//! Perl counterpart: `lib/LaTeXML/Util/Image.pm`.
4//!
5//! Provides filesystem search for image candidates, minimal header-based
6//! image size detection (PNG / JPEG / EPS) and the graphicx `sizer` that
7//! converts keyval option strings into box dimensions. The Rust port is
8//! intentionally narrower than the Perl original — Image::Magick is not
9//! used at all; LaTeXML::Post::Graphics carries out any heavy-duty image
10//! operations in a post-processing pass.
11
12use std::path::{Path, PathBuf};
13
14use crate::{
15  BoxOps,
16  common::{dimension::Dimension, numeric_ops::NumericOps, store::Stored},
17  definition::{Definition, ExpansionBody},
18  state,
19  whatsit::Whatsit,
20};
21
22/// Perl: `image_candidates($path)` (Util::Image L43-57).
23///
24/// Returns comma-separated list of candidate paths for `path`, searching
25/// GRAPHICSPATHS + SEARCHPATHS + SOURCEDIRECTORY. Paths are returned
26/// relative to SOURCEDIRECTORY when possible, matching the Perl
27/// `pathname_relative($_, $base)` post-filter.
28pub fn image_candidates(path: &str) -> String { image_candidates_with(path, true) }
29
30/// [`image_candidates`]; `fallbacks` says whether a name the search directories do not hold is asked of kpsewhich and,
31/// with a graphics extension, retried under its base name (off for that retry itself).
32fn image_candidates_with(path: &str, fallbacks: bool) -> String {
33  // `\IfFileExists` looks a name up unquoted: `\set@curr@file`'s `\unquote@name` drops every `"` (latex.ltx:9654-9666),
34  // so graphics.sty's `\Gin@getbase` finds `{"Figure_1".jpg}` as `Figure_1.jpg` (1907.03916, 2005.11727), as it finds a
35  // name quoted whole.
36  let unquoted = path.replace('"', "");
37  // `.//x` is TeX's `./x` (`\includegraphics{\wdir/x.pdf}` with `\wdir` = `./`, 2605.12577; KNOWN_PERL_ERRORS #1343).
38  let path = crate::util::pathname::dot_relative(unquoted.trim());
39  if path.is_empty() {
40    return String::new();
41  }
42  let mut search_dirs: Vec<String> = state::get_graphics_paths();
43  search_dirs.extend(state::get_search_paths());
44  let source_dir = state::lookup_string("SOURCEDIRECTORY");
45  if !source_dir.is_empty() {
46    search_dirs.push(source_dir.clone());
47  }
48  // Then each `\input@path` entry (a directory relative to the source): graphics.sty's `\Gin@getbase` tests every
49  // name with `\IfFileExists` (graphics.sty:211-231), whose `\@iffileonpath` looks it up under each `\input@path`
50  // entry (latex.ltx:9698), so pdflatex finds a `\includegraphics{502f01a.eps}` in `graphics/` under
51  // `\def\input@path{{style/}{graphics/}{}}` (1112.0840's `arxiv-general.cfg`, 8 figures). After the directories above,
52  // so a name they hold keeps its first candidate.
53  for entry in crate::binding::content::input_path_entries() {
54    let entry = entry.trim().trim_matches('"');
55    if entry.is_empty() {
56      continue;
57    }
58    let written = entry;
59    let dir = if Path::new(entry).is_absolute() || source_dir.is_empty() {
60      entry.to_string()
61    } else {
62      PathBuf::from(&source_dir)
63        .join(entry)
64        .to_string_lossy()
65        .to_string()
66    };
67    if !search_dirs.contains(&dir) && crate::util::pathname::search_dir_allowed(written, &dir) {
68      search_dirs.push(dir);
69    }
70  }
71  let confined = crate::util::pathname::is_confined();
72  if search_dirs.is_empty() && !confined {
73    search_dirs.push(".".to_string());
74  }
75
76  // Perl `pathname_findall($path, types => ['*'], paths => …)` (Pathname.pm:325-371): in each search directory, the
77  // files named as the image (its whole name, a dotted `b.v0.5_x` too) or that name with one more extension
78  // (`^name\.\w+$`), case-insensitive matches only when no exact one exists. Beyond Perl (OXIDIZED_DESIGN_DIVERGENCES
79  // #477), as pdflatex takes them: a name whose extension has a graphics rule (`has_graphics_rule`) that names a file in
80  // some directory is that file alone (`\Gin@getbase` tries the name over every `\input@path` entry before appending
81  // any extension, graphics.sty:211-231 — Perl lists a `c.eps.png` beside `c.eps` too, and post would render it), or
82  // failing that the file of that name in another case (kpathsea's `fig.pdf` for `fig.PDF`); any other name —
83  // extensionless, or with an extension no rule reads, `b.v0.5_x`, `c.EPS` — lists its `name.ext` files before a bare
84  // file of that name, which pdflatex takes only when no extended one exists (graphics.sty:205-231); only files are
85  // candidates (Perl's list defers `-f`, Pathname.pm:391, and names a directory too).
86  let has_extension = Path::new(path).extension().is_some();
87  let source_path = if source_dir.is_empty() {
88    None
89  } else {
90    Some(PathBuf::from(&source_dir))
91  };
92  // (a path naming no file, `..` or `/`, matches nothing here and goes on to kpsewhich below)
93  let name = Path::new(path)
94    .file_name()
95    .map(|s| s.to_string_lossy().to_string())
96    .unwrap_or_default();
97  let name_lower = name.to_lowercase();
98  // TeX tries each `\input@path` entry glued to the name as written (latex.ltx `\InputIfFileExists` over
99  // `\input@path`), so `plots/` and `/example_1/a.pdf` are `plots//example_1/a.pdf`; a leading `/` that names no
100  // file is read under each directory as TeX reads it (2409.13454's `\folder` = `/example_1/`), where joining an
101  // absolute path would drop the directory (Perl searches only the name's own directory, Pathname.pm:328-329; #477).
102  // The source directory and `SEARCHPATHS` count as such directories too, beyond pdflatex (which fails on the name
103  // without a `\graphicspath`), as post's own fallback already glued it (latexml_post graphics.rs).
104  // Confined, an absolute name outside the roots is never opened: it is only read under each directory, and refused
105  // below when that finds nothing and it names a file (`\figpath/x.pdf` with an empty `\figpath`, 2605.05563,
106  // 2605.19326, 2605.23388, 2605.30797).
107  let outside_absolute = confined
108    && crate::util::pathname::is_absolute(path)
109    && !crate::util::pathname::read_allowed(path);
110  let relative_name = match path.strip_prefix('/') {
111    Some(rest) if !(crate::util::pathname::read_allowed(path) && Path::new(path).exists()) => rest,
112    _ => path,
113  };
114
115  // Confined, a directory outside the roots is never listed; a name all of whose directories are is refused when it
116  // names a file there, as is one whose only match is a link leading out of its folder.
117  let mut listed_any = false;
118  let mut unlisted: Vec<PathBuf> = Vec::new();
119  let link_refused = std::cell::Cell::new(false);
120  let found = search_dirs
121    .iter()
122    .filter(|_| !name.is_empty())
123    .flat_map(|dir| {
124      // Strip surrounding double-quotes from the search directory, symmetric to
125      // the `path.trim_matches('"')` above. A quoted `\graphicspath{{"./dir"}}`
126      // (or `\svgpath` / `--graphicspaths`) otherwise joins to a `"…"` path that
127      // never resolves. See OXIDIZED_DESIGN #55.
128      let dir = dir.trim().trim_matches('"');
129      let base = PathBuf::from(dir).join(relative_name);
130      let parent = base
131        .parent()
132        .unwrap_or_else(|| Path::new("."))
133        .to_path_buf();
134      let allowed = !confined || crate::util::pathname::read_allowed(&parent.to_string_lossy());
135      listed_any |= allowed;
136      if !allowed {
137        unlisted.push(base.clone());
138      }
139      allowed
140        .then(|| std::fs::read_dir(parent).into_iter().flatten().flatten())
141        .into_iter()
142        .flatten()
143    })
144    .filter_map(|entry| {
145      // the name first, so that only an entry named as the image costs a `stat`
146      let fname = entry.file_name().to_string_lossy().to_string();
147      image_file_name_match(&fname, &name, &name_lower)?;
148      let full = entry.path();
149      // Confined, judged before any test: a refused entry is tested only for whether it names a file (a link out to
150      // one is refused, a dangling one is missing, as `refused_exists` decides).
151      if confined && !crate::util::pathname::read_allowed(&full.to_string_lossy()) {
152        link_refused.set(link_refused.get() || full.is_file());
153        return None;
154      }
155      if !full.is_file() {
156        return None;
157      }
158      // Perl relativizes every hit to SOURCEDIRECTORY via pathname_relative
159      // (→ File::Spec->abs2rel), which emits a `../…` path for a graphic in a
160      // SIBLING directory (issue #698: `\subimport*{../gfx_asset/}` reaching a
161      // sideways tree). See `pathname::relative`, which now matches Perl (it
162      // used to leak the absolute path on a non-descendant hit).
163      let rel = match &source_path {
164        Some(sp) => crate::util::pathname::relative(&full.to_string_lossy(), &sp.to_string_lossy()),
165        None => full.to_string_lossy().to_string(),
166      };
167      Some((fname, rel))
168    });
169  let ImageCandidateLists {
170    exact_names,
171    extended_names,
172    mut nocase_exact_names,
173    nocase_candidates,
174  } = image_candidate_lists(found, &name);
175  // (an extensionless name is the file a search would take with a graphics extension)
176  let names_a_file = |base: &Path| {
177    crate::util::pathname::refused_exists(&base.to_string_lossy())
178      || !has_extension
179        && GRAPHICS_EXTENSIONS.iter().any(|ext| {
180          crate::util::pathname::refused_exists(&format!("{}.{ext}", base.to_string_lossy()))
181        })
182  };
183  let graphics_name = has_graphics_rule(&name);
184  let mut candidates: Vec<String> = if graphics_name && !exact_names.is_empty() {
185    exact_names
186  } else if graphics_name && !nocase_exact_names.is_empty() {
187    std::mem::take(&mut nocase_exact_names)
188  } else {
189    extended_names.into_iter().chain(exact_names).collect()
190  };
191  if candidates.is_empty() {
192    candidates = if graphics_name {
193      nocase_exact_names
194        .into_iter()
195        .chain(nocase_candidates)
196        .collect()
197    } else {
198      nocase_candidates
199        .into_iter()
200        .chain(nocase_exact_names)
201        .collect()
202    };
203  }
204  // (an unlisted directory's file is refused when the listed ones find nothing, as `pathname::find` refuses an outside
205  // candidate: `src/d -> ../far/deep` beside a real `--path` `opt/d` for `d/../img.png`)
206  let unlisted_out = confined
207    && candidates.is_empty()
208    && !name.is_empty()
209    && unlisted.iter().any(|base| names_a_file(base));
210  let link_out = link_refused.get() && candidates.is_empty();
211  let absolute_out = outside_absolute && candidates.is_empty() && names_a_file(Path::new(path));
212  if unlisted_out || link_out || (absolute_out && fallbacks) {
213    crate::util::pathname::refuse(path);
214  }
215  let refused = unlisted_out || link_out || absolute_out;
216
217  // Perl image_candidates (Util/Image.pm L49-53): when the search directories hold nothing, kpsewhich finds the
218  // TeX tree's file (mwe's `example-image-a`; only files that exist, so a missing image has no candidate), Perl
219  // asking for `.png` then `.pdf`. Beyond Perl, the extensions are tried in `\Gin@extensions` order and the first
220  // found wins (graphics.sty:206-209 `\@for\Gin@temp:=\Gin@extensions` over `\Gin@getbase`'s `\IfFileExists`, whose
221  // `\openin` searches TeX's input path), so `example-image` is its `.pdf` (321.2pt, as pdflatex sets it), not the
222  // `.png` beside it (401.5pt). A name with a graphics extension is asked as-is below (#230).
223  if fallbacks && candidates.is_empty() && !has_graphics_extension(&name) {
224    let mut extensions = graphics_extensions_in_order();
225    if extensions.is_empty() {
226      extensions = PDFTEX_GIN_EXTENSIONS.map(str::to_string).to_vec();
227    }
228    let names: Vec<String> = extensions
229      .iter()
230      .map(|ext| format!("{path}{ext}"))
231      .collect();
232    let names: Vec<&str> = names.iter().map(String::as_str).collect();
233    if let Some(found) = crate::util::pathname::kpsewhich_tex_input(&names) {
234      // Perl relativizes every candidate to SOURCEDIRECTORY (pathname_relative): a `../…` path for a hit in the
235      // texmf tree, not an absolute machine path (issue #698).
236      let rel = match &source_path {
237        Some(sp) => crate::util::pathname::relative(&found, &sp.to_string_lossy()),
238        None => found,
239      };
240      candidates.push(rel);
241    }
242  }
243
244  // Beyond Perl (OXIDIZED_DESIGN_DIVERGENCES #230): a name WITH an extension
245  // that the search paths do not hold is asked of kpsewhich as-is. Perl
246  // consults kpsewhich only with `.png`/`.pdf` appended (Util/Image.pm:49-53;
247  // the branch above, with `\Gin@extensions`), so a package-shipped asset
248  // referenced by its full name — `\includegraphics[page=N]
249  // {openmoji-color-all.pdf}` and the other icon galleries, 97.8 % of the
250  // corpus's lost figures (~27,700) — never resolved although kpsewhich finds
251  // it in the texmf tree. Guard: `cluster_package_guards::graphics_kpsewhich::
252  // extensioned_texmf_graphic_is_a_candidate`.
253  if fallbacks
254    && candidates.is_empty()
255    && has_extension
256    && let Some(found) = crate::util::pathname::kpsewhich(&[path])
257  {
258    let rel = match &source_path {
259      Some(sp) => crate::util::pathname::relative(&found, &sp.to_string_lossy()),
260      None => found,
261    };
262    candidates.push(rel);
263  }
264
265  // Beyond Perl (OXIDIZED_DESIGN_DIVERGENCES #882): a name with a graphics extension that names no file anywhere
266  // (`\includegraphics{recomb.eps}` where the author ran epstopdf and shipped only `recomb.pdf`) is retried under its
267  // base name, its files of a graphics type the candidates, as post's `find_graphic_file` (latexml_post graphics.rs)
268  // already finds the image: so the digestion-time sizer reads the real file and a sub-figure panel has its width
269  // (1408.2843 Fig 1-2, 1503.04804 Fig 3; KNOWN_PERL_ERRORS #1137, where Perl's Image.pm:43-56 and post both lose it). A
270  // requested file that exists, on the search paths or in the texmf tree, is found above and stays the only one.
271  if fallbacks
272    && !refused
273    && candidates.is_empty()
274    && has_graphics_extension(&name)
275    && path.ends_with(&name)
276    && let Some(stem) = Path::new(&name)
277      .file_stem()
278      .map(|s| s.to_string_lossy().to_string())
279    && !stem.is_empty()
280  {
281    let base = format!("{}{stem}", &path[..path.len() - name.len()]);
282    candidates = image_candidates_with(&base, false)
283      .split(',')
284      .filter(|found| {
285        let found_name = found.rsplit('/').next().unwrap_or(found);
286        has_graphics_extension(found_name)
287          && Path::new(found_name)
288            .file_stem()
289            .is_some_and(|s| s.to_string_lossy().eq_ignore_ascii_case(&stem))
290      })
291      .map(str::to_string)
292      .collect();
293    in_graphics_type_order(&mut candidates);
294  }
295
296  // Deduplicate while preserving order
297  let mut seen = rustc_hash::FxHashSet::default();
298  candidates.retain(|c| seen.insert(c.clone()));
299
300  // Perl image_candidates (Util/Image.pm) returns ($path, @candidates) where
301  // @candidates holds only files actually found (pathname_findall + kpsewhich);
302  // graphicx.sty sets `candidates => join(',', @candidates)`, so a missing file
303  // yields an EMPTY candidates string (the attribute is then omitted) while the
304  // `graphic` attribute still carries the raw path. The earlier Rust port fell
305  // back to the raw path here, emitting `candidates="missing.png"` where Perl
306  // emits no candidates at all. Return empty to match.
307  candidates.join(",")
308}
309
310/// The files one image search found, by how each matches the image's name ([`image_candidate_lists`]).
311#[derive(Debug, Default, PartialEq)]
312struct ImageCandidateLists {
313  /// The name itself.
314  exact_names:        Vec<String>,
315  /// The name and one more extension (`fig` → `fig.pdf`).
316  extended_names:     Vec<String>,
317  /// The name itself in another case.
318  nocase_exact_names: Vec<String>,
319  /// The name and one more extension, in another case.
320  nocase_candidates:  Vec<String>,
321}
322
323/// The image `name`'s candidates among `found`: each a directory entry's file name and the path to list it under,
324/// the search directories in their search order, each directory's entries in whatever order it lists them. Each
325/// list comes out in TeX's order ([`in_graphics_type_order`]: by type, then search directory, then name), not the
326/// directory's. Beyond Perl (OXIDIZED_DESIGN_DIVERGENCES #883): Perl's `pathname_findall` returns `readdir`'s order
327/// within a directory (Pathname.pm:350-371), which the filesystem decides, and the leading directory's hits first
328/// (Pathname.pm:375); an extensionless `\includegraphics{fig}` beside `fig.png` and `fig.pdf` listed them in an order
329/// that differed from one host to the next, and the first readable one is the one the digestion-time sizer reads
330/// (det354 4b; witness 2011.14197, whose `fig3..6.eps,.pdf` are now `.pdf,.eps`). Type before directory is TeX's
331/// order: graphics.sty:206-224 runs `\@for\Gin@temp:=\Gin@extensions` outermost, the path search inside
332/// `\IfFileExists`.
333fn image_candidate_lists(
334  found: impl IntoIterator<Item = (String, String)>,
335  name: &str,
336) -> ImageCandidateLists {
337  let name_lower = name.to_lowercase();
338  let mut lists = ImageCandidateLists::default();
339  for (fname, rel) in found {
340    let Some(exact) = image_file_name_match(&fname, name, &name_lower) else {
341      continue;
342    };
343    if !exact && fname.to_lowercase() == name_lower {
344      lists.nocase_exact_names.push(rel);
345    } else if !exact {
346      lists.nocase_candidates.push(rel);
347    } else if fname == name {
348      lists.exact_names.push(rel);
349    } else {
350      lists.extended_names.push(rel);
351    }
352  }
353  for list in [
354    &mut lists.exact_names,
355    &mut lists.extended_names,
356    &mut lists.nocase_exact_names,
357    &mut lists.nocase_candidates,
358  ] {
359    in_graphics_type_order(list);
360  }
361  lists
362}
363
364/// Whether `name` ends in an extension pdftex.def has a graphics rule for (`\Gin@rule@.<ext>`, pdftex.def:601-612,
365/// case as written): graphics.sty:211-231 then takes the name as given before appending any extension, so
366/// `\includegraphics{c.eps}` names that file and not a `c.eps.png` beside it, while `c.EPS` (no rule) tries the
367/// appended extensions first.
368fn has_graphics_rule(name: &str) -> bool {
369  const RULED_EXTENSIONS: [&str; 12] = [
370    "jpg", "jpeg", "JPG", "JPEG", "jb2", "jbig2", "png", "PNG", "mps", "pdf", "PDF", "eps",
371  ];
372  Path::new(name)
373    .extension()
374    .is_some_and(|ext| RULED_EXTENSIONS.iter().any(|r| ext == *r))
375}
376
377/// The extensions a graphics driver reads, in the order a name without one tries them: pdftex.def's `\Gin@extensions`
378/// (`.pdf,.png,.jpg,.mps,.jpeg,.jbig2,.jb2`, then their uppercase `.PDF,…,.JB2`, pdftex.def:597-600), then `.eps`
379/// (epstopdf-base.sty:498-505 appends it), dvips.def's `.ps` and the formats post converts. Written lowercase, the first
380/// [`GIN_EXTENSIONS`] pdftex.def's; [`graphics_type_rank`] places the other-case variants.
381const GRAPHICS_EXTENSIONS: [&str; 14] = [
382  "pdf", "png", "jpg", "mps", "jpeg", "jbig2", "jb2", "eps", "ps", "svg", "gif", "tif", "tiff",
383  "bmp",
384];
385
386/// How many of [`GRAPHICS_EXTENSIONS`] are pdftex.def's lowercase `\Gin@extensions` (pdftex.def:597-598).
387const GIN_EXTENSIONS: usize = 7;
388
389/// Whether `name` ends in an extension a graphics driver reads ([`GRAPHICS_EXTENSIONS`]), case aside — the names
390/// kpsewhich is not asked for with an extension appended.
391fn has_graphics_extension(name: &str) -> bool {
392  graphics_type_rank(name) < 4 * GRAPHICS_EXTENSIONS.len()
393}
394
395/// `candidates` in TeX's order, not the directory's: by type ([`graphics_extensions_in_order`], then
396/// [`graphics_type_rank`]: pdftex.def's `\Gin@extensions` order, pdftex.def:597-600), then by search directory (each
397/// type is looked for along the `\graphicspath`/`\input@path` entries in turn, latex.ltx:9698 `\@iffileonpath`, so
398/// `\graphicspath{{new/}{figs/}}` takes `new/plot.pdf` before `figs/plot.pdf`; the directories in the order the search
399/// listed their hits), then by name within one directory. One difference stays: LaTeX's `\IfFileExists` tries the bare
400/// name in the working directory first (latex.ltx:1095-1102), where `search_dirs` lists the source directory last
401/// (review rev78v3 finding 2; a SYNC row). The base-name retry's hits were listed as `read_dir` gave them, so 0907.3747
402/// had `nuebar.pdf,nuebar.ps` beside `nuebar_limit.ps,nuebar_limit.pdf`, and the sizer reads the first readable one
403/// (review rev78v finding 3; rev78v2 finding 2, where a tie-break by full path put `figs/` first).
404fn in_graphics_type_order(candidates: &mut [String]) {
405  let declared = graphics_extensions_in_order();
406  let directory = |found: &str| {
407    found
408      .rsplit_once('/')
409      .map_or("", |(dir, _)| dir)
410      .to_string()
411  };
412  let mut directories: Vec<String> = Vec::new();
413  for found in candidates.iter() {
414    let dir = directory(found);
415    if !directories.contains(&dir) {
416      directories.push(dir);
417    }
418  }
419  candidates.sort_by_cached_key(|found| {
420    let found_name = found.rsplit('/').next().unwrap_or(found);
421    let dir = directory(found);
422    (
423      declared_rank(found_name, &declared),
424      graphics_type_rank(found_name),
425      directories.iter().position(|d| *d == dir),
426      found_name.to_string(),
427    )
428  });
429}
430
431/// The extensions a name without one is tried with, in order, each as written with its dot (`.eps`): the live
432/// `\Gin@extensions` (graphics.sty:206-209), which graphics_sty.rs seeds as pdftex.def:597-600 and epstopdf-base's
433/// `.eps` set it ([`GRAPHICS_EXTENSIONS`]' order), as the document declared them (graphics.sty:116-117
434/// `\DeclareGraphicsExtensions`) or edited them (grfext's `\AppendGraphicsExtensions`, `\PrependGraphicsExtensions`,
435/// `\RemoveGraphicsExtensions`). One order for the search directories' candidates ([`in_graphics_type_order`]) and
436/// the TeX tree's (kpsewhich); empty without the graphics binding, where the driver's order stands
437/// ([`graphics_type_rank`], [`PDFTEX_GIN_EXTENSIONS`]).
438fn graphics_extensions_in_order() -> Vec<String> {
439  let Some(Stored::Expandable(defn)) = state::lookup_meaning(&crate::T_CS!("\\Gin@extensions"))
440  else {
441    return Vec::new();
442  };
443  let Some(ExpansionBody::Tokens(body)) = defn.get_expansion() else {
444    return Vec::new();
445  };
446  body
447    .to_string()
448    .split(',')
449    .map(|ext| ext.trim().to_string())
450    .filter(|ext| ext.starts_with('.') && ext.len() > 1)
451    .collect()
452}
453
454/// pdftex.def's `\Gin@extensions` (pdftex.def:597-600), the list graphics_sty.rs seeds.
455const PDFTEX_GIN_EXTENSIONS: [&str; 13] = [
456  ".pdf", ".png", ".jpg", ".mps", ".jpeg", ".jbig2", ".jb2", ".PDF", ".PNG", ".JPG", ".JPEG",
457  ".JBIG2", ".JB2",
458];
459
460/// The place of `name`'s extension among the `declared` ones ([`graphics_extensions_in_order`]), its case aside: TeX
461/// tries a name without an extension with each of `\Gin@extensions` in turn (graphics.sty:206-224), so after
462/// `\DeclareGraphicsExtensions{.pdf,.eps,.png}` a `fig` beside `fig.png` and `fig.eps` is `fig.eps` (2107.02597's
463/// gnuplot figures); and kpathsea finds each name as written, then in another case (TL's `texmf_casefold_search=1`),
464/// so a `.png` entry finds `nsfnet.PNG` before the `.eps` the driver appends at `\begin{document}` (1608.05172, whose
465/// pdflatex log reads `<./img/nsfnet.PNG>` beside `img/nsfnet.eps`; review rev79a2 finding 2): the place, then
466/// `false` for the entry's own case before `true` for another. An extension it does not declare comes after them
467/// (TeX does not try it). All equal when nothing was declared.
468fn declared_rank(name: &str, declared: &[String]) -> (usize, bool) {
469  declared
470    .iter()
471    .enumerate()
472    .find_map(|(place, ext)| {
473      let start = name
474        .len()
475        .checked_sub(ext.len())
476        .filter(|start| *start > 0)?;
477      let tail = name.get(start..)?;
478      tail
479        .eq_ignore_ascii_case(ext)
480        .then(|| (place, tail != ext.as_str()))
481    })
482    .unwrap_or((declared.len(), false))
483}
484
485/// The place of `name`'s extension in the order pdftex tries them: pdftex.def's `\Gin@extensions` lowercase, then in
486/// another case (`.PDF`, as it lists `.PDF,.PNG,…` after them, pdftex.def:597-600), then the rest of
487/// [`GRAPHICS_EXTENSIONS`] (`.eps` first, which epstopdf-base appends) lowercase, then in another case; past all four
488/// for any other extension.
489fn graphics_type_rank(name: &str) -> usize {
490  let n = GRAPHICS_EXTENSIONS.len();
491  let Some(ext) = Path::new(name).extension().map(|e| e.to_string_lossy()) else {
492    return 4 * n;
493  };
494  let Some(index) = GRAPHICS_EXTENSIONS
495    .iter()
496    .position(|g| ext.eq_ignore_ascii_case(g))
497  else {
498    return 4 * n;
499  };
500  let other_case = GRAPHICS_EXTENSIONS[index] != ext;
501  match (index < GIN_EXTENSIONS, other_case) {
502    (true, false) => index,
503    (true, true) => n + index,
504    (false, false) => 2 * n + index,
505    (false, true) => 3 * n + index,
506  }
507}
508
509/// Whether the directory entry `entry` is the image `name`: the name itself or the name and one extension of word
510/// characters (`fig` → `fig.pdf`, not `fig.old.pdf`; `b.v0.5_x` → `b.v0.5_x.pdf`), as Perl's `candidate_pathnames`
511/// matches with types `['*']` (Pathname.pm:350-371): `Some(true)` exactly, `Some(false)` only ignoring case
512/// (`name_lower` the name lowercased).
513fn image_file_name_match(entry: &str, name: &str, name_lower: &str) -> Option<bool> {
514  let matches = |entry: &str, name: &str| {
515    entry == name
516      || entry
517        .strip_prefix(name)
518        .and_then(|rest| rest.strip_prefix('.'))
519        .is_some_and(|ext| !ext.is_empty() && ext.chars().all(|c| c.is_alphanumeric() || c == '_'))
520  };
521  if matches(entry, name) {
522    Some(true)
523  } else if matches(&entry.to_lowercase(), name_lower) {
524    Some(false)
525  } else {
526    None
527  }
528}
529
530/// One graphicx transformation, as compiled from the option string.
531///
532/// Port of the `@transform` list Perl `image_graphicx_parse` builds
533/// (`Util/Image.pm` L142-196). Lengths are in **bp**, the unit `to_bp` yields,
534/// and angles in degrees counter-clockwise, as graphicx states them.
535#[derive(Debug, Clone, PartialEq)]
536pub enum GraphicxOp {
537  /// `page=N` — which page of a multi-page source to take.
538  Page(u32),
539  /// `trim=l b r t` — amounts to remove from each edge.
540  Trim {
541    l: f64,
542    b: f64,
543    r: f64,
544    t: f64,
545  },
546  /// `viewport=llx lly urx ury` — an absolute box (Perl's `clip` op).
547  Clip {
548    l: f64,
549    b: f64,
550    r: f64,
551    t: f64,
552  },
553  /// `angle=N`, counter-clockwise.
554  Rotate(f64),
555  Reflect,
556  /// `scale=`/`xscale=`/`yscale=`.
557  Scale {
558    x: f64,
559    y: f64,
560  },
561  /// `width=`/`height=`/`totalheight=`. A dimension left `None` is derived
562  /// from the other through the aspect ratio; Perl spells that as a 999999
563  /// sentinel with `keep_aspect` forced on (L188-189).
564  ScaleTo {
565    w:           Option<f64>,
566    h:           Option<f64>,
567    keep_aspect: bool,
568  },
569}
570
571/// A TeX/graphicx length in **bp**. Port of Perl `to_bp` + `%BP_conversions`
572/// (`Util/Image.pm` L198-210), including its `true`-prefix strip (`truept`) and
573/// its "unknown unit counts as bp" fallback. A value that is not a length at
574/// all yields 1, exactly as Perl's `else { return 1 }` does.
575pub fn to_bp(x: &str) -> f64 {
576  let x = x.trim();
577  let split = x
578    .find(|c: char| !c.is_ascii_digit() && c != '.' && c != '+' && c != '-')
579    .unwrap_or(x.len());
580  let (num, unit) = x.split_at(split);
581  let Ok(v) = num.parse::<f64>() else {
582    return 1.0;
583  };
584  let unit = unit.trim().strip_prefix("true").unwrap_or(unit.trim());
585  let factor = match unit {
586    "" | "bp" => 1.0,
587    "pt" => 72.0 / 72.27,
588    "pc" => 12.0 * 72.0 / 72.27,
589    "in" => 72.0,
590    "cm" => 72.0 / 2.54,
591    "mm" => 72.0 / 25.4,
592    "dd" => (72.0 / 72.27) * (1238.0 / 1157.0),
593    "cc" => 12.0 * (72.0 / 72.27) * (1238.0 / 1157.0),
594    "sp" => 72.0 / 72.27 / 65536.0,
595    // Perl: `($u && $BP_conversions{$u}) || 1` — an unrecognised unit falls
596    // back to a factor of 1, i.e. the number is taken as bp.
597    _ => 1.0,
598  };
599  v * factor
600}
601
602/// Compile a graphicx option string into the transformation sequence.
603///
604/// Port of Perl `image_graphicx_parse` (`Util/Image.pm` L142-196). Key order
605/// matters and is Perl's, in two ways:
606///
607/// * A rotation is applied **before** scaling when no sizing option preceded
608///   the `angle` in the source string, and after it otherwise. Perl decides
609///   this the instant it parses `angle` (`$rotfirst = !($width || $height ||
610///   $xscale || $yscale)`, L168), from the keys seen *so far* — so
611///   `angle=90,width=100pt` rotates then scales, while `width=100pt,angle=90`
612///   scales then rotates. graphicx really behaves this way and pdflatex agrees:
613///   the first is ~100x200, the second ~50x100 for a 200x100 source. We capture
614///   `rot_first` at the same point, not from the final key set.
615///
616/// `pc` differs from Perl by design: Perl's table has `pc => 12/72.27`, which
617/// is 12 *TeX pt* expressed in bp only if you also drop the pt→bp step — a pica
618/// is 12 pt, so the factor is `12 * 72/72.27`. Perl's value makes a 1pc box
619/// 0.166bp instead of 11.955bp. Ours is the correct one; no test in the corpus
620/// exercised `pc`.
621pub fn parse_graphicx_options(options: &str) -> Vec<GraphicxOp> {
622  let (mut width, mut height) = (None, None);
623  let (mut xscale, mut yscale) = (None, None);
624  let (mut aspect, mut angle, mut page) = (false, 0.0f64, None);
625  let (mut viewport, mut is_trim) = (None, false);
626  // Set the instant `angle` is parsed, from the sizing keys seen so far — NOT
627  // recomputed from the final key set. Perl `image_graphicx_parse` L168.
628  let mut rot_first = false;
629  for opt in options.split(',') {
630    let opt = opt.trim();
631    if opt.is_empty() {
632      continue;
633    }
634    let (key, val) = match opt.split_once('=') {
635      Some((k, v)) => (k.trim(), v.trim()),
636      None => (opt, ""),
637    };
638    let box4 = |v: &str| {
639      let n: Vec<f64> = v.split_whitespace().map(to_bp).collect();
640      if n.len() == 4 {
641        Some((n[0], n[1], n[2], n[3]))
642      } else {
643        None
644      }
645    };
646    match key {
647      "width" => width = Some(to_bp(val)),
648      "height" | "totalheight" => height = Some(to_bp(val)),
649      "scale" => {
650        let s = val.parse::<f64>().ok();
651        xscale = s;
652        yscale = s;
653      },
654      "xscale" => xscale = val.parse::<f64>().ok(),
655      "yscale" => yscale = val.parse::<f64>().ok(),
656      "angle" => {
657        angle = val.parse::<f64>().unwrap_or(0.0);
658        rot_first = width.is_none() && height.is_none() && xscale.is_none() && yscale.is_none();
659      },
660      "keepaspectratio" => aspect = val != "false",
661      "page" => page = val.parse::<u32>().ok(),
662      "viewport" => {
663        viewport = box4(val);
664        is_trim = false;
665      },
666      "trim" => {
667        viewport = box4(val);
668        is_trim = true;
669      },
670      _ => {},
671    }
672  }
673
674  let mut ops = Vec::new();
675  if let Some(p) = page {
676    ops.push(GraphicxOp::Page(p));
677  }
678  if let Some((a, b, c, d)) = viewport {
679    ops.push(if is_trim {
680      GraphicxOp::Trim { l: a, b, r: c, t: d }
681    } else {
682      GraphicxOp::Clip { l: a, b, r: c, t: d }
683    });
684  }
685  if rot_first && angle != 0.0 {
686    ops.push(GraphicxOp::Rotate(angle));
687  }
688  match (width, height, xscale, yscale) {
689    // Perl L187-189: a single dimension forces aspect preservation, whatever
690    // `keepaspectratio` said.
691    (Some(w), Some(h), ..) => ops.push(GraphicxOp::ScaleTo {
692      w:           Some(w),
693      h:           Some(h),
694      keep_aspect: aspect,
695    }),
696    (Some(w), None, ..) => ops.push(GraphicxOp::ScaleTo {
697      w:           Some(w),
698      h:           None,
699      keep_aspect: true,
700    }),
701    (None, Some(h), ..) => ops.push(GraphicxOp::ScaleTo {
702      w:           None,
703      h:           Some(h),
704      keep_aspect: true,
705    }),
706    (None, None, Some(x), Some(y)) => ops.push(GraphicxOp::Scale { x, y }),
707    (None, None, Some(x), None) => ops.push(GraphicxOp::Scale { x, y: 1.0 }),
708    (None, None, None, Some(y)) => ops.push(GraphicxOp::Scale { x: 1.0, y }),
709    (None, None, None, None) => {},
710  }
711  if !rot_first && angle != 0.0 {
712    ops.push(GraphicxOp::Rotate(angle));
713  }
714  ops
715}
716
717/// Apply a compiled transformation sequence to a natural size.
718///
719/// Port of Perl `image_graphicx_size` (`Util/Image.pm` L221-256), generalised
720/// over the output unit so the engine and the post-processor share one algebra:
721///
722/// * `units_per_bp` scales a bp-valued option into the caller's unit —
723///   `DPI/72.27` for device pixels (Perl's `$dppt`), `72.27/72` for TeX pt.
724/// * `quantize` applies Perl's `ceil` at each sizing step. True in pixel space,
725///   where a fractional device pixel is meaningless; false in pt space, where
726///   rounding the box to 1/100 inch would be a needless loss of precision.
727///
728/// `Page` is a selector, not a geometric transform, so it is skipped here —
729/// callers read it out separately.
730pub fn apply_graphicx_ops(
731  mut w: f64,
732  mut h: f64,
733  ops: &[GraphicxOp],
734  units_per_bp: f64,
735  quantize: bool,
736) -> (f64, f64) {
737  let round = |v: f64| if quantize { v.ceil() } else { v };
738  for op in ops {
739    match *op {
740      GraphicxOp::Page(_) | GraphicxOp::Reflect => {},
741      GraphicxOp::Scale { x, y } => {
742        w = round(w * x);
743        h = round(h * y);
744      },
745      GraphicxOp::ScaleTo { w: rw, h: rh, keep_aspect } => {
746        let (tw, th) = (rw.map(|v| v * units_per_bp), rh.map(|v| v * units_per_bp));
747        match (tw, th) {
748          (Some(tw), Some(th)) if keep_aspect => {
749            // Perl L234 `return unless $w && $h` — a degenerate natural size
750            // carries no aspect ratio to preserve, and Perl abandons the whole
751            // computation rather than guess. The sizer then reports 0.
752            if w <= 0.0 || h <= 0.0 {
753              return (0.0, 0.0);
754            }
755            // Perl L233-236: honour the less extreme request, so the result
756            // fits inside the requested box.
757            if tw / w < th / h {
758              h = h * tw / w;
759              w = tw;
760            } else {
761              w = w * th / h;
762              h = th;
763            }
764            w = round(w);
765            h = round(h);
766          },
767          (Some(tw), Some(th)) => {
768            w = round(tw);
769            h = round(th);
770          },
771          // A single dimension always preserves aspect (Perl compiles it as a
772          // scale-to with a 999999 sentinel and `keep_aspect` forced on), so
773          // the same degenerate-size bail applies.
774          (Some(tw), None) => {
775            if w <= 0.0 || h <= 0.0 {
776              return (0.0, 0.0);
777            }
778            h = round(h * tw / w);
779            w = round(tw);
780          },
781          (None, Some(th)) => {
782            if w <= 0.0 || h <= 0.0 {
783              return (0.0, 0.0);
784            }
785            w = round(w * th / h);
786            h = round(th);
787          },
788          (None, None) => {},
789        }
790      },
791      GraphicxOp::Rotate(deg) => {
792        // Perl L239-242: `$rad = -$a1 * pi/180`, then the axis-aligned bounding
793        // box of the rotated rectangle. Not quantized — Perl does not ceil here.
794        let rad = -deg * std::f64::consts::PI / 180.0;
795        let (s, c) = (rad.sin(), rad.cos());
796        let (nw, nh) = ((w * c).abs() + (h * s).abs(), (w * s).abs() + (h * c).abs());
797        w = nw;
798        h = nh;
799      },
800      GraphicxOp::Trim { l, b, r, t } => {
801        // Perl L248-250: shrink by the trimmed edges.
802        w = round(w - (l + r) * units_per_bp);
803        h = round(h - (t + b) * units_per_bp);
804      },
805      GraphicxOp::Clip { l, b, r, t } => {
806        // Perl L252-253: the viewport box IS the new extent.
807        w = round((r - l) * units_per_bp);
808        h = round((t - b) * units_per_bp);
809      },
810    }
811  }
812  (w.max(0.0), h.max(0.0))
813}
814
815/// The pixel rectangle a `trim`/`viewport` op keeps of a `w`×`h` raster, as
816/// `(x, y, width, height)` from its top-left corner; `None` when the box keeps
817/// the whole image or no pixel of it. Port of Perl `image_graphicx_complex`'s
818/// trim/clip arm (`Util/Image.pm` L400-418): TeX measures the box from the
819/// lower-left corner and ImageMagick from the upper-left, and the box is
820/// clamped to the image, never padded. `px_per_bp` is the raster's own
821/// resolution over 72 (DIVERGENCES #337: Perl divides by 72.27 and reads the
822/// resolution without its unit).
823pub fn graphicx_crop_rect(
824  w: u32,
825  h: u32,
826  op: &GraphicxOp,
827  px_per_bp: f64,
828) -> Option<(u32, u32, u32, u32)> {
829  let (wf, hf) = (w as f64, h as f64);
830  // A length in pt reaches here as bp through 72/72.27, so a whole number of
831  // pixels can land a hair off it (`100.375pt` is 100.00000000000001bp):
832  // snap within a millionth before rounding, or the box gains a pixel row.
833  let floor = |v: f64| (v + 1e-6).floor();
834  let ceil = |v: f64| (v - 1e-6).ceil();
835  let (x0, y0, ww, hh) = match *op {
836    // Amounts to trim: left, bottom, right, top.
837    GraphicxOp::Trim { l, b, r, t } => (
838      floor(l * px_per_bp),
839      floor(t * px_per_bp),
840      ceil(wf - (l + r) * px_per_bp),
841      ceil(hf - (t + b) * px_per_bp),
842    ),
843    // The box itself: lower-left and upper-right corners.
844    GraphicxOp::Clip { l, b, r, t } => (
845      floor(l * px_per_bp),
846      floor(hf - t * px_per_bp),
847      ceil((r - l) * px_per_bp),
848      ceil((t - b) * px_per_bp),
849    ),
850    _ => return None,
851  };
852  if !(x0 > 0.0 || y0 > 0.0 || x0 + ww < wf || y0 + hh < hf) {
853    return None;
854  }
855  let (x, y) = (x0.max(0.0), y0.max(0.0));
856  let cw = (ww + x0.min(0.0)).min(wf - x);
857  let ch = (hh + y0.min(0.0)).min(hf - y);
858  (cw >= 1.0 && ch >= 1.0).then_some((x as u32, y as u32, cw as u32, ch as u32))
859}
860
861/// A raster's own resolution in dots per inch, `(x, y)`, as pdfTeX reads it
862/// to size an image: a PNG's `pHYs` chunk (unit 1 is per metre), rounded to
863/// whole dpi, or a JPEG's density from the segment right after SOI
864/// (`jpeg_resolution_dpi`) — pdflatex measures an 11811 px/m PNG at 300 dpi
865/// and a 118 px/cm JPEG at 299. `None` when the file states none, only an aspect ratio (unit 0), or one pdfTeX ignores
866/// for a raster of `pixels` (width, height; `pdftex_raster_resolution`): pdfTeX then takes `\pdfimageresolution`
867/// ([`raster_sizing_dpi`]). Reads the head only: both come before the pixels.
868pub fn raster_resolution_dpi(path: &str, pixels: (f64, f64)) -> Option<(f64, f64)> {
869  pdftex_raster_resolution(path, pixels).ok()
870}
871
872/// The resolution pdfTeX sizes a raster of `pixels` at, as `\pdfximage` does (pdftex.web:34488-34515): its own
873/// ([`raster_resolution_dpi`]), else `\pdfimageresolution` ([`pdf_image_resolution`]), with pdfTeX's Warning, when
874/// `warn`, if it ignores one the file states.
875pub fn raster_sizing_dpi(path: &str, pixels: (f64, f64), warn: bool) -> (f64, f64) {
876  pdftex_raster_resolution(path, pixels).unwrap_or_else(|ignored| {
877    if let Some(why) = ignored.filter(|_| warn) {
878      Warn!(
879        "unexpected",
880        "resolution",
881        s!("{why} image resolution ignored in {path}")
882      );
883    }
884    let res = pdf_image_resolution();
885    (res, res)
886  })
887}
888
889/// The resolution the raster at `path` states, if pdfTeX keeps it for its `(x, y)` pixels (pdftex.web:34488-34505, in
890/// its order): above 65535 dpi on either axis it is "too large"; both axes 0 is no resolution (no warning); else one inch
891/// (`one_inch` = 226 px, :15812) or more per stated dot on either axis, a zero axis among them, is "too small" — a
892/// 300 px image stating 1 dpi would be 28800 px wide. `Err` carries the reason pdfTeX warns with, if any.
893fn pdftex_raster_resolution(
894  path: &str,
895  (x, y): (f64, f64),
896) -> Result<(f64, f64), Option<&'static str>> {
897  let Some((xr, yr)) = stated_raster_resolution(path) else {
898    return Err(None);
899  };
900  if xr > 65535.0 || yr > 65535.0 {
901    Err(Some("too large"))
902  } else if xr == 0.0 && yr == 0.0 {
903    Err(None)
904  } else if x / 226.0 >= xr || y / 226.0 >= yr {
905    Err(Some("too small"))
906  } else {
907    Ok((xr, yr))
908  }
909}
910
911/// `\pdfimageresolution` as pdftex.web:34511-34515 applies it to a raster stating no usable resolution: the register
912/// clamped to 0..65535, and 72 dpi when that is 0 (`ext_xn_over_d(one_hundred_inch, x, 7200)`).
913pub fn pdf_image_resolution() -> f64 {
914  let res = match state::lookup_register_quiet("\\pdfimageresolution") {
915    Some(crate::RegisterValue::Number(n)) => n.0.clamp(0, 65535),
916    _ => 72,
917  };
918  if res > 0 { res as f64 } else { 72.0 }
919}
920
921/// What a graphic file holds, by its first bytes: drawn (PDF, PostScript), so a converter renders it at a density, or
922/// a raster's pixels (PNG, JPEG, GIF, TIFF, BMP, WebP), which `-density` does not resample.
923#[derive(Debug, Clone, Copy, PartialEq, Eq)]
924pub enum GraphicContent {
925  Pdf,
926  PostScript,
927  Raster,
928}
929
930/// [`GraphicContent`] of the file at `path`, whatever its name (a PDF or EPS saved as `.pstex`, cond-mat0603250's
931/// `loop.pstex`); `None` when the head is none of them (a compressed `.eps.gz` among them).
932pub fn graphic_content(path: &Path) -> Option<GraphicContent> {
933  use std::io::Read;
934  let mut head = [0u8; 12];
935  let mut file = open_file_resilient(path)?;
936  let n = file.read(&mut head).ok()?;
937  let head = &head[..n];
938  if head.starts_with(b"%PDF") {
939    Some(GraphicContent::Pdf)
940  } else if is_postscript_head(head) {
941    Some(GraphicContent::PostScript)
942  } else if head.starts_with(b"\x89PNG\r\n\x1a\n")
943    || head.starts_with(&[0xFF, 0xD8])
944    || head.starts_with(b"GIF8")
945    || head.starts_with(b"II*\0")
946    || head.starts_with(b"MM\0*")
947    || head.starts_with(b"BM")
948    || (head.starts_with(b"RIFF") && head.get(8..12) == Some(b"WEBP"))
949  {
950    Some(GraphicContent::Raster)
951  } else {
952    None
953  }
954}
955
956/// A PostScript head: a DSC `%!` or `%%` line, or a DOS EPS binary header (read by [`read_postscript_boxes`]).
957fn is_postscript_head(head: &[u8]) -> bool {
958  head.starts_with(b"%!") || head.starts_with(b"%%") || head.starts_with(b"\xc5\xd0\xd3\xc6")
959}
960
961/// The resolution [`raster_resolution_dpi`] checks, as the file states it.
962fn stated_raster_resolution(path: &str) -> Option<(f64, f64)> {
963  use std::io::Read;
964  let mut bytes = Vec::new();
965  std::fs::File::open(path)
966    .ok()?
967    .take(1 << 18)
968    .read_to_end(&mut bytes)
969    .ok()?;
970  if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
971    // Chunks: length, type, data, CRC; `pHYs` precedes the first `IDAT`.
972    let mut at = 8;
973    while at + 8 <= bytes.len() {
974      let len = u32::from_be_bytes(bytes[at..at + 4].try_into().ok()?) as usize;
975      let kind = &bytes[at + 4..at + 8];
976      let data = bytes.get(at + 8..at + 8 + len)?;
977      match kind {
978        b"pHYs" if len == 9 && data[8] == 1 => {
979          let x = u32::from_be_bytes(data[0..4].try_into().ok()?) as f64;
980          let y = u32::from_be_bytes(data[4..8].try_into().ok()?) as f64;
981          return Some(((x * 0.0254).round(), (y * 0.0254).round()));
982        },
983        b"IDAT" | b"IEND" => return None,
984        _ => at += 12 + len,
985      }
986    }
987    None
988  } else if bytes.starts_with(&[0xFF, 0xD8]) {
989    jpeg_resolution_dpi(&bytes)
990  } else {
991    None
992  }
993}
994
995/// A JPEG's density as pdfTeX's `read_jpg_info` reads it (pdftexdir/writejpg.c, TL 2025): only the segment right after
996/// SOI counts. A JFIF `APP0` gives its density (unit 1 per inch; 2 per centimetre, `img_xres *= 2.54` truncated to an
997/// int; any other unit none), a zero axis taking the other's value; an Exif `APP1` its IFD0 resolution
998/// ([`exif_resolution_dpi`]); anything else, or Exif after a JFIF segment, none.
999fn jpeg_resolution_dpi(bytes: &[u8]) -> Option<(f64, f64)> {
1000  let len = u16::from_be_bytes([*bytes.get(4)?, *bytes.get(5)?]) as usize;
1001  match bytes.get(2..4)? {
1002    [0xFF, 0xE0] => {
1003      let data = bytes.get(6..)?;
1004      if !data.starts_with(b"JFIF\0") {
1005        return None;
1006      }
1007      let x = u16::from_be_bytes([*data.get(8)?, *data.get(9)?]) as f64;
1008      let y = u16::from_be_bytes([*data.get(10)?, *data.get(11)?]) as f64;
1009      let (x, y) = match data[7] {
1010        1 => (x, y),
1011        2 => ((x * 2.54).trunc(), (y * 2.54).trunc()),
1012        _ => (0.0, 0.0),
1013      };
1014      Some(match (x, y) {
1015        (0.0, y) => (y, y),
1016        (x, 0.0) => (x, x),
1017        xy => xy,
1018      })
1019    },
1020    [0xFF, 0xE1] => {
1021      // `length = get_unsigned_pair(fp) - 2`, then the 5-byte signature.
1022      let data = bytes.get(6..6 + len.checked_sub(2)?)?;
1023      exif_resolution_dpi(data.strip_prefix(b"Exif\0")?)
1024    },
1025    _ => None,
1026  }
1027}
1028
1029/// An Exif segment's resolution as writejpg.c's `read_APP1_Exif` reads it: the TIFF header after any NUL padding, IFD0's
1030/// `XResolution` (282) and `YResolution` (283) as an integer quotient, 72 when absent, times `ResolutionUnit` (296: 3
1031/// is per centimetre), truncated to an int; a malformed header gives none.
1032fn exif_resolution_dpi(data: &[u8]) -> Option<(f64, f64)> {
1033  let tiff = data.get(data.iter().position(|&b| b != 0)?..)?;
1034  let big = match tiff.get(..2)? {
1035    b"MM" => true,
1036    b"II" => false,
1037    _ => return None,
1038  };
1039  let read = |at: usize, n: usize| -> Option<u32> {
1040    let b = tiff.get(at..at + n)?;
1041    Some(b.iter().enumerate().fold(0u32, |v, (i, &byte)| {
1042      let shift = 8 * if big { n - 1 - i } else { i };
1043      v | (u32::from(byte) << shift)
1044    }))
1045  };
1046  if read(2, 2)? != 42 {
1047    return None;
1048  }
1049  let mut at = read(4, 4)? as usize;
1050  let fields = read(at, 2)?;
1051  at += 2;
1052  let (mut xres, mut yres, mut unit) = (72.0, 72.0, 1.0);
1053  // (`num`/`den` keep the last rational read, as the C does)
1054  let (mut num, mut den) = (0i32, 0i32);
1055  let mut value = 0u32;
1056  for _ in 0..fields {
1057    let (tag, kind) = (read(at, 2)?, read(at + 2, 2)?);
1058    let field = at + 8;
1059    match kind {
1060      1 | 7 => value = u32::from(*tiff.get(field)?),
1061      3 => value = read(field, 2)?,
1062      4 | 9 => value = read(field, 4)?,
1063      5 | 10 => {
1064        value = read(field, 4)?;
1065        num = read(value as usize, 4)? as i32;
1066        den = read(value as usize + 4, 4)? as i32;
1067      },
1068      _ => {},
1069    }
1070    match tag {
1071      282 if den != 0 => xres = f64::from(num.wrapping_div(den)),
1072      283 if den != 0 => yres = f64::from(num.wrapping_div(den)),
1073      296 if value == 2 => unit = 1.0,
1074      296 if value == 3 => unit = 2.54,
1075      _ => {},
1076    }
1077    at += 12;
1078  }
1079  Some(((xres * unit).trunc(), (yres * unit).trunc()))
1080}
1081
1082/// A graphic's natural size as its file gives it: a raster's in pixels, a vector's (EPS/PS, PDF, SVG) a physical length
1083/// in pt.
1084enum Natural {
1085  Pixels(f64, f64),
1086  Points(f64, f64),
1087}
1088
1089/// The natural size of the graphic file at `path`, read by its content, not its name (`None` when no reader sizes it).
1090fn natural_size(path: &Path) -> Option<Natural> {
1091  match read_image_size(path) {
1092    Some(ImageSize::Pixels(w, h)) if w > 0 && h > 0 => Some(Natural::Pixels(w as f64, h as f64)),
1093    // Beyond Perl (OXIDIZED_DESIGN_DIVERGENCES #886): an EPS/PS BoundingBox is bp, as TeX reads it (graphics.sty
1094    // `\Gread@eps`; pdflatex through epstopdf), not pixels at `DPI` — Perl's Util/Image.pm:271 `$w * 72.27 / $dpi`
1095    // made a 40bp figure 28.908pt where latex makes it 40.15pt, and a `\psfig` panel row (OD #876) 72.27/100 of
1096    // its width (1106.2745 Figs 1-2, 7, 8, 10).
1097    Some(ImageSize::PostScriptBp(w, h)) => Some(Natural::Points(bp_to_pt(w), bp_to_pt(h))),
1098    // Not a raster or PostScript file (or one without a size): emulate pdfTeX and read the natural size from the
1099    // file itself. pdfTeX's built-in reader takes a PDF's CropBox (its default) or MediaBox, and an SVG's viewBox —
1100    // with NO external tool. (Perl-LaTeXML instead shells out to ImageMagick precisely because Image::Size can't
1101    // read PDF; even then it forces `pdf:use-cropbox` to match pdfTeX. So the faithful, self-contained move is
1102    // pdfTeX's, not Perl's.) `natural_size_pt` shares the same CropBox→MediaBox reader as
1103    // `LaTeXML::Post::Graphics`.
1104    _ => natural_size_pt(path).map(|(w, h)| Natural::Points(w, h)),
1105  }
1106}
1107
1108/// The natural size of the first of `candidates` (comma-joined, resolved against `source_dir`) whose size can be read,
1109/// whatever its type: the candidates come in TeX's order (`in_graphics_type_order`, pdftex.def's `\Gin@extensions`),
1110/// so beside `fig.pdf` an extensionless `fig`'s size is the `.pdf`'s, as pdflatex reads it, not a `fig.ps`'s further
1111/// down the list, and beside `q.eps` a `q.png` before it is the graphic; Perl's sizer stops at the first candidate it
1112/// can read too (Util/Image.pm:259-272, `return … if $w`). The box (`image_graphicx_sizer`) and the natural `cssstyle`
1113/// (`natural_display_size_pt_of_candidates`) both read this one, so the `cssstyle` is the size pdflatex prints the
1114/// graphic at (review rev78z finding 1). Post may render another candidate — it picks by desirability
1115/// (latexml_post/src/graphics.rs:321-371) —, at that size: 2107.02597's 640x480 png at its eps's 36.135em x 25.294em,
1116/// about 7 % out of proportion (a SYNC row).
1117fn first_natural_size(candidates: &str, source_dir: &str) -> Option<(Natural, PathBuf)> {
1118  candidates.split(',').find_map(|candidate| {
1119    let candidate = candidate.trim();
1120    // (judged as opened: the candidate is a lexical form of the file the search judged)
1121    let path = resolve_candidate(candidate, source_dir);
1122    (!candidate.is_empty() && crate::util::pathname::read_allowed(&path.to_string_lossy()))
1123      .then(|| natural_size(&path))
1124      .flatten()
1125      .map(|natural| (natural, path))
1126  })
1127}
1128
1129/// Perl: `image_graphicx_sizer($whatsit)` (Util::Image L259-272).
1130///
1131/// Reads image dimensions from `candidates`, applies the `options` string
1132/// (graphicx keyvals: width/height/totalheight/scale/keepaspectratio) and
1133/// writes back `cached_width`, `cached_height`, `cached_depth` on the
1134/// whatsit so downstream getSize() consumers (pgf, tikz) see the correct
1135/// box dimensions.
1136pub fn image_graphicx_sizer(whatsit: &mut Whatsit) {
1137  let candidates = whatsit
1138    .get_property("candidates")
1139    .map(|c| c.to_string())
1140    .unwrap_or_default();
1141  let options = whatsit
1142    .get_property("options")
1143    .map(|c| c.to_string())
1144    .unwrap_or_default();
1145
1146  // The first candidate whose size can be read decides, whatever its type (`first_natural_size`).
1147  let source_dir = state::lookup_string("SOURCEDIRECTORY");
1148  let natural = first_natural_size(&candidates, &source_dir);
1149
1150  let (nw_pt, nh_pt) = match natural {
1151    // Beyond Perl (OXIDIZED_DESIGN_DIVERGENCES #1188): a raster is as long as pdfTeX sets it, its pixels at its own
1152    // density, else at `\pdfimageresolution` (72 dpi: a densityless 200 px PNG is 200bp), not at Perl's `$DPI = 100`
1153    // (Util/Image.pm:37, :271).
1154    Some((Natural::Pixels(w, h), path)) => {
1155      // pdftex.def's `\Gread@@pdftex` reads a file by `\pdfximage` once and reuses it (`\csname <file>
1156      // image\Gin@attr@hash\endcsname`), so pdfTeX warns about its resolution at the first inclusion only; the hash's
1157      // `:D[<decode>]` and `:I` (interpolate) make another read. (Its page and pagebox parts read a raster once.)
1158      let path = path.to_string_lossy();
1159      // graphicx.sty:101-103 `decodearray` sets `\Gin@decode`; :119-120 `interpolate` goes through `\Gin@boolkey`
1160      // (:137-138): lowercased, empty is true, `true`/`false` set it, any other value names no macro and changes nothing.
1161      let (mut decode, mut interpolate) = ("", false);
1162      for opt in options.split(',') {
1163        let (key, value) = opt
1164          .split_once('=')
1165          .map_or((opt.trim(), None), |(k, v)| (k.trim(), Some(v.trim())));
1166        match (key, value) {
1167          ("decodearray", Some(v)) => {
1168            decode = v
1169              .strip_prefix('{')
1170              .and_then(|v| v.strip_suffix('}'))
1171              .unwrap_or(v)
1172              .trim();
1173          },
1174          ("interpolate", None) => interpolate = true,
1175          ("interpolate", Some(v)) => match v.to_lowercase().as_str() {
1176            "" | "true" => interpolate = true,
1177            "false" => interpolate = false,
1178            _ => {},
1179          },
1180          _ => {},
1181        }
1182      }
1183      let decode = if decode.is_empty() {
1184        String::new()
1185      } else {
1186        s!(":D[{decode}]")
1187      };
1188      let read = s!(
1189        "Gin_image_read:{path}{decode}{}",
1190        if interpolate { ":I" } else { "" }
1191      );
1192      let first = !state::lookup_bool(&read);
1193      state::assign_value(&read, true, Some(state::Scope::Global));
1194      let (x, y) = raster_sizing_dpi(&path, (w, h), first);
1195      (w * 72.27 / x, h * 72.27 / y)
1196    },
1197    Some((Natural::Points(w, h), _)) => (w, h),
1198    None => {
1199      // Whatever we decide, we MUST set `cached_width`: without it, `compute_size`
1200      // falls through to summing the whatsit's ARGUMENT boxes — and one of them is
1201      // the Semiverbatim *filename* — so a bare `arrange_panels` would wrap figure
1202      // rows by path length (arXiv:2409.16471 fig 2: 12 uniform 0.245\textwidth
1203      // panels split 3/3/2/3/1 by filename, not 3 rows of 4).
1204      //
1205      // Last resort — a PDF whose page box is buried in a compressed object stream
1206      // (where pdfTeX's full parser would still succeed but our byte reader can't),
1207      // or an unreadable SVG. Honor an EXPLICIT `width=`/`height=` request (the
1208      // display size LaTeXML already emits), else 0 (Perl-without-ImageMagick
1209      // parity). Still set `cached_width` so the filename is never summed.
1210      let mut ew: Option<Dimension> = None;
1211      let mut eh: Option<Dimension> = None;
1212      for opt in options.split(',') {
1213        let opt = opt.trim();
1214        if let Some(val) = opt.strip_prefix("width=") {
1215          ew = <Dimension as std::str::FromStr>::from_str(val.trim()).ok();
1216        } else if let Some(val) = opt.strip_prefix("height=") {
1217          eh = <Dimension as std::str::FromStr>::from_str(val.trim()).ok();
1218        } else if let Some(val) = opt.strip_prefix("totalheight=") {
1219          eh = <Dimension as std::str::FromStr>::from_str(val.trim()).ok();
1220        }
1221      }
1222      whatsit.set_property("cached_width", Stored::Dimension(ew.unwrap_or_default()));
1223      whatsit.set_property("cached_height", Stored::Dimension(eh.unwrap_or_default()));
1224      whatsit.set_property("cached_depth", Stored::Dimension(Dimension::default()));
1225      return;
1226    },
1227  };
1228  // pdfTeX/graphics.sty box sizing in pt (verified against `\the\wd` under pdflatex): with an explicit `width=`, the
1229  // box width IS the request and the natural size only fills in the height via the aspect ratio.
1230  let (bw, bh) = graphicx_box_pt(nw_pt, nh_pt, &options);
1231  whatsit.set_property("cached_width", Stored::Dimension(bw));
1232  whatsit.set_property("cached_height", Stored::Dimension(bh));
1233  whatsit.set_property("cached_depth", Stored::Dimension(Dimension::default()));
1234}
1235
1236/// Run a fallible I/O op, retrying on a *transient* lock. On Windows a
1237/// just-written file — a figure the converter emitted a moment ago, or a test
1238/// fixture — can be momentarily locked by another handle (antivirus real-time
1239/// scanning of the fresh file, or Windows' stricter default file sharing). A
1240/// bare `op().ok()?` would turn that into a silent `None`, and a figure would
1241/// reach the engine at 0x0.
1242///
1243/// A genuine `NotFound` is not a lock, so it fails fast. Every *other* error is
1244/// treated as possibly-transient and retried with a widening backoff up to
1245/// ~0.5 s total. The fresh-file lock usually surfaces as `PermissionDenied`
1246/// (`ERROR_SHARING_VIOLATION`), but under heavy parallel load (a full `cargo
1247/// test` with antivirus active) it has shown other kinds and needed longer than
1248/// a few ms to clear — so this deliberately retries broadly rather than gating on
1249/// one `ErrorKind`. A permanently-unreadable path pays the full budget once and
1250/// then fails; the happy path (Ok on the first try) pays nothing.
1251fn with_transient_retry<T>(mut op: impl FnMut() -> std::io::Result<T>) -> Option<T> {
1252  let mut tries = 0u32;
1253  loop {
1254    match op() {
1255      Ok(v) => return Some(v),
1256      Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None,
1257      Err(_) if tries < 10 => {
1258        tries += 1;
1259        std::thread::sleep(std::time::Duration::from_millis(u64::from(tries) * 10));
1260      },
1261      Err(_) => return None,
1262    }
1263  }
1264}
1265
1266/// [`std::fs::read`] with the transient-lock retry of [`with_transient_retry`].
1267fn read_file_resilient(path: &Path) -> Option<Vec<u8>> {
1268  with_transient_retry(|| std::fs::read(path))
1269}
1270
1271/// [`std::fs::File::open`] with the transient-lock retry of
1272/// [`with_transient_retry`]. Only the open races with the scanner/writer; reads
1273/// on the returned handle do not, so callers keep their streaming reads.
1274fn open_file_resilient(path: &Path) -> Option<std::fs::File> {
1275  with_transient_retry(|| std::fs::File::open(path))
1276}
1277
1278/// Read image dimensions (width, height) in pixels from a file.
1279/// Supports PNG, JPEG, and EPS (PostScript BoundingBox, its bp rounded to whole units).
1280///
1281/// This is a narrow replacement for `Image::Size::imgsize` (Perl
1282/// `image_size` at Util::Image L86-97). Only a few formats are needed
1283/// for typical arXiv graphics inclusions — anything else returns `None`
1284/// so the caller skips sizing (mirroring Perl's `return unless $w`).
1285pub fn read_image_dimensions(path: &Path) -> Option<(u32, u32)> {
1286  read_image_size(path).map(|size| match size {
1287    ImageSize::Pixels(w, h) => (w, h),
1288    ImageSize::PostScriptBp(w, h) => (w.round() as u32, h.round() as u32),
1289  })
1290}
1291
1292/// What [`read_image_size`] measures: a raster's pixel count, or a PostScript file's bounding box in bp — a physical
1293/// size, which needs no resolution.
1294#[derive(Debug, Clone, Copy, PartialEq)]
1295pub enum ImageSize {
1296  /// A PNG's or JPEG's width and height in pixels.
1297  Pixels(u32, u32),
1298  /// An EPS/PS file's `%%BoundingBox` width and height in bp ([`read_postscript_size_bp`]).
1299  PostScriptBp(f64, f64),
1300}
1301
1302/// The size of a PNG, JPEG or EPS/PS file, sniffed from its header ([`ImageSize`]), read once per path and conversion.
1303pub fn read_image_size(path: &Path) -> Option<ImageSize> {
1304  IMAGE_DIMENSIONS_MEMO.with(|m| {
1305    if let Some(hit) = m.borrow().get(path) {
1306      return *hit;
1307    }
1308    let value = read_image_size_uncached(path);
1309    m.borrow_mut().insert(path.to_path_buf(), value);
1310    value
1311  })
1312}
1313
1314// Per-thread memos of the on-disk size reads, keyed by path and cleared per
1315// conversion (`clear_image_size_memo`, beside the kpsewhich memo). pdfTeX
1316// reads an image file's box ONCE and shares the XObject across every
1317// `\includegraphics` of it (`page=N` selects a page of the read resource);
1318// without the memo every inclusion re-read the file — hwemoji's manual
1319// includes its 6.7 MB, 3,677-page `hwemoji-assets.pdf` ~7,800 times through
1320// `\hwemoji@insert` (hwemoji.sty:11), three reads each, and timed out at
1321// 420 s once #230 let the asset resolve (2 s before). Guard:
1322// `cluster_package_guards::graphics_asset_memo::repeated_inclusions_of_one_asset_read_it_once`.
1323type SizeMemo<T> = std::cell::RefCell<rustc_hash::FxHashMap<PathBuf, Option<T>>>;
1324std::thread_local! {
1325  static IMAGE_DIMENSIONS_MEMO: SizeMemo<ImageSize> =
1326    std::cell::RefCell::new(rustc_hash::FxHashMap::default());
1327  static PDF_PAGE_BOX_MEMO: SizeMemo<[f64; 4]> =
1328    std::cell::RefCell::new(rustc_hash::FxHashMap::default());
1329}
1330
1331/// Clear the per-thread image size memos. Called at the start of every
1332/// conversion, beside `clear_kpsewhich_memo`: a long-lived worker thread
1333/// converts many papers, and a file may change between them.
1334pub fn clear_image_size_memo() {
1335  IMAGE_DIMENSIONS_MEMO.with(|m| m.borrow_mut().clear());
1336  PDF_PAGE_BOX_MEMO.with(|m| m.borrow_mut().clear());
1337  PDF_PAGE_COUNT_MEMO.with(|m| m.borrow_mut().clear());
1338}
1339
1340fn read_image_size_uncached(path: &Path) -> Option<ImageSize> {
1341  use std::io::Read;
1342  let mut file = open_file_resilient(path)?;
1343  let mut header = [0u8; 32];
1344  file.read_exact(&mut header).ok()?;
1345
1346  // PNG: signature + IHDR chunk
1347  if &header[0..8] == b"\x89PNG\r\n\x1a\n" {
1348    let width = u32::from_be_bytes([header[16], header[17], header[18], header[19]]);
1349    let height = u32::from_be_bytes([header[20], header[21], header[22], header[23]]);
1350    return Some(ImageSize::Pixels(width, height));
1351  }
1352
1353  // JPEG: the frame header (SOF) gives the size; walk the segments to it,
1354  // seeking past each one rather than reading the file.
1355  if header[0] == 0xFF && header[1] == 0xD8 {
1356    return read_jpeg_frame_size(&mut file).map(|(w, h)| ImageSize::Pixels(w, h));
1357  }
1358
1359  // EPS: PostScript BoundingBox comment, in bp (1bp = 1/72"), or a binary preview header.
1360  if is_postscript_head(&header) {
1361    let (w, h) = read_postscript_size_bp(path)?;
1362    return Some(ImageSize::PostScriptBp(w, h));
1363  }
1364
1365  None
1366}
1367
1368/// A PostScript file's size in bp, as TeX reads it: the `%%BoundingBox`, graphics.sty's `\Gread@eps` reading
1369/// (`\Gread@BBox`, graphics.sty:52, read at :365-399; the `hiresbb` option, :56-57, aside) and epstopdf's, which
1370/// pdflatex then reads as the page; a
1371/// `%%HiResBoundingBox` only when there is no `%%BoundingBox` (where TeX finds no size at all), as post reads the file
1372/// (latexml_post graphics.rs `read_postscript_bounding_box_full`). `None` for an empty box. Until 78z the high-resolution
1373/// box came first, rounded: a file with `%%BoundingBox: 0 0 200 100` and `%%HiResBoundingBox: 0.4 0.3 199.3 99.4` was
1374/// 199bp x 99bp where latex and pdflatex make it 200.75pt x 100.375pt; hep-ex0703011's `eeggmet.eps` carries a stale
1375/// full-page `%%HiResBoundingBox` (612x792) beside its 540x522 `%%BoundingBox`.
1376pub fn read_postscript_size_bp(path: &Path) -> Option<(f64, f64)> {
1377  let boxes = read_postscript_boxes(path)?;
1378  let (llx, lly, urx, ury) = boxes.bounding_box.or(boxes.hires_bounding_box)?;
1379  let (w, h) = ((urx - llx).max(0.0), (ury - lly).max(0.0));
1380  (w > 0.0 && h > 0.0).then_some((w, h))
1381}
1382
1383/// Parse `"llx lly urx ury"` from a BoundingBox comment body.
1384pub fn parse_bbox(rest: &str) -> Option<(f64, f64, f64, f64)> {
1385  let mut it = rest.split_whitespace();
1386  let llx = it.next()?.parse::<f64>().ok()?;
1387  let lly = it.next()?.parse::<f64>().ok()?;
1388  let urx = it.next()?.parse::<f64>().ok()?;
1389  let ury = it.next()?.parse::<f64>().ok()?;
1390  Some((llx, lly, urx, ury))
1391}
1392
1393/// The DSC bounding-box comments of a PostScript file (Adobe DSC 3.0:
1394/// `%%BoundingBox:`, `%%HiResBoundingBox:`, `(atend)`), as `(llx, lly, urx, ury)`
1395/// in bp.
1396///
1397/// A comment line is ASCII, but its neighbours need not be text: a Latin-1
1398/// `%%Title`, a binary preview, a multi-byte character cut at the window's
1399/// edge. So the file is scanned as bytes, in lines ending at CR, LF or CRLF.
1400/// Only the header window (the first 32 KB, `PS_COMMENT_WINDOW`) is read, and
1401/// the trailer window too when the box is deferred with `(atend)`. The first
1402/// `%%BoundingBox:` line decides, as in graphics.sty (`\Gread@eps`, 391-399)
1403/// and epstopdf; after `(atend)` the trailer's last box wins, as DSC and
1404/// graphics.sty read it. Comments inside an embedded document
1405/// (`%%BeginDocument` .. `%%EndDocument`) are its own, not the file's, and are
1406/// skipped. A DOS EPS binary header (`C5 D0 D3 C6`, then the PostScript
1407/// section's offset and length, little-endian) is followed to its PostScript
1408/// section. pdflatex (through epstopdf) sizes a Latin-1, a CR-only, an
1409/// `(atend)` and a DOS EPS alike; repro `graphics-tikz/eps_bounding_box_bytes.tex`.
1410#[derive(Debug, Default, Clone, Copy, PartialEq)]
1411pub struct PostScriptBoxes {
1412  pub bounding_box:       Option<(f64, f64, f64, f64)>,
1413  pub hires_bounding_box: Option<(f64, f64, f64, f64)>,
1414}
1415
1416/// How much of a PostScript file's head (and, for `(atend)`, its tail) is read.
1417const PS_COMMENT_WINDOW: u64 = 32 * 1024;
1418
1419/// See [`PostScriptBoxes`]; `None` when the file cannot be read.
1420pub fn read_postscript_boxes(path: &Path) -> Option<PostScriptBoxes> {
1421  use std::io::{Read, Seek, SeekFrom};
1422  let mut file = open_file_resilient(path)?;
1423  let file_len = file.metadata().ok()?.len();
1424  let mut dos = [0u8; 12];
1425  let dos_len = file.read(&mut dos).ok()?;
1426  let (start, end) = if dos_len == 12 && dos.starts_with(b"\xc5\xd0\xd3\xc6") {
1427    let offset = u64::from(u32::from_le_bytes([dos[4], dos[5], dos[6], dos[7]]));
1428    let length = u64::from(u32::from_le_bytes([dos[8], dos[9], dos[10], dos[11]]));
1429    (
1430      offset.min(file_len),
1431      offset.saturating_add(length).min(file_len),
1432    )
1433  } else {
1434    (0, file_len)
1435  };
1436  let mut window = |from: u64, to: u64| -> Option<Vec<u8>> {
1437    file.seek(SeekFrom::Start(from)).ok()?;
1438    let mut bytes = Vec::new();
1439    (&mut file).take(to - from).read_to_end(&mut bytes).ok()?;
1440    Some(bytes)
1441  };
1442  let mut boxes = PostScriptBoxes::default();
1443  let mut atend = false;
1444  let mut seen_box = false;
1445  let mut depth = 0usize;
1446  for line in dsc_lines(&window(start, (start + PS_COMMENT_WINDOW).min(end))?) {
1447    if line.starts_with(b"%%BeginDocument") {
1448      depth += 1;
1449      continue;
1450    }
1451    if line.starts_with(b"%%EndDocument") {
1452      depth = depth.saturating_sub(1);
1453      continue;
1454    }
1455    if depth > 0 {
1456      continue;
1457    }
1458    if let Some(rest) = line.strip_prefix(b"%%BoundingBox:") {
1459      // A line that reads as no box is passed over (epstopdf's value match).
1460      if !seen_box {
1461        if rest.trim_ascii() == b"(atend)" {
1462          seen_box = true;
1463          atend = true;
1464        } else if let Some(bbox) = parse_bbox_bytes(rest) {
1465          seen_box = true;
1466          boxes.bounding_box = Some(bbox);
1467        }
1468      }
1469    } else if let Some(rest) = line.strip_prefix(b"%%HiResBoundingBox:")
1470      && boxes.hires_bounding_box.is_none()
1471    {
1472      boxes.hires_bounding_box = parse_bbox_bytes(rest);
1473    }
1474  }
1475  if atend {
1476    // The trailer is at the file's top level: read backwards, an
1477    // `%%EndDocument` opening an embedded document, its `%%BeginDocument`
1478    // closing it.
1479    let tail = window(end.saturating_sub(PS_COMMENT_WINDOW).max(start), end)?;
1480    let mut depth = 0usize;
1481    for line in dsc_lines(&tail).collect::<Vec<_>>().into_iter().rev() {
1482      if line.starts_with(b"%%EndDocument") {
1483        depth += 1;
1484      } else if line.starts_with(b"%%BeginDocument") {
1485        depth = depth.saturating_sub(1);
1486      } else if depth == 0
1487        && let Some(rest) = line.strip_prefix(b"%%BoundingBox:")
1488        && let Some(bbox) = parse_bbox_bytes(rest)
1489      {
1490        boxes.bounding_box = Some(bbox);
1491        break;
1492      }
1493    }
1494  }
1495  Some(boxes)
1496}
1497
1498/// The lines of `bytes`, split at CR or LF, leading blanks trimmed.
1499fn dsc_lines(bytes: &[u8]) -> impl Iterator<Item = &[u8]> {
1500  bytes
1501    .split(|&b| b == b'\n' || b == b'\r')
1502    .map(<[u8]>::trim_ascii_start)
1503}
1504
1505fn parse_bbox_bytes(rest: &[u8]) -> Option<(f64, f64, f64, f64)> {
1506  parse_bbox(std::str::from_utf8(rest.trim_ascii()).ok()?)
1507}
1508
1509/// The size of a JPEG's first frame, `(width, height)` in pixels, from its SOF
1510/// segment (ITU T.81 B.2.2: `FFCn`, length, precision, height, width). The
1511/// segments before it are skipped by their lengths; the entropy-coded data
1512/// after SOS (`FFDA`) is never read.
1513fn read_jpeg_frame_size(file: &mut std::fs::File) -> Option<(u32, u32)> {
1514  use std::io::{BufReader, Read, Seek, SeekFrom};
1515  let mut reader = BufReader::new(file);
1516  reader.seek(SeekFrom::Start(2)).ok()?;
1517  let mut byte = [0u8; 1];
1518  loop {
1519    reader.read_exact(&mut byte).ok()?;
1520    if byte[0] != 0xFF {
1521      return None;
1522    }
1523    // Fill bytes: any number of FF before the marker code.
1524    let marker = loop {
1525      reader.read_exact(&mut byte).ok()?;
1526      if byte[0] != 0xFF {
1527        break byte[0];
1528      }
1529    };
1530    match marker {
1531      // Stand-alone markers carry no length.
1532      0x01 | 0xD0..=0xD7 => continue,
1533      // SOS or EOI before any frame: no size.
1534      0xDA | 0xD9 => return None,
1535      _ => {},
1536    }
1537    let mut length = [0u8; 2];
1538    reader.read_exact(&mut length).ok()?;
1539    let length = i64::from(u16::from_be_bytes(length));
1540    // SOF markers: 0xC0-0xCF (except 0xC4 DHT, 0xC8 JPG, 0xCC DAC)
1541    if (0xC0..=0xCF).contains(&marker) && !matches!(marker, 0xC4 | 0xC8 | 0xCC) {
1542      let mut frame = [0u8; 5];
1543      reader.read_exact(&mut frame).ok()?;
1544      let height = u32::from(u16::from_be_bytes([frame[1], frame[2]]));
1545      let width = u32::from(u16::from_be_bytes([frame[3], frame[4]]));
1546      return Some((width, height));
1547    }
1548    if length < 2 {
1549      return None;
1550    }
1551    reader.seek_relative(length - 2).ok()?;
1552  }
1553}
1554
1555/// Resolve an `image_candidates` entry to a filesystem path, relative to the
1556/// document's `SOURCEDIRECTORY` when the candidate isn't already absolute.
1557fn resolve_candidate(candidate: &str, source_dir: &str) -> PathBuf {
1558  if Path::new(candidate).is_absolute() {
1559    PathBuf::from(candidate)
1560  } else if !source_dir.is_empty() {
1561    PathBuf::from(source_dir).join(candidate)
1562  } else {
1563    PathBuf::from(candidate)
1564  }
1565}
1566
1567/// Natural (unscaled) size of a graphic in TeX points, read the way pdfTeX
1568/// reads it — with no external tool: a PDF's CropBox (default) / MediaBox, or an
1569/// SVG's width/height / viewBox. `None` for formats the raster readers already
1570/// handle, or when the geometry can't be recovered (e.g. a PDF whose page box is
1571/// hidden inside a compressed object stream).
1572fn natural_size_pt(path: &Path) -> Option<(f64, f64)> {
1573  if let Some((w_bp, h_bp)) = read_pdf_page_box(path) {
1574    return Some((bp_to_pt(w_bp), bp_to_pt(h_bp)));
1575  }
1576  read_svg_size_pt(path)
1577}
1578
1579/// bp (PostScript big point, 1/72") → TeX pt (1/72.27").
1580fn bp_to_pt(bp: f64) -> f64 { bp * 72.27 / 72.0 }
1581
1582/// The figure's TRUE natural (typeset) size in TeX pt, for the VECTOR formats
1583/// whose intrinsic size is a real physical dimension: a PDF page box, an EPS/PS
1584/// `%%BoundingBox` (both bp), or an SVG's lengths/viewBox. `None` for raster
1585/// formats — a pixel count is not a physical size without a DPI — and when the
1586/// geometry can't be recovered.
1587///
1588/// For a vector format this is the natural size `image_graphicx_sizer` gives the
1589/// box (since 78z an EPS/PS one too, OXIDIZED_DESIGN_DIVERGENCES #886), read by
1590/// the same reader (`natural_size`, by the file's content); for a raster it is
1591/// `None`, though the sizer's box is its pixels at their density (#1188): the em
1592/// path stays gated to vector figures (FIGURE_MODEL.md batch FRACTION widens it).
1593/// This function is the size a browser should reproduce, used for the
1594/// font-relative (`em`) sizing of natural-size figure inclusions (#562). Pure
1595/// Rust, no external tool.
1596pub fn natural_display_size_pt(path: &Path) -> Option<(f64, f64)> {
1597  match natural_size(path)? {
1598    Natural::Points(w, h) => Some((w, h)),
1599    Natural::Pixels(..) => None,
1600  }
1601}
1602
1603/// [`natural_display_size_pt`] of the candidate the box is sized from: the first
1604/// of a comma-joined `candidates` string (the `<ltx:graphics candidates=…>`
1605/// attribute, resolved against `source_dir`) that any reader sizes
1606/// (`first_natural_size`), `None` when that one is a raster — so a `q.png`
1607/// before a `q.eps` gives no `em` size, as any raster does, rather than the
1608/// eps's size for the png pdflatex prints (review rev78z finding 1).
1609pub fn natural_display_size_pt_of_candidates(
1610  candidates: &str,
1611  source_dir: &str,
1612) -> Option<(f64, f64)> {
1613  match first_natural_size(candidates, source_dir)?.0 {
1614    Natural::Points(w, h) => Some((w, h)),
1615    Natural::Pixels(..) => None,
1616  }
1617}
1618
1619/// pt (f64) → `Dimension` (scaled points).
1620fn pt_to_dim(pt: f64) -> Dimension { Dimension::new((pt * 65536.0).round() as i64) }
1621
1622/// Apply graphicx `width`/`height`/`totalheight`/`scale`/`keepaspectratio` to a
1623/// natural (pt) size, matching pdfTeX/graphics.sty box sizing. Verified against
1624/// `\the\wd` under pdflatex: an explicit `width=` sets the box width outright,
1625/// the natural size only supplying the missing dimension via the aspect ratio.
1626fn graphicx_box_pt(nw: f64, nh: f64, options: &str) -> (Dimension, Dimension) {
1627  // The same algebra as the pixel branch, in pt and without quantization:
1628  // options arrive in bp, and 1bp = 72.27/72 pt. Rounding a typeset box to a
1629  // whole device pixel — which is what the pixel branch's `ceil` amounts to —
1630  // would throw away four digits of a TeX dimension for nothing.
1631  let (bw, bh) = apply_graphicx_ops(
1632    nw,
1633    nh,
1634    &parse_graphicx_options(options),
1635    72.27 / 72.0,
1636    false,
1637  );
1638  (pt_to_dim(bw), pt_to_dim(bh))
1639}
1640
1641/// Read a PDF's page box (width, height) in bp — CropBox (pdfTeX's default),
1642/// else MediaBox. Pure Rust, no external tool (this is what pdfTeX's built-in
1643/// reader does). Shared with `LaTeXML::Post::Graphics`.
1644///
1645/// Looks in the raw bytes first, then inside object streams. `%PDF-1.5` and
1646/// later — everything current pdflatex emits — may put the page tree in a
1647/// `/Type /ObjStm` stream, where the box tokens do not appear as raw bytes at
1648/// all: measured over 14 real PDFs in this repo, 5 were unreadable without this
1649/// second pass, and `ObjStm` presence predicted it exactly.
1650///
1651/// **First box wins**, in file order, as the raw-byte scan has always done. A
1652/// correct answer for page N would mean resolving the page tree through the
1653/// xref stream; for the figures `\includegraphics` pulls in, which are
1654/// single-page, the first box is the page's own (or the `/Pages` node's, which
1655/// it inherits).
1656pub fn read_pdf_page_box(path: &Path) -> Option<(f64, f64)> {
1657  read_pdf_page_box_corners(path).map(|[x0, y0, x1, y1]| ((x1 - x0).abs(), (y1 - y0).abs()))
1658}
1659
1660/// The page box [`read_pdf_page_box`] reads, as its corners `[llx, lly, urx, ury]` in bp —
1661/// what pdfTeX's `\pdfximagebbox` reports for an image (pdftex.web `pdf_ximage_bbox`).
1662pub fn read_pdf_page_box_corners(path: &Path) -> Option<[f64; 4]> {
1663  PDF_PAGE_BOX_MEMO.with(|m| {
1664    if let Some(hit) = m.borrow().get(path) {
1665      return *hit;
1666    }
1667    let value = read_pdf_page_box_uncached(path);
1668    m.borrow_mut().insert(path.to_path_buf(), value);
1669    value
1670  })
1671}
1672
1673fn read_pdf_page_box_uncached(path: &Path) -> Option<[f64; 4]> {
1674  let bytes = read_file_resilient(path)?;
1675  if let Some(box_) =
1676    parse_pdf_box(&bytes, b"/CropBox").or_else(|| parse_pdf_box(&bytes, b"/MediaBox"))
1677  {
1678    return Some(box_);
1679  }
1680  let inflated = inflate_object_streams(&bytes)?;
1681  parse_pdf_box(&inflated, b"/CropBox").or_else(|| parse_pdf_box(&inflated, b"/MediaBox"))
1682}
1683
1684/// The page count of a PDF, as pdfTeX's `\pdflastximagepages` reports it
1685/// after `\pdfximage`: the root `/Type /Pages` node's `/Count`. Without a
1686/// full parser, the root is the `/Pages` dictionary with the LARGEST `/Count`
1687/// (intermediate nodes count only their subtree); raw bytes first, then the
1688/// inflated object streams (PDF 1.5+, see [`read_pdf_page_box`]). A PDF with
1689/// no `/Pages` dictionary at all falls back to counting `/Type /Page` objects.
1690pub fn read_pdf_page_count(path: &Path) -> Option<u32> {
1691  PDF_PAGE_COUNT_MEMO.with(|m| {
1692    if let Some(hit) = m.borrow().get(path) {
1693      return *hit;
1694    }
1695    let value = read_pdf_page_count_uncached(path);
1696    m.borrow_mut().insert(path.to_path_buf(), value);
1697    value
1698  })
1699}
1700
1701std::thread_local! {
1702  static PDF_PAGE_COUNT_MEMO: SizeMemo<u32> =
1703    std::cell::RefCell::new(rustc_hash::FxHashMap::default());
1704}
1705
1706fn read_pdf_page_count_uncached(path: &Path) -> Option<u32> {
1707  let bytes = read_file_resilient(path)?;
1708  if let Some(n) = max_pages_count(&bytes) {
1709    return Some(n);
1710  }
1711  let inflated = inflate_object_streams(&bytes);
1712  if let Some(content) = inflated.as_deref()
1713    && let Some(n) = max_pages_count(content)
1714  {
1715    return Some(n);
1716  }
1717  let pages = count_page_objects(&bytes) + inflated.as_deref().map_or(0, count_page_objects);
1718  if pages > 0 { Some(pages) } else { None }
1719}
1720
1721/// The largest `/Count N` of a `/Type /Pages` dictionary. From each
1722/// `/Type /Pages` (with or without the space) scan forward to the `/Count` at
1723/// the dictionary's own brace depth — a nested `/Resources << … >>` before it
1724/// must not end the search — stopping at the dictionary's closing `>>`.
1725fn max_pages_count(content: &[u8]) -> Option<u32> {
1726  let mut best: Option<u32> = None;
1727  for key in [&b"/Type /Pages"[..], b"/Type/Pages"] {
1728    for at in memchr::memmem::find_iter(content, key) {
1729      let start = at + key.len();
1730      let mut depth = 0i32;
1731      let mut i = start;
1732      while i < content.len() {
1733        let rest = &content[i..];
1734        if rest.starts_with(b"<<") {
1735          depth += 1;
1736          i += 2;
1737          continue;
1738        }
1739        if rest.starts_with(b">>") {
1740          if depth == 0 {
1741            break;
1742          }
1743          depth -= 1;
1744          i += 2;
1745          continue;
1746        }
1747        if depth == 0 && rest.starts_with(b"/Count") {
1748          if let Some(n) = leading_u32(trim_start_pdf_whitespace(&rest[6..])) {
1749            best = Some(best.map_or(n, |b| b.max(n)));
1750          }
1751          break;
1752        }
1753        i += 1;
1754      }
1755    }
1756  }
1757  best
1758}
1759
1760fn count_page_objects(content: &[u8]) -> u32 {
1761  let mut n = 0;
1762  for key in [&b"/Type /Page"[..], b"/Type/Page"] {
1763    for at in memchr::memmem::find_iter(content, key) {
1764      // `/Page` followed by a delimiter, not `/Pages`.
1765      if content.get(at + key.len()) != Some(&b's') {
1766        n += 1;
1767      }
1768    }
1769  }
1770  n
1771}
1772
1773/// PDF's white-space characters: NUL, HT, LF, FF, CR and SP (ISO 32000-1
1774/// §7.2.2, Table 1). They separate an array's numbers; nothing else does — a
1775/// non-ASCII space next to a digit (a UTF-8 NBSP) is not one, where the earlier
1776/// reading of a UTF-8 copy split on any Unicode white space.
1777fn is_pdf_whitespace(b: u8) -> bool { matches!(b, 0 | b'\t' | b'\n' | 0x0c | b'\r' | b' ') }
1778
1779fn trim_start_pdf_whitespace(bytes: &[u8]) -> &[u8] {
1780  let skip = bytes.iter().take_while(|&&b| is_pdf_whitespace(b)).count();
1781  &bytes[skip..]
1782}
1783
1784/// The run of ASCII digits `bytes` opens with, as a `u32`.
1785fn leading_u32(bytes: &[u8]) -> Option<u32> {
1786  let len = bytes.iter().take_while(|b| b.is_ascii_digit()).count();
1787  std::str::from_utf8(&bytes[..len]).ok()?.parse().ok()
1788}
1789
1790/// Concatenate the inflated contents of every `/Type /ObjStm` in `bytes`.
1791///
1792/// Deliberately not a PDF parser: it finds object-stream dictionaries, takes the
1793/// `stream`…`endstream` payload that follows each, and inflates it. That is
1794/// enough to expose the page dictionary, and it stops well short of xref-stream
1795/// parsing and object resolution — which is what a real page-N lookup would
1796/// need, and is not what a figure's natural size is worth.
1797///
1798/// Only `/FlateDecode` streams are attempted (the only filter pdflatex, Ghost-
1799/// script, Cairo or matplotlib use for object streams), and only the first
1800/// [`MAX_OBJSTM_SCAN`] of them, so a pathological file cannot turn a size probe
1801/// into an unbounded decompression.
1802fn inflate_object_streams(bytes: &[u8]) -> Option<Vec<u8>> {
1803  use std::io::Read;
1804
1805  /// Enough for any real document; a figure PDF has one or two.
1806  const MAX_OBJSTM_SCAN: usize = 64;
1807  /// Per-stream inflate ceiling, so a zip bomb cannot be handed to us as a
1808  /// figure. A page dictionary is a few hundred bytes.
1809  const MAX_INFLATED: u64 = 8 << 20;
1810
1811  let mut out = Vec::new();
1812  let mut from = 0;
1813  let mut seen = 0;
1814  while seen < MAX_OBJSTM_SCAN {
1815    let Some(hit) = byte_find(&bytes[from..], b"/ObjStm") else {
1816      break;
1817    };
1818    let at = from + hit;
1819    from = at + b"/ObjStm".len();
1820    seen += 1;
1821    // The dictionary ends at `stream`, optionally followed by CR, then LF.
1822    let Some(rel) = byte_find(&bytes[at..], b"stream") else {
1823      continue;
1824    };
1825    // The stream's dictionary runs from its object header (`N G obj`) to `stream`, its keys in any order: an
1826    // Illustrator PDF writes `/Filter /FlateDecode` before `/Type /ObjStm` (1904.12947's Whitehead.pdf, whose page
1827    // box, page count and natural size were unreadable).
1828    let window = at.saturating_sub(1024);
1829    let dict_start = memchr::memmem::rfind(&bytes[window..at], b"obj").map_or(at, |p| window + p);
1830    let dict = &bytes[dict_start..at + rel];
1831    if byte_find(dict, b"/FlateDecode").is_none() {
1832      continue;
1833    }
1834    let mut start = at + rel + b"stream".len();
1835    if bytes.get(start) == Some(&b'\r') {
1836      start += 1;
1837    }
1838    if bytes.get(start) == Some(&b'\n') {
1839      start += 1;
1840    }
1841    let end = byte_find(&bytes[start..], b"endstream").map_or(bytes.len(), |e| start + e);
1842    let mut buf = Vec::new();
1843    if flate2::read::ZlibDecoder::new(&bytes[start..end])
1844      .take(MAX_INFLATED)
1845      .read_to_end(&mut buf)
1846      .is_err()
1847      && buf.is_empty()
1848    {
1849      // A truncated or mis-delimited stream still yields the bytes decoded
1850      // before the error, and the page dictionary sits at the front — so an
1851      // error is only fatal when nothing at all came out.
1852      continue;
1853    }
1854    out.extend_from_slice(&buf);
1855    out.push(b'\n');
1856  }
1857  (!out.is_empty()).then_some(out)
1858}
1859
1860/// Parse `TOKEN [ llx lly urx ury ]` from PDF content, returning `(w, h)`.
1861///
1862/// The PDF's bytes are searched as they are. The key, the brackets and the
1863/// numbers are ASCII, which a lossy UTF-8 copy keeps in the same order, so the
1864/// same box is found; the separators are PDF's own white space
1865/// ([`is_pdf_whitespace`]). Making that copy of a whole figure PDF cost, in
1866/// release instructions with `--preload=ar5iv.sty`, 18.7 % of arXiv
1867/// 2605.13583's conversion, 14.5 % of 2605.09543's and 8.0 % of 2605.08504's.
1868fn parse_pdf_box(content: &[u8], token: &[u8]) -> Option<[f64; 4]> {
1869  let start = byte_find(content, token)? + token.len();
1870  let rest = &content[start..];
1871  let lb = memchr::memchr(b'[', rest)?;
1872  let rb = memchr::memchr(b']', &rest[lb..])? + lb;
1873  let mut it = rest[lb + 1..rb]
1874    .split(|&b| is_pdf_whitespace(b))
1875    .filter(|s| !s.is_empty())
1876    .filter_map(|s| std::str::from_utf8(s).ok()?.parse::<f64>().ok());
1877  let [x0, y0, x1, y1] = [it.next()?, it.next()?, it.next()?, it.next()?];
1878  // A PDF rectangle may name any two opposite corners (ISO 32000-1 §7.9.5); read as lower left, upper right.
1879  Some([x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)])
1880}
1881
1882/// Byte-level substring search.
1883fn byte_find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
1884  if needle.is_empty() || needle.len() > haystack.len() {
1885    return None;
1886  }
1887  memchr::memmem::find(haystack, needle)
1888}
1889
1890/// Natural SVG size in pt, from the root `<svg>` element: the root
1891/// `width`/`height` lengths (a unitless value is CSS px, exactly as a browser
1892/// treats it), else the `viewBox` extent (user units ≈ CSS px) as a last
1893/// resort. Gives at least a correct aspect ratio, which is all a `width=`-ed
1894/// inclusion needs. `None` if the file isn't an SVG or has no usable geometry.
1895///
1896/// Width/height lead and the viewBox only backstops them — see
1897/// [`read_svg_viewport_px`] for the full rationale (issue #696).
1898fn read_svg_size_pt(path: &Path) -> Option<(f64, f64)> {
1899  let head = read_head_lossy(path)?;
1900  let tag = svg_root_tag(&head)?;
1901  if let Some((w, h)) = svg_root_lengths_px(tag) {
1902    return Some((px_to_pt(w), px_to_pt(h)));
1903  }
1904  let (vw, vh) = svg_viewbox_extent(tag)?;
1905  // viewBox user units ≈ CSS px (1/96"); convert to pt for a plausible scale.
1906  Some((px_to_pt(vw), px_to_pt(vh)))
1907}
1908
1909/// SVG **viewport** size in CSS px, the way a browser takes it: the root
1910/// `width`/`height` (a unitless value is CSS px), falling back to the `viewBox`
1911/// only when the lengths are absent or relative (`%`). `None` when neither is
1912/// usable, so the caller omits the dimensions and lets the browser size it.
1913///
1914/// Basis for `imagewidth`/`imageheight` in `LaTeXML::Post::Graphics`. The
1915/// `viewBox` is only a coordinate system, not the rendered size; preferring it
1916/// under-sized SVGs whose lengths disagreed with it (issue #696, reported by the
1917/// LaTeXML maintainer). Not parity-relevant: Perl parses no SVG — it renders via
1918/// Image::Magick, whose raster follows `width`/`height`, not the `viewBox`
1919/// (`Util/Image.pm:86-97`); `pdftocairo`/`mutool` are our own beyond-Perl
1920/// PDF→SVG pipeline, absent from Perl.
1921pub fn read_svg_viewport_px(path: &Path) -> Option<(u32, u32)> {
1922  svg_viewport_px(&read_head_lossy(path)?)
1923}
1924
1925/// [`read_svg_viewport_px`] of an SVG's text (its head suffices) already in memory.
1926pub fn svg_viewport_px(head: &str) -> Option<(u32, u32)> {
1927  let tag = svg_root_tag(head)?;
1928  let (w, h) = svg_root_lengths_px(tag).or_else(|| svg_viewbox_extent(tag))?;
1929  Some((w.round().max(1.0) as u32, h.round().max(1.0) as u32))
1930}
1931
1932/// The leading bytes of a file, decoded lossily. Bounded: an SVG can be
1933/// hundreds of MB, and every geometry attribute we want lives in the root tag.
1934/// Lossy rather than strict UTF-8 so a latin-1 preamble still yields a
1935/// readable root tag (and so a multi-byte sequence split by the read boundary
1936/// degrades to U+FFFD instead of failing the whole read).
1937fn read_head_lossy(path: &Path) -> Option<String> {
1938  use std::io::Read;
1939  let mut file = std::fs::File::open(path).ok()?;
1940  let mut buf = [0u8; 8192];
1941  let n = file.read(&mut buf).ok()?;
1942  Some(String::from_utf8_lossy(&buf[..n]).into_owned())
1943}
1944
1945/// The root `<svg …>` start tag within `head`, quote-aware so a `>` inside an
1946/// attribute value doesn't end the tag early. Skipping to `<svg` also steps over
1947/// the `<?xml …?>` prolog, comments and any DOCTYPE — otherwise the prolog's
1948/// `?>` would be mistaken for the end of the start tag.
1949pub fn svg_root_tag(head: &str) -> Option<&str> { xml_start_tag(&head[head.find("<svg")?..]) }
1950
1951/// The start tag that `text` begins with, up to (not including) its `>`, quote-aware.
1952pub fn xml_start_tag(text: &str) -> Option<&str> {
1953  let mut quote: Option<char> = None;
1954  for (i, c) in text.char_indices() {
1955    match quote {
1956      Some(q) if c == q => quote = None,
1957      Some(_) => {},
1958      None if c == '"' || c == '\'' => quote = Some(c),
1959      None if c == '>' => return Some(&text[..i]),
1960      None => {},
1961    }
1962  }
1963  None
1964}
1965
1966/// Value of the `name="…"` / `name='…'` attribute in an XML start tag.
1967///
1968/// The attribute **name is matched whole**: a bare substring search reads
1969/// `stroke-width="2"` — legal on a root `<svg>` — as `width`, which is how a
1970/// 634×805 drawing once measured 2×805.
1971pub fn svg_attr_value<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
1972  let mut from = 0;
1973  while let Some(hit) = tag[from..].find(name) {
1974    let at = from + hit;
1975    from = at + name.len();
1976    // Left boundary: the name must start an attribute, not end another one
1977    // (`stroke-width`) — so what precedes it is whitespace, or the `<svg`.
1978    let preceded_ok = tag[..at]
1979      .chars()
1980      .next_back()
1981      .is_some_and(|c| c.is_whitespace());
1982    if !preceded_ok {
1983      continue;
1984    }
1985    // Right boundary: `=` (optionally spaced) then a quoted value.
1986    let after = tag[from..].trim_start();
1987    let Some(after) = after.strip_prefix('=') else {
1988      continue;
1989    };
1990    let after = after.trim_start();
1991    let Some(q) = after.chars().next() else {
1992      continue;
1993    };
1994    if q != '"' && q != '\'' {
1995      continue;
1996    }
1997    let body = &after[q.len_utf8()..];
1998    let end = body.find(q)?;
1999    return Some(&body[..end]);
2000  }
2001  None
2002}
2003
2004/// `(width, height)` extent of the root `viewBox`, in user units (≈ CSS px).
2005/// Per the SVG grammar the four numbers are comma-**and/or**-whitespace
2006/// separated, so `viewBox="0,0,634,805"` must parse like `"0 0 634 805"`.
2007fn svg_viewbox_extent(tag: &str) -> Option<(f64, f64)> {
2008  let vb = svg_attr_value(tag, "viewBox")?;
2009  let mut it = vb
2010    .split(|c: char| c.is_whitespace() || c == ',')
2011    .filter(|s| !s.is_empty());
2012  let (_x, _y) = (it.next()?, it.next()?);
2013  let vw = it.next()?.parse::<f64>().ok()?;
2014  let vh = it.next()?.parse::<f64>().ok()?;
2015  Some((vw, vh))
2016}
2017
2018/// An SVG length attribute in CSS px. A unitless value is user units, i.e. px.
2019/// `None` for anything that isn't an absolute length (`%`, `em`, `ex`, …) —
2020/// those are resolved against a viewport we don't have, so the caller must fall
2021/// back to the viewBox rather than treat the bare number as pixels.
2022pub fn svg_attr_len_px(tag: &str, name: &str) -> Option<f64> {
2023  svg_len_px(svg_attr_value(tag, name)?)
2024}
2025
2026/// The root `<svg>` `width`/`height` as a CSS-px pair — the browser's sizing
2027/// basis. `Some` only when **both** are absolute lengths (a unitless value is
2028/// user units = px, a unit-bearing value is converted); `None` if either is
2029/// missing or relative (`%`, `em`, …), so the caller falls back to the viewBox.
2030fn svg_root_lengths_px(tag: &str) -> Option<(f64, f64)> {
2031  Some((
2032    svg_attr_len_px(tag, "width")?,
2033    svg_attr_len_px(tag, "height")?,
2034  ))
2035}
2036
2037/// Parse an SVG/CSS length into CSS px (1/96"), or `None` if it carries no
2038/// absolute unit. Unitless = user units = px.
2039fn svg_len_px(raw: &str) -> Option<f64> {
2040  let raw = raw.trim();
2041  // Split the number from its unit — but `6.34e2` must not split at the
2042  // exponent's `e`, which would silently read 634 as 6.
2043  let mut split = raw.len();
2044  for (i, c) in raw.char_indices() {
2045    if (c.is_alphabetic() || c == '%') && !is_exponent(&raw[i..]) {
2046      split = i;
2047      break;
2048    }
2049  }
2050  let (num, unit) = raw.split_at(split);
2051  let v = num.trim().parse::<f64>().ok()?;
2052  match unit.trim() {
2053    "" | "px" => Some(v),
2054    "pt" => Some(v * 96.0 / 72.0),
2055    "in" => Some(v * 96.0),
2056    "cm" => Some(v * 96.0 / 2.54),
2057    "mm" => Some(v * 96.0 / 25.4),
2058    "pc" => Some(v * 16.0),
2059    "Q" => Some(v * 96.0 / 101.6),
2060    _ => None, // %, em, ex, rem, vw, … → no absolute length
2061  }
2062}
2063
2064/// Does this trailing fragment start an exponent (`e-3`, `E+10`) rather than a
2065/// unit?
2066fn is_exponent(tail: &str) -> bool {
2067  let mut cs = tail.chars();
2068  matches!(cs.next(), Some('e') | Some('E'))
2069    && cs
2070      .next()
2071      .is_some_and(|c| c.is_ascii_digit() || c == '+' || c == '-')
2072}
2073
2074/// CSS px (1/96") → TeX pt (1/72.27").
2075fn px_to_pt(px: f64) -> f64 { px * 72.27 / 96.0 }
2076
2077#[cfg(test)]
2078mod candidate_order_tests {
2079  use super::*;
2080
2081  /// The base-name retry's hits from one directory, listed by it in either order, come out in one: by type in
2082  /// `\Gin@extensions` order, its uppercase extensions after its lowercase ones (`x.jpg` before `x.PNG`, `x.pdf` before
2083  /// `x.PDF`, pdftex.def:597-600), then `.eps` (appended by epstopdf-base) and the other types, a type of no graphics
2084  /// rule last (0907.3747's `nuebar_limit.ps,nuebar_limit.pdf`).
2085  #[test]
2086  fn retry_hits_are_in_graphics_type_order_whatever_the_directory_order() {
2087    let expected = [
2088      "nuebar.pdf",
2089      "nuebar.jpg",
2090      "nuebar.PDF",
2091      "nuebar.PNG",
2092      "nuebar.eps",
2093      "nuebar.ps",
2094      "nuebar.EPS",
2095      "nuebar.xyz",
2096    ];
2097    for listed in [
2098      [
2099        "nuebar.ps",
2100        "nuebar.xyz",
2101        "nuebar.PDF",
2102        "nuebar.eps",
2103        "nuebar.pdf",
2104        "nuebar.PNG",
2105        "nuebar.jpg",
2106        "nuebar.EPS",
2107      ],
2108      [
2109        "nuebar.PNG",
2110        "nuebar.jpg",
2111        "nuebar.eps",
2112        "nuebar.pdf",
2113        "nuebar.xyz",
2114        "nuebar.PDF",
2115        "nuebar.EPS",
2116        "nuebar.ps",
2117      ],
2118    ] {
2119      let mut candidates: Vec<String> = listed.iter().map(|c| c.to_string()).collect();
2120      in_graphics_type_order(&mut candidates);
2121      assert_eq!(candidates, expected);
2122    }
2123  }
2124
2125  /// An extensionless name's candidates come out in one order whatever order each directory lists its entries in:
2126  /// the same entries of `a/` and `b/` (searched in that order), fed as listed, reversed and rotated within each
2127  /// directory, give one set of lists, each by type, then search directory (det354 4b, review rev78w finding 1: the
2128  /// conversion guard `includegraphics_extensionless_candidates_in_type_order` passes on an ext4 `/tmp` without the
2129  /// sort; witness 2011.14197's `fig3.eps,fig3.pdf`).
2130  #[test]
2131  fn extensionless_candidates_in_one_order_whatever_the_directory_lists() {
2132    let directory = |dir: &str, names: &[&str]| -> Vec<(String, String)> {
2133      names
2134        .iter()
2135        .map(|n| (n.to_string(), format!("{dir}/{n}")))
2136        .collect()
2137    };
2138    let a = [
2139      "fig.eps",
2140      "fig",
2141      "notes.txt",
2142      "fig.PDF",
2143      "fig.pdf",
2144      "Fig.png",
2145      "fig.ps",
2146      "FIG",
2147      "fig.old.pdf",
2148    ];
2149    let b = ["fig.png", "fig.eps", "fig", "fig.pdf"];
2150    let reversed =
2151      |names: &[&'static str]| -> Vec<&'static str> { names.iter().rev().copied().collect() };
2152    let rotated = |names: &[&'static str], by: usize| -> Vec<&'static str> {
2153      let mut names = names.to_vec();
2154      let by = by % names.len();
2155      names.rotate_left(by);
2156      names
2157    };
2158    let expected = ImageCandidateLists {
2159      exact_names:        vec!["a/fig".to_string(), "b/fig".to_string()],
2160      extended_names:     [
2161        "a/fig.pdf",
2162        "b/fig.pdf",
2163        "b/fig.png",
2164        "a/fig.PDF",
2165        "a/fig.eps",
2166        "b/fig.eps",
2167        "a/fig.ps",
2168      ]
2169      .map(String::from)
2170      .to_vec(),
2171      nocase_exact_names: vec!["a/FIG".to_string()],
2172      nocase_candidates:  vec!["a/Fig.png".to_string()],
2173    };
2174    let listings: Vec<(Vec<&str>, Vec<&str>)> = vec![
2175      (a.to_vec(), b.to_vec()),
2176      (reversed(&a), reversed(&b)),
2177      (rotated(&a, 3), rotated(&b, 1)),
2178      (rotated(&a, 7), rotated(&b, 2)),
2179    ];
2180    for (listed_a, listed_b) in listings {
2181      let found = directory("a", &listed_a)
2182        .into_iter()
2183        .chain(directory("b", &listed_b));
2184      assert_eq!(
2185        image_candidate_lists(found, "fig"),
2186        expected,
2187        "a/ listed {listed_a:?}, b/ listed {listed_b:?}"
2188      );
2189    }
2190  }
2191
2192  /// Hits of one type in several search directories keep the directories' search order (the order the search
2193  /// listed them), not their names' (`\graphicspath{{new/}{figs/}}`: `new/plot.pdf` first, as pdftex reads it; review
2194  /// rev78v2 finding 2); a better type in a later directory still comes first.
2195  #[test]
2196  fn retry_hits_of_one_type_keep_the_search_directory_order() {
2197    for (listed, expected) in [
2198      (["new/plot.eps", "new/plot.pdf", "figs/plot.pdf"], [
2199        "new/plot.pdf",
2200        "figs/plot.pdf",
2201        "new/plot.eps",
2202      ]),
2203      (["figs/plot.pdf", "new/plot.eps", "new/plot.pdf"], [
2204        "figs/plot.pdf",
2205        "new/plot.pdf",
2206        "new/plot.eps",
2207      ]),
2208      (["b/nuebar.ps", "a/nuebar.eps", "b/nuebar.eps"], [
2209        "b/nuebar.eps",
2210        "a/nuebar.eps",
2211        "b/nuebar.ps",
2212      ]),
2213    ] {
2214      let mut candidates: Vec<String> = listed.iter().map(|c| c.to_string()).collect();
2215      in_graphics_type_order(&mut candidates);
2216      assert_eq!(candidates, expected);
2217    }
2218  }
2219}
2220
2221#[cfg(test)]
2222mod svg_geometry_tests {
2223  use super::*;
2224
2225  /// Write `content` to a uniquely-named temp `.svg` and hand back the path.
2226  fn svg_file(name: &str, content: &str) -> PathBuf {
2227    let path = std::env::temp_dir().join(format!("lximg-{}-{name}.svg", std::process::id()));
2228    std::fs::write(&path, content).expect("write svg fixture");
2229    path
2230  }
2231
2232  #[test]
2233  fn root_tag_skips_the_prolog_and_stops_at_the_real_tag_end() {
2234    let head = "<?xml version=\"1.0\"?>\n<!-- a > in a comment -->\n<svg width=\"3\">\n<rect/>";
2235    assert_eq!(svg_root_tag(head), Some("<svg width=\"3\""));
2236    // A `>` inside an attribute value must not end the start tag.
2237    let quoted = r#"<svg desc="a > b" width="3"><rect/>"#;
2238    assert_eq!(svg_root_tag(quoted), Some(r#"<svg desc="a > b" width="3""#));
2239    assert_eq!(svg_root_tag("no svg here"), None);
2240  }
2241
2242  /// A bare substring search reads `stroke-width` as `width`. Both attribute
2243  /// orders, since the bug only bites when the decoy comes first.
2244  #[test]
2245  fn attr_value_matches_whole_names_not_substrings() {
2246    let decoy_first = r#"<svg stroke-width="2" width="634" height="805""#;
2247    assert_eq!(svg_attr_value(decoy_first, "width"), Some("634"));
2248    assert_eq!(svg_attr_value(decoy_first, "stroke-width"), Some("2"));
2249    let decoy_last = r#"<svg width="634" stroke-width="2""#;
2250    assert_eq!(svg_attr_value(decoy_last, "width"), Some("634"));
2251    // A name that appears only as a suffix of another attribute is absent.
2252    assert_eq!(svg_attr_value(r#"<svg stroke-width="2""#, "width"), None);
2253  }
2254
2255  #[test]
2256  fn attr_value_reads_both_quote_styles() {
2257    let single = r#"<svg xmlns='http://www.w3.org/2000/svg' width='634' height='805'"#;
2258    assert_eq!(svg_attr_value(single, "width"), Some("634"));
2259    assert_eq!(svg_attr_value(single, "height"), Some("805"));
2260    // Spaces around `=` are legal XML.
2261    assert_eq!(
2262      svg_attr_value(r#"<svg width = "634""#, "width"),
2263      Some("634")
2264    );
2265  }
2266
2267  /// The unit table, in CSS px (1in = 96px). Every absolute unit SVG allows,
2268  /// plus the three shapes that must NOT be read as a pixel count.
2269  #[test]
2270  fn len_px_converts_absolute_units_and_rejects_relative_ones() {
2271    let cases: &[(&str, Option<f64>)] = &[
2272      ("634", Some(634.0)), // unitless = user units = px
2273      ("634px", Some(634.0)),
2274      ("10cm", Some(377.952_755_905_511_8)),
2275      ("7.5cm", Some(283.464_566_929_133_84)),
2276      ("100mm", Some(377.952_755_905_511_8)),
2277      ("4in", Some(384.0)),
2278      ("72pt", Some(96.0)),
2279      ("6pc", Some(96.0)),
2280      ("6.34e2", Some(634.0)), // exponent, not a `e` unit
2281      ("-5", Some(-5.0)),
2282      ("100%", None), // resolved against a viewport we don't have
2283      ("2em", None),
2284      ("50vw", None),
2285      ("", None),
2286      ("wide", None),
2287    ];
2288    for (raw, want) in cases {
2289      match (svg_len_px(raw), want) {
2290        (Some(got), Some(w)) => assert!(
2291          (got - w).abs() < 1e-9,
2292          "svg_len_px({raw:?}) = {got}, want {w}"
2293        ),
2294        (got, want) => assert_eq!(
2295          got.is_none(),
2296          want.is_none(),
2297          "svg_len_px({raw:?}) = {got:?}"
2298        ),
2299      }
2300    }
2301  }
2302
2303  /// The viewport reader sizes the way a browser does: the root `width`/`height`
2304  /// lead, the `viewBox` only backstops them (issue #696). `pdftocairo -svg`
2305  /// writes `width="612pt"`, which a browser renders at 612·96/72 = 816 px — not
2306  /// the viewBox's 612. `mutool draw -F svg` writes a unitless `612`, i.e. 612
2307  /// px, matching its viewBox. Root tags copied verbatim from the tools.
2308  #[test]
2309  fn viewport_px_sizes_from_root_lengths_like_a_browser() {
2310    let pdftocairo = svg_file(
2311      "pdftocairo",
2312      r#"<?xml version="1.0" encoding="UTF-8"?>
2313<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="612pt" height="792pt" viewBox="0 0 612 792">
2314<defs/></svg>"#,
2315    );
2316    assert_eq!(read_svg_viewport_px(&pdftocairo), Some((816, 1056)));
2317    let mutool = svg_file(
2318      "mutool",
2319      r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" width="612" height="792" viewBox="0 0 612 792">
2320<defs/></svg>"#,
2321    );
2322    assert_eq!(read_svg_viewport_px(&mutool), Some((612, 792)));
2323    let _ = std::fs::remove_file(pdftocairo);
2324    let _ = std::fs::remove_file(mutool);
2325  }
2326
2327  /// The `viewBox` is only a fallback now: it sizes the viewport iff the root
2328  /// carries no absolute `width`/`height`. When both are present the lengths win
2329  /// (that is the whole of issue #696), so a viewBox that disagrees with them is
2330  /// ignored for sizing.
2331  #[test]
2332  fn viewport_px_uses_the_viewbox_only_when_lengths_are_absent() {
2333    let vb_only = svg_file(
2334      "vb_only",
2335      r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 480"><rect/></svg>"#,
2336    );
2337    assert_eq!(read_svg_viewport_px(&vb_only), Some((640, 480)));
2338    // Lengths present and disagreeing with the viewBox → lengths win.
2339    let both = svg_file(
2340      "vb_both",
2341      r#"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100" viewBox="0 0 640 480"><rect/></svg>"#,
2342    );
2343    assert_eq!(read_svg_viewport_px(&both), Some((200, 100)));
2344    // A percentage width is not absolute → fall through to the viewBox.
2345    let pct_w = svg_file(
2346      "vb_pct",
2347      r#"<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 640 480"><rect/></svg>"#,
2348    );
2349    assert_eq!(read_svg_viewport_px(&pct_w), Some((640, 480)));
2350    for p in [vb_only, both, pct_w] {
2351      let _ = std::fs::remove_file(p);
2352    }
2353  }
2354
2355  /// Without a viewBox the root lengths are the viewport — and they must be
2356  /// *converted*, not truncated. Reading `10cm` as 10 px is how a poster-sized
2357  /// drawing became a 10-pixel thumbnail (issue 498 follow-up).
2358  #[test]
2359  fn viewport_px_converts_unit_bearing_lengths_when_there_is_no_viewbox() {
2360    let cm = svg_file(
2361      "cm",
2362      r#"<svg xmlns="http://www.w3.org/2000/svg" width="10cm" height="7.5cm"><rect/></svg>"#,
2363    );
2364    assert_eq!(read_svg_viewport_px(&cm), Some((378, 283)));
2365    let inch = svg_file("in", r#"<svg width="4in" height="2in"><rect/></svg>"#);
2366    assert_eq!(read_svg_viewport_px(&inch), Some((384, 192)));
2367    let quoted = svg_file(
2368      "sq",
2369      r#"<svg xmlns='http://www.w3.org/2000/svg' width='634' height='805'><rect/></svg>"#,
2370    );
2371    assert_eq!(read_svg_viewport_px(&quoted), Some((634, 805)));
2372    let decoy = svg_file(
2373      "decoy",
2374      r#"<svg xmlns="http://www.w3.org/2000/svg" stroke-width="2" width="634" height="805"><rect/></svg>"#,
2375    );
2376    assert_eq!(read_svg_viewport_px(&decoy), Some((634, 805)));
2377    for p in [cm, inch, quoted, decoy] {
2378      let _ = std::fs::remove_file(p);
2379    }
2380  }
2381
2382  /// A percentage-sized root with no viewBox has no intrinsic pixel size at
2383  /// all. `None` is the whole point: the caller then emits no width/height and
2384  /// the browser sizes the image itself, which is strictly better than
2385  /// asserting `width="100"`.
2386  #[test]
2387  fn viewport_px_declines_relative_lengths_rather_than_inventing_pixels() {
2388    let pct = svg_file("pct", r#"<svg width="100%" height="100%"><rect/></svg>"#);
2389    assert_eq!(read_svg_viewport_px(&pct), None);
2390    let none = svg_file(
2391      "bare",
2392      r#"<svg xmlns="http://www.w3.org/2000/svg"><rect/></svg>"#,
2393    );
2394    assert_eq!(read_svg_viewport_px(&none), None);
2395    for p in [pct, none] {
2396      let _ = std::fs::remove_file(p);
2397    }
2398  }
2399
2400  /// The SVG grammar allows comma-separated viewBox numbers.
2401  #[test]
2402  fn viewport_px_parses_a_comma_separated_viewbox() {
2403    let comma = svg_file("comma", r#"<svg viewBox="0,0,634,805"><rect/></svg>"#);
2404    assert_eq!(read_svg_viewport_px(&comma), Some((634, 805)));
2405    let _ = std::fs::remove_file(comma);
2406  }
2407
2408  /// `read_svg_size_pt` shares the viewport reader's precedence — root lengths
2409  /// first, viewBox second — differing only in that it answers "how big would
2410  /// this typeset (pt)?" rather than "how many px is the viewport?". SVG `pt` is
2411  /// a PostScript big point (1/72"), and a unitless length is CSS px.
2412  #[test]
2413  fn size_pt_prefers_absolute_lengths_then_falls_back_to_the_viewbox() {
2414    // 4in = 288.something TeX pt (72.27/in).
2415    let inch = svg_file(
2416      "pt_in",
2417      r#"<svg width="4in" height="2in" viewBox="0 0 10 5"><rect/></svg>"#,
2418    );
2419    let (w, h) = read_svg_size_pt(&inch).expect("absolute lengths");
2420    assert!((w - 4.0 * 72.27).abs() < 1e-9, "w = {w}");
2421    assert!((h - 2.0 * 72.27).abs() < 1e-9, "h = {h}");
2422    // SVG `pt` is a PostScript big point (1/72"), NOT a TeX pt (1/72.27") — so
2423    // `72pt` is one inch, i.e. 72.27 TeX pt. The old reader equated the two
2424    // units and under-reported every pt-sized SVG by 0.375%.
2425    let bigpt = svg_file("pt_pt", r#"<svg width="72pt" height="36pt"><rect/></svg>"#);
2426    let (w, h) = read_svg_size_pt(&bigpt).expect("pt lengths");
2427    assert!((w - 72.27).abs() < 1e-9, "w = {w}");
2428    assert!((h - 72.27 / 2.0).abs() < 1e-9, "h = {h}");
2429    let _ = std::fs::remove_file(bigpt);
2430    // Unitless lengths are CSS px, and they WIN over a disagreeing viewBox
2431    // (issue #696): 96 px → 72.27 pt, 48 px → 36.135 pt, not the viewBox's 634.
2432    let unitless = svg_file(
2433      "pt_len",
2434      r#"<svg width="96" height="48" viewBox="0 0 634 805"><rect/></svg>"#,
2435    );
2436    let (w, h) = read_svg_size_pt(&unitless).expect("root lengths");
2437    assert!((w - 72.27).abs() < 1e-9, "w = {w}");
2438    assert!((h - 72.27 / 2.0).abs() < 1e-9, "h = {h}");
2439    // Only a root without absolute lengths falls back to the viewBox.
2440    let vb_only = svg_file("pt_vb", r#"<svg viewBox="0 0 96 48"><rect/></svg>"#);
2441    let (w, h) = read_svg_size_pt(&vb_only).expect("viewBox fallback");
2442    assert!((w - 72.27).abs() < 1e-9, "w = {w}");
2443    assert!((h - 72.27 / 2.0).abs() < 1e-9, "h = {h}");
2444    for p in [inch, unitless, vb_only] {
2445      let _ = std::fs::remove_file(p);
2446    }
2447  }
2448}
2449
2450/// Characterization tests for the engine-side image sizing pipeline.
2451///
2452/// **These pin behaviour, not correctness.** Several of the numbers below are
2453/// known to disagree with pdflatex — a PNG is assumed to be 100 dpi (Perl's
2454/// rule, DIVERGENCES #337), an SVG 96 dpi, and a raster box is quantized to whole
2455/// device pixels. An EPS BoundingBox was read as pixels too until 78z; it is bp
2456/// now, as TeX reads it (DIVERGENCES #886). They are recorded exactly as they are today so that the
2457/// planned unification of the sizing pipeline (one probe, one resolution
2458/// policy, one graphicx algebra) has to declare every change it makes instead
2459/// of drifting silently. When a value here changes, that is a decision, and the
2460/// comment above it says which way the current number leans.
2461///
2462/// Measured references, same 200x100 figure in each format, `\the\wd0` with no
2463/// graphicx options, recorded 2026-08-04:
2464///
2465/// | source              | pdflatex   | Perl LaTeXML | here       |
2466/// |---------------------|------------|--------------|------------|
2467/// | PNG 200x100 px      | 200.7495pt | 144.54pt     | 144.54pt   |
2468/// | EPS BBox 200x100 bp | 200.7495pt | (no sizer)   | 200.75pt   |
2469/// | PDF 200x100 bp      | 200.7495pt | (no sizer)   | 200.75pt   |
2470/// | SVG viewBox 200x100 | -          | (no sizer)   | 150.5625pt |
2471#[cfg(test)]
2472mod sizing_characterization_tests {
2473  use super::*;
2474
2475  /// A fixture file in the temp directory, removed when dropped: each one used to stay behind, thousands of
2476  /// `lxsize-*` files per run of the suite.
2477  struct Fixture(PathBuf);
2478
2479  impl std::ops::Deref for Fixture {
2480    type Target = Path;
2481
2482    fn deref(&self) -> &Path { &self.0 }
2483  }
2484
2485  impl Drop for Fixture {
2486    fn drop(&mut self) { let _ = std::fs::remove_file(&self.0); }
2487  }
2488
2489  fn fixture(name: &str, bytes: &[u8]) -> Fixture {
2490    // A per-call sequence makes every fixture path unique. Two tests reused the
2491    // same `name` ("m.pdf"), so keying only on pid+name let them race on one temp
2492    // file when run in parallel: whichever wrote last won, and the other test's
2493    // reader saw the wrong bytes -> a flaky `None` under full-suite load (it only
2494    // surfaced when scheduling made the two writes overlap).
2495    use std::sync::atomic::{AtomicU64, Ordering};
2496    static SEQ: AtomicU64 = AtomicU64::new(0);
2497    let seq = SEQ.fetch_add(1, Ordering::Relaxed);
2498    let path = std::env::temp_dir().join(format!("lxsize-{}-{seq}-{name}", std::process::id()));
2499    std::fs::write(&path, bytes).expect("write fixture");
2500    Fixture(path)
2501  }
2502
2503  fn io_err(kind: std::io::ErrorKind) -> std::io::Error { std::io::Error::from(kind) }
2504
2505  /// A genuine `NotFound` is a missing file, not a lock: it must map straight to
2506  /// `None` on the first attempt, with no retry and no sleep. The "no sleep"
2507  /// half is what keeps `read_pdf_page_box`/`read_image_dimensions` cheap for
2508  /// the common missing-figure case, so the perf argument depends on it.
2509  #[test]
2510  fn transient_retry_notfound_is_immediate_none() {
2511    let mut calls = 0u32;
2512    let got: Option<()> = with_transient_retry(|| {
2513      calls += 1;
2514      Err(io_err(std::io::ErrorKind::NotFound))
2515    });
2516    assert!(got.is_none(), "NotFound must map to None");
2517    assert_eq!(calls, 1, "NotFound must not be retried");
2518  }
2519
2520  /// A lock that clears after a couple of tries: the op is retried and its
2521  /// eventual `Ok` is returned — a fresh figure is not silently dropped to 0x0.
2522  #[test]
2523  fn transient_retry_recovers_after_transient_errors() {
2524    let mut calls = 0u32;
2525    let got = with_transient_retry(|| {
2526      calls += 1;
2527      if calls < 3 {
2528        Err(io_err(std::io::ErrorKind::PermissionDenied))
2529      } else {
2530        Ok(42u32)
2531      }
2532    });
2533    assert_eq!(
2534      got,
2535      Some(42),
2536      "a clearing lock should be retried then succeed"
2537    );
2538    assert_eq!(calls, 3, "should retry until the op succeeds");
2539  }
2540
2541  /// A persistent non-`NotFound` error gives up with `None` after the retry cap
2542  /// (1 initial attempt + 10 retries = 11 invocations) instead of looping.
2543  #[test]
2544  fn transient_retry_gives_up_after_cap() {
2545    let mut calls = 0u32;
2546    let got: Option<()> = with_transient_retry(|| {
2547      calls += 1;
2548      Err(io_err(std::io::ErrorKind::PermissionDenied))
2549    });
2550    assert!(got.is_none(), "a persistent error must give up with None");
2551    assert_eq!(calls, 11, "one attempt then retries up to the cap");
2552  }
2553
2554  /// A minimal `%PDF-1.5` whose only object is a Flate-compressed object stream
2555  /// carrying `payload` — the shape pdflatex emits for a page tree since 1.5.
2556  fn objstm_pdf(payload: &[u8]) -> Vec<u8> {
2557    use std::io::Write;
2558    let mut enc = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
2559    enc.write_all(payload).expect("deflate");
2560    let body = enc.finish().expect("finish");
2561    let mut pdf = Vec::from(
2562      &b"%PDF-1.5\n1 0 obj\n<< /Type /ObjStm /N 1 /First 4 /Filter /FlateDecode >>\nstream\n"[..],
2563    );
2564    pdf.extend_from_slice(&body);
2565    pdf.extend_from_slice(b"\nendstream\nendobj\n");
2566    pdf
2567  }
2568
2569  /// A PNG header with the given IHDR dimensions. `read_image_dimensions` reads
2570  /// a fixed 32-byte prefix and takes bytes 16..24 as width/height, so an
2571  /// honest signature + IHDR is the whole contract; no CRC is consulted.
2572  fn png_header(w: u32, h: u32) -> Vec<u8> {
2573    let mut v = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
2574    v.extend_from_slice(&13u32.to_be_bytes());
2575    v.extend_from_slice(b"IHDR");
2576    v.extend_from_slice(&w.to_be_bytes());
2577    v.extend_from_slice(&h.to_be_bytes());
2578    v.extend_from_slice(&[0x08, 0x02, 0x00, 0x00, 0x00]);
2579    v.extend_from_slice(&[0u8; 16]); // pad past the 32-byte read_exact
2580    v
2581  }
2582
2583  /// A JPEG with a single SOF0 frame header. The reader scans markers for
2584  /// 0xC0..=0xCF (minus DHT/JPG/DAC) and takes height then width, big-endian.
2585  fn jpeg_header(w: u16, h: u16) -> Vec<u8> {
2586    let mut v = vec![0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x11, 0x08];
2587    v.extend_from_slice(&h.to_be_bytes());
2588    v.extend_from_slice(&w.to_be_bytes());
2589    v.extend_from_slice(&[0x03, 0x01, 0x22, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01]);
2590    v.extend_from_slice(&[0xFF, 0xD9]);
2591    v.extend_from_slice(&[0u8; 16]);
2592    v
2593  }
2594
2595  // ── layer 1: what each format probe returns, and in which unit ────────
2596
2597  /// The DSC comments are read as bytes, in CR/LF lines, in a head window and,
2598  /// for `(atend)`, a tail window; a DOS EPS header is followed to its
2599  /// PostScript section. Each shape lost its box before (strict UTF-8 over the
2600  /// whole window, `str::lines`, no tail, no seek past the first 32 KB).
2601  #[test]
2602  fn postscript_boxes_are_read_as_bytes() {
2603    let bbox = Some((0.0, 0.0, 144.0, 72.0));
2604    let latin1 = fixture(
2605      "latin1.eps",
2606      b"%!PS-Adobe-3.0 EPSF-3.0\n%%Title: caf\xe9\n%%BoundingBox: 0 0 144 72\n%%EndComments\n",
2607    );
2608    assert_eq!(
2609      read_postscript_boxes(&latin1).unwrap().bounding_box,
2610      bbox,
2611      "Latin-1 title"
2612    );
2613    assert_eq!(
2614      read_image_dimensions(&latin1),
2615      Some((144, 72)),
2616      "Latin-1 title"
2617    );
2618
2619    let cr = fixture(
2620      "cr.eps",
2621      b"%!PS-Adobe-3.0 EPSF-3.0\r%%BoundingBox: 0 0 144 72\r%%EndComments\r",
2622    );
2623    assert_eq!(read_image_dimensions(&cr), Some((144, 72)), "CR line ends");
2624
2625    // The trailer lies past the head window; an embedded document's box before
2626    // it does not count (the trailer's, the last, wins).
2627    let mut atend = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: (atend)\n%%EndComments\n".to_vec();
2628    atend
2629      .extend_from_slice(b"%%BeginDocument: inner.eps\n%%BoundingBox: 0 0 10 10\n%%EndDocument\n");
2630    atend.extend(std::iter::repeat_n(b"% filler\n".as_slice(), 5000).flatten());
2631    atend.extend_from_slice(b"%%Trailer\n%%BoundingBox: 0 0 144 72\n%%EOF\n");
2632    let atend = fixture("atend.eps", &atend);
2633    assert_eq!(
2634      read_postscript_boxes(&atend).unwrap().bounding_box,
2635      bbox,
2636      "(atend) trailer"
2637    );
2638
2639    // Within one window: the trailer's box is the last at the top level; the
2640    // embedded document's own trailer, earlier in the tail, does not count.
2641    let two_trailers = fixture(
2642      "two_trailers.eps",
2643      b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: (atend)\n%%EndComments\n\
2644        %%BeginDocument: inner.eps\n%%BoundingBox: (atend)\n%%Trailer\n%%BoundingBox: 0 0 10 10\n\
2645        %%EndDocument\n%%Trailer\n%%BoundingBox: 0 0 144 72\n%%EOF\n",
2646    );
2647    assert_eq!(
2648      read_postscript_boxes(&two_trailers).unwrap().bounding_box,
2649      bbox,
2650      "outer trailer"
2651    );
2652
2653    // The first box decides: an embedded document's `(atend)` or HiRes box is its
2654    // own (graphics.sty `\Gread@eps`, epstopdf keep the first real box).
2655    let embedded = fixture(
2656      "embedded.eps",
2657      b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 144 72\n%%EndComments\n\
2658        %%BeginDocument: inner.eps\n%%BoundingBox: (atend)\n%%HiResBoundingBox: 0 0 10 10\n\
2659        %%Trailer\n%%BoundingBox: 0 0 10 10\n%%EndDocument\n",
2660    );
2661    let bad_first = fixture(
2662      "bad_first.eps",
2663      b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: none\n%%BoundingBox: 0 0 144 72\n",
2664    );
2665    assert_eq!(
2666      read_postscript_boxes(&bad_first).unwrap().bounding_box,
2667      bbox,
2668      "unreadable first"
2669    );
2670    let boxes = read_postscript_boxes(&embedded).unwrap();
2671    assert_eq!(
2672      (boxes.bounding_box, boxes.hires_bounding_box),
2673      (bbox, None),
2674      "embedded"
2675    );
2676    assert_eq!(
2677      read_image_dimensions(&embedded),
2678      Some((144, 72)),
2679      "embedded"
2680    );
2681
2682    // A DOS EPS whose preview comes first, putting the PostScript past 32 KB.
2683    let ps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 144 72\n%%EndComments\n";
2684    let preview = vec![0xFFu8; 40_000];
2685    let ps_offset = 30 + preview.len() as u32;
2686    let mut dos = b"\xc5\xd0\xd3\xc6".to_vec();
2687    for field in [ps_offset, ps.len() as u32, 0, 0, 30, preview.len() as u32] {
2688      dos.extend_from_slice(&field.to_le_bytes());
2689    }
2690    dos.extend_from_slice(&[0xFF, 0xFF]);
2691    dos.extend_from_slice(&preview);
2692    dos.extend_from_slice(ps);
2693    let dos = fixture("dos.eps", &dos);
2694    assert_eq!(
2695      read_image_dimensions(&dos),
2696      Some((144, 72)),
2697      "DOS EPS header"
2698    );
2699  }
2700
2701  /// The JPEG reader seeks from segment to segment to the frame header, past
2702  /// application segments and fill bytes, and never reads the scan data.
2703  #[test]
2704  fn jpeg_frame_size_skips_segments() {
2705    let mut jpg = vec![0xFF, 0xD8];
2706    // APP1 of 60,000 bytes (an Exif thumbnail), then a fill byte before SOF2.
2707    jpg.extend_from_slice(&[0xFF, 0xE1]);
2708    jpg.extend_from_slice(&60_000u16.to_be_bytes());
2709    jpg.extend(std::iter::repeat_n(0u8, 60_000 - 2));
2710    jpg.extend_from_slice(&[0xFF, 0xFF, 0xC2, 0x00, 0x11, 0x08]);
2711    jpg.extend_from_slice(&480u16.to_be_bytes());
2712    jpg.extend_from_slice(&640u16.to_be_bytes());
2713    jpg.extend_from_slice(&[
2714      0x03, 0x01, 0x22, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xFF, 0xD9,
2715    ]);
2716    assert_eq!(
2717      read_image_dimensions(&fixture("app1.jpg", &jpg)),
2718      Some((640, 480))
2719    );
2720    // Scan data before any frame: no size.
2721    let no_frame = [0xFF, 0xD8, 0xFF, 0xDA, 0x00, 0x02, 0x12, 0x34, 0xFF, 0xD9];
2722    let mut no_frame = no_frame.to_vec();
2723    no_frame.extend_from_slice(&[0u8; 32]);
2724    assert_eq!(
2725      read_image_dimensions(&fixture("noframe.jpg", &no_frame)),
2726      None
2727    );
2728  }
2729
2730  /// PNG and JPEG report true device pixels; EPS reports **bp** through the
2731  /// same `(u32, u32)` channel. `read_image_size` tells them apart
2732  /// (`ImageSize::Pixels` / `ImageSize::PostScriptBp`, 78z), which is what the
2733  /// digestion-time sizer reads; this projection is pinned so its callers'
2734  /// numbers stay visible.
2735  #[test]
2736  fn read_image_dimensions_returns_pixels_for_raster_and_bp_for_eps() {
2737    let png = fixture("dims.png", &png_header(200, 100));
2738    assert_eq!(read_image_dimensions(&png), Some((200, 100)), "PNG IHDR px");
2739
2740    let jpg = fixture("dims.jpg", &jpeg_header(640, 480));
2741    assert_eq!(read_image_dimensions(&jpg), Some((640, 480)), "JPEG SOF px");
2742
2743    // 200 x 100 **bp**, handed back as if it were 200 x 100 pixels.
2744    let eps = fixture(
2745      "dims.eps",
2746      b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 200 100\n%%EndComments\n",
2747    );
2748    assert_eq!(
2749      read_image_dimensions(&eps),
2750      Some((200, 100)),
2751      "EPS bp-as-px"
2752    );
2753
2754    // The BoundingBox decides when both are present, as graphics.sty's `\Gread@eps` and epstopdf read it (latex and
2755    // pdflatex 200.75pt x 100.375pt); until 78z the HiResBoundingBox won, rounded, (200, 99).
2756    let hires = fixture(
2757      "hires.eps",
2758      b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 200 100\n\
2759        %%HiResBoundingBox: 0 0 199.5 99.4\n%%EndComments\n",
2760    );
2761    assert_eq!(
2762      read_image_dimensions(&hires),
2763      Some((200, 100)),
2764      "the BoundingBox wins"
2765    );
2766    assert_eq!(
2767      read_image_size(&hires),
2768      Some(ImageSize::PostScriptBp(200.0, 100.0))
2769    );
2770    // Only without a BoundingBox does the HiResBoundingBox size the file, unrounded.
2771    let hires_only = fixture(
2772      "hires_only.eps",
2773      b"%!PS-Adobe-3.0 EPSF-3.0\n%%HiResBoundingBox: 0 0 199.5 99.4\n%%EndComments\n",
2774    );
2775    assert_eq!(
2776      read_image_size(&hires_only),
2777      Some(ImageSize::PostScriptBp(199.5, 99.4))
2778    );
2779
2780    // Formats this reader does not know stay `None` — that is what routes a
2781    // PDF or an SVG to the `natural_size_pt` fallback.
2782    let pdf = fixture(
2783      "dims1.pdf",
2784      b"%PDF-1.4\n1 0 obj\n<< /MediaBox [0 0 200 100] >>\nendobj\n",
2785    );
2786    assert_eq!(
2787      read_image_dimensions(&pdf),
2788      None,
2789      "PDF is not this reader's job"
2790    );
2791  }
2792
2793  /// The PDF page box: CropBox is pdfTeX's default and wins over MediaBox, and
2794  /// a box compressed into an object stream is inflated and read.
2795  ///
2796  /// That last case is not hypothetical. Across 14 real PDFs in this repo, 5
2797  /// returned `None` before the object-stream pass, correlating exactly with
2798  /// `ObjStm` — the default for `%PDF-1.5` and later, which is what modern
2799  /// pdflatex emits — and those figures reached the engine with a 0x0 natural
2800  /// box. All 14 now match `pdfinfo` exactly.
2801  #[test]
2802  fn read_pdf_page_box_prefers_cropbox_and_reaches_into_object_streams() {
2803    let media = fixture("m.pdf", b"%PDF-1.4\n<< /MediaBox [0 0 200 100] >>\n");
2804    assert_eq!(read_pdf_page_box(&media), Some((200.0, 100.0)));
2805
2806    let both = fixture(
2807      "b.pdf",
2808      b"%PDF-1.4\n<< /MediaBox [0 0 612 792] /CropBox [0 0 200 100] >>\n",
2809    );
2810    assert_eq!(
2811      read_pdf_page_box(&both),
2812      Some((200.0, 100.0)),
2813      "CropBox wins"
2814    );
2815
2816    // Non-zero origin: the box is the extent, not the corner.
2817    let offset = fixture("o.pdf", b"%PDF-1.4\n<< /MediaBox [10 20 210 120] >>\n");
2818    assert_eq!(read_pdf_page_box(&offset), Some((200.0, 100.0)));
2819    // Opposite corners in either order name the same rectangle: `\pdfximagebbox` reports lower left, upper right.
2820    let flipped = fixture("f.pdf", b"%PDF-1.4\n<< /MediaBox [210 120 10 20] >>\n");
2821    assert_eq!(
2822      read_pdf_page_box_corners(&flipped),
2823      Some([10.0, 20.0, 210.0, 120.0])
2824    );
2825
2826    // A real object stream: the box exists only as deflated bytes.
2827    let objstm = fixture(
2828      "h.pdf",
2829      &objstm_pdf(b"5 0 << /Type /Page /MediaBox [0 0 200 100] >>"),
2830    );
2831    assert_eq!(read_pdf_page_box(&objstm), Some((200.0, 100.0)));
2832
2833    // A CropBox inside the stream still wins over a MediaBox beside it.
2834    let cropped = fixture(
2835      "hc.pdf",
2836      &objstm_pdf(b"5 0 << /MediaBox [0 0 612 792] /CropBox [0 0 200 100] >>"),
2837    );
2838    assert_eq!(read_pdf_page_box(&cropped), Some((200.0, 100.0)));
2839
2840    // The stream dictionary's keys in another order (`/Filter` before `/Type`, as Illustrator writes them).
2841    let filter_first = {
2842      use std::io::Write;
2843      let mut enc = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
2844      enc
2845        .write_all(b"13 0 <</CropBox[0.0 0.0 108.056 52.537]/Type/Page>>")
2846        .expect("deflate");
2847      let mut pdf = Vec::from(
2848        &b"%PDF-1.6\r82 0 obj\r<</Filter/FlateDecode/First 5/Length 60/N 1/Type/ObjStm>>stream\r\n"
2849          [..],
2850      );
2851      pdf.extend_from_slice(&enc.finish().expect("finish"));
2852      pdf.extend_from_slice(b"\r\nendstream\rendobj\r");
2853      fixture("hf.pdf", &pdf)
2854    };
2855    assert_eq!(
2856      read_pdf_page_box_corners(&filter_first),
2857      Some([0.0, 0.0, 108.056, 52.537])
2858    );
2859
2860    // Nothing readable anywhere: an object stream we cannot inflate.
2861    let opaque = fixture(
2862      "ho.pdf",
2863      b"%PDF-1.5\n<< /Type /ObjStm /N 12 /Filter /FlateDecode >>\nstream\nnot-zlib\nendstream\n",
2864    );
2865    assert_eq!(read_pdf_page_box(&opaque), None);
2866  }
2867
2868  /// The size and page-count probes search the PDF's bytes, which need not be
2869  /// UTF-8 (binary comment line, text strings in a dictionary). A byte that is
2870  /// not UTF-8 inside the `/Pages` dictionary, before its `/Count`: the count
2871  /// scan sliced a lossy UTF-8 copy of the file at every byte index and
2872  /// panicked inside the U+FFFD that byte had become.
2873  #[test]
2874  fn pdf_probes_read_through_non_utf8_bytes() {
2875    let pages = fixture(
2876      "p8.pdf",
2877      b"%PDF-1.4\n%\xE2\xE3\xCF\xD3\n<< /Type /Pages /Title (\xE9t\xE9) /Count 3 >>\n",
2878    );
2879    assert_eq!(read_pdf_page_count(&pages), Some(3));
2880
2881    // The box's numbers may be separated by any PDF white space, here FF and HT.
2882    let boxed = fixture(
2883      "b8.pdf",
2884      b"%PDF-1.4\n%\xE2\xE3\xCF\xD3\n<< /Title (\xE9) /MediaBox [0\x0c0 200\t100] >>\n",
2885    );
2886    assert_eq!(read_pdf_page_box(&boxed), Some((200.0, 100.0)));
2887
2888    // The same through an object stream, and a token that is not UTF-8 in the box.
2889    let streamed = fixture(
2890      "s8.pdf",
2891      &objstm_pdf(b"2 0 << /Type /Pages /T (\xE9) /Count 4 >>"),
2892    );
2893    assert_eq!(read_pdf_page_count(&streamed), Some(4));
2894    let odd = fixture("o8.pdf", b"%PDF-1.4\n<< /MediaBox [0 0 \xFF 200 100] >>\n");
2895    assert_eq!(read_pdf_page_box(&odd), Some((200.0, 100.0)));
2896    // NUL is PDF white space; a UTF-8 NBSP between digits is not.
2897    let nul = fixture("n8.pdf", b"%PDF-1.4\n<< /MediaBox [0\x000 200 100] >>\n");
2898    assert_eq!(read_pdf_page_box(&nul), Some((200.0, 100.0)));
2899    let nbsp = fixture(
2900      "nb8.pdf",
2901      b"%PDF-1.4\n<< /MediaBox [0 0 200\xC2\xA0100 50] >>\n",
2902    );
2903    assert_eq!(read_pdf_page_box(&nbsp), None);
2904
2905    // No `/Pages` dictionary: the `/Type /Page` objects are counted, not `/Pages`.
2906    let loose = fixture(
2907      "l8.pdf",
2908      b"%PDF-1.4\n<< /Type /Page /T (\xFF) >>\n<< /Type/Page >>\n<< /Type /Pagesx >>\n",
2909    );
2910    assert_eq!(read_pdf_page_count(&loose), Some(2));
2911  }
2912
2913  /// `natural_size_pt` is the only place a file-read number is actually
2914  /// converted from its own unit into TeX pt — and it uses a different
2915  /// resolution per format: PDF at 72 (bp), SVG at 96 (CSS px).
2916  #[test]
2917  fn natural_size_pt_uses_72_for_pdf_and_96_for_svg() {
2918    let pdf = fixture("n.pdf", b"%PDF-1.4\n<< /MediaBox [0 0 200 100] >>\n");
2919    let (w, h) = natural_size_pt(&pdf).expect("pdf box");
2920    assert!((w - 200.0 * 72.27 / 72.0).abs() < 1e-9, "w = {w}"); // 200.75
2921    assert!((h - 100.0 * 72.27 / 72.0).abs() < 1e-9, "h = {h}");
2922
2923    let svg = fixture("n.svg", br#"<svg viewBox="0 0 200 100"><rect/></svg>"#);
2924    let (w, h) = natural_size_pt(&svg).expect("svg viewport");
2925    assert!((w - 200.0 * 72.27 / 96.0).abs() < 1e-9, "w = {w}"); // 150.5625
2926    assert!((h - 100.0 * 72.27 / 96.0).abs() < 1e-9, "h = {h}");
2927
2928    // A raster file has no page box and no SVG root: `None`, so the caller
2929    // keeps whatever the pixel reader gave it.
2930    let png = fixture("n.png", &png_header(200, 100));
2931    assert_eq!(natural_size_pt(&png), None);
2932  }
2933
2934  /// The compiled op *sequence* depends on where `angle` sits relative to the
2935  /// sizing keys — the ordering graphicx and pdflatex both honour. Pinned at the
2936  /// parse layer so the rule is guarded without a rasterizer: `angle` before a
2937  /// sizing key rotates first, after it rotates last, and a rotation with no
2938  /// sizing key at all rotates first.
2939  #[test]
2940  fn parse_orders_rotation_by_key_position() {
2941    use GraphicxOp::*;
2942    let w100 = ScaleTo {
2943      w:           Some(to_bp("100pt")),
2944      h:           None,
2945      keep_aspect: true,
2946    };
2947    assert_eq!(
2948      parse_graphicx_options("angle=90,width=100pt"),
2949      vec![Rotate(90.0), w100.clone()],
2950      "angle first -> rotate then scale"
2951    );
2952    assert_eq!(
2953      parse_graphicx_options("width=100pt,angle=90"),
2954      vec![w100, Rotate(90.0)],
2955      "width first -> scale then rotate"
2956    );
2957    assert_eq!(
2958      parse_graphicx_options("angle=90"),
2959      vec![Rotate(90.0)],
2960      "no sizing key -> rotate first (trivially)"
2961    );
2962    // scale is a sizing key too, so it flips the order the same way.
2963    assert_eq!(
2964      parse_graphicx_options("angle=90,scale=2")[0],
2965      Rotate(90.0),
2966      "angle before scale -> rotate first"
2967    );
2968    assert_eq!(
2969      parse_graphicx_options("scale=2,angle=90")[1],
2970      Rotate(90.0),
2971      "angle after scale -> rotate last"
2972    );
2973  }
2974
2975  // ── layer 3a: the pt-space algebra (fallback branch) ──────────────────
2976
2977  /// `graphicx_box_pt` works in pt throughout and never quantizes, so an
2978  /// explicit `width=100pt` comes out as exactly 100pt. Compare
2979  /// `sizer_quantizes_the_box_to_whole_device_pixels` below, which is the
2980  /// px-space algebra answering the *same* request with 99.7326pt.
2981  #[test]
2982  fn graphicx_box_pt_table() {
2983    let pt = |d: Dimension| d.value_of() as f64 / 65536.0;
2984    let case = |opts: &str| {
2985      let (w, h) = graphicx_box_pt(200.0, 100.0, opts);
2986      (pt(w), pt(h))
2987    };
2988    let near = |got: (f64, f64), want: (f64, f64), label: &str| {
2989      assert!(
2990        (got.0 - want.0).abs() < 1e-3 && (got.1 - want.1).abs() < 1e-3,
2991        "{label}: got {got:?}, want {want:?}"
2992      );
2993    };
2994    near(case(""), (200.0, 100.0), "no options = natural size");
2995    near(
2996      case("width=100pt"),
2997      (100.0, 50.0),
2998      "width= drives height by aspect",
2999    );
3000    near(
3001      case("height=25pt"),
3002      (50.0, 25.0),
3003      "height= drives width by aspect",
3004    );
3005    near(
3006      case("totalheight=25pt"),
3007      (50.0, 25.0),
3008      "totalheight aliases height",
3009    );
3010    near(case("scale=0.5"), (100.0, 50.0), "scale=");
3011    near(
3012      case("width=100pt,height=80pt"),
3013      (100.0, 80.0),
3014      "both, no keepaspect",
3015    );
3016    // keepaspectratio drops the more extreme request and fits inside the box.
3017    near(
3018      case("width=100pt,height=80pt,keepaspectratio"),
3019      (100.0, 50.0),
3020      "keepaspectratio fits width",
3021    );
3022    near(
3023      case("width=400pt,height=80pt,keepaspectratio"),
3024      (160.0, 80.0),
3025      "keepaspectratio fits height",
3026    );
3027    // An explicit width wins over scale (scale is only consulted when neither
3028    // width nor height is given).
3029    near(
3030      case("scale=2,width=100pt"),
3031      (100.0, 50.0),
3032      "width beats scale",
3033    );
3034    // Units other than pt parse through `Dimension::from_str`.
3035    near(case("width=1in"), (72.27, 36.135), "in parses");
3036    // A degenerate natural size carries no aspect ratio, and a lone `width=`
3037    // always wants one — Perl abandons the computation rather than guess
3038    // (`Util/Image.pm` L234), reporting nothing, i.e. a zero box.
3039    let (w, h) = graphicx_box_pt(0.0, 0.0, "width=100pt");
3040    near((pt(w), pt(h)), (0.0, 0.0), "zero natural height");
3041  }
3042
3043  // ── layer 3b: the px-space algebra, and the whole seam ────────────────
3044
3045  /// Drive the real entry point, `image_graphicx_sizer`, with an absolute
3046  /// candidate path so no `SOURCEDIRECTORY` is needed. Returns cached
3047  /// (width, height) in pt.
3048  fn sizer_pt(path: &Path, options: &str) -> (f64, f64) {
3049    let mut w = Whatsit::default();
3050    w.set_property("candidates", path.to_string_lossy().to_string());
3051    w.set_property("options", options.to_string());
3052    image_graphicx_sizer(&mut w);
3053    let get = |k: &str| match w.get_property(k).map(|c| c.into_owned()) {
3054      Some(Stored::Dimension(d)) => d.value_of() as f64 / 65536.0,
3055      other => panic!("{k} was {other:?}"),
3056    };
3057    (get("cached_width"), get("cached_height"))
3058  }
3059
3060  /// **The whole engine-side seam, as one matrix.** Same 200x100 figure in
3061  /// four containers, eight option strings, `cached_width`/`cached_height` in
3062  /// pt. This is the table the unified pipeline has to reproduce, row by row,
3063  /// or explicitly change.
3064  ///
3065  /// What each surprising row records:
3066  ///
3067  /// * **Three resolutions.** With no options the same figure is 200.75pt as a
3068  ///   PNG (72 dpi, pdfTeX's `\pdfimageresolution`, where it states none; at
3069  ///   100 dpi, 144.54pt, until OD #1188), a PDF or an EPS (bp; the EPS was read
3070  ///   as 100 dpi pixels until 78z), 150.5625pt as an SVG (96 dpi, CSS px), and
3071  ///   0 as a PDF whose page box sits in an object stream. pdflatex says
3072  ///   200.7495pt for the PNG, the EPS and the PDF alike. A PNG that states
3073  ///   300 dpi is its pixels at 300 dpi.
3074  /// * **One algebra**, `graphicx_box_pt`, in pt. Until OD #1188 a PNG took a
3075  ///   px-space branch that read graphicx's bp as pt and quantized the box to a
3076  ///   whole pixel: `width=100pt` was 99.7326pt (KNOWN_PERL_ERRORS #1142).
3077  /// * **A single dimension always preserves aspect**, on both branches, as
3078  ///   Perl does by compiling `width=` alone into a scale-to with a 999999
3079  ///   sentinel and `keep_aspect` forced on (`Util/Image.pm` L188-189). Until
3080  ///   2026-08-04 the px branch left the height at its natural value; the
3081  ///   `keepaspectratio=true` that `graphicx_sty` injects had been hiding it
3082  ///   from ordinary LaTeX.
3083  /// * **`angle=` rotates the reserved box** (Perl L238-242). Until 2026-08-04
3084  ///   neither branch implemented the op, so a sideways figure reserved its
3085  ///   unrotated width — a Rust-only gap, since Perl has always rotated:
3086  ///   measured `angle=90` on the PNG gives Perl 72.27 x 144.54, and that is
3087  ///   now what this matrix pins.
3088  /// * **The last-resort branch** (unreadable page box) honours an explicit
3089  ///   `width=`/`height=` and reports 0 for the dimension not asked for.
3090  #[test]
3091  fn sizer_matrix_across_formats_and_options() {
3092    let png = fixture("m.png", &png_header(200, 100));
3093    // 600x300 px at 300 dpi (11811 px/m): 2in x 1in.
3094    let mut png300 = png_header(600, 300)[..33].to_vec();
3095    png300.extend_from_slice(&9u32.to_be_bytes());
3096    png300.extend_from_slice(b"pHYs");
3097    png300.extend_from_slice(&[0, 0, 0x2e, 0x23, 0, 0, 0x2e, 0x23, 1, 0, 0, 0, 0]);
3098    let png300 = fixture("m300.png", &png300);
3099    let eps = fixture(
3100      "m.eps",
3101      b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 200 100\n",
3102    );
3103    let pdf = fixture("m.pdf", b"%PDF-1.4\n<< /MediaBox [0 0 200 100] >>\n");
3104    let svg = fixture("m.svg", br#"<svg viewBox="0 0 200 100"><rect/></svg>"#);
3105    let objstm = fixture("m2.pdf", b"%PDF-1.5\n<< /Type /ObjStm >>\nstream\n..\n");
3106
3107    // (source, options, expected width pt, expected height pt)
3108    #[rustfmt::skip]
3109    let matrix: &[(&str, &str, f64, f64)] = &[
3110      // A raster: its pixels at 72 dpi when it states no resolution, else at its own.
3111      ("png", "",                                 200.7500, 100.3750),
3112      ("png", "width=100pt,keepaspectratio=true", 100.0000,  50.0000),
3113      ("png", "width=100pt",                      100.0000,  50.0000),
3114      ("png", "scale=0.5",                        100.3750,  50.1875),
3115      ("png", "height=25pt,keepaspectratio=true",  50.0000,  25.0000),
3116      ("png", "width=100pt,height=80pt",          100.0000,  80.0000),
3117      ("png", "width=1in,keepaspectratio=true",    72.2700,  36.1350),
3118      ("png", "angle=90",                         100.3750, 200.7500),
3119      ("png300", "",                              144.5400,  72.2700),
3120      ("png300", "scale=0.5",                      72.2700,  36.1350),
3121      // pt-space branch: the vector formats, no quantization — an EPS BoundingBox
3122      // in bp (78z; it was read as pixels, 144.54pt for the natural size).
3123      ("eps", "",                                 200.7500, 100.3750),
3124      ("eps", "width=100pt,keepaspectratio=true", 100.0000,  50.0000),
3125      ("eps", "width=100pt",                      100.0000,  50.0000),
3126      ("eps", "scale=0.5",                        100.3750,  50.1875),
3127      ("eps", "height=25pt,keepaspectratio=true",  50.0000,  25.0000),
3128      ("eps", "width=100pt,height=80pt",          100.0000,  80.0000),
3129      ("eps", "width=1in,keepaspectratio=true",    72.2700,  36.1350),
3130      ("eps", "angle=90",                         100.3750, 200.7500),
3131      ("pdf", "",                                 200.7500, 100.3750),
3132      ("pdf", "width=100pt,keepaspectratio=true", 100.0000,  50.0000),
3133      ("pdf", "width=100pt",                      100.0000,  50.0000),
3134      ("pdf", "scale=0.5",                        100.3750,  50.1875),
3135      ("pdf", "height=25pt,keepaspectratio=true",  50.0000,  25.0000),
3136      ("pdf", "width=100pt,height=80pt",          100.0000,  80.0000),
3137      ("pdf", "width=1in,keepaspectratio=true",    72.2700,  36.1350),
3138      ("pdf", "angle=90",                         100.3750, 200.7500),
3139      ("svg", "",                                 150.5625,  75.2812),
3140      ("svg", "width=100pt,keepaspectratio=true", 100.0000,  50.0000),
3141      ("svg", "width=100pt",                      100.0000,  50.0000),
3142      ("svg", "scale=0.5",                         75.2812,  37.6406),
3143      ("svg", "height=25pt,keepaspectratio=true",  50.0000,  25.0000),
3144      ("svg", "width=100pt,height=80pt",          100.0000,  80.0000),
3145      ("svg", "width=1in,keepaspectratio=true",    72.2700,  36.1350),
3146      ("svg", "angle=90",                          75.2812, 150.5625),
3147      // last resort: nothing measurable, only an explicit request is honoured.
3148      ("objstm", "",                                0.0000,   0.0000),
3149      ("objstm", "width=100pt,keepaspectratio=true", 100.0000, 0.0000),
3150      ("objstm", "width=100pt",                    100.0000,   0.0000),
3151      ("objstm", "scale=0.5",                        0.0000,   0.0000),
3152      ("objstm", "height=25pt,keepaspectratio=true", 0.0000,  25.0000),
3153      ("objstm", "width=100pt,height=80pt",        100.0000,  80.0000),
3154      ("objstm", "width=1in,keepaspectratio=true",  72.2700,   0.0000),
3155      ("objstm", "angle=90",                         0.0000,   0.0000),
3156    ];
3157
3158    // Report EVERY divergence, not just the first: when this matrix moves it is
3159    // usually because a shared rule changed, and the whole delta is the useful
3160    // signal.
3161    let mut deltas = Vec::new();
3162    for (src, opts, want_w, want_h) in matrix {
3163      let path = match *src {
3164        "png" => &png,
3165        "png300" => &png300,
3166        "eps" => &eps,
3167        "pdf" => &pdf,
3168        "svg" => &svg,
3169        _ => &objstm,
3170      };
3171      let (w, h) = sizer_pt(path, opts);
3172      // 1e-3 pt is ~1/70000 inch: far tighter than any behaviour change, loose
3173      // enough to survive `Dimension`'s fixed-point round trip.
3174      if (w - want_w).abs() >= 1e-3 || (h - want_h).abs() >= 1e-3 {
3175        deltas.push(format!(
3176          "  {src:<7} [{opts}]\n      pinned ({want_w:.4}, {want_h:.4})  got ({w:.4}, {h:.4})"
3177        ));
3178      }
3179    }
3180    assert!(
3181      deltas.is_empty(),
3182      "{} of {} pinned rows moved:\n{}",
3183      deltas.len(),
3184      matrix.len(),
3185      deltas.join("\n")
3186    );
3187  }
3188
3189  /// Perl `image_graphicx_complex`'s trim/clip arm (`Util/Image.pm` L400-418),
3190  /// on a 200×100 raster at 72 dpi (1 px = 1 bp): `trim=100 0 0 50` keeps the
3191  /// bottom-right quadrant and `viewport=0 0 100 50` the bottom-left one, as
3192  /// pdflatex shows them; a box over the whole image crops nothing.
3193  #[test]
3194  fn graphicx_crop_rect_follows_perl_trim_and_viewport() {
3195    let trim = GraphicxOp::Trim {
3196      l: 100.0,
3197      b: 0.0,
3198      r: 0.0,
3199      t: 50.0,
3200    };
3201    assert_eq!(
3202      graphicx_crop_rect(200, 100, &trim, 1.0),
3203      Some((100, 50, 100, 50))
3204    );
3205    let viewport = GraphicxOp::Clip {
3206      l: 0.0,
3207      b: 0.0,
3208      r: 100.0,
3209      t: 50.0,
3210    };
3211    assert_eq!(
3212      graphicx_crop_rect(200, 100, &viewport, 1.0),
3213      Some((0, 50, 100, 50))
3214    );
3215    let nothing = GraphicxOp::Trim { l: 0.0, b: 0.0, r: 0.0, t: 0.0 };
3216    assert_eq!(graphicx_crop_rect(200, 100, &nothing, 1.0), None);
3217    // A viewport reaching past the image is clamped, never padded.
3218    let past = GraphicxOp::Clip {
3219      l: -20.0,
3220      b: 0.0,
3221      r: 50.0,
3222      t: 100.0,
3223    };
3224    assert_eq!(
3225      graphicx_crop_rect(200, 100, &past, 1.0),
3226      Some((0, 0, 50, 100))
3227    );
3228    // 2510.17772 Fig 7: `trim=90 30 50 50` on a 3000×1500 raster at 300 dpi.
3229    let witness = GraphicxOp::Trim {
3230      l: 90.0,
3231      b: 30.0,
3232      r: 50.0,
3233      t: 50.0,
3234    };
3235    assert_eq!(
3236      graphicx_crop_rect(3000, 1500, &witness, 300.0 / 72.0),
3237      Some((375, 208, 2417, 1167))
3238    );
3239  }
3240
3241  /// A PNG's `pHYs` counts per metre, a JFIF density per inch or centimetre,
3242  /// rounded and truncated to whole dpi as pdfTeX takes them; an aspect-only
3243  /// density (unit 0) states no resolution.
3244  #[test]
3245  fn raster_resolution_reads_png_and_jfif_units() {
3246    let dir = std::env::temp_dir().join(format!("raster_dpi_{}", std::process::id()));
3247    std::fs::create_dir_all(&dir).unwrap();
3248    let mut png = png_header(10, 10)[..33].to_vec();
3249    png.extend_from_slice(&9u32.to_be_bytes());
3250    png.extend_from_slice(b"pHYs");
3251    png.extend_from_slice(&11811u32.to_be_bytes());
3252    png.extend_from_slice(&11811u32.to_be_bytes());
3253    png.extend_from_slice(&[1, 0, 0, 0, 0]); // unit, CRC
3254    let png_path = dir.join("r.png");
3255    std::fs::write(&png_path, &png).unwrap();
3256    assert_eq!(
3257      raster_resolution_dpi(png_path.to_str().unwrap(), (10.0, 10.0)),
3258      Some((300.0, 300.0))
3259    );
3260    // Above 65535 dpi pdfTeX ignores the resolution (pdftex.web:34488-34491): 3,000,000 px/m is 76200 dpi.
3261    png[41..45].copy_from_slice(&3_000_000u32.to_be_bytes());
3262    std::fs::write(&png_path, &png).unwrap();
3263    assert_eq!(
3264      raster_resolution_dpi(png_path.to_str().unwrap(), (10.0, 10.0)),
3265      None
3266    );
3267    let jfif = |unit: u8| {
3268      let mut v = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10];
3269      v.extend_from_slice(b"JFIF\0\x01\x02");
3270      v.push(unit);
3271      v.extend_from_slice(&[0x00, 0x76, 0x00, 0x76, 0, 0]); // 118 × 118
3272      v
3273    };
3274    let jpg_path = dir.join("r.jpg");
3275    std::fs::write(&jpg_path, jfif(2)).unwrap();
3276    assert_eq!(
3277      raster_resolution_dpi(jpg_path.to_str().unwrap(), (10.0, 10.0)),
3278      Some((299.0, 299.0))
3279    );
3280    std::fs::write(&jpg_path, jfif(0)).unwrap();
3281    assert_eq!(
3282      raster_resolution_dpi(jpg_path.to_str().unwrap(), (10.0, 10.0)),
3283      None
3284    );
3285    std::fs::remove_dir_all(&dir).ok();
3286  }
3287
3288  /// A JPEG's density as pdfTeX's `read_jpg_info` reads it (writejpg.c): the segment right after SOI only, a JFIF
3289  /// `APP0` or an Exif `APP1` (IFD0's rational X/YResolution, an integer quotient, 72 when absent; unit 3 per cm), and
3290  /// the 65535 cap of pdftex.web:34488 on both. pdflatex (TL 2025) on a 300x150 px JPEG: Exif-only 300 dpi 72.2698pt,
3291  /// JFIF unit 0 then that Exif 301.12425pt, JFIF 30000 px/cm 301.12425pt ("too large image resolution ignored").
3292  /// Red (b8358aa0b28): Exif-only None, 30000 px/cm `Some((76200.0, 76200.0))`.
3293  #[test]
3294  fn jpeg_resolution_is_the_first_segment_as_pdftex_reads_it() {
3295    let dir = std::env::temp_dir().join(format!("jpeg_dpi_{}", std::process::id()));
3296    std::fs::create_dir_all(&dir).unwrap();
3297    let path = dir.join("r.jpg");
3298    let dpi = |bytes: &[u8]| {
3299      std::fs::write(&path, bytes).unwrap();
3300      raster_resolution_dpi(path.to_str().unwrap(), (300.0, 150.0))
3301    };
3302    let jfif = |unit: u8, x: u16, y: u16| {
3303      let mut v = vec![0xFF, 0xE0, 0x00, 0x10];
3304      v.extend_from_slice(b"JFIF\0\x01\x02");
3305      v.push(unit);
3306      v.extend_from_slice(&x.to_be_bytes());
3307      v.extend_from_slice(&y.to_be_bytes());
3308      v.extend_from_slice(&[0, 0]);
3309      v
3310    };
3311    // An Exif APP1: a TIFF header (`II` little-endian or `MM`), IFD0 at 8 with the given (tag, rational) entries and a
3312    // ResolutionUnit, the rationals after it.
3313    let exif = |big: bool, res: &[(u16, u32, u32)], unit: Option<u16>| {
3314      let u16b = |v: u16| {
3315        if big {
3316          v.to_be_bytes()
3317        } else {
3318          v.to_le_bytes()
3319        }
3320      };
3321      let u32b = |v: u32| {
3322        if big {
3323          v.to_be_bytes()
3324        } else {
3325          v.to_le_bytes()
3326        }
3327      };
3328      let n = res.len() + usize::from(unit.is_some());
3329      let mut tiff = if big { b"MM".to_vec() } else { b"II".to_vec() };
3330      tiff.extend_from_slice(&u16b(42));
3331      tiff.extend_from_slice(&u32b(8));
3332      tiff.extend_from_slice(&u16b(n as u16));
3333      let mut rationals = Vec::new();
3334      let base = 8 + 2 + 12 * n as u32 + 4;
3335      for &(tag, num, den) in res {
3336        tiff.extend_from_slice(&u16b(tag));
3337        tiff.extend_from_slice(&u16b(5));
3338        tiff.extend_from_slice(&u32b(1));
3339        tiff.extend_from_slice(&u32b(base + rationals.len() as u32));
3340        rationals.extend_from_slice(&u32b(num));
3341        rationals.extend_from_slice(&u32b(den));
3342      }
3343      if let Some(unit) = unit {
3344        tiff.extend_from_slice(&u16b(296));
3345        tiff.extend_from_slice(&u16b(3));
3346        tiff.extend_from_slice(&u32b(1));
3347        tiff.extend_from_slice(&u16b(unit));
3348        tiff.extend_from_slice(&[0, 0]);
3349      }
3350      tiff.extend_from_slice(&[0; 4]);
3351      tiff.extend_from_slice(&rationals);
3352      let mut v = vec![0xFF, 0xE1];
3353      v.extend_from_slice(&((2 + 6 + tiff.len()) as u16).to_be_bytes());
3354      v.extend_from_slice(b"Exif\0\0");
3355      v.extend_from_slice(&tiff);
3356      v
3357    };
3358    let soi = |segments: &[Vec<u8>]| [vec![0xFF, 0xD8], segments.concat()].concat();
3359    let x300 = exif(false, &[(282, 300, 1), (283, 300, 1)], Some(2));
3360    assert_eq!(dpi(&soi(std::slice::from_ref(&x300))), Some((300.0, 300.0)));
3361    assert_eq!(
3362      dpi(&soi(&[exif(
3363        true,
3364        &[(282, 300, 1), (283, 150, 1)],
3365        Some(2)
3366      )])),
3367      Some((300.0, 150.0))
3368    );
3369    // An integer quotient, then the centimetre: 2999/10 = 299 px/cm, x 2.54 = 759.46, 759 dpi.
3370    assert_eq!(
3371      dpi(&soi(&[exif(
3372        false,
3373        &[(282, 2999, 10), (283, 2999, 10)],
3374        Some(3)
3375      )])),
3376      Some((759.0, 759.0))
3377    );
3378    // No resolution tags: 72.
3379    assert_eq!(dpi(&soi(&[exif(false, &[], None)])), Some((72.0, 72.0)));
3380    // A JFIF segment first decides, even at unit 0; an Exif after it is not read.
3381    assert_eq!(dpi(&soi(&[jfif(0, 1, 1), x300])), None);
3382    // Any other first segment (an Adobe APP14) states none, though a JFIF follows.
3383    let app14 = vec![0xFF, 0xEE, 0x00, 0x04, 0, 0];
3384    assert_eq!(dpi(&soi(&[app14, jfif(1, 300, 300)])), None);
3385    // 30000 px/cm = 76200 dpi, above 65535: ignored, as the PNG's.
3386    assert_eq!(dpi(&soi(&[jfif(2, 30000, 30000)])), None);
3387    // A zero axis takes the other's value.
3388    assert_eq!(dpi(&soi(&[jfif(1, 0, 150)])), Some((150.0, 150.0)));
3389    std::fs::remove_dir_all(&dir).ok();
3390  }
3391}