oxedyne/fe2o3/fe2o3_austenite/tests/pdf_info.rs
22.1 KiB, 1 run
created by r1870400018:62389, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! The PDF Info dictionary, read back from the file by `pdfinfo` and held against Typst's own for the same |
| 2 | //! source: `Title`, `Author`, `Subject` and `Keywords` from the document's `#set document(...)`, and |
| 3 | //! `Creator` and `Producer` naming the engine. Compiled through `compile::emit_pdf`, the emit both the |
| 4 | //! wasm surface and the native binary call. |
| 5 | |
| 6 | use oxedyne_fe2o3_austenite::compile; |
| 7 | use oxedyne_fe2o3_austenite::fonts; |
| 8 | use oxedyne_fe2o3_austenite::vfs; |
| 9 | |
| 10 | use oxedyne_fe2o3_core::prelude::*; |
| 11 | |
| 12 | use std::collections::BTreeMap; |
| 13 | use std::collections::HashMap; |
| 14 | use std::path::{ |
| 15 | Path, |
| 16 | PathBuf, |
| 17 | }; |
| 18 | use std::process::Command; |
| 19 | use std::sync::{ |
| 20 | Arc, |
| 21 | Mutex, |
| 22 | }; |
| 23 | |
| 24 | // The source map is a process-wide global, so the cases take turns. |
| 25 | static VFS: Mutex<()> = Mutex::new(()); |
| 26 | |
| 27 | const METADATA: [&str; 4] = ["Title", "Author", "Subject", "Keywords"]; |
| 28 | |
| 29 | fn compile_pdf(src: &str) -> Outcome<Vec<u8>> { |
| 30 | let _turn = VFS.lock().unwrap_or_else(|p| p.into_inner()); |
| 31 | let main = PathBuf::from("/doc/main.typ"); |
| 32 | let mut files: HashMap<PathBuf, Vec<u8>> = HashMap::new(); |
| 33 | files.insert(main.clone(), src.as_bytes().to_vec()); |
| 34 | res!(vfs::install(files)); |
| 35 | let set = Arc::new(res!(fonts::libertinus())); |
| 36 | let result = compile::assemble(&main, || Ok(set.clone())) |
| 37 | .and_then(compile::author_and_run); |
| 38 | let _ = vfs::clear(); |
| 39 | let rendered = res!(result); |
| 40 | let mut out = rendered.out; |
| 41 | compile::emit_pdf(&mut out, &rendered.heads, &rendered.doc_info) |
| 42 | } |
| 43 | |
| 44 | /// Compiles a project of several sources, rooted at the first, as `compile_pdf` compiles a lone one. |
| 45 | fn compile_project(files: &[(&str, &str)]) -> Outcome<Vec<u8>> { |
| 46 | let _turn = VFS.lock().unwrap_or_else(|p| p.into_inner()); |
| 47 | let main = match files.first() { |
| 48 | Some((path, _)) => PathBuf::from(path), |
| 49 | None => return Err(err!("A project needs a root source."; Test, Missing)), |
| 50 | }; |
| 51 | let mut map: HashMap<PathBuf, Vec<u8>> = HashMap::new(); |
| 52 | for (path, text) in files { |
| 53 | map.insert(PathBuf::from(path), text.as_bytes().to_vec()); |
| 54 | } |
| 55 | res!(vfs::install(map)); |
| 56 | let set = Arc::new(res!(fonts::libertinus())); |
| 57 | let result = compile::assemble(&main, || Ok(set.clone())) |
| 58 | .and_then(compile::author_and_run); |
| 59 | let _ = vfs::clear(); |
| 60 | let rendered = res!(result); |
| 61 | let mut out = rendered.out; |
| 62 | compile::emit_pdf(&mut out, &rendered.heads, &rendered.doc_info) |
| 63 | } |
| 64 | |
| 65 | /// Typst's own Info fields for the project `files`, written by their file names into a scratch directory |
| 66 | /// of their own and compiled from the first, or `None` when no `typst` is installed to ask. |
| 67 | fn typst_project_info(files: &[(&str, &str)], name: &str) -> Outcome<Option<BTreeMap<String, String>>> { |
| 68 | let dir = scratch(&fmt!("pdf_info_{}", name)); |
| 69 | res!(std::fs::create_dir_all(&dir)); |
| 70 | let mut root: Option<PathBuf> = None; |
| 71 | for (path, text) in files { |
| 72 | let file = match Path::new(path).file_name() { |
| 73 | Some(f) => dir.join(f), |
| 74 | None => return Err(err!("{:?} names no file.", path; Test, Invalid)), |
| 75 | }; |
| 76 | res!(std::fs::write(&file, text)); |
| 77 | root.get_or_insert(file); |
| 78 | } |
| 79 | let root = match root { |
| 80 | Some(r) => r, |
| 81 | None => return Err(err!("A project needs a root source."; Test, Missing)), |
| 82 | }; |
| 83 | let pdf = dir.join("typst.pdf"); |
| 84 | let out = match Command::new("typst").arg("compile").arg(&root).arg(&pdf).output() { |
| 85 | Ok(o) => o, |
| 86 | Err(_) => { |
| 87 | eprintln!("SKIP: `typst` is not installed, so {} is not compared with it.", name); |
| 88 | return Ok(None); |
| 89 | }, |
| 90 | }; |
| 91 | if !out.status.success() { |
| 92 | return Err(err!("typst refused {}: {}", name, String::from_utf8_lossy(&out.stderr); Test)); |
| 93 | } |
| 94 | Ok(Some(res!(info_of(&pdf)))) |
| 95 | } |
| 96 | |
| 97 | fn scratch(name: &str) -> PathBuf { |
| 98 | PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(name) |
| 99 | } |
| 100 | |
| 101 | /// The Info fields `pdfinfo` reads from a PDF, by key. |
| 102 | fn info_of(pdf: &Path) -> Outcome<BTreeMap<String, String>> { |
| 103 | let out = res!(Command::new("pdfinfo").arg(pdf).output()); |
| 104 | if !out.status.success() { |
| 105 | return Err(err!("pdfinfo could not read {:?}: {}", pdf, String::from_utf8_lossy(&out.stderr); Test)); |
| 106 | } |
| 107 | let mut fields = BTreeMap::new(); |
| 108 | for line in res!(String::from_utf8(out.stdout)).lines() { |
| 109 | if let Some((key, value)) = line.split_once(':') { |
| 110 | if METADATA.contains(&key) || key == "Creator" || key == "Producer" { |
| 111 | fields.insert(key.to_string(), value.trim().to_string()); |
| 112 | } |
| 113 | } |
| 114 | } |
| 115 | Ok(fields) |
| 116 | } |
| 117 | |
| 118 | /// Typst's own Info fields for `src`, or `None` when no `typst` is installed to ask. |
| 119 | fn typst_info(src: &str, name: &str) -> Outcome<Option<BTreeMap<String, String>>> { |
| 120 | let typ = scratch(&fmt!("pdf_info_{}.typ", name)); |
| 121 | let pdf = scratch(&fmt!("pdf_info_{}_typst.pdf", name)); |
| 122 | res!(std::fs::write(&typ, src)); |
| 123 | let out = match Command::new("typst").arg("compile").arg(&typ).arg(&pdf).output() { |
| 124 | Ok(o) => o, |
| 125 | Err(_) => { |
| 126 | eprintln!("SKIP: `typst` is not installed, so {} is not compared with it.", name); |
| 127 | return Ok(None); |
| 128 | }, |
| 129 | }; |
| 130 | if !out.status.success() { |
| 131 | return Err(err!("typst refused {}: {}", name, String::from_utf8_lossy(&out.stderr); Test)); |
| 132 | } |
| 133 | Ok(Some(res!(info_of(&pdf)))) |
| 134 | } |
| 135 | |
| 136 | #[test] |
| 137 | fn the_info_dictionary_is_typsts_for_the_same_source() -> Outcome<()> { |
| 138 | let cases = [ |
| 139 | ("all", "#set document(\n title: \"A Title\",\n author: (\"Ann Author\", \"Bob\"),\n \ |
| 140 | description: \"A subject line\",\n keywords: (\"one\", \"two\"),\n)\n\n= Heading\n\nBody words.\n"), |
| 141 | ("content", "#set document(title: [A *bold* Title], \ |
| 142 | description: \"\\u{dc}n\\u{ef}c\\u{f6}d\\u{e9} \\\"quoted\\\"\", author: \"Solo\")\n\n= Heading\n\nBody.\n"), |
| 143 | ("override", "#set document(title: \"One\", keywords: \"k\")\n#set document(title: \"Two\")\n\n= H\n\nBody.\n"), |
| 144 | ("none", "= Heading\n\nBody words.\n"), |
| 145 | ]; |
| 146 | for (name, src) in cases { |
| 147 | let pdf = scratch(&fmt!("pdf_info_{}.pdf", name)); |
| 148 | res!(std::fs::write(&pdf, res!(compile_pdf(src)))); |
| 149 | let ours = res!(info_of(&pdf)); |
| 150 | assert_eq!(ours.get("Creator").map(|s| s.as_str()), Some("Austenite"), "{}", name); |
| 151 | assert_eq!(ours.get("Producer").map(|s| s.as_str()), Some("Austenite"), "{}", name); |
| 152 | if let Some(theirs) = res!(typst_info(src, name)) { |
| 153 | for key in METADATA { |
| 154 | assert_eq!(ours.get(key), theirs.get(key), "{}: {} (ours {:?}, typst {:?})", name, key, ours, theirs); |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | // Typst 0.15.1's own reading of the first case, so the fields are checked where no typst is installed. |
| 160 | let ours = res!(info_of(&scratch("pdf_info_all.pdf"))); |
| 161 | let want = [("Title", "A Title"), ("Author", "Ann Author, Bob"), ("Subject", "A subject line"), |
| 162 | ("Keywords", "one, two")]; |
| 163 | for (key, value) in want { |
| 164 | assert_eq!(ours.get(key).map(|s| s.as_str()), Some(value), "{}", key); |
| 165 | } |
| 166 | let none = res!(info_of(&scratch("pdf_info_none.pdf"))); |
| 167 | assert!(METADATA.iter().all(|k| !none.contains_key(*k)), "an unset field writes no entry: {:?}", none); |
| 168 | Ok(()) |
| 169 | } |
| 170 | |
| 171 | /// A comment inside a `#set document`'s parentheses is trivia, as Typst reads it: a field commented out is |
| 172 | /// no field, a comma in a comment parts no argument, and a `key:` in a comment, a string or raw text names |
| 173 | /// none, while a string's or raw text's own comment markers stay text. Each case is pinned to Typst 0.15.1's |
| 174 | /// reading of it, and held against the installed `typst` where there is one. |
| 175 | #[test] |
| 176 | fn comments_in_set_document_are_trivia() -> Outcome<()> { |
| 177 | let cases: [(&str, &str, [Option<&str>; 4]); 9] = [ |
| 178 | ("e2", "#set document(title: \"T\" /* c */)\n\n= Root\n\nBody.\n", [Some("T"), None, None, None]), |
| 179 | ("d3", "#set document(author: \"A\", title: \"T\" /* , title: \"Wrong\" */)\n\n= Root\n\nBody.\n", |
| 180 | [Some("T"), Some("A"), None, None]), |
| 181 | ("i", "#set document(title: \"T, author: Q\" /* , author: \"X\" */, keywords: (\"k\",))\nBody.\n", |
| 182 | [Some("T, author: Q"), None, None, Some("k")]), |
| 183 | ("j", "#set document(title: \"T\" // , author: \"X\"\n)\nBody.\n", [Some("T"), None, None, None]), |
| 184 | ("k", "#set document(title: \"T\", author: \"A /* not */ B\")\nBody.\n", |
| 185 | [Some("T"), Some("A /* not */ B"), None, None]), |
| 186 | ("l", "#set document(title: [T `raw, author: \"X\"` z])\nBody.\n", |
| 187 | [Some("T raw, author: \"X\" z"), None, None, None]), |
| 188 | ("w", "#set document(\n title: \"T\", // the working title\n author: \"A\",\n)\nBody.\n", |
| 189 | [Some("T"), Some("A"), None, None]), |
| 190 | ("x", "#set document(title: \"T\", keywords: (\"a\", /* \"b\", */ \"c\"))\nBody.\n", |
| 191 | [Some("T"), None, None, Some("a, c")]), |
| 192 | ("y", "#set document(\n // author: \"Old\",\n title: \"T\",\n)\nBody.\n", [Some("T"), None, None, None]), |
| 193 | ]; |
| 194 | for (name, src, want) in cases { |
| 195 | let pdf = scratch(&fmt!("pdf_info_trivia_{}.pdf", name)); |
| 196 | res!(std::fs::write(&pdf, res!(compile_pdf(src)))); |
| 197 | let ours = res!(info_of(&pdf)); |
| 198 | for (key, value) in METADATA.iter().zip(want) { |
| 199 | assert_eq!(ours.get(*key).map(|s| s.as_str()), value, "{}: {} ({:?})", name, key, ours); |
| 200 | } |
| 201 | if let Some(theirs) = res!(typst_info(src, &fmt!("trivia_{}", name))) { |
| 202 | for key in METADATA { |
| 203 | assert_eq!(ours.get(key), theirs.get(key), "{}: {} (ours {:?}, typst {:?})", name, key, ours, theirs); |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | // A field named twice is refused by Typst, which writes no PDF; nothing of the rule is applied here. |
| 209 | let pdf = scratch("pdf_info_trivia_dup.pdf"); |
| 210 | res!(std::fs::write(&pdf, res!(compile_pdf("#set document(title: \"A\", title: \"B\")\nBody.\n")))); |
| 211 | let ours = res!(info_of(&pdf)); |
| 212 | assert!(METADATA.iter().all(|k| !ours.contains_key(*k)), "a refused rule sets no field: {:?}", ours); |
| 213 | Ok(()) |
| 214 | } |
| 215 | |
| 216 | /// A `#set document` shown in a raw block or written in a comment is text, so it writes no Info entry, as |
| 217 | /// in Typst. |
| 218 | #[test] |
| 219 | fn a_shown_or_commented_set_document_writes_no_info() -> Outcome<()> { |
| 220 | let src = "```typst\n#set document(title: \"Example Title\")\n```\n\ |
| 221 | /*\n#set document(author: \"Commented Out\")\n*/\n= Heading\n\nBody.\n"; |
| 222 | let pdf = scratch("pdf_info_shown.pdf"); |
| 223 | res!(std::fs::write(&pdf, res!(compile_pdf(src)))); |
| 224 | let ours = res!(info_of(&pdf)); |
| 225 | assert!(METADATA.iter().all(|k| !ours.contains_key(*k)), "no field was set: {:?}", ours); |
| 226 | if let Some(theirs) = res!(typst_info(src, "shown")) { |
| 227 | assert!(METADATA.iter().all(|k| !theirs.contains_key(*k)), "typst sets none either: {:?}", theirs); |
| 228 | } |
| 229 | Ok(()) |
| 230 | } |
| 231 | |
| 232 | /// An included file's own top-level `#set document` is applied where the include stands, between the root's |
| 233 | /// rules before and after it, field by field, as Typst applies it. |
| 234 | #[test] |
| 235 | fn an_included_files_set_document_is_applied_where_it_stands() -> Outcome<()> { |
| 236 | let files = [ |
| 237 | ("/doc/main.typ", "#set document(title: \"Root Title\", author: \"Root Author\")\n= H\n\nBody.\n\n\ |
| 238 | #include \"ch1.typ\"\n\n#set document(keywords: \"after\")\n"), |
| 239 | ("/doc/ch1.typ", "#set document(title: \"From Chapter\")\n== Sub\n\nText.\n"), |
| 240 | ]; |
| 241 | let pdf = scratch("pdf_info_included.pdf"); |
| 242 | res!(std::fs::write(&pdf, res!(compile_project(&files)))); |
| 243 | let ours = res!(info_of(&pdf)); |
| 244 | let want = [("Title", "From Chapter"), ("Author", "Root Author"), ("Keywords", "after")]; |
| 245 | for (key, value) in want { |
| 246 | assert_eq!(ours.get(key).map(|s| s.as_str()), Some(value), "{}: {:?}", key, ours); |
| 247 | } |
| 248 | if let Some(theirs) = res!(typst_project_info(&files, "included")) { |
| 249 | for key in METADATA { |
| 250 | assert_eq!(ours.get(key), theirs.get(key), "{} (ours {:?}, typst {:?})", key, ours, theirs); |
| 251 | } |
| 252 | } |
| 253 | Ok(()) |
| 254 | } |
| 255 | |
| 256 | /// Compiles `files`, rooted at the first, as `compile_project` does, and returns the PDF with every site the |
| 257 | /// compile reports, as `(line, col, message)`. |
| 258 | fn compile_with_sites(files: &[(&str, &str)]) -> Outcome<(Vec<u8>, Vec<(usize, usize, String)>)> { |
| 259 | let _turn = VFS.lock().unwrap_or_else(|p| p.into_inner()); |
| 260 | let main = match files.first() { |
| 261 | Some((path, _)) => PathBuf::from(path), |
| 262 | None => return Err(err!("A project needs a root source."; Test, Missing)), |
| 263 | }; |
| 264 | let mut map: HashMap<PathBuf, Vec<u8>> = HashMap::new(); |
| 265 | for (path, text) in files { |
| 266 | map.insert(PathBuf::from(path), text.as_bytes().to_vec()); |
| 267 | } |
| 268 | res!(vfs::install(map)); |
| 269 | let set = Arc::new(res!(fonts::libertinus())); |
| 270 | // The report reads each site's line from the installed source, so it is built before the map is cleared. |
| 271 | let run = || -> Outcome<(compile::Rendered, compile::Report)> { |
| 272 | let assembled = res!(compile::assemble(&main, || Ok(set.clone()))); |
| 273 | let empty = assembled.blocks.is_empty(); |
| 274 | let rendered = res!(compile::author_and_run(assembled)); |
| 275 | let report = compile::Report::new(rendered.out.pages.len(), &rendered.refusals, empty); |
| 276 | Ok((rendered, report)) |
| 277 | }; |
| 278 | let result = run(); |
| 279 | let _ = vfs::clear(); |
| 280 | let (mut rendered, report) = res!(result); |
| 281 | let sites = report.diagnostics.iter().map(|d| (d.line, d.col, d.message.clone())).collect(); |
| 282 | let pdf = res!(compile::emit_pdf(&mut rendered.out, &rendered.heads, &rendered.doc_info)); |
| 283 | Ok((pdf, sites)) |
| 284 | } |
| 285 | |
| 286 | /// The first error Typst reports for `src`, or `None` when no `typst` is installed to ask. An error is |
| 287 | /// required: the source is one Typst refuses. |
| 288 | fn typst_error(src: &str, name: &str) -> Outcome<Option<String>> { |
| 289 | let typ = scratch(&fmt!("pdf_info_{}.typ", name)); |
| 290 | let pdf = scratch(&fmt!("pdf_info_{}_typst.pdf", name)); |
| 291 | res!(std::fs::write(&typ, src)); |
| 292 | let out = match Command::new("typst").arg("compile").arg(&typ).arg(&pdf).output() { |
| 293 | Ok(o) => o, |
| 294 | Err(_) => { |
| 295 | eprintln!("SKIP: `typst` is not installed, so {} is not compared with it.", name); |
| 296 | return Ok(None); |
| 297 | }, |
| 298 | }; |
| 299 | if out.status.success() { |
| 300 | return Err(err!("typst compiled {}, which it should refuse.", name; Test)); |
| 301 | } |
| 302 | let text = String::from_utf8_lossy(&out.stderr).to_string(); |
| 303 | Ok(Some(text.lines().find(|l| l.starts_with("error:")).unwrap_or("").to_string())) |
| 304 | } |
| 305 | |
| 306 | /// The text `pdftotext` reads from a PDF, the words joined by single spaces. |
| 307 | fn text_of(pdf: &[u8], name: &str) -> Outcome<String> { |
| 308 | let path = scratch(&fmt!("pdf_info_{}_text.pdf", name)); |
| 309 | res!(std::fs::write(&path, pdf)); |
| 310 | let out = res!(Command::new("pdftotext").arg(&path).arg("-").output()); |
| 311 | Ok(res!(String::from_utf8(out.stdout)).split_whitespace().collect::<Vec<_>>().join(" ")) |
| 312 | } |
| 313 | |
| 314 | /// A `#set document` in a container -- a list item, strong or emphasis, or after a `*` or `_` that opens |
| 315 | /// one prose never closes -- sets no field and is refused at its site, as Typst refuses it. Each of the |
| 316 | /// cases below is a probe of the lexer audit (`d4`, `e4`, `e5`, `u4`, `u2`). |
| 317 | fn assert_container_refused(name: &str, src: &str, line: usize, col: usize, typst: &str) -> Outcome<()> { |
| 318 | let (pdf, sites) = res!(compile_with_sites(&[("/doc/main.typ", src)])); |
| 319 | let path = scratch(&fmt!("pdf_info_{}.pdf", name)); |
| 320 | res!(std::fs::write(&path, &pdf)); |
| 321 | let ours = res!(info_of(&path)); |
| 322 | assert!(!ours.contains_key("Title"), "{}: the rule in a container set a title: {:?}", name, ours); |
| 323 | let held: Vec<&(usize, usize, String)> = sites.iter() |
| 324 | .filter(|(_, _, m)| m.contains("not allowed inside of containers")).collect(); |
| 325 | assert_eq!(held.len(), 1, "{}: one site for the rule: {:?}", name, sites); |
| 326 | assert_eq!((held[0].0, held[0].1), (line, col), "{}: the site stands at the rule's `#`: {:?}", name, sites); |
| 327 | assert!(held[0].2.starts_with("#set document"), "{}: {:?}", name, held[0]); |
| 328 | if let Some(theirs) = res!(typst_error(src, name)) { |
| 329 | assert!(theirs.contains(typst), "{}: typst refuses with {:?}", name, theirs); |
| 330 | } |
| 331 | Ok(()) |
| 332 | } |
| 333 | |
| 334 | #[test] |
| 335 | fn set_document_in_strong_is_refused_at_its_site() -> Outcome<()> { |
| 336 | assert_container_refused("strong", "= Root\n\n*bold [\n#set document(title: \"Strong Title\")\nstill bold*\n\nBody.\n", |
| 337 | 4, 1, "not allowed inside of containers") |
| 338 | } |
| 339 | |
| 340 | #[test] |
| 341 | fn set_document_in_emphasis_is_refused_at_its_site() -> Outcome<()> { |
| 342 | assert_container_refused("emph", "= Root\n\n_emph\n#set document(title: \"Emph Title\")\nstill_\n\nBody.\n", |
| 343 | 4, 1, "not allowed inside of containers") |
| 344 | } |
| 345 | |
| 346 | #[test] |
| 347 | fn set_document_in_list_item_is_refused_at_its_site() -> Outcome<()> { |
| 348 | assert_container_refused("item", "= Root\n\n- item\n #set document(title: \"Item Title\")\n\nBody.\n", |
| 349 | 4, 3, "not allowed inside of containers") |
| 350 | } |
| 351 | |
| 352 | /// A `*` between spaces opens strong that nothing closes, so the rule after it is in a container; Typst |
| 353 | /// refuses the file for the unclosed delimiter before it reaches the rule. |
| 354 | #[test] |
| 355 | fn set_document_after_unclosed_star_is_refused() -> Outcome<()> { |
| 356 | assert_container_refused("star", "= Root\n\n2 * 3 = 6\n#set document(title: \"Star Title\")\n\nBody.\n", |
| 357 | 4, 1, "unclosed delimiter") |
| 358 | } |
| 359 | |
| 360 | /// A `_` between letters of a script that writes no spaces between words opens emphasis, as Typst reads it, |
| 361 | /// so the rule after an unclosed one is in a container. One between Latin letters is within a word, and |
| 362 | /// opens nothing. |
| 363 | #[test] |
| 364 | fn set_document_after_cjk_underscore_is_refused() -> Outcome<()> { |
| 365 | assert_container_refused("cjk", "= Root\n\n\u{65E5}\u{672C}_\u{8A9E}\n#set document(title: \"Cjk Title\")\n\nBody.\n", |
| 366 | 4, 1, "unclosed delimiter")?; |
| 367 | let word = "= Root\n\nsnake_case and a*b\n#set document(title: \"Word Title\")\n\nBody.\n"; |
| 368 | let (pdf, sites) = res!(compile_with_sites(&[("/doc/main.typ", word)])); |
| 369 | let path = scratch("pdf_info_word.pdf"); |
| 370 | res!(std::fs::write(&path, &pdf)); |
| 371 | assert_eq!(res!(info_of(&path)).get("Title").map(|s| s.as_str()), Some("Word Title")); |
| 372 | assert!(sites.is_empty(), "markers within a word open nothing: {:?}", sites); |
| 373 | Ok(()) |
| 374 | } |
| 375 | |
| 376 | /// A bare content block is not a container: Typst joins it into the markup around it, so a `#set document` in |
| 377 | /// it applies where it stands, and its brackets are not shown. One in a `#box` is in a container, and refused. |
| 378 | #[test] |
| 379 | fn set_document_in_bare_block_applies() -> Outcome<()> { |
| 380 | let src = "= Root\n\n#[\n#set document(title: \"Block Title\")\nIn block.\n]\n\nBody.\n"; |
| 381 | let (pdf, sites) = res!(compile_with_sites(&[("/doc/main.typ", src)])); |
| 382 | let path = scratch("pdf_info_bare.pdf"); |
| 383 | res!(std::fs::write(&path, &pdf)); |
| 384 | let ours = res!(info_of(&path)); |
| 385 | assert_eq!(ours.get("Title").map(|s| s.as_str()), Some("Block Title"), "{:?}", ours); |
| 386 | assert!(sites.is_empty(), "nothing in the block is refused: {:?}", sites); |
| 387 | let text = res!(text_of(&pdf, "bare")); |
| 388 | assert!(text.contains("In block.") && text.contains("Body."), "{}", text); |
| 389 | assert!(!text.contains("#[") && !text.contains(']'), "the block's brackets are not prose: {}", text); |
| 390 | if let Some(theirs) = res!(typst_info(src, "bare")) { |
| 391 | assert_eq!(ours.get("Title"), theirs.get("Title"), "typst: {:?}", theirs); |
| 392 | } |
| 393 | Ok(()) |
| 394 | } |
| 395 | |
| 396 | #[test] |
| 397 | fn set_document_in_box_is_refused() -> Outcome<()> { |
| 398 | let src = "= Root\n\n#box[\n#set document(title: \"X\")\n]\n\nBody.\n"; |
| 399 | let (pdf, sites) = res!(compile_with_sites(&[("/doc/main.typ", src)])); |
| 400 | let path = scratch("pdf_info_box.pdf"); |
| 401 | res!(std::fs::write(&path, &pdf)); |
| 402 | assert!(!res!(info_of(&path)).contains_key("Title")); |
| 403 | assert!(!sites.is_empty(), "the box and the rule in it are refused at a site"); |
| 404 | if let Some(theirs) = res!(typst_error(src, "box")) { |
| 405 | assert!(theirs.contains("not allowed inside of containers"), "{:?}", theirs); |
| 406 | } |
| 407 | Ok(()) |
| 408 | } |
| 409 | |
| 410 | /// Whatever a `#set document` stands in, it either sets a field or is refused at a site: none is passed over |
| 411 | /// in silence. |
| 412 | #[test] |
| 413 | fn no_set_document_is_passed_without_a_site() -> Outcome<()> { |
| 414 | let cases = [ |
| 415 | ("a", "= R\n\n*b [\n#set document(title: \"T\")\nb*\n\nB.\n"), |
| 416 | ("b", "= R\n\n_e\n#set document(title: \"T\")\ne_\n\nB.\n"), |
| 417 | ("c", "= R\n\n- i\n #set document(title: \"T\")\n\nB.\n"), |
| 418 | ("d", "= R\n\n2 * 3\n#set document(title: \"T\")\n\nB.\n"), |
| 419 | ("e", "= R\n\n#[\n#set document(title: \"T\")\nx\n]\n\nB.\n"), |
| 420 | ("f", "= R\n\n#box[\n#set document(title: \"T\")\n]\n\nB.\n"), |
| 421 | ("g", "= R\n\n#set document(title: \"T\")\n\nB.\n"), |
| 422 | ]; |
| 423 | for (name, src) in cases { |
| 424 | let (pdf, sites) = res!(compile_with_sites(&[("/doc/main.typ", src)])); |
| 425 | let path = scratch(&fmt!("pdf_info_none_{}.pdf", name)); |
| 426 | res!(std::fs::write(&path, &pdf)); |
| 427 | let titled = res!(info_of(&path)).contains_key("Title"); |
| 428 | assert!(titled || !sites.is_empty(), "{}: no title and no site", name); |
| 429 | assert!(!(titled && sites.iter().any(|(_, _, m)| m.contains("#set document"))), |
| 430 | "{}: a rule is applied and refused at once: {:?}", name, sites); |
| 431 | } |
| 432 | Ok(()) |
| 433 | } |
| 434 | |
| 435 | /// A `#set document` in code -- in a bare content block in the branch of a conditional, or in a list item |
| 436 | /// there -- is joined into nothing the file's own lines hold, so it is refused where it stands rather than |
| 437 | /// passed over. |
| 438 | #[test] |
| 439 | fn set_document_in_a_conditional_branch_below_its_level_is_refused() -> Outcome<()> { |
| 440 | let cases = [ |
| 441 | ("block", "#let media = \"ebook\"\n\n= Root\n\n#if media == \"ebook\" [\n#[\n#set document(title: \"T\")\n]\n]\n\nBody.\n"), |
| 442 | ("item", "#let media = \"ebook\"\n\n= Root\n\n#if media == \"ebook\" [\n- x\n #set document(title: \"T\")\n]\n\nBody.\n"), |
| 443 | ]; |
| 444 | for (name, src) in cases { |
| 445 | let (pdf, sites) = res!(compile_with_sites(&[("/doc/main.typ", src)])); |
| 446 | let path = scratch(&fmt!("pdf_info_incode_{}.pdf", name)); |
| 447 | res!(std::fs::write(&path, &pdf)); |
| 448 | assert!(!res!(info_of(&path)).contains_key("Title"), "{}", name); |
| 449 | let held: Vec<&(usize, usize, String)> = sites.iter().filter(|(_, _, m)| m.contains("#set document")).collect(); |
| 450 | assert_eq!(held.len(), 1, "{}: the rule is refused once: {:?}", name, sites); |
| 451 | assert!(held[0].2.contains("inside a body, where it is not applied"), "{}: {:?}", name, held[0]); |
| 452 | } |
| 453 | Ok(()) |
| 454 | } |
| 455 | |
| 456 | /// A `#set document` that names a field the Info fold cannot take is refused at its line, naming it, wherever |
| 457 | /// the fold applies the rest of the rule: at a file's top level and in a bare content block. One in a container |
| 458 | /// is refused there alone, once, for the container. |
| 459 | #[test] |
| 460 | fn set_document_that_leaves_a_field_unapplied_names_it() -> Outcome<()> { |
| 461 | let cases = [ |
| 462 | ("top", "= Root\n\n#set document(title: \"T\", date: auto)\n\nBody.\n", 3, true), |
| 463 | ("block", "= Root\n\n#[\n#set document(title: \"T\", date: auto)\nIn block.\n]\n\nBody.\n", 4, true), |
| 464 | ("item", "= Root\n\n- item\n #set document(title: \"T\", date: auto)\n\nBody.\n", 4, false), |
| 465 | ]; |
| 466 | for (name, src, line, applied) in cases { |
| 467 | let (pdf, sites) = res!(compile_with_sites(&[("/doc/main.typ", src)])); |
| 468 | let path = scratch(&fmt!("pdf_info_unapplied_{}.pdf", name)); |
| 469 | res!(std::fs::write(&path, &pdf)); |
| 470 | let titled = res!(info_of(&path)).get("Title").map(|s| s.as_str()) == Some("T"); |
| 471 | assert_eq!(titled, applied, "{}: the title is applied only where the fold applies the rule", name); |
| 472 | let held: Vec<&(usize, usize, String)> = sites.iter().filter(|(_, _, m)| m.contains("#set document")).collect(); |
| 473 | assert_eq!(held.len(), 1, "{}: one site for the rule: {:?}", name, sites); |
| 474 | assert_eq!(held[0].0, line, "{}: {:?}", name, held[0]); |
| 475 | if applied { |
| 476 | assert!(!held[0].2.contains("not allowed inside of containers"), "{}: refused for what it left: {:?}", name, held[0]); |
| 477 | } else { |
| 478 | assert!(held[0].2.contains("not allowed inside of containers"), "{}: {:?}", name, held[0]); |
| 479 | } |
| 480 | } |
| 481 | Ok(()) |
| 482 | } |