1use std::{
8 cell::{Cell, RefCell},
9 collections::HashSet,
10 fs,
11 path::{Path, PathBuf},
12 sync::LazyLock,
13};
14
15use latexml_core::{
16 document::resource::{BINDING_RESOURCE_CLASS, is_remote},
17 util::pathname,
18};
19use libxml::tree::{Namespace, Node, NodeType};
20use regex::Regex;
21use rustc_hash::FxHashMap as HashMap;
22
23use crate::{
24 document::{PostDocument, PostDocumentOptions},
25 processor::{PostError, ProcessResult, Processor},
26};
27
28fn set_xslt_max_depth() {
34 static SET_MAX_DEPTH: std::sync::Once = std::sync::Once::new();
35 SET_MAX_DEPTH.call_once(|| {
36 #[cfg(any(unix, windows))]
42 unsafe {
43 xsltMaxDepth = 1000;
44 }
45 });
48}
49
50#[cfg(any(unix, windows))]
74#[allow(non_upper_case_globals)]
75unsafe extern "C" {
76 static mut xsltMaxDepth: std::os::raw::c_int;
77}
78
79#[cfg(all(test, any(unix, windows)))]
80mod max_depth_tests {
81 use crate::{
82 document::{PostDocument, PostDocumentOptions},
83 processor::Processor,
84 };
85
86 #[test]
89 fn extern_static_sets_perl_parity_cap() {
90 super::set_xslt_max_depth();
91 let val = unsafe { super::xsltMaxDepth };
94 assert_eq!(val, 1000);
95 }
96
97 fn apply_recursion(n: u32) -> bool {
103 const RECURSION_XSL: &str = r#"<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
104 <xsl:param name="n" select="0"/>
105 <xsl:template match="/">
106 <out><xsl:call-template name="down"><xsl:with-param name="k" select="$n"/></xsl:call-template></out>
107 </xsl:template>
108 <xsl:template name="down">
109 <xsl:param name="k"/>
110 <xsl:if test="$k > 0">
111 <xsl:call-template name="down"><xsl:with-param name="k" select="$k - 1"/></xsl:call-template>
112 </xsl:if>
113 </xsl:template>
114</xsl:stylesheet>
115"#;
116 let dir = tempfile::tempdir().expect("tempdir");
117 let xsl = dir.path().join("recursion.xsl");
118 std::fs::write(&xsl, RECURSION_XSL).expect("write recursion.xsl");
119 let mut params = rustc_hash::FxHashMap::default();
120 params.insert("n".to_string(), n.to_string());
121 let mut xslt =
122 super::XSLT::new(xsl.to_str().unwrap(), params, true, None, vec![]).expect("XSLT processor");
123 let doc =
124 PostDocument::new_from_string("<a/>", PostDocumentOptions::default()).expect("parse <a/>");
125 xslt.process(doc, vec![]).is_ok()
126 }
127
128 #[test]
132 fn transform_aborts_past_perls_recursion_depth() {
133 assert!(
134 apply_recursion(400),
135 "a 400-level recursion (800 of 1000 depth units) must transform"
136 );
137 let (completed, libxslt_says) = with_fd2_captured(|| apply_recursion(700));
138 assert!(
139 !completed,
140 "a 700-level recursion (1400 depth units) must abort at Perl's cap of 1000, \
141 not run on to libxslt's default of 3000"
142 );
143 if let Some(said) = libxslt_says {
144 assert!(
145 said.contains("potential infinite template recursion"),
146 "{said}"
147 );
148 }
149 }
150
151 #[cfg(unix)]
156 fn with_fd2_captured<T>(f: impl FnOnce() -> T) -> (T, Option<String>) {
157 use std::{
158 io::{Read, Seek},
159 os::fd::OwnedFd,
160 };
161 struct Restore(OwnedFd);
163 impl Drop for Restore {
164 fn drop(&mut self) { let _ = rustix::stdio::dup2_stderr(&self.0); }
165 }
166 let mut sink = tempfile::tempfile().expect("tempfile");
167 let restore = Restore(rustix::io::dup(std::io::stderr()).expect("dup(2)"));
168 rustix::stdio::dup2_stderr(&sink).expect("dup2 onto fd 2");
169 let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
170 drop(restore);
171 let mut text = String::new();
172 sink.rewind().expect("rewind");
173 sink.read_to_string(&mut text).expect("read captured fd 2");
174 match out {
175 Ok(out) => (out, Some(text)),
176 Err(panic) => {
177 eprint!("{text}");
179 std::panic::resume_unwind(panic)
180 },
181 }
182 }
183 #[cfg(not(unix))]
184 fn with_fd2_captured<T>(f: impl FnOnce() -> T) -> (T, Option<String>) { (f(), None) }
185}
186
187#[cfg(test)]
188mod local_stylesheet_tests {
189 use crate::{
190 document::{PostDocument, PostDocumentOptions},
191 processor::Processor,
192 };
193
194 fn marker_xsl(marker: &str) -> String {
195 format!(
196 r#"<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
197 <xsl:template match="/"><out>{marker}</out></xsl:template>
198</xsl:stylesheet>
199"#
200 )
201 }
202
203 fn apply(xsl: &std::path::Path) -> String {
204 let mut xslt = super::XSLT::new(
205 xsl.to_str().unwrap(),
206 Default::default(),
207 true,
208 None,
209 vec![],
210 )
211 .expect("XSLT");
212 let doc = PostDocument::new_from_string("<a/>", PostDocumentOptions::default()).expect("<a/>");
213 let out = xslt.process(doc, vec![]).expect("transform");
214 out[0].to_xml_string()
215 }
216
217 #[test]
220 fn a_stylesheet_on_disk_wins_over_the_embedded_copy() {
221 let dir = tempfile::tempdir().expect("tempdir");
222 let html5 = dir.path().join("LaTeXML-html5.xsl");
223 std::fs::write(&html5, marker_xsl("LOCAL-HTML5")).unwrap();
224 assert!(apply(&html5).contains("<out>LOCAL-HTML5</out>"));
225
226 let common = dir.path().join("LaTeXML-common.xsl");
227 std::fs::write(&common, marker_xsl("LOCAL-COMMON")).unwrap();
228 let mine = dir.path().join("mine.xsl");
229 std::fs::write(
230 &mine,
231 r#"<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
232 <xsl:import href="LaTeXML-common.xsl"/>
233</xsl:stylesheet>
234"#,
235 )
236 .unwrap();
237 assert!(apply(&mine).contains("<out>LOCAL-COMMON</out>"));
238 }
239
240 #[test]
244 fn only_a_named_file_is_read_from_disk() {
245 let dir = tempfile::tempdir().expect("tempdir");
246 let spaced = dir.path().join("a b");
247 std::fs::create_dir(&spaced).unwrap();
248 let common = spaced.join("LaTeXML-common.xsl");
249 std::fs::write(&common, marker_xsl("SPACED-COMMON")).unwrap();
250 let mine = spaced.join("mine.xsl");
251 std::fs::write(
252 &mine,
253 r#"<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
254 <xsl:import href="LaTeXML-common.xsl"/>
255</xsl:stylesheet>
256"#,
257 )
258 .unwrap();
259 assert!(apply(&mine).contains("<out>SPACED-COMMON</out>"));
260
261 let file_url_path = |path: &std::path::Path| {
263 let path = path.to_str().unwrap().replace('\\', "/");
264 if path.starts_with('/') {
265 path
266 } else {
267 format!("/{path}")
268 }
269 };
270 let abs = common.to_str().unwrap();
271 let escaped = file_url_path(&common).replace(' ', "%20");
272 for url in [
273 abs.to_string(),
274 format!("file://{escaped}"),
275 format!("file://localhost{escaped}"),
276 format!("file:{escaped}"),
277 ] {
278 assert!(super::embedded_xslt::resolve(&url).is_none(), "{url}");
279 }
280 for name in ["100%", "%41"] {
282 let pct = dir.path().join(name);
283 std::fs::create_dir(&pct).unwrap();
284 let html5 = pct.join("LaTeXML-html5.xsl");
285 std::fs::write(&html5, marker_xsl("PCT-HTML5")).unwrap();
286 assert!(apply(&html5).contains("<out>PCT-HTML5</out>"), "{name}");
287 std::fs::write(pct.join("LaTeXML-common.xsl"), marker_xsl("PCT-COMMON")).unwrap();
288 std::fs::copy(&mine, pct.join("mine.xsl")).unwrap();
289 assert!(
290 apply(&pct.join("mine.xsl")).contains("<out>PCT-COMMON</out>"),
291 "{name}"
292 );
293 let url = format!("file://{}", file_url_path(&html5).replace('%', "%25"));
295 assert_eq!(super::embedded_xslt::disk_path(&url), Some(html5), "{url}");
297 }
298 let unc = "file://server/share/a%20b/LaTeXML-common.xsl";
301 assert_eq!(
302 super::embedded_xslt::url_path(unc),
303 cfg!(windows).then(|| std::path::PathBuf::from("//server/share/a b/LaTeXML-common.xsl")),
304 "{unc}"
305 );
306 for url in [
308 "resources/XSLT/LaTeXML-all-xhtml.xsl",
309 "embed:///LaTeXML-html5.xsl",
310 "urn:x-LaTeXML:XSLT:LaTeXML-html5.xsl",
311 ] {
312 assert!(super::embedded_xslt::resolve(url).is_some(), "{url}");
313 }
314 }
315}
316
317struct ResourceInfo {
319 extension: &'static str,
320 subdir: &'static str,
321}
322
323const RESOURCE_CSS: ResourceInfo = ResourceInfo {
324 extension: "css",
325 subdir: "resources/CSS",
326};
327const RESOURCE_JS: ResourceInfo = ResourceInfo {
328 extension: "js",
329 subdir: "resources/javascript",
330};
331
332pub struct XSLT {
336 name: String,
337 stylesheet_path: Option<String>,
339 parameters: HashMap<String, String>,
341 no_resources: bool,
343 resource_directory: Option<String>,
345 searchpaths: Vec<String>,
347 standin_attribute: bool,
349 copied: RefCell<HashSet<ResourceKey>>,
354}
355
356type ResourceKey = (String, Option<String>, String, bool);
358
359std::thread_local! {
360 static RESOURCE_COPIES: Cell<usize> = const { Cell::new(0) };
361}
362
363pub fn resource_copy_count() -> usize { RESOURCE_COPIES.get() }
365fn note_resource_copy() { RESOURCE_COPIES.set(RESOURCE_COPIES.get() + 1); }
366
367impl XSLT {
368 pub fn new(
369 stylesheet: &str,
370 parameters: HashMap<String, String>,
371 no_resources: bool,
372 resource_directory: Option<String>,
373 searchpaths: Vec<String>,
374 ) -> Result<Self, PostError> {
375 if stylesheet.is_empty() {
376 Error!("expected", "stylesheet", "No stylesheet specified!");
379 return Err(PostError::Processing(
380 "No stylesheet specified!".to_string(),
381 ));
382 }
383
384 let stylesheet_path = match find_stylesheet(stylesheet, &searchpaths) {
386 Ok(p) => p,
387 Err(e) => {
388 Error!(
391 "missing-file",
392 stylesheet,
393 "No stylesheet '{}' found!",
394 stylesheet
395 );
396 return Err(e);
397 },
398 };
399
400 let sheet = stylesheet
403 .rsplit(['/', '\\', ':'])
404 .next()
405 .unwrap_or(stylesheet);
406 let standin_attribute = matches!(sheet, "LaTeXML-html5.xsl" | "LaTeXML-xhtml5.xsl");
407 Ok(XSLT {
408 name: format!(
409 "XSLT[using {}]",
410 stylesheet
411 .strip_prefix(embedded_xslt::URL_PREFIX)
412 .unwrap_or(stylesheet)
413 ),
414 stylesheet_path: Some(stylesheet_path),
415 parameters,
416 no_resources,
417 resource_directory,
418 searchpaths,
419 standin_attribute,
420 copied: RefCell::default(),
421 })
422 }
423
424 fn copy_resource(&self, doc: &PostDocument, src: &str, resource_type: Option<&str>) -> String {
428 self.copy_resource_following(doc, src, resource_type, None)
429 }
430
431 fn copy_resource_following(
434 &self,
435 doc: &PostDocument,
436 src: &str,
437 resource_type: Option<&str>,
438 imports: Option<&mut HashSet<PathBuf>>,
439 ) -> String {
440 if is_remote(src) {
442 return src.to_string();
443 }
444
445 let info = match resource_type {
446 Some("text/css") => Some(&RESOURCE_CSS),
447 Some("text/javascript") => Some(&RESOURCE_JS),
448 _ => None,
449 };
450
451 let search_paths: Vec<&str> = doc
453 .get_search_paths()
454 .iter()
455 .chain(self.searchpaths.iter())
456 .map(String::as_str)
457 .collect();
458
459 let basename = Path::new(src)
460 .file_name()
461 .and_then(|f| f.to_str())
462 .unwrap_or(src);
463
464 let rel_dest: String = if self.resource_directory.is_some() {
472 basename.to_string()
473 } else {
474 let relpath = pathname::relative(src, doc.get_source_directory());
475 if relpath.starts_with("../") || Path::new(&relpath).is_absolute() {
476 basename.to_string()
477 } else {
478 relpath
479 }
480 };
481
482 let (root, dest) = if let Some(ref rd) = self.resource_directory {
486 if let Some(site_dir) = doc.get_site_directory() {
487 (site_dir, format!("{}/{}/{}", site_dir, rd, rel_dest))
488 } else {
489 (rd.as_str(), format!("{}/{}", rd, rel_dest))
490 }
491 } else if let Some(base) = doc
492 .get_site_directory()
493 .or_else(|| doc.get_destination_directory())
494 {
495 (base, format!("{}/{}", base, rel_dest))
496 } else {
497 (".", rel_dest)
498 };
499 let ensure_parent = |dest: &str| {
500 if let Some(parent) = Path::new(dest).parent() {
501 let _ = fs::create_dir_all(parent);
502 }
503 };
504 let follows = imports.is_some() && info.is_some_and(|i| i.extension == "css");
505 let mut key = (
506 src.to_string(),
507 resource_type.map(str::to_string),
508 dest.clone(),
509 true,
510 );
511 let done = self.copied.borrow().contains(&key) || {
513 key.3 = follows;
514 self.copied.borrow().contains(&key)
515 };
516 if done {
517 return relative_to_destination(doc, dest);
518 }
519 if pathname::is_contained_resolved(&dest, root).is_none() {
521 Warn!(
522 "unexpected",
523 src,
524 "{} would be copied to {} outside {}; not copied",
525 src,
526 dest,
527 root
528 );
529 return src.to_string();
530 }
531 let mut placed = true;
533
534 match find_resource_file(src, info, &search_paths) {
535 Some((path, found_under)) => {
536 if crate::writer::same_file(&path, &dest) {
537 if let Some(bytes) = embedded_resources::bundled(src, basename)
540 && crate::writer::needs_write(Path::new(&dest))
541 {
542 ensure_parent(&dest);
543 note_resource_copy();
544 if let Err(e) = crate::writer::write_atomic(Path::new(&dest), bytes) {
545 placed = false;
546 Warn!(
547 "I/O",
548 dest,
549 "Couldn't rewrite embedded {} to {}: {}",
550 basename,
551 dest,
552 e
553 );
554 }
555 }
556 } else {
557 ensure_parent(&dest);
558 note_resource_copy();
559 if let Err(e) = crate::writer::copy_atomic(Path::new(&path), Path::new(&dest)) {
560 placed = false;
561 Warn!("I/O", dest, "Couldn't copy {} to {}: {}", path, dest, e);
562 }
563 }
564 if let Some(seen) = imports
565 && follows
566 {
567 placed &= copy_css_imports(
568 Path::new(&path),
569 Path::new(&dest),
570 &Roots {
571 dest: root,
572 source: &found_under,
573 },
574 seen,
575 );
576 }
577 },
578 None => {
579 if let Some(bytes) = embedded_resources::bundled(src, basename) {
582 if crate::writer::needs_write(Path::new(&dest)) {
583 ensure_parent(&dest);
584 note_resource_copy();
585 if let Err(e) = crate::writer::write_atomic(Path::new(&dest), bytes) {
586 placed = false;
587 Warn!(
588 "I/O",
589 dest,
590 "Couldn't write embedded resource {} to {}: {}",
591 basename,
592 dest,
593 e
594 );
595 }
596 }
597 } else if src == embedded_resources::AR5IV_CSS_NAME {
598 Warn!(
600 "missing_file",
601 src,
602 "{} is bundled only in release builds; pass a path to a local copy",
603 src
604 );
605 return src.to_string();
606 } else {
607 Warn!(
608 "missing_file",
609 src,
610 "Couldn't find resource file {} in paths {:?}",
611 src,
612 search_paths
613 );
614 return src.to_string();
615 }
616 },
617 }
618 if placed {
619 self.copied.borrow_mut().insert(key);
620 }
621 relative_to_destination(doc, dest)
622 }
623
624 fn copy_param_resources(
628 &self,
629 doc: &PostDocument,
630 value: &str,
631 resource_type: Option<&str>,
632 ) -> String {
633 if doc
634 .get_site_directory()
635 .or_else(|| doc.get_destination_directory())
636 .is_none()
637 {
638 return value.to_string();
639 }
640 let mut seen: HashSet<PathBuf> = HashSet::new();
641 let entries: Vec<String> = value
642 .trim_matches('"')
643 .split('|')
644 .map(str::trim)
645 .filter(|entry| !entry.is_empty())
646 .map(|entry| self.copy_resource_following(doc, entry, resource_type, Some(&mut seen)))
647 .collect();
648 format!("\"{}\"", entries.join("|"))
649 }
650}
651
652fn relative_to_destination(doc: &PostDocument, dest: String) -> String {
654 if let Some(dest_dir) = doc.get_destination_directory() {
655 pathname::relative(&pathname::absolute(&dest), &pathname::absolute(dest_dir))
656 } else {
657 dest
658 }
659}
660
661struct Roots<'a> {
664 dest: &'a str,
665 source: &'a str,
666}
667
668fn parse_css_imports(css: &str) -> Vec<String> {
676 static COMMENT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?s)/\*.*?\*/").unwrap());
677 static IMPORT: LazyLock<Regex> =
678 LazyLock::new(|| Regex::new(r#"(?i)@import\s+(?:url\(\s*)?["']?([^"')\s;]+)"#).unwrap());
679 let stripped = COMMENT.replace_all(css, "");
680 IMPORT
681 .captures_iter(&stripped)
682 .filter_map(|c| c.get(1).map(|m| m.as_str().to_string()))
683 .collect()
684}
685
686fn copy_css_imports(src: &Path, dest: &Path, roots: &Roots, seen: &mut HashSet<PathBuf>) -> bool {
703 let content = match fs::read_to_string(src) {
704 Ok(c) => c,
705 Err(_) => return true,
706 };
707 let (Some(src_dir), Some(dest_dir)) = (src.parent(), dest.parent()) else {
708 return true;
709 };
710 let mut placed = true;
711 for target in parse_css_imports(&content) {
712 let t = target.trim();
713 if t.is_empty()
715 || t.starts_with('/')
716 || t.starts_with("//")
717 || t.starts_with("data:")
718 || t.contains("://")
719 {
720 continue;
721 }
722 let lexical = |dir: &Path| PathBuf::from(pathname::absolute(&dir.join(t).to_string_lossy()));
723 let import_src = lexical(src_dir);
724 let import_dest = lexical(dest_dir);
725 if pathname::is_contained_resolved(&import_dest.to_string_lossy(), roots.dest).is_none() {
726 Warn!(
727 "unexpected",
728 t,
729 "@import {} in {} would be copied outside {}; not copied",
730 t,
731 src.display(),
732 roots.dest
733 );
734 continue;
735 }
736 if !resolves_inside(&import_src, roots.source) {
737 Warn!(
738 "unexpected",
739 t,
740 "@import {} in {} resolves outside {}; not copied",
741 t,
742 src.display(),
743 roots.source
744 );
745 continue;
746 }
747 if !seen.insert(import_src.clone()) {
749 continue;
750 }
751 if !import_src.is_file() {
752 Warn!(
753 "missing_file",
754 t,
755 "Couldn't find @import target {} referenced by {}",
756 t,
757 src.display()
758 );
759 placed = false;
760 continue;
761 }
762 if !crate::writer::same_file(&import_src, &import_dest) {
763 if let Some(parent) = import_dest.parent() {
764 let _ = fs::create_dir_all(parent);
765 }
766 if let Err(e) = crate::writer::copy_atomic(&import_src, &import_dest) {
767 Warn!(
768 "I/O",
769 t,
770 "Couldn't copy @import {} to {}: {}",
771 import_src.display(),
772 import_dest.display(),
773 e
774 );
775 placed = false;
776 continue;
777 }
778 }
779 if import_src
781 .extension()
782 .and_then(|e| e.to_str())
783 .is_some_and(|e| e.eq_ignore_ascii_case("css"))
784 {
785 placed &= copy_css_imports(&import_src, &import_dest, roots, seen);
786 }
787 }
788 placed
789}
790
791const DATA_NS: &str = "http://dlmf.nist.gov/LaTeXML/data";
794
795fn standin_to_attribute(doc: &mut PostDocument) {
800 let owners = doc.findnodes("//*[contains(@class,'ltx_standin')]");
801 if owners.is_empty() {
802 return;
803 }
804 let Some(mut root) = doc.get_document_element() else {
805 return;
806 };
807 let Some(ns) = root
809 .get_namespace_declarations()
810 .into_iter()
811 .find(|ns| ns.get_prefix() == "data" && ns.get_href() == DATA_NS)
812 .or_else(|| Namespace::new("data", DATA_NS, &mut root).ok())
813 else {
814 return;
815 };
816 for mut owner in owners {
817 if !owner
818 .get_attribute("class")
819 .is_some_and(|class| class.split_whitespace().any(|c| c == "ltx_standin"))
820 {
821 continue;
822 }
823 let texts: Vec<Node> = owner
824 .get_child_nodes()
825 .into_iter()
826 .filter(|child| child.get_type() == Some(NodeType::TextNode))
827 .collect();
828 let twin: String = texts.iter().map(Node::get_content).collect();
829 if twin.is_empty() || owner.set_attribute_ns("standin", &twin, &ns).is_err() {
830 continue;
831 }
832 for mut text in texts {
833 text.unlink_node();
834 doc.discard_subtree(text);
835 }
836 }
837}
838
839impl Processor for XSLT {
840 fn get_name(&self) -> &str { &self.name }
841
842 fn process(&mut self, mut doc: PostDocument, _nodes: Vec<Node>) -> ProcessResult {
843 let stylesheet_path = match &self.stylesheet_path {
844 Some(p) => p.clone(),
845 None => return Ok(vec![doc]),
846 };
847
848 Info!(
849 "xslt",
850 "stylesheet",
851 "Applying XSLT stylesheet: {}",
852 stylesheet_path
853 );
854
855 let resource_nodes = doc.findnodes("//ltx:resource[@src]");
857 if self.no_resources {
858 for mut node in resource_nodes {
862 let keep = node.get_attribute("type").as_deref() == Some("text/css")
863 && node.get_attribute("src").is_some_and(|src| is_remote(&src))
864 && node.get_attribute("class").is_some_and(|class| {
865 class
866 .split_whitespace()
867 .any(|c| c == BINDING_RESOURCE_CLASS)
868 });
869 if !keep {
870 node.unlink_node();
871 }
872 }
873 } else {
874 for node in &resource_nodes {
875 if let Some(src) = node.get_attribute("src") {
876 let resource_type = node.get_attribute("type");
877 let path = self.copy_resource(&doc, &src, resource_type.as_deref());
878 if path != src {
882 node.clone().set_attribute("src", &path).ok();
883 }
884 }
885 }
886 }
887
888 if self.standin_attribute {
889 standin_to_attribute(&mut doc);
890 }
891
892 let mut per_doc_params = self.parameters.clone();
895 for (key, resource_type) in [
896 ("CSS", Some("text/css")),
897 ("JAVASCRIPT", Some("text/javascript")),
898 ("ICON", None),
899 ] {
900 if let Some(value) = self.parameters.get(key) {
901 let copied = pathname::own_behalf(|| self.copy_param_resources(&doc, value, resource_type));
903 per_doc_params.insert(key.to_string(), copied);
904 }
905 }
906
907 static XSLT_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
924 let _xslt_guard = XSLT_LOCK
925 .lock()
926 .unwrap_or_else(|poisoned| poisoned.into_inner());
927
928 libxslt::register_exslt();
932
933 set_xslt_max_depth();
942
943 let transform_doc = doc.get_document().clone();
963
964 let params: Vec<(&str, &str)> = per_doc_params
965 .iter()
966 .map(|(k, v)| (k.as_str(), v.as_str()))
967 .collect();
968
969 let result_doc = with_cached_stylesheet(&stylesheet_path, |stylesheet| {
976 stylesheet
977 .transform(transform_doc, params)
978 .map_err(|e| PostError::Processing(format!("XSLT transformation failed: {}", e)))
979 })?;
980 drop(_xslt_guard);
988
989 if result_doc.get_root_element().is_none() {
994 return Err(PostError::Processing(
995 "XSLT produced empty output".to_string(),
996 ));
997 }
998
999 let result_doc = PostDocument::new_transformed(result_doc, PostDocumentOptions {
1000 destination: doc.destination.clone(),
1001 destination_directory: doc.destination_directory.clone(),
1002 site_directory: doc.site_directory.clone(),
1003 source: doc.source.clone(),
1004 source_directory: doc.source_directory.clone(),
1005 searchpaths: Some(doc.searchpaths.clone()),
1006 ..PostDocumentOptions::default()
1007 });
1008
1009 Ok(vec![result_doc])
1010 }
1011}
1012
1013fn cache_key(path: &str) -> String {
1044 if path.starts_with(embedded_xslt::URL_PREFIX) {
1047 return path.to_string();
1048 }
1049 fs::canonicalize(path)
1054 .map(|p| p.to_string_lossy().into_owned())
1055 .unwrap_or_else(|_| path.to_string())
1056}
1057
1058thread_local! {
1059 static STYLESHEET_CACHE: RefCell<HashMap<String, libxslt::stylesheet::Stylesheet>> =
1060 RefCell::new(HashMap::default());
1061}
1062
1063fn with_cached_stylesheet<F, R>(path: &str, f: F) -> Result<R, PostError>
1068where F: FnOnce(&mut libxslt::stylesheet::Stylesheet) -> Result<R, PostError> {
1069 let key = cache_key(path);
1070 embedded_xslt::install_callback_once();
1074 STYLESHEET_CACHE.with(|cache| {
1075 let mut map = cache.borrow_mut();
1076 if !map.contains_key(&key) {
1077 let parsed = if let Some(name) = path.strip_prefix(embedded_xslt::URL_PREFIX) {
1078 let bytes = embedded_xslt::lookup(name).ok_or_else(|| {
1083 PostError::Processing(format!("Embedded XSLT stylesheet {} not found", name))
1084 })?;
1085 libxslt::parser::parse_bytes(bytes.to_vec(), path)
1086 .map_err(|e| PostError::Processing(format!("Failed to parse embedded XSLT: {}", e)))?
1087 } else {
1088 libxslt::parser::parse_file(path)
1089 .map_err(|e| PostError::Processing(format!("Failed to parse XSLT stylesheet: {}", e)))?
1090 };
1091 map.insert(key.clone(), parsed);
1092 }
1093 let entry = map
1094 .get_mut(&key)
1095 .expect("cache entry just inserted is missing");
1096 f(entry)
1097 })
1098}
1099
1100mod embedded_xslt {
1106 pub const FILES: &[(&str, &str)] = &[
1107 (
1108 "LaTeXML-html5.xsl",
1109 include_str!("../resources/XSLT/LaTeXML-html5.xsl"),
1110 ),
1111 (
1112 "LaTeXML-all-xhtml.xsl",
1113 include_str!("../resources/XSLT/LaTeXML-all-xhtml.xsl"),
1114 ),
1115 (
1116 "LaTeXML-bib-xhtml.xsl",
1117 include_str!("../resources/XSLT/LaTeXML-bib-xhtml.xsl"),
1118 ),
1119 (
1120 "LaTeXML-block-xhtml.xsl",
1121 include_str!("../resources/XSLT/LaTeXML-block-xhtml.xsl"),
1122 ),
1123 (
1124 "LaTeXML-common.xsl",
1125 include_str!("../resources/XSLT/LaTeXML-common.xsl"),
1126 ),
1127 (
1128 "LaTeXML-epub3.xsl",
1129 include_str!("../resources/XSLT/LaTeXML-epub3.xsl"),
1130 ),
1131 (
1132 "LaTeXML-html4.xsl",
1133 include_str!("../resources/XSLT/LaTeXML-html4.xsl"),
1134 ),
1135 (
1136 "LaTeXML-inline-xhtml.xsl",
1137 include_str!("../resources/XSLT/LaTeXML-inline-xhtml.xsl"),
1138 ),
1139 (
1140 "LaTeXML-jats.xsl",
1141 include_str!("../resources/XSLT/LaTeXML-jats.xsl"),
1142 ),
1143 (
1144 "LaTeXML-math-xhtml.xsl",
1145 include_str!("../resources/XSLT/LaTeXML-math-xhtml.xsl"),
1146 ),
1147 (
1148 "LaTeXML-meta-xhtml.xsl",
1149 include_str!("../resources/XSLT/LaTeXML-meta-xhtml.xsl"),
1150 ),
1151 (
1152 "LaTeXML-misc-xhtml.xsl",
1153 include_str!("../resources/XSLT/LaTeXML-misc-xhtml.xsl"),
1154 ),
1155 (
1156 "LaTeXML-para-xhtml.xsl",
1157 include_str!("../resources/XSLT/LaTeXML-para-xhtml.xsl"),
1158 ),
1159 (
1160 "LaTeXML-picture-xhtml.xsl",
1161 include_str!("../resources/XSLT/LaTeXML-picture-xhtml.xsl"),
1162 ),
1163 (
1164 "LaTeXML-structure-xhtml.xsl",
1165 include_str!("../resources/XSLT/LaTeXML-structure-xhtml.xsl"),
1166 ),
1167 (
1168 "LaTeXML-tabular-xhtml.xsl",
1169 include_str!("../resources/XSLT/LaTeXML-tabular-xhtml.xsl"),
1170 ),
1171 (
1172 "LaTeXML-tei.xsl",
1173 include_str!("../resources/XSLT/LaTeXML-tei.xsl"),
1174 ),
1175 (
1176 "LaTeXML-webpage-xhtml.xsl",
1177 include_str!("../resources/XSLT/LaTeXML-webpage-xhtml.xsl"),
1178 ),
1179 (
1180 "LaTeXML-xhtml5.xsl",
1181 include_str!("../resources/XSLT/LaTeXML-xhtml5.xsl"),
1182 ),
1183 (
1184 "LaTeXML-xhtml.xsl",
1185 include_str!("../resources/XSLT/LaTeXML-xhtml.xsl"),
1186 ),
1187 ];
1188
1189 use std::sync::OnceLock;
1190
1191 pub const URL_PREFIX: &str = "embed:///";
1196
1197 pub fn lookup(name: &str) -> Option<&'static [u8]> {
1200 FILES
1201 .iter()
1202 .find_map(|(n, c)| (*n == name).then_some(c.as_bytes()))
1203 }
1204
1205 pub fn resolve(url: &str) -> Option<&'static [u8]> {
1221 if disk_path(url).is_some() {
1222 return None;
1223 }
1224 let name = url.rsplit(['/', ':']).next().unwrap_or(url);
1225 lookup(name)
1226 }
1227
1228 pub fn disk_path(url: &str) -> Option<std::path::PathBuf> {
1230 url_path(url).filter(|path| path.is_absolute() && path.is_file())
1231 }
1232
1233 pub(super) fn url_path(url: &str) -> Option<std::path::PathBuf> {
1237 let path = match url.strip_prefix("file:") {
1238 None => url.to_string(),
1239 Some(rest) => {
1240 let path = match rest.strip_prefix("//") {
1241 Some(auth) => match auth.strip_prefix("localhost").unwrap_or(auth) {
1242 local if local.starts_with('/') => local,
1243 _ if cfg!(windows) => rest,
1245 _ => return None,
1246 },
1247 None => rest,
1248 };
1249 let path = percent_decode(path)?;
1250 match path.strip_prefix('/') {
1252 Some(rest) if cfg!(windows) && rest.as_bytes().get(1) == Some(&b':') => rest.to_string(),
1253 _ => path,
1254 }
1255 },
1256 };
1257 Some(std::path::PathBuf::from(path))
1258 }
1259
1260 fn percent_decode(s: &str) -> Option<String> {
1261 if !s.contains('%') {
1262 return Some(s.to_string());
1263 }
1264 let mut bytes = Vec::with_capacity(s.len());
1265 let mut it = s.bytes();
1266 while let Some(b) = it.next() {
1267 if b == b'%' {
1268 let hex = [it.next()?, it.next()?];
1269 bytes.push(u8::from_str_radix(std::str::from_utf8(&hex).ok()?, 16).ok()?);
1270 } else {
1271 bytes.push(b);
1272 }
1273 }
1274 String::from_utf8(bytes).ok()
1275 }
1276
1277 pub fn install_callback_once() {
1285 static INSTALLED: OnceLock<()> = OnceLock::new();
1286 INSTALLED.get_or_init(|| {
1287 libxml::io::register_input_callback(
1288 |url| resolve(url).is_some(),
1294 |url| resolve(url).map(|s| s.to_vec()),
1295 );
1296 });
1297 }
1298}
1299
1300mod embedded_resources {
1313 pub const CSS_FILES: &[(&str, &str)] = &[
1314 (
1315 "LaTeXML-blue.css",
1316 include_str!("../resources/CSS/LaTeXML-blue.css"),
1317 ),
1318 (
1319 "LaTeXML-epub.css",
1320 include_str!("../resources/CSS/LaTeXML-epub.css"),
1321 ),
1322 (
1323 "LaTeXML-marginpar.css",
1324 include_str!("../resources/CSS/LaTeXML-marginpar.css"),
1325 ),
1326 (
1327 "LaTeXML-navbar-left.css",
1328 include_str!("../resources/CSS/LaTeXML-navbar-left.css"),
1329 ),
1330 (
1331 "LaTeXML-navbar-right.css",
1332 include_str!("../resources/CSS/LaTeXML-navbar-right.css"),
1333 ),
1334 ("LaTeXML.css", include_str!("../resources/CSS/LaTeXML.css")),
1335 (
1336 "ltx-amsart.css",
1337 include_str!("../resources/CSS/ltx-amsart.css"),
1338 ),
1339 ("ltx-apj.css", include_str!("../resources/CSS/ltx-apj.css")),
1340 (
1341 "ltx-article.css",
1342 include_str!("../resources/CSS/ltx-article.css"),
1343 ),
1344 (
1345 "ltx-book.css",
1346 include_str!("../resources/CSS/ltx-book.css"),
1347 ),
1348 ("ltx-cv.css", include_str!("../resources/CSS/ltx-cv.css")),
1349 (
1350 "ltx-listings.css",
1351 include_str!("../resources/CSS/ltx-listings.css"),
1352 ),
1353 (
1354 "ltx-report.css",
1355 include_str!("../resources/CSS/ltx-report.css"),
1356 ),
1357 (
1358 "ltx-svjour.css",
1359 include_str!("../resources/CSS/ltx-svjour.css"),
1360 ),
1361 (
1362 "ltx-ulem.css",
1363 include_str!("../resources/CSS/ltx-ulem.css"),
1364 ),
1365 (
1366 "relaxng-schema-rustdoc-theme.css",
1367 include_str!("../resources/CSS/relaxng-schema-rustdoc-theme.css"),
1368 ),
1369 ];
1370
1371 pub const JS_FILES: &[(&str, &str)] = &[
1372 (
1373 "LaTeXML-maybeMathjax.js",
1374 include_str!("../resources/javascript/LaTeXML-maybeMathjax.js"),
1375 ),
1376 (
1377 "relaxng-schema-rustdoc-theme.js",
1378 include_str!("../resources/javascript/relaxng-schema-rustdoc-theme.js"),
1379 ),
1380 ];
1381
1382 include!(concat!(env!("OUT_DIR"), "/embedded_ar5iv_css.rs"));
1384
1385 pub const AR5IV_CSS_NAME: &str = "ar5iv.css";
1387
1388 pub fn lookup(basename: &str) -> Option<&'static [u8]> {
1393 CSS_FILES
1394 .iter()
1395 .chain(JS_FILES.iter())
1396 .find_map(|(n, c)| (*n == basename).then_some(c.as_bytes()))
1397 }
1398
1399 pub fn bundled(src: &str, basename: &str) -> Option<&'static [u8]> {
1402 lookup(basename).or_else(|| {
1403 AR5IV_CSS
1404 .filter(|_| src == AR5IV_CSS_NAME)
1405 .map(str::as_bytes)
1406 })
1407 }
1408}
1409
1410pub fn ar5iv_css_bundled() -> Option<&'static str> { embedded_resources::AR5IV_CSS }
1412
1413fn find_stylesheet(stylesheet: &str, searchpaths: &[String]) -> Result<String, PostError> {
1420 if let Some(name) = stylesheet.strip_prefix(embedded_xslt::URL_PREFIX)
1421 && embedded_xslt::lookup(name).is_some()
1422 {
1423 embedded_xslt::install_callback_once();
1424 return Ok(stylesheet.to_string());
1425 }
1426 if let Some(path) = embedded_xslt::disk_path(stylesheet) {
1427 return Ok(path.to_string_lossy().into_owned());
1428 }
1429 let candidates = std::iter::once(PathBuf::from(stylesheet))
1430 .chain(searchpaths.iter().map(|sp| Path::new(sp).join(stylesheet)));
1431 for candidate in candidates {
1432 if candidate.is_file() {
1433 let path = std::path::absolute(&candidate).unwrap_or(candidate);
1434 return Ok(path.to_string_lossy().into_owned());
1435 }
1436 }
1437 let filename = Path::new(stylesheet)
1442 .file_name()
1443 .and_then(|f| f.to_str())
1444 .unwrap_or(stylesheet);
1445 if embedded_xslt::lookup(filename).is_some() {
1446 embedded_xslt::install_callback_once();
1447 return Ok(format!("{}{}", embedded_xslt::URL_PREFIX, filename));
1448 }
1449 Err(PostError::Processing(format!(
1450 "No stylesheet '{}' found!",
1451 stylesheet
1452 )))
1453}
1454
1455fn find_resource_file(
1466 src: &str,
1467 info: Option<&ResourceInfo>,
1468 search_paths: &[&str],
1469) -> Option<(String, String)> {
1470 let name = Path::new(src).file_name()?.to_str()?;
1471 let mut candidates = vec![src.to_string()];
1472 if let Some(info) = info {
1473 candidates.push(format!("{}/{}", info.subdir, name));
1474 candidates.push(format!("{}/{}", info.subdir, src));
1475 candidates.dedup();
1476 }
1477 let found_under = |path: &str, base: &str| {
1478 if pathname::is_contained(path, base).is_none() {
1479 let own = Path::new(path)
1480 .parent()
1481 .map(Path::to_path_buf)
1482 .unwrap_or_default();
1483 return Some((path.to_string(), own.to_string_lossy().into_owned()));
1484 }
1485 if resolves_inside(Path::new(path), base) {
1486 return Some((path.to_string(), base.to_string()));
1487 }
1488 Warn!(
1489 "unexpected",
1490 src,
1491 "{} resolves outside {}; not used",
1492 path,
1493 base
1494 );
1495 None
1496 };
1497 let points_out = pathname::is_absolute(src) || src.split(['/', '\\']).any(|part| part == "..");
1501 let readable = |path: &str| {
1502 if pathname::read_allowed(path) {
1503 return Path::new(path).is_file();
1504 }
1505 if (points_out || pathname::refused_inside(path)) && pathname::refused_exists(path) {
1506 pathname::refuse(src);
1507 }
1508 false
1509 };
1510 pathname::requested_as(src, || {
1511 for candidate in &candidates {
1512 if readable(candidate)
1513 && let Some(found) = found_under(candidate, ".")
1514 {
1515 return Some(found);
1516 }
1517 for (i, sp) in search_paths.iter().enumerate() {
1518 let p = format!("{}/{}", sp, candidate);
1519 if !search_paths[..i].contains(sp)
1520 && readable(&p)
1521 && let Some(found) = found_under(&p, sp)
1522 {
1523 return Some(found);
1524 }
1525 }
1526 }
1527 None
1528 })
1529}
1530
1531fn resolves_inside(path: &Path, root: &str) -> bool {
1534 pathname::opens_inside(path, root).unwrap_or_else(|| {
1535 pathname::is_contained(
1536 &pathname::resolved(&path.to_string_lossy()),
1537 &pathname::resolved(root),
1538 )
1539 .is_some()
1540 })
1541}
1542
1543#[cfg(test)]
1546mod css_copy_containment_tests {
1547 use std::{collections::HashSet, fs, path::Path};
1548
1549 use latexml_core::common::error::{LogStatus, get_status};
1550
1551 use super::{RESOURCE_CSS, Roots, copy_css_imports, find_resource_file};
1552
1553 struct Row {
1555 name: &'static str,
1556 css: &'static str,
1557 files: &'static [(&'static str, &'static str)],
1558 links: &'static [(&'static str, &'static str)],
1560 copied: &'static [(&'static str, &'static str)],
1561 warnings: usize,
1562 }
1563
1564 const NESTED: &[(&str, &str)] = &[
1565 ("src/parts/a.css", "@import url(\"../b.css\");\n"),
1566 ("src/parts/deep/c.css", "@import url( \"../../b2.css\" );\n"),
1567 ("src/b.css", "/*b*/\n"),
1568 ("src/b2.css", "/*b2*/\n"),
1569 ];
1570
1571 fn rows() -> Vec<Row> {
1572 let mut rows = vec![Row {
1573 name: "nested in-root ../ imports",
1574 css: "@import url(\"parts/a.css\"); @import \"parts/deep/c.css\"; body{}\n",
1575 files: NESTED,
1576 links: &[],
1577 copied: &[
1578 ("out/parts/a.css", "@import url(\"../b.css\");\n"),
1579 ("out/parts/deep/c.css", "@import url( \"../../b2.css\" );\n"),
1580 ("out/b.css", "/*b*/\n"),
1581 ("out/b2.css", "/*b2*/\n"),
1582 ],
1583 warnings: 0,
1584 }];
1585 if cfg!(unix) {
1586 rows.extend([
1587 Row {
1588 name: "a link in the destination",
1589 css: "@import url(\"L/evil.css\");\n",
1590 files: &[("src/L/evil.css", "FROM-SRC\n")],
1591 links: &[("out/L", "victim")],
1592 copied: &[],
1593 warnings: 1,
1594 },
1595 Row {
1597 name: "a link then .. in the destination",
1598 css: "@import url(\"L/../evil.css\");\n",
1599 files: &[("src/evil.css", "FROM-SRC\n"), ("src/L/keep", "")],
1600 links: &[("out/L", "victim/sub")],
1601 copied: &[("out/evil.css", "FROM-SRC\n")],
1602 warnings: 0,
1603 },
1604 Row {
1605 name: "an import that links to a host file",
1606 css: "@import url(\"s.css\");\n",
1607 files: &[],
1608 links: &[("src/s.css", "secret.txt")],
1609 copied: &[],
1610 warnings: 1,
1611 },
1612 Row {
1613 name: "an import through a folder link out of the source",
1614 css: "@import url(\"L/secret.txt\");\n",
1615 files: &[],
1616 links: &[("src/L", "")],
1617 copied: &[],
1618 warnings: 1,
1619 },
1620 Row {
1622 name: "a link inside the source then ..",
1623 css: "@import url(\"a/b/c/L/../../../../secret.txt\");\n",
1624 files: &[("src/a/b/c/keep", ""), ("src/x/y/z/keep", "")],
1625 links: &[("src/a/b/c/L", "src/x/y/z")],
1626 copied: &[],
1627 warnings: 1,
1628 },
1629 Row {
1630 name: "a link that stays in the source",
1631 css: "@import \"alias.css\";\n",
1632 files: &[("src/b.css", "/*b*/\n")],
1633 links: &[("src/alias.css", "src/b.css")],
1634 copied: &[("out/alias.css", "/*b*/\n")],
1635 warnings: 0,
1636 },
1637 ]);
1638 }
1639 rows
1640 }
1641
1642 fn write(path: &Path, body: &str) {
1643 fs::create_dir_all(path.parent().unwrap()).unwrap();
1644 fs::write(path, body).unwrap();
1645 }
1646
1647 #[cfg(unix)]
1648 fn link(at: &Path, target: &Path) {
1649 fs::create_dir_all(at.parent().unwrap()).unwrap();
1650 std::os::unix::fs::symlink(target, at).unwrap();
1651 }
1652 #[cfg(not(unix))]
1653 fn link(_: &Path, _: &Path) {}
1654
1655 #[test]
1656 fn css_imports_stay_inside_their_roots() {
1657 for row in rows() {
1658 let work = tempfile::tempdir().unwrap();
1659 let w = work.path();
1660 write(&w.join("victim/evil.css"), "ORIGINAL\n");
1661 fs::create_dir_all(w.join("victim/sub")).unwrap();
1662 write(&w.join("secret.txt"), "SECRET\n");
1663 write(&w.join("src/top.css"), row.css);
1664 write(&w.join("out/top.css"), row.css);
1665 for (path, body) in row.files {
1666 write(&w.join(path), body);
1667 }
1668 for (at, target) in row.links {
1669 link(&w.join(at), &w.join(target));
1670 }
1671 let (src, out) = (w.join("src"), w.join("out"));
1672 let roots = Roots {
1673 dest: &out.to_string_lossy(),
1674 source: &src.to_string_lossy(),
1675 };
1676 let before = get_status(LogStatus::Warning);
1677 copy_css_imports(
1678 &src.join("top.css"),
1679 &out.join("top.css"),
1680 &roots,
1681 &mut HashSet::new(),
1682 );
1683 let name = row.name;
1684 assert_eq!(
1685 get_status(LogStatus::Warning) - before,
1686 row.warnings,
1687 "{name}"
1688 );
1689 assert_eq!(
1690 fs::read_to_string(w.join("victim/evil.css")).unwrap(),
1691 "ORIGINAL\n",
1692 "{name}"
1693 );
1694 for (path, body) in row.copied {
1695 assert_eq!(
1696 fs::read_to_string(w.join(path)).ok().as_deref(),
1697 Some(*body),
1698 "{name}: {path}"
1699 );
1700 }
1701 let mut written: Vec<String> = Vec::new();
1702 let mut stack = vec![out.clone(), w.join("victim")];
1703 while let Some(dir) = stack.pop() {
1704 for entry in fs::read_dir(&dir).unwrap().flatten() {
1705 let path = entry.path();
1706 if entry.file_type().unwrap().is_dir() {
1707 stack.push(path);
1708 } else if entry.file_type().unwrap().is_file() {
1709 assert_ne!(
1710 fs::read_to_string(&path).unwrap(),
1711 "SECRET\n",
1712 "{name}: {}",
1713 path.display()
1714 );
1715 written.push(
1716 path
1717 .strip_prefix(w)
1718 .unwrap()
1719 .to_string_lossy()
1720 .replace('\\', "/"),
1721 );
1722 }
1723 }
1724 }
1725 written.sort();
1726 let mut expected: Vec<String> = row
1727 .copied
1728 .iter()
1729 .map(|(path, _)| path.to_string())
1730 .collect();
1731 expected.extend(["out/top.css".to_string(), "victim/evil.css".to_string()]);
1732 expected.sort();
1733 assert_eq!(written, expected, "{name}");
1734 }
1735 }
1736
1737 #[test]
1739 fn a_found_stylesheet_resolves_inside_its_search_path() {
1740 let work = tempfile::tempdir().unwrap();
1741 let sp = work.path().join("paper");
1742 write(
1743 &sp.join("resources/CSS/containment-row-plain.css"),
1744 "/*plain*/\n",
1745 );
1746 let sp_str = sp.to_string_lossy().into_owned();
1747 let before = get_status(LogStatus::Warning);
1748 let found = find_resource_file("containment-row-plain.css", Some(&RESOURCE_CSS), &[&sp_str]);
1749 assert_eq!(
1750 found,
1751 Some((
1752 format!("{sp_str}/resources/CSS/containment-row-plain.css"),
1753 sp_str.clone()
1754 ))
1755 );
1756 assert_eq!(get_status(LogStatus::Warning), before);
1757 if cfg!(unix) {
1758 write(&work.path().join("secret.txt"), "SECRET\n");
1759 link(
1760 &sp.join("resources/CSS/containment-row-link.css"),
1761 &work.path().join("secret.txt"),
1762 );
1763 let found = find_resource_file("containment-row-link.css", Some(&RESOURCE_CSS), &[&sp_str]);
1764 assert_eq!(found, None);
1765 assert_eq!(get_status(LogStatus::Warning) - before, 1);
1766 fs::create_dir_all(sp.join("a/b")).unwrap();
1768 fs::create_dir_all(sp.join("deep/er")).unwrap();
1769 link(&sp.join("a/b/L"), &sp.join("deep/er"));
1770 write(&work.path().join("containment-row-climb.css"), "SECRET\n");
1771 let found = find_resource_file("a/b/L/../../../containment-row-climb.css", None, &[&sp_str]);
1772 assert_eq!(found, None);
1773 assert_eq!(get_status(LogStatus::Warning) - before, 2);
1774 }
1775 }
1776}
1777
1778#[cfg(test)]
1779mod witnessed_css_delta {
1780 use super::embedded_resources;
1791
1792 fn bundled_latexml_css() -> &'static str {
1793 std::str::from_utf8(embedded_resources::lookup("LaTeXML.css").expect("LaTeXML.css is bundled"))
1794 .expect("LaTeXML.css is valid UTF-8")
1795 }
1796
1797 #[test]
1798 fn witnessed_minipage_delta_stays_present() {
1799 let css = bundled_latexml_css();
1800 assert!(
1801 css.contains("2605.02240")
1802 && css.contains(
1803 ".ltx_foreignobject_container:has( > .ltx_foreignobject_content > .ltx_minipage)"
1804 ),
1805 "the witnessed minipage top-alignment delta (2605.02240) is missing from LaTeXML.css",
1806 );
1807 }
1808
1809 #[test]
1810 fn dark_mode_note_popup_delta_stays_present() {
1811 let css = bundled_latexml_css();
1812 let start = css
1813 .find("@media (prefers-color-scheme: dark) {")
1814 .expect("LaTeXML.css has a dark-mode block");
1815 let mut depth = 0usize;
1816 let mut end = css.len();
1817 for (offset, ch) in css[start..].char_indices() {
1818 match ch {
1819 '{' => depth += 1,
1820 '}' => {
1821 depth -= 1;
1822 if depth == 0 {
1823 end = start + offset;
1824 break;
1825 }
1826 },
1827 _ => {},
1828 }
1829 }
1830 let dark = &css[start..end];
1831 assert!(
1832 dark.contains("#1207")
1833 && dark.contains(" .ltx_note_content,\n")
1834 && dark.contains(".ltx_author_notes:hover .ltx_author_notes_content,")
1835 && dark.contains(".ltx_pubnotes:hover .ltx_pubnotes_content,")
1836 && dark.contains("background-color: black;"),
1837 "the dark-mode pop-up note delta (issue #1207) is missing from LaTeXML.css's dark block: a note's \
1838 pop-up would keep its white box under the page's white text and read blank",
1839 );
1840 }
1841
1842 #[test]
1843 fn equation_display_margin_delta_stays_present() {
1844 let css = bundled_latexml_css();
1845 assert!(
1846 css.contains("#473")
1847 && css.contains(".ltx_eqn_table, .ltx_eqn_div { margin-top:1em; margin-bottom:1em; }"),
1848 "the display-equation vertical-margin delta (issue #473) is missing from LaTeXML.css: \
1849 adjacent display equations would render touching, unlike TeX's \\abovedisplayskip",
1850 );
1851 }
1852
1853 #[test]
1854 fn verbatim_whitespace_delta_stays_present() {
1855 let css = bundled_latexml_css();
1856 assert!(
1857 css.contains("#431")
1858 && css.contains(".ltx_verbatim { white-space:pre; }")
1859 && css.contains(".ltx_text.ltx_verbatim.ltx_inline-block"),
1860 "the verbatim whitespace/line-block delta (issue #431) is missing from LaTeXML.css: \
1861 plain verbatim would collapse to one line under vanilla's nowrap, and fancyvrb \
1862 source lines would reflow side-by-side with their indentation collapsed",
1863 );
1864 for rule in [
1872 "code.ltx_verbatim { white-space:pre-wrap; overflow-wrap:break-word; }",
1873 ".ltx_td code.ltx_verbatim, .ltx_th code.ltx_verbatim { white-space:pre; }",
1874 ".ltx_verbatim .ltx_parbox { white-space:normal; }",
1875 ".ltx_verbatim .ltx_parbox .ltx_p { white-space:pre-wrap; }",
1876 ".ltx_text.ltx_verbatim.ltx_inline-block { display:block; text-indent:0; min-height:1lh; \
1877 max-width:100%; }",
1878 ".ltx_text.ltx_inline-block:has(> .ltx_text.ltx_verbatim.ltx_inline-block) { display:flex; \
1879 text-indent:0; max-width:100%; }",
1880 ".ltx_text.ltx_inline-block > .ltx_text.ltx_verbatim.ltx_inline-block { min-width:0; }",
1881 ".ltx_text.ltx_verbatim.ltx_inline-block:has(> .ltx_parbox, > .ltx_text > .ltx_parbox) { \
1882 display:flex; }",
1883 ".ltx_verbatim > .ltx_text:has(> .ltx_parbox) { display:contents; }",
1884 ".ltx_verbatim > .ltx_parbox, .ltx_verbatim > .ltx_text > .ltx_parbox { flex-shrink:1; \
1885 min-width:0; }",
1886 ".ltx_framed.ltx_framed_verbatim { display:block; width:fit-content; }",
1887 ] {
1888 assert!(
1889 css.contains(rule),
1890 "LaTeXML.css lost the verbatim rule `{rule}` (issues #431/#702/853)"
1891 );
1892 }
1893 }
1894
1895 #[test]
1896 fn dashed_border_delta_follows_the_border_rules() {
1897 let css = bundled_latexml_css();
1900 let last_shorthand = css
1901 .find(".ltx_border_L {")
1902 .expect("the light left border rule");
1903 for rule in [
1904 ".ltx_border_t_dashed { border-top-style:dashed; }",
1905 ".ltx_border_r_dashed { border-right-style:dashed; }",
1906 ".ltx_border_b_dashed { border-bottom-style:dashed; }",
1907 ".ltx_border_l_dashed { border-left-style:dashed; }",
1908 ] {
1909 let at = css
1910 .find(rule)
1911 .unwrap_or_else(|| panic!("LaTeXML.css lost the dashed border rule `{rule}`"));
1912 assert!(
1913 at > last_shorthand,
1914 "`{rule}` must follow the border shorthands"
1915 );
1916 }
1917 }
1918
1919 #[test]
1920 fn author_line_delta_stays_present() {
1921 const CARD: &str =
1926 ":not(:has(.ltx_contact:not(.ltx_author_line):not(.ltx_role_note):not(.ltx_role_thanks)))";
1927 let css = bundled_latexml_css();
1928 for rule in [
1929 format!("DOC .ltx_creator:has(.ltx_author_line){CARD} {{\n display:inline-block;"),
1930 format!("DOC .ltx_author_notes{CARD}:has(.ltx_author_line) {{\n display:inline; }}"),
1931 format!(
1932 "DOC .ltx_author_notes{CARD}:has(.ltx_author_line):not(:has(.ltx_role_note, \
1933 .ltx_role_thanks)):before {{\n content:none; }}"
1934 ),
1935 format!(
1936 "DOC .ltx_author_notes{CARD}:has(.ltx_author_line) .ltx_contact:not(.ltx_author_line) {{\n display:none; }}"
1937 ),
1938 format!(
1940 "DOC .ltx_author_notes{CARD}:has(.ltx_author_line):hover .ltx_contact:not(.ltx_author_line) {{\n \
1941 display:block; position:static; contain:inline-size;"
1942 ),
1943 format!(
1944 "DOC .ltx_author_notes{CARD}:has(.ltx_author_line) .ltx_author_line .ltx_contact_name {{ display:none; }}"
1945 ),
1946 ] {
1947 let rule = rule.replace("DOC", ".ltx_document:not(.ltx_authors_multiline)");
1948 assert!(
1949 css.contains("#783") && css.contains(&rule),
1950 "LaTeXML.css lost the author-line rule `{rule}` (issue #783)"
1951 );
1952 }
1953 assert!(
1955 !css.contains("\n.ltx_author_line .ltx_contact_name"),
1956 "an unscoped author-line label hide"
1957 );
1958 }
1959
1960 #[test]
1961 fn shared_author_note_delta_stays_present() {
1962 const CARD: &str = ".ltx_document:not(.ltx_authors_multiline) .ltx_creator:has(.ltx_author_line):not(:has(\
1972 .ltx_contact:not(.ltx_author_line):not(.ltx_role_note):not(.ltx_role_thanks)))";
1973 let card = format!(":is({CARD}, .ltx_authors_multiline .ltx_creator)");
1974 let lines = format!("{card} .ltx_annotated_personname > .ltx_note");
1975 let body = ".ltx_note_outer:not(.ltx_note_copy)";
1976 let css = bundled_latexml_css();
1977 for rule in [
1978 ".ltx_annotated_personname:has(> .ltx_note) { display:inline; }".to_string(),
1979 ".ltx_note_shared > .ltx_note_mark > a { color:inherit; text-decoration:none; }".to_string(),
1980 format!("{lines} {{ display:inline; }}"),
1981 format!("{lines} > {body} .ltx_note_content {{\n display:block; position:static; float:inline-start; clear:both; width:100%;"),
1982 format!("{lines} > {body} .ltx_note_content .ltx_note_mark {{ position:static; }}"),
1983 format!("{lines} > {body} .ltx_note_type {{ display:none; }}"),
1984 ".ltx_annotated_personname > .ltx_note:has(~ .ltx_note) > .ltx_note_mark::after { content:\",\"; }".to_string(),
1985 ] {
1986 assert!(
1987 css.contains("#1052") && css.contains(&rule),
1988 "LaTeXML.css lost the shared author note rule `{rule}` (#1052)"
1989 );
1990 }
1991 assert!(
1992 !css.contains(&format!(
1993 "{lines}:not(.ltx_note_shared):not(.ltx_role_footnotemark) .ltx_note_mark"
1994 )),
1995 "LaTeXML.css hides a one-author note's mark again (DG 2026-11-17: every marked note shows the mark the PDF prints)"
1996 );
1997 assert!(
1998 !css.contains(&format!("{card} > .ltx_note")),
1999 "LaTeXML.css shows an unmarked author note under the name (#1052, 1510.02728)"
2000 );
2001 }
2002
2003 #[test]
2004 fn constrained_equation_overflow_delta_stays_present() {
2005 let css = bundled_latexml_css();
2010 for rule in [
2011 ".ltx_inline-block .ltx_eqn_table,\n.ltx_td .ltx_eqn_table { display:block; max-width:100%; }",
2012 ":is(.ltx_inline-block, .ltx_inline-logical-block, .ltx_minipage, .ltx_parbox):has(.ltx_eqn_table) {\n \
2013 min-width:min-content; }",
2014 ":is(.ltx_inline-block, .ltx_inline-logical-block, .ltx_minipage, .ltx_parbox, .ltx_td) :is(.ltx_eqn_center_padleft, .ltx_eqn_center_padright) {\n \
2015 min-width:0; }",
2016 ".ltx_note_content:has(.ltx_eqn_table) { overflow-x:auto; }",
2017 ] {
2018 assert!(
2019 css.contains("#533") && css.contains("#972") && css.contains(rule),
2020 "LaTeXML.css lost the constrained-equation rule `{rule}` (issues #533, #972)"
2021 );
2022 }
2023 assert!(
2024 !css.contains("display:block; overflow-x:auto; max-width:100%;"),
2025 "a display in a box is a scroll container again (issue #972: phantom vertical scrollbars)"
2026 );
2027 }
2028
2029 #[test]
2030 fn equation_tag_and_mathjax_deltas_stay_present() {
2031 let css = bundled_latexml_css();
2036 for (issue, rule) in [
2037 ("#810", ".ltx_eqn_eqno { max-width:none; }"),
2038 (
2039 "#810",
2040 ".ltx_equation.ltx_eqn_table > * > .ltx_eqn_row:only-child:has(> .ltx_eqn_center_padleft) {\n \
2041 display:grid; grid-template-columns:minmax(2em,1fr) auto 1fr; align-items:center; }",
2042 ),
2043 (
2044 "#475",
2045 ".ltx_eqn_table .ltx_eqn_cell > mjx-container[display=\"true\"],\n\
2046 .ltx_eqn_table .ltx_eqn_cell > .MathJax_Display { margin-top:0; margin-bottom:0; }",
2047 ),
2048 ] {
2049 assert!(
2050 css.contains(issue) && css.contains(rule),
2051 "LaTeXML.css lost the issue {issue} rule `{rule}`"
2052 );
2053 }
2054 }
2055
2056 #[test]
2057 fn equation_rows_in_inline_context_delta_stays_present() {
2058 let css = bundled_latexml_css();
2065 for rule in [
2066 "span.ltx_eqn_table > span:not([class]) { display:table-row-group; }",
2067 "span.ltx_eqn_table { display:block; max-width:100%; }",
2068 ".ltx_tabular .ltx_eqn_cell { padding:0; }",
2069 ".ltx_eqn_align .ltx_equation > .ltx_align_left + .ltx_align_right,",
2070 ".ltx_eqn_eqnarray .ltx_eqn_lefteqn + .ltx_eqn_row > .ltx_align_right { min-width:2em; }",
2071 "span.ltx_eqn_table .ltx_eqn_cell { padding:1px; }",
2072 "span.ltx_eqn_table > span:not([class]):has(> .ltx_eqn_row > .ltx_eqn_cell[colspan]:only-child),\n\
2073 span.ltx_eqn_table > span:not([class]) > .ltx_eqn_row:has(> .ltx_eqn_cell[colspan]:only-child),\n\
2074 span.ltx_eqn_table > span:not([class]) > .ltx_eqn_row > .ltx_eqn_cell[colspan]:only-child { display:block; }",
2075 ] {
2076 assert!(
2077 css.contains("#972") && css.contains(rule),
2078 "LaTeXML.css lost the issue #972 rule `{rule}`"
2079 );
2080 }
2081 }
2082
2083 #[test]
2084 fn framed_verbatim_responsive_delta_stays_present() {
2085 let css = bundled_latexml_css();
2086 assert!(
2087 css.contains("#525")
2088 && css.contains(
2089 ".ltx_framed_verbatim { max-width:100%; overflow-x:auto; box-sizing:border-box; }"
2090 ),
2091 "the framed-verbatim responsive-containment delta (issue #525) is missing from \
2092 LaTeXML.css: a fancyvrb frame=single box spans the print \\linewidth and would push \
2093 its border off-screen and scroll the whole page on a phone",
2094 );
2095 }
2096
2097 #[test]
2098 fn float_safe_center_delta_stays_present() {
2099 for name in ["ltx-article.css", "ltx-book.css", "ltx-report.css"] {
2103 let css =
2104 std::str::from_utf8(embedded_resources::lookup(name).expect("bundled")).expect("UTF-8");
2105 assert!(
2106 css.contains(
2107 ".ltx_table,\n.ltx_figure { display:flex; flex-direction:column; align-items:center; \
2108 align-items:safe center; }"
2109 ),
2110 "{name} lost the float's `align-items:safe center` after its `center` fallback (issue #1135)"
2111 );
2112 }
2113 }
2114
2115 #[test]
2116 fn title_pubnote_content_stays_collapsed() {
2117 let css = bundled_latexml_css();
2124 assert!(
2125 css.contains(".ltx_pubnotes:before {\n content:\"\\24D8\""),
2126 "the title-footnote handle rule (.ltx_pubnotes:before, ⓘ since OXIDIZED_DESIGN_DIVERGENCES #1069) is missing \
2127 from LaTeXML.css (arXiv/html_feedback#6888)",
2128 );
2129 assert!(
2130 css.contains(".ltx_pubnotes .ltx_pubnotes_content")
2131 && css.contains("visibility:hidden; opacity:0"),
2132 "the title-footnote CONTENT-hidden rule (.ltx_pubnotes .ltx_pubnotes_content \
2133 {{ visibility:hidden }}) is missing from LaTeXML.css: the `\\thanks` text would \
2134 render inline in the title instead of collapsing to its handle \
2135 (arXiv/html_feedback#6888)",
2136 );
2137 }
2138
2139 #[test]
2140 fn no_xsl_key_match_has_a_predicated_descendant_step() {
2141 for (name, xsl) in [(
2146 "LaTeXML-meta-xhtml.xsl",
2147 include_str!("../resources/XSLT/LaTeXML-meta-xhtml.xsl"),
2148 )] {
2149 for key in xsl.split("<xsl:key ").skip(1) {
2150 let matched = key
2151 .split("match=\"")
2152 .nth(1)
2153 .and_then(|m| m.split('"').next())
2154 .unwrap_or("");
2155 let flat: String = matched.split_whitespace().collect::<Vec<_>>().join(" ");
2156 for step in flat.split("//").skip(1) {
2157 let head: String = step
2158 .chars()
2159 .take_while(|c| !matches!(c, '[' | '|' | '/' | ' '))
2160 .collect();
2161 assert!(
2162 !step[head.len()..].starts_with('['),
2163 "{name}: an xsl:key match has the predicated descendant step `//{head}[…]`: {flat}"
2164 );
2165 }
2166 }
2167 }
2168 }
2169
2170 #[test]
2171 fn css_draws_no_footnote_mark_glyph() {
2172 let css = bundled_latexml_css();
2177 for glyph in [
2178 "*", "\\2217", "∗", "\\002020", "\\2020", "†", "\\2021", "‡", "\\00A7", "§", "\\00B6", "¶",
2179 "\\2016", "‖",
2180 ] {
2181 for spaced in ["", " "] {
2182 let rule = format!("content:{spaced}\"{glyph}\"");
2183 assert!(
2184 !css.contains(&rule),
2185 "LaTeXML.css draws the footnote-mark glyph `{rule}`"
2186 );
2187 }
2188 }
2189 for handle in [
2190 ".ltx_author_notes:before {\n content:\"\\24D8\"",
2191 ".ltx_pubnotes:before {\n content:\"\\24D8\"",
2192 ] {
2193 assert!(
2194 css.contains(handle),
2195 "LaTeXML.css lacks the ⓘ hover handle `{handle}`"
2196 );
2197 }
2198 }
2199}