From 1e0a17a09bec324c5d3f66518eb0f91e199968b2 Mon Sep 17 00:00:00 2001
From: SteamSmith <341182916+SteamSmith@users.noreply.github.com>
Date: Wed, 4 Nov 2026 23:48:03 -0500
Subject: [PATCH 001/138] fix(formats): files a mesh references must stay
inside its folder after links are followed
below() only checks the text of a referenced path, so a symbolic link or
junction inside the mesh's folder could lead a glTF/FBX/USD reference to any
file the user can read, which was then embedded in the project. read_mesh_file
now canonicalizes the folder and the file and refuses anything outside.
Co-Authored-By: Claude Sonnet 5.5
---
crates/formats/src/mesh_import/external.rs | 46 +++++++++++++++++++++-
1 file changed, 45 insertions(+), 1 deletion(-)
diff --git a/crates/formats/src/mesh_import/external.rs b/crates/formats/src/mesh_import/external.rs
index 25fa8bbd..bbe79671 100644
--- a/crates/formats/src/mesh_import/external.rs
+++ b/crates/formats/src/mesh_import/external.rs
@@ -57,7 +57,20 @@ pub fn self_contained_mesh(name: &str, bytes: Vec, read: &mut dyn FnMut(&str
pub fn read_mesh_file(path: &std::path::Path) -> Result {
let bytes = crate::read_capped(path, MAX_MESH_FILE_BYTES)?;
let dir = path.parent().unwrap_or_else(|| std::path::Path::new(""));
- self_contained_mesh(&path.to_string_lossy(), bytes, &mut |rel| crate::read_capped(&dir.join(rel), MAX_MESH_FILE_BYTES).ok())
+ self_contained_mesh(&path.to_string_lossy(), bytes, &mut |rel| read_inside(dir, rel))
+}
+
+/// `rel` (already checked by [`below`]) read from below `dir`, or None when it is missing, too big,
+/// or, once symbolic links and junctions are followed, is not inside `dir`: `below` only looks at
+/// the text of the path, so a link in the folder could otherwise lead to any file.
+#[cfg(not(target_arch = "wasm32"))]
+fn read_inside(dir: &std::path::Path, rel: &str) -> Option> {
+ let root = std::fs::canonicalize(if dir.as_os_str().is_empty() { std::path::Path::new(".") } else { dir }).ok()?;
+ let file = std::fs::canonicalize(dir.join(rel)).ok()?;
+ if !file.starts_with(&root) {
+ return None;
+ }
+ crate::read_capped(&file, MAX_MESH_FILE_BYTES).ok()
}
/// `asset` as a path below the mesh's folder (`/`-separated, `.` and `..` resolved), or None when
@@ -126,6 +139,37 @@ fn image_mime(path: &str) -> &'static str {
mod tests {
use super::*;
+ /// A link `link` inside `dir` leading to `target` (a folder): a symbolic link on Unix, a junction
+ /// on Windows. False when the system refuses to make one.
+ #[cfg(not(target_arch = "wasm32"))]
+ fn link_dir(link: &std::path::Path, target: &std::path::Path) -> bool {
+ #[cfg(unix)]
+ return std::os::unix::fs::symlink(target, link).is_ok();
+ #[cfg(windows)]
+ return std::process::Command::new("cmd.exe").args(["/D", "/C", "mklink", "/J"]).arg(link).arg(target).output().is_ok_and(|o| o.status.success());
+ #[cfg(not(any(unix, windows)))]
+ return false;
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn a_link_in_the_mesh_folder_cannot_lead_outside_it() {
+ let base = std::env::temp_dir().join(format!("tc-mesh-link-{}", std::process::id()));
+ let (dir, outside) = (base.join("model"), base.join("secret"));
+ std::fs::create_dir_all(dir.join("tex")).unwrap();
+ std::fs::create_dir_all(&outside).unwrap();
+ std::fs::write(outside.join("key.txt"), b"private").unwrap();
+ std::fs::write(dir.join("tex/a.png"), b"inside").unwrap();
+ assert_eq!(read_inside(&dir, "tex/a.png").as_deref(), Some(&b"inside"[..]), "ordinary files below the folder are read");
+ assert_eq!(read_inside(&dir, "tex/missing.png"), None);
+ if link_dir(&dir.join("out"), &outside) {
+ assert_eq!(read_inside(&dir, "out/key.txt"), None, "through a link to another folder");
+ } else {
+ eprintln!("skipped the link case: this system would not make a link");
+ }
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
#[test]
fn below_keeps_paths_inside_the_folder() {
assert_eq!(below("tex/a.png").as_deref(), Some("tex/a.png"));
From 45c3d5decd63ebde976b714d7f11c706afae1d44 Mon Sep 17 00:00:00 2001
From: SteamSmith <341182916+SteamSmith@users.noreply.github.com>
Date: Fri, 6 Nov 2026 06:59:04 -0500
Subject: [PATCH 002/138] test(#255): links that stay inside the folder, file
links and a linked mesh folder
Co-Authored-By: Claude Sonnet 5.5
---
crates/formats/src/mesh_import/external.rs | 14 ++++++++++++++
1 file changed, 14 insertions(+)
diff --git a/crates/formats/src/mesh_import/external.rs b/crates/formats/src/mesh_import/external.rs
index bbe79671..6629a8f0 100644
--- a/crates/formats/src/mesh_import/external.rs
+++ b/crates/formats/src/mesh_import/external.rs
@@ -167,6 +167,20 @@ mod tests {
} else {
eprintln!("skipped the link case: this system would not make a link");
}
+ // A link that stays inside the folder is an ordinary shortcut and still works.
+ if link_dir(&dir.join("shortcut"), &dir.join("tex")) {
+ assert_eq!(read_inside(&dir, "shortcut/a.png").as_deref(), Some(&b"inside"[..]), "through a link to a folder inside");
+ }
+ // A link to a single outside file (Unix symbolic links; Windows file links need privileges).
+ #[cfg(unix)]
+ {
+ std::os::unix::fs::symlink(outside.join("key.txt"), dir.join("tex/key.png")).unwrap();
+ assert_eq!(read_inside(&dir, "tex/key.png"), None, "through a link to an outside file");
+ }
+ // The mesh's own folder reached through a link is fine: both sides are resolved.
+ if link_dir(&base.join("alias"), &dir) {
+ assert_eq!(read_inside(&base.join("alias"), "tex/a.png").as_deref(), Some(&b"inside"[..]), "folder given through a link");
+ }
let _ = std::fs::remove_dir_all(&base);
}
From 24210c4678a2e658ab6861d59ba44fa58d5b8b79 Mon Sep 17 00:00:00 2001
From: SteamSmith <341182916+SteamSmith@users.noreply.github.com>
Date: Fri, 6 Nov 2026 22:31:33 -0500
Subject: [PATCH 003/138] docs(#255): doc comments for the touched functions
and the new tests
Co-Authored-By: Claude Sonnet 5.5
---
crates/formats/src/mesh_import/external.rs | 2 ++
1 file changed, 2 insertions(+)
diff --git a/crates/formats/src/mesh_import/external.rs b/crates/formats/src/mesh_import/external.rs
index 6629a8f0..0897d666 100644
--- a/crates/formats/src/mesh_import/external.rs
+++ b/crates/formats/src/mesh_import/external.rs
@@ -151,6 +151,8 @@ mod tests {
return false;
}
+ /// Files are read through ordinary paths and links that stay inside the folder, but not through a link
+ /// (folder or file) that leads outside it.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_link_in_the_mesh_folder_cannot_lead_outside_it() {
From cd1f8c5daa61a08981cddb367a740a975114a9c4 Mon Sep 17 00:00:00 2001
From: SteamSmith
Date: Sat, 14 Nov 2026 11:31:03 -0500
Subject: [PATCH 004/138] fix(#255): test the link guard through
read_mesh_file, fail instead of skipping, document hard-link limit
Co-Authored-By: Claude Sonnet 5.5
---
crates/formats/src/mesh_import/external.rs | 81 ++++++++++++++--------
1 file changed, 53 insertions(+), 28 deletions(-)
diff --git a/crates/formats/src/mesh_import/external.rs b/crates/formats/src/mesh_import/external.rs
index 0897d666..3bf375cf 100644
--- a/crates/formats/src/mesh_import/external.rs
+++ b/crates/formats/src/mesh_import/external.rs
@@ -52,7 +52,10 @@ pub fn self_contained_mesh(name: &str, bytes: Vec, read: &mut dyn FnMut(&str
}
/// Read mesh file `path` with the files it references from its folder (see
-/// [`self_contained_mesh`]), each at most [`MAX_MESH_FILE_BYTES`].
+/// [`self_contained_mesh`]), each at most [`MAX_MESH_FILE_BYTES`]. A referenced file is used only
+/// when, after symbolic links and junctions are followed, it is still inside the mesh's folder;
+/// one that leads outside counts as not found (a warning, like a missing file), while links that
+/// stay inside the folder work. Hard links cannot be told apart by path: see [`read_inside`].
#[cfg(not(target_arch = "wasm32"))]
pub fn read_mesh_file(path: &std::path::Path) -> Result {
let bytes = crate::read_capped(path, MAX_MESH_FILE_BYTES)?;
@@ -63,6 +66,12 @@ pub fn read_mesh_file(path: &std::path::Path) -> Result {
/// `rel` (already checked by [`below`]) read from below `dir`, or None when it is missing, too big,
/// or, once symbolic links and junctions are followed, is not inside `dir`: `below` only looks at
/// the text of the path, so a link in the folder could otherwise lead to any file.
+///
+/// Limit: a HARD link is an ordinary directory entry, so a hard link in the folder to a file
+/// outside it looks like a file inside it and is read. Telling them apart needs the link count,
+/// which std offers only on Unix (and a count above one is also what legitimate files can have);
+/// we don't use `unsafe`, so it is not checked. Making a hard link needs write access to the
+/// folder and read access to the target.
#[cfg(not(target_arch = "wasm32"))]
fn read_inside(dir: &std::path::Path, rel: &str) -> Option> {
let root = std::fs::canonicalize(if dir.as_os_str().is_empty() { std::path::Path::new(".") } else { dir }).ok()?;
@@ -152,38 +161,54 @@ mod tests {
}
/// Files are read through ordinary paths and links that stay inside the folder, but not through a link
- /// (folder or file) that leads outside it.
+ /// (folder or file) that leads outside it. Fails when the system refuses to make the links (Unix
+ /// symbolic links and Windows junctions need no privilege), so it cannot pass without testing them.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_link_in_the_mesh_folder_cannot_lead_outside_it() {
let base = std::env::temp_dir().join(format!("tc-mesh-link-{}", std::process::id()));
- let (dir, outside) = (base.join("model"), base.join("secret"));
- std::fs::create_dir_all(dir.join("tex")).unwrap();
- std::fs::create_dir_all(&outside).unwrap();
- std::fs::write(outside.join("key.txt"), b"private").unwrap();
- std::fs::write(dir.join("tex/a.png"), b"inside").unwrap();
- assert_eq!(read_inside(&dir, "tex/a.png").as_deref(), Some(&b"inside"[..]), "ordinary files below the folder are read");
- assert_eq!(read_inside(&dir, "tex/missing.png"), None);
- if link_dir(&dir.join("out"), &outside) {
- assert_eq!(read_inside(&dir, "out/key.txt"), None, "through a link to another folder");
- } else {
- eprintln!("skipped the link case: this system would not make a link");
- }
- // A link that stays inside the folder is an ordinary shortcut and still works.
- if link_dir(&dir.join("shortcut"), &dir.join("tex")) {
- assert_eq!(read_inside(&dir, "shortcut/a.png").as_deref(), Some(&b"inside"[..]), "through a link to a folder inside");
- }
- // A link to a single outside file (Unix symbolic links; Windows file links need privileges).
- #[cfg(unix)]
- {
- std::os::unix::fs::symlink(outside.join("key.txt"), dir.join("tex/key.png")).unwrap();
- assert_eq!(read_inside(&dir, "tex/key.png"), None, "through a link to an outside file");
- }
- // The mesh's own folder reached through a link is fine: both sides are resolved.
- if link_dir(&base.join("alias"), &dir) {
- assert_eq!(read_inside(&base.join("alias"), "tex/a.png").as_deref(), Some(&b"inside"[..]), "folder given through a link");
- }
let _ = std::fs::remove_dir_all(&base);
+ let (dir, outside) = (base.join("model"), base.join("secret"));
+ let result = std::panic::catch_unwind(|| {
+ std::fs::create_dir_all(dir.join("tex")).unwrap();
+ std::fs::create_dir_all(&outside).unwrap();
+ std::fs::write(outside.join("key.txt"), b"private").unwrap();
+ std::fs::write(dir.join("tex/a.png"), b"inside").unwrap();
+ assert_eq!(read_inside(&dir, "tex/a.png").as_deref(), Some(&b"inside"[..]), "ordinary files below the folder are read");
+ assert_eq!(read_inside(&dir, "tex/missing.png"), None);
+ assert!(link_dir(&dir.join("out"), &outside), "this system would not make a link");
+ assert_eq!(read_inside(&dir, "out/key.txt"), None, "through a link to another folder");
+ // A link that stays inside the folder is an ordinary shortcut and still works.
+ assert!(link_dir(&dir.join("shortcut"), &dir.join("tex")), "this system would not make a link");
+ assert_eq!(read_inside(&dir, "shortcut/a.png").as_deref(), Some(&b"inside"[..]), "through a link to a folder inside");
+ // A link to a single outside file (Unix symbolic links; Windows file links need privileges).
+ #[cfg(unix)]
+ {
+ std::os::unix::fs::symlink(outside.join("key.txt"), dir.join("tex/key.png")).unwrap();
+ assert_eq!(read_inside(&dir, "tex/key.png"), None, "through a link to an outside file");
+ }
+ // The mesh's own folder reached through a link is fine: both sides are resolved.
+ assert!(link_dir(&base.join("alias"), &dir), "this system would not make a link");
+ assert_eq!(read_inside(&base.join("alias"), "tex/a.png").as_deref(), Some(&b"inside"[..]), "folder given through a link");
+
+ // The same through read_mesh_file: the outside bytes must not end up in the glTF.
+ std::fs::write(
+ dir.join("m.gltf"),
+ br#"{"asset": {"version": "2.0"}, "buffers": [{"uri": "out/key.txt", "byteLength": 7}, {"uri": "tex/a.png", "byteLength": 6}]}"#,
+ )
+ .unwrap();
+ let mesh = read_mesh_file(&dir.join("m.gltf")).unwrap();
+ let text = String::from_utf8(mesh.bytes).unwrap();
+ let b64 = |b: &[u8]| base64::engine::general_purpose::STANDARD.encode(b);
+ assert!(!text.contains(&b64(b"private")), "outside bytes were inlined");
+ assert!(text.contains(&b64(b"inside")), "the inside file is inlined");
+ assert_eq!(mesh.warnings.len(), 1, "{:?}", mesh.warnings);
+ assert!(mesh.warnings[0].contains("out/key.txt"), "{:?}", mesh.warnings);
+ });
+ let _ = std::fs::remove_dir_all(&base);
+ if let Err(e) = result {
+ std::panic::resume_unwind(e);
+ }
}
#[test]
From c25c984395ad379a51bef33871bbd77b6e97f197 Mon Sep 17 00:00:00 2001
From: Kirill M <176898419+JaffarSk24@users.noreply.github.com>
Date: Thu, 19 Nov 2026 21:13:17 +0100
Subject: [PATCH 005/138] i18n: offer Russian
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
LANGUAGES gains ru (Русский); ru-RU, ru-SK and ru_RU.UTF-8 resolve to it. Its texturecraft.tsv catalog comes from craft-i18n; Cyrillic is drawn by egui's built-in fonts. Docs list eleven languages.
---
ROADMAP.md | 5 +++--
crates/ui-egui/src/fonts.rs | 6 ++++--
crates/ui-egui/src/i18n.rs | 5 +++--
docs/features.md | 4 ++--
docs/localization-parity.md | 1 +
5 files changed, 13 insertions(+), 8 deletions(-)
diff --git a/ROADMAP.md b/ROADMAP.md
index 759dfde7..4ff0ad33 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -95,7 +95,7 @@ incomplete validation; they are not measured success rates or speed comparisons.
| UI/UX fidelity | ~65% | 20 | TBD | Current editing/bake/export UI checked; [gaps](docs/ui-parity.md), ArtCraft UI adoption and revalidation after refactoring remain |
| File formats / interchange | ~60% | 10 | TBD | Current native save and basic exports exercised; possible `.tcraft`/output-package reworks, unfinished upstream `.mcmat`, `.spp` and consumer validation remain |
| Hardware (GPU, pen, displays) | ~50% | 8 | TBD | One Windows GPU exercised; pen tilt, pressure across platforms and display coverage remain incomplete |
-| Localization | ~35% | 4 | TBD | Ten picker languages in source; optional shared catalogs/fonts and native-language review need current measurement |
+| Localization | ~35% | 4 | TBD | Eleven picker languages in source; optional shared catalogs/fonts and native-language review need current measurement |
| Performance | ~40% | 10 | TBD | Dirty-tile/budgeted architecture and benchmark code exist; no matched performance budgets or large-project results from this review |
| Stability | ~55% | 10 | TBD | Small save/reopen and undo/redo passed; recovery, large projects and long sessions need coverage, including after format/library migrations |
| Platforms | ~65% | 3 | TBD | Desktop/web build and packaging paths exist; this review ran Windows only |
@@ -158,7 +158,7 @@ exist; older reports must not turn them into fresh missing-feature claims.
## Languages
-The [picker](crates/ui-egui/src/i18n.rs) contains ten languages. Shared catalogs are optional at
+The [picker](crates/ui-egui/src/i18n.rs) contains eleven languages. Shared catalogs are optional at
build time; missing entries fall back to English, and builds without catalogs offer English only.
The older [coverage table](docs/localization-parity.md) predates catalog migration, so its “100%”
rows are not a current measurement. This audit ran an English build without external catalogs.
@@ -170,6 +170,7 @@ rows are not a current measurement. This audit ran an English build without exte
| Spanish | `es` | Not remeasured | Catalog dependent; native review pending |
| Hindi | `hi` | No picker entry | Not offered |
| Arabic | `ar` | Not remeasured | Catalog/font dependent; shaping/layout needs current review |
+| Russian | `ru` | Catalog dependent | Added with the craft-i18n `ru/texturecraft.tsv` catalog; reviewed by a native speaker |
| French | `fr` | Not remeasured | Catalog dependent; native review pending |
| Portuguese (Brazil) | `pt-BR` | Not remeasured | Catalog dependent; native review pending |
| Indonesian | `id` | No picker entry | Not offered |
diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs
index b31b423a..6f11efec 100644
--- a/crates/ui-egui/src/fonts.rs
+++ b/crates/ui-egui/src/fonts.rs
@@ -278,9 +278,11 @@ mod tests {
assert_eq!(Script::of_language("ko"), Some(Script::Korean));
assert_eq!(Script::of_language("ar"), Some(Script::Arabic));
assert_eq!(Script::of_language("de"), None);
+ assert_eq!(Script::of_language("ru"), None);
for l in &crate::i18n::LANGUAGES {
- // Past the Latin blocks and their diacritics.
- let other_script = l.name.chars().any(|c| c > '\u{036F}');
+ // Past the Latin blocks and their diacritics. Cyrillic needs no fallback: the UI fonts
+ // themselves carry it (egui's Ubuntu and craft-fonts' Inter).
+ let other_script = l.name.chars().any(|c| c > '\u{036F}' && !('\u{0400}'..='\u{04FF}').contains(&c));
assert_eq!(other_script, Script::of_language(l.code).is_some(), "{}", l.code);
}
}
diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs
index bbbea0ec..fe1cca17 100644
--- a/crates/ui-egui/src/i18n.rs
+++ b/crates/ui-egui/src/i18n.rs
@@ -37,7 +37,7 @@ pub struct Language {
pub english: &'static str,
}
-const COUNT: usize = 10;
+const COUNT: usize = 11;
pub static LANGUAGES: [Language; COUNT] = [
Language { code: "en", name: "English", english: "English" },
@@ -46,6 +46,7 @@ pub static LANGUAGES: [Language; COUNT] = [
Language { code: "es", name: "Español", english: "Spanish" },
Language { code: "pt-BR", name: "Português (Brasil)", english: "Portuguese (Brazil)" },
Language { code: "it", name: "Italiano", english: "Italian" },
+ Language { code: "ru", name: "Русский", english: "Russian" },
Language { code: "ja", name: "日本語", english: "Japanese" },
Language { code: "zh-Hans", name: "简体中文", english: "Chinese (Simplified)" },
Language { code: "ko", name: "한국어", english: "Korean" },
@@ -386,7 +387,7 @@ mod tests",
assert_eq!(trf("{a} of {b} {c}", &[("a", &1), ("b", &2)]), "1 of 2 {c}");
assert_eq!(trf("{unclosed", &[]), "{unclosed");
for (locale, code) in
- [("de-AT", "de"), ("pt_PT.UTF-8", "pt-BR"), ("zh-Hant-TW", "zh-Hans"), ("ja", "ja"), ("ko_KR", "ko"), ("ar-EG", "ar"), ("nl-NL", "en"), ("", "en")]
+ [("de-AT", "de"), ("pt_PT.UTF-8", "pt-BR"), ("zh-Hant-TW", "zh-Hans"), ("ja", "ja"), ("ko_KR", "ko"), ("ar-EG", "ar"), ("ru-SK", "ru"), ("ru_RU.UTF-8", "ru"), ("nl-NL", "en"), ("", "en")]
{
assert_eq!(language_for_locale(locale), code, "{locale}");
}
diff --git a/docs/features.md b/docs/features.md
index 79bae167..1a66c200 100644
--- a/docs/features.md
+++ b/docs/features.md
@@ -260,8 +260,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
channel to a text file with each entry's recorded UTC time, severity and source. The desktop app asks
for a destination, and the browser downloads the file.
- A **History** panel: click any step to go back to it, or forward again to an undone one.
-- **10 languages:** English, French, German, Spanish, Portuguese, Italian, Japanese, Chinese,
- Korean and Arabic, switchable live.
+- **11 languages:** English, French, German, Spanish, Portuguese, Italian, Russian, Japanese,
+ Chinese, Korean and Arabic, switchable live.
- **In the browser:** the same app compiled to WebAssembly, on WebGPU or WebGL2, with touch
navigation and project open, save and download.
diff --git a/docs/localization-parity.md b/docs/localization-parity.md
index fb6a8a49..3625d0cd 100644
--- a/docs/localization-parity.md
+++ b/docs/localization-parity.md
@@ -29,6 +29,7 @@ generator, filter and brush alpha names (**KEYS** strings, counted by the
| Arabic | `ar` | KEYS (100%) | yes | Arabic glyphs: craft-fonts (Noto Sans Arabic) or system fonts on desktop; egui shapes the text and orders it right to left (panels keep the left-to-right layout) | yes | full | 0 h |
| French | `fr` | KEYS (100%) | yes | Latin | no | full | 1 h (review) |
| Portuguese (Brazil) | `pt-BR` | KEYS (100%) | yes | Latin | no | full | 1 h (review) |
+| Russian | `ru` | KEYS (~99%) | yes | Cyrillic: egui's built-in fonts | yes | full with the craft-i18n `ru/texturecraft.tsv` catalog | 0 h |
| Indonesian | `id` | 0 | no | Latin | no | none | 3 h |
| Japanese | `ja` | KEYS (100%) | yes | CJK glyphs: craft-fonts (BIZ UDPGothic) or system fonts on desktop | no | full | 2 h (review) |
| German | `de` | KEYS (100%) | yes | Latin | no | full | 1 h (review) |
From ab13dc9870bdd5251497031c37a98a72937b8926 Mon Sep 17 00:00:00 2001
From: Kirill M <176898419+JaffarSk24@users.noreply.github.com>
Date: Thu, 19 Nov 2026 23:09:28 +0100
Subject: [PATCH 006/138] i18n: format the locale test; features.md says a
build without catalogs offers English only
---
crates/ui-egui/src/i18n.rs | 15 ++++++++++++---
docs/features.md | 3 ++-
2 files changed, 14 insertions(+), 4 deletions(-)
diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs
index fe1cca17..a0697be5 100644
--- a/crates/ui-egui/src/i18n.rs
+++ b/crates/ui-egui/src/i18n.rs
@@ -386,9 +386,18 @@ mod tests",
assert_eq!(trf("Saved {path}", &[("path", &"a.tcraft")]), "Saved a.tcraft");
assert_eq!(trf("{a} of {b} {c}", &[("a", &1), ("b", &2)]), "1 of 2 {c}");
assert_eq!(trf("{unclosed", &[]), "{unclosed");
- for (locale, code) in
- [("de-AT", "de"), ("pt_PT.UTF-8", "pt-BR"), ("zh-Hant-TW", "zh-Hans"), ("ja", "ja"), ("ko_KR", "ko"), ("ar-EG", "ar"), ("ru-SK", "ru"), ("ru_RU.UTF-8", "ru"), ("nl-NL", "en"), ("", "en")]
- {
+ for (locale, code) in [
+ ("de-AT", "de"),
+ ("pt_PT.UTF-8", "pt-BR"),
+ ("zh-Hant-TW", "zh-Hans"),
+ ("ja", "ja"),
+ ("ko_KR", "ko"),
+ ("ar-EG", "ar"),
+ ("ru-SK", "ru"),
+ ("ru_RU.UTF-8", "ru"),
+ ("nl-NL", "en"),
+ ("", "en"),
+ ] {
assert_eq!(language_for_locale(locale), code, "{locale}");
}
set_language("de");
diff --git a/docs/features.md b/docs/features.md
index 1a66c200..220eadf2 100644
--- a/docs/features.md
+++ b/docs/features.md
@@ -261,7 +261,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
for a destination, and the browser downloads the file.
- A **History** panel: click any step to go back to it, or forward again to an undone one.
- **11 languages:** English, French, German, Spanish, Portuguese, Italian, Russian, Japanese,
- Chinese, Korean and Arabic, switchable live.
+ Chinese, Korean and Arabic, switchable live. A build without the shared craft-i18n catalogs
+ offers English only.
- **In the browser:** the same app compiled to WebAssembly, on WebGPU or WebGL2, with touch
navigation and project open, save and download.
From 025aff43182c6b0c3fc3795a9d91739c0856c50e Mon Sep 17 00:00:00 2001
From: Kirill M <176898419+JaffarSk24@users.noreply.github.com>
Date: Thu, 19 Nov 2026 23:09:29 +0100
Subject: [PATCH 007/138] tests: pin the UI harnesses to English
The app starts in the system language and these tests find controls by their English labels, so on a machine whose language TextureCraft offers they failed. Each harness built around TextureCraftApp now sets prefs.language to en right after it is built, as rail.rs and settings_window.rs already did; the toolbar-only harnesses, which never run a full frame, set the language directly. ui_state_persistence keeps the saved state it tests.
---
crates/ui-egui/tests/bake_preview.rs | 2 ++
crates/ui-egui/tests/brush_cursor_2d.rs | 2 ++
crates/ui-egui/tests/it/bake_job_mesh.rs | 2 ++
crates/ui-egui/tests/it/bake_mode.rs | 4 ++++
crates/ui-egui/tests/it/bake_presets.rs | 3 +++
crates/ui-egui/tests/it/brush_drag.rs | 3 +++
crates/ui-egui/tests/it/camera_views.rs | 3 +++
crates/ui-egui/tests/it/clone_source_view.rs | 2 ++
crates/ui-egui/tests/it/close_unsaved.rs | 2 ++
crates/ui-egui/tests/it/color_selection_editor.rs | 3 +++
crates/ui-egui/tests/it/curvature_generator.rs | 2 ++
crates/ui-egui/tests/it/effect_rows.rs | 4 ++++
crates/ui-egui/tests/it/effect_sliders.rs | 3 +++
crates/ui-egui/tests/it/export_template_guards.rs | 2 ++
crates/ui-egui/tests/it/file_dialogs.rs | 2 ++
crates/ui-egui/tests/it/filter_picker.rs | 3 +++
crates/ui-egui/tests/it/frame_selection.rs | 2 ++
crates/ui-egui/tests/it/generator_panel.rs | 2 ++
crates/ui-egui/tests/it/history_panel.rs | 3 +++
crates/ui-egui/tests/it/import_resources.rs | 1 +
crates/ui-egui/tests/it/inactive_set_hint.rs | 2 ++
crates/ui-egui/tests/it/layer_blending_options.rs | 2 ++
crates/ui-egui/tests/it/layer_clipboard.rs | 3 +++
crates/ui-egui/tests/it/layer_multi_select.rs | 2 ++
crates/ui-egui/tests/it/layer_rename.rs | 2 ++
crates/ui-egui/tests/it/layers_panel.rs | 3 +++
crates/ui-egui/tests/it/levels_editor.rs | 2 ++
crates/ui-egui/tests/it/mask_export.rs | 2 ++
crates/ui-egui/tests/it/mask_value_swap.rs | 2 ++
crates/ui-egui/tests/it/named_layouts.rs | 2 ++
crates/ui-egui/tests/it/nav_buttons.rs | 2 ++
crates/ui-egui/tests/it/new_project_baked_maps.rs | 3 +++
crates/ui-egui/tests/it/path_in_view.rs | 4 ++++
crates/ui-egui/tests/it/path_list.rs | 2 ++
crates/ui-egui/tests/it/pen_pressure.rs | 2 ++
crates/ui-egui/tests/it/polygon_fill.rs | 3 +++
crates/ui-egui/tests/it/project_config.rs | 1 +
crates/ui-egui/tests/it/properties_popup.rs | 2 ++
crates/ui-egui/tests/it/shelf_click.rs | 2 ++
crates/ui-egui/tests/it/shelf_drop.rs | 2 ++
crates/ui-egui/tests/it/shelf_hover_preview.rs | 2 ++
crates/ui-egui/tests/it/shelf_panel.rs | 2 ++
crates/ui-egui/tests/it/shift_lines_2d.rs | 3 +++
crates/ui-egui/tests/it/shift_lines_3d.rs | 2 ++
crates/ui-egui/tests/it/shortcut_keys.rs | 2 ++
crates/ui-egui/tests/it/skew_paint.rs | 2 ++
crates/ui-egui/tests/it/smudge_channels.rs | 2 ++
crates/ui-egui/tests/it/snapped_lines.rs | 2 ++
crates/ui-egui/tests/it/split_divider.rs | 2 ++
crates/ui-egui/tests/it/symmetry.rs | 2 ++
crates/ui-egui/tests/it/symmetry_2d.rs | 2 ++
crates/ui-egui/tests/it/tool_availability.rs | 4 ++++
crates/ui-egui/tests/it/tool_settings_saved.rs | 2 ++
crates/ui-egui/tests/it/toolbar.rs | 7 +++++++
crates/ui-egui/tests/it/user_smart_mask.rs | 2 ++
crates/ui-egui/tests/list_panels.rs | 3 +++
56 files changed, 136 insertions(+)
diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs
index 1703abde..9e00f082 100644
--- a/crates/ui-egui/tests/bake_preview.rs
+++ b/crates/ui-egui/tests/bake_preview.rs
@@ -20,6 +20,8 @@ fn harness() -> Harness<'static, TextureCraftApp> {
session.view = ViewMode::UvChecker;
let mut harness = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|context| TextureCraftApp::new(context, session));
+ // The labels below are English; a first run would speak the system's language
+ harness.state_mut().ui.prefs.language = "en".into();
harness.state_mut().ui.mode = Mode::Baking;
harness.run_steps(3);
harness
diff --git a/crates/ui-egui/tests/brush_cursor_2d.rs b/crates/ui-egui/tests/brush_cursor_2d.rs
index 6c54d052..323b7924 100644
--- a/crates/ui-egui/tests/brush_cursor_2d.rs
+++ b/crates/ui-egui/tests/brush_cursor_2d.rs
@@ -10,6 +10,8 @@ use texturecraft_ui_egui::state::{Mode, ViewLayout};
fn harness() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session));
+ // The labels below are English; a first run would speak the system's language
+ harness.state_mut().ui.prefs.language = "en".into();
harness.state_mut().ui.layout = ViewLayout::Only2D;
harness.run_steps(4);
harness
diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs
index 60f6f03e..6d166d46 100644
--- a/crates/ui-egui/tests/it/bake_job_mesh.rs
+++ b/crates/ui-egui/tests/it/bake_job_mesh.rs
@@ -12,6 +12,8 @@ use texturecraft_ui_egui::{BakeJob, RunningBake, TextureCraftApp};
fn harness_with_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, TextureCraftApp>, Arc
+
+ TextureCraft — открытая нативная программа для рисования 3D-текстур, устроенная так,
+ как привыкли художники по текстурам: знакомые меню, сочетания клавиш, панели и
+ инструменты, а наборы текстур, слои, маски, заливки и эффекты наносятся прямо на
+ модель.
+
Open glTF/GLB, FBX, COLLADA, USD (USDA/USDC/USDZ), Alembic, OBJ, PLY and STL meshes and save projects as .tcraft
+
Открытие сеток glTF/GLB, FBX, COLLADA, USD (USDA/USDC/USDZ), Alembic, OBJ, PLY и STL и сохранение проектов в .tcraft
Paint base colour, roughness, metallic, normal and height together with PBR brushes
+
Рисование базового цвета, шероховатости, металличности, нормалей и высоты одновременно с помощью PBR-кистей
Bake mesh maps and export texture sets as PNG, EXR, TGA, JPEG or TIFF
+
Запекание карт сетки и экспорт наборов текстур в PNG, EXR, TGA, JPEG или TIFF
Every action is a command, scriptable from a CLI and a JSON control channel
+
Каждое действие — это команда, которую можно вызывать из CLI и через управляющий канал JSON
ai.storyteller.texturecraft.desktop
@@ -36,9 +47,13 @@
texture painting
+ рисование текстурpbr
+ pbr3d
+ 3dmesh
+ сетка#f0c39c
diff --git a/packaging/linux/ai.storyteller.texturecraft.mime.xml b/packaging/linux/ai.storyteller.texturecraft.mime.xml
index cf5204b3..2b1b811e 100644
--- a/packaging/linux/ai.storyteller.texturecraft.mime.xml
+++ b/packaging/linux/ai.storyteller.texturecraft.mime.xml
@@ -1,16 +1,19 @@
+
TextureCraft project
+ Проект TextureCraftglTF binary model
+ Двоичная модель glTF
@@ -18,11 +21,13 @@
glTF model
+ Модель glTFFBX model
+ Модель FBX
@@ -30,11 +35,13 @@
COLLADA model
+ Модель COLLADAUniversal Scene Description
+ Universal Scene Description
@@ -44,17 +51,20 @@
Universal Scene Description (text)
+ Universal Scene Description (текст)Universal Scene Description package
+ Пакет Universal Scene DescriptionAlembic model
+ Модель Alembic
@@ -62,11 +72,13 @@
Wavefront OBJ model
+ Модель Wavefront OBJPLY model
+ Модель PLY
@@ -75,6 +87,7 @@
STL model
+ Модель STL
From e4585fb2b34234e7a5f4b58ee0db1f744e500048 Mon Sep 17 00:00:00 2001
From: supersfera
Date: Sat, 21 Nov 2026 20:23:02 -0800
Subject: [PATCH 010/138] ru: update language-script test for Cyrillic
---
crates/ui-egui/src/fonts.rs | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs
index b31b423a..5a5eb801 100644
--- a/crates/ui-egui/src/fonts.rs
+++ b/crates/ui-egui/src/fonts.rs
@@ -279,8 +279,9 @@ mod tests {
assert_eq!(Script::of_language("ar"), Some(Script::Arabic));
assert_eq!(Script::of_language("de"), None);
for l in &crate::i18n::LANGUAGES {
- // Past the Latin blocks and their diacritics.
- let other_script = l.name.chars().any(|c| c > '\u{036F}');
+ // Past the Latin blocks and their diacritics. Cyrillic is already in the
+ // interface font (Inter / Ubuntu-Light), so Russian needs no fallback script.
+ let other_script = l.name.chars().any(|c| c > '\u{036F}' && !('\u{0400}'..='\u{04FF}').contains(&c));
assert_eq!(other_script, Script::of_language(l.code).is_some(), "{}", l.code);
}
}
From 03169492d7dc5cb44522ad407e96e556eed9dd2a Mon Sep 17 00:00:00 2001
From: vangel76
Date: Sun, 22 Nov 2026 13:10:17 +0100
Subject: [PATCH 011/138] Toggle layer effects from their thumbnails
---
crates/ui-egui/src/dock.rs | 177 ++++++++++++-----------
crates/ui-egui/src/layer_panel.rs | 26 ++--
crates/ui-egui/tests/it/effect_rows.rs | 5 +
crates/ui-egui/tests/it/layers_panel.rs | 121 +++++++++++-----
crates/ui-egui/tests/it/rename_anchor.rs | 20 ++-
5 files changed, 220 insertions(+), 129 deletions(-)
diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs
index 7f8cebfe..9136689f 100644
--- a/crates/ui-egui/src/dock.rs
+++ b/crates/ui-egui/src/dock.rs
@@ -209,6 +209,12 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) {
let stack: Vec = app.session.doc.project.texture_sets.get(ts).map(|t| t.stack.iter().rev().copied().collect()).unwrap_or_default();
let now = ui.input(|i| i.time);
app.layer_panel.begin(&app.session, now);
+ let selected_stack = app.session.selected_layer().map(|layer| (layer, !targets_content(app)));
+ if matches!(app.session.target, StackTarget::Effect(_)) {
+ app.layer_panel.expanded_effects = selected_stack;
+ } else if app.layer_panel.expanded_effects != selected_stack {
+ app.layer_panel.expanded_effects = None;
+ }
egui::ScrollArea::vertical().id_salt("layers_scroll").auto_shrink([false, false]).show(ui, |ui| {
let mut count = 0;
for id in stack {
@@ -241,6 +247,15 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) {
}
});
select_all_layers(app, ui);
+ // A thumbnail or selection can close the editor before its TextEdit sees lost focus.
+ if let Some((id, _)) = &app.ui.rename
+ && let Some((owner, _)) = app.session.doc.project.effect(LayerId(*id))
+ && app.layer_panel.expanded_effects.is_none_or(|(layer, in_mask)| {
+ layer != owner || !app.session.doc.project.layers.get(&layer).is_some_and(|l| stack_effects(l, in_mask).iter().any(|e| e.id.0 == *id))
+ })
+ {
+ finish_effect_rename(app);
+ }
}
/// Ctrl+A (Cmd+A on macOS) with the pointer over the Layers panel selects every row shown in the
@@ -382,6 +397,7 @@ const EYE_CHIP_ROUNDING: f32 = 4.0;
/// An effect thumbnail's corner rounding and border, the strike across a hidden effect's, and the line marking where a drag drops.
const THUMBNAIL_ROUNDING: f32 = 2.0;
const THUMBNAIL_BORDER_WIDTH: f32 = 1.0;
+const EFFECT_DISCLOSURE_SIZE: f32 = 13.0;
const HIDDEN_STRIKE_WIDTH: f32 = 1.5;
const DROP_LINE_WIDTH: f32 = 2.0;
/// The eye's size and the column it sits in (the eye and a gap before the thumbnail).
@@ -442,23 +458,12 @@ const EFFECT_ROW_SHADES: [f32; 2] = [0.2, 0.5];
/// Width of the blend mode and opacity pair at the right of an effect row (a gap between them), and of its opacity part.
const EFFECT_BLEND_WIDTH: f32 = 82.0;
const EFFECT_OPACITY_WIDTH: f32 = 36.0;
-/// Height of the "Content effects" / "Mask effects" header rows.
-const GROUP_HEADER_H: f32 = 20.0;
-
-// Group header spacing leaves room for the label and effect count
-const GROUP_HEADER_CARET_OFFSET: f32 = 15.0;
-const GROUP_HEADER_LABEL_GAP: f32 = 10.0;
-const GROUP_HEADER_LABEL_RESERVE: f32 = 28.0;
-const GROUP_HEADER_COUNT_PADDING: f32 = 8.0;
-const GROUP_HEADER_LABEL_FONT_SIZE: f32 = 10.5;
/// Hover tint of alternating layer rows
const ALTERNATE_LAYER_SHADE: f32 = 0.45;
/// Maximum layer-tree nesting shown by the dock
const MAX_LAYER_TREE_DEPTH: usize = 12;
/// Checkerboard cells along each thumbnail edge
const THUMB_CHECKER_CELLS: usize = 4;
-/// Keep the group label and count readable when the panel is narrow
-const GROUP_HEADER_MIN_REMAINING_WIDTH: f32 = 90.0;
/// Keep both thumbnail targets inside the row before spending space on indentation
fn layer_thumbnail_layout(width: f32, depth: usize, folder: bool, preferred_size: f32) -> (f32, f32) {
@@ -492,18 +497,23 @@ fn level_x(left: f32, level: usize) -> f32 {
left + ROW_LEFT_PADDING + level as f32 * INDENT + EYE_SIZE * 0.5
}
+fn stack_effects(layer: &Layer, in_mask: bool) -> &[Effect] {
+ if in_mask { layer.mask.as_ref().map_or(&[], |mask| &mask.effects) } else { &layer.content_effects }
+}
+
fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize, count: &mut usize) {
let Some(layer) = app.session.doc.project.layers.get(&id).cloned() else { return };
let index = *count;
*count += 1;
layer_row(app, ui, &layer, depth, index);
- let mask_effects = layer.mask.as_ref().map_or(0, |mask| mask.effects.len());
- if !layer.content_effects.is_empty() {
- effect_group(app, ui, &layer, depth, false, mask_effects > 0);
- }
- if mask_effects > 0 {
- effect_group(app, ui, &layer, depth, true, false);
+ if let Some((open_layer, in_mask)) = app.layer_panel.expanded_effects
+ && open_layer == id
+ {
+ let stack = stack_effects(&layer, in_mask);
+ for (index, effect) in stack.iter().rev().enumerate() {
+ effect_row(app, ui, &layer, stack, effect, index, depth + 2, index + 1 == stack.len(), in_mask);
+ }
}
// A line under the layer and its effects separates it from the next layer.
@@ -558,7 +568,8 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
let content_target = selected && targets_content(app);
let preferred_size = layer_preview_size(app);
let row_height = layer_row_height(preferred_size);
- let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), row_height), Sense::click_and_drag());
+ let (_, rect) = ui.allocate_space(vec2(ui.available_width(), row_height));
+ let row = ui.interact(rect, ui.scope_id().with(("layer_row", layer.id.0)), Sense::click_and_drag());
row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, highlighted, &layer.name));
// Background, folder lines, the selected rows' accent edge and the colour tag
@@ -659,9 +670,14 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
}
painter.rect_stroke(thumbnail, THUMBNAIL_ROUNDING, target_stroke(&tokens, content_target), egui::StrokeKind::Outside);
let content_response = ui.interact(thumbnail, ui.scope_id().with(("content", layer.id.0)), Sense::click()).on_hover_text(tr("Select the layer content"));
+ let content_stack = (!layer.content_effects.is_empty()).then_some((layer.id, false));
+ effect_stack_thumbnail(app, &painter, &tokens, &content_response, (tr("Select the layer content"), &layer.name), content_target, content_stack);
if content_response.clicked() {
let modifiers = ui.input(|input| input.modifiers);
click_layer(app, modifiers, layer.id.0, Some("content"));
+ if !modifiers.shift && !modifiers.command {
+ app.layer_panel.toggle_effects(content_stack);
+ }
}
x = thumbnail.right() + THUMBNAIL_SPACING;
@@ -699,12 +715,24 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
let mask_response = ui
.interact(mask_rect, ui.scope_id().with(("mask", layer.id.0)), Sense::click())
.on_hover_text(tr("Select the mask (Alt+click: show it in the viewport)"));
+ let mask_stack = layer.mask.as_ref().filter(|mask| !mask.effects.is_empty()).map(|_| (layer.id, true));
+ effect_stack_thumbnail(
+ app,
+ &painter,
+ &tokens,
+ &mask_response,
+ (tr("Select the mask (Alt+click: show it in the viewport)"), &layer.name),
+ mask_target,
+ mask_stack,
+ );
if mask_response.clicked() {
app.run("layer.select", json!({"layer": layer.id.0, "target": "mask"}));
if ui.input(|input| input.modifiers.alt) {
let showing = app.session.view == texturecraft_engine::ViewMode::Mask(layer.id);
let view = if showing { json!({"mode": "material"}) } else { json!({"mode": "mask", "layer": layer.id.0}) };
app.run("viewport.view", view);
+ } else {
+ app.layer_panel.toggle_effects(mask_stack);
}
}
if app.session.view == texturecraft_engine::ViewMode::Mask(layer.id) {
@@ -820,6 +848,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
let modifiers = ui.input(|input| input.modifiers);
if row.clicked() && !on_control && !renaming {
click_layer(app, modifiers, layer.id.0, None);
+ app.layer_panel.expanded_effects = None;
}
if row.double_clicked() && !on_control && !renaming && show_name && !modifiers.shift && !modifiers.command {
app.ui.rename = Some((layer.id.0, layer.name.clone()));
@@ -918,69 +947,45 @@ fn content_glyph(p: &egui::Painter, tk: &Tokens, thumb: Rect, layer: &Layer) {
}
}
-/// The "Content effects" or "Mask effects" header of `layer` and, unless folded, its effect rows
-/// hung off tree lines. `more_below`: a second group follows, so the tree line goes on.
-fn effect_group(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize, mask: bool, more_below: bool) {
- let tokens = Tokens::get(ui.ctx());
- let stack: &[Effect] = if mask { layer.mask.as_ref().map_or(&[], |layer_mask| &layer_mask.effects) } else { &layer.content_effects };
- let key = (layer.id.0, mask);
- let folded = app.layer_panel.folded.contains(&key);
- let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), GROUP_HEADER_H), Sense::click());
- let label = if mask { tr("Mask effects") } else { tr("Content effects") };
- response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));
- let painter = ui.painter().clone();
- painter.rect_filled(rect, 0.0, if response.hovered() { tokens.row_hover } else { tokens.panel });
- let indent = ((depth + 1) as f32 * INDENT).min((rect.width() - GROUP_HEADER_MIN_REMAINING_WIDTH).max(0.0));
- tree_lines(&painter, &tokens, rect, indent, &[], more_below);
- let x = rect.left() + GROUP_HEADER_CARET_OFFSET + indent;
- painter.text(
- pos2(x, rect.center().y),
- egui::Align2::CENTER_CENTER,
- if folded { ic::CARET_RIGHT } else { ic::CARET_DOWN },
- egui::FontId::proportional(LAYER_SUBTITLE_FONT_SIZE),
- tokens.text_dim,
- );
- let galley = elided(
- &painter,
- label.to_string(),
- GROUP_HEADER_LABEL_FONT_SIZE,
- tokens.text_dim,
- (rect.right() - GROUP_HEADER_LABEL_RESERVE - x - GROUP_HEADER_LABEL_GAP).max(0.0),
- );
- painter.galley(pos2(x + GROUP_HEADER_LABEL_GAP, rect.center().y - galley.size().y * 0.5), galley, tokens.text_dim);
- painter.text(
- pos2(rect.right() - GROUP_HEADER_COUNT_PADDING, rect.center().y),
- egui::Align2::RIGHT_CENTER,
- stack.len().to_string(),
- egui::FontId::proportional(LAYER_SUBTITLE_FONT_SIZE),
- tokens.text_dim,
- );
- if response.on_hover_text(tr("Fold or unfold these effects")).clicked() && !app.layer_panel.folded.remove(&key) {
- app.layer_panel.folded.insert(key);
+/// Draw the effect disclosure on its thumbnail and expose the same state to AccessKit.
+fn effect_stack_thumbnail(
+ app: &TextureCraftApp,
+ painter: &egui::Painter,
+ tokens: &Tokens,
+ response: &egui::Response,
+ (label, name): (&str, &str),
+ selected: bool,
+ stack: Option<(LayerId, bool)>,
+) {
+ response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, format!("{label} ({name})")));
+ if response.has_focus() {
+ painter.rect_stroke(response.rect.shrink(2.0), THUMBNAIL_ROUNDING, Stroke::new(1.0, tokens.text_strong), egui::StrokeKind::Inside);
}
- if folded {
- return;
- }
-
- let trunks: Vec = if more_below { vec![depth] } else { Vec::new() };
- for (row_index, effect) in stack.iter().rev().enumerate() {
- effect_row(app, ui, layer, stack, effect, row_index, depth + 2, &trunks, row_index + 1 == stack.len(), mask);
+ if let Some(stack) = stack {
+ let expanded = app.layer_panel.expanded_effects == Some(stack);
+ response.ctx.accesskit_node_builder(response.id, |node| node.set_expanded(expanded));
+ if response.rect.width() < EFFECT_DISCLOSURE_SIZE {
+ return;
+ }
+ let size = vec2(EFFECT_DISCLOSURE_SIZE, EFFECT_DISCLOSURE_SIZE);
+ let badge = Rect::from_min_size(response.rect.max - size, size);
+ painter.rect_filled(badge, THUMBNAIL_ROUNDING, tokens.button);
+ painter.text(
+ badge.center(),
+ egui::Align2::CENTER_CENTER,
+ if expanded { ic::CARET_DOWN } else { ic::CARET_RIGHT },
+ egui::FontId::proportional(EFFECT_DISCLOSURE_SIZE - 3.0),
+ tokens.text_strong,
+ );
}
}
-/// Tree connector of a row at the clamped `indent`: a line down from the parent's column (to the middle
-/// of the row when `more` is false, the row's end otherwise) and a tick towards the row, with
-/// lines straight through for the `trunks` of ancestors that continue.
-fn tree_lines(p: &egui::Painter, tk: &Tokens, rect: Rect, indent: f32, trunks: &[usize], more: bool) {
+/// Draw the line along the open effect stack and a branch to this row.
+fn effect_tree_line(p: &egui::Painter, tk: &Tokens, rect: Rect, indent: f32, more: bool) {
if indent < INDENT {
return;
}
let stroke = Stroke::new(1.0, tk.button_border);
- for t in trunks {
- if *t as f32 * INDENT + 8.0 < indent {
- p.vline(level_x(rect.left(), *t), rect.y_range(), stroke);
- }
- }
let x = rect.left() + 15.0 + indent - INDENT;
let end = if more { rect.bottom() } else { rect.center().y };
p.vline(x, rect.top()..=end, stroke);
@@ -1067,7 +1072,6 @@ fn effect_row(
effect: &Effect,
row_index: usize,
level: usize,
- trunks: &[usize],
last: bool,
in_mask: bool,
) {
@@ -1076,7 +1080,8 @@ fn effect_row(
let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(effect_id);
let layer_preview = layer_preview_size(app);
let preview_size = effect_preview_size(layer_preview);
- let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), effect_row_height(layer_preview)), Sense::click_and_drag());
+ let (_, rect) = ui.allocate_space(vec2(ui.available_width(), effect_row_height(layer_preview)));
+ let row = ui.interact(rect, ui.scope_id().with(("effect_row", effect_id.0)), Sense::click_and_drag());
row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &effect.name));
// Background, tree lines and the selected row's accent edge
@@ -1092,7 +1097,7 @@ fn effect_row(
};
painter.rect_filled(rect, 0.0, background);
let indent = effect_row_indent(rect.width(), level, preview_size);
- tree_lines(&painter, &tokens, rect, indent, trunks, !last);
+ effect_tree_line(&painter, &tokens, rect, indent, !last);
if selected {
painter.rect_filled(Rect::from_min_size(rect.min, vec2(SELECTED_EDGE_WIDTH, rect.height())), 0.0, tokens.accent);
}
@@ -1124,7 +1129,7 @@ fn effect_row(
if renaming {
let half_height = EFFECT_NAME_EDIT_HEIGHT * 0.5;
let name_rect = Rect::from_min_max(pos2(name_left, rect.center().y - half_height), pos2(name_right, rect.center().y + half_height));
- effect_rename_editor(app, ui, name_rect, effect);
+ effect_rename_editor(app, ui, name_rect);
} else {
let name_width = (name_right - name_left).max(MIN_NAME_WIDTH);
if text_is_cut(&painter, &effect.name, EFFECT_NAME_FONT_SIZE, name_width) {
@@ -1212,8 +1217,8 @@ fn effect_row(
});
}
-/// The name editor of `effect` in `rect`: Enter or a click elsewhere renames, Escape cancels.
-fn effect_rename_editor(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, effect: &Effect) {
+/// The effect name editor: Enter or a click elsewhere renames, Escape cancels.
+fn effect_rename_editor(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) {
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(egui::Layout::left_to_right(egui::Align::Center)));
let Some((_, name_buffer)) = app.ui.rename.as_mut() else { return };
@@ -1224,17 +1229,21 @@ fn effect_rename_editor(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, effe
if ui.input(|input| input.key_pressed(egui::Key::Escape)) {
app.ui.rename = None;
} else if response.lost_focus() {
- let name = name_buffer.trim().to_string();
- app.ui.rename = None;
- if !name.is_empty() && name != effect.name {
- app.run("effect.set", json!({"effect": effect.id.0, "name": name}));
- }
+ finish_effect_rename(app);
} else if !response.has_focus() {
// Only until the field has focus (see the layer rename editor)
response.request_focus();
}
}
+fn finish_effect_rename(app: &mut TextureCraftApp) {
+ let Some((id, name)) = app.ui.rename.take() else { return };
+ let name = name.trim();
+ if !name.is_empty() && app.session.doc.project.effect(LayerId(id)).is_some_and(|(_, effect)| name != effect.name) {
+ app.run("effect.set", json!({"effect": id, "name": name}));
+ }
+}
+
/// The Geometry mask tool: what a click does, and the selected layer's parts.
fn geometry_tool_section(app: &mut TextureCraftApp, ui: &mut Ui) {
let tk = Tokens::get(ui.ctx());
diff --git a/crates/ui-egui/src/layer_panel.rs b/crates/ui-egui/src/layer_panel.rs
index d5390546..554161f3 100644
--- a/crates/ui-egui/src/layer_panel.rs
+++ b/crates/ui-egui/src/layer_panel.rs
@@ -1,12 +1,13 @@
//! State behind the Layers panel: the thumbnail service, the GPU textures made from its pictures,
-//! which effect groups are folded, and the one place the preview size is decided.
+//! which effect stack is open, and the one place the preview size is decided.
-use std::collections::{HashMap, HashSet};
+use std::collections::HashMap;
use std::time::Duration;
use egui::{Context, TextureHandle, TextureId, TextureOptions};
use texturecraft_engine::Session;
use texturecraft_engine::compose::ThumbTarget;
+use texturecraft_engine::core::LayerId;
use texturecraft_engine::thumbs::{CACHE_ENTRIES, ThumbService};
use crate::TextureCraftApp;
@@ -42,20 +43,23 @@ pub struct LayerPanel {
frame: u64,
/// Whether this frame's pictures are begun and not yet finished by [`LayerPanel::end`]
pictures_begun: bool,
- /// Folded effect groups: (layer, true for the mask's). A view setting; the document is not touched.
- pub(crate) folded: HashSet<(u64, bool)>,
+ /// The open stack, with `true` for a layer's mask. This belongs to the panel view.
+ pub(crate) expanded_effects: Option<(LayerId, bool)>,
}
/// How soon to look again for pictures still rendering (milliseconds)
const POLL_INTERVAL_MS: u64 = 40;
impl LayerPanel {
+ pub(crate) fn toggle_effects(&mut self, stack: Option<(LayerId, bool)>) {
+ self.expanded_effects = stack.filter(|stack| Some(*stack) != self.expanded_effects);
+ }
+
/// Start drawing the panel for this frame.
pub(crate) fn begin(&mut self, session: &Session, now: f64) {
self.begin_pictures(session, now);
- // Deleted layer IDs must not accumulate in panel state
- self.folded.retain(|(layer, _)| session.doc.project.layers.contains_key(&texturecraft_engine::core::LayerId(*layer)));
+ self.expanded_effects = self.expanded_effects.filter(|(layer, _)| session.doc.project.layers.contains_key(layer));
}
/// Advance the picture frame once, whether the panel or a picture outside it asks first
@@ -115,22 +119,22 @@ impl LayerPanel {
#[cfg(test)]
mod tests {
use super::*;
- use texturecraft_engine::core::{Channel, LayerId};
+ use texturecraft_engine::core::Channel;
use texturecraft_engine::geom::primitives;
#[test]
- fn deleted_layers_release_their_fold_state() {
+ fn deleted_layers_close_their_effect_stack() {
let mut session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap();
let layer = session.selected_layer().unwrap();
let mut panel = LayerPanel::default();
- panel.folded.extend([(layer.0, false), (layer.0, true)]);
+ panel.expanded_effects = Some((layer, false));
panel.begin(&session, 0.0);
- assert_eq!(panel.folded.len(), 2, "existing layers keep their view settings");
+ assert_eq!(panel.expanded_effects, Some((layer, false)), "existing layers keep their view settings");
texturecraft_engine::execute(&mut session, "layer.remove", &serde_json::json!({"layer": layer.0})).unwrap();
panel.begin(&session, 1.0);
- assert!(panel.folded.is_empty(), "deleted layer IDs must not accumulate in view state");
+ assert_eq!(panel.expanded_effects, None, "the deleted layer leaves no open stack");
}
#[test]
diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs
index fdd04351..b8afbe42 100644
--- a/crates/ui-egui/tests/it/effect_rows.rs
+++ b/crates/ui-egui/tests/it/effect_rows.rs
@@ -7,6 +7,8 @@ use texturecraft_engine::core::LayerId;
use texturecraft_engine::execute;
use texturecraft_ui_egui::TextureCraftApp;
+use super::layers_panel::click_selected_content_thumbnail;
+
fn id(v: Value, key: &str) -> u64 {
v[key].as_u64().unwrap()
}
@@ -34,6 +36,7 @@ fn dragging_an_effect_row_reorders_its_stack() {
execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
harness.run_steps(4);
+ click_selected_content_thumbnail(&mut harness);
let order =
|harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>();
assert_eq!(order(&harness), [a, b, c]);
@@ -60,6 +63,7 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() {
execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
harness.run_steps(4);
+ click_selected_content_thumbnail(&mut harness);
let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone();
assert_eq!(effect, effect_of(&harness).id.0);
@@ -97,6 +101,7 @@ fn an_opacity_drag_starting_without_a_change_is_its_own_undo_step() {
execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
harness.run_steps(4);
+ click_selected_content_thumbnail(&mut harness);
let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone();
let history = harness.state().session.history_labels().len();
diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs
index 0a88c260..4deeadc6 100644
--- a/crates/ui-egui/tests/it/layers_panel.rs
+++ b/crates/ui-egui/tests/it/layers_panel.rs
@@ -1,8 +1,8 @@
-//! The Layers panel rows: content and mask thumbnails select their own target, effect groups
-//! fold without touching the document, and the thumbnails arrive from the worker.
+//! The Layers panel rows: thumbnails select and disclose their own effects without editing the
+//! document, and the thumbnail images arrive from the worker.
use egui_kittest::Harness;
-use egui_kittest::kittest::Queryable;
+use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::{Value, json};
use texturecraft_engine::compose::ThumbTarget;
use texturecraft_engine::core::{Channel, LayerId};
@@ -35,11 +35,12 @@ fn thumb(h: &Harness<'_, TextureCraftApp>, name: &str, mask: bool) -> egui::Pos2
egui::pos2(x, row.center().y)
}
-/// The `label` header that follows the "Masked fill" row (other layers have groups too).
-fn header(h: &mut Harness<'_, TextureCraftApp>, label: &str) {
- let top = h.get_by_label("Masked fill").rect().top();
- let at = h.get_all_by_label(label).map(|n| n.rect()).filter(|r| r.top() > top).min_by(|a, b| a.top().total_cmp(&b.top())).unwrap().center();
- click(h, at);
+/// Toggle the effect rows through the selected layer's content thumbnail.
+pub(super) fn click_selected_content_thumbnail(h: &mut Harness<'_, TextureCraftApp>) {
+ let layer = h.state().session.selected_layer().unwrap();
+ let name = &h.state().session.doc.project.layers[&layer].name;
+ h.get_by_label(&format!("Select the layer content ({name})")).click();
+ h.run_steps(3);
}
fn click(h: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) {
@@ -49,35 +50,84 @@ fn click(h: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) {
}
#[test]
-fn mask_and_content_thumbnails_select_their_own_target() {
+fn mask_and_content_thumbnails_toggle_their_own_stacks() {
let (mut h, layer) = harness();
- let at = thumb(&h, "Masked fill", true);
- click(&mut h, at);
+ let content = thumb(&h, "Masked fill", false);
+ let mask = thumb(&h, "Masked fill", true);
+ assert!(h.query_by_label("Effect A").is_none() && h.query_by_label("Effect M").is_none(), "stacks start closed");
+
+ click(&mut h, mask);
assert_eq!(h.state().session.selected_layer(), Some(layer));
- assert_eq!(h.state().session.target, StackTarget::Mask, "the mask thumbnail routes to the mask");
- let at = thumb(&h, "Masked fill", false);
- click(&mut h, at);
- assert_eq!(h.state().session.target, StackTarget::Content, "the content thumbnail routes back");
- // Clicking an effect row's name still selects that effect (its right end holds the blend mode and opacity)
+ assert_eq!(h.state().session.target, StackTarget::Mask);
+ assert!(h.query_by_label("Effect M").is_some());
+ click(&mut h, mask);
+ assert!(h.query_by_label("Effect M").is_none(), "the same mask thumbnail closes its stack");
+ click(&mut h, mask);
+ assert!(h.query_by_label("Effect M").is_some());
+
+ click(&mut h, content);
+ assert_eq!(h.state().session.target, StackTarget::Content);
+ assert!(h.query_by_label("Effect M").is_none(), "switching thumbnails closes the mask stack");
+ assert!(h.query_by_label("Effect A").is_some());
+ click(&mut h, content);
+ assert!(h.query_by_label("Effect A").is_none(), "the same content thumbnail closes its stack");
+ click(&mut h, content);
let row = h.get_by_label("Effect A").rect();
click(&mut h, row.center());
assert!(matches!(h.state().session.target, StackTarget::Effect(_)));
+ assert!(h.query_by_label("Effect A").is_some(), "selecting an effect leaves its stack open");
}
#[test]
-fn folding_an_effect_group_hides_its_rows_without_changing_the_document() {
- let (mut h, _) = harness();
- let (project, undo) = (h.state().session.doc.project.clone(), h.state().session.revision);
- assert!(h.query_by_label("Effect A").is_some() && h.query_by_label("Effect M").is_some());
- header(&mut h, "Content effects");
- assert!(h.query_by_label("Effect A").is_none(), "folded content effects are hidden");
- assert!(h.query_by_label("Effect M").is_some(), "the mask group stays open");
- header(&mut h, "Mask effects");
- assert!(h.query_by_label("Effect M").is_none());
- assert_eq!(h.state().session.doc.project, project);
- assert_eq!(h.state().session.revision, undo, "folding is not an edit");
- header(&mut h, "Content effects");
- assert!(h.query_by_label("Effect A").is_some(), "unfolds again");
+fn keyboard_toggles_effects_without_editing_the_document() {
+ let (mut h, layer) = harness();
+ let session = &h.state().session;
+ let (project, history, modified) = (session.doc.project.clone(), session.history_labels(), session.modified);
+ let content = "Select the layer content (Masked fill)";
+ assert_eq!(h.get_by_label(content).accesskit_node().data().is_expanded(), Some(false));
+
+ // Move focus to the thumbnail and activate it with the standard button keys.
+ h.get_by_label(content).focus();
+ h.run_steps(3);
+ assert!(h.get_by_label(content).is_focused());
+ h.key_press(egui::Key::Enter);
+ h.run_steps(3);
+ assert!(h.query_by_label("Effect A").is_some());
+ h.key_press(egui::Key::Space);
+ h.run_steps(3);
+ assert!(h.query_by_label("Effect A").is_none());
+ assert_eq!(h.get_by_label(content).accesskit_node().data().is_expanded(), Some(false));
+
+ h.key_press(egui::Key::Enter);
+ h.run_steps(3);
+ assert!(h.get_by_label(content).is_focused());
+ assert_eq!(h.get_by_label(content).accesskit_node().data().is_expanded(), Some(true));
+
+ let session = &h.state().session;
+ let empty = session.doc.project.texture_sets[session.ts()]
+ .stack
+ .iter()
+ .rev()
+ .find_map(|id| {
+ let layer = session.doc.project.layers.get(id)?;
+ (layer.mask.is_none() && layer.content_effects.is_empty()).then(|| (*id, layer.name.clone()))
+ })
+ .expect("sample contains an empty paint layer");
+ let empty_thumbnail = format!("Select the layer content ({})", empty.1);
+ h.get_by_label(&empty_thumbnail).focus();
+ h.run_steps(3);
+ assert!(h.get_by_label(&empty_thumbnail).is_focused());
+ h.key_press(egui::Key::Enter);
+ h.run_steps(3);
+ assert_eq!(h.state().session.selected_layer(), Some(empty.0));
+ assert_ne!(empty.0, layer);
+ assert!(h.query_by_label("Effect A").is_none() && h.query_by_label("Effect M").is_none(), "switching layers closes the old stack");
+ assert_eq!(h.get_by_label(&empty_thumbnail).accesskit_node().data().is_expanded(), None);
+
+ let session = &h.state().session;
+ assert_eq!(session.doc.project, project);
+ assert_eq!(session.history_labels(), history);
+ assert_eq!(session.modified, modified);
}
#[test]
@@ -85,14 +135,15 @@ fn visible_rows_get_their_thumbnails() {
let (mut h, layer) = harness();
let content = ThumbTarget::Content { layer, channel: Channel::BaseColor };
let mask = ThumbTarget::Mask { layer };
+ let effect = h.state().session.doc.project.layers[&layer].content_effects[0].id;
+ let stage = ThumbTarget::Stage { effect, channel: Channel::BaseColor };
+ click_selected_content_thumbnail(&mut h);
let t0 = std::time::Instant::now();
- while !(h.state().layer_panel.service().is_fresh(content) && h.state().layer_panel.service().is_fresh(mask)) {
+ while ![content, mask, stage].iter().all(|target| h.state().layer_panel.service().is_fresh(*target)) {
assert!(t0.elapsed().as_secs() < 60, "thumbnails never arrived");
h.run_steps(1);
std::thread::sleep(std::time::Duration::from_millis(5));
}
- // Rows, mask, and every effect stage on screen were asked for: well under the cache size.
- assert!(h.state().layer_panel.service().cached() >= 4);
}
#[test]
@@ -121,6 +172,9 @@ fn deeply_nested_effect_visibility_is_reachable_in_a_narrow_panel() {
harness.state_mut().ui.dock.close(texturecraft_ui_egui::docking::Panel::Properties);
harness.run_steps(4);
+ harness.state_mut().run("layer.select", json!({"layer": layer.0})).unwrap();
+ harness.run_steps(3);
+ click_selected_content_thumbnail(&mut harness);
let row = harness.get_by_label("Effect A").rect();
assert!(row.width() < 180.0, "the test must use a compact panel: {row:?}");
@@ -297,12 +351,13 @@ const LONG_EFFECT_NAME: &str = "Edge wear from curvature with dirt accumulation"
fn an_effect_name_cut_short_shows_in_full_on_hover() {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
let layer = id(execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer");
- execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap();
execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": LONG_EFFECT_NAME})).unwrap();
+ execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.prefs.language = "en".into();
h.run_steps(4);
+ click_selected_content_thumbnail(&mut h);
let row = h.get_by_label(LONG_EFFECT_NAME).rect();
let before = h.query_all_by_label_contains(LONG_EFFECT_NAME).count();
h.hover_at(egui::pos2(row.left() + 75.0, row.center().y));
diff --git a/crates/ui-egui/tests/it/rename_anchor.rs b/crates/ui-egui/tests/it/rename_anchor.rs
index f8ee1763..9287725b 100644
--- a/crates/ui-egui/tests/it/rename_anchor.rs
+++ b/crates/ui-egui/tests/it/rename_anchor.rs
@@ -12,6 +12,8 @@ use texturecraft_engine::core::{Channel, EffectKind, LayerId, Source};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, StackTarget};
use texturecraft_ui_egui::TextureCraftApp;
+
+use super::layers_panel::click_selected_content_thumbnail;
use texturecraft_ui_egui::file_dialogs::Answer;
const BLACK: [f32; 3] = [0.0; 3];
@@ -69,7 +71,9 @@ fn effect_harness() -> (Harness<'static, TextureCraftApp>, u64) {
"effect",
);
texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap();
- (harness_for(session), effect)
+ let mut h = harness_for(session);
+ click_selected_content_thumbnail(&mut h);
+ (h, effect)
}
/// Choose Rename effect from the row's context menu and type `text` over the old name.
@@ -116,10 +120,24 @@ fn renaming_an_effect_row_undoes_redoes_and_survives_save_and_reopen() {
let layer = h.state().session.doc.project.effect(LayerId(effect)).unwrap().0;
h.state_mut().run("layer.select", json!({"layer": layer.0}));
h.run_steps(3);
+ assert!(h.query_by_label("Pitted rust").is_none(), "the reopened stack starts closed");
+ click_selected_content_thumbnail(&mut h);
assert!(h.query_by_label("Pitted rust").is_some(), "the reopened stack shows the name");
std::fs::remove_dir_all(file.parent().unwrap()).unwrap();
}
+#[test]
+fn collapsing_an_effect_stack_finishes_its_rename() {
+ let (mut h, effect) = effect_harness();
+ rename_from_the_menu(&mut h, "Effect A", "Pitted rust");
+ click_selected_content_thumbnail(&mut h);
+ assert!(h.state().ui.rename.is_none(), "the hidden editor has committed the name");
+ assert_eq!(effect_name(&h, effect), "Pitted rust");
+ assert!(h.query_by_label("Pitted rust").is_none(), "the effect stack closed");
+ click_selected_content_thumbnail(&mut h);
+ assert!(h.query_by_label("Pitted rust").is_some());
+}
+
#[test]
fn escape_in_the_effect_editor_keeps_the_name() {
let (mut h, effect) = effect_harness();
From 857fb1e3d08aa8e4f8fdd21697809693e662cbb3 Mon Sep 17 00:00:00 2001
From: vangel76
Date: Sun, 22 Nov 2026 17:15:46 +0100
Subject: [PATCH 012/138] Save projects in the background and show progress
---
crates/engine/src/bake/mesh_map_command.rs | 24 +--
crates/engine/src/file_cmds.rs | 165 +++++++++++++-----
crates/engine/src/painting.rs | 3 +-
crates/engine/src/path_tool.rs | 3 +-
crates/engine/src/session.rs | 37 +++-
crates/formats/src/project_file/mod.rs | 14 +-
.../src/project_file/ram_reservation.rs | 12 +-
.../formats/src/project_file/save_progress.rs | 69 ++++++++
crates/ui-egui/src/control.rs | 4 +
crates/ui-egui/src/display_settings.rs | 3 +-
crates/ui-egui/src/lib.rs | 29 ++-
crates/ui-egui/src/manual_save.rs | 88 ++++++++++
crates/ui-egui/src/menus.rs | 4 +
crates/ui-egui/src/shader_settings.rs | 3 +-
crates/ui-egui/src/toolbar.rs | 5 +
crates/ui-egui/src/windows.rs | 59 ++++---
crates/ui-egui/tests/it/file_dialogs.rs | 77 ++++++--
17 files changed, 468 insertions(+), 131 deletions(-)
create mode 100644 crates/formats/src/project_file/save_progress.rs
create mode 100644 crates/ui-egui/src/manual_save.rs
diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs
index fef27ea3..4e219bd1 100644
--- a/crates/engine/src/bake/mesh_map_command.rs
+++ b/crates/engine/src/bake/mesh_map_command.rs
@@ -56,7 +56,7 @@ pub(super) fn specs() -> Vec {
cmd!("bake.cage.set", "Load cage mesh", [], None, "{path} — a mesh with the low poly's triangles", always, cage_set),
cmd!("bake.cage.clear", "Remove cage mesh", [], None, "{}", always, |s, _| {
s.bake_meshes.cage = None;
- s.modified = true;
+ s.mark_modified();
Ok(meshes_json(s))
}),
]
@@ -274,7 +274,7 @@ impl Session {
for set in &mut self.doc.project.texture_sets {
set.bake.high_poly.use_low_as_high = false;
}
- self.modified = true;
+ self.mark_modified();
Ok(name)
}
@@ -285,7 +285,7 @@ impl Session {
}
let removed = self.bake_meshes.high.remove(index);
self.bake_meshes.rebuild();
- self.modified = true;
+ self.mark_modified();
Ok(removed)
}
@@ -303,7 +303,7 @@ impl Session {
m.base_color.clear();
let name = m.name.clone();
self.bake_meshes.cage = Some(m);
- self.modified = true;
+ self.mark_modified();
Ok(name)
}
@@ -347,20 +347,6 @@ impl Session {
}
}
}
-
- pub(crate) fn saved_bake_paint(&self) -> BTreeMap<(usize, BakePaintTarget), texturecraft_formats::BakePaintData> {
- self.doc
- .bake_paint
- .iter()
- .map(|(key, map)| (*key, texturecraft_formats::BakePaintData { width: map.width, height: map.height, values: map.values.clone() }))
- .collect()
- }
-
- /// The bake meshes for a project file: (high polys, cage).
- pub(crate) fn saved_bake_meshes(&self) -> (Vec, Option) {
- let entry = |m: &BakeMesh| (m.name.clone(), m.bytes.as_ref().clone());
- (self.bake_meshes.high.iter().map(entry).collect(), self.bake_meshes.cage.as_ref().map(entry))
- }
}
/// `bake.highPoly.list`: the high polys and the cage (also part of `project.inspect`).
@@ -392,7 +378,7 @@ fn high_remove(s: &mut Session, p: &Value) -> Result {
if boolp(p, "all") == Some(true) {
s.bake_meshes.high.clear();
s.bake_meshes.rebuild();
- s.modified = true;
+ s.mark_modified();
return Ok(meshes_json(s));
}
let index = match (u64p(p, "index"), strp(p, "name")) {
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index f493093b..fdc29bf1 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -16,6 +16,47 @@ use crate::commands::{CommandSpec, always, bad, normal_format_param, strp, u64p}
use crate::session::{Document, Session};
use crate::{EngineError, Result, cmd};
+fn project_with_resources(
+ doc: &Document,
+ mesh: Option<&(String, Arc>)>,
+ bake_meshes: &crate::BakeMeshes,
+ resources: BTreeMap,
+) -> ProjectFile {
+ let mut pixels = doc.pixels.clone();
+
+ // Drop pixel images whose size no longer matches their texture set
+ let size_of = |id: texturecraft_core::LayerId| {
+ doc.project.locate(id).and_then(|(ts, _, _)| doc.project.texture_sets.get(ts)).map(TextureSet::size).or_else(|| {
+ doc.project
+ .effect(id)
+ .and_then(|(owner, _)| doc.project.locate(owner))
+ .and_then(|(ts, _, _)| doc.project.texture_sets.get(ts))
+ .map(TextureSet::size)
+ })
+ };
+ pixels.layers.retain(|(id, _), img| size_of(*id) == Some((img.width(), img.height())));
+ pixels.masks.retain(|id, img| size_of(*id) == Some((img.width(), img.height())));
+
+ let bake_mesh = |mesh: &crate::BakeMesh| (mesh.name.clone(), mesh.bytes.as_ref().clone());
+ let bake_paint = doc
+ .bake_paint
+ .iter()
+ .map(|(key, map)| (*key, texturecraft_formats::BakePaintData { width: map.width, height: map.height, values: map.values.clone() }))
+ .collect();
+ ProjectFile {
+ project: doc.project.clone(),
+ pixels,
+ baked: doc.baked.clone(),
+ mesh: mesh.map(|(extension, bytes)| (extension.clone(), bytes.as_ref().clone())),
+ high_poly: bake_meshes.high.iter().map(bake_mesh).collect(),
+ cage: bake_meshes.cage.as_ref().map(bake_mesh),
+ bake_paint,
+ thumbnail: None,
+ resources,
+ warnings: Vec::new(),
+ }
+}
+
pub fn specs() -> Vec {
vec![
cmd!(
@@ -171,7 +212,7 @@ impl Session {
// Packed mesh files can have spare capacity that the project would otherwise retain
let mut source = bytes.into_owned();
source.shrink_to_fit();
- session.mesh_source = Some((extension, source));
+ session.mesh_source = Some((extension, Arc::new(source)));
session.doc.project.mesh_file = leaf_of(file_name);
session.doc.project.cameras = imported.cameras;
@@ -204,7 +245,7 @@ impl Session {
};
check_materials(&pf.project, &mesh)?;
- let source = pf.mesh.clone();
+ let source = pf.mesh;
let resources = pf.resources.into_iter().map(|(k, v)| (k, std::sync::Arc::new(v))).collect();
let mut s =
Session::new(Document { bake_paint: Default::default(), project: pf.project, pixels: pf.pixels, baked: pf.baked, resources }, mesh, source)?;
@@ -220,44 +261,12 @@ impl Session {
/// The project with independently owned resource bytes.
pub fn project_file(&self) -> ProjectFile {
let resources = self.doc.resources.iter().map(|(name, bytes)| (name.clone(), bytes.as_ref().clone())).collect();
- self.project_with_resources(resources)
+ project_with_resources(&self.doc, self.mesh_source.as_ref(), &self.bake_meshes, resources)
}
/// A save snapshot that shares immutable resource payloads with the document.
pub fn project_snapshot(&self) -> ProjectFile>> {
- self.project_with_resources(self.doc.resources.clone())
- }
-
- fn project_with_resources(&self, resources: BTreeMap) -> ProjectFile {
- let mut pixels = self.doc.pixels.clone();
-
- // Drop pixel images whose size no longer matches their texture set
- let size_of = |id: texturecraft_core::LayerId| {
- self.doc.project.locate(id).and_then(|(ts, _, _)| self.doc.project.texture_sets.get(ts)).map(TextureSet::size).or_else(|| {
- self.doc
- .project
- .effect(id)
- .and_then(|(owner, _)| self.doc.project.locate(owner))
- .and_then(|(ts, _, _)| self.doc.project.texture_sets.get(ts))
- .map(TextureSet::size)
- })
- };
- pixels.layers.retain(|(id, _), img| size_of(*id) == Some((img.width(), img.height())));
- pixels.masks.retain(|id, img| size_of(*id) == Some((img.width(), img.height())));
-
- let (high_poly, cage) = self.saved_bake_meshes();
- ProjectFile {
- project: self.doc.project.clone(),
- pixels,
- baked: self.doc.baked.clone(),
- mesh: self.mesh_source.clone(),
- high_poly,
- cage,
- bake_paint: self.saved_bake_paint(),
- thumbnail: None,
- resources,
- warnings: Vec::new(),
- }
+ project_with_resources(&self.doc, self.mesh_source.as_ref(), &self.bake_meshes, self.doc.resources.clone())
}
pub fn to_project_bytes(&self) -> Result> {
@@ -449,6 +458,7 @@ fn plan(session: &mut Session, params: &Value) -> Result {
mod native {
use super::*;
use std::path::Path;
+ use texturecraft_formats::project_file::SaveProgress;
pub fn path_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<&'a str> {
strp(p, key).filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(cmd, format!("`{key}` is required")))
@@ -484,21 +494,82 @@ mod native {
}
pub fn save_to(s: &mut Session, path: &str, adopt: bool) -> Result {
- let path = if ext_of(path) == PROJECT_EXT { path.to_string() } else { format!("{path}.{PROJECT_EXT}") };
- let mut reservation = texturecraft_formats::RamReservation::for_save().map_err(fe)?;
- reservation.save(Path::new(&path), &s.project_snapshot()).map_err(fe)?;
+ let output = s.save_task(path, adopt).run(None)?;
+ output.apply(s);
+ Ok(json!({ "path": output.path }))
+ }
- if adopt {
- s.path = Some(path.clone());
- s.modified = false;
+ struct SaveTarget {
+ project_id: u64,
+ revision: u64,
+ adopt: bool,
+ path: String,
+ }
+
+ /// A manual save of the document at the moment it was requested. Large payloads are shared
+ /// until the worker assembles the archive.
+ pub struct SaveTask {
+ target: SaveTarget,
+ doc: Document,
+ mesh: Option<(String, Arc>)>,
+ bake_meshes: crate::BakeMeshes,
+ }
+
+ impl Session {
+ pub fn save_task(&self, path: &str, adopt: bool) -> SaveTask {
+ let path = if ext_of(path) == PROJECT_EXT { path.to_string() } else { format!("{path}.{PROJECT_EXT}") };
+ SaveTask {
+ target: SaveTarget { project_id: self.project_id, revision: self.save_revision, adopt, path },
+ doc: self.doc.clone(),
+ mesh: self.mesh_source.clone(),
+ bake_meshes: self.bake_meshes.clone(),
+ }
+ }
+ }
+
+ impl SaveTask {
+ /// Complete the atomic write on the worker. Waiting for a previous save to release the
+ /// RAM allowance also happens here.
+ pub fn run(self, progress: Option<&SaveProgress>) -> Result {
+ let mut reservation = texturecraft_formats::RamReservation::for_save().map_err(fe)?;
+ let snapshot = project_with_resources(&self.doc, self.mesh.as_ref(), &self.bake_meshes, self.doc.resources.clone());
+ let path = Path::new(&self.target.path);
+ match progress {
+ Some(progress) => reservation.save_with_progress(path, &snapshot, progress),
+ None => reservation.save(path, &snapshot),
+ }
+ .map_err(fe)?;
+ Ok(SaveOutput { path: self.target.path, project_id: self.target.project_id, revision: self.target.revision, adopt: self.target.adopt })
+ }
+ }
+
+ /// An archive that was written successfully. Only the same project can adopt its path.
+ pub struct SaveOutput {
+ pub path: String,
+ project_id: u64,
+ revision: u64,
+ adopt: bool,
+ }
+
+ impl SaveOutput {
+ /// Apply the saved path without clearing edits made since the snapshot.
+ pub fn apply(&self, session: &mut Session) {
+ if session.project_id != self.project_id {
+ return;
+ }
+ if self.adopt {
+ session.path = Some(self.path.clone());
+ if session.save_revision == self.revision && !session.stroke_active() {
+ session.modified = false;
+ }
+ }
+ session.log.info("Project", format!("Saved {}", self.path));
}
- s.log.info("Project", format!("Saved {path}"));
- Ok(json!({ "path": path }))
}
}
#[cfg(not(target_arch = "wasm32"))]
-pub use native::{absolute, open_path, read_mesh};
+pub use native::{SaveOutput, SaveTask, absolute, open_path, read_mesh};
/// `file.new {mesh, name?, resolution?, uvTiles?, template?, importCameras?}`: a new project from the
/// mesh file `mesh`, remembering its path for Reimport mesh.
@@ -597,7 +668,7 @@ impl Session {
let (mesh, source, warnings, mesh_file) = match file {
Some(f) => {
let m = texturecraft_formats::import_mesh_bytes(&f.name, &f.bytes).map_err(fe)?.mesh;
- (m, Some((ext_of(&f.name), f.bytes)), f.warnings, leaf_of(&f.name))
+ (m, Some((ext_of(&f.name), Arc::new(f.bytes))), f.warnings, leaf_of(&f.name))
}
None => match &self.mesh_source {
Some((ext, bytes)) => {
@@ -612,7 +683,7 @@ impl Session {
doc.project.mesh = format!("mesh.{ext}");
doc.project.mesh_file = mesh_file;
}
- let mut next = Session::new(doc, mesh, source)?;
+ let mut next = Session::new_with_source(doc, mesh, source)?;
next.log.warnings("Importer", warnings);
next.path = self.path.clone();
next.sync_images();
diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs
index 62010b50..9ca5836a 100644
--- a/crates/engine/src/painting.rs
+++ b/crates/engine/src/painting.rs
@@ -576,8 +576,7 @@ impl Session {
self.undo.remove(0);
}
self.redo.clear();
- self.modified = true;
- self.revision = self.revision.wrapping_add(1);
+ self.mark_modified();
// The live preview already shows the committed result: the stroke's tiles recomposite
// from the committed pixels at low priority, without holding up this frame.
self.mark_settle(st.ts, st.target, st.canvas.dirty.iter().copied());
diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs
index 5398501f..63d047b2 100644
--- a/crates/engine/src/path_tool.rs
+++ b/crates/engine/src/path_tool.rs
@@ -922,8 +922,7 @@ impl Session {
} else {
self.invalidate_changed(&before);
}
- self.revision = self.revision.wrapping_add(1);
- self.modified = true;
+ self.mark_modified();
Ok((painted, before))
}
diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs
index b493a8b6..4f2c8b77 100644
--- a/crates/engine/src/session.rs
+++ b/crates/engine/src/session.rs
@@ -418,7 +418,7 @@ pub struct Session {
pub(crate) source: Arc,
pub bvh: Arc,
/// Original mesh file (saved inside the project); None for built-in meshes.
- pub mesh_source: Option<(String, Vec)>,
+ pub mesh_source: Option<(String, Arc>)>,
/// High-definition meshes and cage for baking (saved inside the project).
pub bake_meshes: crate::BakeMeshes,
pub caches: Vec,
@@ -467,6 +467,9 @@ pub struct Session {
/// (see [`crate::commands::check_enabled`]).
pub project_open: bool,
pub modified: bool,
+ /// Edits to saved data, independent of viewport and tool changes.
+ #[cfg(not(target_arch = "wasm32"))]
+ pub(crate) save_revision: u64,
/// Bumps on every document change.
pub revision: u64,
/// Messages for the UI (status bar / toasts).
@@ -492,6 +495,10 @@ pub struct Session {
impl Session {
/// A session for `project` on `mesh` (its sets must reference mesh materials), with UV-tiled sets' UVs mapped into their atlas ([`Session::source_mesh`])
pub fn new(doc: Document, mesh: Mesh, mesh_source: Option<(String, Vec)>) -> Result {
+ Self::new_with_source(doc, mesh, mesh_source.map(|(extension, bytes)| (extension, Arc::new(bytes))))
+ }
+
+ pub(crate) fn new_with_source(doc: Document, mesh: Mesh, mesh_source: Option<(String, Arc>)>) -> Result {
mesh.validate().map_err(|error| EngineError::Other(error.to_string()))?;
let source = Arc::new(mesh);
@@ -539,6 +546,8 @@ impl Session {
path: None,
project_open: true,
modified: false,
+ #[cfg(not(target_arch = "wasm32"))]
+ save_revision: 0,
revision: 1,
log: crate::log::SessionLog::new(),
log_id: next_mesh_id(),
@@ -567,6 +576,10 @@ impl Session {
pub fn switch_to(&mut self, mut next: Session) {
// Invalidate caches even when both projects were loaded with the same revision
next.revision = self.revision.wrapping_add(1);
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ next.save_revision = self.save_revision.wrapping_add(1);
+ }
next.viewport = self.viewport;
next.export_presets = std::mem::take(&mut self.export_presets);
@@ -711,8 +724,7 @@ impl Session {
self.path_steps = Default::default();
}
- self.modified = true;
- self.revision = self.revision.wrapping_add(1);
+ self.mark_modified();
if !(merge && self.undo.last().is_some_and(|(l, _)| l == label)) {
self.undo.push((label.to_string(), before));
}
@@ -723,8 +735,7 @@ impl Session {
/// A change from `other` to the current document that is not an undo step (a path preview)
pub(crate) fn changed_without_history(&mut self, other: &Document) {
- self.modified = true;
- self.revision = self.revision.wrapping_add(1);
+ self.mark_modified();
self.invalidate_changed(other);
}
@@ -835,14 +846,23 @@ impl Session {
/// Mark the document changed and every texture set dirty.
pub fn touched(&mut self) {
- self.modified = true;
- self.revision = self.revision.wrapping_add(1);
+ self.mark_modified();
self.sync_caches();
for c in &mut self.caches {
c.invalidate_all();
}
}
+ /// Mark saved data changed without invalidating the texture sets.
+ pub fn mark_modified(&mut self) {
+ self.modified = true;
+ self.revision = self.revision.wrapping_add(1);
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ self.save_revision = self.save_revision.wrapping_add(1);
+ }
+ }
+
/// Make caches agree with the project's texture sets (resolution or channel changes).
pub fn sync_caches(&mut self) {
let sets = self.doc.project.texture_sets.clone();
@@ -953,11 +973,10 @@ impl Session {
fn after_history(&mut self, other: &Document) {
// Pending operations may still hold layer IDs from the discarded snapshot
self.doc.project.next_id = self.doc.project.next_id.max(other.project.next_id);
- self.modified = true;
+ self.mark_modified();
// Layers picked together belong to the stack they were picked in
self.multi.clear();
- self.revision = self.revision.wrapping_add(1);
self.invalidate_changed(other);
// An undone add or duplicate takes the selected effect away
diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs
index c5bf3bdb..06a504ca 100644
--- a/crates/formats/src/project_file/mod.rs
+++ b/crates/formats/src/project_file/mod.rs
@@ -38,10 +38,12 @@ mod load_budget;
mod project_open_limit;
mod ram_operation;
mod ram_reservation;
+mod save_progress;
#[cfg(not(target_arch = "wasm32"))]
pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, configured_ram_budget, save_ram_budget, set_save_resources};
pub use project_open_limit::{DEFAULT_PROJECT_OPEN_LIMIT_GIB, project_open_limit_gib, set_project_open_limit_gib};
pub use ram_reservation::RamReservation;
+pub use save_progress::SaveProgress;
const KIND: &str = "project file";
#[cfg(test)]
@@ -109,11 +111,11 @@ pub fn save_project(path: &std::path::Path, project_file: &ProjectFile) -> Resul
}
#[cfg(not(target_arch = "wasm32"))]
-fn write_project_atomic(path: &std::path::Path, project_file: &ProjectFile>>) -> Result<()> {
+fn write_project_atomic(path: &std::path::Path, project_file: &ProjectFile>>, progress: Option<&SaveProgress>) -> Result<()> {
let (temporary_path, file) = crate::create_temp(path)?;
let result = (|| -> Result<()> {
let mut file = std::io::BufWriter::new(file);
- write_project(&mut file, project_file)?;
+ write_project(&mut file, project_file, progress)?;
file.into_inner().map_err(|error| error.into_error())?.sync_all()?;
std::fs::rename(&temporary_path, path)?;
Ok(())
@@ -276,9 +278,13 @@ fn entries(pf: &ProjectFile>>) -> Result>> {
Ok(out)
}
-fn write_project(out: W, pf: &ProjectFile>>) -> Result<()> {
+fn write_project(out: W, pf: &ProjectFile>>, progress: Option<&SaveProgress>) -> Result<()> {
let mut zip = ZipWriter::new(out);
- entries::write_entries(&mut zip, entries(pf)?)?;
+ let mut entries = entries(pf)?;
+ if let Some(progress) = progress {
+ progress.track(&mut entries);
+ }
+ entries::write_entries(&mut zip, entries)?;
zip.finish().map_err(zip_err)?;
Ok(())
}
diff --git a/crates/formats/src/project_file/ram_reservation.rs b/crates/formats/src/project_file/ram_reservation.rs
index 72857c15..caff4af1 100644
--- a/crates/formats/src/project_file/ram_reservation.rs
+++ b/crates/formats/src/project_file/ram_reservation.rs
@@ -2,6 +2,8 @@ use std::borrow::Borrow;
use std::io::Cursor;
use std::sync::{Condvar, Mutex};
+#[cfg(not(target_arch = "wasm32"))]
+use super::SaveProgress;
use super::{ProjectFile, ram_operation::RamOperation, write_project};
use crate::{FormatError, Result};
@@ -57,14 +59,20 @@ impl RamReservation {
pub fn save_bytes(&mut self, project_file: &ProjectFile>>) -> Result> {
self.check_save()?;
let mut out = Cursor::new(Vec::new());
- write_project(&mut out, project_file)?;
+ write_project(&mut out, project_file, None)?;
Ok(out.into_inner())
}
#[cfg(not(target_arch = "wasm32"))]
pub fn save(&mut self, path: &std::path::Path, project_file: &ProjectFile>>) -> Result<()> {
self.check_save()?;
- super::write_project_atomic(path, project_file)
+ super::write_project_atomic(path, project_file, None)
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ pub fn save_with_progress(&mut self, path: &std::path::Path, project_file: &ProjectFile>>, progress: &SaveProgress) -> Result<()> {
+ self.check_save()?;
+ super::write_project_atomic(path, project_file, Some(progress))
}
fn check_save(&self) -> Result<()> {
diff --git a/crates/formats/src/project_file/save_progress.rs b/crates/formats/src/project_file/save_progress.rs
new file mode 100644
index 00000000..4e7c1810
--- /dev/null
+++ b/crates/formats/src/project_file/save_progress.rs
@@ -0,0 +1,69 @@
+use std::io::{self, Write};
+use std::sync::atomic::{AtomicU64, Ordering};
+
+use super::entries::Entry;
+
+/// Estimated archive progress, based on the payload processed by the entry writers.
+/// Completing the archive, syncing it to disk, and replacing the destination can take longer.
+#[derive(Default)]
+pub struct SaveProgress {
+ total: AtomicU64,
+ processed: AtomicU64,
+}
+
+impl SaveProgress {
+ pub fn fraction(&self) -> f32 {
+ let total = self.total.load(Ordering::Relaxed);
+ if total == 0 {
+ return 0.0;
+ }
+ let processed = self.processed.load(Ordering::Relaxed).min(total);
+ // Leave room for the final write and atomic replacement.
+ 0.95 * (processed as f64 / total as f64) as f32
+ }
+
+ pub(super) fn track<'a>(&'a self, entries: &mut [Entry<'a>]) {
+ self.processed.store(0, Ordering::Relaxed);
+ self.total.store(entries.iter().fold(0u64, |sum, entry| sum.saturating_add(entry.weight)), Ordering::Relaxed);
+ for entry in entries {
+ let body = std::mem::replace(&mut entry.body, Box::new(|_| Ok(())));
+ let remaining = entry.weight;
+ entry.body = Box::new(move |target| {
+ let mut writer = ProgressWriter { target, progress: self, remaining, pending: 0 };
+ body(&mut writer)?;
+ writer.report();
+ Ok(())
+ });
+ }
+ }
+}
+
+struct ProgressWriter<'a> {
+ target: &'a mut dyn Write,
+ progress: &'a SaveProgress,
+ remaining: u64,
+ pending: u64,
+}
+
+impl ProgressWriter<'_> {
+ fn report(&mut self) {
+ self.progress.processed.fetch_add(std::mem::take(&mut self.pending), Ordering::Relaxed);
+ }
+}
+
+impl Write for ProgressWriter<'_> {
+ fn write(&mut self, bytes: &[u8]) -> io::Result {
+ let written = self.target.write(bytes)?;
+ let counted = (written as u64).min(self.remaining);
+ self.remaining -= counted;
+ self.pending += counted;
+ if self.pending >= 64 << 10 {
+ self.report();
+ }
+ Ok(written)
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ self.target.flush()
+ }
+}
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 6b471ff5..6e999d7d 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -141,6 +141,10 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para
},
"command.run" => {
let Some(id) = params.get("id").and_then(Value::as_str) else { return err("`id` is required") };
+ #[cfg(not(target_arch = "wasm32"))]
+ if app.save_job.is_some() && crate::manual_save::is_save(id) {
+ return err("A manual project save is already running");
+ }
let command_params = params.get("params").cloned().unwrap_or(Value::Null);
let before = app.session.camera;
match texturecraft_engine::execute(&mut app.session, id, &command_params) {
diff --git a/crates/ui-egui/src/display_settings.rs b/crates/ui-egui/src/display_settings.rs
index 7c0bc14d..6a8e56b2 100644
--- a/crates/ui-egui/src/display_settings.rs
+++ b/crates/ui-egui/src/display_settings.rs
@@ -57,8 +57,7 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
}
app.session.doc.project.display = display;
- app.session.modified = true;
- app.session.revision = app.session.revision.wrapping_add(1);
+ app.session.mark_modified();
}
if import_hdr {
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 1a8508eb..f6b25860 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -50,6 +50,8 @@ mod levels_properties;
mod line_snap;
mod list_action;
pub mod log_panel;
+#[cfg(not(target_arch = "wasm32"))]
+mod manual_save;
mod mask_preview_image;
mod material_preview_image;
pub mod menus;
@@ -189,6 +191,7 @@ pub struct Toast {
pub error: bool,
pub until: f64,
pub show_log: bool,
+ announce: bool,
}
pub struct TextureCraftApp {
@@ -267,10 +270,13 @@ pub struct TextureCraftApp {
/// Native file dialogs and their continuations (desktop only).
#[cfg(not(target_arch = "wasm32"))]
pub file_dialogs: file_dialogs::FileDialogs,
- /// The unsaved-changes dialog's Save is waiting on the Save dialog's answer.
+ /// A manual save running on the desktop archive writer.
+ #[cfg(not(target_arch = "wasm32"))]
+ pub(crate) save_job: Option,
+ /// The unsaved-changes dialog's Save is waiting for a path or a save result.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) saving_for_prompt: bool,
- /// That Save dialog saved the project; the prompt goes on at its next frame.
+ /// The requested save completed; the prompt goes on at its next frame.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) prompt_saved: bool,
/// The resolved keymap and its key dispatcher.
@@ -364,6 +370,8 @@ impl TextureCraftApp {
#[cfg(not(target_arch = "wasm32"))]
file_dialogs: file_dialogs::FileDialogs::new(cc.egui_ctx.clone()),
#[cfg(not(target_arch = "wasm32"))]
+ save_job: None,
+ #[cfg(not(target_arch = "wasm32"))]
saving_for_prompt: false,
#[cfg(not(target_arch = "wasm32"))]
prompt_saved: false,
@@ -504,13 +512,13 @@ impl TextureCraftApp {
}
pub fn toast(&mut self, text: impl Into, error: bool) {
- self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 }, show_log: false });
+ self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 }, show_log: false, announce: false });
}
/// An error toast that stays until the user dismisses it (for a problem that persists and
/// is reported once, like a texture set the GPU could not hold).
pub fn toast_sticky(&mut self, text: impl Into) {
- self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false });
+ self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false, announce: false });
}
/// Start baking texture sets in the background, one after another. Invalid set indices
@@ -871,6 +879,9 @@ impl TextureCraftApp {
/// and written on a worker thread; the project data is shared copy-on-write).
#[cfg(not(target_arch = "wasm32"))]
fn autosave(&mut self, now: f64) {
+ if self.save_job.is_some() {
+ return;
+ }
let period = autosave_period_seconds(self.ui.prefs.autosave_minutes);
// The clock starts at the first unsaved change
@@ -1023,7 +1034,10 @@ impl eframe::App for TextureCraftApp {
ctx.set_zoom_factor(scale);
}
#[cfg(not(target_arch = "wasm32"))]
- self.autosave(now);
+ {
+ self.poll_save(ctx);
+ self.autosave(now);
+ }
i18n::set_language(&self.ui.prefs.language);
#[cfg(target_arch = "wasm32")]
{
@@ -1198,7 +1212,10 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) {
ui.allocate_ui_with_layout(egui::vec2(width, 0.0), egui::Layout::top_down(egui::Align::Min), |ui| {
egui::ScrollArea::vertical().id_salt(("toast", i)).max_height(max_text_height).show(ui, |ui| {
ui.set_max_width(width);
- ui.add(egui::Label::new(egui::RichText::new(&t.text).color(tk.text_strong)).wrap());
+ let label = ui.add(egui::Label::new(egui::RichText::new(&t.text).color(tk.text_strong)).wrap());
+ if t.announce {
+ ui.ctx().accesskit_node_builder(label.id, |node| node.set_live(egui::accesskit::Live::Polite));
+ }
});
if t.show_log && ui.link(i18n::tr("Open Log")).clicked() {
show_log = true;
diff --git a/crates/ui-egui/src/manual_save.rs b/crates/ui-egui/src/manual_save.rs
new file mode 100644
index 00000000..c2481678
--- /dev/null
+++ b/crates/ui-egui/src/manual_save.rs
@@ -0,0 +1,88 @@
+//! Manual desktop saves share the atomic archive writer with autosave and headless saves.
+
+use std::sync::{Arc, mpsc};
+use std::time::Duration;
+
+use texturecraft_engine::{Result, file_cmds::SaveOutput, formats::project_file::SaveProgress};
+
+use crate::{
+ TextureCraftApp,
+ i18n::{tr, trf},
+};
+
+pub(crate) struct SaveJob {
+ progress: Arc,
+ output: mpsc::Receiver>,
+ project_id: u64,
+ for_prompt: bool,
+ remember: bool,
+ pub(crate) quit_after_save: bool,
+}
+
+pub(crate) fn is_save(id: &str) -> bool {
+ matches!(id, "file.save" | "file.saveAs" | "file.saveCopy")
+}
+
+impl TextureCraftApp {
+ pub(crate) fn start_save(&mut self, path: &str, adopt: bool, for_prompt: bool, remember: bool) -> bool {
+ if self.save_job.is_some() {
+ self.toast(tr("A project save is already running"), true);
+ return false;
+ }
+ if let Err(error) = self.session.end_stroke() {
+ self.toast(error.to_string(), true);
+ return false;
+ }
+
+ let task = self.session.save_task(path, adopt);
+ let progress = Arc::new(SaveProgress::default());
+ let worker_progress = progress.clone();
+ let output = crate::spawn_worker("texturecraft-save", move || task.run(Some(&worker_progress)));
+ self.save_job = Some(SaveJob { progress, output, project_id: self.session.project_id, for_prompt, remember, quit_after_save: false });
+ true
+ }
+
+ pub(crate) fn save_progress(&self) -> Option {
+ self.save_job.as_ref().map(|job| job.progress.fraction())
+ }
+
+ pub(crate) fn poll_save(&mut self, ctx: &egui::Context) {
+ let Some(job) = &self.save_job else { return };
+ let result = match job.output.try_recv() {
+ Ok(result) => result.map_err(|error| error.to_string()),
+ Err(mpsc::TryRecvError::Empty) => {
+ ctx.request_repaint_after(Duration::from_millis(80));
+ return;
+ }
+ Err(mpsc::TryRecvError::Disconnected) => Err(tr("The project save worker stopped").into()),
+ };
+ let Some(job) = self.save_job.take() else { return };
+ let same_project = job.project_id == self.session.project_id;
+ let continue_prompt = job.for_prompt && self.saving_for_prompt;
+ if job.for_prompt {
+ self.saving_for_prompt = false;
+ }
+
+ match result {
+ Ok(output) => {
+ output.apply(&mut self.session);
+ if job.remember {
+ crate::windows::remember(self, &output.path);
+ }
+ self.prompt_saved = continue_prompt && same_project && !self.session.modified && !self.session.stroke_active();
+ self.toast(trf("Saved {path}", &[("path", &output.path)]), false);
+ if job.quit_after_save && same_project {
+ ctx.send_viewport_cmd(egui::ViewportCommand::Close);
+ }
+ }
+ Err(error) => {
+ let message = trf("Could not save project: {error}", &[("error", &error)]);
+ self.session.log.warn("Project", message.clone());
+ self.toast(message, true);
+ }
+ }
+ if let Some(toast) = self.toasts.last_mut() {
+ toast.announce = true;
+ }
+ }
+}
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 7ec42c75..8aea36c1 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -175,6 +175,10 @@ fn tooltip_of(id: &str) -> Option<&'static str> {
/// Whether an item can run now
pub fn enabled(app: &TextureCraftApp, id: &str) -> bool {
+ #[cfg(not(target_arch = "wasm32"))]
+ if app.save_job.is_some() && crate::manual_save::is_save(id) {
+ return false;
+ }
if UNAVAILABLE.contains(&id) {
return false;
}
diff --git a/crates/ui-egui/src/shader_settings.rs b/crates/ui-egui/src/shader_settings.rs
index ba00a046..88dd9ae4 100644
--- a/crates/ui-egui/src/shader_settings.rs
+++ b/crates/ui-egui/src/shader_settings.rs
@@ -77,8 +77,7 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
if display != app.session.doc.project.display {
app.session.doc.project.display = display;
- app.session.modified = true;
- app.session.revision = app.session.revision.wrapping_add(1);
+ app.session.mark_modified();
}
}
diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs
index dc2f3453..a28a5360 100644
--- a/crates/ui-egui/src/toolbar.rs
+++ b/crates/ui-egui/src/toolbar.rs
@@ -536,6 +536,11 @@ pub fn status_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
.frame(egui::Frame::NONE.fill(tk.chrome).inner_margin(egui::Margin::symmetric(10, 0)))
.show(ui, |ui| {
ui.horizontal_centered(|ui| {
+ #[cfg(not(target_arch = "wasm32"))]
+ if let Some(progress) = app.save_progress() {
+ ui.add(egui::ProgressBar::new(progress).desired_width(160.0).desired_height(10.0).text(RichText::new(tr("Saving project")).size(10.0)));
+ ui.separator();
+ }
if let Some(p) = app.bake_progress() {
ui.add(egui::ProgressBar::new(p).desired_width(160.0).desired_height(10.0).text(RichText::new(tr("Baking")).size(10.0)));
if ui.small_button(tr("Cancel")).clicked() {
diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs
index 0624e1be..8473de9a 100644
--- a/crates/ui-egui/src/windows.rs
+++ b/crates/ui-egui/src/windows.rs
@@ -92,7 +92,19 @@ pub(crate) fn close_request(app: &mut TextureCraftApp, ctx: &egui::Context) {
{
app.toast(error.to_string(), true);
}
- if closing && ask_to_save(app, crate::state::Unsaved::Quit) {
+ #[cfg(not(target_arch = "wasm32"))]
+ let waiting_for_save = if closing
+ && !app.session.modified
+ && let Some(job) = &mut app.save_job
+ {
+ job.quit_after_save = true;
+ true
+ } else {
+ false
+ };
+ #[cfg(target_arch = "wasm32")]
+ let waiting_for_save = false;
+ if closing && (waiting_for_save || ask_to_save(app, crate::state::Unsaved::Quit)) {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
if ctx.input(|i| i.viewport().minimized == Some(true)) {
ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
@@ -110,7 +122,7 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) {
let Some(pending) = app.ui.windows.unsaved.clone() else { return };
#[cfg(not(target_arch = "wasm32"))]
- let (waiting_for_save, saved_by_dialog) = (app.saving_for_prompt, std::mem::take(&mut app.prompt_saved));
+ let (waiting_for_save, saved_by_dialog) = (app.saving_for_prompt || app.save_job.is_some(), std::mem::take(&mut app.prompt_saved));
#[cfg(target_arch = "wasm32")]
let (waiting_for_save, saved_by_dialog) = (false, false);
@@ -129,7 +141,7 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) {
// One row keeps the window to its contents; a bare right-to-left layout fills the screen height
ui.horizontal(|ui| {
- // The answers wait while the Save dialog is open
+ // Wait for the path picker or an active save to finish.
ui.add_enabled_ui(!waiting_for_save, |ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.add(primary_button(ui, tr("Save"))).clicked() {
@@ -156,11 +168,13 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) {
let discard_after_create = matches!(pending, Unsaved::CreateProject(_)) && save_first == Some(false) && app.session.modified;
match save_first {
Some(true) => {
- // An untitled project is saved from a dialog that answers on a later frame
#[cfg(not(target_arch = "wasm32"))]
{
- app.saving_for_prompt = app.session.path.is_none();
+ app.saving_for_prompt = true;
+ file_action(app, ctx, "file.save");
+ return;
}
+ #[cfg(target_arch = "wasm32")]
file_action(app, ctx, "file.save");
}
// Going ahead anyway: the changes are let go
@@ -484,15 +498,16 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) ->
});
true
}
- "file.save" if app.session.path.is_some() => {
- if let Some(result) = app.run("file.save", json!({})) {
- let saved_path = result["path"].as_str().unwrap_or_default();
- app.toast(trf("Saved {path}", &[("path", &saved_path)]), false);
- }
- true
- }
"file.save" | "file.saveAs" => {
- ask_save_project(app, "file.saveAs");
+ if id == "file.save"
+ && let Some(path) = app.session.path.clone()
+ {
+ if !app.start_save(&path, true, app.saving_for_prompt, false) {
+ app.saving_for_prompt = false;
+ }
+ } else {
+ ask_save_project(app, "file.saveAs");
+ }
true
}
"file.saveCopy" => {
@@ -568,7 +583,7 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) ->
}
}
-/// Asks where to save the project and runs `cmd` with the answer. Each caller is its own dialog
+/// Asks where to save the project and starts the worker with the answer. Each caller is its own dialog
/// request, so Save As and Save a Copy queue separately.
#[cfg(not(target_arch = "wasm32"))]
#[track_caller]
@@ -578,19 +593,11 @@ fn ask_save_project(app: &mut TextureCraftApp, cmd: &'static str) {
// Save a Copy leaves the project unsaved, so it never answers the unsaved-changes prompt.
let for_prompt = app.saving_for_prompt && cmd == "file.saveAs";
let asked = app.ask_file(dialog, Bound::Project, move |app, paths| {
- let mut saved = false;
- if let Some(p) = paths.first() {
- let path = p.display().to_string();
- saved = app.run(cmd, json!({"path": path})).is_some();
- if saved {
- remember(app, &path);
- app.toast(trf("Saved {path}", &[("path", &path)]), false);
- }
- }
- // The answer ends the wait. A canceled or failed save leaves the prompt open for an answer.
- if for_prompt {
+ let for_prompt = for_prompt && app.saving_for_prompt;
+ let started = paths.first().is_some_and(|p| app.start_save(&p.display().to_string(), cmd != "file.saveCopy", for_prompt, true));
+ // Canceled dialogs and failures leave the prompt open for another answer.
+ if for_prompt && !started {
app.saving_for_prompt = false;
- app.prompt_saved = saved && !app.session.modified;
}
});
// A Save As already on its way answers for itself: the prompt's buttons stay usable.
diff --git a/crates/ui-egui/tests/it/file_dialogs.rs b/crates/ui-egui/tests/it/file_dialogs.rs
index a8876e9e..d9ff167b 100644
--- a/crates/ui-egui/tests/it/file_dialogs.rs
+++ b/crates/ui-egui/tests/it/file_dialogs.rs
@@ -1,6 +1,7 @@
//! Native file dialogs answer on a later frame; the tests answer them without a window.
use std::path::{Path, PathBuf};
+use std::time::{Duration, Instant};
use egui::{ViewportCommand, ViewportEvent, ViewportId};
use egui_kittest::Harness;
@@ -10,6 +11,8 @@ use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::file_dialogs::{Answer, Request};
use texturecraft_ui_egui::state::Unsaved;
+use super::temp_dir::TempDir;
+
fn harness(modified: bool) -> Harness<'static, TextureCraftApp> {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
session.modified = modified;
@@ -198,7 +201,7 @@ fn a_mesh_change_keeps_the_answer_for_the_same_project() {
answer(&mut h, move |_| Answer::Paths(vec![path.clone()]));
invoke(&mut h, "file.saveAs");
h.state_mut().session.mesh_id += 1;
- h.run_steps(3);
+ wait_for(&mut h, |h| h.state().session.path.as_deref() == file.to_str());
assert!(file.exists(), "a reimport or a UV layout change is still the same project");
}
@@ -217,6 +220,15 @@ fn sends(h: &mut Harness<'_, TextureCraftApp>, frames: usize, cmd: &ViewportComm
})
}
+fn wait_for(h: &mut Harness<'_, TextureCraftApp>, ready: impl Fn(&Harness<'_, TextureCraftApp>) -> bool) {
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while !ready(h) {
+ assert!(Instant::now() < deadline, "save did not finish");
+ h.step();
+ std::thread::yield_now();
+ }
+}
+
fn untitled_with_prompt(h: &mut Harness<'_, TextureCraftApp>) {
h.state_mut().session.path = None;
request_close(h);
@@ -236,16 +248,61 @@ fn closing_during_a_stroke_finishes_it_and_asks() {
#[test]
fn save_in_the_prompt_goes_on_once_the_dialog_has_saved() {
- let file = temp_file("prompt-save", "saved.tcraft");
+ let temp = TempDir::new("prompt-save");
+ for untitled in [true, false] {
+ let file = temp.join(if untitled { "new.tcraft" } else { "existing.tcraft" });
+ let mut h = harness(true);
+ h.state_mut().session.path = (!untitled).then(|| file.display().to_string());
+ request_close(&mut h);
+ let path = file.clone();
+ answer(&mut h, move |_| Answer::Paths(vec![path.clone()]));
+ h.get_by_label("Save").click();
+ wait_for(&mut h, |h| h.output().viewport_output.get(&ViewportId::ROOT).is_some_and(|v| v.commands.contains(&ViewportCommand::Close)));
+ assert!(file.exists());
+ assert!(!h.state().session.modified);
+ assert!(h.state().ui.windows.unsaved.is_none());
+ }
+}
+
+#[test]
+fn a_background_save_preserves_edits_made_while_the_file_is_written() {
+ let temp = TempDir::new("save-edits");
+ let file = temp.join("project.tcraft");
let mut h = harness(true);
- untitled_with_prompt(&mut h);
- let path = file.clone();
- answer(&mut h, move |_| Answer::Paths(vec![path.clone()]));
- h.get_by_label("Save").click();
- assert!(sends(&mut h, 5, &ViewportCommand::Close), "the close goes on after the save");
- assert!(file.exists());
- assert!(!h.state().session.modified);
- assert!(h.state().ui.windows.unsaved.is_none());
+ h.state_mut().session.path = Some(file.display().to_string());
+ let original = h.state().session.doc.project.texture_sets[0].name.clone();
+ invoke(&mut h, "file.save");
+ assert!(!texturecraft_ui_egui::menus::enabled(h.state(), "file.save"), "the save returns with a worker still to collect");
+ let rename = h.state_mut().run("textureSet.rename", serde_json::json!({"ts": 0, "name": "Edited while saving"}));
+ assert!(rename.is_some(), "editing remains available");
+
+ wait_for(&mut h, |h| texturecraft_ui_egui::menus::enabled(h.state(), "file.save"));
+ let saved = texturecraft_engine::formats::load_project(&file).unwrap();
+ assert_eq!(saved.project.texture_sets[0].name, original, "the first save writes the snapshot it started with");
+ assert_eq!(h.state().session.doc.project.texture_sets[0].name, "Edited while saving");
+ assert!(h.state().session.modified, "the later edit still needs to be saved");
+
+ invoke(&mut h, "file.save");
+ h.state_mut().run("camera.view.front", serde_json::Value::Null);
+ wait_for(&mut h, |h| texturecraft_ui_egui::menus::enabled(h.state(), "file.save"));
+ let saved = texturecraft_engine::formats::load_project(&file).unwrap();
+ assert_eq!(saved.project.texture_sets[0].name, "Edited while saving");
+ assert!(!h.state().session.modified, "moving the camera alone does not create an unsaved edit");
+}
+
+#[test]
+fn a_failed_background_save_keeps_the_project_and_its_path() {
+ let temp = TempDir::new("save-failure");
+ let file = temp.join("current.tcraft");
+ let missing_parent = temp.join("missing").join("as.tcraft");
+ let mut h = harness(true);
+ h.state_mut().session.path = Some(file.display().to_string());
+ answer(&mut h, move |_| Answer::Paths(vec![missing_parent.clone()]));
+ invoke(&mut h, "file.saveAs");
+ wait_for(&mut h, |h| h.state().toasts.iter().any(|toast| toast.error));
+ assert!(h.state().session.modified);
+ assert_eq!(h.state().session.path.as_deref(), file.to_str());
+ assert!(texturecraft_ui_egui::menus::enabled(h.state(), "file.saveAs"));
}
#[test]
From 2e551bbd60861756ad55b7ed198df05786ea6514 Mon Sep 17 00:00:00 2001
From: vangel76
Date: Sun, 22 Nov 2026 23:21:13 +0100
Subject: [PATCH 013/138] Wait for the background save in the rename anchor
tests
---
crates/ui-egui/tests/it/rename_anchor.rs | 9 ++++++++-
1 file changed, 8 insertions(+), 1 deletion(-)
diff --git a/crates/ui-egui/tests/it/rename_anchor.rs b/crates/ui-egui/tests/it/rename_anchor.rs
index f8ee1763..3f0b57c3 100644
--- a/crates/ui-egui/tests/it/rename_anchor.rs
+++ b/crates/ui-egui/tests/it/rename_anchor.rs
@@ -42,7 +42,14 @@ fn save_to(h: &mut Harness<'_, TextureCraftApp>, file: &Path) {
h.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![path.clone()]))));
let ctx = h.ctx.clone();
texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "file.saveAs");
- h.run_steps(3);
+ // The save runs on a worker: step frames until the app has collected it, as the app does
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
+ h.step();
+ while h.state().session.modified || !texturecraft_ui_egui::menus::enabled(h.state(), "file.saveAs") {
+ assert!(std::time::Instant::now() < deadline, "the save did not finish");
+ h.step();
+ std::thread::yield_now();
+ }
assert!(file.exists(), "Save as wrote the project");
assert!(!h.state().session.modified, "the project counts as saved");
}
From 34e8bb0d92107bdd7110ff11e5567b40e2de2004 Mon Sep 17 00:00:00 2001
From: vangel76
Date: Sun, 22 Nov 2026 23:22:49 +0100
Subject: [PATCH 014/138] Open the inherited mask effects from an instance's
mask thumbnail
---
crates/engine/src/layer_cmds.rs | 11 +++++++--
crates/ui-egui/src/dock.rs | 22 +++++++++++-------
crates/ui-egui/tests/it/layers_panel.rs | 30 +++++++++++++++++++++++++
3 files changed, 53 insertions(+), 10 deletions(-)
diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs
index 56d2fc2e..b7b38f76 100644
--- a/crates/engine/src/layer_cmds.rs
+++ b/crates/engine/src/layer_cmds.rs
@@ -297,8 +297,9 @@ fn select(s: &mut Session, p: &Value) -> Result {
}
Some(Value::String(t)) if t == "content" => StackTarget::Content,
Some(v) => match v.as_u64() {
- Some(e) if s.doc.project.effect(LayerId(e)).is_some_and(|(owner, _)| owner == id) => StackTarget::Effect(LayerId(e)),
- _ => return Err(bad("layer.select", "target must be content, mask or an effect id of this layer")),
+ // An instance without a mask of its own edits the effects of the mask it draws with, as it edits that mask
+ Some(e) if selectable_effect(&s.doc.project, id, LayerId(e)) => StackTarget::Effect(LayerId(e)),
+ _ => return Err(bad("layer.select", "target must be content, mask or an effect id of this layer or of the mask it draws with")),
},
None => StackTarget::Content,
};
@@ -307,6 +308,12 @@ fn select(s: &mut Session, p: &Value) -> Result {
Ok(json!({ "layer": id.0, "textureSet": ts, "layers": [id.0] }))
}
+/// Whether effect `effect` can be selected on layer `id`: one of its own, or one in the mask it draws with.
+fn selectable_effect(project: &texturecraft_core::Project, id: LayerId, effect: LayerId) -> bool {
+ let Some((owner, _)) = project.effect(effect) else { return false };
+ owner == id || (owner == project.mask_owner(id) && project.layers.get(&owner).and_then(|l| l.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|e| e.id == effect)))
+}
+
fn rename(s: &mut Session, p: &Value) -> Result {
let id = layer_param(s, "layer.rename", p)?;
let name = strp(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad("layer.rename", "`name` is required"))?.to_string();
diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs
index 9136689f..d3262ea4 100644
--- a/crates/ui-egui/src/dock.rs
+++ b/crates/ui-egui/src/dock.rs
@@ -7,7 +7,7 @@ use serde_json::{Value, json};
use texturecraft_engine::compose::ThumbTarget;
use texturecraft_engine::core::{
BakedMap, BlendMode, Channel, ChannelBlend, ChannelKind, Decal, DecalFlip, Effect, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, LinkParam,
- MaterialLink, Projection, Source,
+ MaterialLink, Project, Projection, Source,
};
use texturecraft_engine::filter_lib::scalar_params;
use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST;
@@ -249,9 +249,10 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) {
select_all_layers(app, ui);
// A thumbnail or selection can close the editor before its TextEdit sees lost focus.
if let Some((id, _)) = &app.ui.rename
- && let Some((owner, _)) = app.session.doc.project.effect(LayerId(*id))
+ && app.session.doc.project.effect(LayerId(*id)).is_some()
&& app.layer_panel.expanded_effects.is_none_or(|(layer, in_mask)| {
- layer != owner || !app.session.doc.project.layers.get(&layer).is_some_and(|l| stack_effects(l, in_mask).iter().any(|e| e.id.0 == *id))
+ let project = &app.session.doc.project;
+ !project.layers.get(&layer).is_some_and(|l| stack_effects(project, l, in_mask).iter().any(|e| e.id.0 == *id))
})
{
finish_effect_rename(app);
@@ -497,8 +498,13 @@ fn level_x(left: f32, level: usize) -> f32 {
left + ROW_LEFT_PADDING + level as f32 * INDENT + EYE_SIZE * 0.5
}
-fn stack_effects(layer: &Layer, in_mask: bool) -> &[Effect] {
- if in_mask { layer.mask.as_ref().map_or(&[], |mask| &mask.effects) } else { &layer.content_effects }
+/// The effects `layer` lists in its mask (the mask it draws with, so an instance without its own shows its source's) or content.
+fn stack_effects(project: &Project, layer: &Layer, in_mask: bool) -> Vec {
+ if in_mask {
+ project.layers.get(&project.mask_owner(layer.id)).and_then(|owner| owner.mask.as_ref()).map_or_else(Vec::new, |mask| mask.effects.clone())
+ } else {
+ layer.content_effects.clone()
+ }
}
fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize, count: &mut usize) {
@@ -510,9 +516,9 @@ fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize,
if let Some((open_layer, in_mask)) = app.layer_panel.expanded_effects
&& open_layer == id
{
- let stack = stack_effects(&layer, in_mask);
+ let stack = stack_effects(&app.session.doc.project, &layer, in_mask);
for (index, effect) in stack.iter().rev().enumerate() {
- effect_row(app, ui, &layer, stack, effect, index, depth + 2, index + 1 == stack.len(), in_mask);
+ effect_row(app, ui, &layer, &stack, effect, index, depth + 2, index + 1 == stack.len(), in_mask);
}
}
@@ -715,7 +721,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
let mask_response = ui
.interact(mask_rect, ui.scope_id().with(("mask", layer.id.0)), Sense::click())
.on_hover_text(tr("Select the mask (Alt+click: show it in the viewport)"));
- let mask_stack = layer.mask.as_ref().filter(|mask| !mask.effects.is_empty()).map(|_| (layer.id, true));
+ let mask_stack = (!mask.effects.is_empty()).then_some((layer.id, true));
effect_stack_thumbnail(
app,
&painter,
diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs
index 4deeadc6..5955a4a5 100644
--- a/crates/ui-egui/tests/it/layers_panel.rs
+++ b/crates/ui-egui/tests/it/layers_panel.rs
@@ -49,6 +49,36 @@ fn click(h: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) {
h.run_steps(3);
}
+/// An instance without a mask of its own shows its source's mask thumbnail with the effect badge, so
+/// that thumbnail opens the source mask's effects and each of those rows can be selected from the instance.
+#[test]
+fn an_instance_mask_thumbnail_opens_the_inherited_mask_effects() {
+ let (mut h, source) = harness();
+ let instance = LayerId(id(execute(&mut h.state_mut().session, "layer.instance", &json!({"layer": source.0})).unwrap(), "layer"));
+ execute(&mut h.state_mut().session, "layer.rename", &json!({"layer": instance.0, "name": "Instance row"})).unwrap();
+ execute(&mut h.state_mut().session, "layer.select", &json!({"layer": instance.0})).unwrap();
+ h.run_steps(4);
+ assert!(h.state().session.doc.project.layers[&instance].mask.is_none(), "the instance draws with its source's mask");
+ assert!(h.query_by_label("Effect M").is_none(), "stacks start closed");
+
+ let mask = thumb(&h, "Instance row", true);
+ click(&mut h, mask);
+ assert_eq!(h.state().session.selected_layer(), Some(instance));
+ assert_eq!(h.state().session.target, StackTarget::Mask);
+ assert!(h.query_by_label("Effect M").is_some(), "the inherited mask effect is listed");
+ click(&mut h, mask);
+ assert!(h.query_by_label("Effect M").is_none(), "the same thumbnail closes the stack");
+ click(&mut h, mask);
+
+ // Selecting the inherited effect through the instance keeps the instance selected and the stack open
+ let row = h.get_by_label("Effect M").rect();
+ click(&mut h, row.center());
+ let StackTarget::Effect(effect) = h.state().session.target else { panic!("{:?}", h.state().session.target) };
+ assert_eq!(h.state().session.doc.project.effect(effect).map(|(owner, _)| owner), Some(source));
+ assert_eq!(h.state().session.selected_layer(), Some(instance));
+ assert!(h.query_by_label("Effect M").is_some(), "selecting an effect leaves its stack open");
+}
+
#[test]
fn mask_and_content_thumbnails_toggle_their_own_stacks() {
let (mut h, layer) = harness();
From 04e835fcf47b1145e95b689ff922ad6f6173310f Mon Sep 17 00:00:00 2001
From: vangel76
Date: Sun, 22 Nov 2026 23:32:05 +0100
Subject: [PATCH 015/138] Fail the save wait on an error toast and wait for the
saved path
---
crates/ui-egui/tests/it/rename_anchor.rs | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/crates/ui-egui/tests/it/rename_anchor.rs b/crates/ui-egui/tests/it/rename_anchor.rs
index 3f0b57c3..7ff9dfac 100644
--- a/crates/ui-egui/tests/it/rename_anchor.rs
+++ b/crates/ui-egui/tests/it/rename_anchor.rs
@@ -45,7 +45,11 @@ fn save_to(h: &mut Harness<'_, TextureCraftApp>, file: &Path) {
// The save runs on a worker: step frames until the app has collected it, as the app does
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
h.step();
- while h.state().session.modified || !texturecraft_ui_egui::menus::enabled(h.state(), "file.saveAs") {
+ let target = file.display().to_string();
+ while !(file.exists() && h.state().session.path.as_deref() == Some(target.as_str()) && texturecraft_ui_egui::menus::enabled(h.state(), "file.saveAs")) {
+ if let Some(toast) = h.state().toasts.iter().find(|toast| toast.error) {
+ panic!("the save failed: {}", toast.text);
+ }
assert!(std::time::Instant::now() < deadline, "the save did not finish");
h.step();
std::thread::yield_now();
From 7d2e1523a84ed1f3da82e52b0de2f5c379b27671 Mon Sep 17 00:00:00 2001
From: vangel76
Date: Sun, 22 Nov 2026 23:40:09 +0100
Subject: [PATCH 016/138] Test inherited mask effect selection from an instance
and document it
---
crates/engine/src/layer_cmds.rs | 4 ++-
crates/engine/tests/it/content_effects.rs | 34 +++++++++++++++++++++++
crates/ui-egui/tests/it/layers_panel.rs | 18 ++++++++++++
docs/control-protocol.md | 2 +-
4 files changed, 56 insertions(+), 2 deletions(-)
diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs
index b7b38f76..8823112f 100644
--- a/crates/engine/src/layer_cmds.rs
+++ b/crates/engine/src/layer_cmds.rs
@@ -311,7 +311,9 @@ fn select(s: &mut Session, p: &Value) -> Result {
/// Whether effect `effect` can be selected on layer `id`: one of its own, or one in the mask it draws with.
fn selectable_effect(project: &texturecraft_core::Project, id: LayerId, effect: LayerId) -> bool {
let Some((owner, _)) = project.effect(effect) else { return false };
- owner == id || (owner == project.mask_owner(id) && project.layers.get(&owner).and_then(|l| l.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|e| e.id == effect)))
+ owner == id
+ || (owner == project.mask_owner(id)
+ && project.layers.get(&owner).and_then(|l| l.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|e| e.id == effect)))
}
fn rename(s: &mut Session, p: &Value) -> Result {
diff --git a/crates/engine/tests/it/content_effects.rs b/crates/engine/tests/it/content_effects.rs
index 4b761fc8..47c6b8fe 100644
--- a/crates/engine/tests/it/content_effects.rs
+++ b/crates/engine/tests/it/content_effects.rs
@@ -179,6 +179,40 @@ fn anchor_effects_added_through_instance_validate_against_source() {
assert!(session.doc.project.layer(LayerId(source)).unwrap().mask.is_none());
}
+#[test]
+fn an_instance_selects_the_effects_of_the_mask_it_draws_with() {
+ let mut s = session();
+ let source = id(execute(&mut s, "layer.add.fill", &json!({"height": 0.5})).unwrap(), "layer");
+ execute(&mut s, "mask.add.black", &Value::Null).unwrap();
+ let source_mask = id(execute(&mut s, "effect.add.generator", &json!({"generator": "position", "level": 0.5})).unwrap(), "effect");
+ let source_content = id(execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect");
+ let other = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer");
+ execute(&mut s, "mask.add.black", &Value::Null).unwrap();
+ let other_mask = id(execute(&mut s, "effect.add.generator", &json!({"generator": "position", "level": 0.5})).unwrap(), "effect");
+ let instance = id(execute(&mut s, "layer.instance", &json!({"layer": source})).unwrap(), "layer");
+ let select = |s: &mut Session, effect: u64| execute(s, "layer.select", &json!({"layer": instance, "target": effect}));
+
+ // Without a mask of its own the instance draws with the source's, so it selects that mask's effects
+ select(&mut s, source_mask).unwrap();
+ assert_eq!(s.selected_layer(), Some(LayerId(instance)));
+ assert_eq!(s.target, StackTarget::Effect(LayerId(source_mask)));
+
+ // Content effects of the source and effects of unrelated layers stay out of reach
+ for effect in [source_content, other_mask] {
+ let error = select(&mut s, effect).unwrap_err().to_string();
+ assert!(error.contains("an effect id of this layer or of the mask it draws with"), "{error}");
+ }
+ assert_ne!(other, instance);
+
+ // An instance with its own mask draws with that one: the source's mask effects are not its own
+ execute(&mut s, "layer.select", &json!({"layer": instance})).unwrap();
+ execute(&mut s, "mask.add.black", &Value::Null).unwrap();
+ let own = id(execute(&mut s, "effect.add.generator", &json!({"generator": "position", "level": 0.5})).unwrap(), "effect");
+ assert!(select(&mut s, source_mask).is_err());
+ select(&mut s, own).unwrap();
+ assert_eq!(s.target, StackTarget::Effect(LayerId(own)));
+}
+
#[test]
fn painting_into_a_content_paint_effect() {
let mut s = session();
diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs
index 5955a4a5..d3bde0a3 100644
--- a/crates/ui-egui/tests/it/layers_panel.rs
+++ b/crates/ui-egui/tests/it/layers_panel.rs
@@ -79,6 +79,24 @@ fn an_instance_mask_thumbnail_opens_the_inherited_mask_effects() {
assert!(h.query_by_label("Effect M").is_some(), "selecting an effect leaves its stack open");
}
+/// An instance with a mask of its own lists that mask's effects, not its source's.
+#[test]
+fn an_instance_with_its_own_mask_opens_its_own_mask_effects() {
+ let (mut h, source) = harness();
+ let instance = LayerId(id(execute(&mut h.state_mut().session, "layer.instance", &json!({"layer": source.0})).unwrap(), "layer"));
+ execute(&mut h.state_mut().session, "layer.rename", &json!({"layer": instance.0, "name": "Instance row"})).unwrap();
+ execute(&mut h.state_mut().session, "layer.select", &json!({"layer": instance.0})).unwrap();
+ execute(&mut h.state_mut().session, "mask.add.black", &Value::Null).unwrap();
+ execute(&mut h.state_mut().session, "effect.add.generator", &json!({"generator": "position", "level": 0.5, "name": "Own effect"})).unwrap();
+ execute(&mut h.state_mut().session, "layer.select", &json!({"layer": instance.0})).unwrap();
+ h.run_steps(4);
+
+ let mask = thumb(&h, "Instance row", true);
+ click(&mut h, mask);
+ assert!(h.query_by_label("Own effect").is_some(), "the instance's own mask effect is listed");
+ assert!(h.query_by_label("Effect M").is_none(), "the source's mask effect is not");
+}
+
#[test]
fn mask_and_content_thumbnails_toggle_their_own_stacks() {
let (mut h, layer) = harness();
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index bd11cb2d..cb29d5ba 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -20,7 +20,7 @@ one just above itself. `effect.copy {effect?}` and `effect.cut {effect?}` put an
layer clipboard, and `effect.paste {layer?, target?}` adds it to another layer's content or mask.
`layer.select {layers: [id], layer?}` selects several layers of one texture set at once (`layer`
is the active one), and `{layer, range: true}` / `{layer, toggle: true}` do what Shift+click and
-Ctrl+click do in the Layers panel. `layer.select {all: true}` (Ctrl+A with the pointer over the
+Ctrl+click do in the Layers panel. `layer.select {layer, target}` takes `content`, `mask` or an effect id: one of the layer, or of the mask it draws with. `layer.select {all: true}` (Ctrl+A with the pointer over the
Layers panel) selects every shown row of the active texture set: the folder rows and the layers
of open folders, not the layers of collapsed ones. `{layer, toggle: true}` on the only selected
layer leaves nothing selected. `layer.visible {layers, layer}` gives every listed layer the
From 3fc5d23b9f428321d65fb69ffb9df0487cfe5c95 Mon Sep 17 00:00:00 2001
From: vangel76
Date: Sun, 22 Nov 2026 23:42:58 +0100
Subject: [PATCH 017/138] Expect an instance to select its source mask effect
in the decal frame test
---
crates/ui-egui/src/viewport.rs | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index 97edafed..6e81eed8 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -2920,8 +2920,9 @@ mod tests {
let session = &mut harness.state_mut().session;
let instance = execute(session, "layer.instance", &json!({"layer": original.layer.0, "ts": 1})).unwrap()["layer"].clone();
- // The source effect remains a valid inherited target when selection changes to its instance
- assert!(execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).is_err());
+ // The source effect is a valid inherited target when selection changes to its instance
+ execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).unwrap();
+ assert_eq!(session.target, texturecraft_engine::StackTarget::Effect(effect));
assert_eq!(session.ts(), 1);
assert_eq!(session.selected_layer().unwrap().0, instance.as_u64().unwrap());
From 7f6375bf98716f0c93d1d422dcf7edc41c9962ca Mon Sep 17 00:00:00 2001
From: supersfera
Date: Tue, 24 Nov 2026 07:10:16 -0800
Subject: [PATCH 018/138] ru: state CC0-1.0 for Russian metainfo strings
---
packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in | 1 +
1 file changed, 1 insertion(+)
diff --git a/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in b/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in
index 9b14d960..65088b0f 100644
--- a/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in
+++ b/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in
@@ -1,4 +1,5 @@
+
From 3a444c1136d8a3ca2ad6fd07d33fb5a56039302c Mon Sep 17 00:00:00 2001
From: vangel76
Date: Tue, 24 Nov 2026 23:08:01 +0100
Subject: [PATCH 019/138] Quit after a running save when Close arrives during
it
---
crates/ui-egui/src/manual_save.rs | 142 +++++++++++++++++++++++++++++-
crates/ui-egui/src/windows.rs | 13 +--
2 files changed, 148 insertions(+), 7 deletions(-)
diff --git a/crates/ui-egui/src/manual_save.rs b/crates/ui-egui/src/manual_save.rs
index c2481678..1aa3f479 100644
--- a/crates/ui-egui/src/manual_save.rs
+++ b/crates/ui-egui/src/manual_save.rs
@@ -8,6 +8,7 @@ use texturecraft_engine::{Result, file_cmds::SaveOutput, formats::project_file::
use crate::{
TextureCraftApp,
i18n::{tr, trf},
+ state::Unsaved,
};
pub(crate) struct SaveJob {
@@ -63,15 +64,19 @@ impl TextureCraftApp {
self.saving_for_prompt = false;
}
+ let mut quitting = false;
match result {
Ok(output) => {
output.apply(&mut self.session);
if job.remember {
crate::windows::remember(self, &output.path);
}
- self.prompt_saved = continue_prompt && same_project && !self.session.modified && !self.session.stroke_active();
+ let clean = same_project && !self.session.modified && !self.session.stroke_active();
+ quitting = job.quit_after_save && clean;
+ self.prompt_saved = continue_prompt && clean && !quitting;
self.toast(trf("Saved {path}", &[("path", &output.path)]), false);
- if job.quit_after_save && same_project {
+ if quitting {
+ self.ui.windows.unsaved = None;
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
}
@@ -81,8 +86,141 @@ impl TextureCraftApp {
self.toast(message, true);
}
}
+
+ // A close that the save could not finish asks about the changes it left
+ if job.quit_after_save && !quitting {
+ crate::windows::ask_to_save(self, Unsaved::Quit);
+ }
if let Some(toast) = self.toasts.last_mut() {
toast.announce = true;
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use egui::{ViewportCommand, ViewportEvent, ViewportId};
+ use egui_kittest::Harness;
+ use egui_kittest::kittest::{NodeT as _, Queryable as _};
+ use texturecraft_engine::file_cmds::SaveTask;
+
+ use super::*;
+
+ fn harness() -> Harness<'static, TextureCraftApp> {
+ let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
+ session.modified = true;
+ let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
+
+ // Match English labels independently of the system locale
+ h.state_mut().ui.prefs.language = "en".into();
+ h.run_steps(2);
+ h
+ }
+
+ fn temp_file(test: &str) -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!("tc-manual-save-{test}-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ dir.join("project.tcraft")
+ }
+
+ /// A save the test finishes by hand, so the close lands while it is still running
+ fn start_held_save(h: &mut Harness<'_, TextureCraftApp>, path: &std::path::Path, adopt: bool) -> (SaveTask, mpsc::Sender>) {
+ let app = h.state_mut();
+ let task = app.session.save_task(&path.display().to_string(), adopt);
+ let (sender, output) = mpsc::channel();
+ app.save_job =
+ Some(SaveJob { progress: Arc::default(), output, project_id: app.session.project_id, for_prompt: false, remember: false, quit_after_save: false });
+ (task, sender)
+ }
+
+ fn request_close(h: &mut Harness<'_, TextureCraftApp>) {
+ h.input_mut().viewports.entry(ViewportId::ROOT).or_default().events.push(ViewportEvent::Close);
+ h.step();
+ h.input_mut().viewports.entry(ViewportId::ROOT).or_default().events.clear();
+ h.run_steps(2);
+ }
+
+ /// Hands the worker's result over and reports whether the app asked to close in the next frames
+ fn finish(h: &mut Harness<'_, TextureCraftApp>, task: SaveTask, sender: &mpsc::Sender>) -> bool {
+ sender.send(task.run(None)).unwrap();
+ (0..3).any(|_| {
+ h.step();
+ h.output().viewport_output.get(&ViewportId::ROOT).is_some_and(|v| v.commands.contains(&ViewportCommand::Close))
+ })
+ }
+
+ fn prompt_is_usable(h: &Harness<'_, TextureCraftApp>) -> bool {
+ ["Save", "Don't save", "Cancel"].iter().all(|label| !h.get_by_label(label).accesskit_node().is_disabled())
+ }
+
+ #[test]
+ fn closing_during_a_regular_save_quits_once_it_has_saved() {
+ let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+ let file = temp_file("close-then-saved");
+ let mut h = harness();
+ h.state_mut().session.path = Some(file.display().to_string());
+ let (task, sender) = start_held_save(&mut h, &file, true);
+
+ request_close(&mut h);
+ assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the changes are not written yet");
+ assert!(h.get_by_label("Save").accesskit_node().is_disabled(), "the prompt waits for the running save");
+ let closed = finish(&mut h, task, &sender);
+
+ assert!(closed, "the close goes on after the save");
+ assert!(file.exists());
+ assert!(!h.state().session.modified);
+ assert!(h.state().ui.windows.unsaved.is_none(), "no question is left once the changes are saved");
+ }
+
+ #[test]
+ fn closing_during_a_failed_save_keeps_a_usable_prompt() {
+ let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+ let file = temp_file("close-then-failed").with_file_name("missing").join("project.tcraft");
+ let mut h = harness();
+ let (task, sender) = start_held_save(&mut h, &file, true);
+
+ request_close(&mut h);
+ let closed = finish(&mut h, task, &sender);
+
+ assert!(!closed);
+ assert!(h.state().session.modified);
+ assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit));
+ assert!(prompt_is_usable(&h), "the prompt answers again after the failed write");
+ }
+
+ #[test]
+ fn closing_during_a_save_a_copy_keeps_the_prompt() {
+ let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+ let file = temp_file("close-then-copied");
+ let mut h = harness();
+ let (task, sender) = start_held_save(&mut h, &file, false);
+
+ request_close(&mut h);
+ let closed = finish(&mut h, task, &sender);
+
+ assert!(!closed, "a copy leaves the project's own changes unsaved");
+ assert!(file.exists());
+ assert!(h.state().session.modified);
+ assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit));
+ assert!(prompt_is_usable(&h));
+ }
+
+ #[test]
+ fn closing_during_a_save_keeps_the_prompt_for_later_edits() {
+ let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+ let file = temp_file("close-then-edited");
+ let mut h = harness();
+ h.state_mut().session.path = Some(file.display().to_string());
+ let (task, sender) = start_held_save(&mut h, &file, true);
+ let rename = h.state_mut().run("textureSet.rename", serde_json::json!({"ts": 0, "name": "Edited while saving"}));
+ assert!(rename.is_some());
+
+ request_close(&mut h);
+ let closed = finish(&mut h, task, &sender);
+
+ assert!(!closed, "the edit made after the snapshot is not in the file");
+ assert!(h.state().session.modified);
+ assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit));
+ assert!(prompt_is_usable(&h));
+ }
+}
diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs
index 96d7ca0a..8f83610c 100644
--- a/crates/ui-egui/src/windows.rs
+++ b/crates/ui-egui/src/windows.rs
@@ -95,12 +95,10 @@ pub(crate) fn close_request(app: &mut TextureCraftApp, ctx: &egui::Context) {
app.toast(error.to_string(), true);
}
#[cfg(not(target_arch = "wasm32"))]
- let waiting_for_save = if closing
- && !app.session.modified
- && let Some(job) = &mut app.save_job
- {
+ let waiting_for_save = if closing && let Some(job) = &mut app.save_job {
+ // The running save carries the quit; unsaved changes still open the prompt meanwhile
job.quit_after_save = true;
- true
+ !app.session.modified
} else {
false
};
@@ -164,6 +162,11 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) {
#[cfg(not(target_arch = "wasm32"))]
{
app.saving_for_prompt = false;
+ if pending == Unsaved::Quit
+ && let Some(job) = &mut app.save_job
+ {
+ job.quit_after_save = false;
+ }
}
}
From 5b4b082c83a97e28f3f926600055d87e5c545742 Mon Sep 17 00:00:00 2001
From: vangel76
Date: Tue, 24 Nov 2026 23:26:07 +0100
Subject: [PATCH 020/138] Ask about edits made after a clean close while the
save runs
---
crates/ui-egui/src/manual_save.rs | 21 +++++++++++++++++++++
1 file changed, 21 insertions(+)
diff --git a/crates/ui-egui/src/manual_save.rs b/crates/ui-egui/src/manual_save.rs
index 1aa3f479..2ccb9ae7 100644
--- a/crates/ui-egui/src/manual_save.rs
+++ b/crates/ui-egui/src/manual_save.rs
@@ -223,4 +223,25 @@ mod tests {
assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit));
assert!(prompt_is_usable(&h));
}
+
+ #[test]
+ fn an_edit_after_a_clean_close_asks_once_the_save_returns() {
+ let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+ let file = temp_file("clean-close-then-edited");
+ let mut h = harness();
+ h.state_mut().session.modified = false;
+ h.state_mut().session.path = Some(file.display().to_string());
+ let (task, sender) = start_held_save(&mut h, &file, true);
+
+ request_close(&mut h);
+ assert!(h.state().ui.windows.unsaved.is_none(), "nothing to ask while the project is clean");
+ let rename = h.state_mut().run("textureSet.rename", serde_json::json!({"ts": 0, "name": "Edited while saving"}));
+ assert!(rename.is_some());
+ let closed = finish(&mut h, task, &sender);
+
+ assert!(!closed);
+ assert!(h.state().session.modified);
+ assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the close asks about the edit instead of being dropped");
+ assert!(prompt_is_usable(&h));
+ }
}
From 65af076fd6129eae114207da176aad1056badc60 Mon Sep 17 00:00:00 2001
From: vangel76
Date: Wed, 25 Nov 2026 00:43:08 +0100
Subject: [PATCH 021/138] Keep a close during a save pending until an open
stroke ends
---
crates/ui-egui/src/lib.rs | 5 +++
crates/ui-egui/src/manual_save.rs | 74 ++++++++++++++++++++++++++++++-
crates/ui-egui/src/windows.rs | 8 ++++
3 files changed, 85 insertions(+), 2 deletions(-)
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 84c103f6..2f981d6b 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -332,6 +332,9 @@ pub struct TextureCraftApp {
/// The unsaved-changes dialog's Save is waiting for a path or a save result.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) saving_for_prompt: bool,
+ /// A close the finished save left waiting for an open stroke; decided once the stroke ends.
+ #[cfg(not(target_arch = "wasm32"))]
+ pub(crate) quit_after_stroke: bool,
/// The requested save completed; the prompt goes on at its next frame.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) prompt_saved: bool,
@@ -453,6 +456,8 @@ impl TextureCraftApp {
#[cfg(not(target_arch = "wasm32"))]
saving_for_prompt: false,
#[cfg(not(target_arch = "wasm32"))]
+ quit_after_stroke: false,
+ #[cfg(not(target_arch = "wasm32"))]
prompt_saved: false,
bindings: keymap::Bindings::default(),
settings_bindings: keymap::Bindings::default(),
diff --git a/crates/ui-egui/src/manual_save.rs b/crates/ui-egui/src/manual_save.rs
index 2ccb9ae7..b7eed0fe 100644
--- a/crates/ui-egui/src/manual_save.rs
+++ b/crates/ui-egui/src/manual_save.rs
@@ -87,9 +87,13 @@ impl TextureCraftApp {
}
}
- // A close that the save could not finish asks about the changes it left
+ // A close that the save could not finish asks about the changes it left, once an open stroke ends
if job.quit_after_save && !quitting {
- crate::windows::ask_to_save(self, Unsaved::Quit);
+ if self.session.stroke_active() {
+ self.quit_after_stroke = true;
+ } else {
+ crate::windows::ask_to_save(self, Unsaved::Quit);
+ }
}
if let Some(toast) = self.toasts.last_mut() {
toast.announce = true;
@@ -143,6 +147,11 @@ mod tests {
/// Hands the worker's result over and reports whether the app asked to close in the next frames
fn finish(h: &mut Harness<'_, TextureCraftApp>, task: SaveTask, sender: &mpsc::Sender>) -> bool {
sender.send(task.run(None)).unwrap();
+ sends_close(h)
+ }
+
+ /// Whether the app asks to close in the next frames
+ fn sends_close(h: &mut Harness<'_, TextureCraftApp>) -> bool {
(0..3).any(|_| {
h.step();
h.output().viewport_output.get(&ViewportId::ROOT).is_some_and(|v| v.commands.contains(&ViewportCommand::Close))
@@ -244,4 +253,65 @@ mod tests {
assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the close asks about the edit instead of being dropped");
assert!(prompt_is_usable(&h));
}
+
+ /// A clean project closed during its save, with paint still held down when the save returns
+ fn stroke_open_when_the_save_returns(test: &str) -> Harness<'static, TextureCraftApp> {
+ let file = temp_file(test);
+ let mut h = harness();
+ h.state_mut().session.modified = false;
+ h.state_mut().session.path = Some(file.display().to_string());
+ let (task, sender) = start_held_save(&mut h, &file, true);
+ request_close(&mut h);
+ h.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap();
+
+ let closed = finish(&mut h, task, &sender);
+
+ assert!(!closed, "the open stroke may still change the project");
+ assert!(h.state().session.stroke_active());
+ assert!(h.state().ui.windows.unsaved.is_none());
+ h
+ }
+
+ #[test]
+ fn a_stroke_open_when_the_save_returns_asks_once_it_is_painted() {
+ let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+ let mut h = stroke_open_when_the_save_returns("stroke-painted");
+
+ h.state_mut().session.end_stroke().unwrap();
+ let closed = sends_close(&mut h);
+
+ assert!(!closed);
+ assert!(h.state().session.modified);
+ assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the close asks about the painted stroke");
+ }
+
+ #[test]
+ fn a_stroke_open_when_the_save_returns_quits_once_it_is_canceled() {
+ let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+ let mut h = stroke_open_when_the_save_returns("stroke-canceled");
+
+ h.state_mut().session.cancel_stroke();
+ let closed = sends_close(&mut h);
+
+ assert!(closed, "nothing is left to save, so the close goes on");
+ assert!(h.state().ui.windows.unsaved.is_none());
+ }
+
+ #[test]
+ fn dismissing_the_prompt_during_a_save_cancels_the_quit() {
+ let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+ let file = temp_file("close-then-dismissed");
+ let mut h = harness();
+ h.state_mut().session.path = Some(file.display().to_string());
+ let (task, sender) = start_held_save(&mut h, &file, true);
+ request_close(&mut h);
+ h.get_by_label("Close window").click();
+ h.run_steps(2);
+ assert!(h.state().ui.windows.unsaved.is_none(), "the prompt is dismissed while the save runs");
+
+ let closed = finish(&mut h, task, &sender);
+
+ assert!(!closed, "a dismissed prompt keeps the app open");
+ assert!(!h.state().session.modified);
+ }
}
diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs
index 8f83610c..1c4681e7 100644
--- a/crates/ui-egui/src/windows.rs
+++ b/crates/ui-egui/src/windows.rs
@@ -94,6 +94,14 @@ pub(crate) fn close_request(app: &mut TextureCraftApp, ctx: &egui::Context) {
{
app.toast(error.to_string(), true);
}
+ #[cfg(not(target_arch = "wasm32"))]
+ if app.quit_after_stroke && !app.session.stroke_active() {
+ app.quit_after_stroke = false;
+ if !ask_to_save(app, crate::state::Unsaved::Quit) {
+ ctx.send_viewport_cmd(egui::ViewportCommand::Close);
+ }
+ }
+
#[cfg(not(target_arch = "wasm32"))]
let waiting_for_save = if closing && let Some(job) = &mut app.save_job {
// The running save carries the quit; unsaved changes still open the prompt meanwhile
From 6120bdd79de129bfb712262feba6353cf64b3369 Mon Sep 17 00:00:00 2001
From: vangel76
Date: Wed, 25 Nov 2026 00:48:58 +0100
Subject: [PATCH 022/138] Resources Updater: find changed resource files on
disk and update or relink them
Image resources imported from a file remember its path and modification
time. resource.status lists each resource as outdated, missing, up to date
or without a file; resource.update reads changed files again and
resource.relink points a resource at another file, each as one undo step
that recomposites every layer using the resource. Undo and redo drop
pixels decoded from bytes they replace under the same name.
The shelf's Resources Updater button opens a window with the project's
resources (outdated first), status and name filters, Update, Select new
resource, Show in folder, Refresh and Update All. When the app gets the
focus back after files changed, a notice offers to update them.
Automation refuses the three commands, since they read host paths the
project names.
---
crates/automation/src/workspace.rs | 6 +
crates/core/src/lib.rs | 2 +
crates/core/src/project.rs | 5 +
crates/core/src/resource_source.rs | 17 +
crates/engine/src/commands.rs | 4 +-
crates/engine/src/lib.rs | 8 +
crates/engine/src/link_cmds.rs | 1 +
crates/engine/src/reloaded_file.rs | 28 ++
crates/engine/src/resource_cmds.rs | 24 +-
crates/engine/src/resource_state.rs | 15 +
crates/engine/src/resource_status.rs | 39 ++
crates/engine/src/resource_update_cmds.rs | 241 +++++++++++
crates/engine/src/session.rs | 2 +
crates/engine/tests/it/main.rs | 1 +
crates/engine/tests/it/resource_updater.rs | 227 +++++++++++
crates/ui-egui/src/lib.rs | 29 +-
crates/ui-egui/src/menus.rs | 3 +
crates/ui-egui/src/resources_updater.rs | 383 ++++++++++++++++++
.../src/resources_updater/row_request.rs | 9 +
crates/ui-egui/src/state.rs | 5 +
crates/ui-egui/src/state/resources_updater.rs | 19 +
crates/ui-egui/src/toast_action.rs | 34 ++
crates/ui-egui/src/toolbar.rs | 28 +-
crates/ui-egui/src/windows.rs | 1 +
crates/ui-egui/tests/it/main.rs | 1 +
crates/ui-egui/tests/it/resources_updater.rs | 137 +++++++
docs/control-protocol.md | 22 +-
docs/features.md | 7 +
28 files changed, 1287 insertions(+), 11 deletions(-)
create mode 100644 crates/core/src/resource_source.rs
create mode 100644 crates/engine/src/reloaded_file.rs
create mode 100644 crates/engine/src/resource_state.rs
create mode 100644 crates/engine/src/resource_status.rs
create mode 100644 crates/engine/src/resource_update_cmds.rs
create mode 100644 crates/engine/tests/it/resource_updater.rs
create mode 100644 crates/ui-egui/src/resources_updater.rs
create mode 100644 crates/ui-egui/src/resources_updater/row_request.rs
create mode 100644 crates/ui-egui/src/state/resources_updater.rs
create mode 100644 crates/ui-egui/src/toast_action.rs
create mode 100644 crates/ui-egui/tests/it/resources_updater.rs
diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs
index a1f18ab9..2e590e15 100644
--- a/crates/automation/src/workspace.rs
+++ b/crates/automation/src/workspace.rs
@@ -138,6 +138,9 @@ pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError
let allowed = match id {
"file.close" | "file.removeUnused" => true,
"file.reimportMesh" => !has_path,
+
+ // The Resources Updater reads the files a project names, which may lie outside the read root
+ "resource.status" | "resource.update" | "resource.relink" => false,
_ => !id.starts_with("file.") && !has_path,
};
if allowed {
@@ -245,6 +248,9 @@ mod tests {
assert!(authorize_command("file.reimportMesh", &json!({"path": "/etc/x.obj"})).is_err());
assert!(authorize_command("file.reimportMesh", &json!({})).is_ok());
assert!(authorize_command("file.close", &json!({})).is_ok());
+ for id in ["resource.status", "resource.update", "resource.relink"] {
+ assert!(authorize_command(id, &json!({})).is_err(), "{id} reads the host paths a project names");
+ }
assert!(authorize_command("layer.add.fill", &json!({"color": "#ff0000", "path": null})).is_ok());
}
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index 88ee96d1..2c5db23b 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -51,6 +51,7 @@ pub mod project;
pub mod projector;
pub mod ramp_curve;
pub mod randomized_seed;
+pub mod resource_source;
mod saved_decal;
mod saved_projection;
pub mod selection_background;
@@ -133,6 +134,7 @@ pub use project::{
pub use projector::Projector;
pub use ramp_curve::RampCurve;
pub use randomized_seed::RandomizedSeed;
+pub use resource_source::ResourceSource;
pub use selection_background::SelectionBackground;
pub use shape_crop::ShapeCrop;
pub use slope_blending::SlopeBlending;
diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs
index 649f4f6d..a4e004ec 100644
--- a/crates/core/src/project.rs
+++ b/crates/core/src/project.rs
@@ -445,6 +445,10 @@ pub struct Project {
/// The project's colour swatches (linear RGB), in the order they were added; projects without any save none
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub swatches: Vec<[f32; 3]>,
+ /// The files image resources were imported from, by resource name (the Resources Updater
+ /// reads them again). Resources made in the app or imported without a file path have none.
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub resource_sources: BTreeMap,
}
impl Project {
@@ -462,6 +466,7 @@ impl Project {
display: DisplaySettings::default(),
cameras: Vec::new(),
swatches: Vec::new(),
+ resource_sources: BTreeMap::new(),
}
}
diff --git a/crates/core/src/resource_source.rs b/crates/core/src/resource_source.rs
new file mode 100644
index 00000000..793122cf
--- /dev/null
+++ b/crates/core/src/resource_source.rs
@@ -0,0 +1,17 @@
+//! Where an image resource was imported from, so the Resources Updater can read it again
+
+use serde::{Deserialize, Serialize};
+
+/// The file an image resource was read from and its modification time then.
+///
+/// The resource's stored bytes are the file's bytes at that time, so a file whose size or
+/// contents differ from them has changed on disk.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ResourceSource {
+ /// Path of the file on the machine that imported it.
+ pub path: String,
+ /// The file's modification time when it was read, in milliseconds since the Unix epoch
+ /// (0 when unknown). An unchanged time and size skip reading the file again.
+ #[serde(default)]
+ pub modified_ms: u64,
+}
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index e34e9327..bb177191 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -31,7 +31,7 @@ impl CommandSpec {
/// that only return data or do nothing without parameters, and the ones that replace the
/// open project (the menu asks to save first).
pub fn bindable(&self) -> bool {
- const NOT_FROM_A_KEY: [&str; 13] = [
+ const NOT_FROM_A_KEY: [&str; 14] = [
"project.inspect",
"project.templates",
"project.new",
@@ -45,6 +45,7 @@ impl CommandSpec {
"bake.preview",
"camera.set",
"textureSet.settings",
+ "resource.status",
];
const NOTHING_WITHOUT_PARAMS: [&str; 4] = ["layer.blend", "tool.stencil", "tool.fillSelection", "tool.path"];
!(self.id.ends_with(".list") || NOT_FROM_A_KEY.contains(&self.id) || NOTHING_WITHOUT_PARAMS.contains(&self.id)) && params_all_optional(self.params)
@@ -143,6 +144,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::file_cmds::specs());
v.extend(crate::preset_cmds::specs());
v.extend(crate::resource_cmds::specs());
+ v.extend(crate::resource_update_cmds::specs());
v.extend(crate::material_lib::specs());
v.extend(crate::link_cmds::specs());
v.extend(crate::smart_masks::specs());
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 23c6b489..0d2f8d3c 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -68,7 +68,13 @@ pub mod preview;
mod procedural_params;
pub mod project_cmds;
pub mod quick_mask;
+// Reloading resource files reads paths on native targets only
+#[cfg(not(target_arch = "wasm32"))]
+mod reloaded_file;
pub mod resource_cmds;
+pub mod resource_state;
+pub mod resource_status;
+pub mod resource_update_cmds;
pub mod session;
mod session_log;
pub mod set_cmds;
@@ -97,6 +103,8 @@ pub use fill_hit_test::FillHitTest;
pub use fill_mode::FillMode;
pub use log::{LogEntry, LogLevel, SessionLog};
pub use path_tool::PathState;
+pub use resource_state::ResourceState;
+pub use resource_status::ResourceStatus;
pub use project_cmds::sample_session;
pub use session::{
CloneFrom, CloneSource, Document, HISTORY_TEMPLATES, NORMAL_HEIGHT_MESH_LABEL, Session, SetCache, StackTarget, StencilLook, StencilState, Tool, ToolState,
diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs
index a20182f6..1312aedd 100644
--- a/crates/engine/src/link_cmds.rs
+++ b/crates/engine/src/link_cmds.rs
@@ -623,6 +623,7 @@ impl Session {
for name in old_names.iter().filter(|name| !used_names.contains(name)) {
session.doc.resources.remove(name);
+ session.doc.project.resource_sources.remove(name);
}
Ok(names)
diff --git a/crates/engine/src/reloaded_file.rs b/crates/engine/src/reloaded_file.rs
new file mode 100644
index 00000000..b65582d2
--- /dev/null
+++ b/crates/engine/src/reloaded_file.rs
@@ -0,0 +1,28 @@
+//! An image file read again for a resource, checked before the project changes
+
+use texturecraft_core::ResourceSource;
+use texturecraft_formats::DecodedImage;
+
+use crate::Result;
+
+/// A resource's new bytes, their decoded pixels and the file they came from
+pub(crate) struct ReloadedFile {
+ pub name: String,
+ pub bytes: Vec,
+ pub image: DecodedImage,
+ pub source: ResourceSource,
+}
+
+impl ReloadedFile {
+ /// Read and decode `path` for resource `name` within the resource limits (`cmd` names errors)
+ pub(crate) fn read(cmd: &str, name: String, path: &str) -> Result {
+ let file_path = std::path::Path::new(path);
+
+ // Taken before reading, so a write during the read still shows as a change later
+ let modified_ms = crate::resource_update_cmds::modified_ms_of(file_path);
+ let bytes = crate::resource_cmds::read_resource_file(cmd, file_path, crate::resource_cmds::MAX_BYTES as u64)?;
+ let image = texturecraft_formats::decode_image(&bytes).map_err(|error| crate::commands::bad(cmd, format!("{path}: {error}")))?;
+
+ Ok(ReloadedFile { name, bytes, image, source: ResourceSource { path: crate::resource_update_cmds::absolute_path(path), modified_ms } })
+ }
+}
diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs
index 39d9fb6c..d20cb60e 100644
--- a/crates/engine/src/resource_cmds.rs
+++ b/crates/engine/src/resource_cmds.rs
@@ -146,6 +146,16 @@ impl Session {
self.drop_missing_image_view();
}
+ /// Undo and redo restore resource bytes under the same name (the Resources Updater replaces
+ /// them in place): the pixels decoded from the bytes `other` held are stale
+ pub(crate) fn forget_replaced_images(&mut self, other: &crate::Document) {
+ for (name, bytes) in &self.doc.resources {
+ if other.resources.get(name).is_some_and(|previous| !Arc::ptr_eq(previous, bytes)) {
+ self.images.remove(name);
+ }
+ }
+ }
+
/// The "Other..." view cannot show an image that is gone (removed or renamed): the material comes back
pub(crate) fn drop_missing_image_view(&mut self) {
if self.view == crate::ViewMode::Image && !self.view_image.as_ref().is_some_and(|name| self.images.contains_key(name)) {
@@ -172,8 +182,18 @@ fn list(s: &Session) -> Value {
#[cfg(not(target_arch = "wasm32"))]
fn import(s: &mut Session, p: &Value) -> Result {
let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?;
+ let prefix = strp(p, "prefix").unwrap_or("");
+
+ // Taken before reading, so a write during the read still shows as a change in the Resources Updater
+ let modified_ms = crate::resource_update_cmds::modified_ms_of(std::path::Path::new(path));
let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?;
- let name = s.import_resource_bytes_prefixed(strp(p, "prefix").unwrap_or(""), path, bytes)?;
+ let source = texturecraft_core::ResourceSource { path: crate::resource_update_cmds::absolute_path(path), modified_ms };
+
+ let name = s.edit("Import resource", |session| {
+ let name = session.add_image_resource_prefixed(prefix, path, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)?;
+ session.doc.project.resource_sources.insert(name.clone(), source);
+ Ok(name)
+ })?;
Ok(json!({ "name": name }))
}
@@ -255,6 +275,7 @@ fn remove(s: &mut Session, p: &Value) -> Result {
s.edit("Remove resource", |s| {
s.doc.resources.remove(&name);
+ s.doc.project.resource_sources.remove(&name);
Ok(())
})?;
s.sync_images();
@@ -277,6 +298,7 @@ fn remove_unused(s: &mut Session, _: &Value) -> Result {
if !unused.is_empty() {
s.edit("Remove unused resources", |s| {
s.doc.resources.retain(|k, _| !unused.contains(k));
+ s.doc.project.resource_sources.retain(|k, _| !unused.contains(k));
Ok(())
})?;
s.sync_images();
diff --git a/crates/engine/src/resource_state.rs b/crates/engine/src/resource_state.rs
new file mode 100644
index 00000000..1a3e427c
--- /dev/null
+++ b/crates/engine/src/resource_state.rs
@@ -0,0 +1,15 @@
+//! One row of the Resources Updater: an image resource, its file and how they compare
+
+use crate::resource_status::ResourceStatus;
+
+/// An image resource, the file it came from and whether that file changed on disk
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ResourceState {
+ /// The resource's name in the project.
+ pub name: String,
+ pub status: ResourceStatus,
+ /// The file it was imported from or relinked to (None: made in the app or imported without a path).
+ pub path: Option,
+ /// Why the file could not be checked (with [`ResourceStatus::Missing`]).
+ pub error: Option,
+}
diff --git a/crates/engine/src/resource_status.rs b/crates/engine/src/resource_status.rs
new file mode 100644
index 00000000..8e8efc70
--- /dev/null
+++ b/crates/engine/src/resource_status.rs
@@ -0,0 +1,39 @@
+//! Whether an image resource still matches the file it was imported from
+
+/// How an image resource compares with its file on disk. The order is the Resources Updater's
+/// list order: what needs attention first.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub enum ResourceStatus {
+ /// The file changed since it was read: Update reads it again.
+ Outdated,
+ /// The file is gone, or cannot be read.
+ Missing,
+ /// The file still holds the resource's bytes.
+ UpToDate,
+ /// Made in the app or imported without a file path: there is nothing to compare with.
+ NoSource,
+}
+
+impl ResourceStatus {
+ pub const ALL: [ResourceStatus; 4] = [ResourceStatus::Outdated, ResourceStatus::Missing, ResourceStatus::UpToDate, ResourceStatus::NoSource];
+
+ /// The id used by the control protocol
+ pub fn id(self) -> &'static str {
+ match self {
+ ResourceStatus::Outdated => "outdated",
+ ResourceStatus::Missing => "missing",
+ ResourceStatus::UpToDate => "upToDate",
+ ResourceStatus::NoSource => "noSource",
+ }
+ }
+
+ /// The name shown in the Resources Updater (English; the shell translates it)
+ pub fn label(self) -> &'static str {
+ match self {
+ ResourceStatus::Outdated => "Outdated",
+ ResourceStatus::Missing => "Missing",
+ ResourceStatus::UpToDate => "Up to date",
+ ResourceStatus::NoSource => "No source file",
+ }
+ }
+}
diff --git a/crates/engine/src/resource_update_cmds.rs b/crates/engine/src/resource_update_cmds.rs
new file mode 100644
index 00000000..ea69042d
--- /dev/null
+++ b/crates/engine/src/resource_update_cmds.rs
@@ -0,0 +1,241 @@
+//! The Resources Updater: compare image resources with the files they came from, read changed
+//! files again and point a resource at another file. Each change is one undo step, and every
+//! layer, mask and view using a changed resource recomposites.
+
+use serde_json::{Value, json};
+use texturecraft_core::ResourceSource;
+
+use crate::commands::{CommandSpec, always, bad};
+use crate::resource_state::ResourceState;
+use crate::resource_status::ResourceStatus;
+use crate::{Result, Session, cmd};
+
+pub fn specs() -> Vec {
+ vec![
+ cmd!(
+ "resource.status",
+ "Check resources on disk",
+ [],
+ None,
+ "{} → {resources: [{name, status: outdated|missing|upToDate|noSource, path?, error?}] (outdated first), total, outdated}",
+ always,
+ |s, _| Ok(status(s))
+ ),
+ cmd!(
+ "resource.update",
+ "Update resources",
+ [],
+ None,
+ "{names?: [resource name] (default: every outdated resource)} → {updated, failed: [{name, error}]} — reads their files again, one undo step",
+ always,
+ update
+ ),
+ cmd!(
+ "resource.relink",
+ "Relink resource",
+ [],
+ None,
+ "{name, path — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr)} → {name, path} — the resource takes the file's pixels and follows it from now on",
+ always,
+ relink
+ ),
+ ]
+}
+
+impl Session {
+ /// The image resources with their files and how they compare, outdated first, then by name.
+ /// Reads a file only when its size matches the stored bytes but its modification time does not.
+ pub fn resource_states(&self) -> Vec {
+ let sources = &self.doc.project.resource_sources;
+ let mut states: Vec = self
+ .doc
+ .resources
+ .iter()
+ .filter(|(name, _)| self.images.contains_key(*name) || sources.contains_key(*name))
+ .map(|(name, bytes)| {
+ let source = sources.get(name);
+ let (status, error) = source.map_or((ResourceStatus::NoSource, None), |source| compare_with_file(source, bytes));
+ ResourceState { name: name.clone(), status, path: source.map(|source| source.path.clone()), error }
+ })
+ .collect();
+
+ states.sort_by(|a, b| a.status.cmp(&b.status).then_with(|| a.name.cmp(&b.name)));
+ states
+ }
+
+ /// Put reloaded files in place of their resources' bytes and pixels as one undo step
+ #[cfg(not(target_arch = "wasm32"))]
+ fn install_reloaded(&mut self, label: &str, files: Vec) -> Result> {
+ if files.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let decoded = self.edit(label, |session| {
+ let mut decoded = Vec::with_capacity(files.len());
+ for file in files {
+ session.doc.resources.insert(file.name.clone(), std::sync::Arc::new(file.bytes));
+ session.doc.project.resource_sources.insert(file.name.clone(), file.source);
+ decoded.push((file.name, file.image));
+ }
+
+ Ok(decoded)
+ })?;
+
+ // The edit marked every set using a replaced resource for recompositing; the new pixels are read then
+ let mut names = Vec::with_capacity(decoded.len());
+ for (name, image) in decoded {
+ if crate::fill_alpha::matches_saved_picture(&name, &image) {
+ self.library_alphas.insert(name.clone());
+ } else {
+ self.library_alphas.remove(&name);
+ }
+
+ self.images.insert(name.clone(), crate::resource_cmds::decoded(image));
+ names.push(name);
+ }
+
+ Ok(names)
+ }
+}
+
+/// How `stored` (a resource's bytes) compares with the file `source` names now
+#[cfg(not(target_arch = "wasm32"))]
+fn compare_with_file(source: &ResourceSource, stored: &[u8]) -> (ResourceStatus, Option) {
+ let path = std::path::Path::new(&source.path);
+ let metadata = match std::fs::metadata(path) {
+ Ok(metadata) if metadata.is_file() => metadata,
+ Ok(_) => return (ResourceStatus::Missing, Some(format!("{} is not a regular file", source.path))),
+ Err(error) => return (ResourceStatus::Missing, Some(format!("{}: {error}", source.path))),
+ };
+
+ if metadata.len() != stored.len() as u64 {
+ return (ResourceStatus::Outdated, None);
+ }
+
+ let modified_ms = modified_ms(&metadata);
+ if modified_ms != 0 && modified_ms == source.modified_ms {
+ return (ResourceStatus::UpToDate, None);
+ }
+
+ // A newer time alone is not a change: the file may have been saved again unchanged
+ match crate::resource_cmds::read_resource_file("resource.status", path, crate::resource_cmds::MAX_BYTES as u64) {
+ Ok(bytes) if bytes == stored => (ResourceStatus::UpToDate, None),
+ Ok(_) => (ResourceStatus::Outdated, None),
+ Err(error) => (ResourceStatus::Missing, Some(error.to_string())),
+ }
+}
+
+#[cfg(target_arch = "wasm32")]
+fn compare_with_file(_: &ResourceSource, _: &[u8]) -> (ResourceStatus, Option) {
+ (ResourceStatus::Missing, Some("file paths are not available in the browser".to_string()))
+}
+
+/// A file's modification time in milliseconds since the Unix epoch (0 when the system has none)
+#[cfg(not(target_arch = "wasm32"))]
+fn modified_ms(metadata: &std::fs::Metadata) -> u64 {
+ let since_epoch = metadata.modified().ok().and_then(|modified| modified.duration_since(std::time::UNIX_EPOCH).ok());
+ since_epoch.map_or(0, |elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX))
+}
+
+/// [`modified_ms`] of the file at `path` (0 when it cannot be read)
+#[cfg(not(target_arch = "wasm32"))]
+pub(crate) fn modified_ms_of(path: &std::path::Path) -> u64 {
+ std::fs::metadata(path).map_or(0, |metadata| modified_ms(&metadata))
+}
+
+/// `path` made absolute against the working folder, so the record does not depend on where the app started
+#[cfg(not(target_arch = "wasm32"))]
+pub(crate) fn absolute_path(path: &str) -> String {
+ std::path::absolute(path).ok().and_then(|absolute| absolute.to_str().map(str::to_string)).unwrap_or_else(|| path.to_string())
+}
+
+fn status(s: &Session) -> Value {
+ let states = s.resource_states();
+ let outdated = states.iter().filter(|state| state.status == ResourceStatus::Outdated).count();
+ let resources: Vec = states
+ .iter()
+ .map(|state| {
+ let mut row = json!({"name": state.name, "status": state.status.id()});
+ if let Some(path) = &state.path {
+ row["path"] = json!(path);
+ }
+ if let Some(error) = &state.error {
+ row["error"] = json!(error);
+ }
+
+ row
+ })
+ .collect();
+
+ json!({"resources": resources, "total": states.len(), "outdated": outdated})
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn update(s: &mut Session, p: &Value) -> Result {
+ const CMD: &str = "resource.update";
+
+ let names: Vec = match p.get("names") {
+ None | Some(Value::Null) => s.resource_states().into_iter().filter(|state| state.status == ResourceStatus::Outdated).map(|state| state.name).collect(),
+ Some(Value::Array(names)) => {
+ names.iter().map(|name| name.as_str().map(str::to_string).ok_or_else(|| bad(CMD, "`names` must be resource names"))).collect::>()?
+ }
+ Some(_) => return Err(bad(CMD, "`names` must be an array of resource names")),
+ };
+
+ // Every name is checked before any file is read
+ for name in &names {
+ if !s.doc.resources.contains_key(name) {
+ return Err(bad(CMD, format!("no resource `{name}`")));
+ }
+ if !s.doc.project.resource_sources.contains_key(name) {
+ return Err(bad(CMD, format!("`{name}` has no source file: relink it to a file first")));
+ }
+ }
+
+ // A file that cannot be read fails alone; the others still update
+ let (mut files, mut failed) = (Vec::new(), Vec::new());
+ for name in names {
+ let Some(path) = s.doc.project.resource_sources.get(&name).map(|source| source.path.clone()) else { continue };
+ match crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), &path) {
+ // Unchanged contents need no undo step
+ Ok(file) if s.doc.resources.get(&name).is_some_and(|stored| **stored == file.bytes) => {}
+ Ok(file) => files.push(file),
+ Err(error) => failed.push(json!({"name": name, "error": error.to_string()})),
+ }
+ }
+
+ if files.is_empty() && !failed.is_empty() {
+ let reasons: Vec<&str> = failed.iter().filter_map(|failure| failure["error"].as_str()).collect();
+ return Err(bad(CMD, format!("nothing was updated: {}", reasons.join("; "))));
+ }
+
+ let updated = s.install_reloaded("Update resources", files)?;
+ Ok(json!({"updated": updated, "failed": failed}))
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn relink(s: &mut Session, p: &Value) -> Result {
+ const CMD: &str = "resource.relink";
+
+ let name = crate::commands::strp(p, "name").ok_or_else(|| bad(CMD, "`name` is required"))?.to_string();
+ let path = crate::commands::strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?;
+ if !s.doc.resources.contains_key(&name) {
+ return Err(bad(CMD, format!("no resource `{name}`")));
+ }
+
+ let file = crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), path)?;
+ let path = file.source.path.clone();
+ s.install_reloaded("Relink resource", vec![file])?;
+
+ Ok(json!({"name": name, "path": path}))
+}
+
+#[cfg(target_arch = "wasm32")]
+fn update(_: &mut Session, _: &Value) -> Result {
+ Err(bad("resource.update", "file paths are not available in the browser"))
+}
+
+#[cfg(target_arch = "wasm32")]
+fn relink(_: &mut Session, _: &Value) -> Result {
+ Err(bad("resource.relink", "file paths are not available in the browser"))
+}
diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs
index 58b5cbe7..beb20ab0 100644
--- a/crates/engine/src/session.rs
+++ b/crates/engine/src/session.rs
@@ -957,6 +957,7 @@ impl Session {
let (label, restored) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?;
let current = std::mem::replace(&mut self.doc, restored);
self.after_history(¤t);
+ self.forget_replaced_images(¤t);
self.redo.push((label.clone(), current));
self.sync_images();
Ok(label)
@@ -977,6 +978,7 @@ impl Session {
let (label, restored) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?;
let current = std::mem::replace(&mut self.doc, restored);
self.after_history(¤t);
+ self.forget_replaced_images(¤t);
self.undo.push((label.clone(), current));
self.sync_images();
Ok(label)
diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs
index ce9f1614..5010e30f 100644
--- a/crates/engine/tests/it/main.rs
+++ b/crates/engine/tests/it/main.rs
@@ -55,6 +55,7 @@ mod pbr_import;
mod perf;
mod polygon_fill;
mod project_recovery;
+mod resource_updater;
mod resources_used;
mod sample;
mod solo;
diff --git a/crates/engine/tests/it/resource_updater.rs b/crates/engine/tests/it/resource_updater.rs
new file mode 100644
index 00000000..c0d0f1dc
--- /dev/null
+++ b/crates/engine/tests/it/resource_updater.rs
@@ -0,0 +1,227 @@
+//! The Resources Updater: image resources remember their files, a changed file shows as outdated,
+//! Update reads it again (one undo step, recompositing its layers) and Relink follows another file
+
+use std::path::{Path, PathBuf};
+
+use serde_json::{Value, json};
+use texturecraft_engine::core::Channel;
+use texturecraft_engine::geom::primitives;
+use texturecraft_engine::{ResourceStatus, Session, execute};
+
+const RESOLUTION: u32 = 64;
+const SAMPLE_STRIDE: usize = 4;
+const RED: [u8; 4] = [255, 0, 0, 255];
+const GREEN: [u8; 4] = [0, 255, 0, 255];
+
+/// A test folder removed when dropped
+struct TempDir(PathBuf);
+
+impl TempDir {
+ fn new(test: &str) -> TempDir {
+ let path = std::env::temp_dir().join(format!("tc-resource-updater-{test}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&path);
+ std::fs::create_dir_all(&path).unwrap();
+ TempDir(path)
+ }
+
+ fn file(&self, name: &str) -> PathBuf {
+ self.0.join(name)
+ }
+}
+
+impl Drop for TempDir {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.0);
+ }
+}
+
+fn session() -> Session {
+ Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, RESOLUTION).unwrap()
+}
+
+/// Write a `size` × `size` PNG of one colour (sizes differ between versions, so the file size changes too)
+fn write_png(path: &Path, size: u32, color: [u8; 4]) {
+ image::RgbaImage::from_pixel(size, size, image::Rgba(color)).save(path).unwrap();
+}
+
+fn text(path: &Path) -> &str {
+ path.to_str().unwrap()
+}
+
+/// Import `path` and show it as a base colour fill; returns the resource name
+fn import_as_fill(s: &mut Session, path: &Path) -> String {
+ let name = execute(s, "resource.import", &json!({"path": text(path)})).unwrap()["name"].as_str().unwrap().to_string();
+ execute(s, "layer.add.image", &json!({"name": name})).unwrap();
+ s.update();
+ name
+}
+
+fn base_colors(s: &Session) -> Vec<[f32; 3]> {
+ let composite = &s.caches[s.ts()].composite;
+ let samples = || (0..RESOLUTION).step_by(SAMPLE_STRIDE);
+ samples().flat_map(|y| samples().map(move |x| (x, y))).map(|(x, y)| composite.value(Channel::BaseColor, x, y)).collect()
+}
+
+fn status_of(s: &Session, name: &str) -> ResourceStatus {
+ s.resource_states().into_iter().find(|state| state.name == name).expect("the resource is listed").status
+}
+
+#[test]
+fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() {
+ let dir = TempDir::new("update");
+ let file = dir.file("bricks.png");
+ write_png(&file, 4, RED);
+ let mut s = session();
+ let name = import_as_fill(&mut s, &file);
+ let before = base_colors(&s);
+ assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate);
+
+ write_png(&file, 8, GREEN);
+ let status = execute(&mut s, "resource.status", &Value::Null).unwrap();
+
+ assert_eq!(status["outdated"], json!(1));
+ assert_eq!(status["resources"][0]["name"], json!(name));
+ assert_eq!(status["resources"][0]["status"], json!("outdated"));
+
+ let steps = s.history_labels().len();
+ let updated = execute(&mut s, "resource.update", &json!({})).unwrap();
+ s.update();
+ let after = base_colors(&s);
+
+ assert_eq!(updated["updated"], json!([name]));
+ assert_eq!(s.history_labels().len(), steps + 1, "one undo step");
+ assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate);
+ assert_eq!(s.images[&name].width, 8, "the new pixels are decoded");
+ assert_ne!(after, before, "the fill using the resource recomposited");
+
+ execute(&mut s, "edit.undo", &Value::Null).unwrap();
+ s.update();
+
+ assert_eq!(s.images[&name].width, 4, "undo brings back the old pixels under the same name");
+ assert_eq!(base_colors(&s), before);
+ assert_eq!(status_of(&s, &name), ResourceStatus::Outdated, "the file on disk is still the new one");
+
+ execute(&mut s, "edit.redo", &Value::Null).unwrap();
+ s.update();
+
+ assert_eq!(s.images[&name].width, 8);
+ assert_eq!(base_colors(&s), after);
+}
+
+#[test]
+fn nothing_outdated_adds_no_undo_step() {
+ let dir = TempDir::new("unchanged");
+ let file = dir.file("same.png");
+ write_png(&file, 4, RED);
+ let mut s = session();
+ import_as_fill(&mut s, &file);
+ let steps = s.history_labels().len();
+
+ let updated = execute(&mut s, "resource.update", &json!({})).unwrap();
+
+ assert_eq!(updated["updated"], json!([]));
+ assert_eq!(s.history_labels().len(), steps);
+}
+
+#[test]
+fn a_missing_file_is_reported_and_updating_it_changes_nothing() {
+ let dir = TempDir::new("missing");
+ let file = dir.file("gone.png");
+ write_png(&file, 4, RED);
+ let mut s = session();
+ let name = import_as_fill(&mut s, &file);
+ std::fs::remove_file(&file).unwrap();
+ let steps = s.history_labels().len();
+
+ let state = s.resource_states().into_iter().find(|state| state.name == name).unwrap();
+ let error = execute(&mut s, "resource.update", &json!({"names": [name]})).unwrap_err();
+
+ assert_eq!(state.status, ResourceStatus::Missing);
+ assert!(state.error.is_some(), "the reason is shown");
+ assert!(error.to_string().contains("nothing was updated"), "{error}");
+ assert_eq!(s.history_labels().len(), steps);
+ assert_eq!(s.images[&name].width, 4, "the resource keeps its pixels");
+}
+
+#[test]
+fn an_unreadable_file_fails_alone_while_the_others_update() {
+ let dir = TempDir::new("partial");
+ let (kept, gone) = (dir.file("kept.png"), dir.file("gone.png"));
+ write_png(&kept, 4, RED);
+ write_png(&gone, 4, RED);
+ let mut s = session();
+ let kept_name = import_as_fill(&mut s, &kept);
+ let gone_name = import_as_fill(&mut s, &gone);
+ write_png(&kept, 8, GREEN);
+ std::fs::remove_file(&gone).unwrap();
+
+ let result = execute(&mut s, "resource.update", &json!({"names": [kept_name, gone_name]})).unwrap();
+
+ assert_eq!(result["updated"], json!([kept_name]));
+ assert_eq!(result["failed"][0]["name"], json!(gone_name));
+ assert_eq!(s.images[&kept_name].width, 8);
+}
+
+#[test]
+fn relink_reads_another_file_and_follows_it_from_then_on() {
+ let dir = TempDir::new("relink");
+ let (first, second) = (dir.file("first.png"), dir.file("second.png"));
+ write_png(&first, 4, RED);
+ write_png(&second, 8, GREEN);
+ let mut s = session();
+ let name = import_as_fill(&mut s, &first);
+ let before = base_colors(&s);
+ let steps = s.history_labels().len();
+
+ execute(&mut s, "resource.relink", &json!({"name": name, "path": text(&second)})).unwrap();
+ s.update();
+
+ assert_eq!(s.history_labels().len(), steps + 1, "one undo step");
+ assert_eq!(s.images[&name].width, 8, "the resource keeps its name and takes the new file's pixels");
+ assert_ne!(base_colors(&s), before);
+ assert!(s.doc.project.resource_sources[&name].path.ends_with("second.png"));
+
+ // The old file no longer matters, the new one does
+ write_png(&first, 16, GREEN);
+ assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate);
+ write_png(&second, 16, RED);
+ assert_eq!(status_of(&s, &name), ResourceStatus::Outdated);
+
+ execute(&mut s, "edit.undo", &Value::Null).unwrap();
+ assert!(s.doc.project.resource_sources[&name].path.ends_with("first.png"), "undo restores the link");
+}
+
+#[test]
+fn resources_without_a_file_cannot_update_and_a_reopened_project_keeps_its_links() {
+ let dir = TempDir::new("reopen");
+ let file = dir.file("kept.png");
+ write_png(&file, 4, RED);
+ let mut s = session();
+ let linked = import_as_fill(&mut s, &file);
+ let png = std::fs::read(&file).unwrap();
+ let unlinked = s.import_resource_bytes("made.png", png).unwrap();
+
+ assert_eq!(status_of(&s, &unlinked), ResourceStatus::NoSource);
+ assert!(execute(&mut s, "resource.update", &json!({"names": [unlinked]})).is_err());
+
+ let reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
+ write_png(&file, 8, GREEN);
+
+ assert_eq!(status_of(&reopened, &linked), ResourceStatus::Outdated);
+}
+
+#[test]
+fn a_removed_resource_forgets_its_file() {
+ let dir = TempDir::new("remove");
+ let file = dir.file("old.png");
+ write_png(&file, 4, RED);
+ let mut s = session();
+ let name = execute(&mut s, "resource.import", &json!({"path": text(&file)})).unwrap()["name"].as_str().unwrap().to_string();
+
+ execute(&mut s, "resource.remove", &json!({"name": name})).unwrap();
+ let png = std::fs::read(&file).unwrap();
+ let reused = s.import_resource_bytes("old.png", png).unwrap();
+
+ assert_eq!(reused, name, "the name is free again");
+ assert_eq!(status_of(&s, &reused), ResourceStatus::NoSource, "a new resource under the old name does not inherit the file");
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 47259f2b..100d07a5 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -124,6 +124,8 @@ mod resolution_band;
mod resource_panel;
mod resource_picker;
mod resource_picker_item;
+#[cfg(not(target_arch = "wasm32"))]
+mod resources_updater;
mod round_gizmo;
mod running_bake;
pub mod saved_search;
@@ -156,6 +158,7 @@ pub mod thumbs;
mod tile_edits;
mod tile_picture;
pub mod titlebar;
+pub mod toast_action;
pub mod toolbar;
pub mod ui_state_store;
pub mod unavailable;
@@ -235,6 +238,8 @@ pub struct Toast {
pub error: bool,
pub until: f64,
pub show_log: bool,
+ /// A button after the text that acts on the notice
+ pub action: Option,
}
pub struct TextureCraftApp {
@@ -317,6 +322,9 @@ pub struct TextureCraftApp {
styled: Option<(theme::Brightness, theme::Accent)>,
/// Whether the window had focus last frame.
focused: bool,
+ /// The outdated resources the last "changed on disk" notice named, so an unchanged set is not announced again
+ #[cfg(not(target_arch = "wasm32"))]
+ pub(crate) resources_notified: std::collections::BTreeSet,
/// The update check and prompt (desktop only).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) updates_rt: updates_ui::Runtime,
@@ -439,6 +447,8 @@ impl TextureCraftApp {
styled: None,
focused: true,
#[cfg(not(target_arch = "wasm32"))]
+ resources_notified: std::collections::BTreeSet::new(),
+ #[cfg(not(target_arch = "wasm32"))]
updates_rt: updates_ui::Runtime::default(),
#[cfg(not(target_arch = "wasm32"))]
file_dialogs: file_dialogs::FileDialogs::new(cc.egui_ctx.clone()),
@@ -590,13 +600,13 @@ impl TextureCraftApp {
}
pub fn toast(&mut self, text: impl Into, error: bool) {
- self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 }, show_log: false });
+ self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 }, show_log: false, action: None });
}
/// An error toast that stays until the user dismisses it (for a problem that persists and
/// is reported once, like a texture set the GPU could not hold).
pub fn toast_sticky(&mut self, text: impl Into) {
- self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false });
+ self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false, action: None });
}
/// Start baking texture sets in the background, one after another. Invalid set indices
@@ -1117,6 +1127,10 @@ impl eframe::App for TextureCraftApp {
let focused = ctx.input(|input| input.viewport().focused).unwrap_or(true);
if focused && !self.focused {
self.library = None;
+
+ // Files may have been edited in another app meanwhile
+ #[cfg(not(target_arch = "wasm32"))]
+ resources_updater::check_on_focus(self);
}
self.focused = focused;
@@ -1292,6 +1306,7 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) {
let tk = theme::Tokens::get(ctx);
let mut dismissed = None;
let mut show_log = false;
+ let mut clicked_action = None;
// Limit toast dimensions so the dismiss button stays visible
let screen = ctx.content_rect().size();
@@ -1320,6 +1335,12 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) {
show_log = true;
dismissed = Some(i);
}
+ if let Some(action) = t.action
+ && ui.button(i18n::tr(action.label())).clicked()
+ {
+ clicked_action = Some(action);
+ dismissed = Some(i);
+ }
});
if sticky && widgets::icon_button(ui, egui_phosphor::regular::X, i18n::tr("Dismiss"), false, 18.0).clicked() {
dismissed = Some(i);
@@ -1337,4 +1358,8 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) {
app.ui.log_channel = log_panel::LogChannel::General;
crate::rail_popup::open(app, crate::docking::Panel::Log);
}
+
+ if let Some(action) = clicked_action {
+ action.run(app);
+ }
}
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 1d4588ea..a0fd80de 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -526,6 +526,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
} else if app.ui.windows.import_resources.is_some() {
#[cfg(not(target_arch = "wasm32"))]
crate::import_resources::keys_in(app, input, nothing_focused, popup_open);
+ } else if app.ui.windows.resources_updater.is_some() && !popup_open && input.key_pressed(Key::Escape) {
+ #[cfg(not(target_arch = "wasm32"))]
+ crate::resources_updater::keys_in(app, input);
} else if !popup_open && app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
app.picking_color = None;
} else if escape_is_free && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
diff --git a/crates/ui-egui/src/resources_updater.rs b/crates/ui-egui/src/resources_updater.rs
new file mode 100644
index 00000000..4bb9ce60
--- /dev/null
+++ b/crates/ui-egui/src/resources_updater.rs
@@ -0,0 +1,383 @@
+//! The Resources Updater: the project's image resources and whether the files they were imported
+//! from changed on disk. Update reads a changed file again, Select new resource points a resource
+//! at another file, and a notice offers to update when the app gets the focus back after files
+//! changed. Everything runs through `resource.status`, `resource.update` and `resource.relink`.
+
+mod row_request;
+
+use std::collections::BTreeSet;
+
+use egui::{Key, Modifiers};
+use serde_json::json;
+use texturecraft_engine::{ResourceState, ResourceStatus};
+
+use crate::TextureCraftApp;
+use crate::file_dialogs::{Bound, FileDialog};
+use crate::i18n::{tr, trf};
+use crate::state::ResourcesUpdater;
+use crate::theme::Tokens;
+use crate::toast_action::ToastAction;
+use crate::web_files::IMAGE_EXTS;
+use crate::widgets::primary_button;
+use row_request::RowRequest;
+
+/// Width of the window
+const WINDOW_WIDTH_POINTS: f32 = 640.0;
+/// Height of the resource list
+const LIST_HEIGHT_POINTS: f32 = 360.0;
+// Initial space for the header, tabs, filters and footer
+const WINDOW_CHROME_HEIGHT_POINTS: f32 = 160.0;
+/// Side of a row's thumbnail
+const THUMBNAIL_POINTS: f32 = 40.0;
+/// Width of the name filter field
+const NAME_FILTER_WIDTH_POINTS: f32 = 160.0;
+/// Width of the status dropdown
+const STATUS_WIDTH_POINTS: f32 = 120.0;
+/// Space inside a row's frame
+const ROW_MARGIN: egui::Margin = egui::Margin::same(4);
+/// Strength of the danger tint behind an outdated row (the status text says it too)
+const OUTDATED_TINT: f32 = 0.18;
+/// How long the "changed on disk" notice stays, in seconds: long enough to reach its button
+const NOTICE_SECONDS: f64 = 12.0;
+
+/// Opens the window, or closes it when it is open (the shelf button)
+pub(crate) fn toggle(app: &mut TextureCraftApp) {
+ if app.ui.windows.resources_updater.take().is_none() {
+ open(app);
+ }
+}
+
+/// Opens the window with the resources checked now (an open window is checked again)
+pub(crate) fn open(app: &mut TextureCraftApp) {
+ let window = app.ui.windows.resources_updater.take().unwrap_or_default();
+ app.ui.windows.resources_updater = Some(ResourcesUpdater {
+ rows: app.session.resource_states(),
+ project: app.session.project_id,
+ checked_revision: app.session.revision,
+ ..window
+ });
+}
+
+/// The app has the focus back: check the files again and, when other resources than last time
+/// are outdated, show a notice whose button updates them
+pub(crate) fn check_on_focus(app: &mut TextureCraftApp) {
+ if !app.session.project_open {
+ return;
+ }
+
+ let rows = app.session.resource_states();
+ let outdated: BTreeSet = rows.iter().filter(|row| row.status == ResourceStatus::Outdated).map(|row| row.name.clone()).collect();
+ if let Some(window) = app.ui.windows.resources_updater.as_mut() {
+ window.rows = rows;
+ window.checked_revision = app.session.revision;
+ }
+
+ if !outdated.is_empty() && outdated != app.resources_notified {
+ let text = if outdated.len() == 1 {
+ tr("1 resource changed on disk").to_string()
+ } else {
+ trf("{count} resources changed on disk", &[("count", &outdated.len())])
+ };
+ app.toast(text, false);
+ if let Some(toast) = app.toasts.last_mut() {
+ toast.until = app.last_time + NOTICE_SECONDS;
+ toast.action = Some(ToastAction::UpdateResources);
+ }
+ }
+ app.resources_notified = outdated;
+}
+
+/// Read the files of `names` again (every outdated resource when None), one undo step, and say
+/// what happened
+pub(crate) fn update(app: &mut TextureCraftApp, names: Option>) {
+ let params = match names {
+ Some(names) => json!({ "names": names }),
+ None => json!({}),
+ };
+ let Some(result) = app.run("resource.update", params) else { return };
+
+ let updated = result["updated"].as_array().map_or(0, Vec::len);
+ let failed: Vec = result["failed"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(|failure| format!("{}: {}", failure["name"].as_str().unwrap_or_default(), failure["error"].as_str().unwrap_or_default()))
+ .collect();
+ if failed.is_empty() {
+ app.toast(trf("Updated {count} resources", &[("count", &updated)]), false);
+ } else {
+ app.toast(trf("Updated {count} resources; could not update {failed}", &[("count", &updated), ("failed", &failed.join("; "))]), true);
+ }
+
+ // What was announced is handled; a later change is announced again
+ app.resources_notified.clear();
+}
+
+/// Ask for another file for resource `name`; the resource takes its pixels and follows it
+fn select_new_resource(app: &mut TextureCraftApp, name: String) {
+ let dialog = FileDialog::open().filter(tr("Images"), IMAGE_EXTS);
+ app.ask_file(dialog, Bound::Project, move |app, paths| {
+ let Some(path) = paths.first() else { return };
+ let Some(path) = path.to_str() else {
+ app.toast(trf("Could not use a path that is not UTF-8: {path}", &[("path", &path.display())]), true);
+ return;
+ };
+
+ if app.run("resource.relink", json!({ "name": name, "path": path })).is_some() {
+ app.toast(trf("{name} now reads {path}", &[("name", &name), ("path", &path)]), false);
+ }
+ });
+}
+
+/// Show the folder holding `path` in the system's file manager
+fn show_in_folder(app: &mut TextureCraftApp, path: &str) {
+ let folder = std::path::Path::new(path).parent().map(std::path::Path::to_path_buf).unwrap_or_default();
+ if let Err(error) = app.file_dialogs.show_folder(&folder) {
+ app.toast(trf("Could not show {folder}: {error}", &[("folder", &folder.display()), ("error", &error)]), true);
+ }
+}
+
+/// The keys of the open window: Escape closes it (an open dropdown takes it first, see `menus`)
+pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState) {
+ if input.consume_key(Modifiers::NONE, Key::Escape) {
+ app.ui.windows.resources_updater = None;
+ }
+}
+
+/// Whether `row` passes the window's status and name filters
+fn shown(window: &ResourcesUpdater, row: &ResourceState) -> bool {
+ let name_filter = window.name_filter.trim().to_lowercase();
+ window.status_filter.is_none_or(|status| row.status == status) && (name_filter.is_empty() || row.name.to_lowercase().contains(&name_filter))
+}
+
+/// "(N resources, M outdated)"
+fn summary(rows: &[ResourceState]) -> String {
+ let outdated = rows.iter().filter(|row| row.status == ResourceStatus::Outdated).count();
+ trf("({count} resources, {outdated} outdated)", &[("count", &rows.len()), ("outdated", &outdated)])
+}
+
+pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
+ let Some(mut window) = app.ui.windows.resources_updater.take() else { return };
+
+ // Resources of another project are not this one's
+ if window.project != app.session.project_id || !app.session.project_open {
+ return;
+ }
+
+ // Every change (an update, undo, redo, a removed resource) is checked again
+ if window.checked_revision != app.session.revision {
+ window.rows = app.session.resource_states();
+ window.checked_revision = app.session.revision;
+ }
+
+ let tokens = Tokens::get(ctx);
+ let mut open = true;
+ let (mut refresh, mut update_all) = (false, false);
+ let mut request = None;
+
+ crate::windows::dialog(ctx, "resources_updater", tr("Resources Updater"), &mut open)
+ .default_size(egui::vec2(WINDOW_WIDTH_POINTS, LIST_HEIGHT_POINTS + WINDOW_CHROME_HEIGHT_POINTS))
+ .show(ctx, |ui| {
+ ui.label(format!("{} {}", tr("Project :"), app.session.doc.project.name));
+
+ // Shader resources have no equivalent here: the one tab lists image resources
+ let tab = ui.add(egui::Button::selectable(true, tr("Resources")));
+ tab.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, true, tr("Resources")));
+ ui.separator();
+
+ ui.horizontal(|ui| {
+ let status_label = ui.label(tr("Status:"));
+ let selected = window.status_filter.map_or(tr("All"), |status| tr(status.label()));
+ egui::ComboBox::from_id_salt("resources_updater_status")
+ .width(STATUS_WIDTH_POINTS)
+ .selected_text(selected)
+ .show_ui(ui, |ui| {
+ ui.selectable_value(&mut window.status_filter, None, tr("All"));
+ for status in ResourceStatus::ALL {
+ ui.selectable_value(&mut window.status_filter, Some(status), tr(status.label()));
+ }
+ })
+ .response
+ .labelled_by(status_label.id);
+
+ let name_label = ui.label(tr("Name filter:"));
+ ui.add(egui::TextEdit::singleline(&mut window.name_filter).desired_width(NAME_FILTER_WIDTH_POINTS)).labelled_by(name_label.id);
+
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if ui.button(tr("Bottom")).clicked() {
+ window.jump = Some(egui::Align::Max);
+ }
+ if ui.button(tr("Top")).clicked() {
+ window.jump = Some(egui::Align::Min);
+ }
+ });
+ });
+ ui.add_space(4.0);
+
+ ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| {
+ ui.horizontal(|ui| {
+ refresh = ui.button(tr("Refresh")).clicked();
+ ui.label(summary(&window.rows));
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ let outdated = window.rows.iter().any(|row| row.status == ResourceStatus::Outdated);
+ let button = ui.add_enabled(outdated, primary_button(ui, tr("Update All")));
+ update_all = button.on_disabled_hover_text(tr("No resource is outdated")).clicked();
+ });
+ });
+ ui.separator();
+
+ let list_height = ui.available_height().max(0.0);
+ ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| {
+ egui::ScrollArea::vertical().max_height(list_height).auto_shrink([false, false]).show(ui, |ui| {
+ let jump = window.jump.take();
+ if jump == Some(egui::Align::Min) {
+ ui.scroll_to_cursor(Some(egui::Align::Min));
+ }
+
+ let visible: Vec<&ResourceState> = window.rows.iter().filter(|row| shown(&window, row)).collect();
+ if visible.is_empty() {
+ ui.label(tr("No resources match the filters"));
+ }
+ for (index, row) in visible.into_iter().enumerate() {
+ if let Some(asked) = row_ui(app, ui, &tokens, index + 1, row) {
+ request = Some(asked);
+ }
+ }
+
+ if jump == Some(egui::Align::Max) {
+ ui.scroll_to_cursor(Some(egui::Align::Max));
+ }
+ });
+ });
+ });
+ });
+
+ if !open {
+ return;
+ }
+
+ app.ui.windows.resources_updater = Some(window);
+
+ if refresh {
+ open(app);
+ }
+ if update_all {
+ update(app, None);
+ }
+ match request {
+ Some(RowRequest::Update(name)) => update(app, Some(vec![name])),
+ Some(RowRequest::SelectNew(name)) => select_new_resource(app, name),
+ Some(RowRequest::ShowFolder(path)) => show_in_folder(app, &path),
+ None => {}
+ }
+}
+
+/// One resource: its thumbnail, number, name, file and status, and its buttons. Outdated rows are
+/// tinted, and their status says so in words too.
+fn row_ui(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, number: usize, row: &ResourceState) -> Option {
+ let outdated = row.status == ResourceStatus::Outdated;
+ let (fill, stroke) = if outdated {
+ (tokens.danger.gamma_multiply(OUTDATED_TINT), egui::Stroke::new(1.0, tokens.danger))
+ } else {
+ (egui::Color32::TRANSPARENT, egui::Stroke::NONE)
+ };
+ let mut request = None;
+
+ egui::Frame::NONE.fill(fill).stroke(stroke).inner_margin(ROW_MARGIN).corner_radius(crate::theme::CARD_RADIUS).show(ui, |ui| {
+ ui.set_width(ui.available_width());
+ ui.horizontal(|ui| {
+ match app.session.images.get(&row.name) {
+ Some(image) => {
+ let texture = app.thumbs.image(ui.ctx(), &row.name, image);
+ ui.add(egui::Image::new(&texture).fit_to_exact_size(egui::vec2(THUMBNAIL_POINTS, THUMBNAIL_POINTS)));
+ }
+
+ // A file that could not be decoded has no picture; the row keeps its place
+ None => ui.add_space(THUMBNAIL_POINTS),
+ }
+ ui.label(number.to_string());
+
+ // Buttons take their room on the right first, so the texts truncate in what is left
+ // Each button's accessible name says which resource it acts on
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ let update = ui.add_enabled(outdated, egui::Button::new(tr("Update")));
+ let update_name = format!("{} {}", tr("Update"), row.name);
+ update.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, outdated, &update_name));
+ if update.clicked() {
+ request = Some(RowRequest::Update(row.name.clone()));
+ }
+
+ let select = ui.button(tr("Select new resource"));
+ let select_name = format!("{} {}", tr("Select new resource"), row.name);
+ select.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &select_name));
+ if select.clicked() {
+ request = Some(RowRequest::SelectNew(row.name.clone()));
+ }
+
+ if let Some(path) = &row.path {
+ let folder = ui.button(tr("Show in folder"));
+ let folder_name = format!("{} {}", tr("Show in folder"), row.name);
+ folder.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &folder_name));
+ if folder.clicked() {
+ request = Some(RowRequest::ShowFolder(path.clone()));
+ }
+ }
+
+ ui.vertical(|ui| {
+ ui.add(egui::Label::new(format!("{} {}", tr("Name :"), row.name)).truncate());
+ let file = row.path.as_deref().unwrap_or(tr("No source file"));
+ ui.add(egui::Label::new(format!("{} {}", tr("File :"), file)).truncate()).on_hover_text(file);
+ let status = ui.label(tr(row.status.label()));
+ if let Some(error) = &row.error {
+ status.on_hover_text(error);
+ }
+ });
+ });
+ });
+ });
+
+ request
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::PoisonError;
+
+ use egui_kittest::Harness;
+ use texturecraft_engine::Session;
+
+ use super::*;
+
+ fn write_png(path: &std::path::Path, size: u32) {
+ image::RgbaImage::from_pixel(size, size, image::Rgba([10, 200, 30, 255])).save(path).unwrap();
+ }
+
+ fn notices(app: &TextureCraftApp) -> usize {
+ app.toasts.iter().filter(|toast| toast.action == Some(ToastAction::UpdateResources)).count()
+ }
+
+ #[test]
+ fn a_changed_file_is_announced_once_and_the_notice_updates_it() {
+ let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(PoisonError::into_inner);
+ let path = std::env::temp_dir().join(format!("texturecraft-resources-notice-{}.png", std::process::id()));
+ write_png(&path, 4);
+ let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
+ let mut harness = Harness::builder().build_eframe(|cc| TextureCraftApp::new(cc, session));
+ let app = harness.state_mut();
+ let name = app.run("resource.import", json!({ "path": path.to_str().unwrap() })).unwrap()["name"].as_str().unwrap().to_string();
+
+ check_on_focus(app);
+ assert_eq!(notices(app), 0, "nothing changed yet");
+
+ write_png(&path, 8);
+ check_on_focus(app);
+ check_on_focus(app);
+ assert_eq!(notices(app), 1, "the same change is announced once");
+
+ ToastAction::UpdateResources.run(app);
+ std::fs::remove_file(&path).ok();
+
+ assert_eq!(app.session.images[&name].width, 8, "the notice's button updated the resource");
+ assert_eq!(app.session.history_labels().last().map(String::as_str), Some("Update resources"));
+ }
+}
diff --git a/crates/ui-egui/src/resources_updater/row_request.rs b/crates/ui-egui/src/resources_updater/row_request.rs
new file mode 100644
index 00000000..75f0626c
--- /dev/null
+++ b/crates/ui-egui/src/resources_updater/row_request.rs
@@ -0,0 +1,9 @@
+/// What a Resources Updater row's buttons asked for, run after the window is drawn
+pub(super) enum RowRequest {
+ /// Update: read the resource's file again
+ Update(String),
+ /// Select new resource: ask for another file for the resource
+ SelectNew(String),
+ /// Show in folder: the folder holding this file
+ ShowFolder(String),
+}
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index 0c767e1b..9f49b2e7 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -14,11 +14,13 @@ mod import_row;
mod library_location;
mod project_config;
mod resource_usage;
+mod resources_updater;
pub use import_resources::ImportResources;
pub use import_row::ImportRow;
pub use library_location::LibraryLocation;
pub use project_config::ProjectConfig;
pub use resource_usage::ResourceUsage;
+pub use resources_updater::ResourcesUpdater;
mod console_line;
mod export_job;
@@ -115,6 +117,9 @@ pub struct Windows {
/// File > Import resources: the files added so far, imported by Import.
#[serde(skip)]
pub import_resources: Option,
+ /// The Resources Updater: the project's image resources and whether their files changed on disk.
+ #[serde(skip)]
+ pub resources_updater: Option,
/// What waits on the unsaved-changes dialog: save, don't save or cancel.
#[serde(skip)]
pub unsaved: Option,
diff --git a/crates/ui-egui/src/state/resources_updater.rs b/crates/ui-egui/src/state/resources_updater.rs
new file mode 100644
index 00000000..46fb9d12
--- /dev/null
+++ b/crates/ui-egui/src/state/resources_updater.rs
@@ -0,0 +1,19 @@
+use texturecraft_engine::{ResourceState, ResourceStatus};
+
+/// The Resources Updater window: the project's image resources as last checked, and the filters
+#[derive(Clone, Debug, PartialEq, Default)]
+pub struct ResourcesUpdater {
+ /// The resources and how they compare with their files, outdated first (checked on opening,
+ /// Refresh, every change and when the app gets the focus back)
+ pub rows: Vec,
+ /// The status the list is narrowed to (None: all)
+ pub status_filter: Option,
+ /// Shows only resources whose name contains this, ignoring case
+ pub name_filter: String,
+ /// Top or Bottom asked the list to scroll to that end in the next frame
+ pub jump: Option,
+ /// The project that was open when this window opened
+ pub project: u64,
+ /// The session revision the rows were checked at
+ pub(crate) checked_revision: u64,
+}
diff --git a/crates/ui-egui/src/toast_action.rs b/crates/ui-egui/src/toast_action.rs
new file mode 100644
index 00000000..d360fd7b
--- /dev/null
+++ b/crates/ui-egui/src/toast_action.rs
@@ -0,0 +1,34 @@
+//! A button on a toast that acts on what the toast says
+
+use crate::TextureCraftApp;
+
+/// What a toast's button does
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum ToastAction {
+ /// "Update": read every outdated resource file again (the "changed on disk" notice)
+ #[cfg(not(target_arch = "wasm32"))]
+ UpdateResources,
+}
+
+impl ToastAction {
+ /// The button's text (English; translated where it is drawn)
+ pub fn label(self) -> &'static str {
+ match self {
+ #[cfg(not(target_arch = "wasm32"))]
+ ToastAction::UpdateResources => "Update",
+ }
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ pub(crate) fn run(self, app: &mut TextureCraftApp) {
+ match self {
+ ToastAction::UpdateResources => crate::resources_updater::update(app, None),
+ }
+ }
+
+ /// The browser's toasts carry no action yet
+ #[cfg(target_arch = "wasm32")]
+ pub(crate) fn run(self, _: &mut TextureCraftApp) {
+ match self {}
+ }
+}
diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs
index 27274a1d..d36f3197 100644
--- a/crates/ui-egui/src/toolbar.rs
+++ b/crates/ui-egui/src/toolbar.rs
@@ -499,15 +499,33 @@ pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
ui.add_space(SHELF_GROUP_GAP);
}
- for (icon, label) in [(ic::HOURGLASS, "Snooze Autosave"), (ic::ARROWS_CLOCKWISE, "Resources Updater")] {
- ui.add_enabled_ui(false, |ui| icon_button(ui, icon, tr(label), false, SHELF_BUTTON_SIZE))
- .inner
- .on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE));
- }
+ ui.add_enabled_ui(false, |ui| icon_button(ui, ic::HOURGLASS, tr("Snooze Autosave"), false, SHELF_BUTTON_SIZE))
+ .inner
+ .on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE));
+ resources_updater_button(app, ui);
});
});
}
+/// The shelf's Resources Updater button: opens or closes its window while a project is open
+#[cfg(not(target_arch = "wasm32"))]
+fn resources_updater_button(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
+ let open = app.ui.windows.resources_updater.is_some();
+ let label = tr("Resources Updater");
+ let button = ui.add_enabled_ui(app.session.project_open, |ui| icon_button(ui, ic::ARROWS_CLOCKWISE, label, open, SHELF_BUTTON_SIZE)).inner;
+ if button.on_disabled_hover_text(tr("Open a project to check its resources")).clicked() {
+ crate::resources_updater::toggle(app);
+ }
+}
+
+/// The browser reads no files from disk, so there is nothing to update
+#[cfg(target_arch = "wasm32")]
+fn resources_updater_button(_: &mut TextureCraftApp, ui: &mut egui::Ui) {
+ ui.add_enabled_ui(false, |ui| icon_button(ui, ic::ARROWS_CLOCKWISE, tr("Resources Updater"), false, SHELF_BUTTON_SIZE))
+ .inner
+ .on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE));
+}
+
/// Width of the icon rail beside the dock
const RAIL_WIDTH: f32 = 38.0;
diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs
index f9e8fa5c..5080d2bd 100644
--- a/crates/ui-egui/src/windows.rs
+++ b/crates/ui-egui/src/windows.rs
@@ -23,6 +23,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
{
crate::project_config::show(app, ctx);
crate::import_resources::show(app, ctx);
+ crate::resources_updater::show(app, ctx);
}
crate::keymap::window(app, ctx);
crate::export_window::show(app, ctx);
diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs
index c8d7f0f3..82c21fcc 100644
--- a/crates/ui-egui/tests/it/main.rs
+++ b/crates/ui-egui/tests/it/main.rs
@@ -77,6 +77,7 @@ mod rail;
mod reference_order;
mod rename_anchor;
mod reset_ui;
+mod resources_updater;
mod settings_window;
mod shelf_click;
mod shelf_drop;
diff --git a/crates/ui-egui/tests/it/resources_updater.rs b/crates/ui-egui/tests/it/resources_updater.rs
new file mode 100644
index 00000000..298c1130
--- /dev/null
+++ b/crates/ui-egui/tests/it/resources_updater.rs
@@ -0,0 +1,137 @@
+//! The Resources Updater window, driven from the keyboard: the shelf button opens it, outdated
+//! resources come first, Update reads a changed file again as one undo step and Select new resource
+//! follows another file. File pickers are answered by the override, never shown.
+
+use std::path::{Path, PathBuf};
+
+use egui::{Key, Role};
+use egui_kittest::Harness;
+use egui_kittest::kittest::{NodeT, Queryable};
+use serde_json::json;
+use texturecraft_engine::Session;
+use texturecraft_ui_egui::TextureCraftApp;
+use texturecraft_ui_egui::file_dialogs::{Answer, Request};
+
+use super::temp_dir::TempDir;
+
+fn app() -> Harness<'static, TextureCraftApp> {
+ let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
+ let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
+ h.state_mut().ui.prefs.language = "en".into();
+ h.run_steps(4);
+
+ h
+}
+
+/// Write a `size` × `size` PNG (each size is a different file size, so a change is seen at once)
+fn png(dir: &Path, name: &str, size: u32) -> PathBuf {
+ let file = dir.join(name);
+ image::RgbaImage::from_pixel(size, size, image::Rgba([10, 200, 30, 255])).save(&file).unwrap();
+
+ file
+}
+
+fn import(h: &mut Harness<'_, TextureCraftApp>, file: &Path) {
+ h.state_mut().run("resource.import", json!({ "path": file.to_str().unwrap() })).unwrap();
+ h.run_steps(2);
+}
+
+fn press(h: &mut Harness<'_, TextureCraftApp>, key: Key) {
+ h.key_press(key);
+ h.run_steps(3);
+}
+
+/// Move the keyboard focus to button `label` and press Enter
+fn activate(h: &mut Harness<'_, TextureCraftApp>, label: &str) {
+ h.get_by_role_and_label(Role::Button, label).focus();
+ h.run_steps(2);
+ press(h, Key::Enter);
+}
+
+fn shows(h: &Harness<'_, TextureCraftApp>, text: &str) -> bool {
+ h.query_by_label(text).is_some()
+}
+
+fn width_of(h: &Harness<'_, TextureCraftApp>, name: &str) -> u32 {
+ h.state().session.images[name].width
+}
+
+#[test]
+fn the_window_opens_from_the_keyboard_and_updates_an_outdated_resource_as_one_undo_step() {
+ let dir = TempDir::new("resources-updater-update");
+ let (kept, changed) = (png(&dir, "kept.png", 4), png(&dir, "changed.png", 4));
+ let mut h = app();
+ import(&mut h, &kept);
+ import(&mut h, &changed);
+ png(&dir, "changed.png", 8);
+
+ activate(&mut h, "Resources Updater");
+
+ let rows = &h.state().ui.windows.resources_updater.as_ref().expect("the window is open").rows;
+ assert_eq!(rows[0].name, "changed.png", "outdated resources come first");
+ assert!(shows(&h, "Project : Test"));
+ assert!(shows(&h, "(2 resources, 1 outdated)"));
+ assert!(shows(&h, "Outdated"), "the status is written out, not only coloured");
+ assert!(h.get_by_role_and_label(Role::Button, "Update kept.png").accesskit_node().is_disabled(), "only outdated resources update");
+
+ let steps = h.state().session.history_labels().len();
+ activate(&mut h, "Update changed.png");
+
+ assert_eq!(width_of(&h, "changed.png"), 8, "the new file's pixels are in the project");
+ assert_eq!(h.state().session.history_labels().len(), steps + 1, "one undo step");
+ assert!(shows(&h, "(2 resources, 0 outdated)"));
+
+ // Undo brings the old pixels back, so the list shows the file as changed again
+ h.state_mut().run("edit.undo", json!({})).unwrap();
+ h.run_steps(3);
+
+ assert_eq!(width_of(&h, "changed.png"), 4);
+ assert!(shows(&h, "(2 resources, 1 outdated)"));
+
+ activate(&mut h, "Update All");
+ assert_eq!(width_of(&h, "changed.png"), 8);
+
+ press(&mut h, Key::Escape);
+ assert!(h.state().ui.windows.resources_updater.is_none(), "Escape closes the window");
+}
+
+#[test]
+fn select_new_resource_follows_the_chosen_file_and_the_name_filter_narrows_the_list() {
+ let dir = TempDir::new("resources-updater-relink");
+ let (first, second) = (png(&dir, "first.png", 4), png(&dir, "second.png", 4));
+ let other = png(&dir, "other.png", 16);
+ let mut h = app();
+ import(&mut h, &first);
+ import(&mut h, &second);
+ activate(&mut h, "Resources Updater");
+
+ h.state_mut().file_dialogs.set_override(Some(Box::new(move |_: &Request| Answer::Paths(vec![other.clone()]))));
+ activate(&mut h, "Select new resource first.png");
+ h.run_steps(3);
+
+ assert_eq!(width_of(&h, "first.png"), 16, "the resource keeps its name and takes the chosen file's pixels");
+ assert!(h.state().session.doc.project.resource_sources["first.png"].path.ends_with("other.png"));
+
+ h.get_by_role_and_label(Role::TextInput, "Name filter:").focus();
+ h.run_steps(2);
+ h.get_by_role_and_label(Role::TextInput, "Name filter:").type_text("SEC");
+ h.run_steps(3);
+
+ assert!(h.query_by_label("Update first.png").is_none(), "the filter hides other names");
+ assert!(h.query_by_label("Update second.png").is_some(), "names match ignoring case");
+}
+
+#[test]
+fn show_in_folder_shows_the_folder_of_the_resource_file() {
+ let dir = TempDir::new("resources-updater-folder");
+ let file = png(&dir, "bricks.png", 4);
+ let mut h = app();
+ import(&mut h, &file);
+ activate(&mut h, "Resources Updater");
+
+ activate(&mut h, "Show in folder bricks.png");
+
+ let shown = h.state().file_dialogs.shown_folders().to_vec();
+ assert_eq!(shown.len(), 1);
+ assert_eq!(shown[0].file_name(), dir.file_name(), "the file's own folder");
+}
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 7873145d..0cf55589 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -222,7 +222,7 @@ keeps its state in a throwaway file.
| `session.inspect` | | project, mesh, texture sets, layer stack, tool, camera, display, history |
| `ui.inspect` | | UI state, viewport rect, fps, bake progress (`baking`, 0..1), the running bake's stage (`bakeStatus`, e.g. "Baking Ambient Occlusion (2/4)") and live preview (`bakePreview`, see *Live bake preview*), toasts, `titleBar` (who draws the title bar this run: `app`, `integrated` on macOS, or `system`) |
| `ui.menu.list` | | the menu catalog: `{menu, submenu, label, id, shortcut, implemented, enabled, checked}` |
-| `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question; `file.exportMesh` opens the Mesh Export Options prompt, whose Export asks for the file; `ui.view.export` opens the right bar's Export panel). `{"id": "ui.layout.apply", "name": ""}` switches to a legacy named panel layout (still accessible through assigned shortcuts) (panels only; mode, zoom and wireframes stay) and errors when no layout has that name. `ui.layout.save` still saves the active mode; `ui.layout.save.painting`, `ui.layout.save.rendering` and `ui.layout.save.baking` ask where to save only that mode's panels and view arrangement as a JSON file (without preferences or recent projects); loading preserves the other modes, `ui.layout.load` asks for one to load ("Load UI Layout"); `ui.toolbar.docks` and `ui.toolbar.tools` show or hide the right bar and the painting tools; the disabled Snooze Autosave and Resources Updater buttons stay visible when Tools is off; `ui.view.renderer` toggles the Renderer Settings panel (Rendering Mode only). `{"id": "ui.layout.swap"}` swaps the 3D and 2D views of the split layout (F4) |
+| `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question; `file.exportMesh` opens the Mesh Export Options prompt, whose Export asks for the file; `ui.view.export` opens the right bar's Export panel). `{"id": "ui.layout.apply", "name": ""}` switches to a legacy named panel layout (still accessible through assigned shortcuts) (panels only; mode, zoom and wireframes stay) and errors when no layout has that name. `ui.layout.save` still saves the active mode; `ui.layout.save.painting`, `ui.layout.save.rendering` and `ui.layout.save.baking` ask where to save only that mode's panels and view arrangement as a JSON file (without preferences or recent projects); loading preserves the other modes, `ui.layout.load` asks for one to load ("Load UI Layout"); `ui.toolbar.docks` and `ui.toolbar.tools` show or hide the right bar and the painting tools; the disabled Snooze Autosave button and the Resources Updater button (enabled while a project is open) stay visible when Tools is off; `ui.view.renderer` toggles the Renderer Settings panel (Rendering Mode only). `{"id": "ui.layout.swap"}` swaps the 3D and 2D views of the split layout (F4) |
| `ui.menu.invoke` id `project.sample` | `{id}` | File > Open Sample Project opens a file picker for a `.tcraft` project. The direct `project.sample` engine command still creates the generated sample for automation. |
| `ui.menu.invoke` id `ui.saveAsTemplate` | `{id}` | File > More Save Options > Save As Template opens a save dialog in the user templates folder. The choice supplies the file path and template name to `project.template.save`. `ui.saveReduced` (Save and Reduce File Size) is listed as not implemented and not enabled |
| `ui.menu.invoke` ids `ui.help.releaseNotes`, `ui.help.showLog`, `ui.help.exportLog` | `{id}` | Help > Release Notes opens the releases page in the browser; Help > Show Log opens the current desktop run's rolling `log.txt` in the system text-file handler; Help > Export Log exports the session log with each entry’s recorded UTC time, severity and source (a save dialog on desktop with a `Log_TextureCraft____.txt` name, a download on the web) |
@@ -348,7 +348,8 @@ with `ui.inspect`, update that field and send the full `prefs` object to `ui.set
File › Save.
Through `command_run`, every `file.*` command but `file.close` and `file.removeUnused` (and
-`file.reimportMesh` without a `path`) is refused, and so is any command given a `path` or `dir`, at the top level or in
+`file.reimportMesh` without a `path`) is refused, and so are `resource.status`, `resource.update` and `resource.relink` (they read
+the files a project names) and any command given a `path` or `dir`, at the top level or in
a `files` entry (`resource.import`, `material.save`, `material.load`, `textureSet.meshMap.import`, …), in both modes: use the workspace tools below. `resource.text`
takes a font family, not a path: it reads only the system's font folders.
@@ -465,6 +466,23 @@ printf '%s\n' '{"id":1,"method":"command.run","params":{"id":"project.new","para
'{"id":2,"method":"render","params":{"width":512,"height":512}}' | texturecraft-cli serve
```
+## Resources Updater
+
+An image resource imported with `resource.import {path}` remembers that file (its absolute path and
+modification time, saved with the project). The shelf's Resources Updater window lists the project's
+image resources through these commands and checks them again when it opens, on Refresh, after every
+change and when the app gets the focus back; then a notice ("N resources changed on disk", with an
+Update button) appears when the set of outdated resources changed since the last notice.
+
+| Command | Params and result |
+|---|---|
+| `resource.status` | `{}` → `{resources: [{name, status, path?, error?}], total, outdated}`; `status` is `outdated` (the file's size or contents differ from the resource), `missing` (the file is gone or unreadable, `error` says why), `upToDate` or `noSource` (made in the app or imported without a path); outdated first, then by name. A file is read only when its size matches but its modification time does not |
+| `resource.update` | `{names?: [name]}` (default: every outdated resource) → `{updated, failed: [{name, error}]}`: reads the files again and replaces the resources' bytes and pixels under the same names, so every layer, mask and view using them recomposites; one undo step, none when nothing changed. A file that cannot be read fails alone; when none could be read the command is an error. Unknown names and resources without a file are refused |
+| `resource.relink` | `{name, path}` → `{name, path}`: the resource takes the image file's pixels (within the image import limits) and follows that file from then on; one undo step |
+
+These commands read host paths stored in the project, so MCP and `serve` refuse them through
+`command_run`; the desktop app's control channel and the trusted local CLI run them.
+
## PBR texture folders
`file.importPbrFolder` turns a folder, a `.zip` or a list of image files of PBR maps into one fill layer
diff --git a/docs/features.md b/docs/features.md
index 04702ee9..a3692d83 100644
--- a/docs/features.md
+++ b/docs/features.md
@@ -98,6 +98,13 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
and alpha images become the brush alpha. Filter by role or remove selected rows before importing.
Failed rows stay in the dialog for retry. Color LUT, post effects and asset-library import are
unavailable. The browser imports images straight from its file picker.
+- **Resources Updater:** the shelf button under the tools lists the project's image resources with
+ their files, outdated ones first. An imported image remembers its file; when that file changes on
+ disk, *Update* (or *Update All*) reads it again and every layer using it recomposites, as one undo
+ step. *Select new resource* points a resource at another file, *Show in folder* opens its folder,
+ and the list filters by status and name. When the app gets the focus back after files changed, a
+ notice offers *Update*. Desktop only; there is no Shaders tab, since TextureCraft has no shader
+ resources.
- **Your own library:** right-click a layer or folder, choose *Create smart material*, and it
appears under *My smart materials*, pixels and images included. *Create smart mask* in the same
menu saves just the layer's mask (all its effects, painted pixels and images); it appears under
From e016ba2f1034bf29119fffff96e5ed2b3552141a Mon Sep 17 00:00:00 2001
From: vangel76
Date: Wed, 25 Nov 2026 00:51:25 +0100
Subject: [PATCH 023/138] Bring the Settings window in line with the reference
(#823)
Defaults follow the reference: the system language, Show keyboard helper,
Show world axes and the baking options on, and GPU raytracing on and
checkable only with a GPU. Show world axes now hides the 3D view's axes.
The Iray, Appearance and Folders sections are gone, Temporary Files is
Files and holds the Data folder, Recent projects limit sits in Resources,
the CPU and RAM limits are sliders in steps of 1 with the core count
beside them, and the section hints are removed. The Local cache directory
is editable and defaults to the system's temporary folder. The shortcut
list adds the reference's manipulator rows after Export Textures, listed
as not available yet.
---
crates/ui-egui/src/control.rs | 6 +
crates/ui-egui/src/keymap.rs | 9 +-
crates/ui-egui/src/lib.rs | 23 ++-
crates/ui-egui/src/settings_window.rs | 211 +++++++++++----------
crates/ui-egui/src/state.rs | 24 ++-
crates/ui-egui/src/viewport.rs | 4 +-
crates/ui-egui/tests/it/settings_window.rs | 162 ++++++++++++----
crates/ui-egui/tests/it/shortcut_list.rs | 27 ++-
crates/ui-egui/tests/project_limits.rs | 4 +-
docs/ui-parity.md | 2 +-
10 files changed, 315 insertions(+), 157 deletions(-)
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 79050e12..ab03dc37 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -111,6 +111,12 @@ fn refresh_draft_preferences(draft: &mut Prefs, previous: &Prefs, current: &Pref
gpu_raytracing,
libraries,
background,
+ show_world_axes,
+ show_keyboard_helper,
+ only_selected_material_when_painting,
+ save_preprocessed_scene_files,
+ live_preview_baking,
+ local_cache_directory,
);
}
diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs
index ee29ac48..17f8acec 100644
--- a/crates/ui-egui/src/keymap.rs
+++ b/crates/ui-egui/src/keymap.rs
@@ -36,7 +36,14 @@ pub struct Binding {
///
/// They are not in [`bindings`], so no key runs them, but another item given their key is reported
/// as sharing it.
-pub static NOT_AVAILABLE_ACTIONS: [(&str, Binding); 2] = [
+pub static NOT_AVAILABLE_ACTIONS: [(&str, Binding); 9] = [
+ ("file.reimportMesh", Binding { id: "ui.manipulator.toggle", group: "Viewport", label: "Show/Hide manipulator", default: Some("Q") }),
+ ("file.reimportMesh", Binding { id: "ui.manipulator.grow", group: "Viewport", label: "Increase the manipulator size", default: None }),
+ ("file.reimportMesh", Binding { id: "ui.manipulator.shrink", group: "Viewport", label: "Decrease the manipulator size", default: Some("-") }),
+ ("file.reimportMesh", Binding { id: "ui.manipulator.space", group: "Viewport", label: "Cycle through manipulation spaces", default: Some("T") }),
+ ("file.reimportMesh", Binding { id: "ui.warpEdit", group: "Viewport", label: "Toggle warp edition mode", default: Some("Shift+V") }),
+ ("file.reimportMesh", Binding { id: "ui.manipulator.translate", group: "Viewport", label: "Translate tool", default: Some("W") }),
+ ("file.reimportMesh", Binding { id: "ui.manipulator.rotate", group: "Viewport", label: "Rotate tool", default: Some("E") }),
("file.reimportMesh", Binding { id: "ui.pauseEngine", group: "Commands", label: "Pause Engine Computation", default: Some("Shift+Esc") }),
("viewport.frame", Binding { id: "ui.toggleAnimation", group: "Viewport", label: "Toggle animation", default: Some("Space") }),
];
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 47259f2b..f6b25a0f 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -342,11 +342,8 @@ pub(crate) fn start_ui(saved: Option, session: &mut Session) -> UiState
ui.tool_settings.apply(&mut session.tool);
ui
}
- None => {
- let mut ui = UiState::default();
- ui.prefs.language = i18n::SYSTEM_LANGUAGE.into();
- ui
- }
+ // The default language follows the operating system
+ None => UiState::default(),
}
}
@@ -1228,13 +1225,25 @@ pub fn data_folder(pref: &str) -> std::path::PathBuf {
std::path::Path::new(&home).join("Documents").join("TextureCraft")
}
-/// The data folder in use (Settings › Folders › Data folder).
+/// The folder for a `Prefs::local_cache_directory` value: that path when it is absolute,
+/// otherwise the system's temporary folder.
+#[cfg(not(target_arch = "wasm32"))]
+pub fn local_cache_folder(pref: &str) -> std::path::PathBuf {
+ let chosen = std::path::Path::new(pref.trim());
+ if chosen.is_absolute() {
+ return chosen.to_path_buf();
+ }
+
+ std::env::temp_dir()
+}
+
+/// The data folder in use (Settings › Files › Data folder).
#[cfg(not(target_arch = "wasm32"))]
pub fn data_dir() -> std::path::PathBuf {
DATA_FOLDER.get().cloned().unwrap_or_else(|| data_folder(""))
}
-/// `` in the data folder in use (Settings › Folders › Data folder).
+/// `` in the data folder in use (Settings › Files › Data folder).
#[cfg(not(target_arch = "wasm32"))]
pub fn user_dir(sub: &str) -> std::path::PathBuf {
data_dir().join(sub)
diff --git a/crates/ui-egui/src/settings_window.rs b/crates/ui-egui/src/settings_window.rs
index 8fda17b0..7da312bc 100644
--- a/crates/ui-egui/src/settings_window.rs
+++ b/crates/ui-egui/src/settings_window.rs
@@ -9,7 +9,7 @@ use crate::TextureCraftApp;
use crate::file_dialogs::{Bound, FileDialog};
use crate::i18n::{LANGUAGES, SYSTEM_LANGUAGE, n_, tr, trf};
use crate::state::{CAMERA_SPEED_RANGE, LibraryLocation, MAX_RECENT_PROJECTS, Prefs};
-use crate::theme::{Accent, Brightness, Tokens, caption};
+use crate::theme::{Tokens, caption};
use crate::unavailable::NOT_AVAILABLE;
use crate::widgets::icon_button;
@@ -274,9 +274,17 @@ fn section(ui: &mut Ui, title: &str) {
ui.add_space(2.0);
}
-/// A disabled check box in the right column of a row labelled `label`.
-fn disabled_check(ui: &mut Ui, label: egui::Id, mut checked: bool) {
- not_available(ui.add_enabled(false, egui::Checkbox::without_text(&mut checked)).labelled_by(label));
+/// A check box in the right column of a row labelled `label`.
+fn check(ui: &mut Ui, label: egui::Id, checked: &mut bool) {
+ ui.add(egui::Checkbox::without_text(checked)).labelled_by(label);
+}
+
+/// A check box with its text.
+fn text_check(ui: &mut Ui, text: &str, checked: &mut bool) {
+ ui.horizontal(|ui| {
+ ui.add_space(12.0);
+ ui.checkbox(checked, tr(text));
+ });
}
/// A disabled check box with its text.
@@ -306,6 +314,35 @@ pub fn gpu_note_shown(adapter: Option<&str>) -> bool {
adapter.is_none() || cfg!(target_arch = "wasm32")
}
+/// The Enable GPU raytracing check box for the hardware and the stored choice: whether it can be
+/// changed and whether it shows ticked. Without a GPU to trace on it is off and disabled; the
+/// stored choice is kept for a machine that has one.
+pub fn gpu_raytracing_check(adapter: Option<&str>, stored: bool) -> (bool, bool) {
+ let supported = !gpu_note_shown(adapter);
+ (supported, supported && stored)
+}
+
+/// The Max CPU threads slider's position for a stored `work_threads`: 0 (every thread) is the
+/// slider's end, the core count.
+#[cfg(not(target_arch = "wasm32"))]
+fn work_threads_shown(work_threads: u32, cores: u32) -> u32 {
+ if work_threads == 0 { cores } else { work_threads.min(cores).max(1) }
+}
+
+/// The stored `work_threads` for the slider at `threads`: its end keeps 0, so every thread works
+/// on any machine.
+#[cfg(not(target_arch = "wasm32"))]
+fn work_threads_stored(threads: u32, cores: u32) -> u32 {
+ if threads >= cores { 0 } else { threads }
+}
+
+/// The note right of a core slider: how many cores this machine has.
+#[cfg(not(target_arch = "wasm32"))]
+fn cores_in_total(ui: &mut Ui, cores: u32) {
+ let tk = Tokens::get(ui.ctx());
+ ui.label(RichText::new(trf("{count} cores in total", &[("count", &cores)])).color(tk.text_dim));
+}
+
/// The General page.
fn general(
ui: &mut Ui,
@@ -339,8 +376,8 @@ fn general(
.response
.labelled_by(label);
});
- row(ui, tr("Show keyboard helper"), |ui, label| disabled_check(ui, label, true));
- row(ui, tr("Show world axes"), |ui, label| disabled_check(ui, label, true));
+ row(ui, tr("Show keyboard helper"), |ui, label| check(ui, label, &mut p.show_keyboard_helper));
+ row(ui, tr("Show world axes"), |ui, label| check(ui, label, &mut p.show_world_axes));
row(ui, tr("Background color"), |ui, _| {
for (index, side, name) in [(0, "top", "Top background"), (1, "bottom", "Bottom background")] {
let id = format!("settings_background_{side}");
@@ -352,20 +389,17 @@ fn general(
ui.add_space(10.0);
}
});
- row(ui, tr("Only display the selected material when painting"), |ui, label| disabled_check(ui, label, false));
+ row(ui, tr("Only display the selected material when painting"), |ui, label| check(ui, label, &mut p.only_selected_material_when_painting));
row(ui, tr("Viewport Scaling"), |ui, label| {
- ui.add_enabled_ui(false, |ui| {
- not_available(
- egui::ComboBox::from_id_salt("settings_viewport_scaling").width(CONTROL_WIDTH).selected_text(tr("Auto")).show_ui(ui, |_| {}).response,
- )
+ // Auto is the one scaling the views have
+ egui::ComboBox::from_id_salt("settings_viewport_scaling")
+ .width(CONTROL_WIDTH)
+ .selected_text(tr("Auto"))
+ .show_ui(ui, |ui| {
+ ui.add(egui::Button::selectable(true, tr("Auto")));
+ })
+ .response
.labelled_by(label);
- });
- });
-
- row(ui, tr("Recent projects limit"), |ui, label| {
- ui.add(egui::DragValue::new(&mut p.recent_projects_limit).range(0..=MAX_RECENT_PROJECTS))
- .labelled_by(label)
- .on_hover_text(tr("Number of recent projects to remember. 0 disables recent-project history."));
});
section(ui, n_("LAYER STACK OPTIONS"));
@@ -397,12 +431,17 @@ fn general(
}
section(ui, n_("BAKING OPTIONS"));
- disabled_text_check(ui, n_("Save preprocessed scene files"), true);
- disabled_text_check(ui, n_("Enable live preview baking process"), true);
+ text_check(ui, n_("Save preprocessed scene files"), &mut p.save_preprocessed_scene_files);
+ text_check(ui, n_("Enable live preview baking process"), &mut p.live_preview_baking);
+ let (gpu_raytracing_enabled, mut gpu_raytracing_ticked) = gpu_raytracing_check(gpu, p.gpu_raytracing);
ui.horizontal(|ui| {
ui.add_space(12.0);
- ui.checkbox(&mut p.gpu_raytracing, tr("Enable GPU raytracing"))
+ let gpu_raytracing = ui
+ .add_enabled(gpu_raytracing_enabled, egui::Checkbox::new(&mut gpu_raytracing_ticked, tr("Enable GPU raytracing")))
.on_hover_text(tr("Bakes cast their rays on the graphics card when one is available. Off, they run on the CPU."));
+ if gpu_raytracing.changed() {
+ p.gpu_raytracing = gpu_raytracing_ticked;
+ }
});
if gpu_note_shown(gpu) {
ui.horizontal(|ui| {
@@ -413,6 +452,17 @@ fn general(
section(ui, n_("PREVIEW OPTIONS"));
row(ui, tr("Local cache directory"), |ui, label| {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ let default = crate::local_cache_folder("").display().to_string();
+ ui.add(egui::TextEdit::singleline(&mut p.local_cache_directory).hint_text(default).desired_width(CONTROL_WIDTH - 24.0)).labelled_by(label);
+ if ui.add(egui::Button::new("R").frame(false)).on_hover_text(tr("Reset to the default folder")).clicked() {
+ p.local_cache_directory.clear();
+ }
+ }
+
+ // The browser has no folders
+ #[cfg(target_arch = "wasm32")]
ui.add_enabled_ui(false, |ui| {
let mut path = String::new();
not_available(ui.add(egui::TextEdit::singleline(&mut path).desired_width(CONTROL_WIDTH - 24.0))).labelled_by(label);
@@ -431,7 +481,7 @@ fn general(
not_available(ui.add_enabled(false, egui::Button::new(text).min_size(vec2(CONTROL_WIDTH, 40.0))));
});
- section(ui, n_("TEMPORARY FILES"));
+ section(ui, n_("FILES"));
row(ui, tr("Cache directory"), |ui, label| {
#[cfg(not(target_arch = "wasm32"))]
let mut path = std::env::temp_dir().display().to_string();
@@ -442,57 +492,19 @@ fn general(
not_available(ui.add(egui::Button::new("R").frame(false)));
});
});
+ #[cfg(not(target_arch = "wasm32"))]
+ row(ui, tr("Data folder"), |ui, label| {
+ let default = crate::data_folder("").display().to_string();
+ ui.add(egui::TextEdit::singleline(&mut p.data_folder).hint_text(default).desired_width(CONTROL_WIDTH - 30.0)).labelled_by(label);
+ if ui.button("...").on_hover_text(tr("Choose the data folder")).clicked() {
+ *pick = Some(SettingsFolder::DataFolder);
+ }
+ });
section(ui, n_("SPARSE VIRTUAL TEXTURE"));
disabled_text_check(ui, n_("Hardware support acceleration"), true);
- section(ui, n_("IRAY HARDWARE"));
- disabled_text_check(ui, gpu.unwrap_or(n_("no GPU")), true);
- disabled_text_check(ui, n_("CPU"), false);
-
// TextureCraft's own settings, after the reference sections
- section(ui, n_("APPEARANCE"));
- row(ui, tr("Interface scale"), |ui, label| {
- ui.add(egui::Slider::new(&mut p.ui_scale, 0.75..=2.0).fixed_decimals(2)).labelled_by(label);
- });
- row(ui, tr("Brightness"), |ui, label| {
- egui::ComboBox::from_id_salt("settings_brightness")
- .width(140.0)
- .selected_text(tr(p.brightness.label()))
- .show_ui(ui, |ui| {
- for b in Brightness::ALL {
- ui.selectable_value(&mut p.brightness, b, tr(b.label()));
- }
- })
- .response
- .labelled_by(label);
- });
- row(ui, tr("Accent color"), |ui, _| {
- for a in Accent::ALL {
- let (rect, resp) = ui.allocate_exact_size(vec2(20.0, 20.0), egui::Sense::click());
- resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, p.accent == a, tr(a.label())));
- let ring = if p.accent == a {
- tk.text_strong
- } else if resp.hovered() {
- tk.text_dim
- } else {
- Color32::TRANSPARENT
- };
- ui.painter().circle(rect.center(), 6.5, a.colors(tk.dark).0, egui::Stroke::NONE);
- ui.painter().circle_stroke(rect.center(), 9.0, egui::Stroke::new(1.5, ring));
- if resp.on_hover_text(tr(a.label())).clicked() {
- p.accent = a;
- }
- }
- });
- #[cfg(not(target_arch = "wasm32"))]
- {
- row(ui, tr("Title bar"), |ui, _| {
- ui.checkbox(&mut p.system_title_bar, tr("System title bar (applies on restart)"))
- .on_hover_text(tr("Use the operating system's window frame and buttons instead of TextureCraft's own title bar"));
- });
- }
-
section(ui, n_("VIEWPORT"));
row(ui, tr("Texture resolution"), |ui, _| {
ui.horizontal(|ui| {
@@ -510,15 +522,22 @@ fn general(
#[cfg(not(target_arch = "wasm32"))]
{
row(ui, tr("Max CPU threads for work"), |ui, label| {
- ui.add(egui::DragValue::new(&mut p.work_threads).range(0..=available_cores))
+ let mut threads = work_threads_shown(p.work_threads, available_cores);
+ let slider = ui
+ .add(egui::Slider::new(&mut threads, 1..=available_cores.max(1)).step_by(1.0))
.labelled_by(label)
- .on_hover_text(tr("Threads that paint, bake and export. 0 uses every CPU thread. Applies on restart."));
+ .on_hover_text(tr("Threads that paint, bake and export. Applies on restart."));
+ if slider.changed() {
+ p.work_threads = work_threads_stored(threads, available_cores);
+ }
+ cores_in_total(ui, available_cores);
});
row(ui, tr("Cores kept for the UI"), |ui, label| {
- ui.add(egui::DragValue::new(&mut p.reserved_cores).range(0..=available_cores)).labelled_by(label);
+ ui.add(egui::Slider::new(&mut p.reserved_cores, 0..=available_cores).step_by(1.0)).labelled_by(label);
+ cores_in_total(ui, available_cores);
});
row(ui, tr("Max RAM while saving"), |ui, label| {
- ui.add(egui::DragValue::new(&mut p.save_ram_percent).range(1..=100).suffix(" %")).labelled_by(label);
+ ui.add(egui::Slider::new(&mut p.save_ram_percent, 0..=100).step_by(1.0).suffix(" %")).labelled_by(label);
let budget_bytes = texturecraft_engine::formats::save_ram_budget(available_ram_bytes, p.save_ram_percent);
ui.label(format!("≈ {:.2} GiB", budget_bytes as f64 / (1_u64 << 30) as f64));
});
@@ -528,10 +547,11 @@ fn general(
.labelled_by(label)
.on_hover_text(tr("Maximum decompressed project data. Increase this limit to open larger projects."));
});
- #[cfg(not(target_arch = "wasm32"))]
- {
- note(ui, tr("Saving uses the other cores and at most this share of the free RAM. At least one core always works."));
- }
+ row(ui, tr("Recent projects limit"), |ui, label| {
+ ui.add(egui::DragValue::new(&mut p.recent_projects_limit).range(0..=MAX_RECENT_PROJECTS))
+ .labelled_by(label)
+ .on_hover_text(tr("Number of recent projects to remember. 0 disables recent-project history."));
+ });
#[cfg(not(target_arch = "wasm32"))]
{
@@ -539,38 +559,9 @@ fn general(
row(ui, tr("Autosave every"), |ui, label| {
ui.add(egui::DragValue::new(&mut p.autosave_minutes).range(0..=120).suffix(format!(" {}", tr("min")))).labelled_by(label);
});
- note(ui, &trf("0 turns autosave off. Copies go to {folder}", &[("folder", &crate::user_dir("autosave").display())]));
-
- section(ui, n_("FOLDERS"));
- row(ui, tr("Data folder"), |ui, label| {
- let default = crate::data_folder("").display().to_string();
- ui.add(egui::TextEdit::singleline(&mut p.data_folder).hint_text(default).desired_width(CONTROL_WIDTH - 30.0)).labelled_by(label);
- if ui.button("...").on_hover_text(tr("Choose the data folder")).clicked() {
- *pick = Some(SettingsFolder::DataFolder);
- }
- });
- for (label, dir) in [(tr("Smart materials"), crate::library_dir()), (tr("UI layouts"), crate::user_dir("layouts"))] {
- row(ui, label, |ui, _| ui.label(RichText::new(dir.display().to_string()).small().color(tk.text_dim)));
- }
- note(
- ui,
- tr(
- "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.",
- ),
- );
}
}
-/// A small dim note under a section's rows.
-#[cfg(not(target_arch = "wasm32"))]
-fn note(ui: &mut Ui, text: &str) {
- let tk = Tokens::get(ui.ctx());
- ui.horizontal(|ui| {
- ui.add_space(12.0);
- ui.add(egui::Label::new(RichText::new(text).small().color(tk.text_dim)).wrap());
- });
-}
-
/// The built-in library locations as (name, path): the user's assets in the data folder, the
/// assets built into TextureCraft, and the font folders text alphas read.
pub fn built_in_locations() -> Vec<(String, String)> {
@@ -797,6 +788,16 @@ mod tests {
assert_eq!(app.next_autosave, 70.0, "an unchanged interval keeps the deadline");
}
+ #[test]
+ fn max_cpu_threads_shows_every_thread_at_the_slider_end_and_keeps_it_as_every_thread() {
+ let cores = 8;
+
+ assert_eq!(work_threads_shown(0, cores), cores, "every thread is the slider's end");
+ assert_eq!(work_threads_shown(64, cores), cores, "a larger machine's choice stays inside this one");
+ assert_eq!(work_threads_stored(cores, cores), 0, "the end follows any machine's core count");
+ assert_eq!(work_threads_stored(work_threads_shown(3, cores), cores), 3);
+ }
+
#[test]
fn a_folder_answer_cannot_edit_a_reopened_settings_window() {
let session = texturecraft_engine::Session::closed().unwrap();
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index 0c767e1b..9d97f54d 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -187,6 +187,22 @@ pub struct Prefs {
/// The plain background of the 3D and 2D views at Environment Opacity 0 (Settings > General >
/// Background color): the color at the top and at the bottom, linear RGB.
pub background: [[f32; 3]; 2],
+ /// The 3D view draws the X, Y and Z axes in its corner.
+ pub show_world_axes: bool,
+ /// Settings > General > Show keyboard helper. Stored only: TextureCraft has no keyboard helper yet.
+ pub show_keyboard_helper: bool,
+ /// Settings > General > Only display the selected material when painting. Stored only: the
+ /// views always show every texture set.
+ pub only_selected_material_when_painting: bool,
+ /// Settings > Baking options > Save preprocessed scene files. Stored only: bakes keep no
+ /// preprocessed scene files.
+ pub save_preprocessed_scene_files: bool,
+ /// Settings > Baking options > Enable live preview baking process. Stored only: the live bake
+ /// preview always runs.
+ pub live_preview_baking: bool,
+ /// Settings > Preview options > Local cache directory (desktop). Empty or relative: the
+ /// system's temporary folder. Stored only: TextureCraft writes no preview cache yet.
+ pub local_cache_directory: String,
}
/// The orbit speed the built-in navigation runs at.
@@ -200,7 +216,7 @@ impl Default for Prefs {
ui_scale: 1.0,
autosave_minutes: 10,
recent_projects_limit: 10,
- language: "en".into(),
+ language: crate::i18n::SYSTEM_LANGUAGE.into(),
viewport_texture: 0,
brightness: crate::theme::Brightness::default(),
accent: crate::theme::Accent::default(),
@@ -218,6 +234,12 @@ impl Default for Prefs {
gpu_raytracing: true,
libraries: Vec::new(),
background: texturecraft_render::DEFAULT_BACKGROUND,
+ show_world_axes: true,
+ show_keyboard_helper: true,
+ only_selected_material_when_painting: false,
+ save_preprocessed_scene_files: true,
+ live_preview_baking: true,
+ local_cache_directory: String::new(),
}
}
}
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index 3c5a3d7e..7a83ccf6 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -1101,7 +1101,9 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
solo_notice(app, ui, rect);
view_header(app, ui, rect, "v3d");
mask_view_badge(app, ui, rect);
- axis_gizmo(ui, rect, app, None);
+ if app.ui.prefs.show_world_axes {
+ axis_gizmo(ui, rect, app, None);
+ }
crate::nav_buttons::show(app, ui, rect, crate::nav_buttons::NavView::Scene);
}
diff --git a/crates/ui-egui/tests/it/settings_window.rs b/crates/ui-egui/tests/it/settings_window.rs
index 4e8508b1..7ca014c9 100644
--- a/crates/ui-egui/tests/it/settings_window.rs
+++ b/crates/ui-egui/tests/it/settings_window.rs
@@ -4,8 +4,10 @@ use egui::{Event, Key, Modifiers, Role};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use texturecraft_engine::Session;
-use texturecraft_ui_egui::settings_window::{DEFAULT_LIBRARY_NOTE, GPU_RAYTRACING_UNAVAILABLE, PROJECT_OPEN_NOTE, SHORTCUT_ERRORS, SettingsPage};
-use texturecraft_ui_egui::state::{LibraryLocation, UiState};
+use texturecraft_ui_egui::settings_window::{
+ DEFAULT_LIBRARY_NOTE, GPU_RAYTRACING_UNAVAILABLE, PROJECT_OPEN_NOTE, SHORTCUT_ERRORS, SettingsPage, gpu_raytracing_check,
+};
+use texturecraft_ui_egui::state::{LibraryLocation, Prefs, UiState};
use texturecraft_ui_egui::unavailable::NOT_AVAILABLE;
use texturecraft_ui_egui::{TextureCraftApp, menus};
@@ -84,47 +86,126 @@ fn the_left_column_switches_between_the_three_pages() {
fn the_general_page_starts_at_the_reference_defaults() {
let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap());
open_settings(&mut h);
- h.state_mut().ui.windows.settings_draft.as_mut().unwrap().prefs.language = texturecraft_ui_egui::i18n::SYSTEM_LANGUAGE.into();
+
+ // A reset puts the defaults in the window; the app itself keeps English for the exact-text checks
+ h.state_mut().ui.windows.settings_draft.as_mut().unwrap().prefs = Prefs::default();
h.run_steps(3);
+
assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Language").value().as_deref(), Some("Default (System Language)"));
- assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Viewport Scaling").value().as_deref(), Some("Auto"));
+ let scaling = h.get_by_role_and_label(Role::ComboBox, "Viewport Scaling");
+ assert_eq!(scaling.value().as_deref(), Some("Auto"));
+ assert!(!scaling.accesskit_node().is_disabled(), "Viewport Scaling can be opened");
assert_eq!(h.get_by_role_and_label(Role::SpinButton, "Local cache budget (in MB)").accesskit_node().numeric_value(), Some(4000.0));
- for label in [
- "Show keyboard helper",
- "Show world axes",
- "Use simplified thumbnails (improves performance)",
- "Save preprocessed scene files",
- "Enable live preview baking process",
- "Enable GPU raytracing",
- "Hardware support acceleration",
- ] {
+ for label in ["Show keyboard helper", "Show world axes", "Save preprocessed scene files", "Enable live preview baking process"] {
+ assert!(toggled(&h, label), "{label} is ticked");
+ assert!(!h.get_by_label(label).accesskit_node().is_disabled(), "{label} can be changed");
+ }
+ for label in ["Use simplified thumbnails (improves performance)", "Hardware support acceleration"] {
assert!(toggled(&h, label), "{label} is ticked");
}
- for label in ["Only display the selected material when painting", "CPU"] {
- assert!(!toggled(&h, label), "{label} is not ticked");
- }
+ let only_selected = "Only display the selected material when painting";
+ assert!(!toggled(&h, only_selected) && !h.get_by_label(only_selected).accesskit_node().is_disabled());
assert!(h.query_all_by_label("Inverse direction").all(|node| node.accesskit_node().toggled() == Some(egui::accesskit::Toggled::False)));
- let prefs = texturecraft_ui_egui::state::Prefs::default();
+ let local_cache = h.get_by_role_and_label(Role::TextInput, "Local cache directory");
+ assert!(!local_cache.accesskit_node().is_disabled(), "the local cache directory can be edited");
+ assert_eq!(texturecraft_ui_egui::local_cache_folder(&Prefs::default().local_cache_directory), std::env::temp_dir());
+
+ let prefs = Prefs::default();
+ assert_eq!(prefs.language, texturecraft_ui_egui::i18n::SYSTEM_LANGUAGE, "a reset follows the system language");
assert_eq!((prefs.rotation_speed, prefs.zoom_speed, prefs.wheel_speed), (2.0, 1.0, 1.0));
}
+#[test]
+fn the_general_page_keeps_the_reference_sections_and_moves_data_folder_and_recent_projects() {
+ let mut h = harness(Session::closed().unwrap());
+ open_settings(&mut h);
+
+ for gone in ["TEMPORARY FILES", "IRAY HARDWARE", "APPEARANCE", "FOLDERS", "PRIVACY", "Interface scale", "Accent color"] {
+ assert!(h.query_by_label(gone).is_none(), "{gone} is not on the page");
+ }
+ for hint in ["Saving uses the other cores", "0 turns autosave off", "A new folder applies on restart"] {
+ assert!(h.query_by_label_contains(hint).is_none(), "the hint \"{hint}\" is gone");
+ }
+
+ let top = |h: &Harness<'_, TextureCraftApp>, label: &str| h.get_by_label(label).rect().top();
+ let data_folder = h.get_by_role_and_label(Role::TextInput, "Data folder").rect().top();
+ assert!(top(&h, "FILES") < data_folder && data_folder < top(&h, "SPARSE VIRTUAL TEXTURE"), "Data folder is in Files");
+ let recent = h.get_by_role_and_label(Role::SpinButton, "Recent projects limit").rect().top();
+ assert!(top(&h, "RESOURCES") < recent && recent < top(&h, "AUTOSAVE"), "Recent projects limit is in Resources");
+ assert!(top(&h, "INTERFACE OPTIONS") < top(&h, "RESOURCES"));
+}
+
+#[test]
+fn the_resource_sliders_step_by_one_and_follow_the_arrow_keys() {
+ let mut h = harness(Session::closed().unwrap());
+ open_settings(&mut h);
+
+ let threads = h.get_by_role_and_label(Role::Slider, "Max CPU threads for work").accesskit_node();
+ let cores = threads.max_numeric_value().unwrap();
+ assert_eq!(threads.numeric_value(), Some(cores), "every thread works by default");
+ assert_eq!(threads.min_numeric_value(), Some(1.0));
+ let reserved = h.get_by_role_and_label(Role::Slider, "Cores kept for the UI").accesskit_node();
+ assert_eq!((reserved.min_numeric_value(), reserved.max_numeric_value()), (Some(0.0), Some(cores)));
+ let ram = h.get_by_role_and_label(Role::Slider, "Max RAM while saving").accesskit_node();
+ assert_eq!((ram.min_numeric_value(), ram.max_numeric_value()), (Some(0.0), Some(100.0)));
+ for label in ["Max CPU threads for work", "Cores kept for the UI", "Max RAM while saving"] {
+ assert_eq!(h.get_by_role_and_label(Role::Slider, label).accesskit_node().numeric_value_step(), Some(1.0), "{label} moves in steps of 1");
+ }
+ assert_eq!(h.query_all_by_label(&format!("{cores} cores in total")).count(), 2, "both core sliders name the total");
+
+ let ram_percent = |h: &Harness<'_, TextureCraftApp>| h.state().ui.windows.settings_draft.as_ref().unwrap().prefs.save_ram_percent;
+ let before = ram_percent(&h);
+ h.get_by_role_and_label(Role::Slider, "Max RAM while saving").focus();
+ h.run_steps(2);
+ press_key(&mut h, Key::ArrowRight);
+ assert_eq!(ram_percent(&h), before + 1, "the right arrow adds one percent");
+ press_key(&mut h, Key::ArrowLeft);
+ press_key(&mut h, Key::ArrowLeft);
+ assert_eq!(ram_percent(&h), before - 1, "the left arrow takes one percent");
+}
+
+#[test]
+fn the_enabled_interface_options_answer_the_keyboard() {
+ let mut h = harness(Session::closed().unwrap());
+ open_settings(&mut h);
+ let draft = |h: &Harness<'_, TextureCraftApp>| h.state().ui.windows.settings_draft.as_ref().unwrap().prefs.clone();
+ let before = draft(&h);
+
+ for label in ["Show keyboard helper", "Show world axes", "Only display the selected material when painting"] {
+ h.get_by_label(label).focus();
+ h.run_steps(2);
+ press_key(&mut h, Key::Space);
+ }
+
+ let after = draft(&h);
+ assert_ne!(after.show_keyboard_helper, before.show_keyboard_helper);
+ assert_ne!(after.show_world_axes, before.show_world_axes);
+ assert_ne!(after.only_selected_material_when_painting, before.only_selected_material_when_painting);
+}
+
+#[test]
+fn the_local_cache_directory_takes_a_folder_and_r_goes_back_to_the_default() {
+ let mut h = harness(Session::closed().unwrap());
+ open_settings(&mut h);
+ let folder = std::env::temp_dir().join("tc-settings-local-cache").display().to_string();
+ let stored = |h: &Harness<'_, TextureCraftApp>| h.state().ui.windows.settings_draft.as_ref().unwrap().prefs.local_cache_directory.clone();
+
+ type_into(&mut h, "Local cache directory", &folder);
+ assert_eq!(stored(&h), folder);
+
+ h.query_all_by_label("R").find(|node| !node.accesskit_node().is_disabled()).unwrap().click();
+ h.run_steps(3);
+ assert!(stored(&h).is_empty(), "R goes back to the default folder");
+}
+
#[test]
fn a_control_the_app_lacks_is_disabled_and_says_so_on_hover() {
let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap());
h.ctx.all_styles_mut(|style| style.interaction.tooltip_delay = 0.0);
open_settings(&mut h);
let away = h.get_by_role_and_label(Role::Tab, "Libraries").rect().center();
- for label in [
- "Show keyboard helper",
- "Show world axes",
- "Only display the selected material when painting",
- "Use simplified thumbnails (improves performance)",
- "Save preprocessed scene files",
- "Enable live preview baking process",
- "Hardware support acceleration",
- "CPU",
- ] {
+ for label in ["Use simplified thumbnails (improves performance)", "Hardware support acceleration"] {
h.hover_at(away);
h.run_steps(3);
assert!(h.query_by_label(NOT_AVAILABLE).is_none(), "no hint before hovering {label}");
@@ -139,7 +220,6 @@ fn a_control_the_app_lacks_is_disabled_and_says_so_on_hover() {
for step in ["−", "+"] {
assert!(h.query_all_by_label(step).any(|node| node.accesskit_node().is_disabled()), "the cache budget's {step} is disabled");
}
- assert!(!h.get_by_label("Enable GPU raytracing").accesskit_node().is_disabled(), "GPU raytracing switches bakes to the CPU");
for label in ["Rotation speed", "Zoom speed", "Wheel speed"] {
assert!(h.query_by_label(label).is_some(), "{label} is shown");
}
@@ -151,7 +231,7 @@ fn cancel_drops_the_changes_and_ok_applies_and_keeps_them() {
let before = h.state().ui.prefs.clone();
open_settings(&mut h);
h.get_by_role_and_label(Role::SpinButton, "Autosave every").set_value_accesskit(25.0);
- click(&mut h, "Enable GPU raytracing");
+ click(&mut h, "Show world axes");
h.run_steps(2);
assert_eq!(h.state().ui.prefs, before, "edits wait for OK");
click(&mut h, "Cancel");
@@ -165,20 +245,20 @@ fn cancel_drops_the_changes_and_ok_applies_and_keeps_them() {
"a new window starts from the settings in use"
);
h.get_by_role_and_label(Role::SpinButton, "Autosave every").set_value_accesskit(25.0);
- h.get_by_role_and_label(Role::SpinButton, "Max CPU threads for work").set_value_accesskit(1.0);
+ h.get_by_role_and_label(Role::Slider, "Max CPU threads for work").set_value_accesskit(1.0);
h.get_by_role_and_label(Role::SpinButton, "Max project size on open").set_value_accesskit(12.0);
h.run_steps(2);
h.query_all_by_label("Inverse direction").next().unwrap().scroll_to_me();
h.run_steps(3);
h.query_all_by_label("Inverse direction").next().unwrap().click();
h.run_steps(2);
- click(&mut h, "Enable GPU raytracing");
+ click(&mut h, "Show world axes");
click(&mut h, "OK");
let prefs = h.state().ui.prefs.clone();
assert!(!h.state().ui.windows.settings, "OK closes the window");
assert_eq!((prefs.autosave_minutes, prefs.work_threads, prefs.project_open_limit_gib), (25, 1, 12));
- assert!(prefs.zoom_inverse && !prefs.wheel_inverse && !prefs.gpu_raytracing);
+ assert!(prefs.zoom_inverse && !prefs.wheel_inverse && !prefs.show_world_axes);
assert!(prefs.drag_zoom_scale() < 0.0, "inverted zoom runs the other way");
let mut storage = MemoryStorage::default();
@@ -434,16 +514,22 @@ fn the_libraries_page_hides_the_add_row_with_a_project_open_and_explains_the_def
}
#[test]
-fn the_baking_options_say_when_there_is_no_gpu_to_trace_on() {
- // The condition, with and without an adapter (the harness's own adapter is not under test)
+fn gpu_raytracing_is_on_and_checkable_with_a_gpu_and_off_and_disabled_without() {
+ let with_gpu = !cfg!(target_arch = "wasm32");
+ assert_eq!(gpu_raytracing_check(Some("Some GPU"), true), (with_gpu, with_gpu), "a GPU keeps it on and checkable");
+ assert_eq!(gpu_raytracing_check(Some("Some GPU"), false), (with_gpu, false), "a GPU shows the stored choice");
+ assert_eq!(gpu_raytracing_check(None, true), (false, false), "without a GPU it is off and disabled");
assert!(texturecraft_ui_egui::settings_window::gpu_note_shown(None));
- assert_eq!(texturecraft_ui_egui::settings_window::gpu_note_shown(Some("Some GPU")), cfg!(target_arch = "wasm32"));
- // The page shows the note exactly when the harness has no adapter (the IRAY HARDWARE row says "no GPU")
+ // The page follows the harness's own adapter, whichever it has
let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap());
open_settings(&mut h);
- let no_gpu = h.query_by_label("no GPU").is_some();
- assert_eq!(h.query_by_label(GPU_RAYTRACING_UNAVAILABLE).is_some(), no_gpu, "the note shows with no GPU and only then");
+ let supported = h.state().render_state.is_some() && with_gpu;
+ let check = h.get_by_label("Enable GPU raytracing");
+ assert_eq!(!check.accesskit_node().is_disabled(), supported, "it can be changed exactly when there is a GPU");
+ assert_eq!(toggled(&h, "Enable GPU raytracing"), supported, "it is on exactly when there is a GPU");
+ assert_eq!(h.query_by_label(GPU_RAYTRACING_UNAVAILABLE).is_some(), !supported, "the note shows with no GPU and only then");
+ assert!(h.state().ui.prefs.gpu_raytracing, "the stored choice stays for a machine with a GPU");
}
#[test]
diff --git a/crates/ui-egui/tests/it/shortcut_list.rs b/crates/ui-egui/tests/it/shortcut_list.rs
index c603cbde..0be5b044 100644
--- a/crates/ui-egui/tests/it/shortcut_list.rs
+++ b/crates/ui-egui/tests/it/shortcut_list.rs
@@ -29,7 +29,7 @@ fn no_two_default_shortcuts_are_the_same() {
}
}
for (_, row) in &NOT_AVAILABLE_ACTIONS {
- let key = row.default.unwrap();
+ let Some(key) = row.default else { continue };
assert!(!seen.contains_key(key), "{} shows {key}, which another item has", row.label);
}
}
@@ -83,3 +83,28 @@ fn a_key_listed_for_a_missing_function_is_reported_as_shared() {
assert!(h.query_by_label_contains("One or several errors").is_some(), "Space is Toggle animation's");
assert!(h.get_by_label("OK").accesskit_node().is_disabled());
}
+
+#[test]
+fn the_manipulator_rows_follow_export_textures_in_the_reference_order() {
+ let mut h = harness();
+ let ctx = h.ctx.clone();
+ menus::invoke(h.state_mut(), &ctx, "ui.settings");
+ h.run_steps(4);
+ h.get_by_role_and_label(Role::Tab, "Shortcuts").click();
+ h.run_steps(4);
+
+ let rows = [
+ "Export Textures...",
+ "Show/Hide manipulator",
+ "Increase the manipulator size",
+ "Decrease the manipulator size",
+ "Cycle through manipulation spaces",
+ "Toggle warp edition mode",
+ "Translate tool",
+ "Rotate tool",
+ "Reimport mesh",
+ ];
+ let tops: Vec = rows.iter().map(|label| h.get_by_label(label).rect().top()).collect();
+
+ assert!(tops.windows(2).all(|pair| pair[0] < pair[1]), "{rows:?} run top to bottom: {tops:?}");
+}
diff --git a/crates/ui-egui/tests/project_limits.rs b/crates/ui-egui/tests/project_limits.rs
index c6c3e34a..69e67067 100644
--- a/crates/ui-egui/tests/project_limits.rs
+++ b/crates/ui-egui/tests/project_limits.rs
@@ -33,11 +33,11 @@ fn resource_settings_follow_hardware_persist_and_apply_before_control_requests()
harness.run_steps(3);
let edited = |harness: &Harness<'_, TextureCraftApp>| harness.state().ui.windows.settings_draft.as_ref().unwrap().prefs.clone();
assert_eq!(edited(&harness).reserved_cores, available_cores, "preferences from a larger machine are clamped");
- harness.get_by_role_and_label(egui::Role::SpinButton, "Cores kept for the UI").set_value_accesskit(f64::from(u32::MAX));
+ harness.get_by_role_and_label(egui::Role::Slider, "Cores kept for the UI").set_value_accesskit(f64::from(u32::MAX));
harness.run_steps(3);
assert_eq!(edited(&harness).reserved_cores, available_cores, "editing cannot exceed this machine's CPU count");
assert!(harness.query_by_label("≈ 8.00 GiB").is_some(), "50% of 16 GiB is shown beside the percentage");
- harness.get_by_role_and_label(egui::Role::SpinButton, "Max RAM while saving").set_value_accesskit(25.0);
+ harness.get_by_role_and_label(egui::Role::Slider, "Max RAM while saving").set_value_accesskit(25.0);
harness.run_steps(3);
assert!(harness.query_by_label("≈ 4.00 GiB").is_some(), "the byte estimate follows the edited percentage");
diff --git a/docs/ui-parity.md b/docs/ui-parity.md
index 1e45c49d..1bd95040 100644
--- a/docs/ui-parity.md
+++ b/docs/ui-parity.md
@@ -154,7 +154,7 @@ that closes it back onto the bar; the float is saved with the UI state.
| UI-12 | Generator depth and property coverage | **UI + source.** The picker contains seven kinds. Switching to Position, changing Global balance and duplicating the effect worked. Shared global adjustments, resolution and input slots already exist; that does not establish the richer generator/control inventory in [#374](https://github.com/storytold/texturecraft/issues/374) | Audit each generator's inputs, micro-detail behavior and controls against the reference; do not count seven shared implementations as equivalent to its whole catalog |
| UI-13 | Narrow workspace readability | **UI.** At 1280 × 800 the app rendered, both views stayed visible and the toolbar exposed scroll arrows. Layer names/types became heavily truncated, the layer toolbar wrapped, and Properties needed scrolling. This was not an input-failure or docking-persistence test | Repeat the editing tasks at smaller sizes, widen/rearrange panels, check full-name tooltips and keyboard access, and retain the layout after restart. Since then: the Layers toolbar stays on one row at 1280 × 800 (its channel box shrinks), and a cut-short layer name or type shows in full on hover. Properties scrolling and restart persistence are unchanged |
| UI-14 | Assets panel filters | **UI + source.** The type dropdown lists the reference entries in its order, Fonts and Show all included. Saved searches and Filter by path are separate scrollable panes with a divider that supports pointer and keyboard resizing and saves its position with the UI state ([#640](https://github.com/storytold/texturecraft/issues/640)). Fonts, the built-in saved searches Favorites, 3D Assets and Flattened layers, and the System fonts and User fonts libraries are listed but greyed with "Not available yet" | Give fonts, favorites, 3D assets and flattened layers real assets, then enable those rows and check that each one filters the grid |
-| UI-15 | Edit > Settings ([#637](https://github.com/storytold/texturecraft/issues/637)) | **Source + headless UI tests.** The window has the reference's General, Shortcuts and Libraries pages with OK and Cancel, and the General sections in its order (no Privacy section: TextureCraft sends no usage data). Language (with Default (System Language)), the camera rotation, zoom and wheel speeds with Inverse direction, Enable GPU raytracing, the Shortcuts page and adding or removing library locations work. Show keyboard helper, Show world axes, Background color, Only display the selected material when painting, Viewport Scaling, Default UV scale for materials, simplified thumbnails, the other baking options, the preview cache and shader, the temporary cache directory, sparse virtual texture and the IRAY HARDWARE choices are shown disabled with "Not available yet". A location's Default choice is fixed to your_assets. The Shortcuts page has the sections Actions, Mouse shortcuts and Modifiers shortcuts and a Reset all to default button; Delete clears a binding; a shared shortcut shows a warning naming the other action, a warning on the page icon and the footer "One or several errors have been found in Shortcuts settings", and OK stays disabled until it is gone (the mouse and modifier rows are shown disabled, the viewports read those gestures from code). The shortcut list uses the reference's action names, order and default keys ("Open project", "Save as project", "Switch to baking mode" Ctrl+Shift+B, "Switch to edition mode" F9, "Camera projection: Perspective view" F5, "Show entire mesh/path", "Select next camera" `>`, "Select previous camera" `<`, "Viewers layout: 3D/2D" F1 to "Viewers layout: Swap 3D/2D" F4 and so on); Quit keeps Ctrl+Q and the menus keep their own texts. "Show mesh wireframe" is a new bindable command without a key; "Pause Engine Computation" (Shift+Esc) and "Toggle animation" (Space) are listed disabled with "Not available yet". The window reopens on the page it was closed on. With a project open the Libraries page hides the add row and shows "Library locations can't be added/removed when a project is opened."; the default library's "−" says "Cannot remove the default library.". "GPU raytracing not available for your hardware." shows under the Baking options when there is no GPU. TextureCraft's own settings (appearance, viewport textures, resources, autosave, folders) follow the reference sections | Run the window in the native app; wire each disabled control as its function lands |
+| UI-15 | Edit > Settings ([#637](https://github.com/storytold/texturecraft/issues/637)) | **Source + headless UI tests.** The window has the reference's General, Shortcuts and Libraries pages with OK and Cancel, and the General sections in its order (no Privacy section: TextureCraft sends no usage data). Language (Default (System Language) by default and after a reset), the camera rotation, zoom and wheel speeds with Inverse direction, Show world axes (the 3D view's X, Y and Z corner), the Shortcuts page and adding or removing library locations work. Enable GPU raytracing is on and can be changed when there is a GPU, and off and disabled without one ([#823](https://github.com/storytold/texturecraft/issues/823)). Show keyboard helper and Save preprocessed scene files (on), Only display the selected material when painting (off), Enable live preview baking process (on), Viewport Scaling (only Auto) and the Local cache directory (empty is the system's temporary folder; R goes back to it) can be changed and are kept, but have no effect yet. Default UV scale for materials, simplified thumbnails, the preview cache budget and shader, the Files cache directory and sparse virtual texture are shown disabled with "Not available yet". There is no IRAY HARDWARE section. A location's Default choice is fixed to your_assets. The Shortcuts page has the sections Actions, Mouse shortcuts and Modifiers shortcuts and a Reset all to default button; Delete clears a binding; a shared shortcut shows a warning naming the other action, a warning on the page icon and the footer "One or several errors have been found in Shortcuts settings", and OK stays disabled until it is gone (the mouse and modifier rows are shown disabled, the viewports read those gestures from code). The shortcut list uses the reference's action names, order and default keys ("Open project", "Show/Hide manipulator" Q to "Rotate tool" E after "Export Textures...", "Save as project", "Switch to baking mode" Ctrl+Shift+B, "Switch to edition mode" F9, "Camera projection: Perspective view" F5, "Show entire mesh/path", "Select next camera" `>`, "Select previous camera" `<`, "Viewers layout: 3D/2D" F1 to "Viewers layout: Swap 3D/2D" F4 and so on); Quit keeps Ctrl+Q and the menus keep their own texts. "Show mesh wireframe" is a new bindable command without a key; "Show/Hide manipulator", "Increase the manipulator size", "Decrease the manipulator size", "Cycle through manipulation spaces", "Toggle warp edition mode", "Translate tool", "Rotate tool", "Pause Engine Computation" (Shift+Esc) and "Toggle animation" (Space) are listed disabled with "Not available yet". The window reopens on the page it was closed on. With a project open the Libraries page hides the add row and shows "Library locations can't be added/removed when a project is opened."; the default library's "−" says "Cannot remove the default library.". "GPU raytracing not available for your hardware." shows under the Baking options when there is no GPU. The reference's TEMPORARY FILES section is called FILES and also holds the Data folder. TextureCraft's own settings follow the reference sections: VIEWPORT (texture resolution), RESOURCES (Max CPU threads for work, default every thread, and Cores kept for the UI as sliders in steps of 1 with the core count beside them, Max RAM while saving as a 0-100% slider, Max project size on open, Recent projects limit) and AUTOSAVE. There is no appearance, folders or analytics section: interface scale, brightness, accent colour and the system title bar stay in the saved settings and `ui.set` | Run the window in the native app; wire each disabled control as its function lands |
Bake workflow (issue [#651](https://github.com/storytold/texturecraft/issues/651)): Mesh Map Bakers
has a Presets menu (save, load, delete named bake settings; Apply to All Texture Sets) and a finished
From af296eb5bc8256bad0c7af6effed4ff62f59c62c Mon Sep 17 00:00:00 2001
From: vangel76
Date: Wed, 25 Nov 2026 00:56:44 +0100
Subject: [PATCH 024/138] Scroll to R before clicking it and document the new
settings fields
---
crates/ui-egui/src/state.rs | 3 ++-
crates/ui-egui/tests/it/settings_window.rs | 5 +++++
docs/control-protocol.md | 6 +++++-
3 files changed, 12 insertions(+), 2 deletions(-)
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index 9d97f54d..bfd72af9 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -167,7 +167,8 @@ pub struct Prefs {
pub reserved_cores: u32,
/// Maximum decompressed project size accepted on open, in GiB (at least one).
pub project_open_limit_gib: u32,
- /// Percent of the free RAM a project save may hold at once (desktop; 1 to 100).
+ /// Percent of the free RAM a project save may hold at once (desktop; 0 to 100, a save holds
+ /// at least 1).
pub save_ram_percent: u8,
/// Worker threads for painting, baking and export (desktop; 0: one per logical CPU). Read at
/// startup, before the first parallel job.
diff --git a/crates/ui-egui/tests/it/settings_window.rs b/crates/ui-egui/tests/it/settings_window.rs
index 7ca014c9..d3040990 100644
--- a/crates/ui-egui/tests/it/settings_window.rs
+++ b/crates/ui-egui/tests/it/settings_window.rs
@@ -156,6 +156,8 @@ fn the_resource_sliders_step_by_one_and_follow_the_arrow_keys() {
let ram_percent = |h: &Harness<'_, TextureCraftApp>| h.state().ui.windows.settings_draft.as_ref().unwrap().prefs.save_ram_percent;
let before = ram_percent(&h);
+ h.get_by_role_and_label(Role::Slider, "Max RAM while saving").scroll_to_me();
+ h.run_steps(3);
h.get_by_role_and_label(Role::Slider, "Max RAM while saving").focus();
h.run_steps(2);
press_key(&mut h, Key::ArrowRight);
@@ -194,6 +196,9 @@ fn the_local_cache_directory_takes_a_folder_and_r_goes_back_to_the_default() {
type_into(&mut h, "Local cache directory", &folder);
assert_eq!(stored(&h), folder);
+ // The Files cache directory's R stays disabled; the local cache's R is the one that works
+ h.query_all_by_label("R").find(|node| !node.accesskit_node().is_disabled()).unwrap().scroll_to_me();
+ h.run_steps(3);
h.query_all_by_label("R").find(|node| !node.accesskit_node().is_disabled()).unwrap().click();
h.run_steps(3);
assert!(stored(&h).is_empty(), "R goes back to the default folder");
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 7873145d..e2d4b3ca 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -326,7 +326,11 @@ Other preferences set through `ui.set {"prefs": {...}}`: `language` (`""` follow
language), `work_threads` (worker threads for painting, baking and export; 0 uses every logical
CPU; read at startup), `rotation_speed` (default 2), `zoom_speed` and `wheel_speed` (default 1,
each from 0.1 to 10) with `zoom_inverse` and `wheel_inverse`, `gpu_raytracing` (false keeps bake
-rays on the CPU) and `libraries` (the folders the shelf scans for saved smart materials and masks).
+rays on the CPU), `show_world_axes` (the 3D view's X, Y and Z corner, default true) and `libraries`
+(the folders the shelf scans for saved smart materials and masks). `show_keyboard_helper`,
+`only_selected_material_when_painting`, `save_preprocessed_scene_files`, `live_preview_baking` and
+`local_cache_directory` (empty: the system's temporary folder) are kept for Settings but have no
+effect yet.
For example, the `libraries` field can contain `[{"name": "Studio", "path": "/assets/studio"}]`.
Use an absolute path on the host running TextureCraft. To change one preference, read `state.prefs`
with `ui.inspect`, update that field and send the full `prefs` object to `ui.set`.
From 2c6222ecde671efa66734bcccf51c8fc4e4e2f9c Mon Sep 17 00:00:00 2001
From: vangel76
Date: Wed, 25 Nov 2026 01:18:07 +0100
Subject: [PATCH 025/138] Move texture resolution to Display Settings and apply
review fixes
Remove the Viewport section from Settings; the texture resolution is in
Display Settings > Render settings and the GPU memory toasts point there.
Add hovers to the Data folder and RAM slider, name the R button for screen
readers, test that Show world axes hides the 3D axes, and fix the docs
that still named the removed sections.
---
crates/ui-egui/src/display_settings.rs | 16 ++++++--
crates/ui-egui/src/lib.rs | 2 +-
crates/ui-egui/src/settings_window.rs | 26 +++++-------
crates/ui-egui/src/viewport.rs | 4 +-
crates/ui-egui/tests/it/settings_window.rs | 46 +++++++++++++++-------
crates/ui-egui/tests/ui_snapshots.rs | 3 ++
docs/control-protocol.md | 1 +
docs/features.md | 6 +--
docs/ui-parity.md | 2 +-
9 files changed, 66 insertions(+), 40 deletions(-)
diff --git a/crates/ui-egui/src/display_settings.rs b/crates/ui-egui/src/display_settings.rs
index 7c0bc14d..92b8e13c 100644
--- a/crates/ui-egui/src/display_settings.rs
+++ b/crates/ui-egui/src/display_settings.rs
@@ -43,7 +43,7 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
0 => import_hdr = environment(app, ui, &mut display),
1 => camera(app, ui, &mut display),
2 => post_effects(ui, &mut display),
- 3 => render_settings(ui, &mut display),
+ 3 => render_settings(app, ui, &mut display),
_ => visualization(app, ui, &mut display),
});
@@ -255,9 +255,19 @@ fn post_effects(ui: &mut Ui, display: &mut DisplaySettings) {
}
}
-/// Temporal anti-aliasing
-fn render_settings(ui: &mut Ui, display: &mut DisplaySettings) {
+/// Temporal anti-aliasing and the viewport texture resolution (an app setting, not the project's)
+fn render_settings(app: &mut TextureCraftApp, ui: &mut Ui, display: &mut DisplaySettings) {
ui.checkbox(&mut display.taa, tr("Temporal anti-aliasing (refines the 3D view while it is still)"));
+ ui.horizontal(|ui| {
+ ui.label(tr("Texture resolution"));
+ for (value, label) in [(0_u8, tr("Full")), (1, tr("Half")), (2, tr("Quarter"))] {
+ ui.selectable_value(&mut app.ui.prefs.viewport_texture, value, label);
+ }
+ })
+ .response
+ .on_hover_text(tr(
+ "Size of the textures the viewport shows: lower uses less GPU memory with large texture sets. Painting and export keep full resolution.",
+ ));
}
/// The mesh wireframe and the single-channel views
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index f6b25a0f..8cddbbc7 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -1014,7 +1014,7 @@ const GLIDE_SECONDS: f64 = 0.35;
/// The share of the running frame rate and frame time averages each frame keeps (an average over about ten frames)
const FRAME_AVERAGE_KEEP: f32 = 0.9;
-/// The interface scale applied: wider than the Settings slider, so a scale set elsewhere still applies within reason
+/// The interface scale applied (`prefs.ui_scale`, set through `ui.set`; Settings has no control for it), clamped to a usable range
const UI_SCALE_APPLIED: std::ops::RangeInclusive = 0.5..=3.0;
/// Zoom factors closer than this are the same zoom (float noise), so the zoom is not set again each frame
const SAME_ZOOM_TOLERANCE: f32 = 1e-3;
diff --git a/crates/ui-egui/src/settings_window.rs b/crates/ui-egui/src/settings_window.rs
index 7da312bc..2227a7d8 100644
--- a/crates/ui-egui/src/settings_window.rs
+++ b/crates/ui-egui/src/settings_window.rs
@@ -456,7 +456,12 @@ fn general(
{
let default = crate::local_cache_folder("").display().to_string();
ui.add(egui::TextEdit::singleline(&mut p.local_cache_directory).hint_text(default).desired_width(CONTROL_WIDTH - 24.0)).labelled_by(label);
- if ui.add(egui::Button::new("R").frame(false)).on_hover_text(tr("Reset to the default folder")).clicked() {
+ let reset = ui.add(egui::Button::new("R").frame(false)).on_hover_text(tr("Reset to the default folder"));
+
+ // Screen readers hear what the single letter does
+ let name = format!("R, {}", tr("Reset to the default folder"));
+ reset.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &name));
+ if reset.clicked() {
p.local_cache_directory.clear();
}
}
@@ -495,7 +500,9 @@ fn general(
#[cfg(not(target_arch = "wasm32"))]
row(ui, tr("Data folder"), |ui, label| {
let default = crate::data_folder("").display().to_string();
- ui.add(egui::TextEdit::singleline(&mut p.data_folder).hint_text(default).desired_width(CONTROL_WIDTH - 30.0)).labelled_by(label);
+ ui.add(egui::TextEdit::singleline(&mut p.data_folder).hint_text(default).desired_width(CONTROL_WIDTH - 30.0))
+ .labelled_by(label)
+ .on_hover_text(tr("Applies on restart."));
if ui.button("...").on_hover_text(tr("Choose the data folder")).clicked() {
*pick = Some(SettingsFolder::DataFolder);
}
@@ -505,19 +512,6 @@ fn general(
disabled_text_check(ui, n_("Hardware support acceleration"), true);
// TextureCraft's own settings, after the reference sections
- section(ui, n_("VIEWPORT"));
- row(ui, tr("Texture resolution"), |ui, _| {
- ui.horizontal(|ui| {
- for (v, l) in [(0u8, tr("Full")), (1, tr("Half")), (2, tr("Quarter"))] {
- ui.selectable_value(&mut p.viewport_texture, v, l);
- }
- })
- .response
- .on_hover_text(tr(
- "Size of the textures the viewport shows: lower uses less GPU memory with large texture sets. Painting and export keep full resolution.",
- ));
- });
-
section(ui, n_("RESOURCES"));
#[cfg(not(target_arch = "wasm32"))]
{
@@ -537,7 +531,7 @@ fn general(
cores_in_total(ui, available_cores);
});
row(ui, tr("Max RAM while saving"), |ui, label| {
- ui.add(egui::Slider::new(&mut p.save_ram_percent, 0..=100).step_by(1.0).suffix(" %")).labelled_by(label);
+ ui.add(egui::Slider::new(&mut p.save_ram_percent, 0..=100).step_by(1.0).suffix(" %")).labelled_by(label).on_hover_text(tr("0 % uses at least 1 %"));
let budget_bytes = texturecraft_engine::formats::save_ram_budget(available_ram_bytes, p.save_ram_percent);
ui.label(format!("≈ {:.2} GiB", budget_bytes as f64 / (1_u64 << 30) as f64));
});
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index 7a83ccf6..c7f65f95 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -405,7 +405,7 @@ fn gpu_report_toasts(app: &mut TextureCraftApp, reports: crate::gpu::GpuReports)
}
let text = match sets.as_slice() {
[one] => trf(
- "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.",
+ "Not enough GPU memory to show texture set \"{name}\" fully: lower the Texture resolution in Display Settings › Render settings. Painting and export are not affected.",
&[("name", one)],
),
many => {
@@ -418,7 +418,7 @@ fn gpu_report_toasts(app: &mut TextureCraftApp, reports: crate::gpu::GpuReports)
list.push_str(", ...");
}
trf(
- "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.",
+ "Not enough GPU memory to show {count} texture sets fully ({names}): lower the Texture resolution in Display Settings › Render settings. Painting and export are not affected.",
&[("count", &many.len()), ("names", &list)],
)
}
diff --git a/crates/ui-egui/tests/it/settings_window.rs b/crates/ui-egui/tests/it/settings_window.rs
index d3040990..c89a8347 100644
--- a/crates/ui-egui/tests/it/settings_window.rs
+++ b/crates/ui-egui/tests/it/settings_window.rs
@@ -87,7 +87,7 @@ fn the_general_page_starts_at_the_reference_defaults() {
let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap());
open_settings(&mut h);
- // A reset puts the defaults in the window; the app itself keeps English for the exact-text checks
+ // The defaults of a first start, in the window; the app itself keeps English for the exact-text checks
h.state_mut().ui.windows.settings_draft.as_mut().unwrap().prefs = Prefs::default();
h.run_steps(3);
@@ -112,7 +112,7 @@ fn the_general_page_starts_at_the_reference_defaults() {
assert_eq!(texturecraft_ui_egui::local_cache_folder(&Prefs::default().local_cache_directory), std::env::temp_dir());
let prefs = Prefs::default();
- assert_eq!(prefs.language, texturecraft_ui_egui::i18n::SYSTEM_LANGUAGE, "a reset follows the system language");
+ assert_eq!(prefs.language, texturecraft_ui_egui::i18n::SYSTEM_LANGUAGE, "the default follows the system language");
assert_eq!((prefs.rotation_speed, prefs.zoom_speed, prefs.wheel_speed), (2.0, 1.0, 1.0));
}
@@ -121,7 +121,7 @@ fn the_general_page_keeps_the_reference_sections_and_moves_data_folder_and_recen
let mut h = harness(Session::closed().unwrap());
open_settings(&mut h);
- for gone in ["TEMPORARY FILES", "IRAY HARDWARE", "APPEARANCE", "FOLDERS", "PRIVACY", "Interface scale", "Accent color"] {
+ for gone in ["TEMPORARY FILES", "IRAY HARDWARE", "APPEARANCE", "FOLDERS", "VIEWPORT", "Interface scale", "Accent color"] {
assert!(h.query_by_label(gone).is_none(), "{gone} is not on the page");
}
for hint in ["Saving uses the other cores", "0 turns autosave off", "A new folder applies on restart"] {
@@ -160,11 +160,32 @@ fn the_resource_sliders_step_by_one_and_follow_the_arrow_keys() {
h.run_steps(3);
h.get_by_role_and_label(Role::Slider, "Max RAM while saving").focus();
h.run_steps(2);
+
press_key(&mut h, Key::ArrowRight);
- assert_eq!(ram_percent(&h), before + 1, "the right arrow adds one percent");
+ let after_right = ram_percent(&h);
press_key(&mut h, Key::ArrowLeft);
press_key(&mut h, Key::ArrowLeft);
- assert_eq!(ram_percent(&h), before - 1, "the left arrow takes one percent");
+ let after_left = ram_percent(&h);
+
+ assert_eq!(after_right, before + 1, "the right arrow adds one percent");
+ assert_eq!(after_left, before - 1, "the left arrow takes one percent");
+}
+
+#[test]
+fn show_world_axes_draws_the_3d_view_axes_and_off_hides_them() {
+ let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap());
+ let painted_z = |h: &Harness<'_, TextureCraftApp>| {
+ h.output().shapes.iter().filter(|clipped| matches!(&clipped.shape, egui::Shape::Text(text) if text.galley.text() == "Z")).count()
+ };
+
+ h.state_mut().ui.prefs.show_world_axes = true;
+ h.run_steps(3);
+ let shown = painted_z(&h);
+ h.state_mut().ui.prefs.show_world_axes = false;
+ h.run_steps(3);
+ let hidden = painted_z(&h);
+
+ assert_eq!(shown, hidden + 1, "the 3D view's Z axis letter is drawn only while Show world axes is on");
}
#[test]
@@ -179,8 +200,8 @@ fn the_enabled_interface_options_answer_the_keyboard() {
h.run_steps(2);
press_key(&mut h, Key::Space);
}
-
let after = draft(&h);
+
assert_ne!(after.show_keyboard_helper, before.show_keyboard_helper);
assert_ne!(after.show_world_axes, before.show_world_axes);
assert_ne!(after.only_selected_material_when_painting, before.only_selected_material_when_painting);
@@ -194,14 +215,12 @@ fn the_local_cache_directory_takes_a_folder_and_r_goes_back_to_the_default() {
let stored = |h: &Harness<'_, TextureCraftApp>| h.state().ui.windows.settings_draft.as_ref().unwrap().prefs.local_cache_directory.clone();
type_into(&mut h, "Local cache directory", &folder);
- assert_eq!(stored(&h), folder);
+ let typed = stored(&h);
+ click(&mut h, "R, Reset to the default folder");
+ let reset = stored(&h);
- // The Files cache directory's R stays disabled; the local cache's R is the one that works
- h.query_all_by_label("R").find(|node| !node.accesskit_node().is_disabled()).unwrap().scroll_to_me();
- h.run_steps(3);
- h.query_all_by_label("R").find(|node| !node.accesskit_node().is_disabled()).unwrap().click();
- h.run_steps(3);
- assert!(stored(&h).is_empty(), "R goes back to the default folder");
+ assert_eq!(typed, folder);
+ assert!(reset.is_empty(), "R goes back to the default folder");
}
#[test]
@@ -534,7 +553,6 @@ fn gpu_raytracing_is_on_and_checkable_with_a_gpu_and_off_and_disabled_without()
assert_eq!(!check.accesskit_node().is_disabled(), supported, "it can be changed exactly when there is a GPU");
assert_eq!(toggled(&h, "Enable GPU raytracing"), supported, "it is on exactly when there is a GPU");
assert_eq!(h.query_by_label(GPU_RAYTRACING_UNAVAILABLE).is_some(), !supported, "the note shows with no GPU and only then");
- assert!(h.state().ui.prefs.gpu_raytracing, "the stored choice stays for a machine with a GPU");
}
#[test]
diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs
index cda0398b..7181557a 100644
--- a/crates/ui-egui/tests/ui_snapshots.rs
+++ b/crates/ui-egui/tests/ui_snapshots.rs
@@ -83,6 +83,9 @@ fn empty_start_snapshot() {
harness.get_by_label("Edit").click();
harness.run_steps(3);
harness.get_by_label("Settings").click();
+ harness.run_steps(3);
+ harness.get_by_label("Recent projects limit").scroll_to_me();
+ harness.run_steps(3);
save(&mut harness, &output_dir, "settings-recent-project-limit");
assert!(!harness.get_by_label("Recent projects limit").accesskit_node().is_disabled());
}
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index e2d4b3ca..35cbd0d3 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -334,6 +334,7 @@ effect yet.
For example, the `libraries` field can contain `[{"name": "Studio", "path": "/assets/studio"}]`.
Use an absolute path on the host running TextureCraft. To change one preference, read `state.prefs`
with `ui.inspect`, update that field and send the full `prefs` object to `ui.set`.
+A `prefs` object without `language` sets the system language (`""`), the default.
## MCP server
diff --git a/docs/features.md b/docs/features.md
index 04702ee9..1106571b 100644
--- a/docs/features.md
+++ b/docs/features.md
@@ -250,10 +250,10 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
- **Swap 3D/2D** (F4, Viewport menu and the layout dropdown, rebindable) puts the 2D view on the left and the 3D view on the right in the split layout. Painting, the divider and the views' headers work on both sides, and the choice is kept with the UI state.
- A modern look in **four brightness levels** (dark, medium dark, medium light and light) with
- **seven accent colors**, set in Settings › General › Appearance.
+ **seven accent colors**, set for now only through `ui.set` (`prefs.brightness`, `prefs.accent`).
- **Its own title bar** with the app icon, menus and window buttons on Windows (and on Linux
desktops that leave the frame to the app, such as GNOME), the macOS traffic lights over the same
- strip, and Settings › General › Appearance › System title bar for the system's frame instead.
+ strip, and the system's frame instead with `prefs.system_title_bar` through `ui.set` (for now).
- **Dockable, tabbed and floating panels**, saved layouts, and panels that reopen where you closed
them. The right bar's panels (Export, Log, Display Settings, Shader Settings, History) pop out
beside it; *Undock* makes one a floating window, and its *Dock* button puts it back on the bar.
@@ -273,7 +273,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
- **No project at launch**: empty views, panels and toolbars until you create or open one (File ›
New project, Open, Recent projects, Open sample project); File › Close returns to that state.
- A **data folder** of your choice for autosaves, smart materials, presets, templates and UI
- layouts, on any drive (Settings › General › Folders; `Documents/TextureCraft` by default).
+ layouts, on any drive (Settings › General › Files › Data folder; `Documents/TextureCraft` by default).
- A **Settings window** (Edit › Settings) with General, Shortcuts and Libraries pages; changes
apply on OK and Cancel drops them. General holds the language (or the system's), the 3D view's
rotation, zoom and wheel speeds with inverse directions, GPU or CPU bake rays, resource limits
diff --git a/docs/ui-parity.md b/docs/ui-parity.md
index 1bd95040..4e6a3f45 100644
--- a/docs/ui-parity.md
+++ b/docs/ui-parity.md
@@ -154,7 +154,7 @@ that closes it back onto the bar; the float is saved with the UI state.
| UI-12 | Generator depth and property coverage | **UI + source.** The picker contains seven kinds. Switching to Position, changing Global balance and duplicating the effect worked. Shared global adjustments, resolution and input slots already exist; that does not establish the richer generator/control inventory in [#374](https://github.com/storytold/texturecraft/issues/374) | Audit each generator's inputs, micro-detail behavior and controls against the reference; do not count seven shared implementations as equivalent to its whole catalog |
| UI-13 | Narrow workspace readability | **UI.** At 1280 × 800 the app rendered, both views stayed visible and the toolbar exposed scroll arrows. Layer names/types became heavily truncated, the layer toolbar wrapped, and Properties needed scrolling. This was not an input-failure or docking-persistence test | Repeat the editing tasks at smaller sizes, widen/rearrange panels, check full-name tooltips and keyboard access, and retain the layout after restart. Since then: the Layers toolbar stays on one row at 1280 × 800 (its channel box shrinks), and a cut-short layer name or type shows in full on hover. Properties scrolling and restart persistence are unchanged |
| UI-14 | Assets panel filters | **UI + source.** The type dropdown lists the reference entries in its order, Fonts and Show all included. Saved searches and Filter by path are separate scrollable panes with a divider that supports pointer and keyboard resizing and saves its position with the UI state ([#640](https://github.com/storytold/texturecraft/issues/640)). Fonts, the built-in saved searches Favorites, 3D Assets and Flattened layers, and the System fonts and User fonts libraries are listed but greyed with "Not available yet" | Give fonts, favorites, 3D assets and flattened layers real assets, then enable those rows and check that each one filters the grid |
-| UI-15 | Edit > Settings ([#637](https://github.com/storytold/texturecraft/issues/637)) | **Source + headless UI tests.** The window has the reference's General, Shortcuts and Libraries pages with OK and Cancel, and the General sections in its order (no Privacy section: TextureCraft sends no usage data). Language (Default (System Language) by default and after a reset), the camera rotation, zoom and wheel speeds with Inverse direction, Show world axes (the 3D view's X, Y and Z corner), the Shortcuts page and adding or removing library locations work. Enable GPU raytracing is on and can be changed when there is a GPU, and off and disabled without one ([#823](https://github.com/storytold/texturecraft/issues/823)). Show keyboard helper and Save preprocessed scene files (on), Only display the selected material when painting (off), Enable live preview baking process (on), Viewport Scaling (only Auto) and the Local cache directory (empty is the system's temporary folder; R goes back to it) can be changed and are kept, but have no effect yet. Default UV scale for materials, simplified thumbnails, the preview cache budget and shader, the Files cache directory and sparse virtual texture are shown disabled with "Not available yet". There is no IRAY HARDWARE section. A location's Default choice is fixed to your_assets. The Shortcuts page has the sections Actions, Mouse shortcuts and Modifiers shortcuts and a Reset all to default button; Delete clears a binding; a shared shortcut shows a warning naming the other action, a warning on the page icon and the footer "One or several errors have been found in Shortcuts settings", and OK stays disabled until it is gone (the mouse and modifier rows are shown disabled, the viewports read those gestures from code). The shortcut list uses the reference's action names, order and default keys ("Open project", "Show/Hide manipulator" Q to "Rotate tool" E after "Export Textures...", "Save as project", "Switch to baking mode" Ctrl+Shift+B, "Switch to edition mode" F9, "Camera projection: Perspective view" F5, "Show entire mesh/path", "Select next camera" `>`, "Select previous camera" `<`, "Viewers layout: 3D/2D" F1 to "Viewers layout: Swap 3D/2D" F4 and so on); Quit keeps Ctrl+Q and the menus keep their own texts. "Show mesh wireframe" is a new bindable command without a key; "Show/Hide manipulator", "Increase the manipulator size", "Decrease the manipulator size", "Cycle through manipulation spaces", "Toggle warp edition mode", "Translate tool", "Rotate tool", "Pause Engine Computation" (Shift+Esc) and "Toggle animation" (Space) are listed disabled with "Not available yet". The window reopens on the page it was closed on. With a project open the Libraries page hides the add row and shows "Library locations can't be added/removed when a project is opened."; the default library's "−" says "Cannot remove the default library.". "GPU raytracing not available for your hardware." shows under the Baking options when there is no GPU. The reference's TEMPORARY FILES section is called FILES and also holds the Data folder. TextureCraft's own settings follow the reference sections: VIEWPORT (texture resolution), RESOURCES (Max CPU threads for work, default every thread, and Cores kept for the UI as sliders in steps of 1 with the core count beside them, Max RAM while saving as a 0-100% slider, Max project size on open, Recent projects limit) and AUTOSAVE. There is no appearance, folders or analytics section: interface scale, brightness, accent colour and the system title bar stay in the saved settings and `ui.set` | Run the window in the native app; wire each disabled control as its function lands |
+| UI-15 | Edit > Settings ([#637](https://github.com/storytold/texturecraft/issues/637)) | **Source + headless UI tests.** The window has the reference's General, Shortcuts and Libraries pages with OK and Cancel, and the General sections in its order (no Privacy section: TextureCraft sends no usage data). Language (Default (System Language) by default and after a reset), the camera rotation, zoom and wheel speeds with Inverse direction, Show world axes (the 3D view's X, Y and Z corner), the Shortcuts page and adding or removing library locations work. Enable GPU raytracing is on and can be changed when there is a GPU, and off and disabled without one ([#823](https://github.com/storytold/texturecraft/issues/823)). Show keyboard helper (on), Only display the selected material when painting (off), Save preprocessed scene files (on), Enable live preview baking process (on) and the Local cache directory (empty is the system's temporary folder; R goes back to it) can be changed and are kept, but have no effect yet. Viewport Scaling opens but lists only Auto, so there is nothing to change. Default UV scale for materials, simplified thumbnails, the preview cache budget and shader, the Files cache directory and sparse virtual texture are shown disabled with "Not available yet". There is no IRAY HARDWARE section. A location's Default choice is fixed to your_assets. The Shortcuts page has the sections Actions, Mouse shortcuts and Modifiers shortcuts and a Reset all to default button; Delete clears a binding; a shared shortcut shows a warning naming the other action, a warning on the page icon and the footer "One or several errors have been found in Shortcuts settings", and OK stays disabled until it is gone (the mouse and modifier rows are shown disabled, the viewports read those gestures from code). The shortcut list uses the reference's action names, order and default keys ("Open project", "Save as project", "Switch to baking mode" Ctrl+Shift+B, "Switch to edition mode" F9, "Camera projection: Perspective view" F5, "Show entire mesh/path", "Select next camera" `>`, "Select previous camera" `<`, "Viewers layout: 3D/2D" F1 to "Viewers layout: Swap 3D/2D" F4 and so on); Quit keeps Ctrl+Q and the menus keep their own texts. "Show mesh wireframe" is a new bindable command without a key; "Pause Engine Computation" (Shift+Esc) and "Toggle animation" (Space) are listed disabled with "Not available yet". The reference's rows after "Export Textures..." are listed the same way, in its order: "Show/Hide manipulator" (Q), "Increase the manipulator size", "Decrease the manipulator size" (-), "Cycle through manipulation spaces" (T), "Toggle warp edition mode" (Shift+V), "Translate tool" (W) and "Rotate tool" (E). The window reopens on the page it was closed on. With a project open the Libraries page hides the add row and shows "Library locations can't be added/removed when a project is opened."; the default library's "−" says "Cannot remove the default library.". "GPU raytracing not available for your hardware." shows under the Baking options when there is no GPU. The reference's TEMPORARY FILES section is called FILES and also holds the Data folder. TextureCraft's own settings follow the reference sections: RESOURCES (Max CPU threads for work, default every thread, and Cores kept for the UI as sliders in steps of 1 with the core count beside them, Max RAM while saving as a 0-100% slider, Max project size on open, Recent projects limit) and AUTOSAVE. There is no appearance, viewport, folders or analytics section: the viewport texture resolution (Full, Half, Quarter) is in Display Settings › Render settings, and interface scale, brightness, accent color and the system title bar stay in the saved settings and `ui.set` | Run the window in the native app; wire each disabled control as its function lands |
Bake workflow (issue [#651](https://github.com/storytold/texturecraft/issues/651)): Mesh Map Bakers
has a Presets menu (save, load, delete named bake settings; Apply to All Texture Sets) and a finished
From 7a3b95e7982d06e03f7bafbe783327e380a23e0b Mon Sep 17 00:00:00 2001
From: Rebornim <250083243+Rebornim@users.noreply.github.com>
Date: Wed, 25 Nov 2026 00:38:08 +0000
Subject: [PATCH 026/138] Export: JPEG 2000 file types, lossless, as a raw
codestream (j2k) or a JP2 file (jp2)
Encoded by the j2k crate (MIT OR Apache-2.0, pure Rust; craft-image-codecs only reads JPEG 2000), which needs Rust 1.96, so the README asks for 1.96.
---
Cargo.lock | 71 +++++++++++++++++++-
Cargo.toml | 3 +
README.md | 2 +-
crates/engine/src/file_cmds.rs | 2 +-
crates/formats/Cargo.toml | 2 +
crates/formats/src/export/jpeg2000.rs | 54 +++++++++++++++
crates/formats/src/export/mod.rs | 20 +++++-
crates/formats/src/export/tests.rs | 71 +++++++++++++++++++-
crates/ui-egui/src/export_window.rs | 4 +-
crates/ui-egui/tests/it/export_file_types.rs | 21 +++---
docs/control-protocol.md | 2 +-
docs/features.md | 2 +-
12 files changed, 228 insertions(+), 26 deletions(-)
create mode 100644 crates/formats/src/export/jpeg2000.rs
diff --git a/Cargo.lock b/Cargo.lock
index d82d26f7..c0494fe8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1832,6 +1832,12 @@ version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"
+[[package]]
+name = "fearless_simd"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a7107516a8be9a4ffe92495f3dbfe04348be0ad18f17c67a1d846511f99e599"
+
[[package]]
name = "filetime"
version = "0.2.29"
@@ -2394,7 +2400,7 @@ version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1"
dependencies = [
- "fearless_simd",
+ "fearless_simd 0.4.1",
]
[[package]]
@@ -2760,6 +2766,63 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+[[package]]
+name = "j2k"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5dcb93d62c580930297896f25933b034bf665534568626787dbf0f03027e7b0"
+dependencies = [
+ "j2k-core",
+ "j2k-native",
+ "j2k-types",
+ "moxcms",
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "j2k-codec-math"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a38b1ddbaa04c07213dba6180ed1168f0e96bfa35890542c414d872cea0c7d58"
+dependencies = [
+ "j2k-types",
+]
+
+[[package]]
+name = "j2k-core"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae969eb19e9b3a8d65c4342f9921717be407571cc0fbc44e4379daa0b588d01c"
+dependencies = [
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "j2k-native"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "971da314ca1501363f686b6796d309ebbda7d2f88d34671c38d79132f7cb59ff"
+dependencies = [
+ "fearless_simd 1.3.0",
+ "j2k-codec-math",
+ "j2k-profile",
+ "j2k-types",
+ "libm",
+ "rayon",
+]
+
+[[package]]
+name = "j2k-profile"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c1c0cc7e85f2ab1cc85c9a6d2bad3680319c0cdf558f3be14b4ccdbd6917fca"
+
+[[package]]
+name = "j2k-types"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "716edd556741a415294d955121f76d41b7d8d650554fb09f30d0654b15127ac9"
+
[[package]]
name = "jni"
version = "0.22.4"
@@ -5218,6 +5281,8 @@ dependencies = [
"gltf",
"half",
"image",
+ "j2k",
+ "j2k-core",
"png",
"quick-xml 0.41.0",
"rayon",
@@ -5757,7 +5822,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbb2141a2bca6e6d598e471fd4d1d7eed8e020aad6a28187edda07f091a325dd"
dependencies = [
"bytemuck",
- "fearless_simd",
+ "fearless_simd 0.4.1",
"guillotiere",
"log",
"peniko",
@@ -7113,7 +7178,7 @@ dependencies = [
"memchr",
"nix",
"typed-path",
- "windows-sys 0.60.2",
+ "windows-sys 0.61.2",
"zeroize",
"zopfli",
]
diff --git a/Cargo.toml b/Cargo.toml
index de6fc98d..d2a340de 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -44,6 +44,9 @@ image = { version = "0.25", default-features = false, features = ["png", "jpeg",
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" }
half = "2"
exr = { version = "1.73", default-features = false }
+# JPEG 2000 writing (craft-image-codecs only reads it); j2k 0.13 needs Rust 1.99
+j2k = "0.11.3"
+j2k-core = "0.11.3"
eframe = { version = "0.37", default-features = false }
egui = "0.37"
wgpu = "30"
diff --git a/README.md b/README.md
index 345c32c1..29b1daea 100644
--- a/README.md
+++ b/README.md
@@ -157,7 +157,7 @@ cd apps/texturecraft-web && trunk serve # web build
cargo xtask ci # fmt, clippy, tests, layering, wasm
```
-You need Rust 1.95 or newer. The app opens with no project (**File ▸ Open sample project** loads a baked one, and **File ▸ Close** returns to the empty state).
+You need Rust 1.96 or newer. The app opens with no project (**File ▸ Open sample project** loads a baked one, and **File ▸ Close** returns to the empty state).
**File ▸ New project** starts from your own mesh file and a project template. TextureCraft generates UVs if the mesh has none.
Japanese, Chinese, Korean and Arabic interface text uses the fonts of
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index 006bb979..d13dbee3 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -58,7 +58,7 @@ pub fn specs() -> Vec {
"Export textures",
["File"],
None,
- "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}",
+ "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|j2k|jp2|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}",
always,
export_textures
),
diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml
index 516e0f5d..e83f5d56 100644
--- a/crates/formats/Cargo.toml
+++ b/crates/formats/Cargo.toml
@@ -32,6 +32,8 @@ half = { workspace = true }
quick-xml = { workspace = true }
zip = { workspace = true }
exr = { workspace = true }
+j2k = { workspace = true }
+j2k-core = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
diff --git a/crates/formats/src/export/jpeg2000.rs b/crates/formats/src/export/jpeg2000.rs
new file mode 100644
index 00000000..b4c2218e
--- /dev/null
+++ b/crates/formats/src/export/jpeg2000.rs
@@ -0,0 +1,54 @@
+//! JPEG 2000, lossless (reversible 5/3 wavelet): a raw codestream (.j2k) or one in a JP2 file (.jp2)
+
+use j2k::{
+ J2kChannelAssociation, J2kChannelDefinition, J2kChannelType, J2kFileBoxMetadata, J2kFileColorSpec, J2kFileWrapOptions, J2kLosslessEncodeOptions,
+ J2kLosslessSamples, encode_j2k_lossless, wrap_j2k_codestream,
+};
+use j2k_core::Colorspace;
+
+/// Encode `bytes` (8-bit or native-endian 16-bit L, LA, RGB or RGBA samples) of a `width`×`height` image; `jp2` wraps it in a JP2 file that records `icc`
+pub(super) fn write_jpeg2000(
+ bytes: Vec,
+ (width, height): (u32, u32),
+ component_count: usize,
+ depth: u8,
+ jp2: bool,
+ icc: Option<&[u8]>,
+) -> Result, String> {
+ // The encoder reads 16-bit samples little-endian
+ let bytes = if depth == 16 { bytes.as_chunks::<2>().0.iter().flat_map(|sample| u16::from_ne_bytes(*sample).to_le_bytes()).collect() } else { bytes };
+ let components = u16::try_from(component_count).map_err(|_| format!("{component_count} components"))?;
+ let input = J2kLosslessSamples { data: &bytes, width, height, components, bit_depth: depth, signed: false };
+ let codestream = encode_j2k_lossless(input, &J2kLosslessEncodeOptions::default()).map_err(|error| error.to_string())?.codestream;
+ drop(bytes);
+ if !jp2 {
+ return Ok(codestream);
+ }
+
+ // The last component of LA and RGBA is opacity, for the whole image
+ let color_count = if component_count >= 3 { 3 } else { 1 };
+ let definitions: Vec = (0..components)
+ .map(|channel_index| {
+ if channel_index < color_count {
+ J2kChannelDefinition {
+ channel_index,
+ channel_type: J2kChannelType::Color,
+ association: J2kChannelAssociation::Color { index: channel_index + 1 },
+ }
+ } else {
+ J2kChannelDefinition { channel_index, channel_type: J2kChannelType::Opacity, association: J2kChannelAssociation::WholeImage }
+ }
+ })
+ .collect();
+ let mut options = J2kFileWrapOptions::jp2();
+ options.color = match icc {
+ Some(profile) if color_count == 3 => J2kFileColorSpec::IccProfile(profile),
+ _ if color_count == 3 => J2kFileColorSpec::Enumerated(Colorspace::SRgb),
+ _ => J2kFileColorSpec::Enumerated(Colorspace::Grayscale),
+ };
+ if component_count.is_multiple_of(2) {
+ options.metadata = J2kFileBoxMetadata { palette: None, component_mappings: &[], channel_definitions: &definitions };
+ }
+
+ wrap_j2k_codestream(&codestream, options).map_err(|error| error.to_string())
+}
diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs
index f2134a0c..de1454fc 100644
--- a/crates/formats/src/export/mod.rs
+++ b/crates/formats/src/export/mod.rs
@@ -26,6 +26,7 @@ use texturecraft_texel::{ColorSpace, DilationMap, linear_to_srgb};
use crate::{FormatError, MAX_IMAGE_SIZE, Result};
mod encoding;
+mod jpeg2000;
mod map_override;
use encoding::Encoding;
pub use map_override::MapOverride;
@@ -93,10 +94,14 @@ pub enum FileFormat {
Pgm,
/// A PSD containing only its merged image.
Psd,
+ /// JPEG 2000 codestream, lossless
+ J2k,
+ /// JPEG 2000 in a JP2 file, lossless
+ Jp2,
}
impl FileFormat {
- pub const ALL: [FileFormat; 11] = [
+ pub const ALL: [FileFormat; 13] = [
FileFormat::Png,
FileFormat::Jpeg,
FileFormat::Tga,
@@ -108,6 +113,8 @@ impl FileFormat {
FileFormat::Jng,
FileFormat::Pgm,
FileFormat::Psd,
+ FileFormat::J2k,
+ FileFormat::Jp2,
];
pub fn extension(self) -> &'static str {
@@ -123,6 +130,8 @@ impl FileFormat {
FileFormat::Jng => "jng",
FileFormat::Pgm => "pgm",
FileFormat::Psd => "psd",
+ FileFormat::J2k => "j2k",
+ FileFormat::Jp2 => "jp2",
}
}
@@ -150,7 +159,7 @@ impl FileFormat {
/// float for TIFF and HDR).
pub fn bit_depths(self) -> &'static [u8] {
match self {
- FileFormat::Png | FileFormat::Pgm | FileFormat::Psd => &[8, 16],
+ FileFormat::Png | FileFormat::Pgm | FileFormat::Psd | FileFormat::J2k | FileFormat::Jp2 => &[8, 16],
FileFormat::Tiff => &[8, 16, 32],
FileFormat::Exr => &[16, 32],
FileFormat::Hdr => &[32],
@@ -1216,7 +1225,7 @@ fn encode(
// Embed ICC or EXR chromaticities only where the format supports them
if let Some(space) = embed
- && matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr | FileFormat::Jng | FileFormat::Psd)
+ && matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr | FileFormat::Jng | FileFormat::Psd | FileFormat::J2k)
{
warnings.push(format!("{} export does not embed a colour space; the colours are in {}", format.extension().to_ascii_uppercase(), space.name()));
}
@@ -1323,6 +1332,11 @@ fn encode(
FileFormat::Pgm => CodecFormat::Pnm,
FileFormat::Psd => return psd(bytes, size, component_count, depth).map_err(|error| encoding_error(&error)),
FileFormat::Jng => return jng(&bytes, size, component_count).map_err(|error| encoding_error(&error)),
+ FileFormat::J2k | FileFormat::Jp2 => {
+ let profile = embed.and_then(crate::icc::profile);
+ let jp2 = format == FileFormat::Jp2;
+ return jpeg2000::write_jpeg2000(bytes, size, component_count, depth, jp2, profile.as_deref()).map_err(|error| encoding_error(&error));
+ }
FileFormat::Exr | FileFormat::Hdr => return Err(encoding_error(&"unexpected float raster format")),
};
let layout = match component_count {
diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs
index 392148a1..45312b0d 100644
--- a/crates/formats/src/export/tests.rs
+++ b/crates/formats/src/export/tests.rs
@@ -366,8 +366,9 @@ fn every_format_encodes_and_decodes() {
let mut preset = builtin_preset("glTF PBR Metal Roughness").unwrap();
preset.maps.push(gray_alpha);
- // JNG, PGM and PSD have tests of their own (the image crate reads none of them)
- for format in FileFormat::ALL.into_iter().filter(|f| !matches!(f, FileFormat::Jng | FileFormat::Pgm | FileFormat::Psd)) {
+ // JNG, PGM, PSD and JPEG 2000 have tests of their own (the image crate reads none of them)
+ let own_tests = |format: &FileFormat| matches!(format, FileFormat::Jng | FileFormat::Pgm | FileFormat::Psd | FileFormat::J2k | FileFormat::Jp2);
+ for format in FileFormat::ALL.into_iter().filter(|format| !own_tests(format)) {
for &depth in format.bit_depths() {
let mut opts = ExportOptions::new(preset.clone());
opts.format_override = Some(format);
@@ -917,7 +918,7 @@ fn exr_carries_the_chromaticities_of_the_space() {
#[test]
fn formats_without_a_place_for_a_colour_space_say_so() {
let data = vec![0.25f32; 4 * 4 * 3];
- for format in [FileFormat::Tga, FileFormat::Bmp, FileFormat::Hdr] {
+ for format in [FileFormat::Tga, FileFormat::Bmp, FileFormat::Hdr, FileFormat::J2k] {
let mut warnings = Vec::new();
encode(Encoding { format, depth: 8, dither: false }, (4, 4), 3, data.clone(), &[false; 3], Some(ColorSpace::AcesCg), &mut warnings).unwrap();
assert!(warnings.iter().any(|w| w.contains("colour space") && w.contains("ACEScg")), "{format:?}: {warnings:?}");
@@ -1245,6 +1246,70 @@ fn jng_has_jpeg_colour_and_lossless_alpha() {
assert!(!gray.bytes.windows(4).any(|w| w == b"IDAT"));
}
+/// A JPEG 2000 file's component planes
+fn jpeg2000_planes(bytes: &[u8]) -> Vec> {
+ let mut decoder = j2k::J2kDecoder::new(bytes).unwrap();
+ let decoded = decoder.decode_native_components().unwrap();
+ decoded
+ .planes()
+ .iter()
+ .map(|plane| match plane.bytes_per_sample() {
+ 1 => plane.data().iter().map(|byte| u16::from(*byte)).collect(),
+ _ => plane.data().chunks(2).map(|pair| u16::from_le_bytes([pair[0], pair[1]])).collect(),
+ })
+ .collect()
+}
+
+#[test]
+fn jpeg2000_is_lossless_at_8_and_16_bits() {
+ let fx = Fx::new(&[Channel::BaseColor, Channel::Opacity, Channel::Roughness, Channel::Metallic, Channel::Normal]);
+ let preset = builtin_preset("glTF PBR Metal Roughness").unwrap();
+ let jp2_signature = [0, 0, 0, 12, b'j', b'P', b' ', b' '];
+ let codestream_signature = [0xFF, 0x4F, 0xFF, 0x51];
+ for depth in [8u8, 16] {
+ let mut png_options = ExportOptions::new(preset.clone());
+ png_options.bit_depth_override = Some(depth);
+ let png = fx.render(&png_options);
+ for format in [FileFormat::J2k, FileFormat::Jp2] {
+ let mut options = png_options.clone();
+ options.format_override = Some(format);
+ let files = fx.render(&options);
+ assert_eq!(files.len(), png.len());
+
+ for (file, reference) in files.iter().zip(&png) {
+ assert!(file.name.ends_with(format.extension()), "{}", file.name);
+ let signature: &[u8] = if format == FileFormat::Jp2 { &jp2_signature } else { &codestream_signature };
+ assert!(file.bytes.starts_with(signature), "{}", file.name);
+
+ // Every sample is the PNG's, with alpha the last component
+ let image = decode(reference);
+ let components = usize::from(image.color().channel_count());
+ let expected = image.to_rgba16();
+ let planes = jpeg2000_planes(&file.bytes);
+ assert_eq!(planes.len(), components, "{}", file.name);
+ for (component, plane) in planes.iter().enumerate() {
+ let source = if components <= 2 && component == 1 { 3 } else { component };
+ for (texel, sample) in expected.pixels().zip(plane) {
+ let want = if depth == 8 { texel[source] / 257 } else { texel[source] };
+ assert_eq!(*sample, want, "{} component {component}", file.name);
+ }
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn jp2_records_a_chosen_colour_space_as_an_icc_profile() {
+ let data = vec![0.25f32; 8 * 8 * 3];
+ let profile = crate::icc::profile(ColorSpace::AcesCg).unwrap();
+ let mut warnings = Vec::new();
+ let bytes =
+ encode(Encoding { format: FileFormat::Jp2, depth: 8, dither: false }, (8, 8), 3, data, &[false; 3], Some(ColorSpace::AcesCg), &mut warnings).unwrap();
+ assert!(bytes.windows(profile.len()).any(|window| window == profile.as_slice()), "the profile is in the file");
+ assert!(warnings.is_empty(), "{warnings:?}");
+}
+
#[test]
fn tiff_32f_holds_linear_floats() {
let fx = Fx::new(&default_channels());
diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs
index 6a46f757..c4a07d5f 100644
--- a/crates/ui-egui/src/export_window.rs
+++ b/crates/ui-egui/src/export_window.rs
@@ -81,8 +81,8 @@ pub(crate) const FILE_TYPES: [(&str, Option); 14] = [
("tiff", Some(FileFormat::Tiff)),
("hdr", Some(FileFormat::Hdr)),
("exr", Some(FileFormat::Exr)),
- ("j2k", None),
- ("jp2", None),
+ ("j2k", Some(FileFormat::J2k)),
+ ("jp2", Some(FileFormat::Jp2)),
("webp", Some(FileFormat::Webp)),
("psd", Some(FileFormat::Psd)),
("sbsar", None),
diff --git a/crates/ui-egui/tests/it/export_file_types.rs b/crates/ui-egui/tests/it/export_file_types.rs
index 8967fe80..a1a020eb 100644
--- a/crates/ui-egui/tests/it/export_file_types.rs
+++ b/crates/ui-egui/tests/it/export_file_types.rs
@@ -46,22 +46,21 @@ fn entries(h: &Harness<'_, TextureCraftApp>, labels: &[&str]) -> Vec {
const TYPES: [&str; 14] = ["bmp", "jpeg", "jng", "pgm", "png", "targa", "tiff", "hdr", "exr", "j2k", "jp2", "webp", "psd", "sbsar"];
#[test]
-fn the_file_type_list_is_the_reference_one_with_three_greyed() {
+fn the_file_type_list_is_the_reference_one_with_sbsar_greyed() {
let mut h = harness();
open_combo(&mut h, "Based on output template");
assert_eq!(entries(&h, &TYPES), TYPES.map(String::from).to_vec());
- // Bottom up, so no tooltip covers the next entry
- for name in ["sbsar", "jp2", "j2k"] {
- assert!(h.get_all_by_label(name).last().unwrap().accesskit_node().is_disabled(), "{name} is greyed");
- h.get_all_by_label(name).last().unwrap().scroll_to_me();
- h.run_steps(6);
- let at = h.get_all_by_label(name).last().unwrap().rect().center();
- h.hover_at(at);
- h.run_steps(30);
- assert!(h.query_by_label("Not available yet").is_some(), "{name} at {at:?}");
+ assert!(h.get_all_by_label("sbsar").last().unwrap().accesskit_node().is_disabled(), "sbsar is greyed");
+ h.get_all_by_label("sbsar").last().unwrap().scroll_to_me();
+ h.run_steps(6);
+ let at = h.get_all_by_label("sbsar").last().unwrap().rect().center();
+ h.hover_at(at);
+ h.run_steps(30);
+ assert!(h.query_by_label("Not available yet").is_some(), "sbsar at {at:?}");
+ for name in ["j2k", "jp2", "psd"] {
+ assert!(!h.get_all_by_label(name).last().unwrap().accesskit_node().is_disabled(), "{name} can be picked");
}
- assert!(!h.get_all_by_label("psd").last().unwrap().accesskit_node().is_disabled());
}
#[test]
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 7873145d..c3a44fc8 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -74,7 +74,7 @@ and names it in `warnings`. Materials omit any map with incomplete tiles or a UD
shared by different sets.
`format` accepts the export window's names (`bmp`, `jpeg`, `jng`, `pgm`, `png`, `targa`, `tiff`,
-`hdr`, `exr`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for
+`hdr`, `exr`, `j2k`, `jp2`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for
TIFF, EXR and HDR. `dithering: true` dithers 8-bit integer output with an ordered pattern, and
`export.plan` reports the effective setting and per-file dimensions (`size` and `sourceSize`, both in pixels). `padding: "diffusion"` dilates by
`dilation` texels and fills the remaining space with a smooth blend of the island colours.
diff --git a/docs/features.md b/docs/features.md
index 42ea07a6..3da74d2d 100644
--- a/docs/features.md
+++ b/docs/features.md
@@ -164,7 +164,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
- **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map),
Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz,
anisotropy, transmission and subsurface maps), separate maps, mesh maps and document channels, in
- PNG, JPEG, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16
+ PNG, JPEG, JPEG 2000, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16
bits or 32-bit float (TIFF, EXR, HDR; 16-bit half float for EXR), with UV padding (dilation,
infinite, or dilation + diffusion), size override and OpenGL or DirectX normals.
- **Output template editor:** build your own presets with per-channel packing, converted maps and per-channel inversion,
From c561a0578fcaac25490603bdb005f35d6efdddde Mon Sep 17 00:00:00 2001
From: Rebornim <250083243+Rebornim@users.noreply.github.com>
Date: Wed, 25 Nov 2026 00:44:12 +0000
Subject: [PATCH 027/138] Export: PSD file type writes every output map of a
texture set as a layer of one file
The layers and the merged image are written with craft-psd's PsdBuilder. The USD asset and MaterialX leave the PSD out (with a warning for the USD asset).
---
crates/engine/src/file_cmds.rs | 19 +-
crates/engine/tests/it/materialx.rs | 4 +-
crates/engine/tests/it/usd_asset.rs | 13 +
crates/formats/src/export/layered_psd.rs | 112 +++++++
crates/formats/src/export/map_renderer.rs | 149 +++++++++
crates/formats/src/export/mod.rs | 370 +++++++++------------
crates/formats/src/export/planned_layer.rs | 10 +
crates/formats/src/export/rendered_map.rs | 13 +
crates/formats/src/export/tests.rs | 130 +++++---
crates/formats/src/mesh_export/usd.rs | 10 +-
crates/ui-egui/src/export_templates.rs | 21 +-
crates/ui-egui/src/export_window.rs | 44 ++-
12 files changed, 608 insertions(+), 287 deletions(-)
create mode 100644 crates/formats/src/export/layered_psd.rs
create mode 100644 crates/formats/src/export/map_renderer.rs
create mode 100644 crates/formats/src/export/planned_layer.rs
create mode 100644 crates/formats/src/export/rendered_map.rs
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index d13dbee3..70194399 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -58,7 +58,7 @@ pub fn specs() -> Vec {
"Export textures",
["File"],
None,
- "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|j2k|jp2|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}",
+ "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|j2k|jp2|webp|psd (or the extension; the maps written as psd are the layers of one _.psd per texture set and UV tile, which the USD asset and MaterialX don't read), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}",
always,
export_textures
),
@@ -76,7 +76,7 @@ pub fn specs() -> Vec {
"List export outputs",
[],
None,
- "{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, format, bitDepth, dithering, size, sourceSize, warnings}] (keeps the first file per case-insensitive name and warns about later duplicates)",
+ "{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, format, bitDepth, dithering, size, sourceSize, warnings, layers: [{map, name}] (a PSD's maps, top first)}] (keeps the first file per case-insensitive name and warns about later duplicates)",
always,
plan
),
@@ -457,6 +457,7 @@ fn plan(session: &mut Session, params: &Value) -> Result {
"size": size,
"sourceSize": source_size,
"warnings": output.warnings,
+ "layers": output.layers.iter().map(|layer| json!({ "map": layer.map, "name": layer.name })).collect::>(),
}));
}
}
@@ -763,7 +764,7 @@ fn usd_asset_param(session: &Session, params: &Value, options: &ExportOptions, s
/// warning: the textures of the command are already written.
#[cfg(not(target_arch = "wasm32"))]
fn write_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport], warnings: &mut Vec) -> Option {
- match build_usd_asset(session, dir, exports) {
+ match build_usd_asset(session, dir, exports, warnings) {
Ok(path) => Some(path),
Err(error) => {
warnings.push(format!("{USD_ASSET_FAILED}: {error}"));
@@ -773,7 +774,7 @@ fn write_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAsset
}
#[cfg(not(target_arch = "wasm32"))]
-fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport]) -> Result {
+fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport], warnings: &mut Vec) -> Result {
use texturecraft_formats::{list_outputs, usd_layer_with_textures, usd_texture_bindings};
let project = &session.doc.project;
let mesh_name = stem_of(project.mesh.trim_start_matches("builtin:"));
@@ -794,6 +795,12 @@ fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAsset
// A map that lost any file (a tile of a UDIM map) is not bound: its `` name would read a file it does not own
kept.retain(|file| !skipped_maps.contains(&file.map));
+ if kept.iter().any(|file| file.format == FileFormat::Psd) {
+ let warning = format!("The USD asset doesn't read PSD files, so the material of texture set \"{}\" leaves out its PSD maps", texture_set.name);
+ if !warnings.contains(&warning) {
+ warnings.push(warning);
+ }
+ }
by_set.entry(set).or_insert_with(|| usd_texture_bindings(texture_set, options, project.normal_format, &kept));
}
}
@@ -841,7 +848,7 @@ fn reserve_export_names(
plans.retain(|plan| {
let name = plan.name.to_ascii_lowercase();
if reserved_patterns.iter().any(|pattern| udim_matches(pattern, &name)) {
- blocked_maps.insert(plan.map);
+ blocked_maps.extend(plan.maps());
warnings.push(format!(
"\"{}\" was not written: an earlier MaterialX document uses that UDIM pattern. Rename a texture set or change the template file names",
plan.name
@@ -854,7 +861,7 @@ fn reserve_export_names(
return true;
}
- blocked_maps.insert(plan.map);
+ blocked_maps.extend(plan.maps());
if fallback {
warnings.push(format!(
"MaterialX: \"{}\" was not written: a file of the chosen template or of an earlier command of this export has the name. Rename a texture set or change the template file names",
diff --git a/crates/engine/tests/it/materialx.rs b/crates/engine/tests/it/materialx.rs
index b69391bd..3f6ba0a9 100644
--- a/crates/engine/tests/it/materialx.rs
+++ b/crates/engine/tests/it/materialx.rs
@@ -197,8 +197,10 @@ fn a_file_type_a_material_cannot_use_falls_back_to_png() {
)
.unwrap();
+ // A PSD holds every map of the texture set as a layer
let all = names(&result);
- assert!(all.iter().any(|f| f.ends_with(&format!("_baseColor.{ext}"))), "{format}: the template's files keep the file type: {all:?}");
+ let template_file = if format == "psd" { ".psd".to_string() } else { format!("_baseColor.{ext}") };
+ assert!(all.iter().any(|f| f.ends_with(&template_file)), "{format}: the template's files keep the file type: {all:?}");
let mtlx = files(&result).into_iter().find(|f| f.ends_with(".mtlx")).unwrap_or_else(|| panic!("{format}: no .mtlx in {all:?}"));
let text = std::fs::read_to_string(mtlx).unwrap();
let wanted = if format == "tiff" { "tif" } else { "png" };
diff --git a/crates/engine/tests/it/usd_asset.rs b/crates/engine/tests/it/usd_asset.rs
index e6ef7bd9..a370c7e1 100644
--- a/crates/engine/tests/it/usd_asset.rs
+++ b/crates/engine/tests/it/usd_asset.rs
@@ -407,3 +407,16 @@ fn a_mesh_without_materials_gets_a_material_bound_to_the_default_texture_set() {
assert!(dir.join(&read.file).is_file(), "{} was written", read.file);
}
}
+
+#[test]
+fn a_psd_of_layers_is_left_out_of_the_materials_and_said_so() {
+ let mut s = ball();
+ let dir = temp("psd");
+
+ let r = export(&mut s, &dir, json!({"ts": 0, "format": "psd", "usdAsset": true}));
+
+ assert!(files(&r).iter().any(|f| f.ends_with(".psd")), "{r}");
+ let materials = read_back(&s, &dir);
+ assert!(materials[material_of(&s, 0)].0.is_empty(), "no input reads the PSD's merged image: {:?}", materials[material_of(&s, 0)]);
+ assert!(r["warnings"].to_string().contains("doesn't read PSD files"), "{r}");
+}
diff --git a/crates/formats/src/export/layered_psd.rs b/crates/formats/src/export/layered_psd.rs
new file mode 100644
index 00000000..e90f8e6e
--- /dev/null
+++ b/crates/formats/src/export/layered_psd.rs
@@ -0,0 +1,112 @@
+//! A texture set's PSD: each output map a layer, a `/` in its name a layer group
+
+use craft_psd::{Compression, GroupSpec, LayerSpec, PixelData, PsdBuilder};
+use texturecraft_texel::linear_to_srgb;
+
+use super::encoding::Encoding;
+use super::map_renderer::MapRenderer;
+use super::{ExportedFile, FileFormat, PSD_MAX_FILE_BYTES, PSD_RGBA_PLANES, PlannedFile, quantize_integer};
+use crate::{FormatError, Result};
+
+/// Where alpha sits in an RGBA texel
+const ALPHA_INDEX: usize = 3;
+
+/// Render the layers of `planned` one at a time and write them as one PSD
+pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile) -> Result {
+ let PlannedFile { name, tile, bit_depth, mut warnings, layers, .. } = planned;
+ let size = renderer.size(tile)?;
+
+ // Each layer as straight RGBA in 0-1, sRGB-encoded where the map's file would be, dropped once quantized
+ let mut composite = vec![0.0f32; size.0 as usize * size.1 as usize * PSD_RGBA_PLANES];
+ let mut pixels = Vec::with_capacity(layers.len());
+ let mut embedded = None;
+ for layer in layers.iter().rev() {
+ let map = renderer.render(layer.map, tile, FileFormat::Psd, bit_depth)?;
+ embedded = map.embed.or(embedded);
+ let rgba = to_rgba(&map.data, map.component_count, &map.srgb);
+ drop(map);
+ over(&mut composite, &rgba);
+ let encoding = Encoding { format: FileFormat::Psd, depth: bit_depth, dither: layer.dither };
+ let bytes = quantize_integer(encoding, size.0, PSD_RGBA_PLANES, rgba.into_iter())?;
+ pixels.push((layer.name.as_str(), pixel_data(bytes, bit_depth)));
+ }
+ if let Some(space) = embedded {
+ warnings.push(format!("PSD export does not embed a colour space; the colours are in {}", space.name()));
+ }
+
+ let encoding = Encoding { format: FileFormat::Psd, depth: bit_depth, dither: false };
+ let composite = pixel_data(quantize_integer(encoding, size.0, PSD_RGBA_PLANES, composite.into_iter())?, bit_depth);
+
+ let bytes = write_layers(size, bit_depth, pixels, composite).map_err(|error| FormatError::Invalid(format!("psd encoding failed: {error}")))?;
+ if bytes.len() as u64 >= PSD_MAX_FILE_BYTES {
+ return Err(FormatError::Invalid(format!("\"{name}\" would reach the 2 GiB PSD file limit; use a smaller export size or fewer PSD maps")));
+ }
+
+ Ok(ExportedFile { name, bytes, width: size.0, height: size.1, warnings })
+}
+
+/// L, LA, RGB or RGBA samples as RGBA (gray repeated, opaque without alpha), sRGB transfer applied to the components `srgb` marks, values clamped to 0-1
+fn to_rgba(data: &[f32], component_count: usize, srgb: &[bool]) -> Vec {
+ let encode = |component: usize, value: f32| if srgb.get(component).copied().unwrap_or(false) { linear_to_srgb(value) } else { value.clamp(0.0, 1.0) };
+ data.chunks_exact(component_count.max(1))
+ .flat_map(|texel| {
+ let encoded = |component| encode(component, texel.get(component).copied().unwrap_or(0.0));
+ match component_count {
+ 1 => [encoded(0), encoded(0), encoded(0), 1.0],
+ 2 => [encoded(0), encoded(0), encoded(0), encoded(1)],
+ 3 => [encoded(0), encoded(1), encoded(2), 1.0],
+ _ => [encoded(0), encoded(1), encoded(2), encoded(3)],
+ }
+ })
+ .collect()
+}
+
+/// Lay straight-alpha RGBA `layer` over `below`, in place
+fn over(below: &mut [f32], layer: &[f32]) {
+ for (under, top) in below.as_chunks_mut::().0.iter_mut().zip(layer.as_chunks::().0) {
+ let (top_alpha, under_alpha) = (top[ALPHA_INDEX], under[ALPHA_INDEX]);
+ let alpha = top_alpha + under_alpha * (1.0 - top_alpha);
+ if alpha <= 0.0 {
+ continue;
+ }
+
+ for (value, top_value) in under.iter_mut().zip(top).take(ALPHA_INDEX) {
+ *value = (top_value * top_alpha + *value * under_alpha * (1.0 - top_alpha)) / alpha;
+ }
+ under[ALPHA_INDEX] = alpha;
+ }
+}
+
+/// Native-endian quantized RGBA samples as the PSD builder takes them
+fn pixel_data(bytes: Vec, depth: u8) -> PixelData {
+ if depth == 16 { PixelData::Rgba16(bytes.as_chunks::<2>().0.iter().map(|sample| u16::from_ne_bytes(*sample)).collect()) } else { PixelData::Rgba8(bytes) }
+}
+
+/// An RGB PSD of `layers` (bottom first, each named by its `/`-separated group path) over the merged `composite`, uncompressed so its size is known up front
+pub(super) fn write_layers((width, height): (u32, u32), depth: u8, layers: Vec<(&str, PixelData)>, composite: PixelData) -> craft_psd::Result> {
+ let mut builder = PsdBuilder::new(width, height).depth(u16::from(depth)).compression(Compression::Raw);
+
+ // The builder stacks bottom up, so the groups open and close in that order too
+ let mut open: Vec<&str> = Vec::new();
+ for (path, pixels) in layers {
+ let mut parts: Vec<&str> = path.split('/').collect();
+ let name = parts.pop().unwrap_or_default();
+ let shared = open.iter().zip(&parts).take_while(|(open, part)| open == part).count();
+ for _ in shared..open.len() {
+ builder.end_group()?;
+ }
+ open.truncate(shared);
+ for group in parts.iter().skip(shared) {
+ builder.begin_group(GroupSpec::new(*group));
+ open.push(group);
+ }
+
+ builder.push_layer(LayerSpec::new(name, 0, 0, width, height, pixels));
+ }
+ for _ in open {
+ builder.end_group()?;
+ }
+
+ builder.composite(composite);
+ builder.to_bytes()
+}
diff --git a/crates/formats/src/export/map_renderer.rs b/crates/formats/src/export/map_renderer.rs
new file mode 100644
index 00000000..c19064c5
--- /dev/null
+++ b/crates/formats/src/export/map_renderer.rs
@@ -0,0 +1,149 @@
+use rayon::prelude::*;
+use texturecraft_core::{TextureSet, TileGrid};
+use texturecraft_texel::{ColorSpace, DilationMap};
+
+use super::rendered_map::RenderedMap;
+use super::{At, Dest, ExportInput, ExportOptions, FileFormat, Padding, Sampler, diffuse_blocks, layout, resize, scale_export_side, tile_side};
+use crate::{FormatError, MAX_IMAGE_SIZE, Result};
+
+/// Renders the output maps of one texture set's export: the padding and sampling every map shares
+pub(super) struct MapRenderer<'a> {
+ options: &'a ExportOptions,
+ set: &'a TextureSet,
+ sampler: Sampler<'a>,
+ dilation_map: Option,
+ grid: Option,
+ /// The composite's size
+ width: u32,
+ height: u32,
+ /// Texels per atlas block (the width for a set without UV tiles)
+ tile_res: u32,
+}
+
+impl<'a> MapRenderer<'a> {
+ pub(super) fn new(input: &ExportInput<'a>, options: &'a ExportOptions) -> Result> {
+ let set = input.project.texture_set(input.ts)?;
+ let (width, height) = (input.composite.resolution, input.composite.height);
+ let grid = set.tile_grid();
+ let tile_res = width / grid.map_or(1, |g| g.cols.max(1));
+ if tile_res == 0 || tile_res > MAX_IMAGE_SIZE || height != tile_res * grid.map_or(1, |g| g.rows) {
+ return Err(FormatError::Invalid(format!("composite size {width}×{height} does not fit texture set \"{}\"", set.name)));
+ }
+
+ if input.coverage.len() != width as usize * height as usize {
+ return Err(FormatError::Invalid(format!("coverage has {} texels, expected {width}×{height}", input.coverage.len())));
+ }
+
+ // Padding stays inside each UV tile
+ let dilation_map = match options.padding {
+ Padding::None => None,
+ Padding::Dilation(d) | Padding::DilationDefault(d) | Padding::DilationDiffusion(d) => {
+ Some(DilationMap::in_blocks(input.coverage, width, height, Some(d), tile_res))
+ }
+ Padding::Infinite => Some(DilationMap::in_blocks(input.coverage, width, height, None, tile_res)),
+ };
+ let sampler = Sampler {
+ set,
+ comp: input.composite,
+ baked: input.baked,
+ coverage: input.coverage,
+ res: width,
+ tile_res,
+ scales: set.block_scales(),
+ normal_override: options.normal_format,
+ project_normal: input.project.normal_format,
+ };
+ Ok(MapRenderer { options, set, sampler, dilation_map, grid, width, height, tile_res })
+ }
+
+ /// The export size of a file of `tile` (None: the whole set).
+ pub(super) fn size(&self, tile: Option) -> Result<(u32, u32)> {
+ let (_, _, w, h) = self.region(tile)?;
+
+ // An atlas scales by the requested size per tile
+ let scale = |value| scale_export_side(value, self.tile_res, self.options.size);
+ Ok((scale(w), scale(h)))
+ }
+
+ /// The composite texels a file of `tile` covers: one tile, or the whole set
+ fn region(&self, tile: Option) -> Result<(u32, u32, u32, u32)> {
+ match (tile, self.grid) {
+ (Some(t), Some(g)) => {
+ let (bx, by) = g.block(t).ok_or_else(|| FormatError::Invalid(format!("UV tile {t} is not in the set's grid")))?;
+
+ // A tile smaller than its block fills the block's top-left corner
+ let side = tile_side(self.set, t, self.tile_res);
+ Ok((bx * self.tile_res, by * self.tile_res, side, side))
+ }
+ _ => Ok((0, 0, self.width, self.height)),
+ }
+ }
+
+ /// Map `map_index` of the preset for `tile`, as `format` at `bit_depth` holds it
+ pub(super) fn render(&self, map_index: usize, tile: Option, format: FileFormat, bit_depth: u8) -> Result {
+ let options = self.options;
+ let map = options.preset.maps.get(map_index).ok_or_else(|| FormatError::Invalid("planned map out of range".into()))?;
+ let channel_layout = layout(self.set, map);
+ let component_count = channel_layout.len();
+ let inverted: Vec = channel_layout.iter().map(|(d, _)| map.inverted.contains(d)).collect();
+ let (x0, y0, w, h) = self.region(tile)?;
+ let size = self.size(tile)?;
+ let sampler = &self.sampler;
+ let dilation_map = self.dilation_map.as_ref();
+ let beyond_default = matches!(options.padding, Padding::DilationDefault(_) | Padding::Infinite);
+
+ let mut data = vec![0.0f32; w as usize * h as usize * component_count];
+ data.par_chunks_mut(w as usize * component_count).enumerate().for_each(|(row_y, row)| {
+ let y = y0 + row_y as u32;
+ for (column, x) in (x0..x0 + w).enumerate() {
+ let at = if sampler.covered(x, y) {
+ Some(At::Texel(x, y))
+ } else {
+ match dilation_map.and_then(|d| d.source(x, y)) {
+ Some((sx, sy)) => Some(At::Texel(sx, sy)),
+ None => beyond_default.then_some(At::Default),
+ }
+ };
+ let Some(at) = at else { continue };
+ let mut cache = None;
+ for (component, (_, source)) in channel_layout.iter().enumerate() {
+ if let Some(value) = row.get_mut(column * component_count + component) {
+ let sample = sampler.sample(source, at, &mut cache);
+ *value = if inverted.get(component).copied().unwrap_or(false) { 1.0 - sample } else { sample };
+ }
+ }
+ }
+ });
+
+ // Diffuse into the texels the dilation did not reach
+ if matches!(options.padding, Padding::DilationDiffusion(_)) {
+ let known: Vec = (y0..y0 + h)
+ .flat_map(|y| (x0..x0 + w).map(move |x| (x, y)))
+ .map(|(x, y)| sampler.covered(x, y) || dilation_map.is_some_and(|d| d.source(x, y).is_some()))
+ .collect();
+
+ // Keep diffusion within each UV tile when rendering an atlas
+ let block = if tile.is_none() && self.grid.is_some() { self.tile_res } else { w.max(h) };
+ diffuse_blocks(&mut data, (w as usize, h as usize), component_count, &known, block as usize);
+ }
+
+ let mut data = resize(data, (w, h), component_count, size);
+
+ // Integer sRGB converts in `encode`; other color spaces convert here
+ let space = options.space_for_map(map, format, bit_depth);
+ let float = format.holds_float(bit_depth);
+ let convert = (space != ColorSpace::Srgb || float) && space != ColorSpace::LinearRec709;
+ if convert {
+ data.par_chunks_mut(component_count).for_each(|px| {
+ if let [r, g, b, ..] = px {
+ [*r, *g, *b] = space.from_linear_rec709([*r, *g, *b]);
+ }
+ });
+ }
+ let srgb = channel_layout.iter().map(|(d, _)| *d != Dest::A && !float && space == ColorSpace::Srgb).collect();
+
+ // A colour space the user chose is written into the colour maps (data maps have none)
+ let embed = (options.color_space.is_some() && map.is_color() && component_count >= 3).then_some(space);
+ Ok(RenderedMap { data, size, component_count, srgb, embed })
+ }
+}
diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs
index de1454fc..6a07413e 100644
--- a/crates/formats/src/export/mod.rs
+++ b/crates/formats/src/export/mod.rs
@@ -21,15 +21,21 @@ use serde::{Deserialize, Serialize};
use texturecraft_compose::{BakedMaps, Composite};
use texturecraft_core::{AoMixing, BakedMap, BlockScales, Channel, ChannelKind, NormalFormat, NormalMixing, Project, TextureSet};
use texturecraft_geom::glam::Vec3;
-use texturecraft_texel::{ColorSpace, DilationMap, linear_to_srgb};
+use texturecraft_texel::{ColorSpace, linear_to_srgb};
use crate::{FormatError, MAX_IMAGE_SIZE, Result};
mod encoding;
mod jpeg2000;
+mod layered_psd;
mod map_override;
+mod map_renderer;
+mod planned_layer;
+mod rendered_map;
use encoding::Encoding;
pub use map_override::MapOverride;
+use map_renderer::MapRenderer;
+pub use planned_layer::PlannedLayer;
/// Height-to-normal slope: with strength 1, a height change of 1 across 1/16 of the texture
/// width tilts the normal 45°, at any resolution.
@@ -37,6 +43,8 @@ const HEIGHT_SPAN: f32 = 16.0;
const JPEG_QUALITY: u8 = 95;
const PSD_MAX_SIDE_PIXELS: u32 = 30_000;
const PSD_MAX_FILE_BYTES: u64 = 2 * 1024 * 1024 * 1024;
+/// Planes of a PSD image or layer: red, green, blue and alpha
+const PSD_RGBA_PLANES: usize = 4;
/// Preset limits (user presets are untrusted JSON).
const MAX_MAPS: usize = 64;
const MAX_TEMPLATE: usize = 256;
@@ -92,7 +100,7 @@ pub enum FileFormat {
Jng,
/// Portable graymap (binary).
Pgm,
- /// A PSD containing only its merged image.
+ /// Photoshop document: every output map of a texture set in this format as a layer of one file
Psd,
/// JPEG 2000 codestream, lossless
J2k,
@@ -517,6 +525,16 @@ pub struct PlannedFile {
/// covers every tile refers to); None when the file isn't tiled.
pub udim_name: Option,
pub warnings: Vec,
+ /// A PSD's output maps, top layer first (`map` is the first); empty for a file of one map
+ pub layers: Vec,
+}
+
+impl PlannedFile {
+ /// The output maps the file writes
+ pub fn maps(&self) -> impl Iterator + '_ {
+ let own = self.layers.is_empty().then_some(self.map);
+ own.into_iter().chain(self.layers.iter().map(|layer| layer.map))
+ }
}
// ---------------------------------------------------------------------------------------------
@@ -592,8 +610,7 @@ pub fn sanitize_file_path(s: &str) -> String {
s.split('/').map(sanitize_file_stem).collect::>().join("/")
}
-/// The files `opts` produces for texture set `ts`, without rendering (for the export dialog).
-/// Template variables: [`FILE_TOKENS`].
+/// The files `opts` produces for texture set `ts` without rendering ([`FILE_TOKENS`] are the template variables); PSD maps are layers of one file
pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOptions) -> Result> {
opts.preset.validate()?;
let set = project.texture_set(ts)?;
@@ -607,9 +624,10 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
let mut active_files = BTreeSet::new();
let mut active_dirs = BTreeSet::new();
let mut out = Vec::new();
+
+ // Maps written as PSD layers, with their tile, bit depth and warnings
+ let mut psd_layers: Vec<(Option, PlannedLayer, u8, Vec)> = Vec::new();
let tiles: Vec