mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-30 10:03:56 +01:00
Auto: Integrate main and resolve catalog embedding conflict
Preserve distinct-character collection for font subsetting alongside main's catalog accessor and compressed wasm embedding. Exercise the generated accessor with both populated and empty catalogs.
This commit is contained in:
commit
b1a0944f89
22 files changed
+847
-49
No files matched your search
@@ -4,10 +4,10 @@
|
||||
"repository_id": 1419654881,
|
||||
"producer_workflow_id": 429738073,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "f94a43818dabb2e85f2f4d5cd768bb8e5662600a",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a",
|
||||
"producer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "f94a43818dabb2e85f2f4d5cd768bb8e5662600a",
|
||||
"signer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
|
||||
@@ -34,12 +34,26 @@ jobs:
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
with:
|
||||
tooling-revision: f94a43818dabb2e85f2f4d5cd768bb8e5662600a
|
||||
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
app-name: texturecraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
# No secrets: inherit or raw platform values in this caller. Only the isolated native
|
||||
# callee job may bind the release environment and export its keys; that environment must
|
||||
# admit nightly-signer alongside release before the first dispatch.
|
||||
@@ -22,9 +22,9 @@ jobs:
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
with:
|
||||
tooling-revision: f94a43818dabb2e85f2f4d5cd768bb8e5662600a
|
||||
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
app-name: texturecraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc
|
||||
|
||||
Generated
+1
@@ -6173,6 +6173,7 @@ dependencies = [
|
||||
"egui",
|
||||
"egui-phosphor",
|
||||
"egui_kittest",
|
||||
"flate2",
|
||||
"image",
|
||||
"js-sys",
|
||||
"log",
|
||||
|
||||
+15
-1
@@ -138,12 +138,26 @@ codegen-units = 16
|
||||
|
||||
[profile.wasm-release]
|
||||
inherits = "release"
|
||||
opt-level = "s"
|
||||
# "z" over "s": the browser build must stay under the 24 MiB gate in packaging/web/package.sh.
|
||||
# Measured on main 7c8dd1ae: 30,812,862 bytes with "s", 26,654,524 bytes with the levels below.
|
||||
opt-level = "z"
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
strip = "debuginfo"
|
||||
|
||||
[profile.wasm-release.package."*"]
|
||||
opt-level = "z"
|
||||
|
||||
# Kept at "s": these rely on inlining, and at "z" they come out larger, not smaller.
|
||||
[profile.wasm-release.package.fearless_simd]
|
||||
opt-level = "s"
|
||||
[profile.wasm-release.package.vello_cpu]
|
||||
opt-level = "s"
|
||||
[profile.wasm-release.package.vello_common]
|
||||
opt-level = "s"
|
||||
[profile.wasm-release.package.craft-image-codecs]
|
||||
opt-level = "s"
|
||||
[profile.wasm-release.package.texturecraft-core]
|
||||
opt-level = "s"
|
||||
|
||||
[profile.wasm-release.package.texturecraft-texel]
|
||||
|
||||
@@ -18,8 +18,9 @@ texturecraft-engine = { workspace = true }
|
||||
texturecraft-ui-egui = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "persistence"] }
|
||||
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. No `default_fonts`: the UI takes egui's faces
|
||||
# from craft-ui's deflated copies (the wasm is under a download budget).
|
||||
eframe = { workspace = true, features = ["wgpu", "accesskit", "persistence"] }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
|
||||
@@ -178,13 +178,21 @@ fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>,
|
||||
/// Nightly's writes at another app's files.
|
||||
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
|
||||
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
|
||||
let child = canonical_future(&chosen.join(name))?;
|
||||
let entry = chosen.join(name);
|
||||
let metadata = std::fs::symlink_metadata(&entry).map_err(|e| format!("cannot inspect the nightly {label}: {e}"))?;
|
||||
if !metadata.is_dir() {
|
||||
return Err(format!("the nightly {label} must be a directory inside its selected profile"));
|
||||
}
|
||||
let child = canonical_future(&entry)?;
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
/// Known folder-only entries directly inside a Nightly profile.
|
||||
const PROFILE_FOLDERS: [&str; 10] = ["autosave", "logs", "cache", "library", "layouts", "templates", "brushes", "export", "export-presets", "Samples"];
|
||||
|
||||
/// Every existing entry directly in the profile (autosave, logs, library and so on) must resolve
|
||||
/// inside it.
|
||||
fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
@@ -195,11 +203,56 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
let path = entry.path();
|
||||
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
// Settings and session state are ordinary files, not directories. Keep the existing
|
||||
// directory-boundary check for folders (including the known folder-only entries).
|
||||
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
|
||||
if metadata.is_file() && !folder_only {
|
||||
private_regular_file(&path, &metadata)?;
|
||||
} else {
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persisted files must have their own ordinary file identity, not an alias to other data.
|
||||
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
if metadata.nlink() != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use winsafe::{HFILE, co};
|
||||
let (file, _) = HFILE::CreateFile(
|
||||
path.to_str().ok_or("the nightly profile file path is not textual")?,
|
||||
co::GENERIC::default(),
|
||||
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
|
||||
None,
|
||||
co::DISPOSITION::OPEN_EXISTING,
|
||||
co::FILE_ATTRIBUTE::NORMAL,
|
||||
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
|
||||
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
|
||||
return Err("the nightly profile file must not be an alias or directory".into());
|
||||
}
|
||||
if info.nNumberOfLinks != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
let _ = (path, metadata);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The app's writable probe: create a file exclusively in the profile and remove it again.
|
||||
pub fn ensure_writable(dir: &Path) -> std::io::Result<()> {
|
||||
let probe = dir.join("exclusive-write-probe");
|
||||
@@ -474,6 +527,31 @@ mod tests {
|
||||
assert!(fixture.check(Platform::Linux, &fixture.home().join("Documents").join(BRAND)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
|
||||
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
for name in ["app.ron", "ui.json", "errors.log", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(private.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
for name in PROFILE_FOLDERS {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
assert_eq!(std::fs::read(private.join("app.ron")).unwrap(), b"saved profile data");
|
||||
for name in PROFILE_FOLDERS {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_profile_whose_existing_ancestor_is_a_link_resolves_before_the_fence() {
|
||||
|
||||
@@ -18,12 +18,13 @@ texturecraft-paint = { workspace = true }
|
||||
texturecraft-bake = { workspace = true }
|
||||
texturecraft-formats = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
epaint_default_fonts = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# The built-in text fonts; the web build gets them from the app (`text_cmds::provide_built_in_fonts`).
|
||||
epaint_default_fonts = { workspace = true }
|
||||
tempfile = "3"
|
||||
|
||||
[target.'cfg(any(target_os = "macos", target_os = "freebsd"))'.dependencies]
|
||||
|
||||
@@ -24,7 +24,38 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
/// Fonts bundled with the app (egui's), used when nothing is installed or in the browser.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const BUILT_IN: [(&str, &[u8]); 2] = [("Ubuntu Light", epaint_default_fonts::UBUNTU_LIGHT), ("Hack", epaint_default_fonts::HACK_REGULAR)];
|
||||
/// The built-in fonts' names, in [`provide_built_in_fonts`]'s order.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
const BUILT_IN_NAMES: [&str; 2] = ["Ubuntu Light", "Hack"];
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
static BUILT_IN_SOURCE: std::sync::OnceLock<fn() -> [&'static [u8]; 2]> = std::sync::OnceLock::new();
|
||||
|
||||
/// The web build's built-in fonts, Ubuntu Light and Hack, from `source`. The browser app already carries egui's faces
|
||||
/// (deflated, for its download budget), so it says where to get them instead of the engine embedding a second, raw
|
||||
/// copy. `source` runs once, when text first needs a built-in font. Only the first call counts.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn provide_built_in_fonts(source: fn() -> [&'static [u8]; 2]) {
|
||||
let _ = BUILT_IN_SOURCE.set(source);
|
||||
}
|
||||
|
||||
/// The built-in fonts: names and bytes. On the web the bytes are empty without [`provide_built_in_fonts`].
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn built_in() -> [(&'static str, &'static [u8]); 2] {
|
||||
static BYTES: std::sync::OnceLock<[&'static [u8]; 2]> = std::sync::OnceLock::new();
|
||||
let bytes = match BUILT_IN_SOURCE.get() {
|
||||
Some(source) => *BYTES.get_or_init(*source),
|
||||
None => [&[] as &[u8], &[]],
|
||||
};
|
||||
[(BUILT_IN_NAMES[0], bytes[0]), (BUILT_IN_NAMES[1], bytes[1])]
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn built_in() -> [(&'static str, &'static [u8]); 2] {
|
||||
BUILT_IN
|
||||
}
|
||||
|
||||
/// Families tried, in order, when no font is asked for.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const DEFAULT_FAMILIES: [&str; 6] = ["Arial", "Segoe UI", "Helvetica", "Liberation Sans", "DejaVu Sans", "Noto Sans"];
|
||||
@@ -54,7 +85,7 @@ fn fonts() -> Value {
|
||||
let families: Vec<(String, Vec<String>)> = Vec::new();
|
||||
json!({
|
||||
"installed": families.into_iter().map(|(family, styles)| json!({"family": family, "styles": styles})).collect::<Vec<_>>(),
|
||||
"builtIn": BUILT_IN.map(|(name, _)| name),
|
||||
"builtIn": built_in().map(|(name, _)| name),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -62,7 +93,8 @@ fn fonts() -> Value {
|
||||
/// or the first default family installed, else the built-in font.
|
||||
fn font_bytes(family: Option<&str>, style: Option<&str>) -> Result<(std::borrow::Cow<'static, [u8]>, u32)> {
|
||||
let is = |a: &str, b: &str| a.eq_ignore_ascii_case(b);
|
||||
if let Some((_, bytes)) = BUILT_IN.iter().find(|(name, _)| family.is_some_and(|f| is(f, name))) {
|
||||
let built_in = built_in();
|
||||
if let Some((_, bytes)) = built_in.iter().find(|(name, _)| family.is_some_and(|f| is(f, name))) {
|
||||
return Ok((std::borrow::Cow::Borrowed(bytes), 0));
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -91,7 +123,7 @@ fn font_bytes(family: Option<&str>, style: Option<&str>) -> Result<(std::borrow:
|
||||
let _ = style;
|
||||
match family {
|
||||
Some(f) => Err(bad("resource.text", format!("no font family `{f}` (see text.fonts)"))),
|
||||
None => Ok((std::borrow::Cow::Borrowed(BUILT_IN[0].1), 0)),
|
||||
None => Ok((std::borrow::Cow::Borrowed(built_in[0].1), 0)),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,8 @@ workspace = true
|
||||
chrono = { workspace = true }
|
||||
texturecraft-engine = { workspace = true }
|
||||
texturecraft-render = { workspace = true }
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "persistence"] }
|
||||
# egui's default fonts: on desktop from egui; the web build uses craft-ui's deflated copies (`fonts::egui_default_definitions`).
|
||||
eframe = { workspace = true, features = ["wgpu", "persistence"] }
|
||||
egui = { workspace = true }
|
||||
craft-ui = { workspace = true }
|
||||
craft-behavior = { workspace = true }
|
||||
@@ -32,6 +33,7 @@ craft-image-codecs = { workspace = true }
|
||||
|
||||
# The OS UI language for the first run (MIT OR Apache-2.0; the browser asks `navigator.language`).
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
eframe = { workspace = true, features = ["default_fonts"] }
|
||||
sys-locale = "0.3"
|
||||
# Help > Check for Updates and the check at start (updates_ui.rs).
|
||||
craft-update = { workspace = true }
|
||||
@@ -61,12 +63,16 @@ zbus = { version = "5.19", default-features = false, features = ["async-io", "bl
|
||||
# versions craft-libs' craft-fonts-build subsets with).
|
||||
[build-dependencies]
|
||||
craft-i18n = { workspace = true }
|
||||
# The web build embeds its fonts and catalogs deflated (build.rs, `fonts::CraftFont`, `i18n`).
|
||||
flate2 = { workspace = true }
|
||||
skera = "0.8"
|
||||
skrifa = { version = "0.48", default-features = false, features = ["std"] }
|
||||
|
||||
# Browser file I/O (web_files.rs): async pickers and Blob downloads.
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
craft-zip = { workspace = true }
|
||||
# Inflates the embedded fonts and catalogs of the web build.
|
||||
flate2 = { workspace = true }
|
||||
rfd = { workspace = true }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
@@ -74,6 +80,8 @@ js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "CssStyleDeclaration", "Navigator"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# build.rs's `i18n_build.rs`, which tests/i18n_build.rs includes.
|
||||
flate2 = { workspace = true }
|
||||
craft-zip = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
|
||||
|
||||
+46
-2
@@ -33,6 +33,7 @@ type Faces = &'static [(&'static str, &'static str)];
|
||||
|
||||
fn main() {
|
||||
let catalogs = i18n_build::embed();
|
||||
deflate_assets();
|
||||
println!("cargo::rerun-if-env-changed=CRAFT_FONTS_DIR");
|
||||
println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED");
|
||||
let mut src = String::from("pub static CRAFT_FONTS: &[CraftFont] = &[\n");
|
||||
@@ -89,15 +90,23 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web:
|
||||
let bytes = std::fs::read(&path).map_err(|e| format!("{file}: {e}"))?;
|
||||
let cut =
|
||||
if rel == LATIN_MANIFEST { without_private_use(&bytes) } else { cut_to_catalogs(&bytes, catalogs) }.map_err(|e| format!("{file}: {e}"))?;
|
||||
let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join(path.file_name().unwrap_or_default());
|
||||
let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join(out_name(file, ""));
|
||||
std::fs::write(&out, cut).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
path = out;
|
||||
}
|
||||
|
||||
// The web build embeds its faces deflated: the wasm is under a download budget and fonts halve.
|
||||
if wasm {
|
||||
let bytes = std::fs::read(&path).map_err(|e| format!("{file}: {e}"))?;
|
||||
let deflated = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join(out_name(file, ".deflate"));
|
||||
std::fs::write(&deflated, i18n_build::deflate(&bytes)?).map_err(|e| format!("{}: {e}", deflated.display()))?;
|
||||
path = deflated;
|
||||
}
|
||||
|
||||
let scripts: Vec<String> = tags.iter().map(|s| format!("{s:?}")).collect();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" CraftFont {{ family: {family:?}, style: {style:?}, scripts: &[{}], bytes: include_bytes!({:?}) }},",
|
||||
" CraftFont {{ family: {family:?}, style: {style:?}, scripts: &[{}], data: include_bytes!({:?}), deflated: {wasm} }},",
|
||||
scripts.join(", "),
|
||||
path.display().to_string(),
|
||||
);
|
||||
@@ -156,3 +165,38 @@ fn subset(font: &FontRef, unicodes: &IntSet<u32>) -> Result<Vec<u8>, String> {
|
||||
);
|
||||
subset_font(font, &plan).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// A face's file name under `OUT_DIR`: its path in the craft-fonts checkout with every separator flattened, so faces
|
||||
/// that share a file name (`jp/Regular.ttf`, `ar/Regular.ttf`) stay apart.
|
||||
fn out_name(file: &str, suffix: &str) -> String {
|
||||
let flat: String = file.chars().map(|c| if c.is_ascii_alphanumeric() || c == '.' || c == '-' { c } else { '_' }).collect();
|
||||
format!("craft-font-{flat}{suffix}")
|
||||
}
|
||||
|
||||
/// The files a web build embeds deflated (the wasm is under a download budget): the icon font and the studio
|
||||
/// environment, from this crate's directory to the name they have under `OUT_DIR` (`name.deflate`). The other builds
|
||||
/// include the files themselves.
|
||||
const DEFLATED_ASSETS: &[(&str, &str)] =
|
||||
&[("../../vendor/egui-phosphor/res/Phosphor.ttf", "Phosphor.ttf"), ("../../assets/hdr/studio_small_09_512.hdr", "studio_small_09_512.hdr")];
|
||||
|
||||
/// Writes [`DEFLATED_ASSETS`] under `OUT_DIR` for the web build.
|
||||
fn deflate_assets() {
|
||||
if !std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32") {
|
||||
return;
|
||||
}
|
||||
|
||||
let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default());
|
||||
let manifest = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default());
|
||||
for (source, name) in DEFLATED_ASSETS {
|
||||
let source = manifest.join(source);
|
||||
println!("cargo::rerun-if-changed={}", source.display());
|
||||
let target = out.join(format!("{name}.deflate"));
|
||||
let written = std::fs::read(&source)
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|bytes| i18n_build::deflate(&bytes))
|
||||
.and_then(|d| std::fs::write(&target, d).map_err(|e| e.to_string()));
|
||||
if let Err(e) = written {
|
||||
println!("cargo::error={}: {e}", source.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,15 +4,64 @@ use std::path::Path;
|
||||
|
||||
/// The catalogs' Rust includes and the distinct characters they use, sorted: the web build cuts
|
||||
/// its CJK interface face to those characters.
|
||||
#[allow(dead_code)] // used by tests/i18n_build.rs, not by build.rs
|
||||
pub fn collect(dir: Option<&Path>, required: bool) -> Result<(String, Vec<char>), String> {
|
||||
let mut source = String::from("pub static CRAFT_I18N: &craft_i18n::Embedded = &[\n");
|
||||
collect_into(dir, required, None)
|
||||
}
|
||||
|
||||
/// `bytes` deflated (raw deflate, as `flate2::read::DeflateDecoder` reads it).
|
||||
pub fn deflate(bytes: &[u8]) -> Result<Vec<u8>, String> {
|
||||
use std::io::Write as _;
|
||||
let mut encoder = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::best());
|
||||
encoder.write_all(bytes).map_err(|e| e.to_string())?;
|
||||
encoder.finish().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// What the generated source does with the catalogs' text. A web build downloads the wasm, so it embeds each catalog
|
||||
/// deflated (written under `out`) and inflates all of them on first use; other builds embed the text itself.
|
||||
const INFLATE_FN: &str = r#"
|
||||
fn inflate_text(deflated: &[u8]) -> &'static str {
|
||||
use std::io::Read as _;
|
||||
let mut text = String::new();
|
||||
// A catalog that does not inflate leaves its language without translations, never a panic.
|
||||
if flate2::read::DeflateDecoder::new(deflated).take(64 << 20).read_to_string(&mut text).is_err() {
|
||||
text.clear();
|
||||
}
|
||||
Box::leak(text.into_boxed_str())
|
||||
}
|
||||
|
||||
pub fn craft_i18n_catalogs() -> &'static craft_i18n::Embedded {
|
||||
static CATALOGS: std::sync::OnceLock<&'static craft_i18n::Embedded> = std::sync::OnceLock::new();
|
||||
CATALOGS.get_or_init(|| {
|
||||
let catalogs: Vec<(&'static str, &'static str, &'static str)> =
|
||||
CRAFT_I18N_DEFLATED.iter().map(|&(locale, common, app)| (locale, inflate_text(common), inflate_text(app))).collect();
|
||||
Box::leak(catalogs.into_boxed_slice())
|
||||
})
|
||||
}
|
||||
"#;
|
||||
|
||||
/// [`collect`], embedding the catalogs deflated under the directory `deflated_in` when it is given.
|
||||
pub fn collect_into(dir: Option<&Path>, required: bool, deflated_in: Option<&Path>) -> Result<(String, Vec<char>), String> {
|
||||
let mut source = match deflated_in {
|
||||
Some(_) => String::from("static CRAFT_I18N_DEFLATED: &[(&str, &[u8], &[u8])] = &[\n"),
|
||||
None => String::from("pub static CRAFT_I18N: &craft_i18n::Embedded = &[\n"),
|
||||
};
|
||||
let finish_source = |mut source: String| {
|
||||
source.push_str("];\n");
|
||||
source.push_str(if deflated_in.is_some() {
|
||||
INFLATE_FN
|
||||
} else {
|
||||
"\npub fn craft_i18n_catalogs() -> &'static craft_i18n::Embedded {\n CRAFT_I18N\n}\n"
|
||||
});
|
||||
source
|
||||
};
|
||||
|
||||
let Some(dir) = dir else {
|
||||
if required {
|
||||
return Err("CRAFT_I18N_REQUIRED=1 requires CRAFT_I18N_DIR".into());
|
||||
}
|
||||
|
||||
source.push_str("];\n");
|
||||
return Ok((source, Vec::new()));
|
||||
return Ok((finish_source(source), Vec::new()));
|
||||
};
|
||||
|
||||
if !dir.is_absolute() {
|
||||
@@ -22,6 +71,7 @@ pub fn collect(dir: Option<&Path>, required: bool) -> Result<(String, Vec<char>)
|
||||
let locales = dir.join("locales");
|
||||
let entries = std::fs::read_dir(&locales).map_err(|e| format!("{}: {e}", locales.display()))?;
|
||||
println!("cargo::rerun-if-changed={}", locales.display());
|
||||
|
||||
let mut paths = Vec::new();
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| e.to_string())?;
|
||||
@@ -34,6 +84,7 @@ pub fn collect(dir: Option<&Path>, required: bool) -> Result<(String, Vec<char>)
|
||||
let mut count = 0;
|
||||
let mut catalogs = Vec::new();
|
||||
let mut characters = std::collections::HashSet::new();
|
||||
|
||||
for path in paths {
|
||||
// Watch directories so adding or removing an app catalog rebuilds the embedding
|
||||
println!("cargo::rerun-if-changed={}", path.display());
|
||||
@@ -49,10 +100,21 @@ pub fn collect(dir: Option<&Path>, required: bool) -> Result<(String, Vec<char>)
|
||||
let name = file.to_str().ok_or("non-UTF-8 catalog path")?;
|
||||
println!("cargo::rerun-if-changed={name}");
|
||||
|
||||
let include = match deflated_in {
|
||||
Some(out) => {
|
||||
let copy = out.join(format!("{locale}.{}.deflate", file.file_stem().and_then(|n| n.to_str()).unwrap_or("catalog")));
|
||||
std::fs::write(©, deflate(text.as_bytes())?).map_err(|e| format!("{}: {e}", copy.display()))?;
|
||||
format!("include_bytes!({:?})", copy.display().to_string())
|
||||
}
|
||||
None => format!("include_str!({name:?})"),
|
||||
};
|
||||
|
||||
// The shared runtime needs static inputs for this short-lived build process
|
||||
Ok((format!("include_str!({name:?})"), Box::leak(text.into_boxed_str())))
|
||||
Ok((include, Box::leak(text.into_boxed_str())))
|
||||
};
|
||||
let (shared, shared_text) = if common.is_file() { embed(&common)? } else { ("\"\"".into(), "") };
|
||||
|
||||
let empty = if deflated_in.is_some() { "&[]" } else { "\"\"" };
|
||||
let (shared, shared_text) = if common.is_file() { embed(&common)? } else { (empty.into(), "") };
|
||||
let (app, app_text) = embed(&app)?;
|
||||
characters.extend(shared_text.chars().chain(app_text.chars()));
|
||||
let code: &'static str = Box::leak(locale.to_owned().into_boxed_str());
|
||||
@@ -60,6 +122,7 @@ pub fn collect(dir: Option<&Path>, required: bool) -> Result<(String, Vec<char>)
|
||||
let _ = writeln!(source, " ({locale:?}, {shared}, {app}),");
|
||||
count += 1;
|
||||
}
|
||||
|
||||
if required && count == 0 {
|
||||
return Err("no TextureCraft translation catalogs found".into());
|
||||
}
|
||||
@@ -71,10 +134,9 @@ pub fn collect(dir: Option<&Path>, required: bool) -> Result<(String, Vec<char>)
|
||||
return Err(format!("invalid translation catalogs in {}: {}", locales.display(), problems.join("; ")));
|
||||
}
|
||||
|
||||
source.push_str("];\n");
|
||||
let mut characters: Vec<_> = characters.into_iter().collect();
|
||||
characters.sort_unstable();
|
||||
Ok((source, characters))
|
||||
Ok((finish_source(source), characters))
|
||||
}
|
||||
|
||||
/// Write the embedding for both desktop and wasm, reporting optional failures as warnings.
|
||||
@@ -87,7 +149,9 @@ pub fn embed() -> Vec<char> {
|
||||
println!("cargo::rerun-if-env-changed=CRAFT_I18N_REQUIRED");
|
||||
let dir = std::env::var_os("CRAFT_I18N_DIR").map(std::path::PathBuf::from);
|
||||
let required = std::env::var("CRAFT_I18N_REQUIRED").is_ok_and(|v| v == "1");
|
||||
let (source, characters) = match collect(dir.as_deref(), required) {
|
||||
let out_dir = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default());
|
||||
let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32");
|
||||
let (source, characters) = match collect_into(dir.as_deref(), required, wasm.then_some(out_dir.as_path())) {
|
||||
Ok(embedded) => embedded,
|
||||
Err(error) => {
|
||||
if required {
|
||||
@@ -95,13 +159,22 @@ pub fn embed() -> Vec<char> {
|
||||
} else {
|
||||
println!("cargo::warning=building without craft-i18n: {error}");
|
||||
}
|
||||
("pub static CRAFT_I18N: &craft_i18n::Embedded = &[];\n".into(), Vec::new())
|
||||
(empty_embedding(wasm), Vec::new())
|
||||
}
|
||||
};
|
||||
|
||||
let out = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_i18n.rs");
|
||||
let out = out_dir.join("craft_i18n.rs");
|
||||
if let Err(error) = std::fs::write(&out, source) {
|
||||
println!("cargo::error=writing {}: {error}", out.display());
|
||||
}
|
||||
characters
|
||||
}
|
||||
|
||||
/// The embedding of a build without catalogs.
|
||||
fn empty_embedding(deflated: bool) -> String {
|
||||
if deflated {
|
||||
format!("static CRAFT_I18N_DEFLATED: &[(&str, &[u8], &[u8])] = &[];\n{INFLATE_FN}")
|
||||
} else {
|
||||
"pub static CRAFT_I18N: &craft_i18n::Embedded = &[];\n\npub fn craft_i18n_catalogs() -> &'static craft_i18n::Embedded {\n CRAFT_I18N\n}\n".into()
|
||||
}
|
||||
}
|
||||
+101
-3
@@ -23,11 +23,109 @@ pub struct CraftFont {
|
||||
pub style: &'static str,
|
||||
/// ISO 15924 scripts the font is for, e.g. `"Jpan"`.
|
||||
pub scripts: &'static [&'static str],
|
||||
pub bytes: &'static [u8],
|
||||
/// The font file; deflated in a web build, where the data is part of the download (see `deflated`).
|
||||
data: &'static [u8],
|
||||
deflated: bool,
|
||||
}
|
||||
|
||||
impl CraftFont {
|
||||
/// Whether this build carries no data for the font.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.data.is_empty()
|
||||
}
|
||||
|
||||
/// The font file's bytes: borrowed as embedded, or inflated from the web build's copy. Data that does not inflate
|
||||
/// gives no bytes (the font is left out), never a panic.
|
||||
pub fn bytes(&self) -> std::borrow::Cow<'static, [u8]> {
|
||||
if self.deflated { std::borrow::Cow::Owned(inflate(self.data)) } else { std::borrow::Cow::Borrowed(self.data) }
|
||||
}
|
||||
|
||||
/// The font as egui takes it, without copying an embedded one.
|
||||
pub fn font_data(&self) -> FontData {
|
||||
match self.bytes() {
|
||||
std::borrow::Cow::Borrowed(bytes) => FontData::from_static(bytes),
|
||||
std::borrow::Cow::Owned(bytes) => FontData::from_owned(bytes),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
include!(concat!(env!("OUT_DIR"), "/craft_fonts.rs"));
|
||||
|
||||
/// Inflates a font the web build embeds deflated. Empty when the data does not inflate.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn inflate(deflated: &[u8]) -> Vec<u8> {
|
||||
use std::io::Read as _;
|
||||
// The largest face is under 1 MB; the bound keeps corrupt data from growing without limit.
|
||||
const MAX_INFLATED_BYTES: u64 = 64 << 20;
|
||||
let mut out = Vec::new();
|
||||
match flate2::read::DeflateDecoder::new(deflated).take(MAX_INFLATED_BYTES + 1).read_to_end(&mut out) {
|
||||
Ok(_) if out.len() as u64 <= MAX_INFLATED_BYTES => out,
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the Phosphor icon font to `fonts`: the font itself on desktop, the web build's deflated copy there (the icon
|
||||
/// font is half a megabyte of the download). Icons draw as missing-glyph boxes if the copy does not inflate.
|
||||
pub(crate) fn add_icon_font(fonts: &mut egui::FontDefinitions) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
egui_phosphor::add_to_fonts(fonts, egui_phosphor::Variant::Regular);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
static PHOSPHOR: std::sync::OnceLock<&'static [u8]> = std::sync::OnceLock::new();
|
||||
let bytes = PHOSPHOR.get_or_init(|| Vec::leak(inflate(include_bytes!(concat!(env!("OUT_DIR"), "/Phosphor.ttf.deflate")))));
|
||||
if bytes.is_empty() {
|
||||
log::warn!("the icon font did not inflate; icons show as boxes");
|
||||
} else {
|
||||
egui_phosphor::add_font_bytes_to_fonts(fonts, "phosphor", bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// egui's default fonts (Hack, Ubuntu Light and egui's icons, in egui's family order). The web build takes them from
|
||||
/// craft-ui's deflated copies instead of egui's `default_fonts` feature, which would embed a second, raw copy, and it
|
||||
/// hands the engine its built-in text fonts from the same copies.
|
||||
pub(crate) fn egui_default_definitions() -> egui::FontDefinitions {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
egui::FontDefinitions::default()
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
texturecraft_engine::text_cmds::provide_built_in_fonts(engine_fonts);
|
||||
let mut fonts = craft_ui::fonts::deflated_default_definitions();
|
||||
// craft-ui's Inter: TextureCraft adds its own (`theme::font_definitions`) and its own semibold family.
|
||||
for name in ["Inter-Regular", "Inter-SemiBold"] {
|
||||
fonts.font_data.remove(name);
|
||||
}
|
||||
fonts.families.remove(&FontFamily::Name(craft_ui::fonts::SEMIBOLD.into()));
|
||||
let known: Vec<String> = fonts.font_data.keys().cloned().collect();
|
||||
for list in fonts.families.values_mut() {
|
||||
list.retain(|name| known.contains(name));
|
||||
}
|
||||
fonts
|
||||
}
|
||||
}
|
||||
|
||||
/// The engine's built-in text fonts, Ubuntu Light and Hack, copied once from the deflated defaults. Empty when a face
|
||||
/// is unavailable (the text command then reports the font as unusable).
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn engine_fonts() -> [&'static [u8]; 2] {
|
||||
let fonts = craft_ui::fonts::deflated_default_definitions();
|
||||
let face = |name: &str| -> &'static [u8] {
|
||||
match fonts.font_data.get(name) {
|
||||
Some(data) => Vec::leak((*data.font).as_ref().to_vec()),
|
||||
None => &[],
|
||||
}
|
||||
};
|
||||
[face("Ubuntu-Light"), face("Hack")]
|
||||
}
|
||||
|
||||
/// Only the web build embeds deflated data.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn inflate(_deflated: &[u8]) -> Vec<u8> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Skip absurdly large files (a corrupt or non-font path must not eat memory).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_FONT_BYTES: u64 = 128 << 20;
|
||||
@@ -186,8 +284,8 @@ impl UiFonts {
|
||||
|
||||
/// The first available font for `script`: craft-fonts' (embedded), then the system's.
|
||||
fn load(script: Script) -> Option<FontData> {
|
||||
if let Some(f) = CRAFT_FONTS.iter().find(|f| f.scripts.contains(&script.iso()) && f.style == "Regular" && !f.bytes.is_empty()) {
|
||||
return Some(aligned(FontData::from_static(f.bytes)));
|
||||
if let Some(f) = CRAFT_FONTS.iter().find(|f| f.scripts.contains(&script.iso()) && f.style == "Regular" && !f.is_empty()) {
|
||||
return Some(aligned(f.font_data()));
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
for (path, index) in script.system_files() {
|
||||
|
||||
@@ -9,7 +9,7 @@ include!(concat!(env!("OUT_DIR"), "/craft_i18n.rs"));
|
||||
|
||||
static I18N: LazyLock<craft_i18n::I18n> = LazyLock::new(|| {
|
||||
let offered: Vec<_> = LANGUAGES.iter().map(|l| l.code).collect();
|
||||
let (i18n, problems) = craft_i18n::I18n::new(CRAFT_I18N, &offered);
|
||||
let (i18n, problems) = craft_i18n::I18n::new(craft_i18n_catalogs(), &offered);
|
||||
for problem in problems {
|
||||
log::warn!("translation catalog: {problem}");
|
||||
}
|
||||
@@ -377,7 +377,7 @@ mod tests",
|
||||
let keys = keys();
|
||||
assert!(keys.len() > 300, "found only {} keys", keys.len());
|
||||
let used: BTreeSet<_> = keys.iter().map(String::as_str).collect();
|
||||
for &(locale, common, app) in CRAFT_I18N {
|
||||
for &(locale, common, app) in craft_i18n_catalogs() {
|
||||
let Some(lang) = I18N.from_code(locale) else { continue };
|
||||
let missing: Vec<_> = keys.iter().filter(|key| I18N.get(lang, "", key).is_none()).collect();
|
||||
|
||||
|
||||
@@ -7,7 +7,11 @@ use texturecraft_engine::geom::glam::Vec3;
|
||||
use texturecraft_render::ibl::{self, EnvImage};
|
||||
|
||||
/// The bundled environment: a small photo studio with soft boxes, 512 x 256 equirect Radiance HDR
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const STUDIO_HDR: &[u8] = include_bytes!("../../../assets/hdr/studio_small_09_512.hdr");
|
||||
/// The same file deflated by build.rs: the web build's wasm is under a download budget
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
const STUDIO_HDR_DEFLATED: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/studio_small_09_512.hdr.deflate"));
|
||||
|
||||
/// Prefiltered levels from mirror (0) to fully rough (last)
|
||||
const LEVELS: u32 = 6;
|
||||
@@ -15,6 +19,23 @@ const LEVELS: u32 = 6;
|
||||
/// How far the studio is turned about the vertical axis (radians) so its key soft box lights the orb from the upper left
|
||||
const TURN: f32 = 4.4;
|
||||
|
||||
/// The bundled file's bytes
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn studio_hdr() -> std::borrow::Cow<'static, [u8]> {
|
||||
std::borrow::Cow::Borrowed(STUDIO_HDR)
|
||||
}
|
||||
|
||||
/// The bundled file's bytes, inflated; none if the copy does not inflate (the studio falls back)
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn studio_hdr() -> std::borrow::Cow<'static, [u8]> {
|
||||
use std::io::Read as _;
|
||||
let mut out = Vec::new();
|
||||
match flate2::read::DeflateDecoder::new(STUDIO_HDR_DEFLATED).take(64 << 20).read_to_end(&mut out) {
|
||||
Ok(_) => std::borrow::Cow::Owned(out),
|
||||
Err(_) => std::borrow::Cow::Owned(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The prefiltered studio
|
||||
pub(crate) struct OrbEnvironment {
|
||||
/// Level `l` holds reflections for roughness `l / (LEVELS - 1)`
|
||||
@@ -27,7 +48,7 @@ impl OrbEnvironment {
|
||||
/// The studio, decoded and prefiltered by the first caller (about a tenth of a second in release)
|
||||
pub(crate) fn get() -> &'static OrbEnvironment {
|
||||
static STUDIO: OnceLock<OrbEnvironment> = OnceLock::new();
|
||||
STUDIO.get_or_init(|| OrbEnvironment::from_hdr(STUDIO_HDR).unwrap_or_else(OrbEnvironment::fallback))
|
||||
STUDIO.get_or_init(|| OrbEnvironment::from_hdr(&studio_hdr()).unwrap_or_else(OrbEnvironment::fallback))
|
||||
}
|
||||
|
||||
fn from_hdr(bytes: &[u8]) -> Option<OrbEnvironment> {
|
||||
|
||||
@@ -301,20 +301,20 @@ pub(crate) const HARD_SHADOW: Color32 = Color32::from_rgb(12, 14, 18);
|
||||
/// adds CJK).
|
||||
pub fn font_definitions() -> egui::FontDefinitions {
|
||||
use std::sync::Arc;
|
||||
let mut fonts = egui::FontDefinitions::default();
|
||||
let face = |style: &str| crate::fonts::CRAFT_FONTS.iter().find(|f| f.family == "Inter" && f.style == style && !f.bytes.is_empty());
|
||||
let mut fonts = crate::fonts::egui_default_definitions();
|
||||
let face = |style: &str| crate::fonts::CRAFT_FONTS.iter().find(|f| f.family == "Inter" && f.style == style && !f.is_empty());
|
||||
// Inter is drawn a little under its size, as in VectorCraft: its letters are wide.
|
||||
let inter = |bytes: &'static [u8]| Arc::new(egui::FontData::from_static(bytes).tweak(egui::FontTweak { scale: 0.92, ..Default::default() }));
|
||||
let inter = |face: &crate::fonts::CraftFont| Arc::new(face.font_data().tweak(egui::FontTweak { scale: 0.92, ..Default::default() }));
|
||||
let mut semibold = None;
|
||||
if let (Some(regular), Some(bold)) = (face("Regular"), face("SemiBold")) {
|
||||
fonts.font_data.insert("inter".into(), inter(regular.bytes));
|
||||
fonts.font_data.insert("inter-semibold".into(), inter(bold.bytes));
|
||||
fonts.font_data.insert("inter".into(), inter(regular));
|
||||
fonts.font_data.insert("inter-semibold".into(), inter(bold));
|
||||
if let Some(list) = fonts.families.get_mut(&FontFamily::Proportional) {
|
||||
list.insert(0, "inter".into());
|
||||
}
|
||||
semibold = Some("inter-semibold");
|
||||
}
|
||||
egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular);
|
||||
crate::fonts::add_icon_font(&mut fonts);
|
||||
// The semibold family: the regular family with its first face swapped for the weight.
|
||||
let mut list = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
|
||||
if let (Some(w), Some(first)) = (semibold, list.first_mut()) {
|
||||
|
||||
@@ -77,13 +77,26 @@ fn unreadable_catalog_fails_before_generating_rust_source() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_paths_compile_and_embed_the_catalog_contents() {
|
||||
fn generated_catalogs_are_readable_through_the_runtime_accessor() {
|
||||
let fixture = Fixture::new();
|
||||
std::fs::write(fixture.0.join("locales/es/texturecraft.tsv"), "\tLayers\tCapas\n").unwrap();
|
||||
let app = "\tLayers\tCapas\n";
|
||||
std::fs::write(fixture.0.join("locales/es/texturecraft.tsv"), app).unwrap();
|
||||
|
||||
let generated = generate(Some(&fixture.0), true).unwrap();
|
||||
let populated = generate(Some(&fixture.0), true).unwrap();
|
||||
let empty = generate(None, false).unwrap();
|
||||
let program = format!(
|
||||
"extern crate self as craft_i18n;\npub type Embedded = [(&'static str, &'static str, &'static str)];\n{generated}\nfn main() {{ assert_eq!(CRAFT_I18N[0].2, \"\\tLayers\\tCapas\\n\"); }}"
|
||||
r#"
|
||||
extern crate self as craft_i18n;
|
||||
pub type Embedded = [(&'static str, &'static str, &'static str)];
|
||||
|
||||
mod populated {{ {populated} }}
|
||||
mod empty {{ {empty} }}
|
||||
|
||||
fn main() {{
|
||||
assert_eq!(populated::craft_i18n_catalogs(), &[("es", "", {app:?})]);
|
||||
assert!(empty::craft_i18n_catalogs().is_empty());
|
||||
}}
|
||||
"#
|
||||
);
|
||||
let source = fixture.0.join("check.rs");
|
||||
let binary = fixture.0.join(format!("check{}", std::env::consts::EXE_SUFFIX));
|
||||
|
||||
@@ -35,11 +35,12 @@ OUTPUT="$DIST/texturecraft-$VERSION-macos-aarch64-nightly.zip"
|
||||
nightly_compile_gui
|
||||
|
||||
APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP"
|
||||
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
|
||||
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/docs"
|
||||
cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE"
|
||||
chmod 755 "$APP/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE"
|
||||
cp "$ROOT/assets/app-icon/$MAC_NIGHTLY_ICON.icns" "$APP/Contents/Resources/$MAC_NIGHTLY_ICON.icns"
|
||||
nightly_copy_notices "$APP/Contents/Resources"
|
||||
# Launcher admits notices under Resources/docs, not beside the icon.
|
||||
nightly_copy_notices "$APP/Contents/Resources/docs"
|
||||
# The private mktemp cwd is the helper authority root: stage the template inside it.
|
||||
cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in"
|
||||
(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \
|
||||
|
||||
@@ -6,8 +6,10 @@ crafted archive) as an argument, which is why packaging/macos/nightly_sign_tests
|
||||
app's ordinary Linux CI.
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import zipfile
|
||||
@@ -16,9 +18,18 @@ from pathlib import Path
|
||||
HERE = Path(__file__).resolve().parent
|
||||
LIB = HERE / "nightly-lib.sh"
|
||||
APP = "TextureCraft Nightly.app"
|
||||
APP_NOTICES = ("README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md")
|
||||
OPTIONAL_NOTICES = ("LICENSE", "COPYRIGHT")
|
||||
IDENTITY = "A" * 40
|
||||
TEAM = "DJ6XS33FX8"
|
||||
APP_CONFIG_ID = "ai.storyteller.texturecraft.nightly"
|
||||
COMMIT = "0123456789abcdef0123456789abcdef01234567"
|
||||
VERSION = "0.24.0-nightly.20261124.7.2.g" + COMMIT[:12]
|
||||
ASSET = f"texturecraft-{VERSION}-macos-aarch64-nightly.zip"
|
||||
SECRETS = (
|
||||
"APPLE_CERTIFICATE", "APPLE_CERTIFICATE_PASSWORD", "KEYCHAIN_PASSWORD",
|
||||
"APPLE_ID", "APPLE_PASSWORD", "APPLE_TEAM_ID", "MACOS_SIGN_IDENTITY", "MACOS_KEYCHAIN",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -178,5 +189,198 @@ class ZipEntries(unittest.TestCase):
|
||||
self.assertFalse(self.checked([*good, entry]), entry[0])
|
||||
|
||||
|
||||
class PackageFixture:
|
||||
"""Stand-in POSIX harness for driving packaging/macos/nightly.sh and nightly-verify.sh."""
|
||||
|
||||
def __init__(self, case):
|
||||
directory = tempfile.TemporaryDirectory()
|
||||
case.addCleanup(directory.cleanup)
|
||||
self.root = Path(directory.name).resolve()
|
||||
self.bin = self.root / "bin"
|
||||
self.dist = self.root / "dist"
|
||||
self.temp = self.root / "tmp"
|
||||
for path in (self.bin, self.dist, self.temp):
|
||||
path.mkdir()
|
||||
self._install_shims()
|
||||
|
||||
def _write_shim(self, name, body):
|
||||
path = self.bin / name
|
||||
path.write_text(body)
|
||||
path.chmod(0o755)
|
||||
|
||||
def _install_shims(self):
|
||||
python = sys.executable
|
||||
self._write_shim(
|
||||
"uname",
|
||||
"#!/bin/sh\n"
|
||||
"case \"$1\" in\n"
|
||||
" -s) echo Darwin ;;\n"
|
||||
" -m) echo arm64 ;;\n"
|
||||
" *) /usr/bin/uname \"$@\" ;;\n"
|
||||
"esac\n",
|
||||
)
|
||||
self._write_shim("lipo", "#!/bin/sh\necho arm64\n")
|
||||
self._write_shim(
|
||||
"plutil",
|
||||
f"#!{python}\n"
|
||||
"import plistlib, sys\n"
|
||||
"args = sys.argv[1:]\n"
|
||||
"if args[:1] == ['-lint']:\n"
|
||||
" with open(args[1], 'rb') as f:\n"
|
||||
" plistlib.load(f)\n"
|
||||
" sys.exit(0)\n"
|
||||
"if args[:1] == ['-extract'] and len(args) == 6 and args[3:5] == ['-o', '-']:\n"
|
||||
" key, fmt, plist_path = args[1], args[2], args[5]\n"
|
||||
" with open(plist_path, 'rb') as f:\n"
|
||||
" data = plistlib.load(f)\n"
|
||||
" if key not in data:\n"
|
||||
" sys.exit(1)\n"
|
||||
" value = data[key]\n"
|
||||
" if fmt == 'raw':\n"
|
||||
" print(value)\n"
|
||||
" else:\n"
|
||||
" print(plistlib.dumps(value).decode('utf-8'))\n"
|
||||
" sys.exit(0)\n"
|
||||
"sys.exit(f'unsupported plutil args: {args}')\n",
|
||||
)
|
||||
self._write_shim(
|
||||
"ditto",
|
||||
f"#!{python}\n"
|
||||
"import os, stat, sys, zipfile\n"
|
||||
"from pathlib import Path\n"
|
||||
"args = sys.argv[1:]\n"
|
||||
"src, dst = Path(args[-2]), Path(args[-1])\n"
|
||||
"if '-c' in args:\n"
|
||||
" base = src.parent if '--keepParent' in args else src\n"
|
||||
" with zipfile.ZipFile(dst, 'w', compression=zipfile.ZIP_DEFLATED) as z:\n"
|
||||
" items = [src] + sorted(src.rglob('*')) if '--keepParent' in args else sorted(src.rglob('*'))\n"
|
||||
" for item in items:\n"
|
||||
" rel = item.relative_to(base).as_posix()\n"
|
||||
" if item.is_dir():\n"
|
||||
" info = zipfile.ZipInfo(rel + '/')\n"
|
||||
" info.external_attr = (stat.S_IFDIR | (item.stat().st_mode & 0o777)) << 16\n"
|
||||
" z.writestr(info, b'')\n"
|
||||
" else:\n"
|
||||
" info = zipfile.ZipInfo(rel)\n"
|
||||
" info.external_attr = (stat.S_IFREG | (item.stat().st_mode & 0o777)) << 16\n"
|
||||
" z.writestr(info, item.read_bytes())\n"
|
||||
"elif '-x' in args:\n"
|
||||
" dst.mkdir(parents=True, exist_ok=True)\n"
|
||||
" with zipfile.ZipFile(src) as z:\n"
|
||||
" for info in z.infolist():\n"
|
||||
" target = dst / info.filename\n"
|
||||
" if info.is_dir():\n"
|
||||
" target.mkdir(parents=True, exist_ok=True)\n"
|
||||
" else:\n"
|
||||
" target.parent.mkdir(parents=True, exist_ok=True)\n"
|
||||
" target.write_bytes(z.read(info.filename))\n"
|
||||
" mode = (info.external_attr >> 16) & 0o777\n"
|
||||
" if mode:\n"
|
||||
" os.chmod(target, mode)\n"
|
||||
"else:\n"
|
||||
" sys.exit(f'unsupported ditto args: {args}')\n",
|
||||
)
|
||||
|
||||
def env(self, **changes):
|
||||
env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "RUNNER_TEMP": str(self.temp)}
|
||||
for key, value in changes.items():
|
||||
if value is None:
|
||||
env.pop(key, None)
|
||||
else:
|
||||
env[key] = str(value)
|
||||
return env
|
||||
|
||||
def run(self, script, *args, **changes):
|
||||
path = Path(script) if Path(script).is_absolute() else HERE / script
|
||||
return subprocess.run(
|
||||
["bash", str(path), *(str(a) for a in args)],
|
||||
env=self.env(**changes), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=60,
|
||||
)
|
||||
|
||||
def package(self, font_licences):
|
||||
"""Drive the real producer from a clean fixture checkout, without Cargo or Apple tools."""
|
||||
source = HERE.parents[1]
|
||||
checkout = self.root / "source"
|
||||
checkout.mkdir()
|
||||
notices = APP_NOTICES + tuple(name for name in OPTIONAL_NOTICES if (source / name).is_file())
|
||||
for relative in (*notices, "packaging/env.sh", "packaging/nightly-common.sh", "packaging/nightly_paths.py",
|
||||
"packaging/macos/nightly.sh", "packaging/macos/nightly-lib.sh",
|
||||
"packaging/macos/Info.plist.in", "packaging/macos/nightly_plist.py",
|
||||
"assets/app-icon/texturecraft-nightly.icns"):
|
||||
target = checkout / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(source / relative, target)
|
||||
env = self.env(**dict.fromkeys(SECRETS))
|
||||
|
||||
def git(*args):
|
||||
return subprocess.run(["git", "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", *args],
|
||||
cwd=checkout, env=env, check=True, capture_output=True, text=True, timeout=30).stdout
|
||||
|
||||
git("init", "-q")
|
||||
git("add", "--", ".")
|
||||
git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-qm", "Packaging fixture")
|
||||
commit = git("rev-parse", "HEAD").strip()
|
||||
version = VERSION[:-12] + commit[:12]
|
||||
# Generated licence text exercises the copier without depending on a font checkout.
|
||||
fonts = self.root / "craft-fonts"
|
||||
for family, data in font_licences.items():
|
||||
licence = fonts / "fonts" / family / "OFL.txt"
|
||||
licence.parent.mkdir(parents=True)
|
||||
licence.write_bytes(data)
|
||||
self._write_shim(
|
||||
"cargo",
|
||||
'#!/bin/sh\nset -eu\n'
|
||||
'gui="$CARGO_TARGET_DIR/aarch64-apple-darwin/release/texturecraft"\n'
|
||||
'mkdir -p "$(dirname "$gui")"\n'
|
||||
"printf \"#!/bin/sh\\necho 'TextureCraft %s (nightly-v1)'\\n\" \"$TEXTURECRAFT_VERSION\" >\"$gui\"\n",
|
||||
)
|
||||
result = self.run(checkout / "packaging/macos/nightly.sh", "--arch", "aarch64", **dict.fromkeys(SECRETS),
|
||||
DIST=str(self.dist), CARGO_TARGET_DIR=str(self.root / "target"), CRAFT_FONTS_DIR=str(fonts),
|
||||
TEXTURECRAFT_BUILD_CHANNEL="nightly-v1", TEXTURECRAFT_VERSION=version,
|
||||
TEXTURECRAFT_BUILD_SHA=commit, TEXTURECRAFT_BUILD_DATE="2026-11-24")
|
||||
assert result.returncode == 0, result.stdout
|
||||
return self.dist / ASSET.replace(VERSION, version)
|
||||
|
||||
|
||||
class Build(unittest.TestCase):
|
||||
def test_unsigned_archive_has_launcher_layout_and_keeps_all_notices(self):
|
||||
f = PackageFixture(self)
|
||||
fonts = {
|
||||
"inter": b"generated font notice one",
|
||||
"biz-ud-pgothic": b"generated font notice two",
|
||||
"noto-sans-cjk-sc": b"generated font notice three",
|
||||
}
|
||||
archive = f.package(fonts)
|
||||
source = HERE.parents[1]
|
||||
resources = f"{APP}/Contents/Resources"
|
||||
icon = "texturecraft-nightly.icns"
|
||||
notice_files = {name: (source / name).read_bytes() for name in APP_NOTICES}
|
||||
notice_files.update({name: (source / name).read_bytes() for name in OPTIONAL_NOTICES if (source / name).is_file()})
|
||||
notice_files.update({f"OFL-{family}.txt": data for family, data in fonts.items()})
|
||||
# Shipped Launcher v0.20.3 accepts these leaves only in Resources/docs, except for the root icon.
|
||||
expected_files = {f"{resources}/docs/{name}": data for name, data in notice_files.items()}
|
||||
expected_files[f"{resources}/{icon}"] = (source / "assets/app-icon" / icon).read_bytes()
|
||||
contents = f"{APP}/Contents"
|
||||
gui = f"{contents}/MacOS/TextureCraft"
|
||||
with zipfile.ZipFile(archive) as zipped:
|
||||
entries = zipped.infolist()
|
||||
names = {entry.filename for entry in entries}
|
||||
self.assertEqual(len(entries), len({name.casefold() for name in names}), "unique paths, ignoring case")
|
||||
self.assertEqual({entry.filename for entry in entries if not entry.is_dir()},
|
||||
set(expected_files) | {gui, f"{contents}/Info.plist", f"{contents}/PkgInfo"})
|
||||
self.assertTrue({entry.filename for entry in entries if entry.is_dir()} <= {
|
||||
f"{APP}/", f"{contents}/", f"{contents}/MacOS/", f"{resources}/", f"{resources}/docs/"})
|
||||
for path, data in expected_files.items():
|
||||
with self.subTest(path=path):
|
||||
self.assertEqual(zipped.read(path), data)
|
||||
mode = zipped.getinfo(path).external_attr >> 16
|
||||
self.assertTrue(stat.S_ISREG(mode))
|
||||
self.assertFalse(mode & 0o111)
|
||||
mode = zipped.getinfo(gui).external_attr >> 16
|
||||
self.assertTrue(stat.S_ISREG(mode) and mode & stat.S_IXUSR)
|
||||
result = f.run("nightly-verify.sh", "--input", archive, "--expect", "unsigned", **dict.fromkeys(SECRETS))
|
||||
self.assertEqual(result.returncode, 0, result.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -13,6 +13,12 @@ APP_NAME = "texturecraft"
|
||||
PRODUCER_WORKFLOW_NAME = "TextureCraft unsigned nightly"
|
||||
|
||||
NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64")
|
||||
# The pinned shared registry enables Windows, Linux and macOS for TextureCraft.
|
||||
SIGNER_SECRETS = {
|
||||
"AZURE_CERT_PROFILE", "AZURE_CLIENT_ID", "AZURE_CLIENT_SECRET", "AZURE_SIGNING_ACCOUNT",
|
||||
"AZURE_SIGNING_ENDPOINT", "AZURE_TENANT_ID", "LINUX_SIGNING_KEY", "APPLE_CERTIFICATE",
|
||||
"APPLE_CERTIFICATE_PASSWORD", "APPLE_ID", "APPLE_PASSWORD", "APPLE_TEAM_ID", "KEYCHAIN_PASSWORD",
|
||||
}
|
||||
NIGHTLY_TRUST = {
|
||||
"windows-x86_64": ("publisher_subject",
|
||||
"CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"),
|
||||
@@ -45,6 +51,49 @@ def assert_nightly_serialization(source):
|
||||
raise ValueError("nightly serialization must use its stable group and no cancellation")
|
||||
|
||||
|
||||
def caller_entries(lines, indent):
|
||||
"""Split the callers' plain YAML block entries; refuse other forms at checked levels."""
|
||||
entries = {}
|
||||
children = None
|
||||
for line in lines:
|
||||
if children is not None and line.startswith(" " * (indent + 1)):
|
||||
children.append(line)
|
||||
continue
|
||||
row = re.fullmatch(r" " * indent + r"([A-Za-z0-9_-]+):(?: (.*))?", line)
|
||||
if row is None or row[1] in entries:
|
||||
raise ValueError("malformed or duplicate caller mapping entry")
|
||||
children = []
|
||||
entries[row[1]] = row[2], children
|
||||
return entries
|
||||
|
||||
|
||||
def assert_caller_secrets(source, job_name, names):
|
||||
"""Check the actual caller's root, job and secret blocks without a YAML dependency."""
|
||||
lines = [line for line in source.splitlines() if line.strip() and not line.lstrip().startswith("#")]
|
||||
root = caller_entries(lines, 0)
|
||||
job_marker, job_lines = root.pop("jobs", (None, []))
|
||||
jobs = caller_entries(job_lines, 2)
|
||||
if job_marker is not None or set(jobs) != {job_name} or jobs[job_name][0] is not None:
|
||||
raise ValueError("the caller must have one plain job block")
|
||||
job = caller_entries(jobs[job_name][1], 4)
|
||||
if "environment" in job or "environment" in root or "secrets" in root:
|
||||
raise ValueError("only the native callee may bind the environment")
|
||||
if names:
|
||||
if "secrets" not in job:
|
||||
raise ValueError("signer requires an explicit target-specific secret map")
|
||||
mode, secret_lines = job.pop("secrets")
|
||||
expected = {name: ("${{ secrets." + name + " }}", []) for name in names}
|
||||
if mode is not None or caller_entries(secret_lines, 6) != expected:
|
||||
raise ValueError("signer must forward exactly the reviewed same-name secret references")
|
||||
elif "secrets" in job:
|
||||
raise ValueError("unsigned caller must not pass secrets")
|
||||
for value, children in (*root.values(), *job.values()):
|
||||
outside_map = "\n".join([value or "", *children])
|
||||
# Scan all remaining text: quoted braces can appear before a secret reference.
|
||||
if re.search(r"(?im)^\s*environment:|\bsecrets\b", outside_map):
|
||||
raise ValueError("secret bindings belong only in the signer map")
|
||||
|
||||
|
||||
def literal_off(condition):
|
||||
"""True only for a guard that a reviewed test update can still see is switched off."""
|
||||
expression = " ".join(condition.split())
|
||||
@@ -204,8 +253,49 @@ class TrustedSourcePreparation(unittest.TestCase):
|
||||
with self.subTest(workflow=name):
|
||||
self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache")
|
||||
self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:")
|
||||
self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):")
|
||||
self.assertNotIn("secrets.", executable)
|
||||
|
||||
def test_signer_forwards_exactly_the_reviewed_secret_names(self):
|
||||
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
|
||||
assert_caller_secrets(signer, "release", SIGNER_SECRETS)
|
||||
|
||||
def test_signer_refuses_missing_extra_alias_duplicate_or_inherited_secrets(self):
|
||||
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
|
||||
header = " secrets:\n"
|
||||
linux = " LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}\n"
|
||||
self.assertIn(linux, signer)
|
||||
mutations = {
|
||||
"missing name": signer.replace(linux, ""),
|
||||
"extra name": signer + " EXTRA: ${{ secrets.EXTRA }}\n",
|
||||
"renamed source": signer.replace(linux, linux.replace("secrets.LINUX_SIGNING_KEY", "secrets.APPLE_ID")),
|
||||
"duplicate name": signer.replace(linux, linux + linux),
|
||||
"duplicate map": signer + header + linux,
|
||||
"quoted duplicate map": signer + ' "secrets": inherit\n',
|
||||
"inherit": signer.split(header)[0] + " secrets: inherit\n",
|
||||
"yaml alias": signer.replace(linux, " LINUX_SIGNING_KEY: *other\n"),
|
||||
"yaml merge": signer + " <<: *other\n",
|
||||
"environment": signer + " environment: release\n",
|
||||
"secret outside map": signer.replace("${{ inputs.producer_run_id }}", "${{ secrets.APPLE_ID }}"),
|
||||
}
|
||||
for change, source in mutations.items():
|
||||
with self.subTest(change=change), self.assertRaises(ValueError):
|
||||
assert_caller_secrets(source, "release", SIGNER_SECRETS)
|
||||
|
||||
def test_unsigned_caller_has_no_secrets(self):
|
||||
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
assert_caller_secrets(producer, "unsigned", set())
|
||||
for suffix in (" secrets: {}\n", " secrets: inherit\n",
|
||||
" secrets:\n EXTRA: ${{ secrets.EXTRA }}\n",
|
||||
" extra: ${{ secrets['EXTRA'] }}\n", " secrets: inherit\n"):
|
||||
with self.subTest(suffix=suffix), self.assertRaises(ValueError):
|
||||
assert_caller_secrets(producer + suffix, "unsigned", set())
|
||||
|
||||
def test_unsigned_caller_refuses_secret_after_format_brace(self):
|
||||
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
# This inert fixture is never dispatched; the brace is part of the format string.
|
||||
env = "env:\n EXAMPLE: ${{ format('value {0}', secrets.EXAMPLE_ONLY) }}\n\n"
|
||||
source = producer.replace("jobs:\n", env + "jobs:\n", 1)
|
||||
with self.assertRaisesRegex(ValueError, "secret bindings belong only in the signer map"):
|
||||
assert_caller_secrets(source, "unsigned", set())
|
||||
|
||||
|
||||
class NightlyTrustAnchors(unittest.TestCase):
|
||||
|
||||
@@ -36,6 +36,18 @@ for wasm in "$SITE"/*.wasm; do
|
||||
echo "$(basename "$wasm"): $size bytes ($((size / 1048576)) MiB; limit $MAX_WASM_BYTES)"
|
||||
if [[ "$size" -gt "$MAX_WASM_BYTES" ]]; then
|
||||
echo "error: $(basename "$wasm") is $size bytes, over the $MAX_WASM_BYTES-byte limit (Cloudflare's per-file cap is 25 MiB)" >&2
|
||||
# Where the bytes go: the optimized file has no function names, so the crate breakdown reads
|
||||
# cargo's own output (before wasm-bindgen and wasm-opt), which keeps them. Best effort only.
|
||||
report="$HERE/wasm_size_report.py"
|
||||
if command -v python3 >/dev/null && [[ -f "$report" ]]; then
|
||||
echo "--- sections of $(basename "$wasm") ---" >&2
|
||||
python3 "$report" "$wasm" >&2 || true
|
||||
raw="$CARGO_TARGET_DIR/wasm32-unknown-unknown/wasm-release/texturecraft-web.wasm"
|
||||
if [[ -f "$raw" ]]; then
|
||||
echo "--- largest crates and functions in cargo's output (before wasm-opt) ---" >&2
|
||||
python3 "$report" "$raw" >&2 || true
|
||||
fi
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Print where a wasm module's bytes go: sections, data, and code by crate."""
|
||||
import os, re, sys
|
||||
from collections import defaultdict
|
||||
|
||||
def leb(b, i):
|
||||
r = s = 0
|
||||
while True:
|
||||
x = b[i]; i += 1
|
||||
r |= (x & 0x7f) << s; s += 7
|
||||
if x < 0x80: return r, i
|
||||
|
||||
def crate_of(name):
|
||||
if name.startswith("_ZN"):
|
||||
m = re.match(r"_ZN(\d+)", name)
|
||||
if m:
|
||||
n = int(m.group(1)); s = name[3 + len(m.group(1)):3 + len(m.group(1)) + n]
|
||||
if s.startswith("_$LT$"):
|
||||
inner = re.match(r"_\$LT\$(?:\$RF\$|mut\$u20\$)*([A-Za-z_][A-Za-z0-9_]*)", s)
|
||||
return (inner.group(1) if inner else s) + " (impl)"
|
||||
return s
|
||||
if name.startswith("_R"):
|
||||
m = re.search(r"C(?:s[0-9A-Za-z]*_)?(\d+)_?([A-Za-z_][A-Za-z0-9_]*)", name)
|
||||
if m: return m.group(2)[:int(m.group(1))]
|
||||
return "<other: " + name.split("::")[0][:40] + ">" if "::" in name else "<unmangled>"
|
||||
|
||||
def main(arg, top=25):
|
||||
repo = os.path.realpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", ".."))
|
||||
target_env = os.environ.get("CARGO_TARGET_DIR")
|
||||
target = os.path.realpath(target_env) if target_env else None
|
||||
path = os.path.realpath(arg)
|
||||
root = target if target and path.startswith(target + os.sep) else repo
|
||||
if not path.startswith(root + os.sep):
|
||||
print(f"wasm_size_report: skipped {arg!r}: not a .wasm file under the repository or CARGO_TARGET_DIR", file=sys.stderr)
|
||||
return
|
||||
if not path.endswith(".wasm") or not os.path.isfile(path):
|
||||
print(f"wasm_size_report: skipped {arg!r}: not a .wasm file under the repository or CARGO_TARGET_DIR", file=sys.stderr)
|
||||
return
|
||||
with open(path, "rb") as f:
|
||||
b = f.read()
|
||||
assert b[:4] == b"\0asm"
|
||||
i = 8; secs = []; names = {}; code_sizes = []; nimports = 0; data_total = 0
|
||||
while i < len(b):
|
||||
sid = b[i]; i += 1
|
||||
size, i = leb(b, i); body = b[i:i + size]
|
||||
label = {0:"custom",1:"type",2:"import",3:"function",4:"table",5:"memory",6:"global",7:"export",8:"start",9:"element",10:"code",11:"data",12:"datacount"}.get(sid, str(sid))
|
||||
if sid == 0:
|
||||
nl, j = leb(body, 0); cname = body[j:j+nl].decode(); label = "custom:" + cname
|
||||
if cname == "name":
|
||||
j += nl
|
||||
while j < len(body):
|
||||
sub = body[j]; j += 1; sl, j = leb(body, j); end = j + sl
|
||||
if sub == 1:
|
||||
cnt, k = leb(body, j)
|
||||
for _ in range(cnt):
|
||||
idx, k = leb(body, k); ln, k = leb(body, k); names[idx] = body[k:k+ln].decode("utf-8", "replace"); k += ln
|
||||
j = end
|
||||
elif sid == 2:
|
||||
cnt, j = leb(body, 0)
|
||||
for _ in range(cnt):
|
||||
l, j = leb(body, j); j += l; l, j = leb(body, j); j += l
|
||||
kind = body[j]; j += 1
|
||||
if kind == 0: nimports += 1; _, j = leb(body, j)
|
||||
elif kind == 1: j += 1; fl, j = leb(body, j); _, j = leb(body, j); j = leb(body, j)[1] if fl & 1 else j
|
||||
elif kind == 2: fl, j = leb(body, j); _, j = leb(body, j); j = leb(body, j)[1] if fl & 1 else j
|
||||
elif kind == 3: j += 2
|
||||
elif sid == 10:
|
||||
cnt, j = leb(body, 0)
|
||||
for _ in range(cnt):
|
||||
fs, j2 = leb(body, j); code_sizes.append(fs + (j2 - j)); j = j2 + fs
|
||||
elif sid == 11:
|
||||
data_total = size
|
||||
secs.append((label, size)); i += size
|
||||
total = len(b)
|
||||
print(f"{path}: {total} bytes")
|
||||
for label, size in sorted(secs, key=lambda s: -s[1])[:8]:
|
||||
print(f" {label:<24}{size:>12} bytes {100*size/total:5.1f}%")
|
||||
by_crate = defaultdict(int); funcs = []
|
||||
for k, sz in enumerate(code_sizes):
|
||||
n = names.get(nimports + k, f"func[{nimports+k}]")
|
||||
by_crate[crate_of(n)] += sz; funcs.append((sz, n))
|
||||
if not names:
|
||||
print(" (no name section: pass the wasm cargo wrote, before wasm-opt, to attribute code to crates)")
|
||||
return
|
||||
print(f" largest crates by code size (of {sum(code_sizes)} code bytes):")
|
||||
for c, sz in sorted(by_crate.items(), key=lambda x: -x[1])[:top]:
|
||||
print(f" {sz:>10} {c}")
|
||||
print(" largest functions:")
|
||||
for sz, n in sorted(funcs, reverse=True)[:10]:
|
||||
print(f" {sz:>10} {n[:140]}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 25)
|
||||
Reference in new issue
Block a user