Skip to main content

aura_build/
lib.rs

1//! Build-script helper for AURA plugins with a Slint GUI.
2//!
3//! Wraps [`slint_build::compile_with_config`] and pre-fills the AURA bits —
4//! the `@aura` widget library path and the include path that lets `.slint`
5//! files `import "JetBrainsMono-Regular.ttf";` etc.
6//!
7//! ```rust,ignore
8//! // build.rs
9//! fn main() {
10//!     aura_build::compile("ui/main.slint").unwrap();
11//! }
12//! ```
13//!
14//! In `.slint`:
15//! ```text
16//! import { Knob, Meter, AuraTheme } from "@aura";
17//! import "JetBrainsMono-Regular.ttf";
18//! // colors: AuraTheme.surface / .primary (Material 3 dark tokens)
19//! ```
20
21use std::error::Error;
22use std::fmt;
23use std::fs;
24use std::path::{Path, PathBuf};
25
26/// Filenames under `OUT_DIR/fonts/` — contract for plugin `.slint` imports.
27const FONT_SOURCES: &[(&str, &[u8])] = &[
28    (
29        "JetBrainsMono-Regular.ttf",
30        include_bytes!("../fonts/JetBrainsMono-Regular.ttf"),
31    ),
32    (
33        "JetBrainsMono-Bold.ttf",
34        include_bytes!("../fonts/JetBrainsMono-Bold.ttf"),
35    ),
36    (
37        "NotoSans-Regular.ttf",
38        include_bytes!("../fonts/NotoSans-Regular.ttf"),
39    ),
40    (
41        "NotoSans-Bold.ttf",
42        include_bytes!("../fonts/NotoSans-Bold.ttf"),
43    ),
44    (
45        "Selawik-Regular.ttf",
46        include_bytes!("../fonts/Selawik-Regular.ttf"),
47    ),
48    (
49        "Selawik-Bold.ttf",
50        include_bytes!("../fonts/Selawik-Bold.ttf"),
51    ),
52];
53
54/// `@aura` library import name (`import { Knob } from "@aura";`).
55const LIBRARY_NAME: &str = "aura";
56
57const WIDGET_SOURCES: &[(&str, &str)] = &[
58    ("widgets.slint", include_str!("../ui/widgets.slint")),
59    ("theme.slint", include_str!("../ui/theme.slint")),
60    ("knob.slint", include_str!("../ui/knob.slint")),
61    ("meter.slint", include_str!("../ui/meter.slint")),
62    ("dropdown.slint", include_str!("../ui/dropdown.slint")),
63    ("slider.slint", include_str!("../ui/slider.slint")),
64    ("toggle.slint", include_str!("../ui/toggle.slint")),
65    ("xy_pad.slint", include_str!("../ui/xy_pad.slint")),
66];
67
68/// Where the bundled widgets and fonts were written, and how the Slint
69/// compiler must be configured to resolve `@aura` and font imports.
70///
71/// Returned by [`materialize_assets`]; usable outside build scripts (e.g.
72/// the `aura-preview` hot-reload viewer configures `slint_interpreter`
73/// with exactly these paths).
74#[derive(Debug, Clone)]
75pub struct AssetPaths {
76    /// `"aura"` → path of the materialized `widgets.slint`.
77    pub library_paths: std::collections::HashMap<String, PathBuf>,
78    /// Directory containing the bundled `.ttf` files.
79    pub include_paths: Vec<PathBuf>,
80    /// Pinned widget style (`"fluent"`).
81    pub style: String,
82}
83
84/// Write the bundled `@aura` widgets and fonts into `dir/aura-build/{ui,fonts}`
85/// and return the compiler configuration pointing at them.
86///
87/// Unlike [`compile`] this does not need `OUT_DIR` and emits no cargo
88/// directives, so it works in any process.
89///
90/// # Errors
91///
92/// [`CompileError`] if the assets cannot be written.
93pub fn materialize_assets(dir: &Path) -> Result<AssetPaths, CompileError> {
94    let ui_dir = materialize_widgets(dir)?;
95    let font_dir = materialize_font(dir)?;
96
97    let mut library_paths = std::collections::HashMap::new();
98    library_paths.insert(LIBRARY_NAME.to_string(), ui_dir.join("widgets.slint"));
99
100    Ok(AssetPaths {
101        library_paths,
102        include_paths: vec![font_dir],
103        // Pin Fluent so ComboBox / std-widgets look the same on every OS.
104        style: "fluent".to_string(),
105    })
106}
107
108/// Compile `slint_entry` (relative to the caller's `CARGO_MANIFEST_DIR`)
109/// with the AURA widget library and font include path.
110///
111/// # Errors
112///
113/// [`CompileError`] if `OUT_DIR` is missing, assets cannot be written, or
114/// `slint-build` rejects the input.
115pub fn compile(slint_entry: impl AsRef<Path>) -> Result<(), CompileError> {
116    let out_dir = std::env::var_os("OUT_DIR")
117        .map(PathBuf::from)
118        .ok_or(CompileError::NoOutDir)?;
119
120    // Rerun if crate fonts change (when building from git path).
121    println!("cargo:rerun-if-changed=fonts");
122    println!("cargo:rerun-if-changed=ui");
123
124    let assets = materialize_assets(&out_dir)?;
125
126    let config = slint_build::CompilerConfiguration::new()
127        .with_library_paths(assets.library_paths)
128        .with_include_paths(assets.include_paths)
129        .with_style(assets.style);
130
131    slint_build::compile_with_config(slint_entry, config)
132        .map_err(|e| CompileError::Slint(format!("{e}")))?;
133
134    Ok(())
135}
136
137/// Errors from [`compile`].
138#[derive(Debug)]
139pub enum CompileError {
140    NoOutDir,
141    Io(std::io::Error),
142    Slint(String),
143}
144
145impl fmt::Display for CompileError {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        match self {
148            Self::NoOutDir => {
149                f.write_str("OUT_DIR not set — call aura_build::compile from a build script")
150            }
151            Self::Io(e) => write!(f, "writing bundled assets to OUT_DIR: {e}"),
152            Self::Slint(e) => write!(f, "slint compile failed: {e}"),
153        }
154    }
155}
156
157impl Error for CompileError {
158    fn source(&self) -> Option<&(dyn Error + 'static)> {
159        match self {
160            Self::Io(e) => Some(e),
161            _ => None,
162        }
163    }
164}
165
166impl From<std::io::Error> for CompileError {
167    fn from(e: std::io::Error) -> Self {
168        Self::Io(e)
169    }
170}
171
172fn materialize_widgets(out_dir: &Path) -> Result<PathBuf, CompileError> {
173    let ui_dir = out_dir.join("aura-build/ui");
174    fs::create_dir_all(&ui_dir)?;
175    for (name, source) in WIDGET_SOURCES {
176        write_if_changed(&ui_dir.join(name), source.as_bytes())?;
177    }
178    Ok(ui_dir)
179}
180
181fn materialize_font(out_dir: &Path) -> Result<PathBuf, CompileError> {
182    let font_dir = out_dir.join("aura-build/fonts");
183    fs::create_dir_all(&font_dir)?;
184    for (name, bytes) in FONT_SOURCES {
185        write_if_changed(&font_dir.join(name), bytes)?;
186    }
187    Ok(font_dir)
188}
189
190fn write_if_changed(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
191    if let Ok(existing) = fs::read(path)
192        && existing == bytes
193    {
194        return Ok(());
195    }
196    fs::write(path, bytes)
197}