Autosave: give each project its own copy

The copy was named after the project, whose name comes from the mesh file, so projects made from one mesh overwrote each other's autosave. It is now `<stem>-<suffix>.tcraft`: from the saved file and its path, or a suffix of its own while the project is unsaved. A project opened from its copy keeps writing to it.

Fixes #851
This commit is contained in:
Morion committed 2026-11-26 00:27:10 -05:00
1 parent d45bb2cad8
commit 23d3f9ae71
4 files changed
+232 -5

No files matched your search

+156
View File
@@ -0,0 +1,156 @@
//! Where a project's autosave copy goes. Each project has a file of its own, `<stem>-<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
use std::path::{Path, PathBuf};
use texturecraft_engine::core::PROJECT_EXT;
use texturecraft_engine::formats::export::sanitize_file_stem;
use crate::TextureCraftApp;
/// Hex digits of a copy's suffix
const SUFFIX_DIGITS: usize = 8;
/// The longest stem kept, so the suffix and the temporary files of a save still fit a file name
const MAX_STEM_CHARS: usize = 180;
impl TextureCraftApp {
/// 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 {
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));
};
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())))
}
}
fn file_name(stem: &str, suffix: u32) -> String {
let stem: String = sanitize_file_stem(stem).chars().take(MAX_STEM_CHARS).collect();
format!("{stem}-{suffix:0SUFFIX_DIGITS$x}.{PROJECT_EXT}")
}
/// `path` made absolute, as given when that fails
fn absolute(path: &Path) -> PathBuf {
std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf())
}
/// Whether `path` is an autosave copy of `folder`: a project file there whose name ends in a suffix
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('-')).map(|(_, suffix)| suffix);
path.parent() == Some(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()))
}
/// A suffix for the unsaved project `project`: from this process and the moment, so another instance or a later run
/// takes a different one
fn new_suffix(project: u64) -> u32 {
let now = chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default();
let mut seed = Vec::new();
seed.extend_from_slice(&std::process::id().to_le_bytes());
seed.extend_from_slice(&now.to_le_bytes());
seed.extend_from_slice(&project.to_le_bytes());
hash(&seed)
}
/// 32-bit FNV-1a: the same bytes give the same suffix in every release, which the standard hasher does not promise
fn hash(bytes: &[u8]) -> u32 {
bytes.iter().fold(0x811c_9dc5, |hash, byte| (hash ^ u32::from(*byte)).wrapping_mul(0x0100_0193))
}
#[cfg(test)]
mod tests {
use texturecraft_engine::Session;
use texturecraft_engine::geom::primitives;
use super::*;
fn project(name: &str) -> Session {
Session::new_project(name, primitives::cube(1.0), "builtin:cube", None, 128).unwrap()
}
fn app(session: Session) -> TextureCraftApp {
TextureCraftApp::new(&eframe::CreationContext::_new_kittest(egui::Context::default()), session)
}
fn name_of(path: &Path) -> &str {
path.file_name().and_then(|name| name.to_str()).unwrap()
}
#[test]
fn unsaved_projects_with_one_name_get_different_copies_that_stay_put() {
let folder = Path::new("autosave");
let mut first = app(project("hero"));
let mut second = app(project("hero"));
let (one, other) = (first.autosave_path(folder), second.autosave_path(folder));
assert_ne!(one, other, "another instance never writes the same file");
assert!(name_of(&one).starts_with("hero-") && name_of(&one).ends_with(".tcraft"), "{one:?}");
assert_eq!(one.parent(), Some(folder));
assert_eq!(first.autosave_path(folder), one, "the next autosave replaces this project's copy");
first.session.switch_to(project("hero"));
assert_ne!(first.autosave_path(folder), one, "a new project of the same name starts its own copy");
}
#[test]
fn a_saved_project_names_its_copy_after_its_file_and_keeps_it_across_restarts() {
let folder = Path::new("autosave");
let copy_of = |saved: &str| {
let mut app = app(project("hero"));
app.session.path = Some(saved.to_string());
app.autosave_path(folder)
};
let first = copy_of("work/Hero_v1.tcraft");
let second = copy_of("work/Hero_v2.tcraft");
let same_name_elsewhere = copy_of("backup/Hero_v1.tcraft");
assert!(name_of(&first).starts_with("Hero_v1-"), "{first:?}");
assert_ne!(first, second);
assert_ne!(first, same_name_elsewhere, "files of one name in two folders keep two copies");
assert_eq!(copy_of("work/Hero_v1.tcraft"), first, "a later run finds the same copy");
}
#[test]
fn a_project_opened_from_its_copy_keeps_writing_to_it() {
let folder = std::env::temp_dir().join("tc-autosave");
let mut app = app(project("hero"));
let copy = app.autosave_path(&folder);
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);
}
#[test]
fn suffixes_have_a_fixed_width_and_long_names_are_cut() {
assert_eq!(file_name("hero", 0x2a), "hero-0000002a.tcraft");
assert_eq!(hash(b"hero"), hash(b"hero"));
assert!(file_name(&"a".repeat(500), 1).len() < 200);
}
}
+8 -5
View File
@@ -10,6 +10,8 @@
mod anchor_properties;
mod angle_dial;
mod ask;
#[cfg(not(target_arch = "wasm32"))]
mod autosave_name;
mod bake_job;
pub mod bake_mode;
mod bake_preset;
@@ -344,6 +346,9 @@ 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.
#[cfg(not(target_arch = "wasm32"))]
unsaved_autosave_suffix: Option<(u64, u32)>,
/// The brightness and accent the style was last built for.
styled: Option<(theme::Brightness, theme::Accent)>,
/// Whether the window had focus last frame.
@@ -475,6 +480,8 @@ impl TextureCraftApp {
title_bar: titlebar::TitleBar::default(),
last_time: 0.0,
next_autosave,
#[cfg(not(target_arch = "wasm32"))]
unsaved_autosave_suffix: None,
styled: None,
focused: true,
#[cfg(not(target_arch = "wasm32"))]
@@ -1034,11 +1041,7 @@ impl TextureCraftApp {
self.next_autosave = now + period;
let dir = user_dir("autosave");
let path = dir.join(format!(
"{}.{}",
texturecraft_engine::formats::export::sanitize_file_stem(&self.session.doc.project.name),
texturecraft_engine::core::PROJECT_EXT
));
let path = self.autosave_path(&dir);
let snapshot = self.session.project_snapshot();
let spawned = std::thread::Builder::new().name("texturecraft-autosave".into()).spawn(move || {
let result =
+65
View File
@@ -0,0 +1,65 @@
//! The desktop autosave writes each project's copy to a file of its own. 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;
/// 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);
/// A project named as one made from `hero.fbx` would be, with `layers` paint layers added since it was saved
fn unsaved_hero(layers: usize) -> Session {
let mut session = Session::new_project("hero", primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
for _ in 0..layers {
execute(&mut session, "layer.add.paint", &json!({})).unwrap();
}
session
}
fn copies(folder: &Path) -> Vec<PathBuf> {
let files = std::fs::read_dir(folder).map(|entries| entries.flatten().map(|entry| entry.path()).collect::<Vec<_>>()).unwrap_or_default();
files.into_iter().filter(|path| path.extension().is_some_and(|extension| extension == "tcraft")).collect()
}
/// Runs an app on `session` until the autosave folder holds `count` copies
fn autosave(session: Session, folder: &Path, count: usize) -> Harness<'static, TextureCraftApp> {
let mut harness = Harness::builder().with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session));
let started = Instant::now();
while copies(folder).len() < count {
harness.step();
assert!(started.elapsed() < WRITE_TIMEOUT, "autosave wrote {:?}", copies(folder));
std::thread::sleep(Duration::from_millis(20));
}
harness
}
#[test]
fn two_projects_of_one_name_keep_two_autosave_copies() {
let data = std::env::temp_dir().join(format!("tc-autosave-files-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&data);
texturecraft_ui_egui::set_data_root(data.clone());
let folder = data.join("autosave");
let first = autosave(unsaved_hero(1), &folder, 1);
let second = autosave(unsaved_hero(2), &folder, 2);
drop((first, second));
// Each copy opens as the project that wrote it
let mut layers: Vec<usize> =
copies(&folder).iter().map(|path| texturecraft_engine::file_cmds::open_path(path.to_str().unwrap()).unwrap().doc.project.layers.len()).collect();
layers.sort_unstable();
assert_eq!(layers[1], layers[0] + 1, "{layers:?}");
std::fs::remove_dir_all(&data).unwrap();
}
+3
View File
@@ -278,6 +278,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
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).
- **Autosave**: each project keeps its own copy in the data folder's `autosave`, named
`<name>-<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.
- 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