Files
AniCraft/build.rs
T
Dylan M. Taylor 1bf696b08f packaging(linux): support co-installable nightly packages (#610)
Linux nightly packaging by @dylanmtaylor, with the per-app Nightly flavor commits stacked on his branch.

Co-authored-by: Dylan M. Taylor <dylan@dylanmtaylor.com>
2026-11-24 19:16:47 -06:00

284 lines
13 KiB
Rust

//! Optional build inputs (the Craft family convention, as in PhotoCraft), and the app icon
//! embedded in the Windows executable.
//!
//! `CRAFT_FONTS_DIR=<craft-fonts checkout> cargo build` embeds the UI typefaces chosen in
//! ADR 0005: Inter (prose) and JetBrains Mono (data), both SIL OFL 1.1. Font files are never
//! committed to this repository. It also embeds Noto Sans Georgian (`Geor`) and Noto Sans Hebrew
//! (`Hebr`) from craft-fonts as fallback faces: the first is what lets the interface offer
//! Georgian, the second draws Hebrew letters in names (Hebrew is not an interface language until
//! egui lays out right to left). Without the variable the app uses egui's bundled defaults, and
//! everything still works.
//!
//! `CRAFT_I18N_DIR=<craft-i18n checkout>` embeds the interface catalogs (ADR 0040); without it
//! the interface is English. Neither repository is ever a Cargo dependency.
use std::path::{Path, PathBuf};
#[path = "src/build_channel.rs"]
mod build_channel;
/// The release channel: `<APP>_BUILD_CHANNEL=nightly-v1` compiles the Nightly flavour in, and
/// `<APP>_VERSION` must then carry the exact prepared feed identity (`X.Y.Z-nightly.<date>.<run>.
/// <attempt>.g<sha12>`). Unset, empty or `stable` is a stable build; anything else is an error.
/// Returns whether this is Nightly and the version the binary reports.
fn build_channel() -> (bool, String) {
println!("cargo:rerun-if-env-changed=ANICRAFT_BUILD_CHANNEL");
println!("cargo:rerun-if-env-changed=ANICRAFT_VERSION");
println!("cargo:rerun-if-env-changed=ANICRAFT_BUILD_SHA");
println!("cargo:rustc-check-cfg=cfg(anicraft_nightly_v1)");
let nightly = match std::env::var("ANICRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo:rustc-cfg=anicraft_nightly_v1");
true
}
// An empty value (an unset CI input) means the default stable build.
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
_ => {
eprintln!("error: unsupported ANICRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
std::process::exit(1);
}
};
let built_version = if nightly {
match std::env::var("ANICRAFT_VERSION") {
Ok(version) if build_channel::is_nightly_version(&version) => version,
_ => {
eprintln!("error: nightly-v1 requires an explicit ANICRAFT_VERSION feed identity");
std::process::exit(1);
}
}
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
let sha = std::env::var("ANICRAFT_BUILD_SHA").unwrap_or_default();
if nightly {
let exact = sha.len() == 40 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
if !exact || !built_version.ends_with(&format!(".g{sha:.12}")) {
eprintln!("error: nightly-v1 requires ANICRAFT_BUILD_SHA, the 40-hex commit the version names");
std::process::exit(1);
}
}
println!("cargo:rustc-env=ANICRAFT_BUILD_SHA={sha}");
println!("cargo:rustc-env=ANICRAFT_BUILT_VERSION={built_version}");
(nightly, built_version)
}
/// Files we look for, and the generated constant each fills.
const FONTS: [(&str, &str); 4] = [
("Inter-Regular.ttf", "UI_FONT"),
("JetBrainsMono-Regular.ttf", "MONO_FONT"),
("NotoSansGeorgian.ttf", "GEORGIAN_FONT"),
("NotoSansHebrew-Regular.ttf", "HEBREW_FONT"),
];
fn find(dir: &Path, name: &str, depth: u32) -> Option<PathBuf> {
let entries = std::fs::read_dir(dir).ok()?;
let mut subdirs = Vec::new();
for e in entries.flatten() {
let p = e.path();
if p.is_dir() {
subdirs.push(p);
} else if p.file_name().is_some_and(|n| n.eq_ignore_ascii_case(name)) {
return Some(p);
}
}
if depth == 0 {
return None;
}
subdirs.iter().find_map(|d| find(d, name, depth - 1))
}
/// Where to look for the fonts when `CRAFT_FONTS_DIR` is not set: a `craft-fonts` checkout next
/// to this repository (or up to three folders above it), then a sibling Craft app that vendors
/// the same OFL files (PhotoCraft's `assets/fonts`). This makes ordinary local builds look like
/// releases without committing font files here.
fn discover() -> Option<PathBuf> {
if let Some(d) = std::env::var_os("CRAFT_FONTS_DIR") {
return Some(PathBuf::from(d));
}
let manifest = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR")?);
let mut dir = manifest.parent().map(Path::to_path_buf);
for _ in 0..4 {
let Some(d) = dir else { break };
for candidate in [d.join("craft-fonts"), d.join("photocraft").join("assets").join("fonts")] {
if candidate.is_dir() {
return Some(candidate);
}
}
dir = d.parent().map(Path::to_path_buf);
}
None
}
/// Release builds set this (packaging/, ADR 0026): a build that would ship without its icon then
/// fails instead of warning.
fn required(var: &str) -> bool {
println!("cargo:rerun-if-env-changed={var}");
std::env::var(var).is_ok_and(|v| v == "1")
}
/// Stops the build with a message (only for the release requirement above).
fn fail(message: &str) -> ! {
eprintln!("error: {message}");
std::process::exit(1);
}
/// Windows only: embed the app icon and version resource into `anicraft.exe` (taskbar, Start
/// menu, Explorer, Alt-Tab). The Nightly build gets its own icon, `ProductName` "AniCraft
/// Nightly" and its exact feed version as `ProductVersion`, which the ArtCraft Launcher checks.
/// A missing resource compiler is a warning, so a cross-compile still links, unless
/// `ANICRAFT_REQUIRE_WINRES=1` (packaging/windows/package.ps1, the Nightly producer).
fn windows_icon(nightly: bool, built_version: &str) {
println!("cargo:rerun-if-changed=assets/app-icon/anicraft.ico");
println!("cargo:rerun-if-changed=assets/app-icon/anicraft-nightly.ico");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
let mut res = winresource::WindowsResource::new();
res.set_icon(build_channel::windows_icon_path(nightly))
.set("ProductName", if nightly { "AniCraft Nightly" } else { "AniCraft" })
.set("FileDescription", if nightly { "AniCraft Nightly animation studio" } else { "AniCraft 2D vector animation studio" });
if nightly {
res.set("ProductVersion", built_version);
}
if let Err(e) = res.compile() {
if required("ANICRAFT_REQUIRE_WINRES") {
fail(&format!("ANICRAFT_REQUIRE_WINRES=1 but anicraft.exe's icon and version resource could not be embedded: {e}"));
}
println!("cargo:warning=anicraft.exe built without its icon: {e}");
}
}
/// The features as cfgs: `gpu_stage` is on when its feature is and the target isn't the web
/// (ADR 0036), so `cargo build --target wasm32-unknown-unknown` works with the default features
/// and the web build draws on the CPU; `sound_output` is on when its feature is, on the web too
/// (Web Audio, ADR 0095).
fn native_features() {
println!("cargo::rustc-check-cfg=cfg(gpu_stage, sound_output)");
let web = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32");
for (feature, cfg, desktop_only) in [("CARGO_FEATURE_GPU_STAGE", "gpu_stage", true), ("CARGO_FEATURE_SOUND_OUTPUT", "sound_output", false)] {
if std::env::var_os(feature).is_some() && !(web && desktop_only) {
println!("cargo::rustc-cfg={cfg}");
}
}
}
fn main() {
native_features();
let (nightly, built_version) = build_channel();
windows_icon(nightly, &built_version);
println!("cargo:rerun-if-env-changed=CRAFT_FONTS_DIR");
println!("cargo:rerun-if-changed=build.rs");
let dir = discover();
match &dir {
Some(d) => println!("cargo:rerun-if-changed={}", d.display()),
None => println!("cargo:warning=UI fonts: no craft-fonts found (set CRAFT_FONTS_DIR or clone storytold/craft-fonts next to the repo); using the built-in fallback fonts"),
}
let mut code = String::from("// Generated by build.rs (CRAFT_FONTS_DIR font input).\n");
let mut total = 0u64;
for (file, constant) in FONTS {
let found = dir.as_deref().and_then(|d| find(d, file, 3));
match found {
Some(p) => {
println!("cargo:rerun-if-changed={}", p.display());
total += std::fs::metadata(&p).map(|m| m.len()).unwrap_or(0);
code.push_str(&format!("pub const {constant}: Option<&[u8]> = Some(include_bytes!({:?}));\n", p.display().to_string()));
}
None => {
if dir.is_some() {
println!("cargo:warning=CRAFT_FONTS_DIR is set but {file} was not found; using the bundled default");
}
code.push_str(&format!("pub const {constant}: Option<&[u8]> = None;\n"));
}
}
}
code.push_str(&format!("pub const CRAFT_FONT_BYTES: u64 = {total};\n"));
let out_dir = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default());
let out = out_dir.join("fonts.rs");
if let Err(e) = std::fs::write(&out, code) {
println!("cargo:warning=could not write {}: {e}", out.display());
}
let out = out_dir.join("craft_i18n.rs");
if let Err(e) = std::fs::write(&out, craft_i18n()) {
println!("cargo:warning=could not write {}: {e}", out.display());
}
}
/// AniCraft's own catalog in a craft-i18n locale: `locales/<locale>/anicraft.tsv`.
const APP_CATALOG: &str = "anicraft.tsv";
/// `CRAFT_I18N` (ADR 0040), as craft-i18n's `docs/integration.md` describes: one
/// `(locale, common.tsv, anicraft.tsv)` entry per locale with AniCraft's own catalog, and the
/// base language of a regional one (`pt` for `pt-br`) so it can fall back, embedded with
/// `include_str!`. Without `CRAFT_I18N_DIR` the list is empty and the interface is English.
/// `CRAFT_I18N_REQUIRED=1` makes a missing or empty checkout an error (for releases).
fn craft_i18n() -> String {
println!("cargo:rerun-if-env-changed=CRAFT_I18N_DIR");
let required = required("CRAFT_I18N_REQUIRED");
let entries = match std::env::var_os("CRAFT_I18N_DIR").filter(|d| !d.is_empty()) {
// Not canonicalized: on Windows that gives `\\?\C:\…`.
Some(dir) => i18n_locales(&PathBuf::from(dir).join("locales")).unwrap_or_else(|e| {
if required {
fail(&format!("CRAFT_I18N_REQUIRED=1 but CRAFT_I18N_DIR: {e}"));
}
println!("cargo:warning=CRAFT_I18N_DIR: {e}; the interface is English only");
Vec::new()
}),
None => {
if required {
fail("CRAFT_I18N_REQUIRED=1 but CRAFT_I18N_DIR is not set");
}
Vec::new()
}
};
let mut code = String::from("// Generated by build.rs (CRAFT_I18N_DIR catalog input).\npub static CRAFT_I18N: &[(&str, &str, &str)] = &[\n");
let include = |p: &Option<PathBuf>| p.as_ref().map_or_else(|| "\"\"".to_string(), |p| format!("include_str!({:?})", p.display().to_string()));
for (locale, common, app) in entries {
code.push_str(&format!(" ({locale:?}, {}, {}),\n", include(&common), include(&app)));
}
code.push_str("];\n");
code
}
/// `(locale, common.tsv, anicraft.tsv)` for every locale under `dir` with AniCraft's catalog,
/// and for the base language of each regional one.
type I18nEntry = (String, Option<PathBuf>, Option<PathBuf>);
fn i18n_locales(dir: &Path) -> Result<Vec<I18nEntry>, String> {
// `include_str!` resolves a relative path against the generated file, not this crate.
if !dir.is_absolute() {
return Err(format!("{} is not an absolute path", dir.display()));
}
let list = std::fs::read_dir(dir).map_err(|e| format!("{} is not a craft-i18n checkout ({e})", dir.display()))?;
println!("cargo:rerun-if-changed={}", dir.display());
let file = |locale: &str, name: &str| Some(dir.join(locale).join(name)).filter(|p| p.is_file());
let mut wanted: Vec<String> = Vec::new();
for path in list.flatten().map(|e| e.path()) {
let Some(locale) = path.file_name().and_then(|n| n.to_str()).map(str::to_ascii_lowercase) else { continue };
if !path.join(APP_CATALOG).is_file() {
continue;
}
// A regional locale (last subtag two letters or three digits) falls back to its base.
if let Some((base, region)) = locale.rsplit_once('-')
&& ((region.len() == 2 && region.chars().all(|c| c.is_ascii_alphabetic())) || (region.len() == 3 && region.chars().all(|c| c.is_ascii_digit())))
&& dir.join(base).is_dir()
{
wanted.push(base.to_string());
}
wanted.push(locale);
}
wanted.sort();
wanted.dedup();
if wanted.is_empty() {
return Err(format!("{} has no locale with {APP_CATALOG} yet", dir.display()));
}
let mut out = Vec::new();
for locale in wanted {
let (common, app) = (file(&locale, "common.tsv"), file(&locale, APP_CATALOG));
for p in common.iter().chain(app.iter()) {
println!("cargo:rerun-if-changed={}", p.display());
}
out.push((locale, common, app));
}
Ok(out)
}