Skip to main content

gammaloop_api/
templates.rs

1use color_eyre::Result;
2use include_dir::Dir;
3use std::fs;
4use std::path::Path;
5
6const LINNEST_PACKAGE_DIR: &str = "crates/linnest/typst";
7const KURVST_PACKAGE_DIR: &str = "crates/kurvst/typst";
8
9pub struct Assets;
10
11include!(concat!(env!("OUT_DIR"), "/embedded_assets.rs"));
12
13impl Assets {
14    /// Get all app template paths written under drawings/templates.
15    pub fn template_paths() -> impl Iterator<Item = String> {
16        GAMMALOOP_TEMPLATE_ASSETS
17            .files()
18            .map(|file| file.path().to_string_lossy().into_owned())
19    }
20
21    /// Extract all drawing templates to drawings/templates relative to target_dir.
22    pub fn extract_templates<P: AsRef<Path>>(target_dir: P) -> Result<()> {
23        let target = target_dir.as_ref().join("drawings/templates");
24
25        fs::create_dir_all(&target)?;
26
27        extract_package(&GAMMALOOP_TEMPLATE_ASSETS, &target)?;
28        extract_package(&LINNEST_PACKAGE_ASSETS, &target.join(LINNEST_PACKAGE_DIR))?;
29        extract_package(&KURVST_PACKAGE_ASSETS, &target.join(KURVST_PACKAGE_DIR))?;
30
31        Ok(())
32    }
33
34    /// Extract the Justfile to the target directory
35    pub fn extract_justfile<P: AsRef<Path>>(target_dir: P) -> Result<()> {
36        let justfile_path = target_dir.as_ref().join("justfile");
37
38        fs::write(
39            &justfile_path,
40            include_bytes!("../../../assets/embedded/drawing/justfile"),
41        )?;
42
43        Ok(())
44    }
45}
46
47fn extract_package(assets: &Dir<'_>, target: &Path) -> Result<()> {
48    fs::create_dir_all(target)?;
49    for file in assets.files() {
50        let target_path = target.join(file.path());
51        if let Some(parent) = target_path.parent() {
52            fs::create_dir_all(parent)?;
53        }
54        fs::write(&target_path, file.contents())?;
55    }
56
57    Ok(())
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63    use gammalooprs::model::ModelGammaLoopExt;
64
65    #[test]
66    fn extract_templates_uses_canonical_package_layout() -> Result<()> {
67        let tempdir = tempfile::tempdir()?;
68
69        Assets::extract_templates(tempdir.path())?;
70
71        let templates = tempdir.path().join("drawings/templates");
72        assert!(templates.join("figure.typ").is_file());
73        assert!(templates.join("grid.typ").is_file());
74        assert!(templates.join("layout.typ").is_file());
75        assert!(templates.join("layout-core.typ").is_file());
76        assert!(templates.join("physics-edge-style.typ").is_file());
77        assert!(templates.join("impl/physics-edge-style.typ").is_file());
78
79        assert!(templates
80            .join("crates/linnest/typst/linnest.wasm")
81            .is_file());
82        assert!(templates
83            .join("crates/linnest/typst/src/curve.typ")
84            .is_file());
85        assert!(templates
86            .join("crates/linnest/typst/src/impl/graph.typ")
87            .is_file());
88        assert!(templates
89            .join("crates/linnest/typst/src/render/layout.typ")
90            .is_file());
91        assert!(!templates
92            .join("crates/linnest/typst/src/physics-edge-style.typ")
93            .exists());
94        assert!(!templates
95            .join("crates/linnest/typst/src/impl/physics-edge-style.typ")
96            .exists());
97        assert!(templates.join("crates/kurvst/typst/kurvst.wasm").is_file());
98        assert!(templates.join("crates/kurvst/typst/src/lib.typ").is_file());
99        assert!(templates.join("crates/kurvst/typst/src/impl.typ").is_file());
100
101        assert!(!templates.join("linnest.wasm").exists());
102        assert!(!templates.join("kurvst.wasm").exists());
103        assert!(!templates.join("curve.typ").exists());
104        for package in [LINNEST_PACKAGE_DIR, KURVST_PACKAGE_DIR] {
105            for excluded in ["docs", "examples", "benches", "README.md", "LICENSE"] {
106                assert!(!templates.join(package).join(excluded).exists());
107            }
108        }
109
110        Assets::extract_justfile(tempdir.path())?;
111        assert!(tempdir.path().join("justfile").is_file());
112
113        Ok(())
114    }
115
116    #[cfg(unix)]
117    #[test]
118    #[ignore = "requires Typst, just, and LINNET_TEST_EXECUTABLE pointing to a built CLI"]
119    fn exported_model_drawings_render_and_cache_without_python() -> Result<()> {
120        use std::collections::BTreeMap;
121        use std::os::unix::fs::symlink;
122        use std::path::PathBuf;
123        use std::process::Command;
124
125        let temp = tempfile::tempdir()?;
126        let bin = temp.path().join("bin");
127        fs::create_dir(&bin)?;
128        let search_path = std::env::var_os("PATH").unwrap_or_default();
129        for (name, configured) in [
130            (
131                "linnet",
132                Some(
133                    std::env::var_os("LINNET_TEST_EXECUTABLE").expect("set LINNET_TEST_EXECUTABLE"),
134                ),
135            ),
136            ("typst", std::env::var_os("TYPST_TEST_EXECUTABLE")),
137            ("just", None),
138            ("sh", None),
139        ] {
140            let executable = configured.map(PathBuf::from).unwrap_or_else(|| {
141                std::env::split_paths(&search_path)
142                    .map(|directory| directory.join(name))
143                    .find(|path| path.is_file())
144                    .unwrap_or_else(|| panic!("{name} must be available on PATH"))
145            });
146            symlink(fs::canonicalize(executable)?, bin.join(name))?;
147        }
148        let absent = Command::new(bin.join("sh"))
149            .env("PATH", &bin)
150            .args(["-c", "! command -v python && ! command -v python3"])
151            .status()?;
152        assert!(absent.success());
153
154        Assets::extract_templates(temp.path())?;
155        Assets::extract_justfile(temp.path())?;
156        let templates = temp.path().join("drawings/templates");
157        let model = gammalooprs::utils::load_generic_model("scalars");
158        model.generate_edge_style_template(templates.join("edge-style.typ"))?;
159        let data = temp.path().join("processes/amplitudes/example.dot");
160        fs::create_dir_all(data.parent().unwrap())?;
161        fs::write(
162            &data,
163            r#"digraph amplitude {
164            a [pos="0,0!"]; b [pos="4,0!"];
165            incoming [style=invis]; outgoing [style=invis];
166            incoming -> a [particle="scalar_0", pos="z:4"];
167            a -> b [particle="scalar_0"];
168            b -> outgoing [particle="scalar_0", pos="z:-2"];
169        }"#,
170        )?;
171
172        for scenario in ["initial", "cached", "changed-source", "explicit-inputs"] {
173            if scenario == "changed-source" {
174                let implementation = templates.join("crates/linnest/typst/src/impl/draw.typ");
175                let source = fs::read_to_string(&implementation)?;
176                fs::write(
177                    implementation,
178                    format!("{source}\n// Cache invalidation probe.\n"),
179                )?;
180            }
181            let mut command = Command::new(bin.join("just"));
182            command.current_dir(temp.path()).env("PATH", &bin).args([
183                "steps=0",
184                "columns=1",
185                "draw",
186            ]);
187            if scenario == "explicit-inputs" {
188                command.args(["--input", "steps=2", "--input", "columns=2"]);
189            }
190            let output = command.output()?;
191            let expected = if scenario == "cached" {
192                "0 built, 1 reused"
193            } else {
194                "1 built, 0 reused"
195            };
196            assert!(
197                output.status.success(),
198                "{}",
199                String::from_utf8_lossy(&output.stderr)
200            );
201            assert!(
202                String::from_utf8_lossy(&output.stdout).contains(expected),
203                "{}",
204                String::from_utf8_lossy(&output.stdout)
205            );
206            for path in [
207                "drawings.pdf",
208                "drawings/figs/processes/amplitudes/example.pdf",
209            ] {
210                assert!(fs::read(temp.path().join(path))?.starts_with(b"%PDF-"));
211            }
212            let metadata: serde_json::Value = serde_json::from_slice(&fs::read(
213                temp.path().join("drawings/.cache/run-metadata.json"),
214            )?)?;
215            let inputs: Vec<(String, String)> = serde_json::from_value(metadata["input"].clone())?;
216            let inputs: BTreeMap<_, _> = inputs.into_iter().collect();
217            assert_eq!(
218                inputs["steps"],
219                if scenario == "explicit-inputs" {
220                    "2"
221                } else {
222                    "0"
223                }
224            );
225            assert_eq!(
226                inputs["columns"],
227                if scenario == "explicit-inputs" {
228                    "2"
229                } else {
230                    "1"
231                }
232            );
233        }
234
235        let assertions = temp.path().join("model-style.typ");
236        fs::write(
237            &assertions,
238            r#"#import "drawings/templates/edge-style.typ" as physics
239#import "drawings/templates/crates/linnest/typst/src/lib.typ": graph
240#let g = graph.parse(read("processes/amplitudes/example.dot")).first()
241#let particle-label = physics.map.at("scalar_0").label
242#let styles = physics.style(label-size: 12pt, label-fill: blue)
243#let expected-label = text(size: 12pt, fill: blue)[#particle-label]
244#assert(particle-label != none)
245#assert(graph.edges(g).len() == 3)
246// Drawing callbacks receive flattened fields, while graph.edges stores DOT
247// attributes in statements. Use the public mapper's normalized view.
248#let _ = graph.map(g, edge: edge => {
249  assert((styles.edge-label)(edge.fields) == expected-label)
250  none
251})
252[Model-generated particle labels work directly in Typst.]
253"#,
254        )?;
255        let output = Command::new(bin.join("typst"))
256            .env("PATH", &bin)
257            .arg("compile")
258            .arg("--root")
259            .arg(temp.path())
260            .arg(&assertions)
261            .arg(temp.path().join("model-style.pdf"))
262            .output()?;
263        assert!(
264            output.status.success(),
265            "{}",
266            String::from_utf8_lossy(&output.stderr)
267        );
268        Ok(())
269    }
270}