1use std::{
9 path::{Path, PathBuf},
10 sync::LazyLock,
11};
12
13use latexml_core::util::image::{GraphicContent, GraphicxOp};
14use libxml::tree::Node;
15use rustc_hash::FxHashMap as HashMap;
16
17use crate::{
18 document::{DocCache, PostDocument},
19 processor::{ProcessResult, Processor},
20 resource_cache::{Output, Proposal, Request, ResourceName},
21};
22
23thread_local! {
24 static LAST_CONVERTER_DIAG: std::cell::RefCell<Option<String>> =
35 const { std::cell::RefCell::new(None) };
36}
37
38fn record_converter_diag(msg: String) { LAST_CONVERTER_DIAG.with(|c| *c.borrow_mut() = Some(msg)); }
40
41fn take_converter_diag() -> Option<String> { LAST_CONVERTER_DIAG.with(|c| c.borrow_mut().take()) }
43
44#[cfg(target_os = "linux")]
48fn reparented(spawner: libc::pid_t, parent_now: libc::pid_t) -> bool { parent_now != spawner }
49
50fn readable(path: &str) -> bool {
53 latexml_core::util::pathname::read_allowed(path) && Path::new(path).exists()
54}
55
56fn im_convert_program() -> &'static str { if cfg!(windows) { "magick" } else { "convert" } }
63
64fn gs_program() -> &'static str {
73 if cfg!(windows) {
74 static GS: LazyLock<&'static str> = LazyLock::new(|| {
78 ["gswin64c", "gswin32c", "mgs", "rungs"]
79 .into_iter()
80 .find(|candidate| which::which(candidate).is_ok())
81 .unwrap_or("gs")
82 });
83 *GS
84 } else {
85 "gs"
86 }
87}
88
89fn missing_tool_hint(prog: &str) -> Option<&'static str> {
97 Some(match prog {
98 "gs" | "gswin64c" | "gswin32c" | "mgs" | "rungs" | "ps2pdf" => {
99 "install Ghostscript (apt `ghostscript`, brew `ghostscript`) for PDF/PostScript conversion"
100 },
101 "mutool" => "install MuPDF (apt `mupdf-tools`, brew `mupdf-tools`) for fast PDF rendering",
102 "pdftocairo" | "pdftoppm" => {
103 "install Poppler (apt `poppler-utils`, brew `poppler`) for vector-SVG PDF conversion"
104 },
105 "convert" | "magick" => {
106 "install ImageMagick (apt `imagemagick`, brew `imagemagick`) for raster image conversion"
107 },
108 "dvisvgm" => {
109 "install dvisvgm (apt `dvisvgm`, brew `texlive`) for vector-SVG LaTeX-image output"
110 },
111 "dvipng" => "install dvipng (apt `dvipng`, brew `texlive`) for raster LaTeX-image output",
112 "latex" | "pdflatex" | "kpsewhich" | "tftopl" => {
113 "install TeX Live (apt `texlive-latex-base`, brew `texlive` / MacTeX) — the TeX ecosystem \
114 must be present at runtime"
115 },
116 _ => return None,
117 })
118}
119
120static SVG_CONVERT_TIMEOUT_SECS: LazyLock<Option<u64>> = LazyLock::new(|| {
132 std::env::var("LATEXML_SVG_CONVERT_TIMEOUT_SECS")
133 .ok()
134 .and_then(|s| s.parse::<u64>().ok())
135 .filter(|&n| n > 0)
136});
137
138const SVG_PPI: (f64, f64) = (96.0, 96.0);
140
141static CONVERT_TIMEOUT_SECS: LazyLock<Option<u64>> = LazyLock::new(|| {
145 std::env::var("LATEXML_CONVERT_TIMEOUT_SECS")
146 .ok()
147 .and_then(|s| s.parse::<u64>().ok())
148 .filter(|&n| n > 0)
149});
150
151#[derive(Debug, Clone)]
153pub struct TypeProperties {
154 pub destination_type: Option<String>,
155 pub transparent: bool,
156 pub prescale: bool,
157 pub ncolors: Option<String>,
158 pub quality: Option<u32>,
159 pub unit: String,
160 pub raster: Option<bool>,
161 pub autocrop: bool,
162 pub desirability: u32,
163}
164
165impl Default for TypeProperties {
166 fn default() -> Self {
167 TypeProperties {
168 destination_type: None,
169 transparent: false,
170 prescale: false,
171 ncolors: None,
172 quality: None,
173 unit: "pixel".to_string(),
174 raster: None,
175 autocrop: false,
176 desirability: 0,
177 }
178 }
179}
180
181#[derive(Clone)]
183struct ConvertJob {
184 job_id: usize,
185 source: String,
186 digest: Option<crate::graphics_cache::SourceDigest>,
188 page: Option<u32>,
189 rel_dest: String,
190 abs_dest_str: String,
191 svg_paths: Option<(String, String)>,
196 copy_source: bool,
199 ops: Vec<GraphicxOp>,
201 density: u32,
204 ppi: (f64, f64),
207 sizing: Vec<GraphicxOp>,
210 dpi: u32,
211}
212
213#[derive(Clone)]
215struct ConvertOutcome {
216 job_id: usize,
217 imagesrc: Option<String>,
219 raw_dims: Option<(u32, u32)>,
222 ppi: (f64, f64),
224}
225
226enum Plan {
228 NotFound { idx: usize, graphic: String },
230 Copy {
232 idx: usize,
233 source: String,
234 options: String,
235 rel: String,
237 copy: bool,
239 },
240 Convert {
242 idx: usize,
243 options: String,
244 job_id: usize,
245 },
246}
247
248struct PageDirs {
250 search_paths: Vec<String>,
251 source_dir: String,
252 dest_dir: String,
253 site_dir: String,
254 cache_dir: Option<String>,
256}
257
258struct PagePlan {
260 plans: Vec<Plan>,
261 jobs: Vec<ConvertJob>,
263 known: Vec<ConvertOutcome>,
265}
266
267enum NodeDesc {
269 NotFound(String),
270 Copy {
271 source: String,
272 options: String,
273 request: Box<Request>,
274 },
275 Convert(Box<ConvertDesc>),
276}
277
278struct ConvertDesc {
280 source: String,
281 options: String,
282 digest: Option<crate::graphics_cache::SourceDigest>,
283 page: Option<u32>,
284 needs_conversion: bool,
285 ops: Vec<GraphicxOp>,
286 drawn: bool,
289 sizing: Vec<GraphicxOp>,
291 request: Request,
292}
293
294impl NodeDesc {
295 fn request(&self) -> Option<&Request> {
296 match self {
297 NodeDesc::NotFound(_) => None,
298 NodeDesc::Copy { request, .. } => Some(request.as_ref()),
299 NodeDesc::Convert(desc) => Some(&desc.request),
300 }
301 }
302}
303
304#[derive(Default)]
308struct ResourceNames {
309 prefix: Option<String>,
311 cache: Option<DocCache>,
313 planned: HashMap<(String, String), ResourceName>,
316 pending: Vec<PendingPage>,
318 planning: bool,
320 copies: HashMap<(String, String), String>,
322 converted: HashMap<(String, String), (ConvertJob, Option<ConvertOutcome>)>,
325 digests: HashMap<String, Option<crate::graphics_cache::SourceDigest>>,
327}
328
329struct PendingPage {
331 cache: DocCache,
332 dirs: PageDirs,
333 requests: Vec<Request>,
334}
335
336impl ResourceNames {
337 fn digest(&mut self, source: &str) -> Option<crate::graphics_cache::SourceDigest> {
338 self
339 .digests
340 .entry(source.to_string())
341 .or_insert_with(|| Graphics::digest_file_content(source))
342 .clone()
343 }
344}
345
346pub struct Graphics {
350 name: String,
351 dpi: Option<u32>,
352 magnify: f64,
353 zoomout: f64,
354 trivial_scaling: bool,
355 graphics_types: Vec<String>,
356 type_properties: HashMap<String, TypeProperties>,
357 background: String,
358 svg_threshold_kb: u32,
365 cache_policy: crate::graphics_cache::CachePolicy,
370 names: ResourceNames,
371}
372
373impl Graphics {
374 const DEFAULT_RASTER_DENSITY: u32 = 120;
384 const MAX_RASTER_DIMENSION_PX: u32 = 2048;
385
386 pub fn new(dpi: Option<u32>, trivial_scaling: bool) -> Self {
387 let mut type_properties = HashMap::default();
388
389 for ext in &["ai", "pdf", "ps", "eps", "epsi", "epsf"] {
399 type_properties.insert(ext.to_string(), TypeProperties {
400 destination_type: Some("png".to_string()),
401 transparent: true,
402 prescale: true,
403 ncolors: Some("400%".to_string()),
404 quality: Some(90),
405 unit: "point".to_string(),
406 ..Default::default()
407 });
408 }
409 for ext in &["jpg", "jpeg"] {
410 type_properties.insert(ext.to_string(), TypeProperties {
411 destination_type: Some(ext.to_string()),
412 ncolors: Some("400%".to_string()),
413 unit: "pixel".to_string(),
414 ..Default::default()
415 });
416 }
417 type_properties.insert("gif".to_string(), TypeProperties {
418 destination_type: Some("gif".to_string()),
419 transparent: true,
420 ncolors: Some("400%".to_string()),
421 unit: "pixel".to_string(),
422 ..Default::default()
423 });
424 type_properties.insert("png".to_string(), TypeProperties {
425 destination_type: Some("png".to_string()),
426 transparent: true,
427 ncolors: Some("400%".to_string()),
428 unit: "pixel".to_string(),
429 ..Default::default()
430 });
431 type_properties.insert("svg".to_string(), TypeProperties {
432 destination_type: Some("svg".to_string()),
433 raster: Some(false),
434 desirability: 11,
435 ..Default::default()
436 });
437
438 Graphics {
439 name: "Graphics".to_string(),
440 dpi,
441 magnify: 1.0,
442 zoomout: 1.0,
443 trivial_scaling,
444 graphics_types: vec![
445 "svg",
446 "png",
447 "gif",
448 "jpg",
449 "jpeg",
450 "eps",
451 "epsi",
452 "epsf",
453 "ps",
454 "postscript",
455 "ai",
456 "pdf",
457 ]
458 .into_iter()
459 .map(String::from)
460 .collect(),
461 type_properties,
462 background: "#FFFFFF".to_string(),
463 svg_threshold_kb: 0,
464 cache_policy: crate::graphics_cache::CachePolicy::default(),
465 names: ResourceNames::default(),
466 }
467 }
468
469 #[must_use]
471 pub fn with_resource_prefix(mut self, prefix: &str) -> Self {
472 self.names.prefix = Some(prefix.to_string());
473 self
474 }
475
476 #[must_use]
486 pub fn with_cache_policy(mut self, policy: crate::graphics_cache::CachePolicy) -> Self {
487 self.cache_policy = policy;
488 self
489 }
490
491 pub fn with_svg_threshold_kb(mut self, kb: u32) -> Self {
496 self.svg_threshold_kb = kb;
497 self
498 }
499
500 fn find_graphic_file(
505 &self,
506 _doc: &PostDocument,
507 node: &Node,
508 search_paths: &[String],
509 ours: &dyn Fn(&str) -> bool,
510 ) -> Option<String> {
511 let source = node.get_attribute("graphic")?;
512
513 if let Some(candidates) = node.get_attribute("candidates") {
516 let mut best: Option<(String, (bool, i32))> = None;
518 for path in candidates.split(',') {
519 let path = path.trim();
520 if path.is_empty() {
521 continue;
522 }
523 let resolved = if readable(path) {
525 Some(path.to_string())
526 } else {
527 search_paths.iter().find_map(|sp| {
528 let candidate = format!("{}/{}", sp, path);
529 if readable(&candidate) {
530 Some(candidate)
531 } else {
532 None
533 }
534 })
535 };
536 if let Some(resolved_path) = resolved {
537 let ext = Path::new(&resolved_path)
538 .extension()
539 .and_then(|e| e.to_str())
540 .unwrap_or("")
541 .to_lowercase();
542 if !ext.is_empty() && !self.graphics_types.iter().any(|t| t == &ext) {
555 continue;
556 }
557 let props = self.type_properties.get(&ext);
558 let d = props.map(|p| p.desirability as i32).unwrap_or(0);
559 let is_same_type = props
560 .and_then(|p| p.destination_type.as_ref())
561 .map(|dt| dt == &ext)
562 .unwrap_or(false);
563 let desirability = (!ours(&resolved_path), if is_same_type { 10 } else { d });
564 if best.as_ref().is_none_or(|(_, bd)| desirability > *bd) {
565 best = Some((resolved_path, desirability));
566 }
567 }
568 }
569 if let Some((path, _)) = best {
570 return Some(path);
571 }
572 }
573
574 let path = Path::new(&source);
576 let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or(&source);
577 let dir = path.parent().and_then(|p| p.to_str()).unwrap_or("");
578
579 let file_base = if dir.is_empty() {
580 name.to_string()
581 } else {
582 format!("{}/{}", dir, name)
583 };
584
585 let mut best_desirability = (false, -1);
587 let mut best_path: Option<String> = None;
588
589 let types: Vec<String> = self
590 .graphics_types
591 .iter()
592 .flat_map(|t| vec![t.clone(), t.to_uppercase()])
593 .collect();
594
595 for search_path in search_paths {
596 let candidate = if search_path.is_empty() {
598 source.clone()
599 } else {
600 format!("{}/{}", search_path, source)
601 };
602 if readable(&candidate) {
603 let ext = Path::new(&candidate)
604 .extension()
605 .and_then(|e| e.to_str())
606 .unwrap_or("")
607 .to_lowercase();
608 let props = self.type_properties.get(&ext);
609 let d = (
610 !ours(&candidate),
611 props.map(|p| p.desirability as i32).unwrap_or(5),
612 );
613 if d > best_desirability {
614 best_desirability = d;
615 best_path = Some(candidate);
616 }
617 }
618 for ext in &types {
620 let candidate = format!("{}/{}.{}", search_path, file_base, ext);
621 if readable(&candidate) {
622 let props = self.type_properties.get(&ext.to_lowercase());
623 let d = props.map(|p| p.desirability as i32).unwrap_or(0);
624 let is_same_type = props
625 .and_then(|p| p.destination_type.as_ref())
626 .map(|dt| dt == &ext.to_lowercase())
627 .unwrap_or(false);
628 let desirability = (!ours(&candidate), if is_same_type { 10 } else { d });
629 if desirability > best_desirability {
630 best_desirability = desirability;
631 best_path = Some(candidate);
632 }
633 }
634 }
635 }
636 if best_path.is_some() {
637 return best_path;
638 }
639
640 for sp in std::iter::once(String::new()).chain(search_paths.iter().cloned()) {
648 let cand = if sp.is_empty() {
649 source.clone()
650 } else {
651 format!("{}/{}", sp, source)
652 };
653 if let Some(found) = Self::casefold_resolve(&cand, &source) {
654 Info!(
655 "graphics",
656 "casefold",
657 "Graphic '{}' resolved case-insensitively to '{}' (kpathsea casefold parity)",
658 source,
659 found
660 );
661 return Some(found);
662 }
663 }
664 None
665 }
666
667 fn casefold_resolve(path: &str, source: &str) -> Option<String> {
671 if !latexml_core::util::pathname::read_allowed(path) {
672 return None;
673 }
674 let p = Path::new(path);
675 if p.exists() {
676 return Some(path.to_string());
677 }
678 let parent = match p.parent() {
679 Some(d) if !d.as_os_str().is_empty() => d,
680 _ => Path::new("."),
681 };
682 let want = p.file_name()?.to_str()?;
683 let mut hit: Option<String> = None;
684 for entry in std::fs::read_dir(parent).ok()? {
685 let entry = entry.ok()?;
686 let name = entry.file_name();
687 let Some(name) = name.to_str() else { continue };
688 if name.eq_ignore_ascii_case(want) && entry.path().is_file() {
689 if hit.is_some() {
690 return None; }
692 hit = Some(entry.path().to_string_lossy().to_string());
693 }
694 }
695 if hit
696 .as_deref()
697 .is_some_and(|hit| !latexml_core::util::pathname::read_allowed(hit))
698 {
699 latexml_core::util::pathname::refuse(source);
700 return None;
701 }
702 hit
703 }
704
705 fn set_graphic_src(node: &mut Node, src: &str, width: Option<u32>, height: Option<u32>) {
709 let src = match src.split('/').next() {
711 Some(first) if first.contains(':') => format!("./{src}"),
712 _ => src.to_string(),
713 };
714 node.set_attribute("imagesrc", &src).ok();
715 if let Some(w) = width {
717 node.set_attribute("imagewidth", &w.to_string()).ok();
718 }
719 if let Some(h) = height {
720 node.set_attribute("imageheight", &h.to_string()).ok();
721 }
722 if let (Some(w), Some(h)) = (width, height) {
724 let class = if w as f64 > 1.24 * h as f64 {
725 "ltx_img_landscape"
726 } else if h as f64 > 1.24 * w as f64 {
727 "ltx_img_portrait"
728 } else {
729 "ltx_img_square"
730 };
731 let existing = node.get_attribute("class").unwrap_or_default();
732 let new_class = if existing.is_empty() {
733 class.to_string()
734 } else {
735 format!("{} {}", existing, class)
736 };
737 node.set_attribute("class", &new_class).ok();
738 let ar = format!("aspect-ratio:{w}/{h}");
747 let cssstyle = match node.get_attribute("cssstyle") {
748 Some(s) if !s.is_empty() => format!("{s};{ar}"),
749 _ => ar,
750 };
751 node.set_attribute("cssstyle", &cssstyle).ok();
752 }
753 }
754
755 fn find_graphics_paths(&self, doc: &PostDocument) -> Vec<String> {
757 use std::sync::LazyLock;
768 static GRAPHICSPATH_RE: LazyLock<regex::Regex> =
769 LazyLock::new(|| regex::Regex::new(r#"^\s*graphicspath\s*=\s*[\"'](.*?)[\"']\s*$"#).unwrap());
770 let mut paths = Vec::new();
771 for pi in doc.findnodes("//processing-instruction('latexml')") {
772 let text = pi.get_content();
773 if let Some(cap) = GRAPHICSPATH_RE.captures(&text)
774 && latexml_core::util::pathname::search_dir_allowed(&cap[1], &cap[1])
775 {
776 paths.push(cap[1].to_string());
777 }
778 }
779 paths.extend(doc.get_search_paths().iter().cloned());
780 paths
781 }
782
783 fn get_parameter(&self, doc: &PostDocument, param: &str) -> Option<f64> {
788 let direct_re = regex::Regex::new(&format!(
789 r#"^\s*{}\s*=\s*[\"']?([\d.]+)[\"']?\s*$"#,
790 regex::escape(param)
791 ))
792 .ok()?;
793 let options_re =
794 regex::Regex::new(r#"package\s*=\s*[\"']latexml[\"'].*options\s*=\s*[\"'](.*?)[\"']"#)
795 .ok()?;
796 let param_in_options_re =
797 regex::Regex::new(&format!(r#"\b{}\s*=\s*([\d.]+)"#, regex::escape(param))).ok()?;
798
799 for pi in doc.findnodes("//processing-instruction('latexml')") {
800 let text = pi.get_content();
801 if let Some(cap) = direct_re.captures(&text) {
802 return cap[1].parse().ok();
803 }
804 if let Some(cap) = options_re.captures(&text) {
805 if let Some(inner) = param_in_options_re.captures(&cap[1]) {
806 return inner[1].parse().ok();
807 }
808 }
809 }
810 None
811 }
812
813 fn effective_dpi(&self, doc: &PostDocument) -> u32 {
817 let dpi = self
818 .get_parameter(doc, "DPI")
819 .map(|v| v as u32)
820 .or(self.dpi)
821 .unwrap_or(96);
822 let magnify = self.get_parameter(doc, "magnify").unwrap_or(self.magnify);
823 let zoomout = self.get_parameter(doc, "zoomout").unwrap_or(self.zoomout);
824 ((dpi as f64) * magnify / zoomout) as u32
825 }
826
827 fn read_image_dimensions(path: &str) -> Option<(u32, u32)> {
830 match imagesize::size(path) {
831 Ok(dim) => Some((dim.width as u32, dim.height as u32)),
832 Err(_) => None,
833 }
834 }
835
836 fn read_source_dimensions(path: &str) -> Option<(u32, u32)> {
846 let is_svg = Path::new(path)
847 .extension()
848 .and_then(|e| e.to_str())
849 .is_some_and(|e| e.eq_ignore_ascii_case("svg"));
850 if is_svg {
851 Self::read_svg_dimensions(path)
852 } else {
853 Self::read_image_dimensions(path)
854 }
855 }
856
857 fn apply_graphicx_transforms(raw_w: u32, raw_h: u32, options: &str, dpi: u32) -> (u32, u32) {
885 let ops = latexml_core::util::image::parse_graphicx_options(options);
886 Self::apply_graphicx_op_list(raw_w, raw_h, (72.0, 72.0), &ops, dpi)
887 }
888
889 fn apply_graphicx_op_list(
893 raw_w: u32,
894 raw_h: u32,
895 ppi: (f64, f64),
896 ops: &[GraphicxOp],
897 dpi: u32,
898 ) -> (u32, u32) {
899 let dpi = dpi as f64;
900 let (w, h) = latexml_core::util::image::apply_graphicx_ops(
901 raw_w as f64 * dpi / ppi.0,
902 raw_h as f64 * dpi / ppi.1,
903 ops,
904 dpi / 72.0,
905 true,
906 );
907 (w.round().max(1.0) as u32, h.round().max(1.0) as u32)
909 }
910
911 fn digest_file_content(path: &str) -> Option<crate::graphics_cache::SourceDigest> {
922 crate::graphics_cache::SourceDigest::of_file(Path::new(path))
923 }
924
925 fn physical_ops(options: &str) -> Vec<GraphicxOp> {
930 latexml_core::util::image::parse_graphicx_options(options)
931 .into_iter()
932 .filter(|op| match op {
933 GraphicxOp::Trim { l, b, r, t } => [l, b, r, t].iter().any(|v| **v > 0.0),
935 GraphicxOp::Clip { .. } => true,
936 GraphicxOp::Rotate(angle) => angle.abs() > 0.5,
937 _ => false,
938 })
939 .collect()
940 }
941
942 fn crop_svg(text: &str, op: &GraphicxOp) -> Result<Option<String>, String> {
951 use latexml_core::util::image::{svg_attr_value, svg_root_tag};
952 let tag = svg_root_tag(text).ok_or("no <svg> root")?;
953 let view: Vec<f64> = svg_attr_value(tag, "viewBox")
954 .ok_or("no viewBox")?
955 .split(|c: char| c.is_whitespace() || c == ',')
956 .filter(|v| !v.is_empty())
957 .filter_map(|v| v.parse().ok())
958 .collect();
959 let [vx, vy, vw, vh] = view[..] else {
960 return Err("unreadable viewBox".to_string());
961 };
962 let (x0, y0, x1, y1) = match *op {
964 GraphicxOp::Trim { l, b, r, t } => (l.max(0.0), t.max(0.0), vw - r.max(0.0), vh - b.max(0.0)),
965 GraphicxOp::Clip { l, b, r, t } => {
966 (l.max(0.0), (vh - t).max(0.0), r.min(vw), (vh - b).min(vh))
967 },
968 _ => return Ok(None),
969 };
970 if x1 - x0 <= 0.0 || y1 - y0 <= 0.0 {
971 return Err("the box keeps nothing".to_string());
972 }
973 if x0 <= 0.0 && y0 <= 0.0 && x1 >= vw && y1 >= vh {
974 return Ok(None);
975 }
976 let number = |v: f64| {
977 let v = format!("{v:.4}");
978 v.trim_end_matches('0').trim_end_matches('.').to_string()
979 };
980 let scaled = |name: &str, ratio: f64| -> Option<String> {
982 let raw = svg_attr_value(tag, name)?.trim();
983 let split = raw
984 .find(|c: char| c.is_ascii_alphabetic() || c == '%')
985 .unwrap_or(raw.len());
986 let (num, unit) = raw.split_at(split);
987 if unit == "%" {
988 return None;
989 }
990 Some(format!(
991 "{}{unit}",
992 number(num.parse::<f64>().ok()? * ratio)
993 ))
994 };
995 let width = scaled("width", (x1 - x0) / vw).ok_or("no usable width")?;
996 let height = scaled("height", (y1 - y0) / vh).ok_or("no usable height")?;
997 let view_box = [vx + x0, vy + y0, x1 - x0, y1 - y0].map(number).join(" ");
998 Self::with_svg_root_attrs(text, &[
999 ("viewBox", view_box),
1000 ("width", width),
1001 ("height", height),
1002 ])
1003 .map(Some)
1004 }
1005
1006 fn size_svg(text: &str, width: u32, height: u32, stretch: bool) -> Result<String, String> {
1010 use latexml_core::util::image::{svg_attr_len_px, svg_attr_value, svg_root_tag};
1011 let tag = svg_root_tag(text).ok_or("no <svg> root")?;
1012 let mut attrs = vec![("width", width.to_string()), ("height", height.to_string())];
1013 if stretch {
1014 attrs.push(("preserveAspectRatio", "none".to_string()));
1015 }
1016 if svg_attr_value(tag, "viewBox").is_none() {
1017 let w = svg_attr_len_px(tag, "width").ok_or("no viewBox and no usable width")?;
1018 let h = svg_attr_len_px(tag, "height").ok_or("no viewBox and no usable height")?;
1019 attrs.push(("viewBox", format!("0 0 {w} {h}")));
1020 }
1021 Self::with_svg_root_attrs(text, &attrs)
1022 }
1023
1024 fn with_svg_root_attrs(text: &str, attrs: &[(&str, String)]) -> Result<String, String> {
1026 use latexml_core::util::image::{svg_attr_value, svg_root_tag};
1027 let tag = svg_root_tag(text).ok_or("no <svg> root")?;
1028 let at = tag.as_ptr() as usize - text.as_ptr() as usize;
1029 let mut new_tag = tag.to_string();
1030 for (name, value) in attrs {
1031 match svg_attr_value(&new_tag, name) {
1032 Some(old) => {
1033 let start = old.as_ptr() as usize - new_tag.as_ptr() as usize;
1034 new_tag.replace_range(start..start + old.len(), value);
1035 },
1036 None => {
1037 let end = new_tag.trim_end().trim_end_matches('/').trim_end().len();
1038 new_tag.insert_str(end, &format!(r#" {name}="{value}""#));
1039 },
1040 }
1041 }
1042 Ok(format!(
1043 "{}{new_tag}{}",
1044 &text[..at],
1045 &text[at + tag.len()..]
1046 ))
1047 }
1048
1049 fn transform_raster_inplace(
1061 dest: &str,
1062 ops: &[GraphicxOp],
1063 px_per_bp: f64,
1064 ) -> Result<Option<(u32, u32)>, String> {
1065 take_converter_diag(); let (w, h) = Self::read_image_dimensions(dest)
1067 .ok_or_else(|| format!("couldn't read the size of {dest}"))?;
1068 let crop = ops
1069 .iter()
1070 .find_map(|op| latexml_core::util::image::graphicx_crop_rect(w, h, op, px_per_bp));
1071 let angle: f64 = ops
1072 .iter()
1073 .map(|op| {
1074 if let GraphicxOp::Rotate(a) = op {
1075 *a
1076 } else {
1077 0.0
1078 }
1079 })
1080 .sum();
1081 if crop.is_none() && angle.abs() <= 0.5 {
1082 return Ok(None);
1083 }
1084 let staged = crate::writer::Staged::beside(Path::new(dest));
1086 let tmp = staged.path();
1087 let mut cmd = std::process::Command::new(im_convert_program());
1088 cmd.arg(dest);
1089 if let Some((x, y, cw, ch)) = crop {
1090 cmd
1093 .arg("+repage")
1094 .arg("-crop")
1095 .arg(format!("{cw}x{ch}+{x}+{y}"))
1096 .arg("+repage");
1097 }
1098 if angle.abs() > 0.5 {
1099 cmd.arg("-rotate").arg(format!("{}", -angle));
1100 }
1101 cmd.arg(tmp);
1102 let timeout = std::time::Duration::from_secs(Self::convert_timeout_secs());
1103 let ran = Self::run_with_timeout(cmd, timeout)
1104 .map(|status| status.success())
1105 .unwrap_or(false);
1106 if !ran || !tmp.exists() || staged.install(Path::new(dest)).is_err() {
1107 let why = take_converter_diag().unwrap_or_else(|| "no converter diagnostic".to_string());
1108 return Err(format!(
1109 "`{}` could not crop or turn {dest}: {why}",
1110 im_convert_program()
1111 ));
1112 }
1113 Ok(crop.map(|(_, _, cw, ch)| (cw, ch)))
1114 }
1115
1116 fn page_dirs(&self, doc: &PostDocument) -> PageDirs {
1119 let mut search_paths = self.find_graphics_paths(doc);
1120 search_paths.extend(doc.get_search_paths().iter().cloned());
1121 let source_dir = doc.get_source_directory().to_string();
1123 if !source_dir.is_empty() && !search_paths.contains(&source_dir) {
1124 search_paths.push(source_dir.clone());
1125 }
1126 if !search_paths.iter().any(|p| p == ".") && latexml_core::util::pathname::cwd_allowed() {
1128 search_paths.push(".".to_string());
1129 }
1130 let dest_dir = doc.get_destination_directory().unwrap_or(".").to_string();
1131 let site_dir = doc.get_site_directory().unwrap_or(&dest_dir).to_string();
1132 PageDirs {
1133 search_paths,
1134 source_dir,
1135 dest_dir,
1136 site_dir,
1137 cache_dir: doc.get_destination_directory().map(String::from),
1138 }
1139 }
1140
1141 pub fn plan_names(&mut self, doc: &PostDocument) -> bool {
1147 let nodes = self.to_process(doc);
1148 if nodes.is_empty() {
1149 return false;
1150 }
1151 let dirs = self.page_dirs(doc);
1152 let mut names = std::mem::take(&mut self.names);
1153 let requests = self
1154 .describe(doc, &nodes, &dirs, &mut names, self.effective_dpi(doc))
1155 .iter()
1156 .filter_map(|desc| desc.request().cloned())
1157 .collect();
1158 let cache = names.cache.clone().unwrap_or_else(|| doc.cache().clone());
1159 names.pending.push(PendingPage { cache, dirs, requests });
1160 names.planning = true;
1161 self.names = names;
1162 true
1163 }
1164
1165 pub fn planned(&self) -> bool { self.names.planning }
1167
1168 pub fn commit_names(&mut self) {
1171 let names = &mut self.names;
1172 names.planning = true;
1173 let pending = std::mem::take(&mut names.pending);
1174 let prefix = names.prefix.clone().unwrap_or_else(|| "x".to_string());
1175 let mut done: Vec<String> = Vec::new();
1176 for first in &pending {
1177 let dir = &first.dirs.dest_dir;
1178 if done.contains(dir) {
1179 continue;
1180 }
1181 done.push(dir.clone());
1182 let pages: Vec<Vec<Request>> = pending
1183 .iter()
1184 .filter(|p| p.dirs.dest_dir == *dir)
1185 .map(|p| p.requests.clone())
1186 .collect();
1187 let resolved = Self::resolve_names(
1188 &first.cache,
1189 &first.dirs,
1190 &prefix,
1191 &pages,
1192 self.cache_policy,
1193 );
1194 for (requests, resolved) in pages.iter().zip(resolved) {
1195 for (request, resolved) in requests.iter().zip(resolved) {
1196 names
1197 .planned
1198 .insert((dir.clone(), request.key.clone()), resolved.name);
1199 }
1200 }
1201 }
1202 }
1203
1204 pub fn planned_names(&self) -> Vec<(String, String, String, Option<String>)> {
1206 let mut list: Vec<_> = self
1207 .names
1208 .planned
1209 .iter()
1210 .map(|((dir, key), name)| {
1211 (
1212 dir.clone(),
1213 key.clone(),
1214 name.dest.clone(),
1215 name.alt.clone(),
1216 )
1217 })
1218 .collect();
1219 list.sort();
1220 list
1221 }
1222
1223 #[must_use]
1225 pub fn with_planned_names(mut self, list: Vec<(String, String, String, Option<String>)>) -> Self {
1226 self.names.planning = true;
1227 self.names.planned = list
1228 .into_iter()
1229 .map(|(dir, key, dest, alt)| ((dir, key), ResourceName { dest, alt }))
1230 .collect();
1231 self
1232 }
1233
1234 #[must_use]
1237 pub fn with_doc_cache(mut self, cache: DocCache) -> Self {
1238 self.names.cache = Some(cache);
1239 self
1240 }
1241
1242 fn describe(
1245 &self,
1246 doc: &PostDocument,
1247 nodes: &[Node],
1248 dirs: &PageDirs,
1249 names: &mut ResourceNames,
1250 dpi: u32,
1251 ) -> Vec<NodeDesc> {
1252 let PageDirs {
1253 search_paths,
1254 source_dir,
1255 dest_dir,
1256 site_dir,
1257 ..
1258 } = dirs;
1259 let mut descs = Vec::with_capacity(nodes.len());
1260 let cache = names.cache.clone().unwrap_or_else(|| doc.cache().clone());
1261 let ours = |path: &str| Self::our_output(&cache, dirs, path);
1262 for node in nodes {
1263 let options = node.get_attribute("options").unwrap_or_default();
1264 let Some(source) = self.find_graphic_file(doc, node, search_paths, &ours) else {
1265 let graphic = node
1266 .get_attribute("graphic")
1267 .unwrap_or_else(|| "none".to_string());
1268 descs.push(NodeDesc::NotFound(graphic));
1269 continue;
1270 };
1271 let src_ext = Path::new(&source)
1272 .extension()
1273 .and_then(|e| e.to_str())
1274 .unwrap_or("")
1275 .to_lowercase();
1276 const SINGLE_PAGE: &[&str] = &["svg", "png", "jpg", "jpeg"];
1278 let page =
1279 Self::parse_page_option(&options).filter(|_| !SINGLE_PAGE.contains(&src_ext.as_str()));
1280 let props = self.type_properties.get(&src_ext).cloned();
1281 const WEB_NATIVE: &[&str] = &["svg", "png", "gif", "jpg", "jpeg"];
1293 let dest_type = props
1294 .as_ref()
1295 .and_then(|p| p.destination_type.as_ref())
1296 .cloned()
1297 .unwrap_or_else(|| {
1298 if WEB_NATIVE.contains(&src_ext.as_str()) {
1299 src_ext.clone()
1300 } else {
1301 "png".to_string()
1302 }
1303 });
1304 let needs_conversion = dest_type != src_ext;
1305 let has_page = page.is_some();
1306 let raster = props.as_ref().and_then(|p| p.raster).unwrap_or(true);
1313 let drawn = match latexml_core::util::image::graphic_content(Path::new(&source)) {
1317 Some(GraphicContent::Pdf | GraphicContent::PostScript) => true,
1318 Some(GraphicContent::Raster) => false,
1319 None => props.as_ref().is_some_and(|p| p.unit == "point"),
1320 };
1321 let ops = if needs_conversion || raster {
1322 Self::physical_ops(&options)
1323 } else {
1324 Vec::new()
1325 };
1326 let transform = !ops.is_empty();
1327 let made = if transform {
1331 format!("{ops:?}")
1332 } else {
1333 String::new()
1334 };
1335 let rel = latexml_core::util::pathname::relative(&source, source_dir);
1338 let owned_source = {
1340 use latexml_core::util::pathname::{absolute, relative};
1341 relative(&absolute(&source), &absolute(dest_dir))
1342 };
1343 let digest = names.digest(&source);
1344 let identity = digest.as_ref().map_or_else(
1345 || format!("path:{source}"),
1346 |d| d.content().iter().map(|b| format!("{b:02x}")).collect(),
1347 );
1348 let key = format!("LaTeXML::Post::Graphics:{rel}.{dest_type}|{options}|{identity}");
1349 if needs_conversion || has_page || transform {
1350 let turned = ops.iter().any(|op| matches!(op, GraphicxOp::Rotate(_)));
1353 let svg_alt = !turned && Self::should_try_svg_path(&source, self.svg_threshold_kb);
1354 let mut sizing: Vec<GraphicxOp> = if svg_alt {
1360 latexml_core::util::image::parse_graphicx_options(&options)
1361 .into_iter()
1362 .filter(|op| matches!(op, GraphicxOp::Scale { .. } | GraphicxOp::ScaleTo { .. }))
1363 .collect()
1364 } else {
1365 Vec::new()
1366 };
1367 if sizing.iter().any(|op| match *op {
1368 GraphicxOp::Scale { x, y } => x <= 0.0 || y <= 0.0,
1369 GraphicxOp::ScaleTo { w, h, .. } => {
1370 w.is_some_and(|w| w <= 0.0) || h.is_some_and(|h| h <= 0.0)
1371 },
1372 _ => false,
1373 }) {
1374 sizing.clear();
1375 }
1376 let sized = if sizing.is_empty() {
1377 String::new()
1378 } else {
1379 format!("|{sizing:?}@{dpi}")
1380 };
1381 let stem = Path::new(&source)
1387 .file_stem()
1388 .and_then(|s| s.to_str())
1389 .unwrap_or("image")
1390 .to_string();
1391 let page_key = page.map_or(String::new(), |p| p.to_string());
1392 let request = Request {
1393 key,
1394 bytes: format!("{dest_type}|{identity}|{page_key}|{made}{sized}"),
1395 owner: format!("{dest_type}|{page_key}|{made}{sized}|{owned_source}"),
1396 source: owned_source,
1397 identity,
1398 proposal: if has_page
1399 || transform
1400 || (!sizing.is_empty() && Self::beside(&source, dest_dir))
1401 {
1402 Proposal::Generated
1403 } else {
1404 Proposal::Stem(stem)
1405 },
1406 ext: dest_type,
1407 svg_alt,
1408 copy: false,
1409 output: if transform || !sizing.is_empty() {
1410 Output::Made
1411 } else {
1412 Output::Render(page)
1413 },
1414 };
1415 descs.push(NodeDesc::Convert(Box::new(ConvertDesc {
1416 source,
1417 options,
1418 digest,
1419 page,
1420 needs_conversion,
1421 ops,
1422 drawn,
1423 sizing,
1424 request,
1425 })));
1426 } else {
1427 let ext = Path::new(&source)
1428 .extension()
1429 .map(|ext| ext.to_string_lossy().into_owned())
1430 .unwrap_or_default();
1431 let request = Request {
1432 key,
1433 bytes: format!("copy|{identity}"),
1434 owner: format!("copy|{owned_source}"),
1435 source: owned_source,
1436 identity,
1437 proposal: Self::kept_path(&rel, dest_dir, site_dir)
1438 .map_or(Proposal::Generated, Proposal::Kept),
1439 ext,
1440 svg_alt: false,
1441 copy: true,
1442 output: Output::Source,
1443 };
1444 descs.push(NodeDesc::Copy {
1445 source,
1446 options,
1447 request: Box::new(request),
1448 });
1449 }
1450 }
1451 descs
1452 }
1453
1454 fn names_for(
1457 doc: &PostDocument,
1458 descs: &[NodeDesc],
1459 dirs: &PageDirs,
1460 names: &mut ResourceNames,
1461 policy: crate::graphics_cache::CachePolicy,
1462 ) -> Vec<Option<ResourceName>> {
1463 let mut out: Vec<Option<ResourceName>> = descs
1464 .iter()
1465 .map(|desc| {
1466 let request = desc.request()?;
1467 names
1468 .planned
1469 .get(&(dirs.dest_dir.clone(), request.key.clone()))
1470 .cloned()
1471 })
1472 .collect();
1473 let misses: Vec<usize> = (0..descs.len())
1474 .filter(|&i| out[i].is_none() && descs[i].request().is_some())
1475 .collect();
1476 if misses.is_empty() {
1477 return out;
1478 }
1479 let requests: Vec<Request> = misses
1480 .iter()
1481 .filter_map(|&i| descs[i].request().cloned())
1482 .collect();
1483 let planning = names.planning;
1484 let prefix = names.prefix.clone().unwrap_or_else(|| "x".to_string());
1485 let cache = names.cache.clone().unwrap_or_else(|| doc.cache().clone());
1486 let resolved = Self::resolve_names(&cache, dirs, &prefix, &[requests], policy)
1487 .into_iter()
1488 .next()
1489 .unwrap_or_default();
1490 for (&i, resolved) in misses.iter().zip(resolved) {
1491 if planning && resolved.allocated {
1492 Warn!(
1493 "unexpected",
1494 "resource_name",
1495 "Graphics: {} was not named before the pages were rendered; {} depends on the render order",
1496 descs[i].request().map_or("", |r| r.key.as_str()),
1497 resolved.name.dest
1498 );
1499 }
1500 out[i] = Some(resolved.name);
1501 }
1502 out
1503 }
1504
1505 fn plan_page(
1508 &self,
1509 doc: &PostDocument,
1510 nodes: &[Node],
1511 dirs: &PageDirs,
1512 names: &mut ResourceNames,
1513 dpi: u32,
1514 ) -> PagePlan {
1515 let descs = self.describe(doc, nodes, dirs, names, dpi);
1516 let resolved = Self::names_for(doc, &descs, dirs, names, self.cache_policy);
1517 let dest_dir = &dirs.dest_dir;
1518 let mut plans: Vec<Plan> = Vec::with_capacity(nodes.len());
1519 let mut convert_jobs: Vec<ConvertJob> = Vec::new();
1520 let mut next_job_id = 0usize;
1522 let mut convert_job_ids: HashMap<String, usize> = HashMap::default();
1523 let mut known: Vec<ConvertOutcome> = Vec::new();
1525 for (idx, (desc, name)) in descs.into_iter().zip(resolved).enumerate() {
1526 let name = name.unwrap_or_else(|| ResourceName {
1527 dest: String::new(),
1528 alt: None,
1529 });
1530 match desc {
1531 NodeDesc::NotFound(graphic) => plans.push(Plan::NotFound { idx, graphic }),
1532 NodeDesc::Copy { source, options, .. } => {
1533 let memo = (dest_dir.clone(), name.dest.clone());
1535 let (rel, copy) = match names.copies.get(&memo) {
1536 Some(rel) => (rel.clone(), false),
1537 None => {
1538 names.copies.insert(memo, name.dest.clone());
1539 (name.dest, true)
1540 },
1541 };
1542 plans.push(Plan::Copy {
1543 idx,
1544 source,
1545 options,
1546 rel,
1547 copy,
1548 });
1549 },
1550 NodeDesc::Convert(desc) => {
1551 let ConvertDesc {
1552 source,
1553 options,
1554 digest,
1555 page,
1556 needs_conversion,
1557 ops,
1558 drawn,
1559 sizing,
1560 ..
1561 } = *desc;
1562 let memo = (dest_dir.clone(), name.dest.clone());
1563 let job_id = if let Some(&job_id) = convert_job_ids.get(&name.dest) {
1564 job_id
1565 } else {
1566 let job_id = next_job_id;
1567 next_job_id += 1;
1568 convert_job_ids.insert(name.dest.clone(), job_id);
1569 match names.converted.get(&memo) {
1570 Some((_, Some(outcome))) => known.push(ConvertOutcome { job_id, ..outcome.clone() }),
1572 Some((job, None)) => convert_jobs.push(ConvertJob { job_id, ..job.clone() }),
1574 None => {
1575 let abs = |rel: &str| {
1576 PathBuf::from(dest_dir)
1577 .join(rel)
1578 .to_string_lossy()
1579 .to_string()
1580 };
1581 let svg_paths = name
1582 .alt
1583 .as_ref()
1584 .map(|rel_svg| (rel_svg.clone(), abs(rel_svg)));
1585 let density = Self::raster_density_for_source(&source);
1588 let ppi = if drawn {
1589 (density as f64, density as f64)
1590 } else {
1591 Self::raster_ppi(&source)
1592 };
1593 let job = ConvertJob {
1594 job_id,
1595 copy_source: !needs_conversion && page.is_none(),
1596 source,
1597 digest,
1598 page,
1599 abs_dest_str: abs(&name.dest),
1600 rel_dest: name.dest.clone(),
1601 svg_paths,
1602 ops,
1603 density,
1604 ppi,
1605 sizing,
1606 dpi,
1607 };
1608 names.converted.insert(memo, (job.clone(), None));
1609 convert_jobs.push(job);
1610 },
1611 }
1612 job_id
1613 };
1614 plans.push(Plan::Convert { idx, options, job_id });
1615 },
1616 }
1617 }
1618 PagePlan {
1619 plans,
1620 jobs: convert_jobs,
1621 known,
1622 }
1623 }
1624
1625 fn resolve_names(
1627 cache: &DocCache,
1628 dirs: &PageDirs,
1629 prefix: &str,
1630 pages: &[Vec<Request>],
1631 policy: crate::graphics_cache::CachePolicy,
1632 ) -> Vec<Vec<crate::resource_cache::Resolved>> {
1633 let cache_file = Path::new(&dirs.dest_dir)
1634 .join(crate::document::CACHE_FILE)
1635 .display()
1636 .to_string();
1637 let usable =
1638 |name: &ResourceName| Self::kept_path(&name.dest, &dirs.dest_dir, &dirs.site_dir).is_some();
1639 let warnings = std::cell::RefCell::new(Vec::<String>::new());
1641 let warn = |w: String| {
1642 let mut warnings = warnings.borrow_mut();
1643 if !warnings.contains(&w) {
1644 warnings.push(w);
1645 }
1646 };
1647 let digests = Digests::default();
1649 let vouch = |r: &Request, name: &ResourceName, source: &str| {
1650 Self::vouch(r, name, source, dirs, &cache_file, &warn, &digests)
1651 };
1652 let file = |part: &str| PathBuf::from(Self::copy_target(&dirs.dest_dir, part));
1654 let present = |part: &str| std::fs::symlink_metadata(file(part)).is_ok();
1655 let not_owned = |r: &Request, name: &ResourceName| {
1658 std::iter::once(&name.dest).chain(&name.alt).any(|part| {
1659 present(part) && !(r.copy && part == &name.dest && Self::is_source(r, part, dirs))
1660 })
1661 };
1662 let holds_other = |r: &Request, name: &ResourceName| {
1665 std::iter::once(&name.dest).chain(&name.alt).any(|part| {
1666 present(part)
1667 && !Self::holds_output(r, &file(part), part == &name.dest, dirs, policy, &digests)
1668 })
1669 };
1670 let names = cache.with_store(dirs.cache_dir.as_deref(), |store| {
1671 let on_file = store.wants_file();
1672 store.immediate(|tx, fell_back| {
1675 warnings.borrow_mut().clear();
1676 let on_disk: Option<crate::resource_cache::OnDisk> = if fell_back {
1677 Some(&holds_other)
1678 } else if on_file {
1679 Some(¬_owned)
1680 } else {
1681 None
1682 };
1683 let checks = crate::resource_cache::Checks {
1684 prefix,
1685 usable: &usable,
1686 vouch: &vouch,
1687 on_disk,
1688 cache: &cache_file,
1689 warn: &warn,
1690 };
1691 crate::resource_cache::resolve(tx, &checks, pages)
1692 })
1693 });
1694 for w in warnings.into_inner() {
1695 Warn!("unexpected", "cache", "{}", w);
1696 }
1697 names.unwrap_or_default()
1699 }
1700
1701 fn our_output(cache: &DocCache, dirs: &PageDirs, path: &str) -> bool {
1704 use latexml_core::util::pathname::{absolute, relative};
1705 let rel = relative(&absolute(path), &absolute(&dirs.dest_dir));
1706 let entry = |key: &str| cache.lookup(dirs.cache_dir.as_deref(), &format!("_{key}_{rel}"));
1707 entry("owner").is_some() && entry("source").as_deref() != Some(rel.as_str())
1708 }
1709
1710 fn beside(source: &str, dir: &str) -> bool {
1712 let source = latexml_core::util::pathname::absolute(source);
1713 Path::new(&source)
1714 .parent()
1715 .is_some_and(|parent| latexml_core::util::pathname::same_file(parent, dir))
1716 }
1717
1718 fn is_source(r: &Request, part: &str, dirs: &PageDirs) -> bool {
1720 let (target, source) = (
1721 Self::copy_target(&dirs.dest_dir, part),
1722 Self::copy_target(&dirs.dest_dir, &r.source),
1723 );
1724 target == source || latexml_core::util::pathname::same_file(&target, &source)
1725 }
1726
1727 fn holds_output(
1730 r: &Request,
1731 path: &Path,
1732 raster: bool,
1733 dirs: &PageDirs,
1734 policy: crate::graphics_cache::CachePolicy,
1735 digests: &Digests,
1736 ) -> bool {
1737 use latexml_core::util::pathname::absolute;
1738 let Some(held) = digests.content(path) else {
1739 return false;
1740 };
1741 let source = absolute(&Path::new(&dirs.dest_dir).join(&r.source).to_string_lossy());
1742 match r.output {
1743 Output::Source => hex(&held) == r.identity,
1744 Output::Render(page) => {
1745 let key = crate::graphics_cache::RenderKey {
1746 page,
1747 density: if raster {
1748 Self::raster_density_for_source(&source)
1749 } else {
1750 0
1751 },
1752 ext: if raster {
1753 ext_from_path(&path.to_string_lossy())
1754 } else {
1755 "svg"
1756 },
1757 };
1758 let digest = digests.of(Path::new(&source));
1759 crate::graphics_cache::cached_output(policy, &source, digest.as_ref(), key)
1760 .and_then(|cached| digests.content(&cached))
1761 .is_some_and(|cached| cached == held)
1762 },
1763 Output::Made => false,
1764 }
1765 }
1766
1767 fn vouch(
1773 r: &Request,
1774 name: &ResourceName,
1775 source: &str,
1776 dirs: &PageDirs,
1777 cache_file: &str,
1778 warn: &dyn Fn(String),
1779 digests: &Digests,
1780 ) -> bool {
1781 use latexml_core::util::pathname::{absolute, relative};
1782 if source.is_empty() {
1783 return false;
1784 }
1785 let relative_path = Path::new(source).components().all(|part| {
1786 matches!(
1787 part,
1788 std::path::Component::Normal(_) | std::path::Component::ParentDir
1789 )
1790 });
1791 let abs = absolute(&Path::new(&dirs.dest_dir).join(source).to_string_lossy());
1792 let unusable = || {
1793 warn(format!(
1794 "The cache {cache_file} gives {} the source {source}, not a file relative to the destination; it is ignored",
1795 name.dest
1796 ));
1797 false
1798 };
1799 if !relative_path {
1800 return unusable();
1801 }
1802 let its_name = if r.copy {
1803 relative(&abs, &absolute(&dirs.source_dir)) == name.dest
1804 } else {
1805 Path::new(&abs)
1806 .file_stem()
1807 .is_some_and(|stem| format!("{}.{}", stem.to_string_lossy(), r.ext) == name.dest)
1808 };
1809 if !its_name {
1810 return false;
1811 }
1812 match std::fs::metadata(&abs).map(|meta| meta.is_file()) {
1813 Ok(false) => unusable(),
1814 Ok(true) => digests
1815 .content(Path::new(&abs))
1816 .is_some_and(|d| hex(&d) == r.identity),
1817 Err(_) => false,
1818 }
1819 }
1820
1821 fn kept_path(rel: &str, dest_dir: &str, site_dir: &str) -> Option<String> {
1825 use latexml_core::util::pathname::{is_contained, is_contained_resolved};
1832 let target = Self::copy_target(dest_dir, rel);
1833 ((is_contained(&target, site_dir).is_some()
1834 || is_contained_resolved(&target, site_dir).is_some())
1835 && Self::resolves_inside_site_or_dest(&target, site_dir, dest_dir))
1836 .then(|| rel.to_string())
1837 }
1838
1839 fn copy_target(dest_dir: &str, rel: &str) -> String {
1843 latexml_core::util::pathname::absolute(&PathBuf::from(dest_dir).join(rel).to_string_lossy())
1844 }
1845
1846 fn resolves_inside_site_or_dest(target: &str, site_dir: &str, dest_dir: &str) -> bool {
1852 use latexml_core::util::pathname::is_contained_resolved;
1853 is_contained_resolved(target, site_dir).is_some()
1854 || is_contained_resolved(target, dest_dir).is_some()
1855 }
1856
1857 fn copy_file(source: &str, dest_dir: &str, rel: &str) -> Option<()> {
1859 let abs_dest = PathBuf::from(Self::copy_target(dest_dir, rel));
1860 if let Some(parent) = abs_dest.parent() {
1861 std::fs::create_dir_all(parent).ok()?;
1862 }
1863 if !crate::writer::same_file(Path::new(source), &abs_dest) {
1866 crate::writer::copy_atomic(Path::new(source), &abs_dest).ok()?;
1867 }
1868 Some(())
1869 }
1870
1871 fn parse_page_option(options: &str) -> Option<u32> {
1874 for opt in options.split(',') {
1875 let opt = opt.trim();
1876 if let Some((key, val)) = opt.split_once('=') {
1877 if key.trim() == "page" {
1878 let val = val.trim().trim_matches('{').trim_matches('}');
1880 return val.parse::<u32>().ok();
1881 }
1882 }
1883 }
1884 None
1885 }
1886
1887 fn convert_image_svg(source: &str, dest: &str, page: Option<u32>) -> bool {
1905 let alias = Self::reachable_source(source);
1906 let source = Self::file_arg(
1907 alias
1908 .as_ref()
1909 .and_then(|a| a.path().to_str())
1910 .unwrap_or(source),
1911 );
1912 let source = &*source;
1913 Self::convert_image_svg_mutool(source, dest, page)
1930 || Self::convert_image_svg_pdftocairo(source, dest, page)
1931 }
1932
1933 const MAX_SVG_OUTPUT_BYTES: u64 = 8 * 1024 * 1024; fn svg_output_too_large(path: &str) -> bool {
1942 std::fs::metadata(path)
1943 .map(|md| md.len() > Self::MAX_SVG_OUTPUT_BYTES)
1944 .unwrap_or(false)
1945 }
1946 fn convert_image_svg_mutool(source: &str, dest: &str, page: Option<u32>) -> bool {
1964 let dest_path = Path::new(dest);
1965 let parent = dest_path.parent().unwrap_or_else(|| Path::new("."));
1966 let stem = crate::writer::bounded_name(
1967 dest_path
1968 .file_name()
1969 .and_then(|s| s.to_str())
1970 .unwrap_or("image"),
1971 );
1972 let tmp_dir = loop {
1975 let dir = parent.join(format!(
1976 ".{}.{}.mutool_svg",
1977 stem,
1978 Self::unique_staging_tag()
1979 ));
1980 match std::fs::create_dir(&dir) {
1981 Ok(()) => break dir,
1982 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
1983 Err(_) => return false,
1984 }
1985 };
1986 let _on_exit = latexml_core::watchdog::remove_on_exit(&tmp_dir);
1987 let tmp_actual = tmp_dir.join("page1.svg");
1988 let p1 = page.map(|p| p.max(1)).unwrap_or(1);
1989 let mut cmd = std::process::Command::new("mutool");
1990 cmd
1991 .arg("convert")
1992 .arg("-F")
1993 .arg("svg")
1994 .arg("-o")
1995 .arg(tmp_dir.join("page%d.svg"))
1996 .arg(source)
1997 .arg(p1.to_string());
1998 let timeout = std::time::Duration::from_secs(Self::svg_convert_timeout_secs());
1999 let ok = Self::run_with_timeout(cmd, timeout).is_some_and(|status| status.success())
2000 && std::fs::metadata(&tmp_actual).is_ok_and(|md| md.len() <= Self::MAX_SVG_OUTPUT_BYTES);
2001 let installed = ok && std::fs::rename(&tmp_actual, dest).is_ok();
2002 let _ = std::fs::remove_dir_all(&tmp_dir);
2003 installed
2004 }
2005
2006 fn convert_image_svg_pdftocairo(source: &str, dest: &str, page: Option<u32>) -> bool {
2012 let mut cmd = std::process::Command::new("pdftocairo");
2013 cmd.arg("-svg");
2014 if let Some(p) = page {
2015 let p1 = p.max(1);
2016 cmd
2017 .arg("-f")
2018 .arg(p1.to_string())
2019 .arg("-l")
2020 .arg(p1.to_string());
2021 } else {
2022 cmd.arg("-f").arg("1").arg("-l").arg("1");
2023 }
2024 cmd.arg(source).arg(dest);
2025 let timeout = std::time::Duration::from_secs(Self::svg_convert_timeout_secs());
2026 match Self::run_with_timeout(cmd, timeout) {
2027 Some(status) => {
2028 if !(status.success() && Path::new(dest).exists()) {
2029 let _ = std::fs::remove_file(dest);
2030 return false;
2031 }
2032 if Self::svg_output_too_large(dest) {
2033 let _ = std::fs::remove_file(dest);
2034 return false;
2035 }
2036 true
2037 },
2038 None => {
2039 let _ = std::fs::remove_file(dest);
2040 false
2041 },
2042 }
2043 }
2044
2045 fn svg_convert_timeout_secs() -> u64 { SVG_CONVERT_TIMEOUT_SECS.unwrap_or(15) }
2051
2052 fn run_with_timeout(
2063 mut cmd: std::process::Command,
2064 timeout: std::time::Duration,
2065 ) -> Option<std::process::ExitStatus> {
2066 let prog = cmd.get_program().to_string_lossy().into_owned();
2068 cmd
2073 .stdout(std::process::Stdio::null())
2074 .stderr(std::process::Stdio::piped());
2075 #[cfg(unix)]
2076 {
2077 use std::os::unix::process::CommandExt;
2078 #[cfg(target_os = "linux")]
2080 let spawner = std::process::id() as libc::pid_t;
2081 unsafe {
2084 cmd.pre_exec(move || {
2085 if libc::setsid() == -1 {
2087 let _ = libc::setpgid(0, 0);
2089 }
2090 #[cfg(target_os = "linux")]
2109 {
2110 libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL);
2111 if reparented(spawner, libc::getppid()) {
2112 libc::_exit(127);
2113 }
2114 }
2115 Ok(())
2116 });
2117 }
2118 }
2119 let mut child = match cmd.spawn() {
2120 Ok(c) => c,
2121 Err(e) => {
2122 let mut msg = format!("could not start `{prog}`: {e}");
2129 if e.kind() == std::io::ErrorKind::NotFound {
2130 if let Some(hint) = missing_tool_hint(&prog) {
2131 msg.push_str(" — ");
2132 msg.push_str(hint);
2133 }
2134 }
2135 record_converter_diag(msg);
2136 return None;
2137 },
2138 };
2139 let (stderr_tx, stderr_rx) = std::sync::mpsc::channel::<String>();
2146 let stderr_reader = child.stderr.take().and_then(|mut se| {
2152 std::thread::Builder::new()
2153 .name("gfx-stderr-drain".into())
2154 .spawn(move || {
2155 use std::io::Read;
2156 let mut kept: Vec<u8> = Vec::new();
2157 let mut chunk = [0u8; 4096];
2158 loop {
2159 match se.read(&mut chunk) {
2160 Ok(0) => break,
2161 Ok(n) => {
2162 if kept.len() < 8192 {
2163 let room = 8192 - kept.len();
2164 kept.extend_from_slice(&chunk[..n.min(room)]);
2165 }
2166 },
2167 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
2170 Err(_) => break,
2171 }
2172 }
2173 let _ = stderr_tx.send(String::from_utf8_lossy(&kept).trim().to_string());
2174 })
2175 .map_err(|e| {
2181 Warn!(
2182 "imageprocessing",
2183 "stderr_drain",
2184 "Graphics: stderr capture thread not spawned ({}); converter stderr not captured",
2185 e
2186 );
2187 })
2188 .ok()
2189 });
2190 let pid = child.id();
2191 let kill_on_exit = latexml_core::watchdog::kill_pid_on_exit(pid, true);
2192 let kill_group = || {
2193 #[cfg(unix)]
2194 {
2195 latexml_core::watchdog::signal_group_term(pid);
2200 std::thread::sleep(std::time::Duration::from_millis(200));
2201 latexml_core::watchdog::kill_pid(pid, true);
2202 }
2203 #[cfg(windows)]
2204 {
2205 latexml_core::watchdog::kill_pid(pid, true);
2210 }
2211 #[cfg(not(any(unix, windows)))]
2212 {
2213 let _ = pid;
2215 }
2216 };
2217 let start = std::time::Instant::now();
2218 let status = loop {
2219 match child.try_wait() {
2220 Ok(Some(status)) => break Some(status),
2221 Ok(None) => {
2222 if start.elapsed() >= timeout {
2223 kill_group();
2224 let _ = child.kill();
2225 let _ = child.wait();
2226 break None;
2227 }
2228 std::thread::sleep(std::time::Duration::from_millis(50));
2229 },
2230 Err(_) => {
2231 kill_group();
2232 let _ = child.kill();
2233 let _ = child.wait();
2234 break None;
2235 },
2236 }
2237 };
2238 drop(kill_on_exit);
2242 let stderr_text = if stderr_reader.is_some() {
2247 let grace = if status.is_some() {
2250 std::time::Duration::from_secs(10)
2251 } else {
2252 std::time::Duration::from_secs(2)
2253 };
2254 stderr_rx.recv_timeout(grace).unwrap_or_default()
2255 } else {
2256 String::new()
2257 };
2258 if !stderr_text.is_empty() {
2259 let flat = stderr_text.replace('\n', "; ");
2262 record_converter_diag(format!("`{prog}`: {flat}"));
2263 } else if status.map(|s| !s.success()).unwrap_or(true) {
2264 let how = match status {
2265 Some(s) => format!("exited {s}"),
2266 None => format!("timed out after {}s / killed", timeout.as_secs()),
2267 };
2268 record_converter_diag(format!("`{prog}`: {how}, no stderr"));
2269 }
2270 status
2271 }
2272
2273 fn read_svg_dimensions(path: &str) -> Option<(u32, u32)> {
2288 latexml_core::util::image::read_svg_viewport_px(Path::new(path))
2289 }
2290
2291 fn raster_ppi(source: &str) -> (f64, f64) {
2294 use latexml_core::util::image;
2295 image::read_image_dimensions(Path::new(source))
2296 .and_then(|(w, h)| image::raster_resolution_dpi(source, (f64::from(w), f64::from(h))))
2297 .unwrap_or((72.0, 72.0))
2298 }
2299
2300 fn should_try_svg_path(source: &str, threshold_kb: u32) -> bool {
2319 if !source.to_lowercase().ends_with(".pdf") {
2320 return false;
2321 }
2322 if threshold_kb > 0 {
2323 return match std::fs::metadata(source) {
2325 Ok(md) => md.len() <= (threshold_kb as u64) * 1024,
2326 Err(_) => false,
2327 };
2328 }
2329 if Self::vector_auto_detect_disabled() {
2331 return false;
2332 }
2333 let len = match std::fs::metadata(source) {
2334 Ok(md) => md.len(),
2335 Err(_) => return false,
2336 };
2337 const AUTO_MAX_BYTES: u64 = 500 * 1024;
2340 len <= AUTO_MAX_BYTES
2341 }
2342
2343 fn vector_auto_detect_disabled() -> bool {
2346 use std::sync::OnceLock;
2347 static CELL: OnceLock<bool> = OnceLock::new();
2348 *CELL.get_or_init(|| {
2349 matches!(
2350 std::env::var("LATEXML_GRAPHICS_VECTOR_AUTO_OFF")
2351 .ok()
2352 .as_deref()
2353 .map(|s| s.trim()),
2354 Some("1") | Some("true") | Some("yes")
2355 )
2356 })
2357 }
2358
2359 fn raster_density_for_source(source: &str) -> u32 {
2360 let base = std::env::var("LATEXML_RASTER_DENSITY")
2364 .ok()
2365 .and_then(|s| s.parse::<u32>().ok())
2366 .map(|d| d.clamp(50, 600))
2367 .unwrap_or(Self::DEFAULT_RASTER_DENSITY);
2368 let source_lc = source.to_lowercase();
2371 let content = latexml_core::util::image::graphic_content(Path::new(source)).or_else(|| {
2372 if [".eps", ".epsi", ".epsf", ".ps", ".ai"]
2373 .iter()
2374 .any(|ext| source_lc.ends_with(ext))
2375 {
2376 Some(GraphicContent::PostScript)
2377 } else if source_lc.ends_with(".pdf") {
2378 Some(GraphicContent::Pdf)
2379 } else {
2380 None
2381 }
2382 });
2383 let page_box = match content {
2384 Some(GraphicContent::PostScript) => read_postscript_bounding_box(source),
2385 Some(GraphicContent::Pdf) => latexml_core::util::image::read_pdf_page_box(Path::new(source)),
2386 _ => None,
2387 };
2388 let Some((w_pt, h_pt)) = page_box else {
2389 return base;
2390 };
2391 let max_pt = w_pt.max(h_pt);
2392 if max_pt <= 0.0 {
2393 return base;
2394 }
2395
2396 let max_density = ((Self::MAX_RASTER_DIMENSION_PX as f64) * 72.0 / max_pt).floor() as u32;
2397 base.min(max_density.max(1))
2398 }
2399
2400 fn postscript_is_landscape(source: &str) -> bool {
2413 let Ok(file) = std::fs::File::open(source) else {
2414 return false;
2415 };
2416 use std::io::BufRead;
2417 let reader = std::io::BufReader::new(file);
2418 for line in reader.lines().take(80).map_while(Result::ok) {
2419 if let Some(rest) = line.strip_prefix("%%Orientation:") {
2420 return rest.trim().eq_ignore_ascii_case("Landscape");
2421 }
2422 }
2423 false
2424 }
2425
2426 fn should_try_eps_pdf_path(source: &str, page: Option<u32>) -> bool {
2427 let _ = (source, page);
2445 false
2446 }
2447
2448 fn should_try_pdf_cairo_path(source: &str) -> bool { source.to_lowercase().ends_with(".pdf") }
2456
2457 fn unique_staging_tag() -> String {
2461 static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2462 let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2463 format!("{}-{}", std::process::id(), seq)
2464 }
2465
2466 fn convert_pdf_via_mutool(source: &str, dest: &str, density: u32, page: Option<u32>) -> bool {
2483 let dest_path = Path::new(dest);
2484 let parent = dest_path.parent().unwrap_or_else(|| Path::new("."));
2485 let stem = crate::writer::bounded_name(
2486 dest_path
2487 .file_name()
2488 .and_then(|s| s.to_str())
2489 .unwrap_or("image"),
2490 );
2491 let unique = Self::unique_staging_tag();
2492 let tmp = parent.join(format!(".{}.{}.mutool.png", stem, unique));
2493 let _on_exit = latexml_core::watchdog::remove_on_exit(&tmp);
2494 let timeout = std::time::Duration::from_secs(20);
2495
2496 let mut cmd = std::process::Command::new("mutool");
2497 cmd
2498 .arg("draw")
2499 .arg("-o")
2500 .arg(&tmp)
2501 .arg("-r")
2502 .arg(density.to_string())
2503 .arg("-F")
2504 .arg("png");
2505 let p1 = page.map(|p| p.max(1)).unwrap_or(1);
2506 cmd.arg(source).arg(p1.to_string());
2507
2508 let mutool_ok = Self::run_with_timeout(cmd, timeout)
2509 .map(|status| status.success())
2510 .unwrap_or(false)
2511 && tmp.exists();
2512 if !mutool_ok {
2513 let _ = std::fs::remove_file(&tmp);
2514 return false;
2515 }
2516
2517 let installed = std::fs::rename(&tmp, dest).is_ok();
2518 let _ = std::fs::remove_file(&tmp);
2519 installed
2520 }
2521
2522 fn convert_pdf_via_pdftocairo(source: &str, dest: &str, density: u32, page: Option<u32>) -> bool {
2526 let dest_path = Path::new(dest);
2527 let parent = dest_path.parent().unwrap_or_else(|| Path::new("."));
2528 let stem = crate::writer::bounded_name(
2529 dest_path
2530 .file_name()
2531 .and_then(|s| s.to_str())
2532 .unwrap_or("image"),
2533 );
2534 let unique = Self::unique_staging_tag();
2535 let tmp_prefix = parent.join(format!(".{}.{}.pdftocairo", stem, unique));
2536 let tmp_png = PathBuf::from(format!("{}.png", tmp_prefix.to_string_lossy()));
2537 let _on_exit = latexml_core::watchdog::remove_on_exit(&tmp_png);
2538 let timeout = std::time::Duration::from_secs(20);
2539
2540 let cleanup = |tmp_png: &Path| {
2541 let _ = std::fs::remove_file(tmp_png);
2542 };
2543
2544 let mut pdftocairo = std::process::Command::new("pdftocairo");
2545 pdftocairo
2546 .arg("-singlefile")
2547 .arg("-png")
2548 .arg("-r")
2549 .arg(density.to_string());
2550 if let Some(p) = page {
2552 let p1 = p.max(1);
2553 pdftocairo
2554 .arg("-f")
2555 .arg(p1.to_string())
2556 .arg("-l")
2557 .arg(p1.to_string());
2558 } else {
2559 pdftocairo.arg("-f").arg("1").arg("-l").arg("1");
2561 }
2562 pdftocairo.arg(source).arg(&tmp_prefix);
2563
2564 let cairo_ok = Self::run_with_timeout(pdftocairo, timeout)
2565 .map(|status| status.success())
2566 .unwrap_or(false)
2567 && tmp_png.exists();
2568 if !cairo_ok {
2569 cleanup(&tmp_png);
2570 return false;
2571 }
2572
2573 let installed = std::fs::rename(&tmp_png, dest).is_ok();
2574 cleanup(&tmp_png);
2575 installed
2576 }
2577
2578 fn convert_eps_via_pdf(source: &str, dest: &str, density: u32) -> bool {
2583 let dest_path = Path::new(dest);
2584 let parent = dest_path.parent().unwrap_or_else(|| Path::new("."));
2585 let stem = crate::writer::bounded_name(
2586 dest_path
2587 .file_name()
2588 .and_then(|s| s.to_str())
2589 .unwrap_or("image"),
2590 );
2591 let unique = Self::unique_staging_tag();
2592 let tmp_pdf = parent.join(format!(".{}.{}.pdf", stem, unique));
2593 let tmp_prefix = parent.join(format!(".{}.{}.pdftocairo", stem, unique));
2594 let tmp_png = PathBuf::from(format!("{}.png", tmp_prefix.to_string_lossy()));
2595 let _on_exit_pdf = latexml_core::watchdog::remove_on_exit(&tmp_pdf);
2596 let _on_exit_png = latexml_core::watchdog::remove_on_exit(&tmp_png);
2597 let timeout = std::time::Duration::from_secs(20);
2598
2599 let cleanup = |tmp_pdf: &Path, tmp_png: &Path| {
2600 let _ = std::fs::remove_file(tmp_pdf);
2601 let _ = std::fs::remove_file(tmp_png);
2602 };
2603
2604 let mut ps2pdf = std::process::Command::new("ps2pdf");
2605 ps2pdf.arg("-dEPSCrop").arg(source).arg(&tmp_pdf);
2606 let ps2pdf_ok = Self::run_with_timeout(ps2pdf, timeout)
2607 .map(|status| status.success())
2608 .unwrap_or(false)
2609 && tmp_pdf.exists();
2610 if !ps2pdf_ok {
2611 cleanup(&tmp_pdf, &tmp_png);
2612 return false;
2613 }
2614
2615 let mut pdftocairo = std::process::Command::new("pdftocairo");
2616 pdftocairo
2617 .arg("-singlefile")
2618 .arg("-png")
2619 .arg("-r")
2620 .arg(density.to_string())
2621 .arg(&tmp_pdf)
2622 .arg(&tmp_prefix);
2623 let cairo_ok = Self::run_with_timeout(pdftocairo, timeout)
2624 .map(|status| status.success())
2625 .unwrap_or(false)
2626 && tmp_png.exists();
2627 if !cairo_ok {
2628 cleanup(&tmp_pdf, &tmp_png);
2629 return false;
2630 }
2631
2632 let installed = std::fs::rename(&tmp_png, dest).is_ok();
2633 cleanup(&tmp_pdf, &tmp_png);
2634 installed
2635 }
2636
2637 fn convert_eps_via_gs(source: &str, dest: &str, density: u32) -> bool {
2648 let dest_path = Path::new(dest);
2649 let parent = dest_path.parent().unwrap_or_else(|| Path::new("."));
2650 let stem = crate::writer::bounded_name(
2651 dest_path
2652 .file_name()
2653 .and_then(|s| s.to_str())
2654 .unwrap_or("image"),
2655 );
2656 let unique = Self::unique_staging_tag();
2657 let tmp = parent.join(format!(".{}.{}.gs", stem, unique));
2660 let _on_exit = latexml_core::watchdog::remove_on_exit(&tmp);
2661 let timeout = std::time::Duration::from_secs(30);
2662 let dest_lc = dest.to_lowercase();
2663 let device = if dest_lc.ends_with(".jpg") || dest_lc.ends_with(".jpeg") {
2668 "jpeg"
2669 } else {
2670 "pngalpha"
2671 };
2672
2673 let mut cmd = std::process::Command::new(gs_program());
2674 cmd
2675 .arg("-q")
2676 .arg("-dNOPAUSE")
2677 .arg("-dBATCH")
2678 .arg("-dSAFER")
2679 .arg("-dTextAlphaBits=4")
2684 .arg("-dGraphicsAlphaBits=4")
2685 .arg("-dMaxBitmap=500000000")
2689 .arg("-dAlignToPixels=0")
2690 .arg("-dGridFitTT=2")
2691 .arg("-dEPSCrop");
2696 cmd
2721 .arg(format!("-sDEVICE={}", device))
2722 .arg(format!("-r{}", density))
2723 .arg(format!("-sOutputFile={}", tmp.display()));
2724 let bbox_full = read_postscript_bounding_box_full(source);
2725 if let Some((x0, y0, w_pt, h_pt)) = bbox_full {
2726 let w = w_pt.max(1.0).ceil() as u32;
2727 let h = h_pt.max(1.0).ceil() as u32;
2728 cmd
2729 .arg("-dFIXEDMEDIA")
2730 .arg(format!("-dDEVICEWIDTHPOINTS={}", w))
2731 .arg(format!("-dDEVICEHEIGHTPOINTS={}", h));
2732 if x0.abs() > 0.5 || y0.abs() > 0.5 {
2733 cmd
2734 .arg("-c")
2735 .arg(format!("{} {} translate", -x0, -y0))
2736 .arg("-f");
2737 }
2738 }
2739 cmd.arg(source);
2740 let gs_ok = Self::run_with_timeout(cmd, timeout)
2741 .map(|s| s.success())
2742 .unwrap_or(false)
2743 && tmp.exists();
2744 if !gs_ok {
2745 let _ = std::fs::remove_file(&tmp);
2746 return false;
2747 }
2748 let installed = std::fs::rename(&tmp, dest).is_ok();
2749 let _ = std::fs::remove_file(&tmp);
2750 installed
2751 }
2752
2753 #[cfg(windows)]
2757 fn reachable_source(source: &str) -> Option<crate::writer::Staged> {
2758 const MAX_PATH: usize = 260;
2759 if std::path::absolute(source).map_or(true, |p| p.as_os_str().len() < MAX_PATH) {
2760 return None;
2761 }
2762 let alias = crate::writer::Staged::alias(Path::new(source)).ok()?;
2763 (alias.path().as_os_str().len() < MAX_PATH).then_some(alias)
2765 }
2766
2767 #[cfg(not(windows))]
2769 fn reachable_source(_source: &str) -> Option<crate::writer::Staged> { None }
2770
2771 fn file_arg(source: &str) -> std::borrow::Cow<'_, str> {
2774 match Path::new(source).components().next() {
2775 Some(std::path::Component::Normal(_)) => Path::new(".")
2776 .join(source)
2777 .to_string_lossy()
2778 .into_owned()
2779 .into(),
2780 _ => source.into(),
2781 }
2782 }
2783
2784 fn convert_image(source: &str, dest: &str, density: u32, page: Option<u32>) -> bool {
2790 let alias = Self::reachable_source(source);
2791 let source = Self::file_arg(
2792 alias
2793 .as_ref()
2794 .and_then(|a| a.path().to_str())
2795 .unwrap_or(source),
2796 );
2797 let source = &*source;
2798 let with_fonts = crate::postscript_fonts::with_downloaded_fonts(source, dest);
2801 Self::convert_image_from(
2803 with_fonts
2804 .as_ref()
2805 .and_then(|copy| copy.path().to_str())
2806 .unwrap_or(source),
2807 dest,
2808 density,
2809 page,
2810 )
2811 }
2812
2813 fn convert_image_from(source: &str, dest: &str, density: u32, page: Option<u32>) -> bool {
2815 let source_arg = if let Some(p) = page {
2818 format!("{}[{}]", source, p.saturating_sub(1))
2819 } else {
2820 if source.to_lowercase().ends_with(".pdf") {
2822 format!("{}[0]", source)
2823 } else {
2824 source.to_string()
2825 }
2826 };
2827 if Self::should_try_eps_pdf_path(source, page)
2830 && Self::convert_eps_via_pdf(source, dest, density)
2831 {
2832 return true;
2833 }
2834 let src_lc = source.to_lowercase();
2854 let is_postscript = src_lc.ends_with(".eps")
2855 || src_lc.ends_with(".epsi")
2856 || src_lc.ends_with(".epsf")
2857 || src_lc.ends_with(".ps");
2858 if is_postscript && page.is_none() {
2859 if Self::postscript_is_landscape(source) && Self::convert_eps_via_pdf(source, dest, density) {
2860 return true;
2861 }
2862 if Self::convert_eps_via_gs(source, dest, density) {
2863 return true;
2864 }
2865 }
2866 if Self::should_try_pdf_cairo_path(source) && dest.to_lowercase().ends_with(".png") {
2877 if Self::convert_pdf_via_mutool(source, dest, density, page) {
2878 return true;
2879 }
2880 if Self::convert_pdf_via_pdftocairo(source, dest, density, page) {
2881 return true;
2882 }
2883 }
2884 let mut cmd = std::process::Command::new(im_convert_program());
2896 cmd
2897 .arg("-define")
2898 .arg("pdf:use-cropbox=true")
2899 .arg("-density")
2900 .arg(density.to_string())
2901 .arg(&source_arg)
2902 .arg(dest);
2903 let timeout = std::time::Duration::from_secs(Self::convert_timeout_secs());
2904 match Self::run_with_timeout(cmd, timeout) {
2905 Some(status) => {
2906 if status.success() && Self::produced_output(dest) {
2915 true
2916 } else {
2917 let _ = std::fs::remove_file(dest); false
2919 }
2920 },
2921 None => {
2922 Warn!(
2923 "shell",
2924 "convert",
2925 "Graphics: convert/gs for {} exceeded {} s — killed",
2926 source,
2927 timeout.as_secs()
2928 );
2929 let _ = std::fs::remove_file(dest);
2930 false
2931 },
2932 }
2933 }
2934
2935 fn produced_output(dest: &str) -> bool {
2940 std::fs::metadata(dest)
2941 .map(|m| m.len() > 0)
2942 .unwrap_or(false)
2943 }
2944
2945 fn convert_timeout_secs() -> u64 { CONVERT_TIMEOUT_SECS.unwrap_or(60) }
2949}
2950
2951struct SvgElement<'a> {
2954 name: &'a str,
2955 tag: &'a str,
2956 children: Vec<usize>,
2957}
2958
2959fn svg_elements(text: &str) -> Option<Vec<SvgElement<'_>>> {
2962 let mut elements: Vec<SvgElement> = Vec::new();
2963 let mut open: Vec<usize> = Vec::new();
2964 let mut at = 0;
2965 while let Some(offset) = text[at..].find('<') {
2966 let start = at + offset;
2967 let rest = &text[start..];
2968 let skip = [
2969 ("<!--", "-->"),
2970 ("<![CDATA[", "]]>"),
2971 ("<?", "?>"),
2972 ("<!", ">"),
2973 ]
2974 .iter()
2975 .find(|(opener, _)| rest.starts_with(opener));
2976 if let Some((_, closer)) = skip {
2977 at = start + rest.find(closer)? + closer.len();
2978 continue;
2979 }
2980 let tag = latexml_core::util::image::xml_start_tag(rest)?;
2981 at = start + tag.len() + 1;
2982 if let Some(name) = tag.strip_prefix("</") {
2983 let top = open.pop()?;
2984 if elements[top].name != name.trim() {
2985 return None;
2986 }
2987 continue;
2988 }
2989 let name = tag[1..]
2990 .split(|c: char| c.is_whitespace() || c == '/')
2991 .next()
2992 .unwrap_or_default();
2993 let index = elements.len();
2994 if let Some(&parent) = open.last() {
2995 elements[parent].children.push(index);
2996 }
2997 elements.push(SvgElement {
2998 name,
2999 tag,
3000 children: Vec::new(),
3001 });
3002 if !tag.ends_with('/') {
3003 open.push(index);
3004 }
3005 }
3006 open.is_empty().then_some(elements)
3007}
3008
3009fn svg_transform_linear(list: &str) -> Option<[f64; 4]> {
3012 let mut m = [1.0, 0.0, 0.0, 1.0];
3013 let mut rest = list.trim();
3014 while !rest.is_empty() {
3015 let (name, tail) = rest.split_once('(')?;
3016 let (args, tail) = tail.split_once(')')?;
3017 let args: Vec<f64> = args
3018 .split(|c: char| c.is_whitespace() || c == ',')
3019 .filter(|v| !v.is_empty())
3020 .map(str::parse)
3021 .collect::<Result<_, _>>()
3022 .ok()?;
3023 let f = match (name.trim(), args.as_slice()) {
3024 ("matrix", [a, b, c, d, _, _]) => [*a, *b, *c, *d],
3025 ("translate", [_] | [_, _]) => [1.0, 0.0, 0.0, 1.0],
3026 ("scale", [s]) => [*s, 0.0, 0.0, *s],
3027 ("scale", [sx, sy]) => [*sx, 0.0, 0.0, *sy],
3028 ("rotate", [deg, ..]) => {
3029 let (sin, cos) = deg.to_radians().sin_cos();
3030 [cos, sin, -sin, cos]
3031 },
3032 _ => return None,
3033 };
3034 m = linear_compose(m, f);
3035 rest = tail.trim_start_matches(|c: char| c.is_whitespace() || c == ',');
3036 }
3037 Some(m)
3038}
3039
3040fn linear_compose(m: [f64; 4], f: [f64; 4]) -> [f64; 4] {
3042 [
3043 m[0] * f[0] + m[2] * f[1],
3044 m[1] * f[0] + m[3] * f[1],
3045 m[0] * f[2] + m[2] * f[3],
3046 m[1] * f[2] + m[3] * f[3],
3047 ]
3048}
3049
3050#[derive(Debug, PartialEq)]
3054struct EnlargedRaster {
3055 pixels: Option<(usize, usize)>,
3056 scale: Option<f64>,
3057}
3058
3059fn svg_enlarged_raster(text: &str) -> Option<EnlargedRaster> {
3063 use latexml_core::util::image::svg_attr_value;
3064 const TOLERANCE: f64 = 1.01;
3065 fn href(tag: &str) -> Option<&str> {
3066 svg_attr_value(tag, "xlink:href").or_else(|| svg_attr_value(tag, "href"))
3067 }
3068 fn pixels(tag: &str) -> Option<(usize, usize)> { href(tag).and_then(data_uri_pixels) }
3069 fn scale(tag: &str, m: [f64; 4]) -> Option<f64> {
3071 let length = |name| svg_attr_value(tag, name).and_then(|v| v.trim().parse::<f64>().ok());
3072 let (w, h, (pw, ph)) = (length("width")?, length("height")?, pixels(tag)?);
3073 let sx = w * m[0].hypot(m[1]) / pw as f64;
3074 let sy = h * m[2].hypot(m[3]) / ph as f64;
3075 Some(sx.max(sy)).filter(|s| s.is_finite())
3076 }
3077 struct Walk<'a> {
3078 elements: &'a [SvgElement<'a>],
3079 ids: HashMap<&'a str, usize>,
3080 scales: HashMap<usize, Option<f64>>,
3082 }
3083 impl Walk<'_> {
3084 fn element(&mut self, at: usize, m: Option<[f64; 4]>, depth: usize) {
3085 let elements = self.elements;
3086 let e = &elements[at];
3087 let own =
3088 svg_attr_value(e.tag, "transform").map_or(Some([1.0, 0.0, 0.0, 1.0]), svg_transform_linear);
3089 let m = m.zip(own).map(|(m, f)| linear_compose(m, f));
3090 let m =
3092 m.filter(|_| at == 0 || e.name != "svg" || svg_attr_value(e.tag, "viewBox").is_none());
3093 let mask = svg_attr_value(e.tag, "mask")
3095 .and_then(|v| v.trim().strip_prefix("url(#")?.strip_suffix(')'))
3096 .and_then(|id| self.ids.get(id).copied())
3097 .filter(|&target| elements[target].name == "mask" && depth < 8);
3098 if let Some(target) = mask {
3099 let units = svg_attr_value(elements[target].tag, "maskContentUnits");
3100 let m = m.filter(|_| units.is_none_or(|u| u.trim() == "userSpaceOnUse"));
3101 for &child in &elements[target].children {
3102 self.element(child, m, depth + 1);
3103 }
3104 }
3105 match e.name {
3106 "image" => {
3107 let s = m.and_then(|m| scale(e.tag, m));
3108 let worst = self.scales.entry(at).or_insert(s);
3109 *worst = worst.zip(s).map(|(a, b)| a.max(b));
3110 },
3111 "use" if depth < 8 => {
3112 if let Some(&target) = href(e.tag).and_then(|h| self.ids.get(h.trim_start_matches('#'))) {
3113 let m = m.filter(|_| elements[target].name != "symbol");
3115 self.element(target, m, depth + 1);
3116 }
3117 },
3118 _ => {
3119 for &child in &e.children {
3120 if !matches!(
3121 elements[child].name,
3122 "defs" | "clipPath" | "mask" | "pattern" | "symbol" | "marker"
3123 ) {
3124 self.element(child, m, depth);
3125 }
3126 }
3127 },
3128 }
3129 }
3130 }
3131 if !text.contains("<image") {
3132 return None;
3133 }
3134 let Some(elements) = svg_elements(text) else {
3135 return Some(EnlargedRaster { pixels: None, scale: None });
3136 };
3137 let ids = elements
3138 .iter()
3139 .enumerate()
3140 .filter_map(|(i, e)| Some((svg_attr_value(e.tag, "id")?, i)))
3141 .collect();
3142 let mut walk = Walk {
3143 elements: &elements,
3144 ids,
3145 scales: HashMap::default(),
3146 };
3147 if !elements.is_empty() {
3148 walk.element(0, Some([1.0, 0.0, 0.0, 1.0]), 0);
3149 }
3150 elements.iter().enumerate().find_map(|(i, e)| {
3153 let scale = walk.scales.get(&i).copied().flatten();
3154 let single_pixel = pixels(e.tag) == Some((1, 1));
3155 (e.name == "image" && !single_pixel && scale.is_none_or(|s| s > TOLERANCE))
3156 .then(|| EnlargedRaster { pixels: pixels(e.tag), scale })
3157 })
3158}
3159
3160fn data_uri_pixels(uri: &str) -> Option<(usize, usize)> {
3162 let (meta, data) = uri.strip_prefix("data:")?.split_once(',')?;
3163 if !meta.ends_with(";base64") {
3164 return None;
3165 }
3166 [4096, usize::MAX].into_iter().find_map(|limit| {
3168 let size = imagesize::blob_size(&base64_prefix(data, limit)).ok()?;
3169 Some((size.width, size.height))
3170 })
3171}
3172
3173fn base64_prefix(data: &str, limit: usize) -> Vec<u8> {
3175 let mut out = Vec::new();
3176 let (mut acc, mut bits) = (0u32, 0u32);
3177 for c in data.bytes() {
3178 let v = match c {
3179 b'A'..=b'Z' => c - b'A',
3180 b'a'..=b'z' => c - b'a' + 26,
3181 b'0'..=b'9' => c - b'0' + 52,
3182 b'+' => 62,
3183 b'/' => 63,
3184 _ if c.is_ascii_whitespace() => continue,
3185 _ => break,
3186 };
3187 acc = (acc << 6 | u32::from(v)) & 0xffff;
3188 bits += 6;
3189 if bits >= 8 {
3190 bits -= 8;
3191 out.push((acc >> bits) as u8);
3192 if out.len() >= limit {
3193 break;
3194 }
3195 }
3196 }
3197 out
3198}
3199
3200#[derive(Default)]
3202struct Digests(std::cell::RefCell<HashMap<PathBuf, Option<crate::graphics_cache::SourceDigest>>>);
3203
3204impl Digests {
3205 fn of(&self, path: &Path) -> Option<crate::graphics_cache::SourceDigest> {
3207 self
3208 .0
3209 .borrow_mut()
3210 .entry(path.to_path_buf())
3211 .or_insert_with(|| crate::graphics_cache::SourceDigest::of_file(path))
3212 .clone()
3213 }
3214
3215 fn content(&self, path: &Path) -> Option<[u8; 32]> { self.of(path).map(|d| d.content()) }
3217}
3218
3219fn hex(digest: &[u8; 32]) -> String { digest.iter().map(|b| format!("{b:02x}")).collect() }
3220
3221fn ext_from_path(path: &str) -> &'static str {
3226 let lower = path.rsplit('/').next().unwrap_or(path);
3227 if let Some(idx) = lower.rfind('.') {
3228 let tail = &lower[idx + 1..];
3229 if tail.eq_ignore_ascii_case("png") {
3230 "png"
3231 } else if tail.eq_ignore_ascii_case("svg") {
3232 "svg"
3233 } else if tail.eq_ignore_ascii_case("jpg") || tail.eq_ignore_ascii_case("jpeg") {
3234 "jpg"
3235 } else if tail.eq_ignore_ascii_case("gif") {
3236 "gif"
3237 } else if tail.eq_ignore_ascii_case("webp") {
3238 "webp"
3239 } else {
3240 ""
3241 }
3242 } else {
3243 ""
3244 }
3245}
3246
3247fn read_postscript_bounding_box_full(source: &str) -> Option<(f64, f64, f64, f64)> {
3257 let boxes = latexml_core::util::image::read_postscript_boxes(Path::new(source))?;
3258 let (x0, y0, x1, y1) = boxes.bounding_box.or(boxes.hires_bounding_box)?;
3259 Some((x0, y0, (x1 - x0).abs(), (y1 - y0).abs()))
3260}
3261
3262fn read_postscript_bounding_box(source: &str) -> Option<(f64, f64)> {
3266 read_postscript_bounding_box_full(source).map(|(_, _, w, h)| (w, h))
3267}
3268
3269impl Processor for Graphics {
3270 fn get_name(&self) -> &str { &self.name }
3271
3272 fn resource_prefix(&self) -> Option<&str> { self.names.prefix.as_deref() }
3273
3274 fn to_process(&self, doc: &PostDocument) -> Vec<Node> {
3275 doc.findnodes("//ltx:graphics[not(@imagesrc)]")
3276 }
3277
3278 fn process(&mut self, doc: PostDocument, nodes: Vec<Node>) -> ProcessResult {
3279 let dirs = self.page_dirs(&doc);
3280 let dest_dir = dirs.dest_dir.clone();
3281 let source_dir = dirs.source_dir.clone();
3282 let effective_dpi = self.effective_dpi(&doc);
3283 let n_to_process = nodes.len();
3284 latexml_core::telemetry::set_graphics_assets(n_to_process as u32);
3285
3286 let mut names = std::mem::take(&mut self.names);
3288
3289 let PagePlan {
3303 plans,
3304 jobs: convert_jobs,
3305 known,
3306 } = self.plan_page(&doc, &nodes, &dirs, &mut names, effective_dpi);
3307
3308 let convert_count = convert_jobs.len();
3314 for job in &convert_jobs {
3315 if let Some(parent) = Path::new(&job.abs_dest_str).parent() {
3316 std::fs::create_dir_all(parent).ok();
3317 }
3318 }
3319 let worker_cap = std::thread::available_parallelism()
3334 .map(|n| n.get())
3335 .unwrap_or(4)
3336 .clamp(1, 22);
3337 let n_workers = convert_count.min(worker_cap).max(1);
3338 let mut outcomes: Vec<ConvertOutcome> = Vec::with_capacity(convert_count);
3339 if convert_count > 0 {
3340 use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
3341 let next = AtomicUsize::new(0);
3342 let subproc_count = AtomicU32::new(0);
3349 let subproc_ref = &subproc_count;
3350 let cache_policy = self.cache_policy;
3353 let jobs: Vec<&ConvertJob> = convert_jobs.iter().collect();
3357 type WorkerResult = (
3371 Vec<ConvertOutcome>,
3372 latexml_core::util::logger::CapturedDiagnostics,
3373 );
3374 let worker_outcomes: Vec<WorkerResult> = std::thread::scope(|s| {
3375 let handles: Vec<_> = (0..n_workers)
3376 .filter_map(|_| {
3377 std::thread::Builder::new()
3378 .stack_size(2 * 1024 * 1024)
3379 .spawn_scoped(s, || {
3380 latexml_core::util::logger::capture(|| {
3386 let mut local = Vec::<ConvertOutcome>::new();
3387 loop {
3388 let i = next.fetch_add(1, Ordering::Relaxed);
3389 if i >= jobs.len() {
3390 break;
3391 }
3392 let ConvertJob {
3393 job_id,
3394 source,
3395 digest,
3396 page,
3397 rel_dest,
3398 abs_dest_str,
3399 svg_paths,
3400 copy_source,
3401 ops,
3402 density,
3403 ppi,
3404 sizing,
3405 dpi,
3406 } = jobs[i];
3407 take_converter_diag();
3411 let svg_outcome = 'svg: {
3421 let Some((rel_svg, abs_svg)) = svg_paths else {
3422 break 'svg None;
3423 };
3424 let staged = crate::writer::Staged::beside(Path::new(abs_svg));
3425 let stage = staged.path().to_string_lossy().into_owned();
3426 let svg_key = crate::graphics_cache::RenderKey {
3427 page: *page,
3428 density: 0,
3429 ext: "svg",
3430 };
3431 let svg_res = crate::graphics_cache::with_cache_dims(
3432 cache_policy,
3433 source,
3434 digest.as_ref(),
3435 &stage,
3436 svg_key,
3437 || {
3438 subproc_ref.fetch_add(1, Ordering::Relaxed);
3439 Self::convert_image_svg(source, &stage, *page)
3440 },
3441 || {
3442 Self::read_svg_dimensions(&stage).map(|(w, h)| {
3443 crate::graphics_cache::CachedDims { width: w, height: h }
3444 })
3445 },
3446 );
3447 let crate::graphics_cache::ConvertResult::Ok { dims } = svg_res else {
3448 Warn!(
3449 "shell",
3450 "svg",
3451 "Graphics: vector-SVG path failed for {}, falling back to raster",
3452 source
3453 );
3454 break 'svg None;
3455 };
3456 let bytes = match std::fs::read(&stage) {
3460 Ok(bytes) => bytes,
3461 Err(e) => {
3462 Warn!(
3463 "shell",
3464 "svg",
3465 "Graphics: can't read the vector render of {} ({}); using a raster",
3466 source,
3467 e
3468 );
3469 break 'svg None;
3470 },
3471 };
3472 let Ok(mut text) = String::from_utf8(bytes) else {
3474 Warn!(
3475 "shell",
3476 "svg",
3477 "Graphics: the vector render of {} is not UTF-8; using a raster",
3478 source
3479 );
3480 break 'svg None;
3481 };
3482 if let Some(EnlargedRaster { pixels, scale }) = svg_enlarged_raster(&text) {
3483 Info!(
3484 "shell",
3485 "svg",
3486 "Graphics: {} draws a {} raster at {} bp per pixel; using a PNG",
3487 source,
3488 pixels.map_or("?".to_string(), |(w, h)| format!("{w}x{h}")),
3489 scale.map_or("?".to_string(), |s| format!("{s:.2}"))
3490 );
3491 break 'svg None;
3492 }
3493 let crop = ops
3496 .iter()
3497 .find(|op| matches!(op, GraphicxOp::Trim { .. } | GraphicxOp::Clip { .. }));
3498 let mut rewritten = false;
3499 let raw_dims = match crop.map(|op| Self::crop_svg(&text, op)) {
3500 None | Some(Ok(None)) => dims.map(|d| (d.width, d.height)),
3501 Some(Ok(Some(cropped))) => {
3502 text = cropped;
3503 rewritten = true;
3504 latexml_core::util::image::svg_viewport_px(&text)
3505 },
3506 Some(Err(why)) => {
3507 Warn!(
3508 "shell",
3509 "svg",
3510 "Graphics: can't crop the vector render of {} ({}); cropping a \
3511 raster instead",
3512 source,
3513 why
3514 );
3515 break 'svg None;
3516 },
3517 };
3518 if let Some((rw, rh)) = raw_dims.filter(|_| !sizing.is_empty()) {
3520 let (w, h) = Self::apply_graphicx_op_list(rw, rh, SVG_PPI, sizing, *dpi);
3521 let stretch = sizing.iter().any(|op| match *op {
3523 GraphicxOp::Scale { x, y } => x != y,
3524 GraphicxOp::ScaleTo { w, h, keep_aspect } => {
3525 w.is_some() && h.is_some() && !keep_aspect
3526 },
3527 _ => false,
3528 });
3529 match Self::size_svg(&text, w, h, stretch) {
3530 Ok(sized) => {
3531 text = sized;
3532 rewritten = true;
3533 },
3534 Err(why) => {
3535 Warn!(
3536 "shell",
3537 "svg",
3538 "Graphics: can't size the vector render of {} ({}); using a raster",
3539 source,
3540 why
3541 );
3542 break 'svg None;
3543 },
3544 }
3545 }
3546 if rewritten
3547 && let Err(e) =
3548 crate::writer::write_atomic(Path::new(&stage), text.as_bytes())
3549 {
3550 Warn!(
3551 "shell",
3552 "svg",
3553 "Graphics: can't rewrite the vector render of {} ({}); using a raster",
3554 source,
3555 e
3556 );
3557 break 'svg None;
3558 }
3559 drop(text);
3560 if let Err(e) = staged.install(Path::new(abs_svg)) {
3561 Warn!(
3562 "shell",
3563 "svg",
3564 "Graphics: can't install the vector render of {} as {} ({}); falling \
3565 back to raster",
3566 source,
3567 abs_svg,
3568 e
3569 );
3570 break 'svg None;
3571 }
3572 Some(ConvertOutcome {
3573 job_id: *job_id,
3574 imagesrc: Some(rel_svg.clone()),
3575 raw_dims,
3576 ppi: SVG_PPI,
3577 })
3578 };
3579 let raster_dims = if svg_outcome.is_some() {
3583 None
3584 } else {
3585 let staged = crate::writer::Staged::beside(Path::new(abs_dest_str));
3586 let stage = staged.path().to_string_lossy().into_owned();
3587 let raster_res = if *copy_source {
3588 match std::fs::copy(source, &stage)
3589 .inspect_err(|e| record_converter_diag(format!("copy {source}: {e}")))
3590 {
3591 Ok(_) => crate::graphics_cache::ConvertResult::Ok {
3592 dims: Self::read_image_dimensions(&stage).map(|(w, h)| {
3593 crate::graphics_cache::CachedDims { width: w, height: h }
3594 }),
3595 },
3596 Err(_) => crate::graphics_cache::ConvertResult::Failed,
3597 }
3598 } else {
3599 let raster_key = crate::graphics_cache::RenderKey {
3600 page: *page,
3601 density: *density,
3602 ext: ext_from_path(abs_dest_str),
3603 };
3604 crate::graphics_cache::with_cache_dims(
3605 cache_policy,
3606 source,
3607 digest.as_ref(),
3608 &stage,
3609 raster_key,
3610 || {
3611 subproc_ref.fetch_add(1, Ordering::Relaxed);
3612 Self::convert_image(source, &stage, *density, *page)
3613 },
3614 || {
3615 Self::read_image_dimensions(&stage).map(|(w, h)| {
3616 crate::graphics_cache::CachedDims { width: w, height: h }
3617 })
3618 },
3619 )
3620 };
3621 if let crate::graphics_cache::ConvertResult::Ok { dims } = raster_res {
3622 let mut raw_dims = dims.map(|d| (d.width, d.height));
3623 if !ops.is_empty() {
3624 match Self::transform_raster_inplace(&stage, ops, ppi.0 / 72.0) {
3625 Ok(Some(size)) => raw_dims = Some(size),
3626 Ok(None) => {},
3627 Err(why) => Error!(
3628 "imageprocessing",
3629 "transform",
3630 "Graphics: {}; {} is shown untransformed",
3631 why,
3632 source
3633 ),
3634 }
3635 }
3636 let dest = Path::new(abs_dest_str);
3637 let installed = if crate::writer::same_file(Path::new(source), dest) {
3638 Err(std::io::Error::other(format!(
3639 "{abs_dest_str} is the source itself"
3640 )))
3641 } else {
3642 staged.install(dest)
3643 };
3644 match installed {
3645 Ok(()) => Some(raw_dims),
3646 Err(e) => {
3647 record_converter_diag(format!("install {abs_dest_str}: {e}"));
3648 None
3649 },
3650 }
3651 } else {
3652 None
3653 }
3654 };
3655 let outcome = if let Some(o) = svg_outcome {
3656 o
3657 } else if let Some(raw_dims) = raster_dims {
3658 ConvertOutcome {
3659 job_id: *job_id,
3660 imagesrc: Some(rel_dest.clone()),
3661 raw_dims,
3662 ppi: *ppi,
3663 }
3664 } else {
3665 let why = take_converter_diag()
3687 .unwrap_or_else(|| "no converter diagnostic captured".to_string());
3688 Error!(
3689 "imageprocessing",
3690 "failed_to_convert",
3691 "Graphics: failed to convert source asset {} — every converter \
3692 failed, no usable image produced (intended target {}); last \
3693 converter error: {}",
3694 source,
3695 abs_dest_str,
3696 why
3697 );
3698 ConvertOutcome {
3699 job_id: *job_id,
3700 imagesrc: None,
3701 raw_dims: None,
3702 ppi: *ppi,
3703 }
3704 };
3705 local.push(outcome);
3706 }
3707 local
3708 })
3709 })
3710 .ok()
3711 })
3712 .collect();
3713 handles
3728 .into_iter()
3729 .filter_map(|h| match h.join() {
3730 Ok(res) => Some(res),
3731 Err(payload) => {
3732 let msg = payload
3733 .downcast_ref::<&'static str>()
3734 .map(|s| (*s).to_string())
3735 .or_else(|| payload.downcast_ref::<String>().cloned())
3736 .unwrap_or_else(|| "opaque panic payload".to_string());
3737 Error!(
3738 "imageprocessing",
3739 "worker_panicked",
3740 "Graphics: a conversion worker thread panicked ({}); its \
3741 unfinished jobs are skipped and their graphics left \
3742 unconverted",
3743 msg
3744 );
3745 None
3746 },
3747 })
3748 .collect()
3749 });
3750 for (v, diags) in worker_outcomes {
3754 outcomes.extend(v);
3755 latexml_core::util::logger::replay_captured(diags);
3756 }
3757 outcomes.sort_by_key(|o| o.job_id);
3758 latexml_core::telemetry::add_graphics_subprocess(subproc_count.load(Ordering::Relaxed));
3759 }
3760 for outcome in outcomes.iter().filter(|o| o.imagesrc.is_some()) {
3763 if let Some(job) = convert_jobs.iter().find(|job| job.job_id == outcome.job_id)
3764 && let Some(entry) = names
3765 .converted
3766 .get_mut(&(dest_dir.clone(), job.rel_dest.clone()))
3767 {
3768 entry.1 = Some(outcome.clone());
3769 }
3770 }
3771 let outcomes_by_job: HashMap<usize, ConvertOutcome> = outcomes
3772 .into_iter()
3773 .chain(known)
3774 .map(|o| (o.job_id, o))
3775 .collect();
3776
3777 for plan in &plans {
3779 match plan {
3780 Plan::NotFound { idx: _, graphic } => {
3781 Warn!(
3794 "expected",
3795 "source",
3796 "No graphic source found; skipping (source was '{}')",
3797 graphic
3798 );
3799 },
3800 Plan::Copy {
3801 idx,
3802 source,
3803 options,
3804 rel,
3805 copy,
3806 } => {
3807 let mut node_mut = nodes[*idx].clone();
3808 let mut rel = rel.clone();
3809 if *copy && Self::copy_file(source, &dest_dir, &rel).is_none() {
3810 let planned = std::mem::replace(
3813 &mut rel,
3814 latexml_core::util::pathname::relative(source, &source_dir),
3815 );
3816 names
3817 .copies
3818 .insert((dest_dir.clone(), planned), rel.clone());
3819 }
3820 let raw_dims = Self::read_source_dimensions(source);
3821 let ppi = if ext_from_path(source).eq_ignore_ascii_case("svg") {
3822 SVG_PPI
3823 } else {
3824 Self::raster_ppi(source)
3825 };
3826 let is_raster = self
3835 .type_properties
3836 .get(ext_from_path(source))
3837 .and_then(|p| p.raster)
3838 .unwrap_or(true);
3839 let all_ops = latexml_core::util::image::parse_graphicx_options(options);
3840 let ops: Vec<GraphicxOp> = if is_raster {
3841 all_ops
3842 .into_iter()
3843 .filter(|op| !matches!(op, GraphicxOp::Trim { .. } | GraphicxOp::Clip { .. }))
3844 .collect()
3845 } else {
3846 let refused: Vec<String> = all_ops
3847 .iter()
3848 .filter_map(|op| match op {
3849 GraphicxOp::Rotate(a) if a.abs() > 0.5 => Some(format!("angle={a}")),
3850 GraphicxOp::Trim { .. } => Some("trim".to_string()),
3851 GraphicxOp::Clip { .. } => Some("viewport".to_string()),
3852 _ => None,
3853 })
3854 .collect();
3855 if !refused.is_empty() {
3856 Warn!(
3857 "limitation",
3858 "graphics",
3859 "Cannot (yet) apply complex transforms to non-raster images: dropping {} for {}",
3860 refused.join(", "),
3861 source
3862 );
3863 }
3864 all_ops
3865 .into_iter()
3866 .filter(|op| matches!(op, GraphicxOp::Scale { .. } | GraphicxOp::ScaleTo { .. }))
3867 .collect()
3868 };
3869 if raw_dims.is_none() {
3870 Warn!(
3873 "expected",
3874 "image",
3875 "Couldn't get usable image size for {}",
3876 source
3877 );
3878 }
3879 let (w, h) = match raw_dims {
3880 Some((rw, rh)) => {
3881 let (tw, th) = Self::apply_graphicx_op_list(rw, rh, ppi, &ops, effective_dpi);
3882 (Some(tw), Some(th))
3883 },
3884 None => (None, None),
3885 };
3886 Self::set_graphic_src(&mut node_mut, &rel, w, h);
3887 },
3888 Plan::Convert { idx, options, job_id } => {
3889 if let Some(out) = outcomes_by_job.get(job_id) {
3890 let mut node_mut = nodes[*idx].clone();
3891 if let Some(imagesrc) = &out.imagesrc {
3892 let ops: Vec<GraphicxOp> = latexml_core::util::image::parse_graphicx_options(options)
3899 .into_iter()
3900 .filter(|op| !matches!(op, GraphicxOp::Trim { .. } | GraphicxOp::Clip { .. }))
3901 .collect();
3902 let (w, h) = match out.raw_dims {
3903 Some((rw, rh)) => {
3904 let (tw, th) = Self::apply_graphicx_op_list(rw, rh, out.ppi, &ops, effective_dpi);
3905 (Some(tw), Some(th))
3906 },
3907 None => (None, None),
3908 };
3909 Self::set_graphic_src(&mut node_mut, imagesrc, w, h);
3910 }
3911 }
3912 },
3913 }
3914 }
3915
3916 Info!(
3917 "graphics",
3918 "process",
3919 "Graphics {} {} to process",
3920 doc.get_destination().unwrap_or("?"),
3921 n_to_process
3922 );
3923 self.names = names;
3924 Ok(vec![doc])
3925 }
3926}
3927
3928#[cfg(test)]
3929mod tests {
3930 use super::*;
3931 use crate::test_env::EnvGuard;
3937 use crate::test_env::TempDir;
3938
3939 #[cfg(windows)]
3942 #[test]
3943 fn a_figure_path_past_max_path_is_reached_through_a_short_alias() {
3944 let tmp = TempDir::new("reachable-source");
3945 let dir = tmp.path().join("d".repeat(120)).join("e".repeat(120));
3946 std::fs::create_dir_all(&dir).unwrap();
3947 let figure = dir.join("figure.pdf");
3948 std::fs::write(&figure, b"%PDF-1.4 figure").unwrap();
3949 let source = std::path::absolute(&figure).unwrap();
3950 assert!(source.as_os_str().len() >= 260, "{}", source.display());
3951 let alias = Graphics::reachable_source(source.to_str().unwrap()).expect("an alias");
3952 let path = alias.path().to_path_buf();
3953 assert!(path.as_os_str().len() < 260, "{}", path.display());
3954 assert_ne!(path.parent(), Some(dir.as_path()));
3955 assert_eq!(std::fs::read(&path).unwrap(), b"%PDF-1.4 figure");
3956 drop(alias);
3957 assert!(!path.exists(), "the alias outlived its drop");
3958 let short = tmp.path().join("figure.pdf");
3959 std::fs::write(&short, b"%PDF-1.4").unwrap();
3960 assert!(Graphics::reachable_source(short.to_str().unwrap()).is_none());
3961 }
3962
3963 #[test]
3966 fn a_relative_source_reaches_the_converters_as_a_file() {
3967 let dot = |name: &str| Path::new(".").join(name).to_string_lossy().into_owned();
3968 for name in ["-o.pdf", "|x.pdf", "png:c.pdf", "fig.eps", "a>b/x.pdf"] {
3969 assert_eq!(Graphics::file_arg(name), dot(name), "{name}");
3970 }
3971 let absolute = std::env::temp_dir().join("-o.pdf");
3972 for name in ["./-o.pdf", "../|x.pdf", absolute.to_str().unwrap()] {
3973 assert_eq!(Graphics::file_arg(name), name, "{name}");
3974 }
3975 }
3976
3977 fn stem_request(source: &str, ext: &str) -> Request {
3979 let stem = Path::new(source)
3980 .file_stem()
3981 .unwrap()
3982 .to_string_lossy()
3983 .into_owned();
3984 Request {
3985 key: format!("LaTeXML::Post::Graphics:{source}.{ext}||{source}"),
3986 bytes: format!("{ext}|{source}||"),
3987 owner: format!("{ext}|||{source}"),
3988 source: source.to_string(),
3989 identity: source.to_string(),
3990 proposal: Proposal::Stem(stem),
3991 ext: ext.to_string(),
3992 svg_alt: false,
3993 copy: false,
3994 output: Output::Render(None),
3995 }
3996 }
3997
3998 fn dests_of(requests: Vec<Request>) -> Vec<String> {
3999 let pages = [requests];
4000 let checks = crate::resource_cache::Checks {
4001 prefix: "x",
4002 usable: &|_| true,
4003 vouch: &|_, _, _| true,
4004 on_disk: None,
4005 cache: crate::document::CACHE_FILE,
4006 warn: &|_| {},
4007 };
4008 DocCache::new(true)
4009 .with_store(None, |store| {
4010 store.immediate(|tx, _| crate::resource_cache::resolve(tx, &checks, &pages))
4011 })
4012 .unwrap()[0]
4013 .iter()
4014 .map(|r| r.name.dest.clone())
4015 .collect()
4016 }
4017
4018 #[test]
4026 fn convert_dest_names_avoid_basename_collision() {
4027 let names = dests_of(vec![
4028 stem_request("figs/a/plot.pdf", "png"),
4029 stem_request("figs/b/plot.pdf", "png"),
4030 stem_request("figs/c/other.pdf", "png"),
4031 stem_request("figs/d/plot.eps", "svg"),
4032 stem_request("figs/a/plot.pdf", "png"),
4033 ]);
4034 assert_eq!(names, [
4035 "plot.png",
4036 "x1.png",
4037 "other.png",
4038 "plot.svg",
4039 "plot.png"
4040 ]);
4041 let names = dests_of(vec![
4042 stem_request("m1/chi2.pdf", "png"),
4043 stem_request("m3/chi2.pdf", "png"),
4044 stem_request("jk/chi2.pdf", "png"),
4045 ]);
4046 assert_eq!(names, ["chi2.png", "x1.png", "x2.png"]);
4047 }
4048
4049 #[test]
4055 fn generated_xn_survives_a_later_literal_xn_source() {
4056 let names = dests_of(vec![
4057 stem_request("figs/b/plot.pdf", "png"),
4058 stem_request("figs/c/plot.pdf", "png"),
4059 stem_request("figs/a/x1.pdf", "png"),
4060 ]);
4061 assert_eq!(names, ["plot.png", "x1.png", "x2.png"]);
4062 }
4063
4064 fn spawn_slow_child() -> std::process::Command {
4072 let mut cmd;
4073 if cfg!(windows) {
4074 cmd = std::process::Command::new("ping");
4075 cmd.args(["-n", "11", "127.0.0.1"]);
4076 } else {
4077 cmd = std::process::Command::new("sleep");
4078 cmd.arg("10");
4079 }
4080 cmd
4081 }
4082
4083 fn spawn_fast_ok() -> std::process::Command {
4085 let mut cmd = std::process::Command::new(if cfg!(windows) { "cmd" } else { "true" });
4086 if cfg!(windows) {
4087 cmd.args(["/C", "exit 0"]);
4088 }
4089 cmd
4090 }
4091
4092 fn spawn_stderr_fail() -> (std::process::Command, &'static str) {
4095 if cfg!(windows) {
4096 let mut cmd = std::process::Command::new("cmd");
4097 cmd.args(["/C", "echo boom on stderr 1>&2 & exit 3"]);
4098 (cmd, "cmd")
4099 } else {
4100 let mut cmd = std::process::Command::new("sh");
4101 cmd.arg("-c").arg("echo 'boom on stderr' >&2; exit 3");
4102 (cmd, "sh")
4103 }
4104 }
4105
4106 #[test]
4110 fn run_with_timeout_kills_slow_child() {
4111 let start = std::time::Instant::now();
4112 let cmd = spawn_slow_child();
4113 let result = Graphics::run_with_timeout(cmd, std::time::Duration::from_millis(200));
4114 let elapsed = start.elapsed();
4115 assert!(
4116 result.is_none(),
4117 "run_with_timeout should return None on kill"
4118 );
4119 assert!(
4122 elapsed < std::time::Duration::from_secs(2),
4123 "killed run should return quickly, took {:?}",
4124 elapsed
4125 );
4126 }
4127
4128 #[test]
4130 fn run_with_timeout_returns_status_for_fast_child() {
4131 let cmd = spawn_fast_ok();
4132 let result = Graphics::run_with_timeout(cmd, std::time::Duration::from_secs(5));
4133 let status = result.expect("expected clean exit");
4134 assert!(status.success(), "a fast child should exit successfully");
4135 }
4136
4137 #[test]
4139 fn run_with_timeout_handles_spawn_failure() {
4140 let cmd = std::process::Command::new("/this/binary/does/not/exist/12345");
4141 let result = Graphics::run_with_timeout(cmd, std::time::Duration::from_secs(1));
4142 assert!(result.is_none());
4143 }
4144
4145 #[test]
4148 fn should_try_svg_path_explicit_threshold() {
4149 let tmp = TempDir::new("svg_gate");
4150 let small_pdf = tmp.join("small.pdf");
4151 let big_pdf = tmp.join("big.pdf");
4152 let png = tmp.join("raster.png");
4153 std::fs::write(&small_pdf, vec![0u8; 10 * 1024]).unwrap(); std::fs::write(&big_pdf, vec![0u8; 500 * 1024]).unwrap(); std::fs::write(&png, vec![0u8; 10 * 1024]).unwrap(); assert!(Graphics::should_try_svg_path(
4159 small_pdf.to_str().unwrap(),
4160 200
4161 ));
4162 assert!(!Graphics::should_try_svg_path(
4164 big_pdf.to_str().unwrap(),
4165 200
4166 ));
4167 assert!(!Graphics::should_try_svg_path(png.to_str().unwrap(), 200));
4169 assert!(!Graphics::should_try_svg_path("/no/such/file.pdf", 200));
4171 }
4172
4173 #[test]
4178 fn should_try_svg_path_auto_detect() {
4179 let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
4180 let cifar = fixtures.join("cifar10_vector.pdf");
4181 let pathological = fixtures.join("pathological_vector.pdf");
4182 let raster = fixtures.join("raster_with_image.pdf");
4183 assert!(cifar.exists(), "fixture missing: {}", cifar.display());
4184 assert!(
4185 pathological.exists(),
4186 "fixture missing: {}",
4187 pathological.display()
4188 );
4189 assert!(raster.exists(), "fixture missing: {}", raster.display());
4190
4191 assert!(
4193 Graphics::should_try_svg_path(cifar.to_str().unwrap(), 0),
4194 "vector-only PDF must trigger SVG path under auto-detect"
4195 );
4196 assert!(
4197 Graphics::should_try_svg_path(pathological.to_str().unwrap(), 0),
4198 "pgfplots-style vector PDF must trigger SVG path under auto-detect"
4199 );
4200
4201 assert!(
4203 Graphics::should_try_svg_path(raster.to_str().unwrap(), 0),
4204 "raster-bearing PDF must try the SVG path under the auto default"
4205 );
4206
4207 let tmp = TempDir::new("auto_svg_bound");
4209 let at_bound = tmp.join("at_bound.pdf");
4210 std::fs::write(&at_bound, vec![0u8; 500 * 1024]).unwrap();
4211 assert!(Graphics::should_try_svg_path(at_bound.to_str().unwrap(), 0));
4212 let over_bound = tmp.join("over_bound.pdf");
4213 std::fs::write(&over_bound, vec![0u8; 500 * 1024 + 1]).unwrap();
4214 assert!(!Graphics::should_try_svg_path(
4215 over_bound.to_str().unwrap(),
4216 0
4217 ));
4218 }
4219
4220 #[test]
4221 fn postscript_density_caps_huge_bounding_box() {
4222 let tmp = TempDir::new("ps_density");
4223 let normal = tmp.join("normal.eps");
4224 let huge = tmp.join("huge.eps");
4225 std::fs::write(
4226 &normal,
4227 "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 567 567\n",
4228 )
4229 .unwrap();
4230 std::fs::write(
4231 &huge,
4232 "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 14 14 11353 11353\n",
4233 )
4234 .unwrap();
4235
4236 assert_eq!(
4237 Graphics::raster_density_for_source(normal.to_str().unwrap()),
4238 Graphics::DEFAULT_RASTER_DENSITY
4239 );
4240 assert_eq!(
4241 Graphics::raster_density_for_source(huge.to_str().unwrap()),
4242 13
4243 );
4244 assert_eq!(
4245 read_postscript_bounding_box(huge.to_str().unwrap()),
4246 Some((11339.0, 11339.0))
4247 );
4248 }
4249
4250 #[test]
4251 fn pdf_density_caps_huge_page_box() {
4252 let dir = TempDir::new("pdf_density");
4253 let tmp = dir.join("page.pdf");
4254 std::fs::write(
4255 &tmp,
4256 b"%PDF-1.4
42571 0 obj
4258<< /Type /Page /MediaBox [0 0 4218 2437] >>
4259endobj
4260",
4261 )
4262 .unwrap();
4263
4264 assert_eq!(
4265 latexml_core::util::image::read_pdf_page_box(Path::new(tmp.to_str().unwrap())),
4266 Some((4218.0, 2437.0))
4267 );
4268 assert_eq!(
4269 Graphics::raster_density_for_source(tmp.to_str().unwrap()),
4270 34
4271 );
4272 }
4273
4274 #[test]
4280 fn read_svg_dimensions_sizes_from_root_lengths() {
4281 let dir = TempDir::new("svg_dim");
4282 let tmp = dir.join("dims.svg");
4283 std::fs::write(
4284 &tmp,
4285 r#"<?xml version="1.0"?>
4286<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 480" width="10cm" height="7.5cm">
4287 <rect width="640" height="480" fill="black"/>
4288</svg>"#,
4289 )
4290 .unwrap();
4291 let dims = Graphics::read_svg_dimensions(tmp.to_str().unwrap()).expect("dims");
4292 assert_eq!(dims, (378, 283));
4293 let vb = dir.join("vb.svg");
4295 std::fs::write(
4296 &vb,
4297 r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 480"><rect/></svg>"#,
4298 )
4299 .unwrap();
4300 assert_eq!(
4301 Graphics::read_svg_dimensions(vb.to_str().unwrap()).expect("viewbox fallback"),
4302 (640, 480)
4303 );
4304 }
4305
4306 #[test]
4312 fn read_svg_dimensions_falls_back_to_width_height() {
4313 let dir = TempDir::new("svg_dim_fallback");
4314 let tmp = dir.join("dims.svg");
4315 std::fs::write(
4316 &tmp,
4317 r#"<svg xmlns="http://www.w3.org/2000/svg" width="123.7pt" height="99.4pt">
4318 <rect/>
4319</svg>"#,
4320 )
4321 .unwrap();
4322 let dims = Graphics::read_svg_dimensions(tmp.to_str().unwrap()).expect("dims");
4323 assert_eq!(dims, (165, 133));
4324 }
4325
4326 #[test]
4331 fn read_svg_dimensions_declines_a_percentage_sized_root() {
4332 let dir = TempDir::new("svg_dim_pct");
4333 let tmp = dir.join("dims.svg");
4334 std::fs::write(
4335 &tmp,
4336 r#"<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%"><rect/></svg>"#,
4337 )
4338 .unwrap();
4339 assert_eq!(Graphics::read_svg_dimensions(tmp.to_str().unwrap()), None);
4340 }
4341
4342 #[test]
4362 #[cfg(unix)]
4363 fn process_coalesces_only_matching_conversion_options() {
4364 use std::os::unix::fs::PermissionsExt;
4365
4366 use crate::{
4367 document::{PostDocument, PostDocumentOptions},
4368 graphics_cache::CachePolicy,
4369 };
4370
4371 let tmp = TempDir::new("graphics_dedupe");
4372 let source = tmp.join("plot.ai");
4373 std::fs::write(&source, "%!PS-Adobe-3.0\n%%BoundingBox: 0 0 100 100\n").unwrap();
4374 let log = tmp.join("convert.log");
4375 let fake_convert = tmp.join("convert");
4376 std::fs::write(
4382 &fake_convert,
4383 "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$(dirname \"$0\")/convert.log\"\n\
4384 for a in \"$@\"; do d=\"$a\"; done\nprintf x > \"$d\"\nexit 0\n",
4385 )
4386 .unwrap();
4387 let mut perms = std::fs::metadata(&fake_convert).unwrap().permissions();
4388 perms.set_mode(0o755);
4389 std::fs::set_permissions(&fake_convert, perms).unwrap();
4390
4391 let old_path = std::env::var("PATH").unwrap_or_default();
4392 let mut env = EnvGuard::acquire();
4393 env.set("PATH", &format!("{}:{}", tmp.path().display(), old_path));
4394 let xml = format!(
4395 r#"<?xml version="1.0"?>
4396<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="d">
4397 <graphics graphic="plot.ai" candidates="{0}" options="width=20pt"/>
4398 <graphics graphic="plot.ai" candidates="{0}" options="width=40pt"/>
4399 <graphics graphic="plot.ai" candidates="{0}" options="width=20pt,page=2"/>
4400</document>"#,
4401 source.display()
4402 );
4403 let doc_opts = PostDocumentOptions {
4404 destination: Some(tmp.join("out.html").display().to_string()),
4405 source_directory: Some(tmp.path().display().to_string()),
4406 ..Default::default()
4407 };
4408 let doc = PostDocument::new_from_string(&xml, doc_opts).unwrap();
4409 let mut graphics = Graphics::new(None, true).with_cache_policy(CachePolicy::Bypass);
4410 let nodes = graphics.to_process(&doc);
4411 assert_eq!(nodes.len(), 3);
4412
4413 let docs = graphics.process(doc, nodes).unwrap();
4414 let out = docs[0].to_xml_string();
4415 let log_contents = std::fs::read_to_string(&log).unwrap_or_else(|e| {
4416 panic!(
4417 "fake `convert` never ran: no log at {} ({e}). The shim is on PATH and the cache is \
4418 bypassed, so `process` should have spawned it.",
4419 log.display()
4420 )
4421 });
4422 assert_eq!(
4423 log_contents.lines().count(),
4424 2,
4425 "two widths of one source and page should coalesce, but another page needs a conversion \
4426 of its own; convert log was:\n{log_contents}"
4427 );
4428 assert_eq!(out.matches(r#"imagesrc="plot.png""#).count(), 2);
4429 assert_eq!(out.matches(r#"imagesrc="x1.png""#).count(), 1);
4430 let edited = xml
4432 .replace("width=40pt", "width=30pt")
4433 .replace("width=20pt", "width=25pt");
4434 let doc_opts = PostDocumentOptions {
4435 destination: Some(tmp.join("out.html").display().to_string()),
4436 source_directory: Some(tmp.path().display().to_string()),
4437 ..Default::default()
4438 };
4439 let doc = PostDocument::new_from_string(&edited, doc_opts).unwrap();
4440 let mut graphics = Graphics::new(None, true).with_cache_policy(CachePolicy::Bypass);
4441 let nodes = graphics.to_process(&doc);
4442 let out = graphics.process(doc, nodes).unwrap()[0].to_xml_string();
4443 assert_eq!(out.matches(r#"imagesrc="plot.png""#).count(), 2);
4444 assert_eq!(out.matches(r#"imagesrc="x1.png""#).count(), 1);
4445 }
4446
4447 #[test]
4452 fn crop_svg_narrows_the_view_box() {
4453 let root = |w: &str, h: &str| {
4454 format!(
4455 r#"<?xml version="1.0"?>
4456<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="{w}" height="{h}" viewBox="0 0 200 100">
4457<rect width="200" height="100"/>
4458</svg>
4459"#
4460 )
4461 };
4462 let trim = GraphicxOp::Trim {
4463 l: 100.0,
4464 b: 0.0,
4465 r: 0.0,
4466 t: 50.0,
4467 };
4468 let text = Graphics::crop_svg(&root("200", "100"), &trim)
4469 .unwrap()
4470 .unwrap();
4471 assert_eq!(
4472 latexml_core::util::image::svg_root_tag(&text),
4473 Some(
4474 r#"<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100" height="50" viewBox="100 50 100 50""#
4475 ),
4476 "{text}"
4477 );
4478 assert!(
4479 text.contains(r#"<rect width="200" height="100"/>"#),
4480 "{text}"
4481 );
4482 let viewport = GraphicxOp::Clip {
4483 l: 0.0,
4484 b: 0.0,
4485 r: 100.0,
4486 t: 50.0,
4487 };
4488 let text = Graphics::crop_svg(&root("200pt", "100pt"), &viewport)
4489 .unwrap()
4490 .unwrap();
4491 assert_eq!(
4492 latexml_core::util::image::svg_root_tag(&text),
4493 Some(
4494 r#"<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100pt" height="50pt" viewBox="0 50 100 50""#
4495 ),
4496 "{text}"
4497 );
4498 let whole = GraphicxOp::Clip {
4499 l: 0.0,
4500 b: 0.0,
4501 r: 200.0,
4502 t: 100.0,
4503 };
4504 assert_eq!(Graphics::crop_svg(&root("200", "100"), &whole), Ok(None));
4505 }
4506
4507 #[test]
4514 fn trim_and_viewport_crop_the_raster_into_its_own_file() {
4515 use crate::{
4516 document::{PostDocument, PostDocumentOptions},
4517 graphics_cache::CachePolicy,
4518 };
4519 let _env = EnvGuard::acquire();
4521 let convert = im_convert_program();
4522 let magick = |args: &[&str]| {
4523 std::process::Command::new(convert)
4524 .args(args)
4525 .output()
4526 .ok()
4527 .filter(|o| o.status.success())
4528 .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
4529 };
4530 if magick(&["-version"]).is_none() {
4531 eprintln!("SKIP trim_and_viewport_crop_the_raster_into_its_own_file: no `{convert}`");
4532 return;
4533 }
4534 let tmp = TempDir::new("graphics_trim_crop");
4535 let img = tmp.join("img.png");
4536 magick(&[
4539 "-size",
4540 "100x50",
4541 "xc:red",
4542 "xc:lime",
4543 "+append",
4544 "(",
4545 "-size",
4546 "100x50",
4547 "xc:blue",
4548 "xc:yellow",
4549 "+append",
4550 ")",
4551 "-append",
4552 "-define",
4553 "png:exclude-chunk=pHYs,date,time",
4554 img.to_str().unwrap(),
4555 ])
4556 .expect("make the quadrant PNG");
4557 let dest = tmp.join("out").join("out.html");
4558 std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
4559 let trim = "trim=100.375pt 0.0pt 0.0pt 50.1875pt";
4560 let viewport = "viewport=0.0pt 0.0pt 100.375pt 50.1875pt";
4561 let xml = format!(
4562 r#"<?xml version="1.0"?>
4563<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="d">
4564 <graphics graphic="img" candidates="{0}" options="{trim},clip=true" xml:id="g1"/>
4565 <graphics graphic="img" candidates="{0}" options="{viewport},clip=true" xml:id="g2"/>
4566 <graphics graphic="img" candidates="{0}" options="{trim}" xml:id="g3"/>
4567 <graphics graphic="img" candidates="{0}" options="angle=90" xml:id="g4"/>
4568 <graphics graphic="img" candidates="{0}" xml:id="g5"/>
4569</document>"#,
4570 img.display()
4571 );
4572 let doc_opts = PostDocumentOptions {
4573 destination: Some(dest.display().to_string()),
4574 source_directory: Some(tmp.path().display().to_string()),
4575 ..Default::default()
4576 };
4577 let doc = PostDocument::new_from_string(&xml, doc_opts).unwrap();
4578 let mut graphics = Graphics::new(None, true).with_cache_policy(CachePolicy::Bypass);
4579 let nodes = graphics.to_process(&doc);
4580 let out = graphics.process(doc, nodes).unwrap()[0].to_xml_string();
4581 let attr = |id: &str, name: &str| -> String {
4582 let at = out.find(&format!(r#"xml:id="{id}""#)).expect(id);
4583 let start = out[..at].rfind('<').unwrap();
4584 let element = &out[start..at + out[at..].find('>').unwrap()];
4585 let key = format!(r#" {name}=""#);
4586 let value = &element[element
4587 .find(&key)
4588 .unwrap_or_else(|| panic!("{name}: {out}"))
4589 + key.len()..];
4590 value[..value.find('"').unwrap()].to_string()
4591 };
4592 let raster = |id: &str| {
4594 let file = dest.parent().unwrap().join(attr(id, "imagesrc"));
4595 let file = file.to_str().unwrap();
4596 let size = magick(&[file, "-format", "%wx%h", "info:"]).unwrap();
4597 let histogram = magick(&[file, "-format", "%c", "histogram:info:-"]).unwrap();
4598 let mut colours: Vec<String> = histogram
4599 .split_whitespace()
4600 .filter(|w| w.starts_with('#') && w.len() >= 7)
4601 .map(|w| w[..7].to_string())
4602 .collect();
4603 colours.sort();
4604 (size, colours)
4605 };
4606 let one = |c: &str| vec![c.to_string()];
4607 assert_eq!(raster("g1"), ("100x50".into(), one("#FFFF00")), "{out}");
4608 assert_eq!(raster("g2"), ("100x50".into(), one("#0000FF")), "{out}");
4609 assert_eq!(raster("g3"), ("100x50".into(), one("#FFFF00")), "{out}");
4610 assert_eq!(raster("g4").0, "100x200", "{out}");
4611 let all: Vec<String> = ["#0000FF", "#00FF00", "#FF0000", "#FFFF00"]
4612 .map(String::from)
4613 .to_vec();
4614 assert_eq!(raster("g5"), ("200x100".into(), all), "{out}");
4615 assert_eq!(attr("g5", "imagesrc"), "img.png", "{out}");
4616 for id in ["g1", "g2", "g3", "g4"] {
4617 assert_ne!(
4618 attr(id, "imagesrc"),
4619 "img.png",
4620 "{id} must not share the plain copy: {out}"
4621 );
4622 }
4623 let size = |id: &str| (attr(id, "imagewidth"), attr(id, "imageheight"));
4624 assert_eq!(size("g1"), ("133".into(), "67".into()), "{out}");
4626 assert_eq!(size("g4"), ("133".into(), "267".into()), "{out}");
4627 }
4628
4629 #[cfg(target_os = "linux")]
4633 #[test]
4634 fn a_converter_whose_spawner_is_pid_one_runs() {
4635 assert!(!reparented(1, 1), "a converter spawned by PID 1 must run");
4636 assert!(!reparented(4242, 4242));
4637 assert!(
4638 reparented(4242, 1),
4639 "an orphan adopted by init must not run unwatched"
4640 );
4641 assert!(
4642 reparented(4242, 77),
4643 "an orphan adopted by a subreaper must not run unwatched"
4644 );
4645 }
4646
4647 #[test]
4652 fn a_vector_render_is_cropped_at_its_density() {
4653 use crate::{
4654 document::{PostDocument, PostDocumentOptions},
4655 graphics_cache::CachePolicy,
4656 };
4657 let _env = EnvGuard::acquire();
4658 let convert = im_convert_program();
4659 let run = |program: &str, args: &[&str]| {
4660 std::process::Command::new(program)
4661 .args(args)
4662 .output()
4663 .ok()
4664 .filter(|o| o.status.success())
4665 .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
4666 };
4667 for (program, probe) in [(convert, "-version"), (gs_program(), "--version")] {
4668 if run(program, &[probe]).is_none() {
4669 eprintln!("SKIP a_vector_render_is_cropped_at_its_density: no `{program}`");
4670 return;
4671 }
4672 }
4673 let tmp = TempDir::new("graphics_vector_crop");
4674 let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
4675 for name in ["trim_quadrants.pdf", "trim_quadrants_huge.pdf"] {
4676 std::fs::copy(fixtures.join(name), tmp.join(name)).unwrap();
4677 }
4678 let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 216 108\n%%EndComments\n\
4680 1 0 0 setrgbcolor 0 54 108 54 rectfill 0 1 0 setrgbcolor 108 54 108 54 rectfill\n\
4681 0 0 1 setrgbcolor 0 0 108 54 rectfill 1 1 0 setrgbcolor 108 0 108 54 rectfill\nshowpage\n";
4682 std::fs::write(tmp.join("trim_quadrants.eps"), eps).unwrap();
4683 let png = tmp.join("q300.png");
4684 run(convert, &[
4685 "-size",
4686 "300x150",
4687 "xc:red",
4688 "xc:lime",
4689 "+append",
4690 "(",
4691 "-size",
4692 "300x150",
4693 "xc:blue",
4694 "xc:yellow",
4695 "+append",
4696 ")",
4697 "-append",
4698 "-units",
4699 "PixelsPerInch",
4700 "-density",
4701 "300",
4702 png.to_str().unwrap(),
4703 ])
4704 .expect("make the 300-dpi PNG");
4705 let rows = [
4707 (
4708 "pdf",
4709 "trim_quadrants.pdf",
4710 "trim=108.405pt 0.0pt 0.0pt 54.2025pt,clip=true",
4711 "180x90",
4712 "#FFFF00",
4713 ),
4714 (
4715 "viewport",
4716 "trim_quadrants.pdf",
4717 "viewport=0.0pt 0.0pt 108.405pt 54.2025pt,clip=true",
4718 "180x90",
4719 "#0000FF",
4720 ),
4721 (
4722 "page2",
4723 "trim_quadrants.pdf",
4724 "page=2,trim=0.0pt 108.405pt 54.2025pt 0.0pt,clip=true",
4725 "90x180",
4726 "#00FFFF",
4727 ),
4728 (
4729 "angle",
4730 "trim_quadrants.pdf",
4731 "trim=108.405pt 0.0pt 0.0pt 54.2025pt,clip=true,angle=90",
4732 "90x180",
4733 "#FFFF00",
4734 ),
4735 (
4736 "huge",
4737 "trim_quadrants_huge.pdf",
4738 "trim=3011.25pt 0.0pt 0.0pt 1505.625pt,clip=true",
4739 "1000x500",
4740 "#FFFF00",
4741 ),
4742 (
4743 "eps",
4744 "trim_quadrants.eps",
4745 "trim=108.405pt 0.0pt 0.0pt 54.2025pt,clip=true",
4746 "180x90",
4747 "#FFFF00",
4748 ),
4749 (
4750 "png300",
4751 "q300.png",
4752 "trim=72.27pt 0.0pt 0.0pt 36.135pt,clip=true",
4753 "300x150",
4754 "#FFFF00",
4755 ),
4756 ];
4757 let pdf_rasterizer = ["mutool", "pdftocairo"].iter().any(|tool| {
4761 std::process::Command::new(tool)
4762 .arg("--version")
4763 .output()
4764 .is_ok()
4765 });
4766 if !pdf_rasterizer {
4767 assert!(
4768 std::env::var_os("LATEXML_SVG_TESTS").is_none(),
4769 "LATEXML_SVG_TESTS is set but neither mutool nor pdftocairo is on PATH"
4770 );
4771 eprintln!(
4772 "SKIP a_vector_render_is_cropped_at_its_density, PDF rows: neither mutool nor pdftocairo on PATH"
4773 );
4774 }
4775 let rows: Vec<_> = rows
4776 .into_iter()
4777 .filter(|(_, file, ..)| pdf_rasterizer || !file.ends_with(".pdf"))
4778 .collect();
4779 let nodes: String = rows
4780 .iter()
4781 .map(|(id, file, options, ..)| {
4782 let path = tmp.join(file);
4783 format!(
4784 r#"<graphics graphic="{file}" candidates="{}" options="{options}" xml:id="{id}"/>"#,
4785 path.display()
4786 )
4787 })
4788 .collect();
4789 let xml = format!(
4790 r#"<?xml version="1.0"?><document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="d">{nodes}</document>"#
4791 );
4792 let dest = tmp.join("out").join("out.html");
4793 std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
4794 let doc_opts = PostDocumentOptions {
4795 destination: Some(dest.display().to_string()),
4796 source_directory: Some(tmp.path().display().to_string()),
4797 ..Default::default()
4798 };
4799 let doc = PostDocument::new_from_string(&xml, doc_opts).unwrap();
4800 let mut graphics = Graphics::new(None, true)
4802 .with_svg_threshold_kb(1)
4803 .with_cache_policy(CachePolicy::Bypass);
4804 let nodes = graphics.to_process(&doc);
4805 let out = graphics.process(doc, nodes).unwrap()[0].to_xml_string();
4806 let kept = |id: &str| {
4807 let at = out.find(&format!(r#"xml:id="{id}""#)).expect(id);
4808 let element = &out[out[..at].rfind('<').unwrap()..at + out[at..].find('>').unwrap()];
4809 let src = element
4810 .split(r#"imagesrc=""#)
4811 .nth(1)
4812 .unwrap_or_else(|| panic!("{element}"));
4813 let file = dest.parent().unwrap().join(&src[..src.find('"').unwrap()]);
4814 let file = file.to_str().unwrap();
4815 let got = run(convert, &[file, "-format", "%wx%h", "info:"]).unwrap();
4816 let histogram = run(convert, &[file, "-format", "%c", "histogram:info:-"]).unwrap();
4817 let mut colours: Vec<&str> = histogram
4818 .split_whitespace()
4819 .filter(|w| w.starts_with('#') && w.len() >= 7)
4820 .map(|w| &w[..7])
4821 .collect();
4822 colours.sort();
4823 format!("{id} {} {}", got, colours.join(","))
4824 };
4825 let got: Vec<String> = rows.iter().map(|row| kept(row.0)).collect();
4826 let want: Vec<String> = rows
4827 .iter()
4828 .map(|(id, _, _, size, colour)| format!("{id} {size} {colour}"))
4829 .collect();
4830 assert_eq!(got, want, "{out}");
4831 }
4832
4833 fn sized_render_rows(
4837 test: &str,
4838 src: &Path,
4839 dest: &Path,
4840 rows: &[(&str, &str, &str)],
4841 ) -> Option<Vec<(String, bool)>> {
4842 use latexml_core::util::image::{svg_attr_value, svg_root_tag};
4843
4844 use crate::{
4845 document::{PostDocument, PostDocumentOptions},
4846 graphics_cache::CachePolicy,
4847 };
4848 if !["mutool", "pdftocairo"]
4849 .iter()
4850 .any(|tool| svg_tool_or_skip(tool, test))
4851 {
4852 return None;
4853 }
4854 let nodes: String = rows
4855 .iter()
4856 .map(|(id, files, options)| {
4857 let candidates: Vec<String> = files
4858 .split(',')
4859 .map(|f| src.join(f).display().to_string())
4860 .collect();
4861 format!(
4862 r#"<graphics graphic="{}" candidates="{}" options="{options}" xml:id="{id}"/>"#,
4863 files.split(',').next().unwrap(),
4864 candidates.join(",")
4865 )
4866 })
4867 .collect();
4868 let xml = format!(
4869 r#"<?xml version="1.0"?><document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="d">{nodes}</document>"#
4870 );
4871 std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
4872 let doc_opts = PostDocumentOptions {
4873 destination: Some(dest.display().to_string()),
4874 source_directory: Some(src.display().to_string()),
4875 ..Default::default()
4876 };
4877 let doc = PostDocument::new_from_string(&xml, doc_opts).unwrap();
4878 let mut graphics = Graphics::new(None, true).with_cache_policy(CachePolicy::Bypass);
4879 let nodes = graphics.to_process(&doc);
4880 let out = graphics.process(doc, nodes).unwrap()[0].to_xml_string();
4881 let attr = |element: &str, name: &str| {
4882 svg_attr_value(element, name)
4883 .map(str::to_string)
4884 .unwrap_or_default()
4885 };
4886 let seen = |&(id, files, _): &(&str, &str, &str)| {
4887 let at = out.find(&format!(r#"xml:id="{id}""#)).expect(id);
4888 let element = &out[out[..at].rfind('<').unwrap()..at + out[at..].find('>').unwrap()];
4889 let file_src = attr(element, "imagesrc");
4890 let object = format!(
4891 "{file_src} {}x{}",
4892 attr(element, "imagewidth"),
4893 attr(element, "imageheight")
4894 );
4895 let file = std::fs::read(dest.parent().unwrap().join(&file_src)).unwrap();
4896 if !file_src.ends_with(".svg") {
4897 let first = files.split(',').next().unwrap();
4898 return (object, file == std::fs::read(src.join(first)).unwrap());
4899 }
4900 let text = String::from_utf8(file).unwrap();
4901 let root = svg_root_tag(&text).unwrap();
4902 let root = format!(
4903 "{} {}x{} viewBox={} par={}",
4904 file_src,
4905 attr(root, "width"),
4906 attr(root, "height"),
4907 attr(root, "viewBox"),
4908 attr(root, "preserveAspectRatio")
4909 );
4910 (format!("{object} | {root}"), true)
4911 };
4912 Some(rows.iter().map(seen).collect())
4913 }
4914
4915 #[test]
4921 fn a_sized_vector_render_carries_its_display_size() {
4922 let tmp = TempDir::new("graphics_svg_size");
4923 let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
4924 for name in ["trim_quadrants.pdf", "grid64.png"] {
4925 std::fs::copy(fixtures.join(name), tmp.join(name)).unwrap();
4926 }
4927 let rows = [
4929 (
4930 "height",
4931 "trim_quadrants.pdf",
4932 "height=170.0pt,keepaspectratio=true",
4933 ),
4934 (
4935 "again",
4936 "trim_quadrants.pdf",
4937 "height=170.0pt,keepaspectratio=true",
4938 ),
4939 (
4940 "width",
4941 "trim_quadrants.pdf",
4942 "width=345.0pt,keepaspectratio=true",
4943 ),
4944 ("natural", "trim_quadrants.pdf", ""),
4945 (
4946 "trim",
4947 "trim_quadrants.pdf",
4948 "trim=108.405pt 0.0pt 0.0pt 54.2025pt,clip=true,width=100.0pt",
4949 ),
4950 (
4951 "stretch",
4952 "trim_quadrants.pdf",
4953 "width=100.0pt,height=100.0pt",
4954 ),
4955 ("scale", "trim_quadrants.pdf", "scale=0.5"),
4956 ("xscale", "trim_quadrants.pdf", "xscale=0.5"),
4957 ("raster", "grid64.png", "width=100.0pt,keepaspectratio=true"),
4958 ("negscale", "trim_quadrants.pdf", "scale=-1"),
4959 (
4960 "negwidth",
4961 "trim_quadrants.pdf",
4962 "width=-100.0pt,keepaspectratio=true",
4963 ),
4964 ];
4965 let dest = tmp.join("out").join("out.html");
4966 let Some(got) = sized_render_rows(
4967 "a_sized_vector_render_carries_its_display_size",
4968 tmp.path(),
4969 &dest,
4970 &rows,
4971 ) else {
4972 return;
4973 };
4974 let natural = &got[3].0;
4976 let (nw, nh, ow, oh) = if natural.contains(" 216ptx108pt ") {
4977 ("216pt", "108pt", 288, 144)
4978 } else {
4979 ("216", "108", 216, 108)
4980 };
4981 let natural = format!("x2.svg {nw}x{nh} viewBox=0 0 216 108 par=");
4983 let want: Vec<(String, bool)> = [
4984 "trim_quadrants.svg 452x226 | trim_quadrants.svg 452x226 viewBox=0 0 216 108 par="
4985 .to_string(),
4986 "trim_quadrants.svg 452x226 | trim_quadrants.svg 452x226 viewBox=0 0 216 108 par="
4987 .to_string(),
4988 "x1.svg 459x230 | x1.svg 459x230 viewBox=0 0 216 108 par=".to_string(),
4989 format!("x2.svg {ow}x{oh} | {natural}"),
4990 "x3.svg 133x67 | x3.svg 133x67 viewBox=108 54 108 54 par=".to_string(),
4991 "x4.svg 133x133 | x4.svg 133x133 viewBox=0 0 216 108 par=none".to_string(),
4992 format!(
4993 "x5.svg {0}x{1} | x5.svg {0}x{1} viewBox=0 0 216 108 par=",
4994 ow / 2,
4995 oh / 2
4996 ),
4997 format!(
4998 "x6.svg {0}x{1} | x6.svg {0}x{1} viewBox=0 0 216 108 par=none",
4999 ow / 2,
5000 oh
5001 ),
5002 "grid64.png 133x133".to_string(),
5003 format!("x2.svg 1x1 | {natural}"),
5004 format!("x2.svg 1x1 | {natural}"),
5005 ]
5006 .into_iter()
5007 .map(|row| (row, true))
5008 .collect();
5009 assert_eq!(got, want);
5010 }
5011
5012 #[test]
5017 fn a_figure_converted_in_place_again_reads_the_authors_source() {
5018 let tmp = TempDir::new("graphics_svg_inplace");
5019 let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
5020 std::fs::copy(
5021 fixtures.join("trim_quadrants.pdf"),
5022 tmp.join("trim_quadrants.pdf"),
5023 )
5024 .unwrap();
5025 let test = "a_figure_converted_in_place_again_reads_the_authors_source";
5026 let dest = tmp.join("inplace.html");
5027 let run = || {
5029 let files: Vec<&str> = ["pdf", "png", "svg"]
5030 .into_iter()
5031 .filter(|ext| tmp.join(&format!("trim_quadrants.{ext}")).exists())
5032 .map(|ext| match ext {
5033 "pdf" => "trim_quadrants.pdf",
5034 "png" => "trim_quadrants.png",
5035 _ => "trim_quadrants.svg",
5036 })
5037 .collect();
5038 let files = files.join(",");
5039 sized_render_rows(test, tmp.path(), &dest, &[
5040 ("wide", &files, "width=200.0pt,keepaspectratio=true"),
5041 ("natural", &files, ""),
5042 ("low", &files, "height=40.0pt,keepaspectratio=true"),
5043 (
5044 "trim",
5045 &files,
5046 "trim=108.405pt 0.0pt 0.0pt 54.2025pt,clip=true",
5047 ),
5048 ])
5049 };
5050 let Some(first) = run() else {
5051 return;
5052 };
5053 let (nw, nh, ow, oh) = if first[1].0.contains(" 216ptx108pt ") {
5054 ("216pt", "108pt", 288, 144)
5055 } else {
5056 ("216", "108", 216, 108)
5057 };
5058 let (cw, ch) = if nw == "216pt" {
5059 ("108pt", "54pt")
5060 } else {
5061 ("108", "54")
5062 };
5063 let want: Vec<(String, bool)> = [
5064 "x1.svg 266x133 | x1.svg 266x133 viewBox=0 0 216 108 par=".to_string(),
5065 format!(
5066 "trim_quadrants.svg {ow}x{oh} | trim_quadrants.svg {nw}x{nh} viewBox=0 0 216 108 par="
5067 ),
5068 "x2.svg 107x54 | x2.svg 107x54 viewBox=0 0 216 108 par=".to_string(),
5069 format!(
5070 "x3.svg {}x{} | x3.svg {cw}x{ch} viewBox=108 54 108 54 par=",
5071 ow / 2,
5072 oh / 2
5073 ),
5074 ]
5075 .into_iter()
5076 .map(|row| (row, true))
5077 .collect();
5078 assert_eq!(first, want);
5079 assert_eq!(run().unwrap(), want, "the second run");
5080 assert_eq!(run().unwrap(), want, "the third run");
5081 let mut files: Vec<String> = std::fs::read_dir(tmp.path())
5082 .unwrap()
5083 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
5084 .filter(|name| !name.starts_with("LaTeXML-oxide.cache") && !name.starts_with("inplace"))
5085 .collect();
5086 files.sort();
5087 assert_eq!(files, [
5088 "trim_quadrants.pdf",
5089 "trim_quadrants.svg",
5090 "x1.svg",
5091 "x2.svg",
5092 "x3.svg"
5093 ]);
5094 for side in ["", "-wal", "-shm"] {
5095 let _ = std::fs::remove_file(tmp.join(&format!("LaTeXML-oxide.cache{side}")));
5096 }
5097 let natural = &run().unwrap()[1].0;
5098 assert!(
5099 natural.contains(&format!(" {ow}x{oh} | "))
5100 && natural.ends_with(&format!(" {nw}x{nh} viewBox=0 0 216 108 par=")),
5101 "without the cache: {natural}"
5102 );
5103 }
5104
5105 #[test]
5113 #[cfg(unix)]
5114 fn a_crop_gets_its_own_file_and_a_zero_trim_none() {
5115 use std::os::unix::fs::PermissionsExt;
5116
5117 use latexml_core::common::error::{LogStatus, get_status};
5118
5119 use crate::{
5120 document::{PostDocument, PostDocumentOptions},
5121 graphics_cache::CachePolicy,
5122 };
5123
5124 let tmp = TempDir::new("graphics_crop_route");
5125 let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
5127 png.extend_from_slice(&13u32.to_be_bytes());
5128 png.extend_from_slice(b"IHDR");
5129 png.extend_from_slice(&200u32.to_be_bytes());
5130 png.extend_from_slice(&100u32.to_be_bytes());
5131 png.extend_from_slice(&[8, 2, 0, 0, 0, 0, 0, 0, 0]);
5132 png.extend_from_slice(&[0u8; 16]);
5133 let img = tmp.join("img.png");
5134 std::fs::write(&img, &png).unwrap();
5135 let authors_png = [png.clone(), vec![1]].concat();
5137 let authors_x1 = tmp.join("x1.png");
5138 std::fs::write(&authors_x1, &authors_png).unwrap();
5139 let log = tmp.join("convert.log");
5140 let fake_convert = tmp.join("convert");
5141 std::fs::write(
5142 &fake_convert,
5143 "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$(dirname \"$0\")/convert.log\"\n\
5144 for a in \"$@\"; do d=\"$a\"; done\nprintf x > \"$d\"\nexit 0\n",
5145 )
5146 .unwrap();
5147 let mut perms = std::fs::metadata(&fake_convert).unwrap().permissions();
5148 perms.set_mode(0o755);
5149 std::fs::set_permissions(&fake_convert, perms).unwrap();
5150 let mut env = EnvGuard::acquire();
5151 let old_path = std::env::var("PATH").unwrap_or_default();
5152 env.set("PATH", &format!("{}:{}", tmp.path().display(), old_path));
5153
5154 let dest = tmp.join("out").join("out.html");
5155 std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
5156 let xml = format!(
5157 r#"<?xml version="1.0"?>
5158<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="d">
5159 <graphics graphic="img" candidates="{0}" options="trim=100.375pt 0.0pt 0.0pt 50.1875pt,clip=true" xml:id="g1"/>
5160 <graphics graphic="img" candidates="{0}" options="trim=0.0pt 0.0pt 0.0pt 0.0pt,clip=true" xml:id="g2"/>
5161 <graphics graphic="x1" candidates="{1}" xml:id="g3"/>
5162</document>"#,
5163 img.display(),
5164 authors_x1.display()
5165 );
5166 let doc_opts = PostDocumentOptions {
5167 destination: Some(dest.display().to_string()),
5168 source_directory: Some(tmp.path().display().to_string()),
5169 ..Default::default()
5170 };
5171 let doc = PostDocument::new_from_string(&xml, doc_opts).unwrap();
5172 let mut graphics = Graphics::new(None, true).with_cache_policy(CachePolicy::Bypass);
5173 let nodes = graphics.to_process(&doc);
5174 let warnings = get_status(LogStatus::Warning);
5175 let out = graphics.process(doc, nodes).unwrap()[0].to_xml_string();
5176 assert_eq!(get_status(LogStatus::Warning), warnings, "{out}");
5177 let invocations = std::fs::read_to_string(&log).unwrap_or_default();
5178 assert_eq!(invocations.lines().count(), 1, "{invocations}");
5179 assert!(
5180 invocations.contains("-crop 100x50+100+50 +repage"),
5181 "{invocations}"
5182 );
5183 for (id, src, w, h) in [
5185 ("g1", "x2.png", 133, 67),
5186 ("g2", "img.png", 267, 133),
5187 ("g3", "x1.png", 267, 133),
5188 ] {
5189 let at = out.find(&format!(r#"xml:id="{id}""#)).unwrap();
5190 let element = &out[out[..at].rfind('<').unwrap()..at + out[at..].find('>').unwrap()];
5191 for attr in [
5192 format!(r#"imagesrc="{src}""#),
5193 format!(r#"imagewidth="{w}""#),
5194 format!(r#"imageheight="{h}""#),
5195 ] {
5196 assert!(element.contains(&attr), "{id}: {attr} missing in {element}");
5197 }
5198 }
5199 let copied = std::fs::read(dest.parent().unwrap().join("x1.png")).unwrap();
5200 assert_eq!(
5201 copied, authors_png,
5202 "the author's x1.png must reach the output unchanged"
5203 );
5204 }
5205
5206 #[test]
5209 #[cfg(unix)]
5210 fn a_single_page_source_ignores_page() {
5211 use std::os::unix::fs::PermissionsExt;
5212
5213 use crate::{
5214 document::{PostDocument, PostDocumentOptions},
5215 graphics_cache::CachePolicy,
5216 };
5217
5218 let tmp = TempDir::new("graphics_single_page");
5219 let svg_body = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100pt" height="50pt" viewBox="0 0 100 50"><rect/></svg>"#;
5220 let svg = tmp.join("draw.svg");
5221 std::fs::write(&svg, svg_body).unwrap();
5222 let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
5223 png.extend_from_slice(&13u32.to_be_bytes());
5224 png.extend_from_slice(b"IHDR");
5225 png.extend_from_slice(&200u32.to_be_bytes());
5226 png.extend_from_slice(&100u32.to_be_bytes());
5227 png.extend_from_slice(&[8, 2, 0, 0, 0, 0, 0, 0, 0]);
5228 png.extend_from_slice(&[0u8; 16]);
5229 let img = tmp.join("img.png");
5230 std::fs::write(&img, &png).unwrap();
5231 let jpg_bytes: &[u8] = &[
5233 0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x11, 0x08, 0x00, 0x64, 0x00, 0xC8, 0x03, 0x01, 0x22, 0x00,
5234 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xFF, 0xD9,
5235 ];
5236 let jpg = tmp.join("pic.jpg");
5237 std::fs::write(&jpg, jpg_bytes).unwrap();
5238
5239 let log = tmp.join("convert.log");
5240 let fake_convert = tmp.join("convert");
5241 std::fs::write(
5242 &fake_convert,
5243 "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$(dirname \"$0\")/convert.log\"\n\
5244 for a in \"$@\"; do d=\"$a\"; done\nprintf x > \"$d\"\nexit 0\n",
5245 )
5246 .unwrap();
5247 let mut perms = std::fs::metadata(&fake_convert).unwrap().permissions();
5248 perms.set_mode(0o755);
5249 std::fs::set_permissions(&fake_convert, perms).unwrap();
5250 let mut env = EnvGuard::acquire();
5251 let old_path = std::env::var("PATH").unwrap_or_default();
5252 env.set("PATH", &format!("{}:{}", tmp.path().display(), old_path));
5253
5254 let dest = tmp.join("out").join("out.html");
5255 std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
5256 let xml = format!(
5257 r#"<?xml version="1.0"?>
5258<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="d">
5259 <graphics graphic="draw" candidates="{0}" options="page=1" xml:id="g1"/>
5260 <graphics graphic="draw" candidates="{0}" xml:id="g2"/>
5261 <graphics graphic="draw" candidates="{0}" options="page=2" xml:id="g3"/>
5262 <graphics graphic="img" candidates="{1}" options="page=2" xml:id="g4"/>
5263 <graphics graphic="pic" candidates="{2}" options="page=1" xml:id="g5"/>
5264</document>"#,
5265 svg.display(),
5266 img.display(),
5267 jpg.display()
5268 );
5269 let doc_opts = PostDocumentOptions {
5270 destination: Some(dest.display().to_string()),
5271 source_directory: Some(tmp.path().display().to_string()),
5272 ..Default::default()
5273 };
5274 let doc = PostDocument::new_from_string(&xml, doc_opts).unwrap();
5275 let mut graphics = Graphics::new(None, true).with_cache_policy(CachePolicy::Bypass);
5276 let nodes = graphics.to_process(&doc);
5277 let out = graphics.process(doc, nodes).unwrap()[0].to_xml_string();
5278 let invocations = std::fs::read_to_string(&log).unwrap_or_default();
5279 assert_eq!(invocations, "", "no single-page source reaches `convert`");
5280 let element = |id: &str| {
5281 let at = out.find(&format!(r#"xml:id="{id}""#)).unwrap();
5282 let tag = &out[out[..at].rfind('<').unwrap()..at + out[at..].find('>').unwrap()];
5283 let attr = |name: &str| {
5284 let at = tag.find(&format!(" {name}=\""))? + name.len() + 3;
5285 Some(tag[at..at + tag[at..].find('"')?].to_string())
5286 };
5287 (attr("imagesrc"), attr("imagewidth"), attr("imageheight"))
5288 };
5289 let svg_size = element("g2");
5290 assert_eq!(svg_size.0.as_deref(), Some("draw.svg"), "{out}");
5291 assert!(svg_size.1.is_some() && svg_size.2.is_some(), "{out}");
5292 for id in ["g1", "g3"] {
5293 assert_eq!(element(id), svg_size, "{id}: as without page=; {out}");
5294 }
5295 let raster = |src: &str| {
5297 (
5298 Some(src.to_string()),
5299 Some("267".to_string()),
5300 Some("133".to_string()),
5301 )
5302 };
5303 assert_eq!(element("g4"), raster("img.png"), "{out}");
5304 assert_eq!(element("g5"), raster("pic.jpg"), "{out}");
5305 let out_dir = dest.parent().unwrap();
5306 assert_eq!(
5307 std::fs::read_to_string(out_dir.join("draw.svg")).unwrap(),
5308 svg_body
5309 );
5310 assert_eq!(std::fs::read(out_dir.join("img.png")).unwrap(), png);
5311 assert_eq!(std::fs::read(out_dir.join("pic.jpg")).unwrap(), jpg_bytes);
5312 }
5313
5314 #[test]
5329 #[cfg(unix)]
5330 fn rotation_is_dropped_for_non_raster_sources_but_kept_for_raster() {
5331 use std::os::unix::fs::PermissionsExt;
5332
5333 use crate::{
5334 document::{PostDocument, PostDocumentOptions},
5335 graphics_cache::CachePolicy,
5336 };
5337
5338 let tmp = TempDir::new("graphics_nonraster_rotate");
5339 let svg_body = r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40"><rect/></svg>"#;
5340 let svg = tmp.join("draw.svg");
5341 std::fs::write(&svg, svg_body).unwrap();
5342 let png = tmp.join("dot.png");
5344 std::fs::write(&png, ONE_PIXEL_PNG).unwrap();
5345
5346 let log = tmp.join("convert.log");
5347 let fake_convert = tmp.join("convert");
5348 std::fs::write(
5349 &fake_convert,
5350 "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$(dirname \"$0\")/convert.log\"\n\
5351 for a in \"$@\"; do d=\"$a\"; done\nprintf x > \"$d\"\nexit 0\n",
5352 )
5353 .unwrap();
5354 let mut perms = std::fs::metadata(&fake_convert).unwrap().permissions();
5355 perms.set_mode(0o755);
5356 std::fs::set_permissions(&fake_convert, perms).unwrap();
5357
5358 let old_path = std::env::var("PATH").unwrap_or_default();
5359 let mut env = EnvGuard::acquire();
5360 env.set("PATH", &format!("{}:{}", tmp.path().display(), old_path));
5361
5362 let dest = tmp.join("sub").join("out.html");
5363 std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
5364 let xml = format!(
5365 r#"<?xml version="1.0"?>
5366<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="d">
5367 <graphics graphic="draw" candidates="{}" options="angle=90" xml:id="g1"/>
5368 <graphics graphic="dot" candidates="{}" options="angle=90" xml:id="g2"/>
5369</document>"#,
5370 svg.display(),
5371 png.display()
5372 );
5373 let doc_opts = PostDocumentOptions {
5374 destination: Some(dest.display().to_string()),
5375 source_directory: Some(tmp.path().display().to_string()),
5376 ..Default::default()
5377 };
5378 let doc = PostDocument::new_from_string(&xml, doc_opts).unwrap();
5379 let mut graphics = Graphics::new(None, true).with_cache_policy(CachePolicy::Bypass);
5380 let nodes = graphics.to_process(&doc);
5381 assert_eq!(nodes.len(), 2);
5382 graphics.process(doc, nodes).unwrap();
5383
5384 let out_svg = dest.parent().unwrap().join("draw.svg");
5385 assert_eq!(
5386 std::fs::read_to_string(&out_svg).ok().as_deref(),
5387 Some(svg_body),
5388 "the copied SVG must be the original drawing, not a `convert` rewrite"
5389 );
5390 let invocations = std::fs::read_to_string(&log).unwrap_or_default();
5393 let calls_for = |name: &str| invocations.lines().filter(|l| l.contains(name)).count();
5394 assert_eq!(
5395 calls_for("draw.svg"),
5396 0,
5397 "`convert` must not be invoked for a non-raster source; log was:\n{invocations}"
5398 );
5399 assert_eq!(
5401 calls_for("-rotate"),
5402 1,
5403 "a raster source with angle= must still be rotated; log was:\n{invocations}"
5404 );
5405 }
5406
5407 #[test]
5424 fn apply_graphicx_transforms_matrix() {
5425 #[rustfmt::skip]
5426 let matrix: &[(&str, u32, u32)] = &[
5427 ("", 267, 133), ("width=100pt", 133, 67),
5429 ("width=100pt,keepaspectratio=true", 133, 67),
5430 ("scale=0.5", 134, 67), ("height=25pt,keepaspectratio=true", 67, 34),
5432 ("width=100pt,height=80pt", 133, 107),
5433 ("width=1in,keepaspectratio=true", 96, 48), ("width=2cm", 76, 38), ("angle=90", 133, 267),
5436 ("width=137.9979pt,keepaspectratio=true", 184, 92), ];
5438 let mut deltas = Vec::new();
5441 for (opts, want_w, want_h) in matrix {
5442 let got = Graphics::apply_graphicx_transforms(200, 100, opts, 96);
5443 if got != (*want_w, *want_h) {
5444 deltas.push(format!(
5445 " [{opts}] pinned ({want_w}, {want_h}) got {got:?}"
5446 ));
5447 }
5448 }
5449 assert!(
5450 deltas.is_empty(),
5451 "{} of {} pinned rows moved:\n{}",
5452 deltas.len(),
5453 matrix.len(),
5454 deltas.join("\n")
5455 );
5456 }
5457
5458 #[test]
5462 fn one_inch_is_96_px_whatever_the_source() {
5463 use crate::{
5464 document::{PostDocument, PostDocumentOptions},
5465 graphics_cache::CachePolicy,
5466 };
5467 let tmp = TempDir::new("graphics_one_inch");
5468 let png = |name: &str, w: u32, h: u32, per_metre: Option<u32>| {
5470 let mut v = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
5471 v.extend_from_slice(&13u32.to_be_bytes());
5472 v.extend_from_slice(b"IHDR");
5473 v.extend_from_slice(&w.to_be_bytes());
5474 v.extend_from_slice(&h.to_be_bytes());
5475 v.extend_from_slice(&[8, 2, 0, 0, 0, 0, 0, 0, 0]);
5476 if let Some(m) = per_metre {
5477 v.extend_from_slice(&9u32.to_be_bytes());
5478 v.extend_from_slice(b"pHYs");
5479 v.extend_from_slice(&m.to_be_bytes());
5480 v.extend_from_slice(&m.to_be_bytes());
5481 v.extend_from_slice(&[1, 0, 0, 0, 0]);
5482 }
5483 v.extend_from_slice(&[0u8; 16]);
5484 let path = tmp.join(name);
5485 std::fs::write(&path, v).unwrap();
5486 path.display().to_string()
5487 };
5488 let p72 = png("p72.png", 72, 36, None);
5489 let p300 = png("p300.png", 300, 150, Some(11811));
5490 let wide = png("wide.png", 200, 100, None);
5491 let svg = tmp.join("inch.svg");
5492 std::fs::write(
5493 &svg,
5494 r#"<svg xmlns="http://www.w3.org/2000/svg" width="1in" height="0.5in"><rect/></svg>"#,
5495 )
5496 .unwrap();
5497 let dest = tmp.join("out").join("out.html");
5498 std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
5499 let sizes = |pi: &str| {
5500 let xml = format!(
5501 r#"<?xml version="1.0"?>{pi}
5502<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="d">
5503 <graphics graphic="p72" candidates="{p72}" xml:id="g1"/>
5504 <graphics graphic="p300" candidates="{p300}" xml:id="g2"/>
5505 <graphics graphic="inch" candidates="{}" xml:id="g3"/>
5506 <graphics graphic="wide" candidates="{wide}" options="width=72.27pt,keepaspectratio=true" xml:id="g4"/>
5507</document>"#,
5508 svg.display()
5509 );
5510 let doc_opts = PostDocumentOptions {
5511 destination: Some(dest.display().to_string()),
5512 source_directory: Some(tmp.path().display().to_string()),
5513 ..Default::default()
5514 };
5515 let doc = PostDocument::new_from_string(&xml, doc_opts).unwrap();
5516 let mut graphics = Graphics::new(None, true).with_cache_policy(CachePolicy::Bypass);
5517 let nodes = graphics.to_process(&doc);
5518 let doc = graphics.process(doc, nodes).unwrap().remove(0);
5519 doc
5520 .findnodes("//ltx:graphics")
5521 .iter()
5522 .map(|n| {
5523 format!(
5524 "{}x{}",
5525 n.get_attribute("imagewidth").unwrap_or_default(),
5526 n.get_attribute("imageheight").unwrap_or_default()
5527 )
5528 })
5529 .collect::<Vec<_>>()
5530 };
5531 assert_eq!(sizes(""), ["96x48", "96x48", "96x48", "96x48"]);
5532 assert_eq!(sizes(r#"<?latexml DPI="100"?>"#), [
5533 "100x50", "100x50", "100x50", "100x50"
5534 ]);
5535 }
5536
5537 #[test]
5542 fn a_too_small_resolution_is_read_at_72_dpi() {
5543 use crate::{
5544 document::{PostDocument, PostDocumentOptions},
5545 graphics_cache::CachePolicy,
5546 };
5547 let tmp = TempDir::new("graphics_too_small_resolution");
5548 let png = |name: &str, x: u32, y: u32| {
5550 let mut v = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
5551 v.extend_from_slice(&13u32.to_be_bytes());
5552 v.extend_from_slice(b"IHDR");
5553 v.extend_from_slice(&300u32.to_be_bytes());
5554 v.extend_from_slice(&150u32.to_be_bytes());
5555 v.extend_from_slice(&[8, 2, 0, 0, 0, 0, 0, 0, 0]);
5556 v.extend_from_slice(&9u32.to_be_bytes());
5557 v.extend_from_slice(b"pHYs");
5558 v.extend_from_slice(&x.to_be_bytes());
5559 v.extend_from_slice(&y.to_be_bytes());
5560 v.extend_from_slice(&[1, 0, 0, 0, 0]);
5561 v.extend_from_slice(&[0u8; 16]);
5562 let path = tmp.join(name);
5563 std::fs::write(&path, v).unwrap();
5564 path.display().to_string()
5565 };
5566 let (one, zero, two) = (
5567 png("one.png", 39, 39),
5568 png("zero.png", 0, 11811),
5569 png("two.png", 79, 79),
5570 );
5571 let dest = tmp.join("out").join("out.html");
5572 std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
5573 let xml = format!(
5574 r#"<?xml version="1.0"?>
5575<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="d">
5576 <graphics graphic="one" candidates="{one}" xml:id="g1"/>
5577 <graphics graphic="zero" candidates="{zero}" xml:id="g2"/>
5578 <graphics graphic="two" candidates="{two}" xml:id="g3"/>
5579</document>"#
5580 );
5581 let doc_opts = PostDocumentOptions {
5582 destination: Some(dest.display().to_string()),
5583 source_directory: Some(tmp.path().display().to_string()),
5584 ..Default::default()
5585 };
5586 let doc = PostDocument::new_from_string(&xml, doc_opts).unwrap();
5587 let mut graphics = Graphics::new(None, true).with_cache_policy(CachePolicy::Bypass);
5588 let nodes = graphics.to_process(&doc);
5589 let doc = graphics.process(doc, nodes).unwrap().remove(0);
5590 let sizes: Vec<String> = doc
5591 .findnodes("//ltx:graphics")
5592 .iter()
5593 .map(|n| {
5594 format!(
5595 "{}x{}",
5596 n.get_attribute("imagewidth").unwrap_or_default(),
5597 n.get_attribute("imageheight").unwrap_or_default()
5598 )
5599 })
5600 .collect();
5601 assert_eq!(sizes, ["400x200", "400x200", "14400x7200"]);
5602 }
5603
5604 #[test]
5611 #[cfg(unix)]
5612 fn a_drawn_source_is_read_at_its_render_density_whatever_its_name() {
5613 use std::os::unix::fs::PermissionsExt;
5614
5615 use crate::{
5616 document::{PostDocument, PostDocumentOptions},
5617 graphics_cache::CachePolicy,
5618 };
5619 let tmp = TempDir::new("graphics_drawn_by_content");
5620 let png = |w: u32, h: u32, per_metre: Option<u32>| {
5622 let mut v = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
5623 v.extend_from_slice(&13u32.to_be_bytes());
5624 v.extend_from_slice(b"IHDR");
5625 v.extend_from_slice(&w.to_be_bytes());
5626 v.extend_from_slice(&h.to_be_bytes());
5627 v.extend_from_slice(&[8, 2, 0, 0, 0, 0, 0, 0, 0]);
5628 if let Some(m) = per_metre {
5629 v.extend_from_slice(&9u32.to_be_bytes());
5630 v.extend_from_slice(b"pHYs");
5631 v.extend_from_slice(&m.to_be_bytes());
5632 v.extend_from_slice(&m.to_be_bytes());
5633 v.extend_from_slice(&[1, 0, 0, 0, 0]);
5634 }
5635 v.extend_from_slice(&[0u8; 16]);
5636 v
5637 };
5638 let write = |name: &str, bytes: &[u8]| {
5639 let path = tmp.join(name);
5640 std::fs::write(&path, bytes).unwrap();
5641 path.display().to_string()
5642 };
5643 let figx = write("figx.pstex", b"%PDF-1.4\n<< /MediaBox [0 0 200 100] >>\n");
5644 write("figx.pstex.render", &png(333, 167, None));
5645 let eps = b"%!PS-Adobe-2.0 EPSF-2.0\n%%BoundingBox: 0 0 446 202\n%%EndComments\n";
5646 let lp = write("loop.pstex", eps);
5647 write("loop.pstex.render", &png(743, 337, None));
5648 let big = write("big.pstex", b"%PDF-1.4\n<< /MediaBox [0 0 2000 1000] >>\n");
5649 write("big.pstex.render", &png(2028, 1014, None));
5650 let scan = write("scan.dat", &png(600, 300, Some(11811)));
5651 write("scan.dat.render", &png(600, 300, Some(11811)));
5652 let fake_convert = tmp.join("convert");
5653 std::fs::write(
5654 &fake_convert,
5655 "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$(dirname \"$0\")/convert.log\"\n\
5656 for a in \"$@\"; do s=\"$d\"; d=\"$a\"; done\ncp \"$s.render\" \"$d\"\n",
5657 )
5658 .unwrap();
5659 let mut perms = std::fs::metadata(&fake_convert).unwrap().permissions();
5660 perms.set_mode(0o755);
5661 std::fs::set_permissions(&fake_convert, perms).unwrap();
5662 let mut env = EnvGuard::acquire();
5663 let old_path = std::env::var("PATH").unwrap_or_default();
5664 env.set("PATH", &format!("{}:{}", tmp.path().display(), old_path));
5665 let dest = tmp.join("out").join("out.html");
5666 std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
5667 let xml = format!(
5668 r#"<?xml version="1.0"?>
5669<document xmlns="http://dlmf.nist.gov/LaTeXML" xml:id="d">
5670 <graphics graphic="figx.pstex" candidates="{figx}" options="scale=0.5" xml:id="g1"/>
5671 <graphics graphic="loop.pstex" candidates="{lp}" xml:id="g2"/>
5672 <graphics graphic="big.pstex" candidates="{big}" xml:id="g3"/>
5673 <graphics graphic="scan.dat" candidates="{scan}" xml:id="g4"/>
5674</document>"#
5675 );
5676 let doc_opts = PostDocumentOptions {
5677 destination: Some(dest.display().to_string()),
5678 source_directory: Some(tmp.path().display().to_string()),
5679 ..Default::default()
5680 };
5681 let doc = PostDocument::new_from_string(&xml, doc_opts).unwrap();
5682 let mut graphics = Graphics::new(None, true).with_cache_policy(CachePolicy::Bypass);
5683 let nodes = graphics.to_process(&doc);
5684 let doc = graphics.process(doc, nodes).unwrap().remove(0);
5685 let sizes: Vec<String> = doc
5686 .findnodes("//ltx:graphics")
5687 .iter()
5688 .map(|n| {
5689 format!(
5690 "{}x{}",
5691 n.get_attribute("imagewidth").unwrap_or_default(),
5692 n.get_attribute("imageheight").unwrap_or_default()
5693 )
5694 })
5695 .collect();
5696 assert_eq!(sizes, ["134x67", "594x270", "2667x1333", "192x96"]);
5699 let log = std::fs::read_to_string(tmp.join("convert.log")).unwrap_or_default();
5700 let density_of = |name: &str| {
5701 let line = log.lines().find(|l| l.contains(name)).unwrap_or_default();
5702 line
5703 .split("-density ")
5704 .nth(1)
5705 .and_then(|r| r.split(' ').next())
5706 .map(str::to_string)
5707 };
5708 assert_eq!(
5709 ["figx", "loop", "big"].map(density_of),
5710 [
5711 Some("120".to_string()),
5712 Some("120".to_string()),
5713 Some("73".to_string())
5714 ],
5715 "{log}"
5716 );
5717 }
5718
5719 #[test]
5728 fn set_graphic_src_emits_requested_aspect_ratio_2392() {
5729 let doc = libxml::tree::Document::new().unwrap();
5730 for (w, h, bucket) in [
5731 (200u32, 100u32, "ltx_img_landscape"),
5732 (476, 476, "ltx_img_square"),
5733 ] {
5734 let mut node = Node::new("graphics", None, &doc).unwrap();
5735 Graphics::set_graphic_src(&mut node, "fig.png", Some(w), Some(h));
5736 let style = node.get_attribute("cssstyle").unwrap_or_default();
5737 assert!(
5738 style.contains(&format!("aspect-ratio:{w}/{h}")),
5739 "expected the requested aspect-ratio {w}/{h} in cssstyle, got {style:?}"
5740 );
5741 assert!(
5742 node
5743 .get_attribute("class")
5744 .unwrap_or_default()
5745 .contains(bucket)
5746 );
5747 }
5748 }
5749
5750 #[test]
5756 fn flex_graphics_css_frees_height_for_aspect_ratio_2392() {
5757 let css = include_str!("../resources/CSS/LaTeXML.css");
5758 assert!(
5759 css.contains(".ltx_flex_figure .ltx_graphics { height: auto; }"),
5760 "the flex-graphics height:auto companion to #2392's aspect-ratio is missing from LaTeXML.css"
5761 );
5762 }
5763
5764 #[test]
5769 fn read_source_dimensions_dispatch_matrix() {
5770 let tmp = TempDir::new("post_dispatch");
5771 let svg = tmp.join("a.svg");
5772 std::fs::write(&svg, r#"<svg viewBox="0 0 200 100"><rect/></svg>"#).unwrap();
5773 let svg_upper = tmp.join("B.SVG");
5774 std::fs::write(&svg_upper, r#"<svg viewBox="0 0 60 40"><rect/></svg>"#).unwrap();
5775 let png = tmp.join("c.png");
5776 std::fs::write(&png, ONE_PIXEL_PNG).unwrap();
5777 let eps = tmp.join("d.eps");
5778 std::fs::write(
5779 &eps,
5780 "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 200 100\n",
5781 )
5782 .unwrap();
5783
5784 let dims = |p: &Path| Graphics::read_source_dimensions(p.to_str().unwrap());
5785 assert_eq!(dims(&svg), Some((200, 100)), "svg via viewBox");
5786 assert_eq!(
5787 dims(&svg_upper),
5788 Some((60, 40)),
5789 "extension match is case-insensitive"
5790 );
5791 assert_eq!(dims(&png), Some((1, 1)), "png via imagesize");
5792 assert_eq!(dims(&eps), None, "EPS is unmeasurable here, by design");
5793 }
5794
5795 #[test]
5798 fn postscript_bounding_box_forms() {
5799 let tmp = TempDir::new("post_psbbox");
5800 let offset = tmp.join("o.eps");
5801 std::fs::write(
5802 &offset,
5803 "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 210 120\n",
5804 )
5805 .unwrap();
5806 assert_eq!(
5807 read_postscript_bounding_box(offset.to_str().unwrap()),
5808 Some((200.0, 100.0)),
5809 "extent, not corners"
5810 );
5811 assert_eq!(
5812 read_postscript_bounding_box_full(offset.to_str().unwrap()),
5813 Some((10.0, 20.0, 200.0, 100.0)),
5814 "full form is (llx, lly, width, height) — NOT (llx,lly,urx,ury)"
5815 );
5816 let atend = tmp.join("a.eps");
5818 std::fs::write(
5819 &atend,
5820 "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: (atend)\nstuff\n%%BoundingBox: 0 0 300 150\n",
5821 )
5822 .unwrap();
5823 assert_eq!(
5824 read_postscript_bounding_box(atend.to_str().unwrap()),
5825 Some((300.0, 150.0))
5826 );
5827 }
5828
5829 #[test]
5833 fn raster_density_is_capped_by_source_box_size() {
5834 let tmp = TempDir::new("post_density");
5835 let small = tmp.join("s.eps");
5836 std::fs::write(
5837 &small,
5838 "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 200 100\n",
5839 )
5840 .unwrap();
5841 assert_eq!(
5842 Graphics::raster_density_for_source(small.to_str().unwrap()),
5843 120
5844 );
5845
5846 let pdf = tmp.join("s.pdf");
5847 std::fs::write(&pdf, "%PDF-1.4\n<< /MediaBox [0 0 200 100] >>\n").unwrap();
5848 assert_eq!(
5849 Graphics::raster_density_for_source(pdf.to_str().unwrap()),
5850 120
5851 );
5852
5853 let png = tmp.join("s.png");
5855 std::fs::write(&png, ONE_PIXEL_PNG).unwrap();
5856 assert_eq!(
5857 Graphics::raster_density_for_source(png.to_str().unwrap()),
5858 120
5859 );
5860
5861 let big = tmp.join("b.eps");
5864 std::fs::write(
5865 &big,
5866 "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 2000 1000\n",
5867 )
5868 .unwrap();
5869 assert_eq!(
5870 Graphics::raster_density_for_source(big.to_str().unwrap()),
5871 73
5872 );
5873 }
5874
5875 const ONE_PIXEL_PNG: &[u8] = &[
5878 0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, b'I', b'H', b'D', b'R', 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53, 0xde, 0x00, 0x00, 0x00, 0x0c, b'I', b'D', b'A', b'T', 0x08, 0xd7, 0x63, 0xf8, 0xcf, 0xc0, 0x00, 0x00, 0x03, 0x01, 0x01, 0x00, 0x18, 0xdd, 0x8d,
5884 0xb0, 0x00, 0x00, 0x00, 0x00, b'I', b'E', b'N', b'D', 0xae, 0x42, 0x60, 0x82,
5886 ];
5887
5888 #[test]
5899 fn worker_diagnostics_fold_into_main_thread_on_join() {
5900 let _ = latexml_core::util::logger::init(log::LevelFilter::Info);
5904 log::set_max_level(log::LevelFilter::Info);
5905
5906 latexml_core::util::logger::bind_log();
5907 let before = latexml_core::common::error::snapshot_report_counts();
5908
5909 let captured: Vec<latexml_core::util::logger::CapturedDiagnostics> = std::thread::scope(|s| {
5913 (0..2)
5914 .map(|i| {
5915 s.spawn(move || {
5916 latexml_core::util::logger::capture(|| {
5917 Error!(
5918 "imageprocessing",
5919 "failed_to_convert",
5920 "Graphics: Failed to convert {} to {}",
5921 format!("w{i}.pdf"),
5922 format!("w{i}.png")
5923 );
5924 })
5925 .1
5926 })
5927 })
5928 .collect::<Vec<_>>()
5929 .into_iter()
5930 .map(|h| h.join().unwrap())
5931 .collect()
5932 });
5933
5934 for diags in captured {
5936 latexml_core::util::logger::replay_captured(diags);
5937 }
5938
5939 let after = latexml_core::common::error::snapshot_report_counts();
5940 let log = latexml_core::util::logger::flush_log();
5941
5942 assert!(
5943 log.contains("imageprocessing:failed_to_convert") && log.contains("Failed to convert"),
5944 "worker Error! must reach the main-thread log; got: {log:?}"
5945 );
5946 assert_eq!(
5947 log
5948 .matches("Error:imageprocessing:failed_to_convert")
5949 .count(),
5950 2,
5951 "{log}"
5952 );
5953 assert_eq!(
5954 after.error,
5955 before.error + 2,
5956 "both workers' Error! must increment the main REPORT error count via the fold"
5957 );
5958 }
5959
5960 #[test]
5964 fn produced_output_requires_a_nonempty_file() {
5965 let tmp = std::env::temp_dir().join(format!("latexml_produced_{}", std::process::id()));
5966 std::fs::create_dir_all(&tmp).unwrap();
5967 let missing = tmp.join("missing.png");
5968 let empty = tmp.join("empty.png");
5969 let real = tmp.join("real.png");
5970 std::fs::write(&empty, b"").unwrap();
5971 std::fs::write(&real, b"\x89PNG").unwrap();
5972 assert!(
5973 !Graphics::produced_output(&missing.to_string_lossy()),
5974 "a missing file is not usable output"
5975 );
5976 assert!(
5977 !Graphics::produced_output(&empty.to_string_lossy()),
5978 "a 0-byte file is not usable output (would render as a broken image)"
5979 );
5980 assert!(
5981 Graphics::produced_output(&real.to_string_lossy()),
5982 "a non-empty file is usable output"
5983 );
5984 std::fs::remove_dir_all(&tmp).ok();
5985 }
5986
5987 #[test]
5990 fn run_with_timeout_captures_stderr_into_diag() {
5991 take_converter_diag(); let (cmd, prog) = spawn_stderr_fail();
5993 let status = Graphics::run_with_timeout(cmd, std::time::Duration::from_secs(5));
5994 assert!(
5995 status.map(|s| !s.success()).unwrap_or(false),
5996 "command should report failure"
5997 );
5998 let diag = take_converter_diag().expect("a diagnostic must be recorded");
5999 assert!(
6000 diag.contains("boom on stderr") && diag.contains(prog),
6001 "diag should name the program + its stderr; got: {diag}"
6002 );
6003 }
6004
6005 #[test]
6008 fn run_with_timeout_records_spawn_failure() {
6009 take_converter_diag();
6010 let cmd = std::process::Command::new("definitely_not_a_real_binary_xyz_123");
6011 let status = Graphics::run_with_timeout(cmd, std::time::Duration::from_secs(5));
6012 assert!(status.is_none(), "spawn failure returns None");
6013 let diag = take_converter_diag().expect("a spawn diagnostic must be recorded");
6014 assert!(
6015 diag.contains("could not start") && diag.contains("definitely_not_a_real_binary_xyz_123"),
6016 "diag should name the missing tool; got: {diag}"
6017 );
6018 }
6019
6020 #[test]
6024 fn missing_tool_hint_names_packages() {
6025 assert!(missing_tool_hint("mutool").unwrap().contains("mupdf-tools"));
6026 assert!(
6027 missing_tool_hint("pdftocairo")
6028 .unwrap()
6029 .contains("poppler-utils")
6030 );
6031 assert!(missing_tool_hint("gs").unwrap().contains("ghostscript"));
6032 assert!(missing_tool_hint("ps2pdf").unwrap().contains("ghostscript"));
6033 assert!(
6034 missing_tool_hint("convert")
6035 .unwrap()
6036 .contains("imagemagick")
6037 );
6038 assert!(missing_tool_hint("dvisvgm").unwrap().contains("dvisvgm"));
6039 assert!(missing_tool_hint("dvipng").unwrap().contains("dvipng"));
6040 assert!(missing_tool_hint("kpsewhich").unwrap().contains("TeX Live"));
6041 assert!(missing_tool_hint("some_unknown_tool").is_none());
6042 }
6043
6044 fn svg_drawn_shape(svg: &str) -> Vec<String> {
6048 const XLINK: &str = "http://www.w3.org/1999/xlink";
6049 fn index(node: &Node, ids: &mut HashMap<String, Node>) {
6050 if let Some(id) = node.get_property("id") {
6051 ids.insert(id, node.clone());
6052 }
6053 for child in node.get_child_elements() {
6054 index(&child, ids);
6055 }
6056 }
6057 fn image(node: &Node) -> String {
6058 let href = node.get_property_ns("href", XLINK).unwrap_or_default();
6059 let media = href
6060 .strip_prefix("data:")
6061 .and_then(|rest| rest.split(';').next())
6062 .unwrap_or("external");
6063 format!(
6064 "image {}x{} {media}",
6065 node.get_property("width").unwrap_or_default(),
6066 node.get_property("height").unwrap_or_default()
6067 )
6068 }
6069 fn walk(node: &Node, ids: &HashMap<String, Node>, out: &mut Vec<String>) {
6070 for child in node.get_child_elements() {
6071 match child.get_name().as_str() {
6072 "defs" | "clipPath" | "mask" => {},
6073 "image" => out.push(image(&child)),
6074 "path" => out.push("path".to_string()),
6075 "use" => {
6076 let target = child.get_property_ns("href", XLINK).unwrap_or_default();
6077 match ids.get(target.trim_start_matches('#')) {
6078 Some(def) if def.get_name() == "image" => out.push(image(def)),
6079 Some(_) => out.push("glyph".to_string()),
6080 None => out.push(format!("dangling {target}")),
6081 }
6082 },
6083 _ => walk(&child, ids, out),
6084 }
6085 }
6086 }
6087 let doc = libxml::parser::Parser::default()
6088 .parse_string(svg)
6089 .expect("SVG parses");
6090 let root = doc.get_root_element().expect("SVG root");
6091 assert_eq!(root.get_name(), "svg");
6092 let mut ids = HashMap::default();
6093 index(&root, &mut ids);
6094 let mut out = Vec::new();
6095 walk(&root, &ids, &mut out);
6096 out
6097 }
6098
6099 fn svg_tool_or_skip(tool: &str, test: &str) -> bool {
6102 let found = std::process::Command::new(tool)
6104 .arg("--version")
6105 .output()
6106 .is_ok();
6107 if !found {
6108 assert!(
6109 std::env::var_os("LATEXML_SVG_TESTS").is_none(),
6110 "LATEXML_SVG_TESTS is set but {tool} is not on PATH ({test})"
6111 );
6112 eprintln!("SKIP {test} with {tool}: not on PATH");
6113 }
6114 found
6115 }
6116
6117 #[test]
6121 fn svg_enlarged_raster_reads_every_placement() {
6122 const PNG: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAEAQMAAACTPww9AAAABlBMVEXgQCAtZLS26lm/AAAADklEQVQI12MoYPgAhA8AC3gDMY2nLXUAAAAASUVORK5CYII=";
6124 const PIXEL: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";
6126 let img = |attrs: &str| format!(r#"<image{attrs} width="4" height="4" xlink:href="{PNG}"/>"#);
6127 let enlarged = |scale: Option<f64>| Some(EnlargedRaster { pixels: Some((4, 4)), scale });
6128 let rows: Vec<(String, Option<EnlargedRaster>)> = vec![
6129 ("<path d=\"M0 0h1\"/>".into(), None),
6130 (
6131 format!(r#"<g transform="matrix(7,0,0,7,1,1)">{}</g>"#, img("")),
6132 enlarged(Some(7.0)),
6133 ),
6134 (
6135 format!(r#"<g transform="matrix(.5,0,0,.5,1,1)">{}</g>"#, img("")),
6136 None,
6137 ),
6138 (
6139 format!(
6140 r#"<g transform="matrix(1.005,0,0,1.005,0,0)">{}</g>"#,
6141 img("")
6142 ),
6143 None,
6144 ),
6145 (
6146 format!(r#"<g transform="scale(.5,2)">{}</g>"#, img("")),
6147 enlarged(Some(2.0)),
6148 ),
6149 (
6150 format!(
6151 r#"<g transform="scale(2)"><g transform="translate(3 4) scale(.25)">{}</g></g>"#,
6152 img("")
6153 ),
6154 None,
6155 ),
6156 (
6157 format!(
6158 r#"<g transform="scale(2)"><g transform="scale(.75)">{}</g></g>"#,
6159 img("")
6160 ),
6161 enlarged(Some(1.5)),
6162 ),
6163 (
6164 format!(
6165 r##"<defs>{}</defs><use xlink:href="#a" transform="matrix(.5, 0, 0, .5, 50, 1)"/>"##,
6166 img(r#" id="a""#)
6167 ),
6168 None,
6169 ),
6170 (
6171 format!(
6172 r##"<defs>{}</defs><use xlink:href="#a" transform="scale(.5)"/><use xlink:href="#a" transform="scale(7)"/>"##,
6173 img(r#" id="a""#)
6174 ),
6175 enlarged(Some(7.0)),
6176 ),
6177 (
6178 format!(
6179 r##"<defs><mask id="m"><g transform="scale(.5)">{}</g></mask></defs><g mask="url(#m)"><g transform="scale(.5)">{}</g></g>"##,
6180 img(""),
6181 img("")
6182 ),
6183 None,
6184 ),
6185 (
6186 format!(
6187 r##"<defs><mask id="m"><g transform="scale(7)">{}</g></mask></defs><g mask="url(#m)"><g transform="scale(.5)">{}</g></g>"##,
6188 img(""),
6189 img("")
6190 ),
6191 enlarged(Some(7.0)),
6192 ),
6193 (
6194 format!(
6195 r##"<defs><mask id="m" maskContentUnits="objectBoundingBox">{}</mask></defs><g mask="url(#m)"/>"##,
6196 img("")
6197 ),
6198 enlarged(None),
6199 ),
6200 (
6201 format!(
6202 r##"<defs><pattern id="p">{}</pattern></defs><path fill="url(#p)" d="M0 0h1"/>"##,
6203 img("")
6204 ),
6205 enlarged(None),
6206 ),
6207 (
6208 format!(
6209 r##"<defs><symbol id="s" viewBox="0 0 1 1">{}</symbol></defs><use xlink:href="#s"/>"##,
6210 img("")
6211 ),
6212 enlarged(None),
6213 ),
6214 (
6215 format!(r#"<g transform="skewX(10)">{}</g>"#, img("")),
6216 enlarged(None),
6217 ),
6218 (
6219 r#"<image width="4" height="4" xlink:href="data:image/png;base64,AAAA"/>"#.into(),
6220 Some(EnlargedRaster { pixels: None, scale: None }),
6221 ),
6222 (
6224 format!(r#"<image width="500" height="500" xlink:href="{PIXEL}"/>"#),
6225 None,
6226 ),
6227 (
6228 format!(
6229 r#"<g transform="skewX(10)"><image width="9" height="9" xlink:href="{PIXEL}"/></g>"#
6230 ),
6231 None,
6232 ),
6233 ];
6234 for (body, expected) in rows {
6235 let svg = format!(
6236 r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 90 30">{body}</svg>"#
6237 );
6238 assert_eq!(svg_enlarged_raster(&svg), expected, "{body}");
6239 }
6240 }
6241
6242 #[test]
6248 fn small_raster_pdf_keeps_vector_labels_unless_enlarged() {
6249 let fixture = |name: &str| format!("{}/tests/fixtures/{name}.pdf", env!("CARGO_MANIFEST_DIR"));
6250 let expected = [
6251 "image 64x64 image/png",
6252 "glyph",
6253 "glyph",
6254 "glyph",
6255 "glyph",
6256 "glyph",
6257 ];
6258 let tmp = TempDir::new("small_raster_pdf");
6259 type Converter = fn(&str, &str, Option<u32>) -> bool;
6260 let converters: [(&str, Converter); 2] = [
6261 ("mutool", Graphics::convert_image_svg_mutool),
6262 ("pdftocairo", Graphics::convert_image_svg_pdftocairo),
6263 ];
6264 let mut any = false;
6265 for (tool, convert) in converters {
6266 if !svg_tool_or_skip(tool, "small_raster_pdf") {
6267 continue;
6268 }
6269 any = true;
6270 let native = tmp.join(&format!("{tool}_native.svg"));
6271 let native = native.to_str().unwrap();
6272 assert!(
6273 convert(&fixture("native_raster_vector"), native, None),
6274 "{tool} converts"
6275 );
6276 let svg = std::fs::read_to_string(native).unwrap();
6277 assert_eq!(svg_drawn_shape(&svg), expected, "{tool}");
6278 assert_eq!(svg_enlarged_raster(&svg), None, "{tool}");
6279 let tile = tmp.join(&format!("{tool}_tile.svg"));
6280 let tile = tile.to_str().unwrap();
6281 assert!(
6282 convert(&fixture("mixed_raster_vector"), tile, None),
6283 "{tool} converts"
6284 );
6285 let decision = svg_enlarged_raster(&std::fs::read_to_string(tile).unwrap());
6286 let scale = decision.as_ref().and_then(|d| d.scale).unwrap_or_default();
6288 assert!(
6289 decision.as_ref().is_some_and(|d| d.pixels == Some((4, 4))) && (6.9..7.1).contains(&scale),
6290 "{tool}: {decision:?}"
6291 );
6292 }
6293 if !any {
6294 return;
6295 }
6296 let pipeline = |name: &str| {
6297 let dir = tmp.join(name);
6298 std::fs::create_dir_all(&dir).unwrap();
6299 let src = dir.join(format!("{name}.pdf"));
6300 std::fs::copy(fixture(name), &src).unwrap();
6301 let xml = format!(
6302 r#"<document xmlns="http://dlmf.nist.gov/LaTeXML"><graphics graphic="{name}.pdf" candidates="{}"/></document>"#,
6303 src.display()
6304 );
6305 let doc_opts = crate::document::PostDocumentOptions {
6306 destination: Some(dir.join("out.html").display().to_string()),
6307 source_directory: Some(dir.display().to_string()),
6308 ..Default::default()
6309 };
6310 let doc = PostDocument::new_from_string(&xml, doc_opts).expect("parse");
6311 let mut graphics =
6312 Graphics::new(None, true).with_cache_policy(crate::graphics_cache::CachePolicy::Bypass);
6313 let nodes = graphics.to_process(&doc);
6314 assert_eq!(nodes.len(), 1);
6315 let out = graphics.process(doc, nodes).expect("graphics process")[0].to_xml_string();
6316 (out, dir)
6317 };
6318 let (out, dir) = pipeline("native_raster_vector");
6319 assert!(
6320 out.contains(r#" imagesrc="native_raster_vector.svg" "#),
6321 "{out}"
6322 );
6323 let svg = std::fs::read_to_string(dir.join("native_raster_vector.svg")).unwrap();
6324 assert_eq!(svg_drawn_shape(&svg), expected);
6325 let raster = std::process::Command::new(gs_program())
6328 .arg("--version")
6329 .output()
6330 .is_ok_and(|o| o.status.success());
6331 let _ = latexml_core::util::logger::init(log::LevelFilter::Info);
6332 log::set_max_level(log::LevelFilter::Info);
6333 latexml_core::util::logger::bind_log();
6334 let before = latexml_core::common::error::snapshot_report_counts();
6335 let (out, dir) = pipeline("mixed_raster_vector");
6336 let after = latexml_core::common::error::snapshot_report_counts();
6337 assert!(
6338 !out.contains(r#" imagesrc="mixed_raster_vector.svg" "#),
6339 "{out}"
6340 );
6341 assert!(!dir.join("mixed_raster_vector.svg").exists());
6342 if raster {
6343 assert!(
6344 out.contains(r#" imagesrc="mixed_raster_vector.png" "#),
6345 "{out}"
6346 );
6347 assert_eq!(after.error, before.error, "{out}");
6348 } else {
6349 eprintln!(
6350 "SKIP small_raster_pdf's PNG output check: {} not on PATH (the SVG drop is still checked)",
6351 gs_program()
6352 );
6353 }
6354 }
6355
6356 #[test]
6361 fn a_sibling_clobbering_the_destination_never_switches_to_png() {
6362 use std::sync::atomic::{AtomicBool, Ordering};
6363 if !["mutool", "pdftocairo"]
6364 .iter()
6365 .any(|tool| svg_tool_or_skip(tool, "a_sibling_clobbering_the_destination"))
6366 {
6367 return;
6368 }
6369 let tmp = TempDir::new("sibling_clobber");
6370 let dir = tmp.join("out");
6371 std::fs::create_dir_all(&dir).unwrap();
6372 let src = dir.join("fig.pdf");
6373 std::fs::copy(
6374 format!(
6375 "{}/tests/fixtures/two_page_sizes.pdf",
6376 env!("CARGO_MANIFEST_DIR")
6377 ),
6378 &src,
6379 )
6380 .unwrap();
6381 let shared = dir.join("fig.svg");
6382 let stop = AtomicBool::new(false);
6383 let mut renders: Vec<String> = Vec::new();
6384 std::thread::scope(|s| {
6385 s.spawn(|| {
6386 while !stop.load(Ordering::Relaxed) {
6387 let _ = std::fs::write(&shared, b"<svg xmlns=\"http://www.w3.org/2000/svg\"");
6388 let _ = std::fs::remove_file(&shared);
6389 }
6390 });
6391 for round in 0..20 {
6392 let xml = format!(
6393 r#"<document xmlns="http://dlmf.nist.gov/LaTeXML"><graphics graphic="fig.pdf" candidates="{}"/></document>"#,
6394 src.display()
6395 );
6396 let doc_opts = crate::document::PostDocumentOptions {
6397 destination: Some(dir.join("out.html").display().to_string()),
6398 source_directory: Some(dir.display().to_string()),
6399 ..Default::default()
6400 };
6401 let doc = PostDocument::new_from_string(&xml, doc_opts).expect("parse");
6402 let mut graphics =
6403 Graphics::new(None, true).with_cache_policy(crate::graphics_cache::CachePolicy::Bypass);
6404 let nodes = graphics.to_process(&doc);
6405 let out = graphics.process(doc, nodes).expect("graphics process")[0].to_xml_string();
6406 let src = out
6409 .split(r#" imagesrc=""#)
6410 .nth(1)
6411 .and_then(|rest| rest.split('"').next())
6412 .unwrap_or_default()
6413 .to_string();
6414 if !src.ends_with(".svg") {
6415 stop.store(true, Ordering::Relaxed);
6416 panic!("round {round}: the figure left its vector render:\n{out}");
6417 }
6418 renders.push(src);
6419 }
6420 stop.store(true, Ordering::Relaxed);
6421 });
6422 let mut left: Vec<String> = std::fs::read_dir(&dir)
6423 .unwrap()
6424 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
6425 .filter(|name| {
6427 name != "fig.pdf"
6428 && name != "fig.svg"
6429 && name != "LaTeXML-oxide.cache"
6430 && !renders.contains(name)
6431 })
6432 .collect();
6433 left.sort();
6434 assert!(
6435 left.is_empty(),
6436 "no PNG and no staged file is left: {left:?}"
6437 );
6438 }
6439
6440 #[test]
6446 fn vector_svg_of_page_two_is_page_two() {
6447 use latexml_core::util::image::{svg_attr_value, svg_root_tag};
6448 let fixture = format!(
6449 "{}/tests/fixtures/two_page_sizes.pdf",
6450 env!("CARGO_MANIFEST_DIR")
6451 );
6452 let view_box = |path: &Path| {
6453 let text = std::fs::read_to_string(path).unwrap();
6454 svg_root_tag(&text)
6455 .and_then(|tag| svg_attr_value(tag, "viewBox"))
6456 .map(|v| v.split_whitespace().collect::<Vec<_>>().join(" "))
6457 };
6458 let listing = |dir: &Path| {
6459 let mut names: Vec<String> = std::fs::read_dir(dir)
6460 .unwrap()
6461 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
6462 .collect();
6463 names.sort();
6464 names
6465 };
6466 let tmp = TempDir::new("svg_page_two");
6467 type Converter = fn(&str, &str, Option<u32>) -> bool;
6468 let converters: [(&str, Converter); 2] = [
6469 ("mutool", Graphics::convert_image_svg_mutool),
6470 ("pdftocairo", Graphics::convert_image_svg_pdftocairo),
6471 ];
6472 let mut mutool = false;
6473 for (tool, convert) in converters {
6474 if !svg_tool_or_skip(tool, "svg_page_two") {
6475 continue;
6476 }
6477 mutool |= tool == "mutool";
6478 let dir = tmp.join(tool);
6479 std::fs::create_dir_all(&dir).unwrap();
6480 for (page, expected) in [(2, "0 0 100 300"), (1, "0 0 300 100")] {
6481 let dest = dir.join(format!("p{page}.svg"));
6482 assert!(
6483 convert(&fixture, dest.to_str().unwrap(), Some(page)),
6484 "{tool} converts page {page}"
6485 );
6486 assert_eq!(
6487 view_box(&dest).as_deref(),
6488 Some(expected),
6489 "{tool} page {page}"
6490 );
6491 }
6492 assert_eq!(listing(&dir), ["p1.svg", "p2.svg"], "{tool}");
6493 }
6494 if !mutool {
6496 return;
6497 }
6498 let src = tmp.join("two_page_sizes.pdf");
6499 std::fs::copy(&fixture, &src).unwrap();
6500 let dest = tmp.join("out").join("out.html");
6501 std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
6502 let xml = format!(
6503 r#"<document xmlns="http://dlmf.nist.gov/LaTeXML">
6504 <graphics graphic="two_page_sizes.pdf" candidates="{0}" options="page=1" xml:id="g1"/>
6505 <graphics graphic="two_page_sizes.pdf" candidates="{0}" options="page=2" xml:id="g2"/>
6506</document>"#,
6507 src.display()
6508 );
6509 let doc_opts = crate::document::PostDocumentOptions {
6510 destination: Some(dest.display().to_string()),
6511 source_directory: Some(tmp.path().display().to_string()),
6512 ..Default::default()
6513 };
6514 let doc = PostDocument::new_from_string(&xml, doc_opts).expect("parse");
6515 let mut graphics =
6516 Graphics::new(None, true).with_cache_policy(crate::graphics_cache::CachePolicy::Bypass);
6517 let nodes = graphics.to_process(&doc);
6518 assert_eq!(nodes.len(), 2);
6519 let out = graphics.process(doc, nodes).expect("graphics process")[0].to_xml_string();
6521 let element = |id: &str| {
6522 let at = out.find(&format!(r#"xml:id="{id}""#)).unwrap();
6523 let tag = &out[out[..at].rfind('<').unwrap()..at + out[at..].find('>').unwrap()];
6524 let attr = |name: &str| {
6525 let at = tag.find(&format!(" {name}=\""))? + name.len() + 3;
6526 Some(tag[at..at + tag[at..].find('"')?].to_string())
6527 };
6528 [attr("imagesrc"), attr("imagewidth"), attr("imageheight")]
6529 };
6530 let some = |v: [&str; 3]| v.map(|s| Some(s.to_string()));
6531 assert_eq!(element("g1"), some(["x1.svg", "300", "100"]), "{out}");
6532 assert_eq!(element("g2"), some(["x2.svg", "100", "300"]), "{out}");
6533 let out_dir = dest.parent().unwrap();
6534 assert_eq!(
6535 listing(out_dir),
6536 ["LaTeXML-oxide.cache", "x1.svg", "x2.svg"],
6537 "{out}"
6538 );
6539 assert_eq!(
6540 view_box(&out_dir.join("x2.svg")).as_deref(),
6541 Some("0 0 100 300")
6542 );
6543 }
6544}