Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/eval/lib/pdf.rs

4.9 KiB, 3 runs

created by r1870400018:63486, 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` module of Typst 0.15: `pdf.attach` and `pdf.artifact`. Austenite writes neither an embedded file nor a
2// tagged structure. An attachment is therefore passed over with a warning that refuses a strict compile, as every
3// construct set otherwise than Typst sets it does; an artifact is its body, since marking a body as a page
4// furnishing changes the tags of a PDF and not what it shows.
5
6use crate::diag::DiagnosticKind;
7use crate::eval::args::Args;
8use crate::eval::content::Content;
9use crate::eval::func::{
10 Func,
11 NativeFunc,
12};
13use crate::eval::import::{
14 read_file,
15 resolve_path,
16};
17use crate::eval::lib::foundations::{
18 define_nth,
19 finish,
20 mismatch,
21 need,
22};
23use crate::eval::scope::Scope;
24use crate::eval::value::{
25 Module,
26 Value,
27};
28use crate::eval::Engine;
29use crate::syntax::Span;
30
31use oxedyne_fe2o3_core::prelude::*;
32
33use std::sync::Arc;
34
35native_fns! {
36 pub enum PdfFn {
37 Attach => "attach",
38 Artifact => "artifact",
39 }
40}
41
42// What an attachment may be to the document, and what a body may be to the page.
43const RELATIONSHIPS: [&str; 4] = ["source", "data", "alternative", "supplement"];
44const KINDS: [&str; 12] = [
45 "header", "footer", "watermark", "page-number", "line-number", "redaction", "bates", "page",
46 "pagination-other", "layout", "background", "other",
47];
48
49pub fn define(scope: &mut Scope) {
50 let mut s = Scope::new();
51 for (n, f) in PdfFn::ALL.iter().enumerate() {
52 define_nth(&mut s, n, f.name(), Value::Func(Func::Native(NativeFunc::Pdf(*f))));
53 }
54 scope.define("pdf", Value::Module(Arc::new(Module::new("pdf", s))));
55}
56
57// The words of `expected "a", "b", or "c"` for a closed set of strings, with `none` among them where it is allowed.
58fn one_of(set: &[&str], none: bool) -> String {
59 let mut items: Vec<String> = set.iter().map(|s| fmt!("\"{}\"", s)).collect();
60 if none {
61 items.push("none".to_string());
62 }
63 match items.split_last() {
64 Some((last, rest)) => fmt!("expected {}, or {}", rest.join(", "), last),
65 None => String::new(),
66 }
67}
68
69// Where Typst places an error in a named argument: at its value.
70fn value_span(args: &Args, name: &str) -> Span {
71 args.items.iter().find(|a| a.name.as_deref() == Some(name)).map(|a| a.value_span).unwrap_or(args.span)
72}
73
74pub fn call(f: PdfFn, engine: &mut Engine, mut args: Args) -> Outcome<Value> {
75 let span = args.span;
76 match f {
77 PdfFn::Attach => {
78 // A path that names no file fails at the argument naming it.
79 let at = args.items.iter().find(|a| a.name.is_none()).map(|a| a.span).unwrap_or(span);
80 let (at_rel, at_mime, at_desc) = (
81 value_span(&args, "relationship"), value_span(&args, "mime-type"), value_span(&args, "description"));
82 let path = match res!(need(engine, &mut args, "path")).symbol_as_str() {
83 Value::Str(s) => s,
84 other => return Err(mismatch(engine, span, "string", &other)),
85 };
86 // The data is the second positional, and never a named argument.
87 let data = res!(args.eat::<Value>());
88 let relationship = res!(args.named::<Value>("relationship"));
89 let mime = res!(args.named::<Value>("mime-type"));
90 let description = res!(args.named::<Value>("description"));
91 res!(finish(engine, args));
92 match relationship {
93 None | Some(Value::None) => (),
94 Some(Value::Str(ref s)) if RELATIONSHIPS.contains(&s.as_str()) => (),
95 Some(_) => {
96 return Err(engine.error(DiagnosticKind::Type, at_rel, one_of(&RELATIONSHIPS, true)));
97 },
98 }
99 for (v, here) in [(&mime, at_mime), (&description, at_desc)] {
100 match v {
101 None | Some(Value::None) | Some(Value::Str(_)) => (),
102 Some(other) => return Err(mismatch(engine, here, "string or none", other)),
103 }
104 }
105 match data {
106 Some(Value::Bytes(_)) => (),
107 // Typst reads the file the path names when no data is given, so a path that names none fails.
108 None | Some(Value::Auto) => {
109 let file = res!(resolve_path(engine, &path, at.file, at));
110 let _ = res!(read_file(engine, &file, at));
111 },
112 Some(other) => return Err(mismatch(engine, span, "bytes or auto", &other)),
113 }
114 engine.warn(DiagnosticKind::Unsupported, span, "pdf attachments are not embedded");
115 Ok(Value::Content(Content::empty()))
116 },
117 PdfFn::Artifact => {
118 let at_kind = value_span(&args, "kind");
119 let body = res!(need(engine, &mut args, "body"));
120 let kind = res!(args.named::<Value>("kind"));
121 res!(finish(engine, args));
122 match kind {
123 None => (),
124 Some(Value::Str(ref s)) if KINDS.contains(&s.as_str()) => (),
125 Some(Value::Str(_)) => return Err(engine.error(DiagnosticKind::Type, at_kind, one_of(&KINDS, false))),
126 Some(other) => {
127 let msg = fmt!("{}, found {}", one_of(&KINDS, false), other.ty().long_name());
128 return Err(engine.error(DiagnosticKind::Type, at_kind, msg));
129 },
130 }
131 match body {
132 Value::Content(c) => Ok(Value::Content(c)),
133 Value::Str(s) => Ok(Value::Content(Content::text(&s))),
134 other => Err(mismatch(engine, span, "content", &other)),
135 }
136 },
137 }
138}