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 opentype_design_and_scaled_requests_share_actual_sized_instances() { use sha2::{Digest, Sha256}; use std::{fs, path::PathBuf, process::Command}; use texrra_tex_core::resources::{LoadedResource, ResourceKind, ResourceVersion}; struct PhysicalFont(LoadedResource); impl SourceProvider for PhysicalFont { fn read(&mut self, name: &str, _: &str) -> Result { Err(format!("unexpected input {name}")) } fn resource(&mut self, kind: ResourceKind, name: &str, _: &str) -> Result { assert_eq!((kind, name), (ResourceKind::OpenType, "lmroman10-regular.otf")); Ok(LoadedResource { version: self.0.version.clone(), data: self.0.data.clone() }) } } let font = Command::new("kpsewhich").arg("lmroman10-regular.otf").output().unwrap(); assert!(font.status.success(), "missing reference OpenType resource"); let path = PathBuf::from(String::from_utf8(font.stdout).unwrap().trim()); let data = fs::read(&path).unwrap(); let mut provider = PhysicalFont(LoadedResource { version: ResourceVersion { path, sha256: format!("{:x}", Sha256::digest(&data)), bytes: data.len() as u64, }, data, }); let result = Executor::new( State::initex().with_etex().with_input_profile(InputProfile::XeTeX), Limits::default(), ) .run( source(r#"\catcode123=1 \catcode125=2 \font\design="[lmroman10-regular.otf]" \font\same="[lmroman10-regular.otf]" scaled1000 \font\exact="[lmroman10-regular.otf]" at657818sp \font\scaled="[lmroman10-regular.otf]" scaled737 \font\explicit="[lmroman10-regular.otf]" at10pt \message{\number\fontdimen6\design/\number\fontdimen6\scaled/\number\fontdimen6\explicit} \message{\ifx\design\same SAME\fi/\ifx\design\exact SAME\fi/\ifx\design\explicit SAME\else DIFFERENT\fi} \end"#), &mut provider, ) .unwrap(); assert_eq!(messages(&result), ["657818/484811/655360", "SAME/SAME/DIFFERENT"]); } #[test] fn named_optical_lookup_reconsiders_new_faces_and_tracks_compared_resources() { use std::{fs, process::Command, sync::Arc}; use texrra_tex_core::resources::{ FileWorld, FontStyle, ProjectDefinition, ProjectSnapshot, ResourceKind, SearchPath, WorldConfig, }; let root = std::env::temp_dir().canonicalize().unwrap().join("texrra-optical-catalogue"); let load = |name: &str| { let found = Command::new("kpsewhich").arg(name).output().unwrap(); assert!(found.status.success(), "missing reference font {name}"); Arc::<[u8]>::from(fs::read(String::from_utf8(found.stdout).unwrap().trim()).unwrap()) }; let base = root.join("lmroman10-regular.otf"); let distant = root.join("lmroman17-regular.otf"); let covering = root.join("lmroman12-regular.otf"); let mut configuration = WorldConfig::new(&root); configuration.paths.insert(ResourceKind::OpenType, vec![SearchPath::directory(&root, false)]); let project = ProjectSnapshot::new(ProjectDefinition { configuration, revision: 1, roots: [root.clone()].into(), files: [ (base.clone(), load("lmroman10-regular.otf")), (distant.clone(), load("lmroman17-regular.otf")), ].into(), directories: Default::default(), aliases: Default::default(), generated_roots: Default::default(), generated: Default::default(), }).unwrap(); let with_covering = project.with_file_changes( 2, [(covering.clone(), Some(load("lmroman12-regular.otf")))].into(), ).unwrap(); for (snapshot, expected, compared) in [ (project, &base, &distant), (with_covering, &covering, &covering), ] { let mut world = FileWorld::from_project(snapshot.clone()).unwrap(); let font = world.read_named_font_with_size( "LMRoman10-Regular", FontStyle::default(), Some(12.5), &root.join("main.tex"), ).unwrap().unwrap(); assert_eq!(&font.resource.version.path, expected); assert_eq!(world.trace().reads, [ snapshot.file(&base).unwrap().version.clone(), snapshot.file(compared).unwrap().version.clone(), ]); } } #[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]); } #[test] fn xdv_root_annotation_keeps_its_extent_and_destination_across_shipouts() { use lopdf::{Document, Object}; 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 \shipout\hbox{\special{pdf:bann<>} \special{pdf:xann width 10pt height 7pt depth 1pt} \vrule width30pt height12pt depth0pt} \shipout\hbox{\kern20pt \special{pdf:extendann width 11pt height 8pt depth 2pt} \special{pdf:eann} \special{pdf:outline 1<>} \special{pdf:dest (topic) [@thispage/Fit]} \special{pdf:dest (chapter) [@prevpage/Fit]} \vrule width10pt height8pt depth0pt} \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_ids = pdf.get_pages(); let first = pdf.get_object(page_ids[&1]).unwrap().as_dict().unwrap(); assert!(!first.has(b"Annots")); let second = pdf.get_object(page_ids[&2]).unwrap().as_dict().unwrap(); let annotations = second.get(b"Annots").unwrap().as_array().unwrap(); assert_eq!(annotations.len(), 1); let annotation = pdf .get_object(annotations[0].as_reference().unwrap()) .unwrap() .as_dict() .unwrap(); assert_eq!(annotation.get(b"Dest").unwrap().as_str().unwrap(), b"0"); let rectangle = annotation.get(b"Rect").unwrap().as_array().unwrap(); let coordinate = |index| match &rectangle[index] { Object::Integer(value) => *value as f64, Object::Real(value) => *value, _ => panic!("expected physical annotation coordinate"), }; assert_eq!(coordinate(0), 72.0); assert_eq!(coordinate(2), 102.884); let names = pdf.catalog().unwrap().get(b"Names").unwrap().as_dict().unwrap(); let names = pdf.get_object(names.get(b"Dests").unwrap().as_reference().unwrap()) .unwrap().as_dict().unwrap().get(b"Names").unwrap().as_array().unwrap(); assert_eq!(names[0].as_str().unwrap(), b"0"); assert_eq!(names[1].as_array().unwrap()[0].as_reference().unwrap(), page_ids[&2]); assert_eq!(names[2].as_str().unwrap(), b"1"); assert_eq!(names[3].as_array().unwrap()[0].as_reference().unwrap(), page_ids[&1]); } #[test] fn xdv_named_objects_keep_forward_edges_and_file_streams_at_shipout() { use lopdf::{Document, Object}; use texrra_tex_core::pdf::shipout_lists_to_native_pdf_document; use texrra_tex_core::resources::{LoadedResource, ResourceKind, ResourceVersion}; struct Device; impl SourceProvider for Device { fn read(&mut self, name: &str, _: &str) -> Result { Err(format!("unexpected input {name}")) } fn default_pk_resolution(&mut self) -> Result { Ok(600) } fn resource(&mut self, kind: ResourceKind, name: &str, from: &str) -> Result { assert_eq!((kind, name, from), (ResourceKind::PdfImage, "object.bin", "profile.tex")); Ok(LoadedResource { version: ResourceVersion { path: name.into(), bytes: 3, sha256: "5240672d7b51756b829ad0ef8d9468b7a078afa2f410484fd3892dab47becb72".into(), }, data: vec![0, 128, 255], }) } } 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:obj @discarded << /bad true >>}} \shipout\hbox{ \special{pdf:put @catalog << /Data @root /Missing @missing >>} \special{pdf:object @root << /Self @root /Page @nextpage /Items @items >>} \special{pdf:obj @items [1]} \special{pdf:put @items 2 @binary} \special{pdf:fstream @binary (object.bin) << /Tag /First >>} \special{pdf:put @binary << /Tag /Final >>} \special{pdf:close @root} \vrule width7pt height8pt} \shipout\hbox{ \special{pdf:put @catalog << /Same @root >>} \vrule width9pt height8pt} \end", ), &mut Device, ) .unwrap(); assert!(result.reads.contains(&Dependency::FileLookup { name: "object.bin".to_owned(), from: "profile.tex".to_owned(), })); let pages = result.shipout_display_lists().unwrap(); let output = shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap(); assert!(output.diagnostics.iter().any(|warning| warning.contains("Object @missing used, but not defined"))); let pdf = Document::load_mem(&output.bytes).unwrap(); let catalog = pdf.catalog().unwrap(); let id = catalog.get(b"Data").unwrap().as_reference().unwrap(); assert_eq!(catalog.get(b"Same").unwrap().as_reference().unwrap(), id); let root = pdf.get_object(id).unwrap().as_dict().unwrap(); assert_eq!(root.get(b"Self").unwrap().as_reference().unwrap(), id); assert_eq!(root.get(b"Page").unwrap().as_reference().unwrap(), pdf.get_pages()[&2]); let items = pdf.get_object(root.get(b"Items").unwrap().as_reference().unwrap()).unwrap().as_array().unwrap(); assert_eq!(items[0].as_i64().unwrap(), 1); assert_eq!(items[1].as_i64().unwrap(), 2); let stream = pdf.get_object(items[2].as_reference().unwrap()).unwrap().as_stream().unwrap(); assert_eq!(stream.dict.get(b"Tag").unwrap().as_name().unwrap(), b"Final"); let bytes = if stream.dict.has(b"Filter") { stream.decompressed_content().unwrap() } else { stream.content.clone() }; assert_eq!(bytes, [0, 128, 255]); let missing = catalog.get(b"Missing").unwrap().as_reference().unwrap(); assert!(matches!(pdf.get_object(missing), Ok(Object::Null))); assert!(!output.bytes.windows(4).any(|window| window == b"/bad")); } #[test] fn xdv_page_dictionaries_and_rectangular_destinations_keep_real_references() { 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 \shipout\hbox{ \special{dvipdfmx:config C 0x10} \special{pdf:put @pages << /Feature @later /Count 22 >>} \special{pdf:put @thispage << /Rotate 90 /CropBox @rect /Type /Other >>} \special{pdf:dest (area) [@thispage /FitR @left 20 300 @upper]} \vrule width7pt height8pt} \shipout\hbox{ \special{pdf:obj @rect [10 20 300 400]} \special{pdf:obj @later << /Page @thispage >>} \special{pdf:obj @left 10} \special{pdf:obj @upper 400} \vrule width9pt height8pt} \end", ), &mut TestDevice, ) .unwrap(); let pages = result.shipout_display_lists().unwrap(); let svg = pages[0].try_to_svg().unwrap(); assert!(svg.contains("width=\"380.000pt\" height=\"290.000pt\""), "{svg}"); let page2_svg = pages[1].try_to_svg().unwrap(); assert!(page2_svg.contains("width=\"612.000pt\" height=\"792.000pt\"")); let output = shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap(); let pdf = Document::load_mem(&output.bytes).unwrap(); let resolve = |object: &lopdf::Object| pdf.get_object(object.as_reference().unwrap()).unwrap(); let ids = pdf.get_pages(); let catalog = pdf.catalog().unwrap(); let root = resolve(catalog.get(b"Pages").unwrap()).as_dict().unwrap(); assert_eq!(root.get(b"Count").unwrap().as_i64().unwrap(), 2); let feature = resolve(root.get(b"Feature").unwrap()).as_dict().unwrap(); assert_eq!(feature.get(b"Page").unwrap().as_reference().unwrap(), ids[&2]); let page = pdf.get_object(ids[&1]).unwrap().as_dict().unwrap(); assert_eq!(page.get(b"Type").unwrap().as_name().unwrap(), b"Page"); assert!(page.get(b"CropBox").unwrap().as_reference().is_ok()); let names = catalog.get(b"Names").unwrap().as_dict().unwrap(); let destinations = resolve(names.get(b"Dests").unwrap()).as_dict().unwrap(); let names = destinations.get(b"Names").unwrap().as_array().unwrap(); let area = names[1].as_array().unwrap(); assert_eq!(area[0].as_reference().unwrap(), ids[&1]); assert_eq!(area[1].as_name().unwrap(), b"FitR"); assert_eq!(resolve(&area[2]).as_i64().unwrap(), 10); assert_eq!(resolve(&area[5]).as_i64().unwrap(), 400); } #[test] fn xdv_scoped_code_uses_shared_resource_categories_and_page_defaults() { use lopdf::{Document, Object, content::Content}; 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 \shipout\hbox{% \special{pdf:obj @shared << >>}% \special{pdf:obj @soft << /ca 0.25 >>}% \special{pdf:put @resources << /ExtGState << /Half << /ca 0.5 >> >> >>}% \special{pdf:put @resources << /ExtGState @shared >>}% \special{pdf:pageresources << /ExtGState << /Soft @soft >> >>}% \special{pdf:bcontent}% \special{pdf:code q /Half gs}% \kern10pt\special{pdf:code 0 0 10 10 re f Q}% \special{pdf:econtent}% \vrule width15pt height1pt} \shipout\hbox{% \special{pdf:put @resources << /ExtGState @shared >>}% \special{pdf:put @shared << /Late << /ca 0.75 >> >>}% \vrule width20pt height1pt} \shipout\hbox{% \special{pdf:pageresources << >>}% \vrule width25pt height1pt} \end", ), &mut TestDevice, ) .unwrap(); let pages = result.shipout_display_lists().unwrap(); assert!(pages[0].has_embedded_pdf()); assert!(pages[1].has_embedded_pdf()); assert!(!pages[2].has_embedded_pdf()); let output = shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap(); let pdf = Document::load_mem(&output.bytes).unwrap(); let ids = pdf.get_pages(); let resources = |id| pdf.get_object(id).unwrap().as_dict().unwrap() .get(b"Resources").unwrap().as_dict().unwrap(); let shared = resources(ids[&1]).get(b"ExtGState").unwrap().as_reference().unwrap(); assert_eq!(resources(ids[&2]).get(b"ExtGState").unwrap().as_reference().unwrap(), shared); assert!(!resources(ids[&3]).has(b"ExtGState")); let fields = pdf.get_object(shared).unwrap().as_dict().unwrap(); assert!(fields.has(b"Half") && fields.has(b"Soft") && fields.has(b"Late")); let operations = Content::decode(&pdf.get_page_content(ids[&1]).unwrap()).unwrap().operations; let style = operations.iter().position(|op| op.operator == "gs").unwrap(); assert!(matches!(&operations[style].operands[..], [Object::Name(name)] if name == b"Half")); assert_eq!(operations[style + 1].operator, "re"); assert_eq!(operations[style + 2].operator, "f"); } #[test] fn xdv_form_capture_isolated_and_reused_as_one_indirect_object() { use lopdf::Document; use texrra_tex_core::{pdf::shipout_lists_to_native_pdf_document, render::DisplayItem}; 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 \shipout\hbox{% \special{pdf:bxobj @box width 30pt height 20pt}% \special{pdf:put @resources << /ExtGState << /A << /ca 0.5 >> >> >>}% \special{pdf:bcontent}\special{pdf:code q /A gs 0 0 10 10 re f Q}% \special{pdf:econtent}% \hbox to0pt{\vrule width5pt height7pt\hss}% \special{pdf:exobj << /Group << /S /Transparency >> >>}% \special{pdf:put @catalog << /Captured @box >>}% \special{pdf:uxobj @box}} \shipout\hbox{\kern20pt\special{pdf:usexobj @box}} \end"), &mut TestDevice, ) .unwrap(); let pages = result.shipout_display_lists().unwrap(); assert_eq!(pages[0].forms.len(), 1); assert!(pages[0].forms[0].list.items.iter().any(|item| matches!(item, DisplayItem::Rule { .. }))); assert!(!pages[0].items.iter().any(|item| matches!(item, DisplayItem::Rule { .. }))); let output = shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap(); let pdf = Document::load_mem(&output.bytes).unwrap(); let object = |page| pdf.get_object(page).unwrap().as_dict().unwrap() .get(b"Resources").unwrap().as_dict().unwrap() .get(b"XObject").unwrap().as_dict().unwrap() .get(b"Fm1").unwrap().as_reference().unwrap(); let ids = pdf.get_pages(); let form = object(ids[&1]); assert_eq!(object(ids[&2]), form); assert_eq!(pdf.catalog().unwrap().get(b"Captured").unwrap().as_reference().unwrap(), form); let stream = pdf.get_object(form).unwrap().as_stream().unwrap(); assert_eq!(stream.dict.get(b"Subtype").unwrap().as_name().unwrap(), b"Form"); let resources = stream.dict.get(b"Resources").unwrap().as_dict().unwrap(); assert!(resources.get(b"ExtGState").unwrap().as_dict().unwrap().has(b"A")); assert!(stream.dict.get(b"Group").unwrap().as_dict().unwrap().has(b"S")); } #[test] fn xdv_form_placement_respects_definition_order_and_crop() { use lopdf::{Document, Object, content::Content}; 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 \shipout\hbox{% \special{pdf:uxobj @inner bbox 2 1 12 11 width 30bp height 20bp}% \special{pdf:bxobj @outer bbox 0 -4 80 35}% \special{pdf:bxobj @inner width 20bp height 12bp depth 2bp}% \hbox to0pt{\vrule width19pt height11pt\hfil}% \special{pdf:exobj}% \kern8pt\special{pdf:uxobj @inner width 35bp height 18bp depth 2bp}% \special{pdf:exobj}% \special{pdf:uxobj @outer}} \shipout\hbox{% \special{pdf:uxobj @inner bbox 2 1 12 11 width 30bp height 20bp}% \kern40pt\special{pdf:uxobj @inner bbox 2 1 12 11 matrix 1 .25 -.2 1 4 3 clip 0}} \shipout\hbox{% \kern20pt\special{pdf:bcontent}% \kern10pt\special{pdf:bxobj @local width 40bp height 20bp depth 2bp}% \special{pdf:code 0 0 1 rg 12 1 7 9 re f}% \hbox to0pt{\vrule width30pt height7pt\hss}% \special{pdf:exobj}% \kern75pt\special{pdf:uxobj @local width 50bp height 23bp depth 2bp}% \special{pdf:econtent}} \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 ids = pdf.get_pages(); let page = |id| Content::decode(&pdf.get_page_content(id).unwrap()).unwrap().operations; let first = page(ids[&1]); let second = page(ids[&2]); let numeric = |values: &[Object]| -> Vec { values.iter().map(|value| value.as_i64().map(|n| n as f64).or_else(|_| value.as_f64()).unwrap()).collect() }; let matrices = |operations: &[lopdf::content::Operation]| -> Vec> { operations.iter().filter(|op| op.operator == "cm") .map(|op| numeric(&op.operands)).collect() }; assert_eq!(&matrices(&first)[1][..4], &[1.0, 0.0, 0.0, 1.0]); assert_eq!(numeric(&first.iter().find(|op| op.operator == "re").unwrap().operands), [2.0, 1.0, 10.0, 10.0]); assert_eq!(&matrices(&second)[1][..4], &[3.0, 0.0, 0.0, 2.0]); assert_eq!(&matrices(&second)[2][..4], &[1.0, 0.25, -0.2, 1.0]); assert_eq!(second.iter().filter(|op| op.operator == "W").count(), 1); let local = page(ids[&3]); assert_eq!(matrices(&local)[2], [1.25, 0.0, 0.0, 1.13636, 84.682, -2.0]); let outer = pdf.objects.values().filter_map(|value| value.as_stream().ok()).find(|stream| { stream.dict.get(b"Resources").and_then(Object::as_dict) .and_then(|resources| resources.get(b"XObject")).is_ok() }).unwrap(); let contents = outer.decompressed_content().unwrap(); let operations = Content::decode(&contents).unwrap().operations; assert_eq!(&matrices(&operations)[0][..4], &[1.75, 0.0, 0.0, 0.80132]); } #[test] fn xdv_imported_image_matches_forward_catalog_and_page_references() { use lopdf::{Document, Object, Stream, dictionary}; use sha2::{Digest, Sha256}; use texrra_tex_core::{ pdf::shipout_lists_to_native_pdf_document, resources::{LoadedResource, ResourceKind, ResourceVersion}, }; struct ImageDevice(LoadedResource); impl SourceProvider for ImageDevice { fn read(&mut self, name: &str, from: &str) -> Result { TestDevice.read(name, from) } fn default_pk_resolution(&mut self) -> Result { TestDevice.default_pk_resolution() } fn resource(&mut self, kind: ResourceKind, name: &str, _: &str) -> Result { assert_eq!((kind, name), (ResourceKind::PdfImage, "drawing.pdf")); Ok(LoadedResource { version: self.0.version.clone(), data: self.0.data.clone() }) } } let mut drawing = Document::with_version("1.5"); let pages = drawing.new_object_id(); let stream = drawing.add_object(Stream::new(dictionary! {}, b"1 0 0 rg 0 0 18 20 re f".to_vec())); let page = drawing.add_object(dictionary! { "Type" => "Page", "Parent" => pages, "Contents" => stream }); drawing.objects.insert(pages, Object::Dictionary(dictionary! { "Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1, "MediaBox" => vec![0.into(), 0.into(), 18.into(), 20.into()], "Resources" => dictionary! {}, })); let root = drawing.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages }); drawing.trailer.set("Root", root); let mut bytes = Vec::new(); drawing.save_to(&mut bytes).unwrap(); let mut device = ImageDevice(LoadedResource { version: ResourceVersion { path: "drawing.pdf".into(), sha256: format!("{:x}", Sha256::digest(&bytes)), bytes: bytes.len() as u64, }, data: bytes, }); 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 \shipout\hbox{% \special{pdf:bann << /Subtype /Link /A << /S /URI /URI (https://example.org/before) >> >>}% \special{pdf:uxobj @Sheet}\special{pdf:eann}% \special{pdf:put @catalog << /Sheet @Sheet >>}} \shipout\hbox{\special{pdf:epdf @Sheet pagebox mediabox hide (drawing.pdf) << /Stamp @Tag >>}% \special{pdf:obj @Tag (proof)}% \special{pdf:bann << /Subtype /Link /A << /S /URI /URI (https://example.org/after) >> >>}% \special{pdf:usexobj @Sheet width 36bp}\special{pdf:eann}} \end"), &mut device, ).unwrap(); let pages = result.shipout_display_lists().unwrap(); let pdf = shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap(); let pdf = Document::load_mem(&pdf.bytes).unwrap(); let reference = pdf.catalog().unwrap().get(b"Sheet").unwrap().as_reference().unwrap(); for (index, id) in pdf.get_pages() { let page = pdf.get_dictionary(id).unwrap(); let xobjects = page.get(b"Resources").unwrap().as_dict().unwrap() .get(b"XObject").unwrap().as_dict().unwrap(); assert_eq!(xobjects.len(), 1); assert_eq!(xobjects.iter().next().unwrap().1.as_reference().unwrap(), reference); let entries = page.get(b"Annots").unwrap().as_array().unwrap(); assert_eq!(entries.len(), 1); let link = pdf.get_dictionary(entries[0].as_reference().unwrap()).unwrap(); let rect: Vec<_> = link.get(b"Rect").unwrap().as_array().unwrap().iter() .map(|value| value.as_i64().map(|n| n as f64).or_else(|_| value.as_f64()).unwrap()).collect(); let expected = if index == 1 { [72.0, 720.0, 73.0, 721.0] } else { [72.0, 720.0, 108.0, 760.0] }; assert_eq!(rect, expected); } let form = pdf.get_object(reference).unwrap().as_stream().unwrap(); let stamp = form.dict.get(b"Stamp").unwrap().as_reference().unwrap(); assert_eq!(pdf.get_object(stamp).unwrap().as_str().unwrap(), b"proof"); assert_eq!(form.dict.get(b"Subtype").unwrap().as_name().unwrap(), b"Form"); } #[test] fn xdv_name_trees_keep_binary_keys_and_share_the_catalog_root() { use lopdf::{Document, Object}; 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 \shipout\hbox{% \special{pdf:put @catalog << /Copy @names >>}% \special{pdf:put @names << /Pages << /Names [(page) @nextpage] >> >>}% \special{pdf:dest (mixed) [@thispage /FitH 55]}% \special{pdf:names /Dests [(manual) [@nextpage /Fit] (mixed) [@nextpage /Fit] (unreached) [@nextpage /Fit]]}% \special{pdf:ann width 5pt height 2pt << /Subtype /Link /Dest (manual) >>}% \special{pdf:ann width 5pt height 2pt << /Subtype /Link /Dest (mixed) >>}% \special{pdf:names /IDS [ 9 (b) 8 (a) 7 <6100> 6 (c) 5 (d) 4 (e) 3 (f) 2 <00> 1]}% \special{pdf:names /AP (first) @leaf}% \vrule width5pt height3pt} \shipout\hbox{\special{pdf:obj @leaf << /Proof (shared) >>}\vrule width5pt height3pt} \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 resolve = |value: &Object| pdf.get_object(value.as_reference().unwrap()).unwrap(); let id = pdf.catalog().unwrap().get(b"Names").unwrap().as_reference().unwrap(); assert_eq!(pdf.catalog().unwrap().get(b"Copy").unwrap().as_reference().unwrap(), id); let root = pdf.get_dictionary(id).unwrap(); let ids = resolve(root.get(b"IDS").unwrap()).as_dict().unwrap(); assert!(!ids.has(b"Limits")); let children = ids.get(b"Kids").unwrap().as_array().unwrap(); let keys: Vec<_> = children.iter().flat_map(|child| { let node = resolve(child).as_dict().unwrap(); let values = node.get(b"Names").unwrap().as_array().unwrap(); let limits = node.get(b"Limits").unwrap().as_array().unwrap(); assert_eq!(limits[0].as_str().unwrap(), values[0].as_str().unwrap()); assert_eq!(limits[1].as_str().unwrap(), values[values.len()-2].as_str().unwrap()); values.iter().step_by(2).map(|key| key.as_str().unwrap().to_vec()) }).collect(); assert_eq!(keys, [b"\0".as_slice(), b"a", b"a\0", b"b", b"c", b"d", b"e", b"f", b"\xff"]); let pages = pdf.get_pages(); let dests = resolve(root.get(b"Dests").unwrap()).as_dict().unwrap() .get(b"Names").unwrap().as_array().unwrap(); assert_eq!(dests.len(), 4); assert_eq!(resolve(&dests[1]).as_array().unwrap()[0].as_reference().unwrap(), pages[&2]); assert_eq!(resolve(&dests[3]).as_array().unwrap()[0].as_reference().unwrap(), pages[&1]); let ap = resolve(root.get(b"AP").unwrap()).as_dict().unwrap() .get(b"Names").unwrap().as_array().unwrap(); assert_eq!(resolve(&ap[1]).as_dict().unwrap().get(b"Proof").unwrap().as_str().unwrap(), b"shared"); assert!(output.diagnostics.iter().any(|message| message.contains("Object @mixed already defined."))); } #[test] fn xdv_font_map_changes_apply_at_shipout_and_keep_loaded_programs() { use sha2::{Digest, Sha256}; use std::path::PathBuf; use texrra_tex_core::native_font::resolve_native_fonts; use texrra_tex_core::render::DisplayItem; use texrra_tex_core::resources::{LoadedResource, ResourceKind, ResourceVersion}; fn loaded(path: PathBuf, data: Vec) -> LoadedResource { let sha256 = format!("{:x}", Sha256::digest(&data)); LoadedResource { version: ResourceVersion { path, sha256, bytes: data.len() as u64 }, data } } struct Fonts { metric: Vec, roman: LoadedResource, italic: LoadedResource, } impl SourceProvider for Fonts { fn read(&mut self, name: &str, _: &str) -> Result { Err(format!("unexpected input {name}")) } fn default_pk_resolution(&mut self) -> Result { Ok(600) } fn resource(&mut self, kind: ResourceKind, name: &str, _: &str) -> Result { match (kind, name) { (ResourceKind::Tfm, "mapped.tfm" | "transformed.tfm" | "later.tfm") => { Ok(loaded(PathBuf::from(name), self.metric.clone())) } (ResourceKind::Type1, "cmr10.pfb") => Ok(LoadedResource { version: self.roman.version.clone(), data: self.roman.data.clone() }), (ResourceKind::Type1, "cmti10.pfb") => Ok(LoadedResource { version: self.italic.version.clone(), data: self.italic.data.clone() }), _ => Err(format!("unexpected font resource {kind:?} {name}")), } } fn optional_font_map(&mut self, name: &str, _: &str) -> Result, String> { Ok((name == "local.map").then(|| loaded( name.into(), b"mapped CMTI10 > = pages.iter().map(|page| { page.items.iter().filter_map(|item| match item { DisplayItem::NativeGlyph { paint: Some(paint), .. } => Some(paint.program.name()), _ => None, }).collect() }).collect(); assert_eq!(programs, [vec!["CMR10"], vec!["CMR10", "CMTI10"], vec!["CMR10"]]); assert!(pages[2].try_to_svg().unwrap().contains("matrix(0.01200000 0 0.00180000 -0.01000000")); }