From ab78d69fd8d2c626cba3073bec03f54141e0d2a2 Mon Sep 17 00:00:00 2001 From: Morion Date: Thu, 26 Nov 2026 08:27:01 -0500 Subject: [PATCH 1/2] Make the project renamable --- crates/engine/src/project_cmds.rs | 29 ++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/rename_project.rs | 34 ++++++++++++++++++++++ crates/ui-egui/src/project_config.rs | 19 ++++++++++++ crates/ui-egui/src/state/project_config.rs | 2 ++ crates/ui-egui/tests/it/project_config.rs | 21 +++++++++++++ 6 files changed, 106 insertions(+) create mode 100644 crates/engine/tests/it/rename_project.rs diff --git a/crates/engine/src/project_cmds.rs b/crates/engine/src/project_cmds.rs index 33432cda..c5da6d34 100644 --- a/crates/engine/src/project_cmds.rs +++ b/crates/engine/src/project_cmds.rs @@ -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 { vec![ cmd!( @@ -22,6 +25,15 @@ pub fn specs() -> Vec { ), 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,23 @@ fn new(s: &mut Session, p: &Value) -> Result { Ok(crate::inspect::session(s)) } +fn rename(s: &mut Session, p: &Value) -> Result { + let name = strp(p, "name") + .map(str::trim) + .filter(|name| !name.is_empty() && name.chars().count() <= MAX_PROJECT_NAME_CHARS && !name.chars().any(char::is_control)) + .ok_or_else(|| bad("project.rename", format!("`name` must be 1-{MAX_PROJECT_NAME_CHARS} characters without control characters")))?; + + // The same name is not an undo step and leaves a saved project unmodified + if name != s.doc.project.name { + s.edit("Rename project", |s| { + s.doc.project.name = name.to_string(); + Ok(()) + })?; + } + + Ok(json!({ "name": name })) +} + fn material(s: &mut Session, p: &Value) -> Result { 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))?; diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 11cfaf41..23517f4a 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -63,6 +63,7 @@ mod perf; mod polygon_fill; mod project_recovery; mod rebuilt_uv_layout; +mod rename_project; mod resources_used; mod sample; mod solo; diff --git a/crates/engine/tests/it/rename_project.rs b/crates/engine/tests/it/rename_project.rs new file mode 100644 index 00000000..5510163b --- /dev/null +++ b/crates/engine/tests/it/rename_project.rs @@ -0,0 +1,34 @@ +//! `project.rename`: the name `$project` stands for in export file names. + +use serde_json::json; +use texturecraft_engine::{Session, execute}; + +use texturecraft_engine::geom::primitives; + +#[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().to_string(); + assert!(plan.contains("Knight_final_") && !plan.contains("hero_"), "{plan}"); + + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(session.doc.project.name, "hero"); +} + +#[test] +fn an_unusable_or_unchanged_project_name_edits_nothing() { + 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!("x".repeat(129))] { + assert!(execute(&mut session, "project.rename", &json!({"name": name.clone()})).is_err(), "{name}"); + } + + execute(&mut session, "project.rename", &json!({"name": "hero"})).unwrap(); + + assert_eq!(session.doc.project.name, "hero"); + assert!(!session.modified, "nothing changed"); +} diff --git a/crates/ui-egui/src/project_config.rs b/crates/ui-egui/src/project_config.rs index a399aa4e..cb887ca1 100644 --- a/crates/ui-egui/src/project_config.rs +++ b/crates/ui-egui/src/project_config.rs @@ -8,6 +8,7 @@ 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; use crate::TextureCraftApp; use crate::dock::info_icon; @@ -44,6 +45,7 @@ pub(crate) fn open(app: &mut TextureCraftApp) { mesh: None, reimport: false, preserve: true, + name: None, normal_format: None, color_management: crate::project_form::ColorManagement::Legacy, confirm: false, @@ -211,6 +213,18 @@ 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 mut name = config.name.clone().unwrap_or_else(|| project.name.clone()); + let field = egui::TextEdit::singleline(&mut name).char_limit(MAX_PROJECT_NAME_CHARS).desired_width(FIELD_WIDTH_POINTS); + if ui.add(field).labelled_by(label).changed() { + config.name = Some(name); + } + }); + }); let shown_format = config.normal_format.unwrap_or(current_normal_format); row( ui, @@ -328,6 +342,11 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } None => true, } + // An untouched name is left alone, even one longer than a typed name may be + && match config.name.as_deref() { + Some(name) => app.run("project.rename", json!({"name": name})).is_some(), + None => true, + } }; if !done && !cancel && open { diff --git a/crates/ui-egui/src/state/project_config.rs b/crates/ui-egui/src/state/project_config.rs index 174b0987..6c7eb95c 100644 --- a/crates/ui-egui/src/state/project_config.rs +++ b/crates/ui-egui/src/state/project_config.rs @@ -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 project name as typed, when the field was edited + pub name: Option, /// The selected normal map format when it differs from the project's pub normal_format: Option, /// Color management as chosen in the window; nothing is applied (the project stays Legacy) diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index a44c4640..700ae461 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -765,3 +765,24 @@ fn project_config_snapshots() { h.run_steps(6); h.render().unwrap().save(output_dir.join("project-config-ocio.png")).unwrap(); } + +#[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); + 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("Knight"); + h.run_steps(2); + 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"); + } +} From 1ccef56f98131235cb2a7d9af4b5a4db52aea276 Mon Sep 17 00:00:00 2001 From: Morion Date: Thu, 26 Nov 2026 18:53:01 -0500 Subject: [PATCH 2/2] Autosave: open a copy as an unsaved project The project a copy came from autosaves to that same file again, so work saved into an opened copy was replaced. Opening a copy now leaves the project without a file: Save asks for one, and its autosave goes to a copy of its own. --- crates/ui-egui/src/autosave_name.rs | 44 ++++++---- crates/ui-egui/src/control.rs | 5 ++ crates/ui-egui/src/lib.rs | 8 ++ crates/ui-egui/tests/autosave_recovery.rs | 100 ++++++++++++++++++++++ docs/features.md | 2 +- 5 files changed, 139 insertions(+), 20 deletions(-) create mode 100644 crates/ui-egui/tests/autosave_recovery.rs diff --git a/crates/ui-egui/src/autosave_name.rs b/crates/ui-egui/src/autosave_name.rs index 69d0ab4d..c5383827 100644 --- a/crates/ui-egui/src/autosave_name.rs +++ b/crates/ui-egui/src/autosave_name.rs @@ -6,7 +6,7 @@ use std::path::{Path, PathBuf}; 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; @@ -18,6 +18,16 @@ const COPY_MARK: &str = "-copy-"; const MAX_STEM_CHARS: usize = 170; impl TextureCraftApp { + /// A project just opened from an autosave copy becomes an unsaved one: the project the copy came from + /// autosaves there again, so work saved into it would be lost + pub(crate) fn detach_autosave_copy(&mut self) { + let folder = absolute(&user_dir("autosave")); + if self.session.path.as_deref().is_some_and(|path| is_copy_in(&absolute(Path::new(path)), &folder)) { + self.session.path = None; + self.session.modified = true; + } + } + /// 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 pub(crate) fn autosave_path(&mut self, folder: &Path) -> PathBuf { @@ -35,12 +45,6 @@ impl TextureCraftApp { }; 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()))) } @@ -142,22 +146,24 @@ 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); + // A file there that is not a copy is the user's own, and so is a copy kept somewhere else + let elsewhere = folder.join("kept").join(name_of(©)); + for own in [folder.join("hero.tcraft"), folder.join("hero-20240115.tcraft"), elsewhere] { + let own = own.display().to_string(); + app.session.path = Some(own.clone()); + app.detach_autosave_copy(); + assert_eq!(app.session.path, Some(own)); + } + 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); - - let dated = folder.join("hero-20240115.tcraft"); - app.session.path = Some(dated.display().to_string()); - assert_ne!(app.autosave_path(&folder), dated); + app.detach_autosave_copy(); + assert_eq!(app.session.path, None, "Save asks for a file"); + assert!(app.session.modified, "closing asks to save the recovered work"); } #[test] diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 8359fbe9..6a551cfd 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -162,6 +162,11 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para app.thumbs.forget_saved_files(); } + #[cfg(not(target_arch = "wasm32"))] + if id == "file.open" { + app.detach_autosave_copy(); + } + // Work from the old project must not reach its replacement if matches!(id, "file.open" | "file.new" | "file.close" | "project.new" | "project.sample") { app.resize = None; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9f0b6d70..aa3f32b7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -555,6 +555,9 @@ impl TextureCraftApp { } } + // A copy named on the command line is already open + 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(); @@ -604,6 +607,11 @@ impl TextureCraftApp { self.thumbs.forget_saved_files(); } + #[cfg(not(target_arch = "wasm32"))] + if id == "file.open" { + self.detach_autosave_copy(); + } + // Pending work and thumbnail snapshots belong to the old project if matches!(id, "file.open" | "file.new" | "file.close" | "project.new" | "project.sample") { self.pbr_import = None; diff --git a/crates/ui-egui/tests/autosave_recovery.rs b/crates/ui-egui/tests/autosave_recovery.rs new file mode 100644 index 00000000..46fd747f --- /dev/null +++ b/crates/ui-egui/tests/autosave_recovery.rs @@ -0,0 +1,100 @@ +//! 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::json; +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; + +/// How long the worker thread gets to write a copy +const WRITE_TIMEOUT: Duration = Duration::from_secs(60); + +fn load(path: &Path) -> Option { + 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(); + } +} + +/// Runs the app until a copy in `folder` holds a project of `count` layers, and returns it +fn autosave(harness: &mut Harness<'_, TextureCraftApp>, folder: &Path, count: usize) -> PathBuf { + let started = Instant::now(); + loop { + harness.step(); + let files = std::fs::read_dir(folder).map(|entries| entries.flatten().map(|entry| entry.path()).collect::>()).unwrap_or_default(); + let found = files + .into_iter() + .find(|path| path.extension().is_some_and(|extension| extension == "tcraft") && load(path).is_some_and(|session| layers(&session) == count)); + if let Some(copy) = found { + return copy; + } + + assert!(started.elapsed() < WRITE_TIMEOUT, "autosave wrote no copy of {count} layers"); + std::thread::sleep(Duration::from_millis(20)); + } +} + +#[test] +fn recovered_work_survives_the_originals_next_autosave() { + let data = std::env::temp_dir().join(format!("tc-autosave-recovery-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&data); + std::fs::create_dir_all(&data).unwrap(); + texturecraft_ui_egui::set_data_root(data.clone()); + let folder = data.join("autosave"); + let own = data.join("hero.tcraft"); + let own_param = json!({ "path": own.to_str().unwrap() }); + + let mut session = Session::new_project("hero", primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + execute(&mut session, "file.saveAs", &own_param).unwrap(); + let saved = layers(&session); + + let mut harness = start(session); + add_layers(harness.state_mut(), 1); + let copy = autosave(&mut harness, &folder, saved + 1); + let copy_param = json!({ "path": copy.to_str().unwrap() }); + + // Opening the copy gives an unsaved project: Save cannot write into it + assert!(harness.state_mut().run("file.open", copy_param.clone()).is_some()); + assert_eq!(harness.state().session.path, None); + add_layers(harness.state_mut(), 3); + let recovered = layers(&harness.state().session); + autosave(&mut harness, &folder, recovered); + + assert!(harness.state_mut().run("file.open", own_param).is_some()); + add_layers(harness.state_mut(), 2); + assert_eq!(autosave(&mut harness, &folder, saved + 2), copy, "the original keeps its copy"); + autosave(&mut harness, &folder, recovered); + + // The control channel and a copy named on the command line open it the same way + let ctx = harness.ctx.clone(); + let result = control::handle(harness.state_mut(), &ctx, "command.run", &json!({ "id": "file.open", "params": copy_param })); + assert_eq!(result["ok"], true, "{result}"); + assert_eq!(harness.state().session.path, None); + assert_eq!(start(load(©).unwrap()).state().session.path, None); + + drop(harness); + std::fs::remove_dir_all(&data).unwrap(); +} diff --git a/docs/features.md b/docs/features.md index 2826868c..81f77af5 100644 --- a/docs/features.md +++ b/docs/features.md @@ -281,7 +281,7 @@ 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 `-copy-.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. A copy opens as an unsaved project, so Save asks for a new file. - 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