use texrra_tex_core::execution::*; struct TestDevice; impl SourceProvider for TestDevice { fn read(&mut self, name: &str, _: &str) -> Result { Err(format!("unexpected input {name}")) } fn default_pk_resolution(&mut self) -> Result { Ok(600) } } fn run(state: State, text: &str) -> Execution { Executor::new(state, Limits::default()) .run(source(text), &mut NoFiles) .unwrap() } fn source(text: &str) -> SourceFile { SourceFile { name: "profile.tex".into(), data: text.as_bytes().into(), } } fn messages(result: &Execution) -> Vec<&str> { result .events .iter() .filter_map(|event| match event { Event::Message { text, .. } => Some(text.as_str()), _ => None, }) .collect() } #[test] fn xetex_primitives_follow_each_profiles_language_and_device() { let tex = r"\catcode123=1 \catcode125=2 \message{\meaning\XeTeXversion/\meaning\XeTeXrevision/\meaning\pdfoutput} \message{\meaning\strcmp/\meaning\pdfstrcmp/\meaning\pdfsavepos} \message{\meaning\pdftexversion/\meaning\Uchar/\meaning\pdfpagesattr} \message{\meaning\XeTeXpdffile/\meaning\XeTeXpdfpagecount/\meaning\XeTeXpicfile} \end"; for (profile, etex, expected) in [ ( InputProfile::XeTeX, true, [ r"\XeTeXversion/\XeTeXrevision/undefined", r"\strcmp/undefined/\pdfsavepos", r"undefined/\Uchar/undefined", r"\XeTeXpdffile/\XeTeXpdfpagecount/\XeTeXpicfile", ], ), ( InputProfile::XeTeX, false, [ "undefined/undefined/undefined", r"\strcmp/undefined/\pdfsavepos", r"undefined/\Uchar/undefined", "undefined/undefined/undefined", ], ), ( InputProfile::UnicodeScalar, true, [ r"undefined/undefined/\pdfoutput", r"undefined/\pdfstrcmp/\pdfsavepos", r"undefined/\Uchar/\pdfpagesattr", "undefined/undefined/undefined", ], ), ( InputProfile::TeX8Bit, true, [ r"undefined/undefined/\pdfoutput", r"undefined/\pdfstrcmp/\pdfsavepos", r"\pdftexversion/undefined/\pdfpagesattr", "undefined/undefined/undefined", ], ), ] { let state = State::initex(); let state = if etex { state.with_etex() } else { state }; let result = run(state.with_input_profile(profile), tex); assert_eq!(messages(&result), expected); } } #[test] fn suppressed_font_probe_restores_state_and_preserves_host_errors() { struct FontProbe { denied: bool, } impl SourceProvider for FontProbe { fn read(&mut self, name: &str, _: &str) -> Result { Err(format!("unexpected input {name}")) } fn optional_font_file( &mut self, _: texrra_tex_core::resources::ResourceKind, _: &str, _: &str, ) -> Result, String> { if self.denied { return Err("font lookup denied by host".into()); } Ok(None) } } let state = State::initex().with_etex().with_input_profile(InputProfile::XeTeX); let tex = source(r"\catcode123=1 \catcode125=2 \begingroup\suppressfontnotfounderror=-1 \font\query=texrra-missing-stage65 \message{\ifx\query\nullfont null\else selected\fi} \endgroup \message{\number\suppressfontnotfounderror/\ifx\query\undefined restored\fi} \end"); let result = Executor::new(state.clone(), Limits::default()) .run(tex.clone(), &mut FontProbe { denied: false }) .unwrap(); assert_eq!(messages(&result), ["null", "0/restored"]); let error = Executor::new(state, Limits::default()) .run(tex, &mut FontProbe { denied: true }) .err() .expect("host denial must be surfaced"); assert!(error.to_string().contains("font lookup denied by host")); } #[test] fn xetex_format_preserves_internal_version_and_profile_identity() { let seed = r#"\catcode123=1 \catcode125=2 \let\versionAlias\XeTeXversion \let\revisionAlias\XeTeXrevision \edef\revisionText{\revisionAlias} \sfcode"1D6FC=3000 \dump"#; let state = State::initex() .with_input_profile(InputProfile::XeTeX) .with_etex(); let dump = run(state.clone(), seed); let bytes = FormatImage::from_dump(dump, Vec::new(), Vec::new()) .unwrap() .encode() .unwrap(); let time = JobTime::new(2025, 10, 9, 0).unwrap(); let load = |profile| { FormatImage::decode(&bytes).unwrap().new_job( state.profile(), profile, time, Limits::default(), |_| Ok(seed.as_bytes().to_vec()), ) }; assert!(matches!( load(InputProfile::UnicodeScalar), Err(message) if message == "native format profile mismatch" )); let result = load(InputProfile::XeTeX) .unwrap() .with_native_pages() .run( source( r#"\count0=\versionAlias \dimen0=\the\versionAlias\revisionAlias pt \message{\the\versionAlias/\number\versionAlias/\the\count0/\revisionText/\the\dimen0} {\sfcode"1D6FC=1500 \message{\the\sfcode"1D6FC }} \message{\the\sfcode"1D6FC } \shipout\hbox{\special{pdf:literal 0 0 5 5 re S}\vrule width5pt height3pt depth0pt} \end"#, ), &mut TestDevice, ) .unwrap(); assert_eq!(messages(&result), ["0/0/0/.999998/1.0pt", "1500", "3000"]); assert!(result.reads.contains(&Dependency::UnicodeSfCode(0x1D6FC))); let page = result .events .iter() .find_map(|event| match event { Event::Shipout(page) => Some(page), _ => None, }) .unwrap(); assert!(matches!( page.device.pdf.as_ref().map(|data| data.driver), Some(texrra_tex_core::pdf_device::PdfDriver::Xdv) )); assert!( page.display_list() .unwrap() .items .iter() .any(|item| matches!( item, texrra_tex_core::render::DisplayItem::PdfGraphics { .. } )) ); } #[test] fn xetex_formats_and_paints_nested_direction_spans() { use texrra_tex_core::render::DisplayItem; let profile_probe = r"\catcode123=1 \catcode125=2 \message{\meaning\TeXXeTstate/\meaning\beginR/\meaning\endR}\end"; let pdftex = run( State::initex().with_input_profile(InputProfile::TeX8Bit).with_etex(), profile_probe, ); assert_eq!(messages(&pdftex), [r"\TeXXeTstate/\beginR/\endR"]); let plain = run(State::initex().with_input_profile(InputProfile::XeTeX), profile_probe); assert_eq!(messages(&plain), ["undefined/undefined/undefined"]); let seed = r"\catcode123=1 \catcode125=2 \TeXXeTstate=1 \let\rtl\beginR \setbox0=\hbox{\vrule width2pt height2pt \rtl\message{\the\lastnodetype}\vrule width3pt height2pt \beginL\vrule width4pt height2pt\vrule width5pt height2pt\endL \vrule width6pt height2pt\endR \vrule width7pt height2pt}\dump"; let state = State::initex().with_input_profile(InputProfile::XeTeX).with_etex(); let dump = run(state, seed); assert_eq!(messages(&dump), ["10"]); let image = FormatImage::from_dump(dump, Vec::new(), Vec::new()).unwrap(); let bytes = image.encode().unwrap(); let result = FormatImage::decode(&bytes) .unwrap() .new_job( Profile::EtexBootstrap, InputProfile::XeTeX, JobTime::new(2025, 10, 9, 0).unwrap(), Limits::default(), |_| Ok(seed.as_bytes().to_vec()), ) .unwrap() .with_native_pages() .run( source(r"{\TeXXeTstate=0 \message{\the\TeXXeTstate}} \message{\the\TeXXeTstate} \shipout\box0 \end"), &mut TestDevice, ) .unwrap(); assert_eq!(messages(&result), ["0", "1"]); let page = result.events.iter().find_map(|event| match event { Event::Shipout(page) => Some(page.display_list().unwrap()), _ => None, }).unwrap(); let rules: Vec<_> = page.items.iter().filter_map(|item| match item { DisplayItem::Rule { x, width, .. } => Some((*x, *width)), _ => None, }).collect(); let origin = rules[0].0; let offsets: Vec<_> = rules.iter().map(|(x, w)| (x - origin, *w)).collect(); assert_eq!( offsets, [(0, 2), (2, 6), (8, 4), (12, 5), (17, 3), (20, 7)].map(|(x, w)| (x * 65536, w * 65536)) ); let error = Executor::new( State::initex().with_input_profile(InputProfile::XeTeX).with_etex(), Limits::default(), ) .run(source(r"\noindent\beginR"), &mut NoFiles) .unwrap_err(); assert!(error.message.contains(r"Improper \beginR")); } #[test] fn xetex_default_encoding_survives_dump_and_current_line_is_already_decoded() { let state = State::initex().with_input_profile(InputProfile::XeTeX).with_etex(); let mut data = br"\catcode123=1 \catcode125=2".to_vec(); data.extend_from_slice("\n\\XeTeXinputencoding \"bytes\" \\message{\\number`é}\n".as_bytes()); data.extend_from_slice(b"\\message{\\number`\xe9}\n"); data.extend_from_slice(br#"{\XeTeXdefaultencoding "utf16be"}\dump"#); let execution = Executor::new(state, Limits::default()) .run(SourceFile { name: "seed.tex".into(), data: data.clone() }, &mut NoFiles) .unwrap(); assert_eq!(messages(&execution), ["233", "233"]); let bytes = FormatImage::from_dump(execution, Vec::new(), Vec::new()) .unwrap().encode().unwrap(); let job = FormatImage::decode(&bytes).unwrap() .new_job( Profile::EtexBootstrap, InputProfile::XeTeX, JobTime::new(2025, 10, 9, 0).unwrap(), Limits::default(), |_| Ok(data.clone()), ) .unwrap(); let input = r"\def\word{😀}\message{\word}\end"; // A UTF-16 source without a BOM must follow the stored mode. let data = input.encode_utf16().flat_map(u16::to_be_bytes).collect::>(); let result = job.run(SourceFile { name: "next.tex".into(), data: data.clone() }, &mut NoFiles) .unwrap(); assert_eq!(messages(&result), ["😀"]); let Meaning::Macro(word) = result.state.meaning(&CommandName::Control("word".into())) else { panic!("expected the real definition"); }; let [Replacement::Token(token)] = word.replacement.as_slice() else { panic!("expected one scalar token"); }; assert_eq!(&data[token.span.start..token.span.end], [0xd8, 0x3d, 0xde, 0x00]); } #[test] fn xetex_inter_character_lists_follow_text_runs_and_shared_grouping() { use sha2::{Digest, Sha256}; use texrra_tex_core::resources::{LoadedResource, ResourceKind, ResourceVersion}; struct TfmSource; impl SourceProvider for TfmSource { fn read(&mut self, name: &str, from: &str) -> Result { NoFiles.read(name, from) } fn resource( &mut self, kind: ResourceKind, name: &str, _: &str, ) -> Result { assert_eq!((kind, name), (ResourceKind::Tfm, "cmr10.tfm")); let data = include_bytes!("../assets/cmr10.tfm").to_vec(); let version = ResourceVersion { path: name.into(), sha256: format!("{:x}", Sha256::digest(&data)), bytes: data.len() as u64, }; Ok(LoadedResource { version, data }) } } let seed = r"\catcode123=1 \catcode125=2 \XeTeXcharclass65=1 \XeTeXcharclass66=2 \XeTeXcharclass67=4096 \XeTeXinterchartoks1 2={\kern2pt\relax} \dump"; let state = State::initex() .with_etex() .with_input_profile(InputProfile::XeTeX); let image = FormatImage::from_dump(run(state.clone(), seed), Vec::new(), Vec::new()) .unwrap() .encode() .unwrap(); let result = FormatImage::decode(&image) .unwrap() .new_job( state.profile(), InputProfile::XeTeX, JobTime::new(2025, 10, 9, 0).unwrap(), Limits::default(), |_| Ok(seed.as_bytes().to_vec()), ) .unwrap() .run( source( r"\font\t=cmr10 \t \XeTeXinterchartoks4095 1={\kern1pt\relax} \XeTeXinterchartoks2 4095={\kern4pt\relax} \setbox0=\hbox{AB} \XeTeXinterchartokenstate=1 \setbox1=\hbox{AB} \setbox2=\hbox{\char65 \char66 C} \message{[\the\wd0,\the\wd1,\the\wd2]} \begingroup \sfcode65=1234 \global\XeTeXcharclass65=1 \endgroup \message{[\the\sfcode65,\the\XeTeXcharclass65]} \begingroup \XeTeXcharclass65=3 \global\sfcode65=1234 \endgroup \message{[\the\sfcode65,\the\XeTeXcharclass65]} \toks2=\XeTeXinterchartoks1 2 \begingroup \XeTeXinterchartokenstate=-1 \XeTeXinterchartoks1 2={} \endgroup \XeTeXinterchartoks3 2=\toks2 \message{[\the\XeTeXinterchartokenstate,\the\XeTeXinterchartoks3 2]} \end", ), &mut TfmSource, ) .unwrap(); assert_eq!( messages(&result), [ "[14.58337pt,21.58337pt,24.8056pt]", "[1234,1]", "[1234,3]", r"[1,\kern 2pt\relax ]", ] ); assert!(result.reads.contains(&Dependency::XeCharClass(67))); assert!(result.reads.contains(&Dependency::XeInterCharTokens(4098))); } #[test] fn xetex_protrusion_level_scopes_and_font_codes_are_job_local() { let state = State::initex() .with_etex() .with_input_profile(InputProfile::XeTeX); let seed = r"\catcode123=1 \catcode125=2 \XeTeXprotrudechars=2 \lpcode\nullfont65535=-1800 \message{\the\lpcode\nullfont65535} \dump"; let execution = run(state.clone(), seed); assert_eq!(messages(&execution), ["-1800"]); let image = FormatImage::from_dump(execution, Vec::new(), Vec::new()) .unwrap() .encode() .unwrap(); let executor = FormatImage::decode(&image) .unwrap() .new_job( state.profile(), InputProfile::XeTeX, JobTime::new(2025, 10, 9, 0).unwrap(), Limits::default(), |_| Ok(seed.as_bytes().to_vec()), ) .unwrap(); let result = executor .with_native_pages() .run( source( r"\message{\the\XeTeXprotrudechars/\the\lpcode\nullfont65535} \begingroup \XeTeXprotrudechars=1 \lpcode\nullfont65535=1600 \message{\the\XeTeXprotrudechars/\the\lpcode\nullfont65535} \endgroup \message{\the\XeTeXprotrudechars/\the\lpcode\nullfont65535} \shipout\hbox{\vrule width5pt height3pt depth0pt} \end", ), &mut TestDevice, ) .unwrap(); assert_eq!(messages(&result), ["2/0", "1/1600", "2/1600"]); } #[test] fn xdv_docinfo_merges_shipped_dictionaries_into_pdf_info() { use lopdf::Document; use texrra_tex_core::pdf::shipout_lists_to_native_pdf_document; let state = State::initex() .with_etex() .with_input_profile(InputProfile::XeTeX); let result = Executor::new(state, Limits::default()) .with_native_pages() .run( source( r"\catcode123=1 \catcode125=2 \setbox0=\hbox{\special{pdf:docinfo<>}} \shipout\hbox{\special{pdf:docinfo<>} \vrule width5pt height3pt depth0pt} \shipout\hbox{\special{pdf:docinfo << /Title(Edited Ω) /Creator() /Author 42 /UserBytes >>}\vrule width5pt height3pt depth0pt} \end", ), &mut TestDevice, ) .unwrap(); assert!(result.reads.contains(&Dependency::PdfInfoState)); let pages: Vec<_> = result .events .iter() .filter_map(|event| match event { Event::Shipout(page) => Some(page.display_list().unwrap()), _ => None, }) .collect(); assert_eq!(pages.len(), 2); let output = shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap(); let pdf = Document::load_mem(&output.bytes).unwrap(); let id = pdf.trailer.get(b"Info").unwrap().as_reference().unwrap(); let info = pdf.get_object(id).unwrap().as_dict().unwrap(); let title: Vec<_> = [0xFE, 0xFF] .into_iter() .chain("Edited Ω".encode_utf16().flat_map(u16::to_be_bytes)) .collect(); assert_eq!(info.get(b"Title").unwrap().as_str().unwrap(), title); assert_eq!(info.get(b"Subject").unwrap().as_str().unwrap(), b"Kept"); assert_eq!(info.get(b"UserBytes").unwrap().as_str().unwrap(), [255, 0]); for omitted in [b"Author".as_slice(), b"Creator", b"Discarded"] { assert!(!info.has(omitted)); } assert!(output.diagnostics.iter().any(|text| text.contains("Author"))); } #[test] fn xdv_destinations_use_shipped_page_ids_and_pdf_string_keys() { use lopdf::Document; use texrra_tex_core::pdf::shipout_lists_to_native_pdf_document; let state = State::initex() .with_etex() .with_input_profile(InputProfile::XeTeX); let result = Executor::new(state, Limits::default()) .with_native_pages() .run( source( r"\catcode123=1 \catcode125=2 \setbox0=\hbox{\special{pdf:dest (discarded) [@thispage /Fit]}} \shipout\hbox{\special{dvipdfmx:config C 0x0010} \special{pdf:minorversion=7} \special{pdf:dest (A) [@nextpage/Fit]} \special{pdf:dest <4100> [@thispage/FitB]} \special{pdf:dest (AB) [@thispage /XYZ null 17.125 1.5]} \vrule width5pt height3pt depth0pt} \shipout\hbox{\special{pdf:minorversion 4} \special{pdf:destination (A) [@prevpage /Fit]} \vrule width5pt height3pt depth0pt} \end", ), &mut TestDevice, ) .unwrap(); let pages: Vec<_> = result .events .iter() .filter_map(|event| match event { Event::Shipout(page) => Some(page.display_list().unwrap()), _ => None, }) .collect(); let output = shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap(); let pdf = Document::load_mem(&output.bytes).unwrap(); assert_eq!(pdf.version, "1.7"); let names = pdf.catalog().unwrap().get(b"Names").unwrap().as_dict().unwrap(); let id = names.get(b"Dests").unwrap().as_reference().unwrap(); let destinations = pdf.get_object(id).unwrap().as_dict().unwrap() .get(b"Names").unwrap().as_array().unwrap(); let keys: Vec<_> = destinations.iter().step_by(2).map(|item| item.as_str().unwrap()).collect(); assert_eq!(keys, [b"A".as_slice(), b"A\0", b"AB"]); let page_ids = pdf.get_pages(); assert_eq!(destinations[1].as_array().unwrap()[0].as_reference().unwrap(), page_ids[&2]); assert_eq!(destinations[3].as_array().unwrap()[0].as_reference().unwrap(), page_ids[&1]); let xyz = destinations[5].as_array().unwrap(); assert!(xyz[2].is_null()); assert_eq!(xyz[3].as_f64().unwrap(), 17.125); assert_eq!(xyz[4].as_f64().unwrap(), 1.5); assert!(output.diagnostics.iter().any(|text| text.contains("Object @A already defined"))); } #[test] fn xdv_color_is_shipped_in_order_and_replayed_on_the_next_page() { use lopdf::Document; use texrra_tex_core::pdf::shipout_lists_to_native_pdf_document; let state = State::initex().with_etex().with_input_profile(InputProfile::XeTeX); let result = Executor::new(state, Limits::default()) .with_native_pages() .run( source( r"\catcode123=1 \catcode125=2 \def\block{\vrule width8pt height6pt depth0pt} \setbox0=\hbox{\special{color push Blue}\special{background Black}} \shipout\hbox{\block\special{color push rgb 1 0 0} \special{x:gsave}\special{pdf:bc fill [0 1 0]}\block \special{x:grestore}\block\special{background gray .875}} \shipout\hbox{\block\special{pdf:ec}\block\special{color pop}\block} \shipout\hbox{\block\special{background White}} \end", ), &mut TestDevice, ) .unwrap(); let pages = result.shipout_display_lists().unwrap(); let output = shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()) .unwrap(); let pdf = Document::load_mem(&output.bytes).unwrap(); let page_contents: Vec<_> = pdf.get_pages().values().map(|&id| { String::from_utf8(pdf.get_page_content(id).unwrap()).unwrap() }).collect(); assert_eq!(page_contents.len(), 3); let first = &page_contents[0]; assert!(first.find("0.875 g").unwrap() < first.find(" re f").unwrap()); let green_fill = "1.000 0.000 0.000 RG 0.000 1.000 0.000 rg"; assert!(first.contains(&format!("Q\n{green_fill}\n"))); let second = &page_contents[1]; let red = "1.000 0.000 0.000 RG 1.000 0.000 0.000 rg"; assert!(second.find("0.875 g").unwrap() < second.find(green_fill).unwrap()); assert!(second.find(green_fill).unwrap() < second.find(red).unwrap()); assert!(!page_contents[2].contains("0.875 g")); let svg = pages[1].try_to_svg().unwrap(); assert!(svg.contains("fill=\"#dfdfdf\"")); assert!(svg.contains("fill=\"#00ff00\"")); let mut without_background = pages[1].clone(); without_background.pdf_background = None; assert!(!pages[1].same_svg_paint(&without_background)); } #[test] fn xdv_catalog_and_outlines_resolve_live_pages_and_retain_referenced_names() { use lopdf::Document; use texrra_tex_core::pdf::shipout_lists_to_native_pdf_document; let state = State::initex().with_etex().with_input_profile(InputProfile::XeTeX); let result = Executor::new(state, Limits::default()) .with_native_pages() .run( source( r"\catcode123=1 \catcode125=2 \setbox0=\hbox{\special{pdf:docview<>}} \shipout\hbox{\special{pdf:docview<>>>} \special{pdf:outline [-] 1</A<>>>} \special{pdf:dest (unused) [@thispage/Fit]} \vrule width7pt height8pt} \shipout\hbox{\special{pdf:docview<>>>} \special{pdf:out [] 2<>} \special{pdf:dest (topic) [@thispage/Fit]} \special{pdf:outline 1<>} \vrule width9pt height8pt} \end", ), &mut TestDevice, ) .unwrap(); assert!(result.reads.contains(&Dependency::PdfCatalogState)); let pages = result.shipout_display_lists().unwrap(); let output = shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap(); let pdf = Document::load_mem(&output.bytes).unwrap(); let catalog = pdf.catalog().unwrap(); let page_ids = pdf.get_pages(); let open = catalog.get(b"OpenAction").unwrap().as_array().unwrap(); assert_eq!(open[0].as_reference().unwrap(), page_ids[&2]); assert_eq!(open[1].as_name().unwrap(), b"Fit"); assert!(!catalog.has(b"Discard")); let preferences = catalog.get(b"ViewerPreferences").unwrap().as_dict().unwrap(); assert!(matches!(preferences.get(b"HideToolbar"), Ok(lopdf::Object::Boolean(true)))); assert!(matches!(preferences.get(b"DisplayDocTitle"), Ok(lopdf::Object::Boolean(true)))); let dictionary = |parent: &lopdf::Dictionary, key: &[u8]| { let id = parent.get(key).unwrap().as_reference().unwrap(); pdf.get_object(id).unwrap().as_dict().unwrap() }; let outlines = dictionary(catalog, b"Outlines"); assert_eq!(outlines.get(b"Count").unwrap().as_i64().unwrap(), 2); let first = dictionary(outlines, b"First"); assert_eq!(first.get(b"Title").unwrap().as_str().unwrap(), [254, 255, 0, 65, 3, 169]); assert_eq!(first.get(b"Count").unwrap().as_i64().unwrap(), -1); let remapped = first.get(b"A").unwrap().as_dict().unwrap().get(b"D").unwrap(); let child = dictionary(first, b"First"); let previous = child.get(b"Dest").unwrap().as_array().unwrap(); assert_eq!(previous[0].as_reference().unwrap(), page_ids[&1]); let sibling = dictionary(first, b"Next"); assert_eq!(sibling.get(b"Title").unwrap().as_str().unwrap(), b"Sibling"); let names = catalog.get(b"Names").unwrap().as_dict().unwrap(); let names = dictionary(names, b"Dests").get(b"Names").unwrap().as_array().unwrap(); assert_eq!(names.len(), 2); assert_eq!(names[0].as_str().unwrap(), b"0"); assert_eq!(remapped.as_str().unwrap(), names[0].as_str().unwrap()); assert_eq!(names[1].as_array().unwrap()[0].as_reference().unwrap(), page_ids[&2]); }