Auto: Integrate main into Paint Properties

Preserve desktop autosave recovery and retain the package and cooked maps of linked materials used in effects. Keep both lockfile dependency entries and the approved Paint Properties changes.
This commit is contained in:
chasse20 committed 2026-11-28 08:08:38 +00:00
commit f2176331a0
12 files changed
+294 -40

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
@@ -6180,6 +6180,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.
+14 -6
View File
@@ -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<String>) {
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<String>, 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<String>,
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() {
+1 -1
View File
@@ -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()
}
+19 -1
View File
@@ -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();
+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]
+89 -27
View File
@@ -3,21 +3,47 @@
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
pub(crate) fn autosave_path(&mut self, folder: &Path) -> PathBuf {
@@ -35,12 +61,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())))
}
@@ -48,7 +68,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 +76,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
@@ -142,22 +198,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),
+6
View File
@@ -596,6 +596,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();
@@ -677,6 +680,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) => {
+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);
}
+2 -1
View File
@@ -309,7 +309,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