Merge remote-tracking branch 'origin/main' into fix/wasm-size-profile

This commit is contained in:
FredApps committed 2026-11-28 09:16:22 +01:00
commit e70e4cbf84
20 files changed
+619 -83

No files matched your search

+3
View File
@@ -30,6 +30,9 @@ licensed and keep their license file next to them.
| `crates/formats/src/mesh_import/usd/fixtures/crafted-references.usdc` | Synthetic USDC class/reference/time-sample acceptance fixture | ArtCraft Team and craft-libs contributors | [Pinned generator and provenance](crates/formats/src/mesh_import/usd/fixtures/README.md) | MIT (`crates/formats/src/mesh_import/usd/fixtures/LICENSE-MIT`) |
| `apps/texturecraft/src/xwayland_pen.rs` | Pen on Wayland opens the window through Xwayland: pen detection, the Xwayland decision and the X11 library check (adapted, reduced to the pen decision) | PhotoCraft contributors | storytold/photocraft `830316b775f1f6734498ac6e39fd1298955ff93f`: [`apps/photocraft/src/tablet.rs`](https://github.com/storytold/photocraft/blob/830316b775f1f6734498ac6e39fd1298955ff93f/apps/photocraft/src/tablet.rs), [`apps/photocraft/src/linux_libs.rs`](https://github.com/storytold/photocraft/blob/830316b775f1f6734498ac6e39fd1298955ff93f/apps/photocraft/src/linux_libs.rs) | MIT OR Apache-2.0 |
Native autosave recovery uses `same-file` to compare file identities. Copyright (c) 2017 Andrew Gallant.
The crate is available under Unlicense OR MIT. [Upstream source and licences](https://github.com/BurntSushi/same-file)
## Third-party assets compiled into the binary
These come from Rust crate dependencies (not files in this repository) and keep their licenses.
Generated
+1
View File
@@ -6179,6 +6179,7 @@ dependencies = [
"raw-window-handle",
"rayon",
"rfd",
"same-file",
"serde",
"serde_json",
"skera",
+3
View File
@@ -26,6 +26,9 @@ Studio Small 09 HDR environment (assets/hdr/studio_small_09_512.hdr),
by Sergej Majboroda (Poly Haven) — CC0-1.0.
Source: https://polyhaven.com/a/studio_small_09 (1K HDR, reduced to 512x256).
Native autosave file identity checks use same-file (Unlicense OR MIT).
Copyright (c) 2017 Andrew Gallant.
Native eyedropper components:
- raw-window-handle — MIT OR Apache-2.0 OR Zlib. Copyright (c) 2019, 2020 Osspial.
- winsafe — MIT. Copyright (c) 2019-present, Rodrigo Cesar de Freitas Dias.
+37 -1
View File
@@ -1,4 +1,4 @@
//! Project-level commands: new project, sample project, smart materials, inspection.
//! Project-level commands: new project, rename, sample project, smart materials, inspection.
use serde_json::{Value, json};
use texturecraft_compose::BakedMaps;
@@ -9,6 +9,9 @@ use crate::commands::{CommandSpec, always, bad, boolp, strp, u64p};
use crate::materials::Place;
use crate::{Result, Session, cmd};
/// Longest project name, in characters; it goes into export file names.
pub const MAX_PROJECT_NAME_CHARS: usize = 128;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
@@ -22,6 +25,15 @@ pub fn specs() -> Vec<CommandSpec> {
),
cmd!("project.sample", "Open sample project", ["File"], None, "{}", always, sample),
cmd!("project.inspect", "Inspect project", [], None, "{}", always, |s, _| Ok(crate::inspect::session(s))),
cmd!(
"project.rename",
"Rename project",
[],
None,
"{name: 1-128 characters without control characters} — the name `$project` stands for in export file names; the project file keeps its own name",
always,
rename
),
cmd!(
"material.apply",
"Add smart material",
@@ -51,6 +63,30 @@ fn new(s: &mut Session, p: &Value) -> Result<Value> {
Ok(crate::inspect::session(s))
}
/// Trim and validate a proposed name without changing the project.
pub fn validate_project_name(name: &str) -> Result<&str> {
let name = name.trim();
if name.is_empty() || name.chars().nth(MAX_PROJECT_NAME_CHARS).is_some() || name.chars().any(char::is_control) {
return Err(bad("project.rename", format!("`name` must be 1-{MAX_PROJECT_NAME_CHARS} characters without control characters")));
}
Ok(name)
}
fn rename(session: &mut Session, params: &Value) -> Result<Value> {
let name = validate_project_name(strp(params, "name").unwrap_or_default())?;
// The same name is not an undo step and leaves a saved project unmodified
if name != session.doc.project.name {
session.edit("Rename project", |session| {
session.doc.project.name = name.to_owned();
Ok(())
})?;
}
Ok(json!({ "name": name }))
}
fn material(s: &mut Session, p: &Value) -> Result<Value> {
let id = strp(p, "material").ok_or_else(|| bad("material.apply", "`material` is required"))?;
let l = crate::materials::apply_at(s, id, Place::from_params(p))?;
+1
View File
@@ -67,6 +67,7 @@ mod perf;
mod polygon_fill;
mod project_recovery;
mod rebuilt_uv_layout;
mod rename_project;
mod resource_updater;
mod resources_used;
mod sample;
+20 -10
View File
@@ -523,19 +523,29 @@ fn sets_with_the_same_file_name_warn_instead_of_overwriting() {
fn a_material_never_points_at_a_texture_kept_for_another_set() {
let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
// The first set's name expands to the same base-colour filename as the second
execute(&mut session, "textureSet.rename", &json!({"ts": 0, "name": "$channel"})).unwrap();
execute(&mut session, "textureSet.rename", &json!({"ts": 1, "name": "baseColor"})).unwrap();
execute(&mut session, "textureSet.rename", &json!({"ts": 0, "name": "body"})).unwrap();
execute(&mut session, "textureSet.rename", &json!({"ts": 1, "name": "trim"})).unwrap();
let directory = temp("shared-map");
let result = export(&mut session, &directory, OPENPBR, true);
// Give the first set a map with the same filename as the second set's canonical base colour
let mut preset = texturecraft_engine::formats::builtin_preset(OPENPBR).unwrap();
let mut conflicting_map = preset.maps.iter().find(|map| map.file.ends_with("_base_color")).unwrap().clone();
let conflicting_stem = "material_ball_trim_base_color";
conflicting_map.file = conflicting_stem.into();
preset.maps.push(conflicting_map);
let materials: Vec<_> = files(&result).into_iter().filter(|path| path.ends_with(".mtlx")).collect();
assert!(materials.len() >= 2, "{result}");
assert!(std::fs::read_to_string(&materials[0]).unwrap().contains("material_ball_baseColor_base_color.png"));
for material in materials.iter().skip(1) {
assert!(!std::fs::read_to_string(material).unwrap().contains("material_ball_baseColor_base_color.png"), "{material}");
}
let result =
execute(&mut session, "file.exportTextures", &json!({"dir": directory.display().to_string(), "preset": preset, "ts": [0, 1], "materialX": true}))
.unwrap();
let conflicting_file = format!("{conflicting_stem}.png");
assert!(names(&result).contains(&conflicting_file), "{result}");
assert!(warned(&result, &format!("\"{conflicting_file}\" was not written")), "{result}");
let body = referenced(&std::fs::read_to_string(directory.join("material_ball_body.mtlx")).unwrap());
let trim = referenced(&std::fs::read_to_string(directory.join("material_ball_trim.mtlx")).unwrap());
assert!(body.iter().any(|file| file == "material_ball_body_base_color.png"), "{body:?}");
assert!(trim.iter().any(|file| file.starts_with("material_ball_trim_")), "{trim:?}");
assert!(!trim.contains(&conflicting_file), "{trim:?}");
}
#[test]
+63
View File
@@ -0,0 +1,63 @@
//! `project.rename`: the name `$project` stands for in export file names.
use serde_json::json;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
#[test]
fn a_renamed_project_exports_under_its_new_name_until_undone() {
let mut session = Session::new_project("hero", primitives::cube(2.0), "builtin:cube", None, 128).unwrap();
let mut preset = execute(&mut session, "export.preset.get", &json!({"name": "Document channels + Normal + AO (No Alpha)"})).unwrap();
preset["maps"][0]["file"] = json!("$project_$textureSet");
execute(&mut session, "project.rename", &json!({"name": " Knight final "})).unwrap();
let plan = execute(&mut session, "export.plan", &json!({"preset": preset})).unwrap();
let renamed_file = plan[0]["file"].as_str().unwrap();
assert!(renamed_file.starts_with("Knight_final_"), "{renamed_file}");
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
assert_eq!(reopened.doc.project.name, "Knight final");
execute(&mut session, "edit.undo", &json!({})).unwrap();
let plan = execute(&mut session, "export.plan", &json!({"preset": preset})).unwrap();
assert_eq!(session.doc.project.name, "hero");
let restored_file = plan[0]["file"].as_str().unwrap();
assert!(restored_file.starts_with("hero_"), "{restored_file}");
}
#[test]
fn an_unusable_or_unchanged_project_name_edits_nothing() {
use texturecraft_engine::project_cmds::MAX_PROJECT_NAME_CHARS;
let mut session = Session::new_project("hero", primitives::cube(2.0), "builtin:cube", None, 128).unwrap();
for name in [json!(null), json!(7), json!(" "), json!("a\nb"), json!("界".repeat(MAX_PROJECT_NAME_CHARS + 1))] {
assert!(execute(&mut session, "project.rename", &json!({"name": name})).is_err(), "{name}");
}
execute(&mut session, "project.rename", &json!({"name": "hero"})).unwrap();
assert_eq!(session.doc.project.name, "hero");
assert!(!session.modified, "nothing changed");
assert!(!session.can_undo());
let at_limit = "界".repeat(MAX_PROJECT_NAME_CHARS);
let result = execute(&mut session, "project.rename", &json!({"name": format!(" {at_limit} ")})).unwrap();
assert_eq!(result["name"], at_limit);
}
#[test]
fn a_renamed_project_is_inserted_into_the_template_as_literal_text() {
let mut session = Session::new_project("hero", primitives::cube(2.0), "builtin:cube", None, 128).unwrap();
let mut preset = execute(&mut session, "export.preset.get", &json!({"name": "Document channels + Normal + AO (No Alpha)"})).unwrap();
preset["maps"][0]["file"] = json!("$project/$mesh");
execute(&mut session, "project.rename", &json!({"name": "Knight/$mesh"})).unwrap();
let plan = execute(&mut session, "export.plan", &json!({"preset": preset})).unwrap();
let file = plan[0]["file"].as_str().unwrap();
assert!(file.starts_with("Knight__mesh/cube."), "{file}");
}
+38 -9
View File
@@ -717,8 +717,32 @@ fn disambiguated_psd_stem(stem: &str, set_index: usize, limit: usize, taken: imp
}
/// [`sanitize_file_stem`] for each `/`-separated folder name and the file stem.
pub fn sanitize_file_path(s: &str) -> String {
s.split('/').map(sanitize_file_stem).collect::<Vec<_>>().join("/")
pub fn sanitize_file_path(path: &str) -> String {
if !path.contains('/') {
return sanitize_file_stem(path);
}
path.split('/').map(sanitize_file_stem).collect::<Vec<_>>().join("/")
}
/// Expand tokens in the template while keeping the substituted values literal.
fn expand_file_template(template: &str, variables: &[(&str, &str)]) -> String {
let mut expanded = String::with_capacity(template.len());
let mut remaining = template;
while let Some(index) = remaining.find('$') {
let (literal, variable) = remaining.split_at(index);
expanded.push_str(literal);
if let Some((value, tail)) = variables.iter().find_map(|&(token, value)| variable.strip_prefix(token).map(|tail| (value, tail))) {
expanded.push_str(value);
remaining = tail;
} else {
expanded.push('$');
remaining = &variable[1..];
}
}
expanded.push_str(remaining);
expanded
}
/// The files `opts` produces for texture set `ts` without rendering ([`FILE_TOKENS`] are the template variables); PSD maps are layers of one file
@@ -773,14 +797,19 @@ fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOpti
} else {
std::borrow::Cow::Borrowed(map.file.as_str())
};
let channel = channel_label(map);
let expand_stem = |udim: &str| {
let expanded = template
.replace("$udim", udim)
.replace("$project", &project_stem)
.replace("$mesh", &mesh_stem)
.replace("$textureSet", &set_stem)
.replace("$channel", channel_label(map))
.replace("$colorSpace", color_space);
let expanded = expand_file_template(
&template,
&[
("$udim", udim),
("$project", &project_stem),
("$mesh", &mesh_stem),
("$textureSet", &set_stem),
("$channel", channel),
("$colorSpace", color_space),
],
);
sanitize_file_path(&expanded)
};
+4
View File
@@ -41,6 +41,10 @@ tempfile = "3"
# Whether the app runs in a real window, where an eyedropper pick may take clicks outside it (screen_pick).
raw-window-handle = "0.6"
[target.'cfg(all(not(unix), not(target_arch = "wasm32")))'.dependencies]
# Compare filesystem identities on native platforms without Unix device and inode metadata
same-file = "1"
# An eyedropper click outside the window (screen_pick): a low-level mouse hook and the eyedropper as the system pointer
# (winsafe, MIT) and one desktop pixel through GDI (xcap, Apache-2.0).
[target.'cfg(windows)'.dependencies]
+119 -39
View File
@@ -1,46 +1,67 @@
//! Where a project's autosave copy goes. Each project has a file of its own, `<stem>-copy-<suffix>.tcraft`: a project's
//! name comes from its mesh file, so the name alone would let projects made from one mesh overwrite each other's copy
//! Where a project's autosave copy goes. Each project has a file of its own, `<stem>-copy-<suffix>.tcraft`,
//! even if several projects share a name or a project is renamed.
use std::path::{Path, PathBuf};
use serde_json::Value;
use texturecraft_engine::core::PROJECT_EXT;
use texturecraft_engine::formats::export::sanitize_file_stem;
use crate::TextureCraftApp;
use crate::{TextureCraftApp, user_dir};
/// Hex digits of a copy's suffix
const SUFFIX_DIGITS: usize = 16;
/// Between a copy's stem and its suffix, so a user's own file named like `report-20240115` is not taken for a copy
const COPY_MARK: &str = "-copy-";
const COPY_MARK: &str = "copy";
/// The longest stem kept, so the suffix and the temporary files of a save still fit a file name
const MAX_STEM_CHARS: usize = 170;
impl TextureCraftApp {
/// Detach a recovered project because the original can overwrite its autosave copy.
pub(crate) fn detach_autosave_copy(&mut self) -> bool {
let Some(path) = self.session.path.as_deref() else {
return false;
};
if !is_copy_in(Path::new(path), &user_dir("autosave")) {
return false;
}
self.session.path = None;
self.session.modified = true;
true
}
/// Keep the engine's open reply consistent with the desktop session.
pub(crate) fn recover_file_open(&mut self, command: &str, mut result: Value) -> Value {
if command == "file.open" && self.detach_autosave_copy() {
result["path"] = Value::Null;
result["modified"] = Value::Bool(true);
}
result
}
/// The open project's autosave file in `folder`. A saved project's copy is named after its file and stays the
/// same across restarts; an unsaved project gets one that no other open project or running instance shares
/// same across restarts; an unsaved project's copy keeps its first autosave name until the project is saved
pub(crate) fn autosave_path(&mut self, folder: &Path) -> PathBuf {
let Some(saved) = self.session.path.as_deref() else {
let project = self.session.project_id;
let suffix = match self.unsaved_autosave_suffix {
Some((owner, suffix)) if owner == project => suffix,
_ => {
let suffix = new_suffix(project);
self.unsaved_autosave_suffix = Some((project, suffix));
suffix
}
};
return folder.join(file_name(&self.session.doc.project.name, suffix));
if let Some((owner, name)) = &self.unsaved_autosave_file
&& *owner == project
{
return folder.join(name);
}
let name = file_name(&self.session.doc.project.name, new_suffix(project));
let path = folder.join(&name);
self.unsaved_autosave_file = Some((project, name));
return path;
};
let saved = absolute(Path::new(saved));
// A project opened from its autosave copy keeps writing there, rather than chaining suffixes
if is_copy_in(&saved, &absolute(folder)) {
return saved;
}
let stem = saved.file_stem().map_or_else(|| self.session.doc.project.name.clone(), |stem| stem.to_string_lossy().into_owned());
folder.join(file_name(&stem, hash(saved.as_os_str().as_encoded_bytes())))
}
@@ -48,7 +69,7 @@ impl TextureCraftApp {
fn file_name(stem: &str, suffix: u64) -> String {
let stem: String = sanitize_file_stem(stem).chars().take(MAX_STEM_CHARS).collect();
format!("{stem}{COPY_MARK}{suffix:0SUFFIX_DIGITS$x}.{PROJECT_EXT}")
format!("{stem}-{COPY_MARK}-{suffix:0SUFFIX_DIGITS$x}.{PROJECT_EXT}")
}
/// `path` made absolute, as given when that fails
@@ -56,17 +77,53 @@ fn absolute(path: &Path) -> PathBuf {
std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf())
}
/// `path` with links and, on Windows, the verbatim prefix resolved so two spellings of one folder compare equal; made absolute when that fails
fn resolved(path: &Path) -> PathBuf {
std::fs::canonicalize(path).unwrap_or_else(|_| absolute(path))
/// Compare device and inode without opening the directory or a possible special file.
#[cfg(unix)]
fn same_location(left: &Path, right: &Path) -> bool {
use std::os::unix::fs::MetadataExt;
matches!((left.metadata(), right.metadata()), (Ok(left), Ok(right)) if (left.dev(), left.ino()) == (right.dev(), right.ino()))
}
/// Whether `path` is an autosave copy of `folder`: a project file there whose name ends in the copy mark and a suffix
#[cfg(not(unix))]
fn same_location(left: &Path, right: &Path) -> bool {
same_file::is_same_file(left, right).unwrap_or(false)
}
/// Whether the opened file is a generated autosave in the current profile.
fn is_copy_in(path: &Path, folder: &Path) -> bool {
let suffix = path.file_stem().and_then(|stem| stem.to_str()).and_then(|stem| stem.rsplit_once(COPY_MARK)).map(|(_, suffix)| suffix);
path.parent().is_some_and(|parent| resolved(parent) == resolved(folder))
&& path.extension().is_some_and(|extension| extension == PROJECT_EXT)
&& suffix.is_some_and(|suffix| suffix.len() == SUFFIX_DIGITS && suffix.bytes().all(|digit| digit.is_ascii_hexdigit()))
let Some(extension) = path.extension().filter(|extension| extension.eq_ignore_ascii_case(PROJECT_EXT)) else {
return false;
};
let Some((prefix, suffix)) = path.file_stem().and_then(|stem| stem.to_str()).and_then(|stem| stem.rsplit_once('-')) else {
return false;
};
let Some((stem, mark)) = prefix.rsplit_once('-') else {
return false;
};
if !mark.eq_ignore_ascii_case(COPY_MARK) || suffix.len() != SUFFIX_DIGITS || !suffix.bytes().all(|digit| digit.is_ascii_hexdigit()) {
return false;
}
let opened = absolute(path);
let Some(parent) = opened.parent() else {
return false;
};
if parent != folder && !same_location(parent, folder) {
return false;
}
if mark == COPY_MARK && extension == PROJECT_EXT {
return true;
}
// On a case-sensitive volume the alternate spelling may be a separate user file
let generated_name = format!("{stem}-{COPY_MARK}-{}.{PROJECT_EXT}", suffix.to_ascii_lowercase());
same_location(path, &folder.join(generated_name))
}
/// A suffix for the unsaved project `project`: from this process and the moment, so another instance or a later run
@@ -122,6 +179,23 @@ mod tests {
assert_ne!(first.autosave_path(folder), one, "a new project of the same name starts its own copy");
}
#[test]
fn renaming_an_unsaved_project_keeps_its_autosave_copy() {
let folder = Path::new("autosave");
let mut app = app(project("hero"));
let copy = app.autosave_path(folder);
for name in ["Knight", "Knight final"] {
texturecraft_engine::execute(&mut app.session, "project.rename", &serde_json::json!({"name": name})).unwrap();
assert_eq!(app.autosave_path(folder), copy);
}
app.session.switch_to(project("Knight"));
assert_ne!(app.autosave_path(folder), copy);
}
#[test]
fn a_saved_project_names_its_copy_after_its_file_and_keeps_it_across_restarts() {
let folder = Path::new("autosave");
@@ -142,22 +216,28 @@ mod tests {
}
#[test]
fn a_project_opened_from_its_copy_keeps_writing_to_it() {
let folder = std::env::temp_dir().join("tc-autosave");
fn only_a_project_opened_from_a_copy_is_detached_from_its_file() {
let folder = user_dir("autosave");
let mut app = app(project("hero"));
let copy = app.autosave_path(&folder);
// Ordinary files and copies kept elsewhere retain their save paths
let elsewhere = folder.join("kept").join(name_of(&copy));
for project_path in [folder.join("hero.tcraft"), folder.join("hero-20240115.tcraft"), elsewhere] {
let project_path = project_path.display().to_string();
app.session.path = Some(project_path.clone());
app.detach_autosave_copy();
assert_eq!(app.session.path, Some(project_path));
}
app.session.path = Some(copy.display().to_string());
assert_eq!(app.autosave_path(&folder), copy);
// A file there that is not a copy is the user's own: autosave leaves it alone
let own = folder.join("hero.tcraft");
app.session.path = Some(own.display().to_string());
assert_ne!(app.autosave_path(&folder), own);
app.detach_autosave_copy();
let dated = folder.join("hero-20240115.tcraft");
app.session.path = Some(dated.display().to_string());
assert_ne!(app.autosave_path(&folder), dated);
assert_eq!(app.session.path, None, "Save asks for a file");
assert!(app.session.modified, "closing asks to save the recovered work");
}
#[test]
+9 -4
View File
@@ -35,8 +35,10 @@ impl ControlRequest {
}
}
fn ok(v: Value) -> Value {
json!({ "ok": true, "result": v })
fn ok(result: Value) -> Value {
let mut reply = json!({ "ok": true });
reply["result"] = result;
reply
}
fn err(e: impl std::fmt::Display) -> Value {
@@ -154,9 +156,9 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para
return err("A manual project save is already running");
}
let command_params = params.get("params").cloned().unwrap_or(Value::Null);
let command_params = params.get("params").unwrap_or(&Value::Null);
let before = app.session.camera;
match texturecraft_engine::execute(&mut app.session, id, &command_params) {
match texturecraft_engine::execute(&mut app.session, id, command_params) {
Ok(value) => {
if matches!(id, "brush.preset.store" | "brush.preset.rename" | "brush.preset.delete") {
app.thumbs.forget_saved_files();
@@ -177,6 +179,9 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para
// A command that moved the camera takes over from a glide in progress; a projection switch joins it
app.settle_camera_glide(id, before);
#[cfg(not(target_arch = "wasm32"))]
let value = app.recover_file_open(id, value);
ok(value)
}
Err(error) => err(error),
+14 -3
View File
@@ -383,9 +383,12 @@ pub struct TextureCraftApp {
/// When the next autosave is due (seconds of app time; desktop only).
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
next_autosave: f64,
/// The unsaved project (its id) and the suffix of its autosave copy.
/// The unsaved project (its id) and the stable filename of its autosave copy.
#[cfg(not(target_arch = "wasm32"))]
unsaved_autosave_suffix: Option<(u64, u64)>,
unsaved_autosave_file: Option<(u64, String)>,
/// The dialog opening that owns the Project name widget's undo state.
#[cfg(not(target_arch = "wasm32"))]
project_name_editor_opening: Option<u64>,
/// The brightness and accent the style was last built for.
styled: Option<(theme::Brightness, theme::Accent)>,
/// Whether the window had focus last frame.
@@ -537,7 +540,9 @@ impl TextureCraftApp {
last_time: 0.0,
next_autosave,
#[cfg(not(target_arch = "wasm32"))]
unsaved_autosave_suffix: None,
unsaved_autosave_file: None,
#[cfg(not(target_arch = "wasm32"))]
project_name_editor_opening: None,
styled: None,
focused: true,
#[cfg(not(target_arch = "wasm32"))]
@@ -585,6 +590,9 @@ impl TextureCraftApp {
}
}
// The desktop launcher can supply an already-open autosave copy
app.detach_autosave_copy();
// An export folder still at the default follows the data folder
if app.ui.export.dir == data_folder("").join("export").display().to_string() {
app.ui.export.dir = user_dir("export").display().to_string();
@@ -666,6 +674,9 @@ impl TextureCraftApp {
None => self.settle_camera_glide(id, before),
}
#[cfg(not(target_arch = "wasm32"))]
let value = self.recover_file_open(id, value);
Some(value)
}
Err(error) => {
+1 -1
View File
@@ -18,7 +18,7 @@ pub const HEADLESS: &[(&str, &str, &str, &str)] = &[
("ui.saveAsTemplate", "partial", "window", "the dialog is desktop-only; `project.template.save` saves it"),
("ui.export", "partial", "window", "the dialog is desktop-only; `file.exportTextures` exports"),
("ui.saveReduced", "no", "engine-gap", "a smaller save could be a command"),
("ui.projectConfig", "no", "engine-gap", "project settings could be set by a command"),
("ui.projectConfig", "partial", "window", "the dialog is desktop-only; `project.rename` sets the project name"),
("ui.recent.clear", "no", "window", "the desktop recent-projects list"),
("ui.quit", "no", "window", "quits the desktop app"),
("ui.settings", "no", "window", "the desktop settings window"),
+55 -13
View File
@@ -1,13 +1,15 @@
//! Edit > Project Configuration...: the project's settings in sections. 3D MESH picks another mesh
//! file for the project or reads the current one again; PROJECT SETTINGS sets the normal map format
//! and shows the UV tiles. Settings TextureCraft does not have yet (tangent space per fragment,
//! physical size, OpenColorIO, import options other than stroke preservation) are shown disabled.
//! file for the project or reads the current one again; PROJECT SETTINGS sets the project name and
//! normal map format and shows the UV tiles. Unsupported options such as tangent space per fragment,
//! physical size and OpenColorIO are shown disabled.
use std::borrow::Cow;
use std::sync::atomic::{AtomicU64, Ordering};
use egui::{Key, Modifiers};
use serde_json::{Value, json};
use texturecraft_engine::core::NormalFormat;
use texturecraft_engine::project_cmds::{MAX_PROJECT_NAME_CHARS, validate_project_name};
use crate::TextureCraftApp;
use crate::dock::info_icon;
@@ -33,6 +35,7 @@ const MIN_FIELD_WIDTH_POINTS: f32 = 60.0;
const DEFAULT_DIALOG_WIDTH_POINTS: f32 = 560.0;
/// Leave space around the centered dialog on short viewports.
const DIALOG_VIEWPORT_MARGIN_POINTS: f32 = 32.0;
const PROJECT_NAME_FIELD_ID: &str = "project_config_name";
/// Opens the window on the current project, with nothing chosen yet.
pub(crate) fn open(app: &mut TextureCraftApp) {
@@ -44,6 +47,7 @@ pub(crate) fn open(app: &mut TextureCraftApp) {
mesh: None,
reimport: false,
preserve: true,
draft_name: None,
normal_format: None,
color_management: crate::project_form::ColorManagement::Legacy,
confirm: false,
@@ -115,14 +119,23 @@ fn format_name(format: NormalFormat) -> &'static str {
}
}
pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
let Some(mut config) = app.ui.windows.project_config.take() else { return };
// Choices for another project cannot be applied here
if config.project != app.session.project_id {
fn sync_name_editor(app: &mut TextureCraftApp, ctx: &egui::Context, opening: Option<u64>) {
if app.project_name_editor_opening == opening {
return;
}
// Egui keeps widget undo data after the dialog closes
app.project_name_editor_opening = opening;
ctx.data_mut(|data| data.remove::<egui::text_edit::TextEditState>(egui::Id::unique(PROJECT_NAME_FIELD_ID)));
}
pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
// Choices for another project cannot be applied here
let config = app.ui.windows.project_config.take().filter(|config| config.project == app.session.project_id);
sync_name_editor(app, ctx, config.as_ref().map(|config| config.opening_id));
let Some(mut config) = config else { return };
let project = &app.session.doc.project;
let current_mesh_path = &project.mesh_path;
@@ -137,7 +150,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
let mut open = true;
let (mut ok, mut cancel, mut select) = (std::mem::take(&mut config.confirm), false, false);
// Start with a form that fits the viewport; subsequent sizes follow the user's resize
// Fit the first frame to the viewport and follow the user's resize after that
let form_height = (ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS - DIALOG_CHROME_HEIGHT_POINTS)
.clamp(crate::project_form::MIN_FORM_HEIGHT_POINTS, crate::project_form::FORM_HEIGHT_POINTS);
let dialog = crate::windows::dialog(ctx, "project_config", tr("Project Configuration"), &mut open)
@@ -211,6 +224,20 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
ui.add_space(12.0);
ui.label(caption(tr("PROJECT SETTINGS")));
ui.add_space(4.0);
ui.horizontal(|ui| {
ui.add_space(ROW_INDENT_POINTS);
let label = ui.label(tr("Project name")).id;
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
info_icon(ui, tr("The name $project stands for in export file names. The project file keeps its own name."));
let was_edited = config.draft_name.is_some();
let mut name = config.draft_name.take().map_or(Cow::Borrowed(project.name.as_str()), Cow::Owned);
let field = egui::TextEdit::singleline(&mut name).id(egui::Id::unique(PROJECT_NAME_FIELD_ID)).desired_width(FIELD_WIDTH_POINTS);
if ui.add(field).labelled_by(label).changed() || was_edited {
config.draft_name = Some(name.into_owned());
}
});
});
let shown_format = config.normal_format.unwrap_or(current_normal_format);
row(
ui,
@@ -284,7 +311,6 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
physical_size(ui, "project_config_physical_size", false);
color_management(ui, "project_config_color_management", &mut config.color_management);
});
});
});
});
@@ -303,9 +329,19 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
});
}
// Apply the mesh first so a failed mesh change leaves the format untouched
let confirming = ok && !cancel && open;
// Reject invalid drafts before applying mesh or format changes
if confirming && config.draft_name.as_deref().is_some_and(|name| validate_project_name(name).is_err()) {
app.toast(trf("Project name must be 1 to {max} characters after trimming, without control characters.", &[("max", &MAX_PROJECT_NAME_CHARS)]), true);
app.announce_latest_toast();
app.ui.windows.project_config = Some(config);
return;
}
// Apply the mesh first so a failed mesh change leaves the remaining settings untouched
let mut mesh_applied = false;
let done = ok && !cancel && open && {
let done = confirming && {
let reimport = config.reimport.then(|| app.session.remembered_mesh_path().map(str::to_string)).flatten();
mesh_applied = if config.reimport && chosen_mesh.is_none() && reimport.is_none() {
// Drop a stale reimport tick so the user can retry the remaining settings
@@ -328,15 +364,21 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
}
None => true,
}
&& match config.draft_name.as_deref() {
Some(name) => app.run("project.rename", json!({"name": name})).is_some(),
None => true,
}
};
if !done && !cancel && open {
// A format retry must not reimport an already changed mesh
// A retry must not reimport an already changed mesh
if ok && mesh_applied {
(config.mesh, config.reimport) = (None, false);
}
app.ui.windows.project_config = Some(config);
} else {
sync_name_editor(app, ctx, None);
}
}
@@ -7,6 +7,8 @@ pub struct ProjectConfig {
pub reimport: bool,
/// Whether painted strokes follow the surface of a newly imported mesh
pub preserve: bool,
/// The name as typed, or None to leave the current name unvalidated and unchanged
pub draft_name: Option<String>,
/// The selected normal map format when it differs from the project's
pub normal_format: Option<texturecraft_engine::core::NormalFormat>,
/// Color management as chosen in the window; nothing is applied (the project stays Legacy)
+143
View File
@@ -0,0 +1,143 @@
//! Work recovered from an autosave copy survives the next autosave of the project the copy came from. This is a test
//! binary of its own because it points the process's data folder at a temporary one
#![cfg(not(target_arch = "wasm32"))]
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use egui_kittest::Harness;
use serde_json::{Value, json};
use texturecraft_engine::core::PROJECT_EXT;
use texturecraft_engine::formats::RamReservation;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
use texturecraft_ui_egui::{TextureCraftApp, control};
/// App time each frame advances by, so a few frames pass any autosave interval
const FRAME_SECONDS: f32 = 600.0;
/// Deadline for the background archive write
const WRITE_TIMEOUT: Duration = Duration::from_secs(60);
/// Allow the worker to make progress between test frames.
const POLL_INTERVAL: Duration = Duration::from_millis(20);
fn load_project(path: &Path) -> Option<Session> {
texturecraft_engine::file_cmds::open_path(path.to_str().unwrap()).ok()
}
fn layers(session: &Session) -> usize {
session.doc.project.layers.len()
}
fn start(session: Session) -> Harness<'static, TextureCraftApp> {
Harness::builder()
.with_step_dt(FRAME_SECONDS)
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
.build_eframe(|cc| TextureCraftApp::new(cc, session))
}
fn add_layers(app: &mut TextureCraftApp, count: usize) {
for _ in 0..count {
execute(&mut app.session, "layer.add.paint", &json!({})).unwrap();
}
}
/// Wait for an autosave containing the requested number of layers.
fn autosave(harness: &mut Harness<'_, TextureCraftApp>, folder: &Path, layer_count: usize) -> PathBuf {
let started = Instant::now();
loop {
if let Some(reservation) = RamReservation::try_for_save() {
// Wait for any previous archive write before advancing another frame
let found = std::fs::read_dir(folder).into_iter().flatten().filter_map(Result::ok).map(|entry| entry.path()).find(|path| {
path.extension().is_some_and(|extension| extension == PROJECT_EXT) && load_project(path).is_some_and(|session| layers(&session) == layer_count)
});
drop(reservation);
if let Some(copy) = found {
return copy;
}
harness.step();
}
assert!(started.elapsed() < WRITE_TIMEOUT, "autosave wrote no copy of {layer_count} layers");
std::thread::sleep(POLL_INTERVAL);
}
}
#[test]
fn recovered_work_survives_the_originals_next_autosave() {
let data = tempfile::tempdir().unwrap();
texturecraft_ui_egui::set_data_root(data.path().to_path_buf());
let folder = data.path().join("autosave");
let original_path = data.path().join("hero.tcraft");
let original_params = json!({ "path": original_path.to_str().unwrap() });
let mut session = Session::new_project("hero", primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
execute(&mut session, "file.saveAs", &original_params).unwrap();
let saved_layer_count = layers(&session);
let mut harness = start(session);
add_layers(harness.state_mut(), 1);
let original_copy = autosave(&mut harness, &folder, saved_layer_count + 1);
let copy_params = json!({ "path": original_copy.to_str().unwrap() });
let opened = harness.state_mut().run("file.open", copy_params.clone()).unwrap();
assert_eq!(harness.state().session.path, None);
assert_eq!(opened.get("path"), Some(&Value::Null));
assert_eq!(opened["modified"], true);
assert!(harness.state_mut().run("file.save", json!({})).is_none(), "saving the recovered project requires a destination");
add_layers(harness.state_mut(), 3);
let recovered_layer_count = layers(&harness.state().session);
let recovered_copy = autosave(&mut harness, &folder, recovered_layer_count);
assert_ne!(recovered_copy, original_copy);
let kept_path = data.path().join("kept.tcraft");
harness.state_mut().run("file.saveAs", json!({ "path": kept_path })).unwrap();
assert_eq!(harness.state().session.path.as_deref(), kept_path.to_str());
let opened = harness.state_mut().run("file.open", original_params.clone()).unwrap();
assert_eq!(opened["path"], original_params["path"]);
assert_eq!(opened["modified"], false);
add_layers(harness.state_mut(), 2);
assert_eq!(autosave(&mut harness, &folder, saved_layer_count + 2), original_copy, "the original keeps its copy");
assert_eq!(layers(&load_project(&recovered_copy).unwrap()), recovered_layer_count);
assert_eq!(layers(&load_project(&kept_path).unwrap()), recovered_layer_count);
// The control reply reports the same recovery state as session inspection
let ctx = harness.ctx.clone();
let reply = control::handle(harness.state_mut(), &ctx, "command.run", &json!({ "id": "file.open", "params": copy_params }));
let inspected = control::handle(harness.state_mut(), &ctx, "session.inspect", &json!({}));
assert_eq!(reply["ok"], true, "{reply}");
assert_eq!(harness.state().session.path, None);
assert_eq!(reply["result"]["path"], inspected["result"]["path"]);
assert_eq!(reply["result"]["modified"], inspected["result"]["modified"]);
// A case-insensitive volume resolves this spelling to the same archive
let alias = original_copy.with_file_name(original_copy.file_name().unwrap().to_str().unwrap().replace("-copy-", "-CoPy-")).with_extension("TCRAFT");
let case_sensitive = !alias.exists();
if case_sensitive {
// Exercise the same identity check with two names for one file
std::fs::hard_link(&original_copy, &alias).unwrap();
}
let opened = harness.state_mut().run("file.open", json!({ "path": alias })).unwrap();
assert_eq!(opened.get("path"), Some(&Value::Null));
assert_eq!(opened["modified"], true);
if case_sensitive {
std::fs::remove_file(&alias).unwrap();
std::fs::copy(&original_copy, &alias).unwrap();
let opened = harness.state_mut().run("file.open", json!({ "path": alias })).unwrap();
assert_eq!(opened["path"], alias.to_str().unwrap());
assert_eq!(opened["modified"], false);
}
// The launcher gives the app a session that has already loaded the archive
let startup = start(load_project(&original_copy).unwrap());
assert_eq!(startup.state().session.path, None);
assert!(startup.state().session.modified);
}
+96
View File
@@ -765,3 +765,99 @@ fn project_config_snapshots() {
h.run_steps(6);
h.render().unwrap().save(output_dir.join("project-config-ocio.png")).unwrap();
}
fn type_project_name(h: &mut Harness<'_, TextureCraftApp>, name: &str) {
in_window(h, Role::TextInput, "Project name").focus();
h.run_steps(2);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
in_window(h, Role::TextInput, "Project name").type_text(name);
h.run_steps(2);
}
#[test]
fn a_typed_project_name_applies_only_with_ok() {
let dir = temp_dir("project-name");
let mut h = app_on_a_quad(&dir);
let before = h.state().session.doc.project.name.clone();
for button in ["Cancel", "OK"] {
open_window(&mut h);
type_project_name(&mut h, "Knight");
click_in_window(&mut h, Role::Button, button);
let expected = if button == "OK" { "Knight" } else { before.as_str() };
assert_eq!(h.state().session.doc.project.name, expected, "after {button}");
assert!(!window_is_open(&h), "{button} closes the window");
}
}
#[test]
fn an_invalid_project_name_leaves_other_configuration_changes_pending() {
use texturecraft_engine::core::NormalFormat;
let dir = temp_dir("invalid-project-name");
let mut h = app_on_a_quad(&dir);
let triangle = dir.join("tri.obj");
std::fs::write(&triangle, TRIANGLE).unwrap();
open_window(&mut h);
select(&mut h, &triangle);
click_in_window(&mut h, Role::ComboBox, FORMAT_HINT);
click_in_window(&mut h, Role::Button, "DirectX");
type_project_name(&mut h, " ");
click_in_window(&mut h, Role::Button, "OK");
assert!(window_is_open(&h));
assert_eq!(h.state().session.doc.project.name, "quad");
assert_eq!(h.state().session.mesh.triangle_count(), 2);
assert_eq!(project_normal_format(&h), NormalFormat::OpenGl);
let message = h.get_by_label("Project name must be 1 to 128 characters after trimming, without control characters.");
assert_eq!(message.accesskit_node().live(), egui::accesskit::Live::Polite);
type_project_name(&mut h, "Knight");
click_in_window(&mut h, Role::Button, "OK");
assert!(!window_is_open(&h));
assert_eq!(h.state().session.doc.project.name, "Knight");
assert_eq!(h.state().session.mesh.triangle_count(), 1);
assert_eq!(project_normal_format(&h), NormalFormat::DirectX);
}
#[test]
fn the_project_name_limit_applies_after_trimming_in_the_dialog() {
use texturecraft_engine::project_cmds::MAX_PROJECT_NAME_CHARS;
let dir = temp_dir("project-name-limit");
let mut h = app_on_a_quad(&dir);
let name = format!("{}Z", "x".repeat(MAX_PROJECT_NAME_CHARS - 1));
open_window(&mut h);
type_project_name(&mut h, &format!(" {name} "));
click_in_window(&mut h, Role::Button, "OK");
assert!(!window_is_open(&h));
assert_eq!(h.state().session.doc.project.name, name);
}
#[test]
fn a_reopened_name_field_cannot_undo_to_a_discarded_draft() {
let dir = temp_dir("project-name-history");
let mut h = app_on_a_quad(&dir);
let original = h.state().session.doc.project.name.clone();
open_window(&mut h);
type_project_name(&mut h, "Discard this name");
// Drive enough virtual frames for the text edit to record an undo point
h.run_steps(90);
click_in_window(&mut h, Role::Button, "Cancel");
open_window(&mut h);
in_window(&h, Role::TextInput, "Project name").focus();
h.run_steps(2);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z);
h.run_steps(2);
let field = in_window(&h, Role::TextInput, "Project name");
assert_eq!(field.accesskit_node().value().as_deref(), Some(original.as_str()));
}
+6
View File
@@ -13,6 +13,12 @@ Everything TextureCraft does is an engine command with a stable id (`layer.add.f
Programmatic calls never open dialogs: a command runs with its defaults. Only `ui.menu.invoke`
behaves like a menu click. `session.inspect` shows every layer, mask, effect, fill source and
painted tile count, so an agent can verify its work without a screenshot.
`project.rename {name}` sets the internal project name used by `$project` in export
templates and returns `{name}` with the trimmed value. The name must contain 1–128
characters after trimming and contain no control characters. Renaming is undoable.
Submitting the current name leaves history unchanged. The project file keeps its own name.
`effect.histogram {effect, channel?, bins?}` counts the values an effect reads (a levels
effect's input), so an agent can pick its input range from the data. `effect.move {effect,
index}` reorders an effect within its stack (0 = bottom) and `effect.duplicate {effect}` copies
+2 -1
View File
@@ -308,7 +308,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
the default). Nightly shows its fixed profile path in the same row.
- **Autosave**: each project keeps its own copy in the data folder's `autosave`, named
`<name>-copy-<suffix>.tcraft` after its saved file (or, until it is saved, the project), so projects made from
one mesh never overwrite each other's copy.
one mesh never overwrite each other's copy. Opening a copy from the current desktop profile's
autosave folder starts an unsaved project. Save asks where to keep the recovered work.
- 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
+2 -2
View File
@@ -4,7 +4,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac
**63 of 64 menu items live (98%).**
**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 21 yes, 40 no (window 33, os 5, engine-gap 2), 3 partial, 0 unknown.** An item is `headless: yes` when its id is an engine command, so `texturecraft-cli` and the MCP server reach it. A `ui.*` id is live in the desktop app only; its value is the hand mark in `HEADLESS` (`crates/ui-egui/src/parity.rs`).
**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 21 yes, 39 no (window 33, os 5, engine-gap 1), 4 partial, 0 unknown.** An item is `headless: yes` when its id is an engine command, so `texturecraft-cli` and the MCP server reach it. A `ui.*` id is live in the desktop app only; its value is the hand mark in `HEADLESS` (`crates/ui-egui/src/parity.rs`).
## File
@@ -32,7 +32,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac
|---|---|---|---|---|
| Undo | `edit.undo` | Ctrl+Z | live | yes |
| Redo | `edit.redo` | Ctrl+Y | live | yes |
| Project Configuration | `ui.projectConfig` | | live | no, reach: engine-gap (project settings could be set by a command) |
| Project Configuration | `ui.projectConfig` | | live | partial, reach: window (the dialog is desktop-only; `project.rename` sets the project name) |
| Reimport Mesh | `file.reimportMesh` | Ctrl+Shift+R | live | yes |
| Settings | `ui.settings` | | live | no, reach: window (the desktop settings window) |