1use 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
22pub fn image_candidates(path: &str) -> String { image_candidates_with(path, true) }
29
30fn image_candidates_with(path: &str, fallbacks: bool) -> String {
33 let unquoted = path.replace('"', "");
37 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 let mut seen = rustc_hash::FxHashSet::default();
298 candidates.retain(|c| seen.insert(c.clone()));
299
300 candidates.join(",")
308}
309
310#[derive(Debug, Default, PartialEq)]
312struct ImageCandidateLists {
313 exact_names: Vec<String>,
315 extended_names: Vec<String>,
317 nocase_exact_names: Vec<String>,
319 nocase_candidates: Vec<String>,
321}
322
323fn 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
364fn 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
377const GRAPHICS_EXTENSIONS: [&str; 14] = [
382 "pdf", "png", "jpg", "mps", "jpeg", "jbig2", "jb2", "eps", "ps", "svg", "gif", "tif", "tiff",
383 "bmp",
384];
385
386const GIN_EXTENSIONS: usize = 7;
388
389fn has_graphics_extension(name: &str) -> bool {
392 graphics_type_rank(name) < 4 * GRAPHICS_EXTENSIONS.len()
393}
394
395fn 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
431fn 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
454const PDFTEX_GIN_EXTENSIONS: [&str; 13] = [
456 ".pdf", ".png", ".jpg", ".mps", ".jpeg", ".jbig2", ".jb2", ".PDF", ".PNG", ".JPG", ".JPEG",
457 ".JBIG2", ".JB2",
458];
459
460fn 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
485fn 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
509fn 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#[derive(Debug, Clone, PartialEq)]
536pub enum GraphicxOp {
537 Page(u32),
539 Trim {
541 l: f64,
542 b: f64,
543 r: f64,
544 t: f64,
545 },
546 Clip {
548 l: f64,
549 b: f64,
550 r: f64,
551 t: f64,
552 },
553 Rotate(f64),
555 Reflect,
556 Scale {
558 x: f64,
559 y: f64,
560 },
561 ScaleTo {
565 w: Option<f64>,
566 h: Option<f64>,
567 keep_aspect: bool,
568 },
569}
570
571pub 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 _ => 1.0,
598 };
599 v * factor
600}
601
602pub 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 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 (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
717pub 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 if w <= 0.0 || h <= 0.0 {
753 return (0.0, 0.0);
754 }
755 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 (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 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 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 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
815pub 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 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 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 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
861pub fn raster_resolution_dpi(path: &str, pixels: (f64, f64)) -> Option<(f64, f64)> {
869 pdftex_raster_resolution(path, pixels).ok()
870}
871
872pub 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
889fn 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
911pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
924pub enum GraphicContent {
925 Pdf,
926 PostScript,
927 Raster,
928}
929
930pub 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
956fn 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
961fn 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 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
995fn 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 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
1029fn 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 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
1082enum Natural {
1085 Pixels(f64, f64),
1086 Points(f64, f64),
1087}
1088
1089fn 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 Some(ImageSize::PostScriptBp(w, h)) => Some(Natural::Points(bp_to_pt(w), bp_to_pt(h))),
1098 _ => natural_size_pt(path).map(|(w, h)| Natural::Points(w, h)),
1105 }
1106}
1107
1108fn first_natural_size(candidates: &str, source_dir: &str) -> Option<(Natural, PathBuf)> {
1118 candidates.split(',').find_map(|candidate| {
1119 let candidate = candidate.trim();
1120 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
1129pub 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 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 Some((Natural::Pixels(w, h), path)) => {
1155 let path = path.to_string_lossy();
1159 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 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 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
1236fn 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
1266fn read_file_resilient(path: &Path) -> Option<Vec<u8>> {
1268 with_transient_retry(|| std::fs::read(path))
1269}
1270
1271fn open_file_resilient(path: &Path) -> Option<std::fs::File> {
1275 with_transient_retry(|| std::fs::File::open(path))
1276}
1277
1278pub 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#[derive(Debug, Clone, Copy, PartialEq)]
1295pub enum ImageSize {
1296 Pixels(u32, u32),
1298 PostScriptBp(f64, f64),
1300}
1301
1302pub 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
1314type 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
1331pub 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 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 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 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
1368pub 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
1383pub 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#[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
1416const PS_COMMENT_WINDOW: u64 = 32 * 1024;
1418
1419pub 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 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 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
1498fn 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
1509fn 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 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 0x01 | 0xD0..=0xD7 => continue,
1533 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 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
1555fn 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
1567fn 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
1579fn bp_to_pt(bp: f64) -> f64 { bp * 72.27 / 72.0 }
1581
1582pub 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
1603pub 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
1619fn pt_to_dim(pt: f64) -> Dimension { Dimension::new((pt * 65536.0).round() as i64) }
1621
1622fn graphicx_box_pt(nw: f64, nh: f64, options: &str) -> (Dimension, Dimension) {
1627 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
1641pub 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
1660pub 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
1684pub 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
1721fn 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 if content.get(at + key.len()) != Some(&b's') {
1766 n += 1;
1767 }
1768 }
1769 }
1770 n
1771}
1772
1773fn 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
1784fn 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
1790fn inflate_object_streams(bytes: &[u8]) -> Option<Vec<u8>> {
1803 use std::io::Read;
1804
1805 const MAX_OBJSTM_SCAN: usize = 64;
1807 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 let Some(rel) = byte_find(&bytes[at..], b"stream") else {
1823 continue;
1824 };
1825 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 continue;
1853 }
1854 out.extend_from_slice(&buf);
1855 out.push(b'\n');
1856 }
1857 (!out.is_empty()).then_some(out)
1858}
1859
1860fn 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 Some([x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)])
1880}
1881
1882fn 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
1890fn 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 Some((px_to_pt(vw), px_to_pt(vh)))
1907}
1908
1909pub fn read_svg_viewport_px(path: &Path) -> Option<(u32, u32)> {
1922 svg_viewport_px(&read_head_lossy(path)?)
1923}
1924
1925pub 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
1932fn 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
1945pub fn svg_root_tag(head: &str) -> Option<&str> { xml_start_tag(&head[head.find("<svg")?..]) }
1950
1951pub 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
1966pub 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 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 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
2004fn 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
2018pub fn svg_attr_len_px(tag: &str, name: &str) -> Option<f64> {
2023 svg_len_px(svg_attr_value(tag, name)?)
2024}
2025
2026fn 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
2037fn svg_len_px(raw: &str) -> Option<f64> {
2040 let raw = raw.trim();
2041 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, }
2062}
2063
2064fn 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
2074fn px_to_pt(px: f64) -> f64 { px * 72.27 / 96.0 }
2076
2077#[cfg(test)]
2078mod candidate_order_tests {
2079 use super::*;
2080
2081 #[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 #[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 #[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 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 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 #[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 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 assert_eq!(
2262 svg_attr_value(r#"<svg width = "634""#, "width"),
2263 Some("634")
2264 );
2265 }
2266
2267 #[test]
2270 fn len_px_converts_absolute_units_and_rejects_relative_ones() {
2271 let cases: &[(&str, Option<f64>)] = &[
2272 ("634", Some(634.0)), ("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)), ("-5", Some(-5.0)),
2282 ("100%", None), ("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 #[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 #[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 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 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 #[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("ed), 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 #[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 #[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 #[test]
2413 fn size_pt_prefers_absolute_lengths_then_falls_back_to_the_viewbox() {
2414 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 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 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 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#[cfg(test)]
2472mod sizing_characterization_tests {
2473 use super::*;
2474
2475 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 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 #[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 #[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 #[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 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 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]); v
2581 }
2582
2583 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 #[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 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 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 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 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 #[test]
2704 fn jpeg_frame_size_skips_segments() {
2705 let mut jpg = vec![0xFF, 0xD8];
2706 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 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 #[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 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 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 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 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 #[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 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 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 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 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 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 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 #[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 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 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 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( ), None);
2904
2905 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 #[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}"); 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}"); assert!((h - 100.0 * 72.27 / 96.0).abs() < 1e-9, "h = {h}");
2927
2928 let png = fixture("n.png", &png_header(200, 100));
2931 assert_eq!(natural_size_pt(&png), None);
2932 }
2933
2934 #[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 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 #[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 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 near(
3030 case("scale=2,width=100pt"),
3031 (100.0, 50.0),
3032 "width beats scale",
3033 );
3034 near(case("width=1in"), (72.27, 36.135), "in parses");
3036 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 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 #[test]
3091 fn sizer_matrix_across_formats_and_options() {
3092 let png = fixture("m.png", &png_header(200, 100));
3093 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 #[rustfmt::skip]
3109 let matrix: &[(&str, &str, f64, f64)] = &[
3110 ("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 ("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 ("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 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 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 #[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, ¬hing, 1.0), None);
3217 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 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 #[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]); 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 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]); 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 #[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 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 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 assert_eq!(dpi(&soi(&[exif(false, &[], None)])), Some((72.0, 72.0)));
3380 assert_eq!(dpi(&soi(&[jfif(0, 1, 1), x300])), None);
3382 let app14 = vec![0xFF, 0xEE, 0x00, 0x04, 0, 0];
3384 assert_eq!(dpi(&soi(&[app14, jfif(1, 300, 300)])), None);
3385 assert_eq!(dpi(&soi(&[jfif(2, 30000, 30000)])), None);
3387 assert_eq!(dpi(&soi(&[jfif(1, 0, 150)])), Some((150.0, 150.0)));
3389 std::fs::remove_dir_all(&dir).ok();
3390 }
3391}