From 1ccef56f98131235cb2a7d9af4b5a4db52aea276 Mon Sep 17 00:00:00 2001 From: Morion Date: Thu, 26 Nov 2026 18:53:01 -0500 Subject: [PATCH 1/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 From 31bf2a58caf09600f47c23ebea667e08cac2bbdd Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:33:59 +0000 Subject: [PATCH 2/2] Assets: Remove unused keeps the package and maps of a material linked in a content effect images_used counted a linked material's package and cooked maps only on a fill layer, so Remove unused dropped them (and a smart material left them out) when the link sat in a content fill effect. --- crates/engine/src/material_lib.rs | 20 ++++++++++++++------ crates/engine/tests/it/materialcraft_link.rs | 2 +- crates/engine/tests/it/resources_used.rs | 20 +++++++++++++++++++- 3 files changed, 34 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 9d496630..0277c6fc 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use serde_json::Value; use texturecraft_compose::PixelStore; -use texturecraft_core::{LayerId, LayerKind, Project, Source, TextureSet}; +use texturecraft_core::{EffectKind, Fill, LayerId, LayerKind, Project, Source, TextureSet}; use crate::commands::{CommandSpec, always, has_layer}; use crate::materials::Place; @@ -36,7 +36,15 @@ fn fe(e: texturecraft_formats::FormatError) -> EngineError { EngineError::Other(e.to_string()) } -/// Image resources a layer subtree uses (fill sources and their patterns, mask or content effects and the images its paths paint with) +/// The package and cooked maps of the MaterialCraft material linked to `fill`, if any +fn link_images(fill: &Fill, out: &mut Vec) { + if let Some(link) = &fill.link { + out.push(link.package.clone()); + out.extend(link.outputs.values().cloned()); + } +} + +/// Image resources a layer subtree uses (fill sources and their patterns, linked materials, mask or content effects and the images its paths paint with) pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, depth: usize) { if depth > texturecraft_core::project::MAX_DEPTH { return; @@ -46,15 +54,15 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, if let LayerKind::Fill(fill) = &layer.kind { out.extend(fill.sources.values().flat_map(Source::images).map(str::to_string)); - if let Some(link) = &fill.link { - out.push(link.package.clone()); - out.extend(link.outputs.values().cloned()); - } + link_images(fill, out); } for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(&layer.content_effects) { out.extend(effect.images_read().map(str::to_string)); out.extend(crate::path_tool::path_images(&effect.kind)); + if let EffectKind::Material(fill) = &effect.kind { + link_images(fill, out); + } } for child in layer.children() { diff --git a/crates/engine/tests/it/materialcraft_link.rs b/crates/engine/tests/it/materialcraft_link.rs index 4a4a5d03..1ee696e1 100644 --- a/crates/engine/tests/it/materialcraft_link.rs +++ b/crates/engine/tests/it/materialcraft_link.rs @@ -47,7 +47,7 @@ fn cooked(roughness: f32, wear: f32) -> CookedMaterial { CookedMaterial::new(serde_json::from_value(interface).unwrap(), maps, 4) } -fn install(session: &mut Session) -> LayerId { +pub(crate) fn install(session: &mut Session) -> LayerId { session.add_cooked_material(&cooked(0.25, 0.5), Arc::new(b"package bytes".to_vec()), "mcmat", Place::Selection).unwrap() } diff --git a/crates/engine/tests/it/resources_used.rs b/crates/engine/tests/it/resources_used.rs index bd89ee77..fbc15d44 100644 --- a/crates/engine/tests/it/resources_used.rs +++ b/crates/engine/tests/it/resources_used.rs @@ -1,7 +1,7 @@ //! The images a project reads beyond fill sources: a colour selection's ID map, a filter's image input, the mask brush and its paths use serde_json::{Value, json}; -use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::core::{Channel, EffectKind, LayerId, LayerKind}; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, execute}; @@ -53,6 +53,24 @@ fn removing_unused_resources_keeps_the_images_a_selection_a_filter_input_the_mas assert_eq!(reply["removed"], json!([unused]), "only the image nothing reads goes"); } +#[test] +fn removing_unused_resources_keeps_the_package_and_maps_of_a_material_linked_in_a_content_effect() { + let mut session = session(); + let unused = session.import_resource_bytes("unused.png", white_png()).unwrap(); + let linked = crate::materialcraft_link::install(&mut session); + let LayerKind::Fill(fill) = session.doc.project.layer(linked).unwrap().kind.clone() else { panic!("not a fill") }; + + // The linked material moves into a content effect of another layer, the only place that uses it + let layer = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + let effect = LayerId(execute(&mut session, "effect.add.fill", &json!({"layer": layer, "target": "content"})).unwrap()["effect"].as_u64().unwrap()); + session.doc.project.effect_mut(effect).unwrap().kind = EffectKind::Material(fill); + execute(&mut session, "layer.remove", &json!({"layer": linked.0})).unwrap(); + + let reply = execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + + assert_eq!(reply["removed"], json!([unused]), "the linked package and its maps stay"); +} + #[test] fn a_smart_material_carries_the_images_its_selection_and_filter_input_read() { let mut session = session();