From 6120bdd79de129bfb712262feba6353cf64b3369 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 00:48:58 +0100 Subject: [PATCH 1/7] Resources Updater: find changed resource files on disk and update or relink them Image resources imported from a file remember its path and modification time. resource.status lists each resource as outdated, missing, up to date or without a file; resource.update reads changed files again and resource.relink points a resource at another file, each as one undo step that recomposites every layer using the resource. Undo and redo drop pixels decoded from bytes they replace under the same name. The shelf's Resources Updater button opens a window with the project's resources (outdated first), status and name filters, Update, Select new resource, Show in folder, Refresh and Update All. When the app gets the focus back after files changed, a notice offers to update them. Automation refuses the three commands, since they read host paths the project names. --- crates/automation/src/workspace.rs | 6 + crates/core/src/lib.rs | 2 + crates/core/src/project.rs | 5 + crates/core/src/resource_source.rs | 17 + crates/engine/src/commands.rs | 4 +- crates/engine/src/lib.rs | 8 + crates/engine/src/link_cmds.rs | 1 + crates/engine/src/reloaded_file.rs | 28 ++ crates/engine/src/resource_cmds.rs | 24 +- crates/engine/src/resource_state.rs | 15 + crates/engine/src/resource_status.rs | 39 ++ crates/engine/src/resource_update_cmds.rs | 241 +++++++++++ crates/engine/src/session.rs | 2 + crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/resource_updater.rs | 227 +++++++++++ crates/ui-egui/src/lib.rs | 29 +- crates/ui-egui/src/menus.rs | 3 + crates/ui-egui/src/resources_updater.rs | 383 ++++++++++++++++++ .../src/resources_updater/row_request.rs | 9 + crates/ui-egui/src/state.rs | 5 + crates/ui-egui/src/state/resources_updater.rs | 19 + crates/ui-egui/src/toast_action.rs | 34 ++ crates/ui-egui/src/toolbar.rs | 28 +- crates/ui-egui/src/windows.rs | 1 + crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/resources_updater.rs | 137 +++++++ docs/control-protocol.md | 22 +- docs/features.md | 7 + 28 files changed, 1287 insertions(+), 11 deletions(-) create mode 100644 crates/core/src/resource_source.rs create mode 100644 crates/engine/src/reloaded_file.rs create mode 100644 crates/engine/src/resource_state.rs create mode 100644 crates/engine/src/resource_status.rs create mode 100644 crates/engine/src/resource_update_cmds.rs create mode 100644 crates/engine/tests/it/resource_updater.rs create mode 100644 crates/ui-egui/src/resources_updater.rs create mode 100644 crates/ui-egui/src/resources_updater/row_request.rs create mode 100644 crates/ui-egui/src/state/resources_updater.rs create mode 100644 crates/ui-egui/src/toast_action.rs create mode 100644 crates/ui-egui/tests/it/resources_updater.rs diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index a1f18ab9..2e590e15 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -138,6 +138,9 @@ pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError let allowed = match id { "file.close" | "file.removeUnused" => true, "file.reimportMesh" => !has_path, + + // The Resources Updater reads the files a project names, which may lie outside the read root + "resource.status" | "resource.update" | "resource.relink" => false, _ => !id.starts_with("file.") && !has_path, }; if allowed { @@ -245,6 +248,9 @@ mod tests { assert!(authorize_command("file.reimportMesh", &json!({"path": "/etc/x.obj"})).is_err()); assert!(authorize_command("file.reimportMesh", &json!({})).is_ok()); assert!(authorize_command("file.close", &json!({})).is_ok()); + for id in ["resource.status", "resource.update", "resource.relink"] { + assert!(authorize_command(id, &json!({})).is_err(), "{id} reads the host paths a project names"); + } assert!(authorize_command("layer.add.fill", &json!({"color": "#ff0000", "path": null})).is_ok()); } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 88ee96d1..2c5db23b 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -51,6 +51,7 @@ pub mod project; pub mod projector; pub mod ramp_curve; pub mod randomized_seed; +pub mod resource_source; mod saved_decal; mod saved_projection; pub mod selection_background; @@ -133,6 +134,7 @@ pub use project::{ pub use projector::Projector; pub use ramp_curve::RampCurve; pub use randomized_seed::RandomizedSeed; +pub use resource_source::ResourceSource; pub use selection_background::SelectionBackground; pub use shape_crop::ShapeCrop; pub use slope_blending::SlopeBlending; diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 649f4f6d..a4e004ec 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -445,6 +445,10 @@ pub struct Project { /// The project's colour swatches (linear RGB), in the order they were added; projects without any save none #[serde(default, skip_serializing_if = "Vec::is_empty")] pub swatches: Vec<[f32; 3]>, + /// The files image resources were imported from, by resource name (the Resources Updater + /// reads them again). Resources made in the app or imported without a file path have none. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub resource_sources: BTreeMap, } impl Project { @@ -462,6 +466,7 @@ impl Project { display: DisplaySettings::default(), cameras: Vec::new(), swatches: Vec::new(), + resource_sources: BTreeMap::new(), } } diff --git a/crates/core/src/resource_source.rs b/crates/core/src/resource_source.rs new file mode 100644 index 00000000..793122cf --- /dev/null +++ b/crates/core/src/resource_source.rs @@ -0,0 +1,17 @@ +//! Where an image resource was imported from, so the Resources Updater can read it again + +use serde::{Deserialize, Serialize}; + +/// The file an image resource was read from and its modification time then. +/// +/// The resource's stored bytes are the file's bytes at that time, so a file whose size or +/// contents differ from them has changed on disk. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResourceSource { + /// Path of the file on the machine that imported it. + pub path: String, + /// The file's modification time when it was read, in milliseconds since the Unix epoch + /// (0 when unknown). An unchanged time and size skip reading the file again. + #[serde(default)] + pub modified_ms: u64, +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index e34e9327..bb177191 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -31,7 +31,7 @@ impl CommandSpec { /// that only return data or do nothing without parameters, and the ones that replace the /// open project (the menu asks to save first). pub fn bindable(&self) -> bool { - const NOT_FROM_A_KEY: [&str; 13] = [ + const NOT_FROM_A_KEY: [&str; 14] = [ "project.inspect", "project.templates", "project.new", @@ -45,6 +45,7 @@ impl CommandSpec { "bake.preview", "camera.set", "textureSet.settings", + "resource.status", ]; const NOTHING_WITHOUT_PARAMS: [&str; 4] = ["layer.blend", "tool.stencil", "tool.fillSelection", "tool.path"]; !(self.id.ends_with(".list") || NOT_FROM_A_KEY.contains(&self.id) || NOTHING_WITHOUT_PARAMS.contains(&self.id)) && params_all_optional(self.params) @@ -143,6 +144,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::file_cmds::specs()); v.extend(crate::preset_cmds::specs()); v.extend(crate::resource_cmds::specs()); + v.extend(crate::resource_update_cmds::specs()); v.extend(crate::material_lib::specs()); v.extend(crate::link_cmds::specs()); v.extend(crate::smart_masks::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 23c6b489..0d2f8d3c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -68,7 +68,13 @@ pub mod preview; mod procedural_params; pub mod project_cmds; pub mod quick_mask; +// Reloading resource files reads paths on native targets only +#[cfg(not(target_arch = "wasm32"))] +mod reloaded_file; pub mod resource_cmds; +pub mod resource_state; +pub mod resource_status; +pub mod resource_update_cmds; pub mod session; mod session_log; pub mod set_cmds; @@ -97,6 +103,8 @@ pub use fill_hit_test::FillHitTest; pub use fill_mode::FillMode; pub use log::{LogEntry, LogLevel, SessionLog}; pub use path_tool::PathState; +pub use resource_state::ResourceState; +pub use resource_status::ResourceStatus; pub use project_cmds::sample_session; pub use session::{ CloneFrom, CloneSource, Document, HISTORY_TEMPLATES, NORMAL_HEIGHT_MESH_LABEL, Session, SetCache, StackTarget, StencilLook, StencilState, Tool, ToolState, diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index a20182f6..1312aedd 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -623,6 +623,7 @@ impl Session { for name in old_names.iter().filter(|name| !used_names.contains(name)) { session.doc.resources.remove(name); + session.doc.project.resource_sources.remove(name); } Ok(names) diff --git a/crates/engine/src/reloaded_file.rs b/crates/engine/src/reloaded_file.rs new file mode 100644 index 00000000..b65582d2 --- /dev/null +++ b/crates/engine/src/reloaded_file.rs @@ -0,0 +1,28 @@ +//! An image file read again for a resource, checked before the project changes + +use texturecraft_core::ResourceSource; +use texturecraft_formats::DecodedImage; + +use crate::Result; + +/// A resource's new bytes, their decoded pixels and the file they came from +pub(crate) struct ReloadedFile { + pub name: String, + pub bytes: Vec, + pub image: DecodedImage, + pub source: ResourceSource, +} + +impl ReloadedFile { + /// Read and decode `path` for resource `name` within the resource limits (`cmd` names errors) + pub(crate) fn read(cmd: &str, name: String, path: &str) -> Result { + let file_path = std::path::Path::new(path); + + // Taken before reading, so a write during the read still shows as a change later + let modified_ms = crate::resource_update_cmds::modified_ms_of(file_path); + let bytes = crate::resource_cmds::read_resource_file(cmd, file_path, crate::resource_cmds::MAX_BYTES as u64)?; + let image = texturecraft_formats::decode_image(&bytes).map_err(|error| crate::commands::bad(cmd, format!("{path}: {error}")))?; + + Ok(ReloadedFile { name, bytes, image, source: ResourceSource { path: crate::resource_update_cmds::absolute_path(path), modified_ms } }) + } +} diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 39d9fb6c..d20cb60e 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -146,6 +146,16 @@ impl Session { self.drop_missing_image_view(); } + /// Undo and redo restore resource bytes under the same name (the Resources Updater replaces + /// them in place): the pixels decoded from the bytes `other` held are stale + pub(crate) fn forget_replaced_images(&mut self, other: &crate::Document) { + for (name, bytes) in &self.doc.resources { + if other.resources.get(name).is_some_and(|previous| !Arc::ptr_eq(previous, bytes)) { + self.images.remove(name); + } + } + } + /// The "Other..." view cannot show an image that is gone (removed or renamed): the material comes back pub(crate) fn drop_missing_image_view(&mut self) { if self.view == crate::ViewMode::Image && !self.view_image.as_ref().is_some_and(|name| self.images.contains_key(name)) { @@ -172,8 +182,18 @@ fn list(s: &Session) -> Value { #[cfg(not(target_arch = "wasm32"))] fn import(s: &mut Session, p: &Value) -> Result { let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?; + let prefix = strp(p, "prefix").unwrap_or(""); + + // Taken before reading, so a write during the read still shows as a change in the Resources Updater + let modified_ms = crate::resource_update_cmds::modified_ms_of(std::path::Path::new(path)); let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?; - let name = s.import_resource_bytes_prefixed(strp(p, "prefix").unwrap_or(""), path, bytes)?; + let source = texturecraft_core::ResourceSource { path: crate::resource_update_cmds::absolute_path(path), modified_ms }; + + let name = s.edit("Import resource", |session| { + let name = session.add_image_resource_prefixed(prefix, path, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)?; + session.doc.project.resource_sources.insert(name.clone(), source); + Ok(name) + })?; Ok(json!({ "name": name })) } @@ -255,6 +275,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { s.edit("Remove resource", |s| { s.doc.resources.remove(&name); + s.doc.project.resource_sources.remove(&name); Ok(()) })?; s.sync_images(); @@ -277,6 +298,7 @@ fn remove_unused(s: &mut Session, _: &Value) -> Result { if !unused.is_empty() { s.edit("Remove unused resources", |s| { s.doc.resources.retain(|k, _| !unused.contains(k)); + s.doc.project.resource_sources.retain(|k, _| !unused.contains(k)); Ok(()) })?; s.sync_images(); diff --git a/crates/engine/src/resource_state.rs b/crates/engine/src/resource_state.rs new file mode 100644 index 00000000..1a3e427c --- /dev/null +++ b/crates/engine/src/resource_state.rs @@ -0,0 +1,15 @@ +//! One row of the Resources Updater: an image resource, its file and how they compare + +use crate::resource_status::ResourceStatus; + +/// An image resource, the file it came from and whether that file changed on disk +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ResourceState { + /// The resource's name in the project. + pub name: String, + pub status: ResourceStatus, + /// The file it was imported from or relinked to (None: made in the app or imported without a path). + pub path: Option, + /// Why the file could not be checked (with [`ResourceStatus::Missing`]). + pub error: Option, +} diff --git a/crates/engine/src/resource_status.rs b/crates/engine/src/resource_status.rs new file mode 100644 index 00000000..8e8efc70 --- /dev/null +++ b/crates/engine/src/resource_status.rs @@ -0,0 +1,39 @@ +//! Whether an image resource still matches the file it was imported from + +/// How an image resource compares with its file on disk. The order is the Resources Updater's +/// list order: what needs attention first. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum ResourceStatus { + /// The file changed since it was read: Update reads it again. + Outdated, + /// The file is gone, or cannot be read. + Missing, + /// The file still holds the resource's bytes. + UpToDate, + /// Made in the app or imported without a file path: there is nothing to compare with. + NoSource, +} + +impl ResourceStatus { + pub const ALL: [ResourceStatus; 4] = [ResourceStatus::Outdated, ResourceStatus::Missing, ResourceStatus::UpToDate, ResourceStatus::NoSource]; + + /// The id used by the control protocol + pub fn id(self) -> &'static str { + match self { + ResourceStatus::Outdated => "outdated", + ResourceStatus::Missing => "missing", + ResourceStatus::UpToDate => "upToDate", + ResourceStatus::NoSource => "noSource", + } + } + + /// The name shown in the Resources Updater (English; the shell translates it) + pub fn label(self) -> &'static str { + match self { + ResourceStatus::Outdated => "Outdated", + ResourceStatus::Missing => "Missing", + ResourceStatus::UpToDate => "Up to date", + ResourceStatus::NoSource => "No source file", + } + } +} diff --git a/crates/engine/src/resource_update_cmds.rs b/crates/engine/src/resource_update_cmds.rs new file mode 100644 index 00000000..ea69042d --- /dev/null +++ b/crates/engine/src/resource_update_cmds.rs @@ -0,0 +1,241 @@ +//! The Resources Updater: compare image resources with the files they came from, read changed +//! files again and point a resource at another file. Each change is one undo step, and every +//! layer, mask and view using a changed resource recomposites. + +use serde_json::{Value, json}; +use texturecraft_core::ResourceSource; + +use crate::commands::{CommandSpec, always, bad}; +use crate::resource_state::ResourceState; +use crate::resource_status::ResourceStatus; +use crate::{Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![ + cmd!( + "resource.status", + "Check resources on disk", + [], + None, + "{} → {resources: [{name, status: outdated|missing|upToDate|noSource, path?, error?}] (outdated first), total, outdated}", + always, + |s, _| Ok(status(s)) + ), + cmd!( + "resource.update", + "Update resources", + [], + None, + "{names?: [resource name] (default: every outdated resource)} → {updated, failed: [{name, error}]} — reads their files again, one undo step", + always, + update + ), + cmd!( + "resource.relink", + "Relink resource", + [], + None, + "{name, path — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr)} → {name, path} — the resource takes the file's pixels and follows it from now on", + always, + relink + ), + ] +} + +impl Session { + /// The image resources with their files and how they compare, outdated first, then by name. + /// Reads a file only when its size matches the stored bytes but its modification time does not. + pub fn resource_states(&self) -> Vec { + let sources = &self.doc.project.resource_sources; + let mut states: Vec = self + .doc + .resources + .iter() + .filter(|(name, _)| self.images.contains_key(*name) || sources.contains_key(*name)) + .map(|(name, bytes)| { + let source = sources.get(name); + let (status, error) = source.map_or((ResourceStatus::NoSource, None), |source| compare_with_file(source, bytes)); + ResourceState { name: name.clone(), status, path: source.map(|source| source.path.clone()), error } + }) + .collect(); + + states.sort_by(|a, b| a.status.cmp(&b.status).then_with(|| a.name.cmp(&b.name))); + states + } + + /// Put reloaded files in place of their resources' bytes and pixels as one undo step + #[cfg(not(target_arch = "wasm32"))] + fn install_reloaded(&mut self, label: &str, files: Vec) -> Result> { + if files.is_empty() { + return Ok(Vec::new()); + } + + let decoded = self.edit(label, |session| { + let mut decoded = Vec::with_capacity(files.len()); + for file in files { + session.doc.resources.insert(file.name.clone(), std::sync::Arc::new(file.bytes)); + session.doc.project.resource_sources.insert(file.name.clone(), file.source); + decoded.push((file.name, file.image)); + } + + Ok(decoded) + })?; + + // The edit marked every set using a replaced resource for recompositing; the new pixels are read then + let mut names = Vec::with_capacity(decoded.len()); + for (name, image) in decoded { + if crate::fill_alpha::matches_saved_picture(&name, &image) { + self.library_alphas.insert(name.clone()); + } else { + self.library_alphas.remove(&name); + } + + self.images.insert(name.clone(), crate::resource_cmds::decoded(image)); + names.push(name); + } + + Ok(names) + } +} + +/// How `stored` (a resource's bytes) compares with the file `source` names now +#[cfg(not(target_arch = "wasm32"))] +fn compare_with_file(source: &ResourceSource, stored: &[u8]) -> (ResourceStatus, Option) { + let path = std::path::Path::new(&source.path); + let metadata = match std::fs::metadata(path) { + Ok(metadata) if metadata.is_file() => metadata, + Ok(_) => return (ResourceStatus::Missing, Some(format!("{} is not a regular file", source.path))), + Err(error) => return (ResourceStatus::Missing, Some(format!("{}: {error}", source.path))), + }; + + if metadata.len() != stored.len() as u64 { + return (ResourceStatus::Outdated, None); + } + + let modified_ms = modified_ms(&metadata); + if modified_ms != 0 && modified_ms == source.modified_ms { + return (ResourceStatus::UpToDate, None); + } + + // A newer time alone is not a change: the file may have been saved again unchanged + match crate::resource_cmds::read_resource_file("resource.status", path, crate::resource_cmds::MAX_BYTES as u64) { + Ok(bytes) if bytes == stored => (ResourceStatus::UpToDate, None), + Ok(_) => (ResourceStatus::Outdated, None), + Err(error) => (ResourceStatus::Missing, Some(error.to_string())), + } +} + +#[cfg(target_arch = "wasm32")] +fn compare_with_file(_: &ResourceSource, _: &[u8]) -> (ResourceStatus, Option) { + (ResourceStatus::Missing, Some("file paths are not available in the browser".to_string())) +} + +/// A file's modification time in milliseconds since the Unix epoch (0 when the system has none) +#[cfg(not(target_arch = "wasm32"))] +fn modified_ms(metadata: &std::fs::Metadata) -> u64 { + let since_epoch = metadata.modified().ok().and_then(|modified| modified.duration_since(std::time::UNIX_EPOCH).ok()); + since_epoch.map_or(0, |elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)) +} + +/// [`modified_ms`] of the file at `path` (0 when it cannot be read) +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn modified_ms_of(path: &std::path::Path) -> u64 { + std::fs::metadata(path).map_or(0, |metadata| modified_ms(&metadata)) +} + +/// `path` made absolute against the working folder, so the record does not depend on where the app started +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn absolute_path(path: &str) -> String { + std::path::absolute(path).ok().and_then(|absolute| absolute.to_str().map(str::to_string)).unwrap_or_else(|| path.to_string()) +} + +fn status(s: &Session) -> Value { + let states = s.resource_states(); + let outdated = states.iter().filter(|state| state.status == ResourceStatus::Outdated).count(); + let resources: Vec = states + .iter() + .map(|state| { + let mut row = json!({"name": state.name, "status": state.status.id()}); + if let Some(path) = &state.path { + row["path"] = json!(path); + } + if let Some(error) = &state.error { + row["error"] = json!(error); + } + + row + }) + .collect(); + + json!({"resources": resources, "total": states.len(), "outdated": outdated}) +} + +#[cfg(not(target_arch = "wasm32"))] +fn update(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "resource.update"; + + let names: Vec = match p.get("names") { + None | Some(Value::Null) => s.resource_states().into_iter().filter(|state| state.status == ResourceStatus::Outdated).map(|state| state.name).collect(), + Some(Value::Array(names)) => { + names.iter().map(|name| name.as_str().map(str::to_string).ok_or_else(|| bad(CMD, "`names` must be resource names"))).collect::>()? + } + Some(_) => return Err(bad(CMD, "`names` must be an array of resource names")), + }; + + // Every name is checked before any file is read + for name in &names { + if !s.doc.resources.contains_key(name) { + return Err(bad(CMD, format!("no resource `{name}`"))); + } + if !s.doc.project.resource_sources.contains_key(name) { + return Err(bad(CMD, format!("`{name}` has no source file: relink it to a file first"))); + } + } + + // A file that cannot be read fails alone; the others still update + let (mut files, mut failed) = (Vec::new(), Vec::new()); + for name in names { + let Some(path) = s.doc.project.resource_sources.get(&name).map(|source| source.path.clone()) else { continue }; + match crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), &path) { + // Unchanged contents need no undo step + Ok(file) if s.doc.resources.get(&name).is_some_and(|stored| **stored == file.bytes) => {} + Ok(file) => files.push(file), + Err(error) => failed.push(json!({"name": name, "error": error.to_string()})), + } + } + + if files.is_empty() && !failed.is_empty() { + let reasons: Vec<&str> = failed.iter().filter_map(|failure| failure["error"].as_str()).collect(); + return Err(bad(CMD, format!("nothing was updated: {}", reasons.join("; ")))); + } + + let updated = s.install_reloaded("Update resources", files)?; + Ok(json!({"updated": updated, "failed": failed})) +} + +#[cfg(not(target_arch = "wasm32"))] +fn relink(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "resource.relink"; + + let name = crate::commands::strp(p, "name").ok_or_else(|| bad(CMD, "`name` is required"))?.to_string(); + let path = crate::commands::strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?; + if !s.doc.resources.contains_key(&name) { + return Err(bad(CMD, format!("no resource `{name}`"))); + } + + let file = crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), path)?; + let path = file.source.path.clone(); + s.install_reloaded("Relink resource", vec![file])?; + + Ok(json!({"name": name, "path": path})) +} + +#[cfg(target_arch = "wasm32")] +fn update(_: &mut Session, _: &Value) -> Result { + Err(bad("resource.update", "file paths are not available in the browser")) +} + +#[cfg(target_arch = "wasm32")] +fn relink(_: &mut Session, _: &Value) -> Result { + Err(bad("resource.relink", "file paths are not available in the browser")) +} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 58b5cbe7..beb20ab0 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -957,6 +957,7 @@ impl Session { let (label, restored) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?; let current = std::mem::replace(&mut self.doc, restored); self.after_history(¤t); + self.forget_replaced_images(¤t); self.redo.push((label.clone(), current)); self.sync_images(); Ok(label) @@ -977,6 +978,7 @@ impl Session { let (label, restored) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?; let current = std::mem::replace(&mut self.doc, restored); self.after_history(¤t); + self.forget_replaced_images(¤t); self.undo.push((label.clone(), current)); self.sync_images(); Ok(label) diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index ce9f1614..5010e30f 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -55,6 +55,7 @@ mod pbr_import; mod perf; mod polygon_fill; mod project_recovery; +mod resource_updater; mod resources_used; mod sample; mod solo; diff --git a/crates/engine/tests/it/resource_updater.rs b/crates/engine/tests/it/resource_updater.rs new file mode 100644 index 00000000..c0d0f1dc --- /dev/null +++ b/crates/engine/tests/it/resource_updater.rs @@ -0,0 +1,227 @@ +//! The Resources Updater: image resources remember their files, a changed file shows as outdated, +//! Update reads it again (one undo step, recompositing its layers) and Relink follows another file + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{ResourceStatus, Session, execute}; + +const RESOLUTION: u32 = 64; +const SAMPLE_STRIDE: usize = 4; +const RED: [u8; 4] = [255, 0, 0, 255]; +const GREEN: [u8; 4] = [0, 255, 0, 255]; + +/// A test folder removed when dropped +struct TempDir(PathBuf); + +impl TempDir { + fn new(test: &str) -> TempDir { + let path = std::env::temp_dir().join(format!("tc-resource-updater-{test}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).unwrap(); + TempDir(path) + } + + fn file(&self, name: &str) -> PathBuf { + self.0.join(name) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn session() -> Session { + Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, RESOLUTION).unwrap() +} + +/// Write a `size` × `size` PNG of one colour (sizes differ between versions, so the file size changes too) +fn write_png(path: &Path, size: u32, color: [u8; 4]) { + image::RgbaImage::from_pixel(size, size, image::Rgba(color)).save(path).unwrap(); +} + +fn text(path: &Path) -> &str { + path.to_str().unwrap() +} + +/// Import `path` and show it as a base colour fill; returns the resource name +fn import_as_fill(s: &mut Session, path: &Path) -> String { + let name = execute(s, "resource.import", &json!({"path": text(path)})).unwrap()["name"].as_str().unwrap().to_string(); + execute(s, "layer.add.image", &json!({"name": name})).unwrap(); + s.update(); + name +} + +fn base_colors(s: &Session) -> Vec<[f32; 3]> { + let composite = &s.caches[s.ts()].composite; + let samples = || (0..RESOLUTION).step_by(SAMPLE_STRIDE); + samples().flat_map(|y| samples().map(move |x| (x, y))).map(|(x, y)| composite.value(Channel::BaseColor, x, y)).collect() +} + +fn status_of(s: &Session, name: &str) -> ResourceStatus { + s.resource_states().into_iter().find(|state| state.name == name).expect("the resource is listed").status +} + +#[test] +fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() { + let dir = TempDir::new("update"); + let file = dir.file("bricks.png"); + write_png(&file, 4, RED); + let mut s = session(); + let name = import_as_fill(&mut s, &file); + let before = base_colors(&s); + assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate); + + write_png(&file, 8, GREEN); + let status = execute(&mut s, "resource.status", &Value::Null).unwrap(); + + assert_eq!(status["outdated"], json!(1)); + assert_eq!(status["resources"][0]["name"], json!(name)); + assert_eq!(status["resources"][0]["status"], json!("outdated")); + + let steps = s.history_labels().len(); + let updated = execute(&mut s, "resource.update", &json!({})).unwrap(); + s.update(); + let after = base_colors(&s); + + assert_eq!(updated["updated"], json!([name])); + assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); + assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate); + assert_eq!(s.images[&name].width, 8, "the new pixels are decoded"); + assert_ne!(after, before, "the fill using the resource recomposited"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + + assert_eq!(s.images[&name].width, 4, "undo brings back the old pixels under the same name"); + assert_eq!(base_colors(&s), before); + assert_eq!(status_of(&s, &name), ResourceStatus::Outdated, "the file on disk is still the new one"); + + execute(&mut s, "edit.redo", &Value::Null).unwrap(); + s.update(); + + assert_eq!(s.images[&name].width, 8); + assert_eq!(base_colors(&s), after); +} + +#[test] +fn nothing_outdated_adds_no_undo_step() { + let dir = TempDir::new("unchanged"); + let file = dir.file("same.png"); + write_png(&file, 4, RED); + let mut s = session(); + import_as_fill(&mut s, &file); + let steps = s.history_labels().len(); + + let updated = execute(&mut s, "resource.update", &json!({})).unwrap(); + + assert_eq!(updated["updated"], json!([])); + assert_eq!(s.history_labels().len(), steps); +} + +#[test] +fn a_missing_file_is_reported_and_updating_it_changes_nothing() { + let dir = TempDir::new("missing"); + let file = dir.file("gone.png"); + write_png(&file, 4, RED); + let mut s = session(); + let name = import_as_fill(&mut s, &file); + std::fs::remove_file(&file).unwrap(); + let steps = s.history_labels().len(); + + let state = s.resource_states().into_iter().find(|state| state.name == name).unwrap(); + let error = execute(&mut s, "resource.update", &json!({"names": [name]})).unwrap_err(); + + assert_eq!(state.status, ResourceStatus::Missing); + assert!(state.error.is_some(), "the reason is shown"); + assert!(error.to_string().contains("nothing was updated"), "{error}"); + assert_eq!(s.history_labels().len(), steps); + assert_eq!(s.images[&name].width, 4, "the resource keeps its pixels"); +} + +#[test] +fn an_unreadable_file_fails_alone_while_the_others_update() { + let dir = TempDir::new("partial"); + let (kept, gone) = (dir.file("kept.png"), dir.file("gone.png")); + write_png(&kept, 4, RED); + write_png(&gone, 4, RED); + let mut s = session(); + let kept_name = import_as_fill(&mut s, &kept); + let gone_name = import_as_fill(&mut s, &gone); + write_png(&kept, 8, GREEN); + std::fs::remove_file(&gone).unwrap(); + + let result = execute(&mut s, "resource.update", &json!({"names": [kept_name, gone_name]})).unwrap(); + + assert_eq!(result["updated"], json!([kept_name])); + assert_eq!(result["failed"][0]["name"], json!(gone_name)); + assert_eq!(s.images[&kept_name].width, 8); +} + +#[test] +fn relink_reads_another_file_and_follows_it_from_then_on() { + let dir = TempDir::new("relink"); + let (first, second) = (dir.file("first.png"), dir.file("second.png")); + write_png(&first, 4, RED); + write_png(&second, 8, GREEN); + let mut s = session(); + let name = import_as_fill(&mut s, &first); + let before = base_colors(&s); + let steps = s.history_labels().len(); + + execute(&mut s, "resource.relink", &json!({"name": name, "path": text(&second)})).unwrap(); + s.update(); + + assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); + assert_eq!(s.images[&name].width, 8, "the resource keeps its name and takes the new file's pixels"); + assert_ne!(base_colors(&s), before); + assert!(s.doc.project.resource_sources[&name].path.ends_with("second.png")); + + // The old file no longer matters, the new one does + write_png(&first, 16, GREEN); + assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate); + write_png(&second, 16, RED); + assert_eq!(status_of(&s, &name), ResourceStatus::Outdated); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.doc.project.resource_sources[&name].path.ends_with("first.png"), "undo restores the link"); +} + +#[test] +fn resources_without_a_file_cannot_update_and_a_reopened_project_keeps_its_links() { + let dir = TempDir::new("reopen"); + let file = dir.file("kept.png"); + write_png(&file, 4, RED); + let mut s = session(); + let linked = import_as_fill(&mut s, &file); + let png = std::fs::read(&file).unwrap(); + let unlinked = s.import_resource_bytes("made.png", png).unwrap(); + + assert_eq!(status_of(&s, &unlinked), ResourceStatus::NoSource); + assert!(execute(&mut s, "resource.update", &json!({"names": [unlinked]})).is_err()); + + let reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + write_png(&file, 8, GREEN); + + assert_eq!(status_of(&reopened, &linked), ResourceStatus::Outdated); +} + +#[test] +fn a_removed_resource_forgets_its_file() { + let dir = TempDir::new("remove"); + let file = dir.file("old.png"); + write_png(&file, 4, RED); + let mut s = session(); + let name = execute(&mut s, "resource.import", &json!({"path": text(&file)})).unwrap()["name"].as_str().unwrap().to_string(); + + execute(&mut s, "resource.remove", &json!({"name": name})).unwrap(); + let png = std::fs::read(&file).unwrap(); + let reused = s.import_resource_bytes("old.png", png).unwrap(); + + assert_eq!(reused, name, "the name is free again"); + assert_eq!(status_of(&s, &reused), ResourceStatus::NoSource, "a new resource under the old name does not inherit the file"); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 47259f2b..100d07a5 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -124,6 +124,8 @@ mod resolution_band; mod resource_panel; mod resource_picker; mod resource_picker_item; +#[cfg(not(target_arch = "wasm32"))] +mod resources_updater; mod round_gizmo; mod running_bake; pub mod saved_search; @@ -156,6 +158,7 @@ pub mod thumbs; mod tile_edits; mod tile_picture; pub mod titlebar; +pub mod toast_action; pub mod toolbar; pub mod ui_state_store; pub mod unavailable; @@ -235,6 +238,8 @@ pub struct Toast { pub error: bool, pub until: f64, pub show_log: bool, + /// A button after the text that acts on the notice + pub action: Option, } pub struct TextureCraftApp { @@ -317,6 +322,9 @@ pub struct TextureCraftApp { styled: Option<(theme::Brightness, theme::Accent)>, /// Whether the window had focus last frame. focused: bool, + /// The outdated resources the last "changed on disk" notice named, so an unchanged set is not announced again + #[cfg(not(target_arch = "wasm32"))] + pub(crate) resources_notified: std::collections::BTreeSet, /// The update check and prompt (desktop only). #[cfg(not(target_arch = "wasm32"))] pub(crate) updates_rt: updates_ui::Runtime, @@ -439,6 +447,8 @@ impl TextureCraftApp { styled: None, focused: true, #[cfg(not(target_arch = "wasm32"))] + resources_notified: std::collections::BTreeSet::new(), + #[cfg(not(target_arch = "wasm32"))] updates_rt: updates_ui::Runtime::default(), #[cfg(not(target_arch = "wasm32"))] file_dialogs: file_dialogs::FileDialogs::new(cc.egui_ctx.clone()), @@ -590,13 +600,13 @@ impl TextureCraftApp { } pub fn toast(&mut self, text: impl Into, error: bool) { - self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 }, show_log: false }); + self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 }, show_log: false, action: None }); } /// An error toast that stays until the user dismisses it (for a problem that persists and /// is reported once, like a texture set the GPU could not hold). pub fn toast_sticky(&mut self, text: impl Into) { - self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false }); + self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false, action: None }); } /// Start baking texture sets in the background, one after another. Invalid set indices @@ -1117,6 +1127,10 @@ impl eframe::App for TextureCraftApp { let focused = ctx.input(|input| input.viewport().focused).unwrap_or(true); if focused && !self.focused { self.library = None; + + // Files may have been edited in another app meanwhile + #[cfg(not(target_arch = "wasm32"))] + resources_updater::check_on_focus(self); } self.focused = focused; @@ -1292,6 +1306,7 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { let tk = theme::Tokens::get(ctx); let mut dismissed = None; let mut show_log = false; + let mut clicked_action = None; // Limit toast dimensions so the dismiss button stays visible let screen = ctx.content_rect().size(); @@ -1320,6 +1335,12 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { show_log = true; dismissed = Some(i); } + if let Some(action) = t.action + && ui.button(i18n::tr(action.label())).clicked() + { + clicked_action = Some(action); + dismissed = Some(i); + } }); if sticky && widgets::icon_button(ui, egui_phosphor::regular::X, i18n::tr("Dismiss"), false, 18.0).clicked() { dismissed = Some(i); @@ -1337,4 +1358,8 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.ui.log_channel = log_panel::LogChannel::General; crate::rail_popup::open(app, crate::docking::Panel::Log); } + + if let Some(action) = clicked_action { + action.run(app); + } } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 1d4588ea..a0fd80de 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -526,6 +526,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { } else if app.ui.windows.import_resources.is_some() { #[cfg(not(target_arch = "wasm32"))] crate::import_resources::keys_in(app, input, nothing_focused, popup_open); + } else if app.ui.windows.resources_updater.is_some() && !popup_open && input.key_pressed(Key::Escape) { + #[cfg(not(target_arch = "wasm32"))] + crate::resources_updater::keys_in(app, input); } else if !popup_open && app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_color = None; } else if escape_is_free && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { diff --git a/crates/ui-egui/src/resources_updater.rs b/crates/ui-egui/src/resources_updater.rs new file mode 100644 index 00000000..4bb9ce60 --- /dev/null +++ b/crates/ui-egui/src/resources_updater.rs @@ -0,0 +1,383 @@ +//! The Resources Updater: the project's image resources and whether the files they were imported +//! from changed on disk. Update reads a changed file again, Select new resource points a resource +//! at another file, and a notice offers to update when the app gets the focus back after files +//! changed. Everything runs through `resource.status`, `resource.update` and `resource.relink`. + +mod row_request; + +use std::collections::BTreeSet; + +use egui::{Key, Modifiers}; +use serde_json::json; +use texturecraft_engine::{ResourceState, ResourceStatus}; + +use crate::TextureCraftApp; +use crate::file_dialogs::{Bound, FileDialog}; +use crate::i18n::{tr, trf}; +use crate::state::ResourcesUpdater; +use crate::theme::Tokens; +use crate::toast_action::ToastAction; +use crate::web_files::IMAGE_EXTS; +use crate::widgets::primary_button; +use row_request::RowRequest; + +/// Width of the window +const WINDOW_WIDTH_POINTS: f32 = 640.0; +/// Height of the resource list +const LIST_HEIGHT_POINTS: f32 = 360.0; +// Initial space for the header, tabs, filters and footer +const WINDOW_CHROME_HEIGHT_POINTS: f32 = 160.0; +/// Side of a row's thumbnail +const THUMBNAIL_POINTS: f32 = 40.0; +/// Width of the name filter field +const NAME_FILTER_WIDTH_POINTS: f32 = 160.0; +/// Width of the status dropdown +const STATUS_WIDTH_POINTS: f32 = 120.0; +/// Space inside a row's frame +const ROW_MARGIN: egui::Margin = egui::Margin::same(4); +/// Strength of the danger tint behind an outdated row (the status text says it too) +const OUTDATED_TINT: f32 = 0.18; +/// How long the "changed on disk" notice stays, in seconds: long enough to reach its button +const NOTICE_SECONDS: f64 = 12.0; + +/// Opens the window, or closes it when it is open (the shelf button) +pub(crate) fn toggle(app: &mut TextureCraftApp) { + if app.ui.windows.resources_updater.take().is_none() { + open(app); + } +} + +/// Opens the window with the resources checked now (an open window is checked again) +pub(crate) fn open(app: &mut TextureCraftApp) { + let window = app.ui.windows.resources_updater.take().unwrap_or_default(); + app.ui.windows.resources_updater = Some(ResourcesUpdater { + rows: app.session.resource_states(), + project: app.session.project_id, + checked_revision: app.session.revision, + ..window + }); +} + +/// The app has the focus back: check the files again and, when other resources than last time +/// are outdated, show a notice whose button updates them +pub(crate) fn check_on_focus(app: &mut TextureCraftApp) { + if !app.session.project_open { + return; + } + + let rows = app.session.resource_states(); + let outdated: BTreeSet = rows.iter().filter(|row| row.status == ResourceStatus::Outdated).map(|row| row.name.clone()).collect(); + if let Some(window) = app.ui.windows.resources_updater.as_mut() { + window.rows = rows; + window.checked_revision = app.session.revision; + } + + if !outdated.is_empty() && outdated != app.resources_notified { + let text = if outdated.len() == 1 { + tr("1 resource changed on disk").to_string() + } else { + trf("{count} resources changed on disk", &[("count", &outdated.len())]) + }; + app.toast(text, false); + if let Some(toast) = app.toasts.last_mut() { + toast.until = app.last_time + NOTICE_SECONDS; + toast.action = Some(ToastAction::UpdateResources); + } + } + app.resources_notified = outdated; +} + +/// Read the files of `names` again (every outdated resource when None), one undo step, and say +/// what happened +pub(crate) fn update(app: &mut TextureCraftApp, names: Option>) { + let params = match names { + Some(names) => json!({ "names": names }), + None => json!({}), + }; + let Some(result) = app.run("resource.update", params) else { return }; + + let updated = result["updated"].as_array().map_or(0, Vec::len); + let failed: Vec = result["failed"] + .as_array() + .into_iter() + .flatten() + .map(|failure| format!("{}: {}", failure["name"].as_str().unwrap_or_default(), failure["error"].as_str().unwrap_or_default())) + .collect(); + if failed.is_empty() { + app.toast(trf("Updated {count} resources", &[("count", &updated)]), false); + } else { + app.toast(trf("Updated {count} resources; could not update {failed}", &[("count", &updated), ("failed", &failed.join("; "))]), true); + } + + // What was announced is handled; a later change is announced again + app.resources_notified.clear(); +} + +/// Ask for another file for resource `name`; the resource takes its pixels and follows it +fn select_new_resource(app: &mut TextureCraftApp, name: String) { + let dialog = FileDialog::open().filter(tr("Images"), IMAGE_EXTS); + app.ask_file(dialog, Bound::Project, move |app, paths| { + let Some(path) = paths.first() else { return }; + let Some(path) = path.to_str() else { + app.toast(trf("Could not use a path that is not UTF-8: {path}", &[("path", &path.display())]), true); + return; + }; + + if app.run("resource.relink", json!({ "name": name, "path": path })).is_some() { + app.toast(trf("{name} now reads {path}", &[("name", &name), ("path", &path)]), false); + } + }); +} + +/// Show the folder holding `path` in the system's file manager +fn show_in_folder(app: &mut TextureCraftApp, path: &str) { + let folder = std::path::Path::new(path).parent().map(std::path::Path::to_path_buf).unwrap_or_default(); + if let Err(error) = app.file_dialogs.show_folder(&folder) { + app.toast(trf("Could not show {folder}: {error}", &[("folder", &folder.display()), ("error", &error)]), true); + } +} + +/// The keys of the open window: Escape closes it (an open dropdown takes it first, see `menus`) +pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState) { + if input.consume_key(Modifiers::NONE, Key::Escape) { + app.ui.windows.resources_updater = None; + } +} + +/// Whether `row` passes the window's status and name filters +fn shown(window: &ResourcesUpdater, row: &ResourceState) -> bool { + let name_filter = window.name_filter.trim().to_lowercase(); + window.status_filter.is_none_or(|status| row.status == status) && (name_filter.is_empty() || row.name.to_lowercase().contains(&name_filter)) +} + +/// "(N resources, M outdated)" +fn summary(rows: &[ResourceState]) -> String { + let outdated = rows.iter().filter(|row| row.status == ResourceStatus::Outdated).count(); + trf("({count} resources, {outdated} outdated)", &[("count", &rows.len()), ("outdated", &outdated)]) +} + +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(mut window) = app.ui.windows.resources_updater.take() else { return }; + + // Resources of another project are not this one's + if window.project != app.session.project_id || !app.session.project_open { + return; + } + + // Every change (an update, undo, redo, a removed resource) is checked again + if window.checked_revision != app.session.revision { + window.rows = app.session.resource_states(); + window.checked_revision = app.session.revision; + } + + let tokens = Tokens::get(ctx); + let mut open = true; + let (mut refresh, mut update_all) = (false, false); + let mut request = None; + + crate::windows::dialog(ctx, "resources_updater", tr("Resources Updater"), &mut open) + .default_size(egui::vec2(WINDOW_WIDTH_POINTS, LIST_HEIGHT_POINTS + WINDOW_CHROME_HEIGHT_POINTS)) + .show(ctx, |ui| { + ui.label(format!("{} {}", tr("Project :"), app.session.doc.project.name)); + + // Shader resources have no equivalent here: the one tab lists image resources + let tab = ui.add(egui::Button::selectable(true, tr("Resources"))); + tab.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, true, tr("Resources"))); + ui.separator(); + + ui.horizontal(|ui| { + let status_label = ui.label(tr("Status:")); + let selected = window.status_filter.map_or(tr("All"), |status| tr(status.label())); + egui::ComboBox::from_id_salt("resources_updater_status") + .width(STATUS_WIDTH_POINTS) + .selected_text(selected) + .show_ui(ui, |ui| { + ui.selectable_value(&mut window.status_filter, None, tr("All")); + for status in ResourceStatus::ALL { + ui.selectable_value(&mut window.status_filter, Some(status), tr(status.label())); + } + }) + .response + .labelled_by(status_label.id); + + let name_label = ui.label(tr("Name filter:")); + ui.add(egui::TextEdit::singleline(&mut window.name_filter).desired_width(NAME_FILTER_WIDTH_POINTS)).labelled_by(name_label.id); + + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Bottom")).clicked() { + window.jump = Some(egui::Align::Max); + } + if ui.button(tr("Top")).clicked() { + window.jump = Some(egui::Align::Min); + } + }); + }); + ui.add_space(4.0); + + ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { + ui.horizontal(|ui| { + refresh = ui.button(tr("Refresh")).clicked(); + ui.label(summary(&window.rows)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let outdated = window.rows.iter().any(|row| row.status == ResourceStatus::Outdated); + let button = ui.add_enabled(outdated, primary_button(ui, tr("Update All"))); + update_all = button.on_disabled_hover_text(tr("No resource is outdated")).clicked(); + }); + }); + ui.separator(); + + let list_height = ui.available_height().max(0.0); + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + egui::ScrollArea::vertical().max_height(list_height).auto_shrink([false, false]).show(ui, |ui| { + let jump = window.jump.take(); + if jump == Some(egui::Align::Min) { + ui.scroll_to_cursor(Some(egui::Align::Min)); + } + + let visible: Vec<&ResourceState> = window.rows.iter().filter(|row| shown(&window, row)).collect(); + if visible.is_empty() { + ui.label(tr("No resources match the filters")); + } + for (index, row) in visible.into_iter().enumerate() { + if let Some(asked) = row_ui(app, ui, &tokens, index + 1, row) { + request = Some(asked); + } + } + + if jump == Some(egui::Align::Max) { + ui.scroll_to_cursor(Some(egui::Align::Max)); + } + }); + }); + }); + }); + + if !open { + return; + } + + app.ui.windows.resources_updater = Some(window); + + if refresh { + open(app); + } + if update_all { + update(app, None); + } + match request { + Some(RowRequest::Update(name)) => update(app, Some(vec![name])), + Some(RowRequest::SelectNew(name)) => select_new_resource(app, name), + Some(RowRequest::ShowFolder(path)) => show_in_folder(app, &path), + None => {} + } +} + +/// One resource: its thumbnail, number, name, file and status, and its buttons. Outdated rows are +/// tinted, and their status says so in words too. +fn row_ui(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, number: usize, row: &ResourceState) -> Option { + let outdated = row.status == ResourceStatus::Outdated; + let (fill, stroke) = if outdated { + (tokens.danger.gamma_multiply(OUTDATED_TINT), egui::Stroke::new(1.0, tokens.danger)) + } else { + (egui::Color32::TRANSPARENT, egui::Stroke::NONE) + }; + let mut request = None; + + egui::Frame::NONE.fill(fill).stroke(stroke).inner_margin(ROW_MARGIN).corner_radius(crate::theme::CARD_RADIUS).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + match app.session.images.get(&row.name) { + Some(image) => { + let texture = app.thumbs.image(ui.ctx(), &row.name, image); + ui.add(egui::Image::new(&texture).fit_to_exact_size(egui::vec2(THUMBNAIL_POINTS, THUMBNAIL_POINTS))); + } + + // A file that could not be decoded has no picture; the row keeps its place + None => ui.add_space(THUMBNAIL_POINTS), + } + ui.label(number.to_string()); + + // Buttons take their room on the right first, so the texts truncate in what is left + // Each button's accessible name says which resource it acts on + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let update = ui.add_enabled(outdated, egui::Button::new(tr("Update"))); + let update_name = format!("{} {}", tr("Update"), row.name); + update.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, outdated, &update_name)); + if update.clicked() { + request = Some(RowRequest::Update(row.name.clone())); + } + + let select = ui.button(tr("Select new resource")); + let select_name = format!("{} {}", tr("Select new resource"), row.name); + select.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &select_name)); + if select.clicked() { + request = Some(RowRequest::SelectNew(row.name.clone())); + } + + if let Some(path) = &row.path { + let folder = ui.button(tr("Show in folder")); + let folder_name = format!("{} {}", tr("Show in folder"), row.name); + folder.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &folder_name)); + if folder.clicked() { + request = Some(RowRequest::ShowFolder(path.clone())); + } + } + + ui.vertical(|ui| { + ui.add(egui::Label::new(format!("{} {}", tr("Name :"), row.name)).truncate()); + let file = row.path.as_deref().unwrap_or(tr("No source file")); + ui.add(egui::Label::new(format!("{} {}", tr("File :"), file)).truncate()).on_hover_text(file); + let status = ui.label(tr(row.status.label())); + if let Some(error) = &row.error { + status.on_hover_text(error); + } + }); + }); + }); + }); + + request +} + +#[cfg(test)] +mod tests { + use std::sync::PoisonError; + + use egui_kittest::Harness; + use texturecraft_engine::Session; + + use super::*; + + fn write_png(path: &std::path::Path, size: u32) { + image::RgbaImage::from_pixel(size, size, image::Rgba([10, 200, 30, 255])).save(path).unwrap(); + } + + fn notices(app: &TextureCraftApp) -> usize { + app.toasts.iter().filter(|toast| toast.action == Some(ToastAction::UpdateResources)).count() + } + + #[test] + fn a_changed_file_is_announced_once_and_the_notice_updates_it() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(PoisonError::into_inner); + let path = std::env::temp_dir().join(format!("texturecraft-resources-notice-{}.png", std::process::id())); + write_png(&path, 4); + let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + let mut harness = Harness::builder().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let app = harness.state_mut(); + let name = app.run("resource.import", json!({ "path": path.to_str().unwrap() })).unwrap()["name"].as_str().unwrap().to_string(); + + check_on_focus(app); + assert_eq!(notices(app), 0, "nothing changed yet"); + + write_png(&path, 8); + check_on_focus(app); + check_on_focus(app); + assert_eq!(notices(app), 1, "the same change is announced once"); + + ToastAction::UpdateResources.run(app); + std::fs::remove_file(&path).ok(); + + assert_eq!(app.session.images[&name].width, 8, "the notice's button updated the resource"); + assert_eq!(app.session.history_labels().last().map(String::as_str), Some("Update resources")); + } +} diff --git a/crates/ui-egui/src/resources_updater/row_request.rs b/crates/ui-egui/src/resources_updater/row_request.rs new file mode 100644 index 00000000..75f0626c --- /dev/null +++ b/crates/ui-egui/src/resources_updater/row_request.rs @@ -0,0 +1,9 @@ +/// What a Resources Updater row's buttons asked for, run after the window is drawn +pub(super) enum RowRequest { + /// Update: read the resource's file again + Update(String), + /// Select new resource: ask for another file for the resource + SelectNew(String), + /// Show in folder: the folder holding this file + ShowFolder(String), +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0c767e1b..9f49b2e7 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -14,11 +14,13 @@ mod import_row; mod library_location; mod project_config; mod resource_usage; +mod resources_updater; pub use import_resources::ImportResources; pub use import_row::ImportRow; pub use library_location::LibraryLocation; pub use project_config::ProjectConfig; pub use resource_usage::ResourceUsage; +pub use resources_updater::ResourcesUpdater; mod console_line; mod export_job; @@ -115,6 +117,9 @@ pub struct Windows { /// File > Import resources: the files added so far, imported by Import. #[serde(skip)] pub import_resources: Option, + /// The Resources Updater: the project's image resources and whether their files changed on disk. + #[serde(skip)] + pub resources_updater: Option, /// What waits on the unsaved-changes dialog: save, don't save or cancel. #[serde(skip)] pub unsaved: Option, diff --git a/crates/ui-egui/src/state/resources_updater.rs b/crates/ui-egui/src/state/resources_updater.rs new file mode 100644 index 00000000..46fb9d12 --- /dev/null +++ b/crates/ui-egui/src/state/resources_updater.rs @@ -0,0 +1,19 @@ +use texturecraft_engine::{ResourceState, ResourceStatus}; + +/// The Resources Updater window: the project's image resources as last checked, and the filters +#[derive(Clone, Debug, PartialEq, Default)] +pub struct ResourcesUpdater { + /// The resources and how they compare with their files, outdated first (checked on opening, + /// Refresh, every change and when the app gets the focus back) + pub rows: Vec, + /// The status the list is narrowed to (None: all) + pub status_filter: Option, + /// Shows only resources whose name contains this, ignoring case + pub name_filter: String, + /// Top or Bottom asked the list to scroll to that end in the next frame + pub jump: Option, + /// The project that was open when this window opened + pub project: u64, + /// The session revision the rows were checked at + pub(crate) checked_revision: u64, +} diff --git a/crates/ui-egui/src/toast_action.rs b/crates/ui-egui/src/toast_action.rs new file mode 100644 index 00000000..d360fd7b --- /dev/null +++ b/crates/ui-egui/src/toast_action.rs @@ -0,0 +1,34 @@ +//! A button on a toast that acts on what the toast says + +use crate::TextureCraftApp; + +/// What a toast's button does +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ToastAction { + /// "Update": read every outdated resource file again (the "changed on disk" notice) + #[cfg(not(target_arch = "wasm32"))] + UpdateResources, +} + +impl ToastAction { + /// The button's text (English; translated where it is drawn) + pub fn label(self) -> &'static str { + match self { + #[cfg(not(target_arch = "wasm32"))] + ToastAction::UpdateResources => "Update", + } + } + + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn run(self, app: &mut TextureCraftApp) { + match self { + ToastAction::UpdateResources => crate::resources_updater::update(app, None), + } + } + + /// The browser's toasts carry no action yet + #[cfg(target_arch = "wasm32")] + pub(crate) fn run(self, _: &mut TextureCraftApp) { + match self {} + } +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 27274a1d..d36f3197 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -499,15 +499,33 @@ pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) { ui.add_space(SHELF_GROUP_GAP); } - for (icon, label) in [(ic::HOURGLASS, "Snooze Autosave"), (ic::ARROWS_CLOCKWISE, "Resources Updater")] { - ui.add_enabled_ui(false, |ui| icon_button(ui, icon, tr(label), false, SHELF_BUTTON_SIZE)) - .inner - .on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE)); - } + ui.add_enabled_ui(false, |ui| icon_button(ui, ic::HOURGLASS, tr("Snooze Autosave"), false, SHELF_BUTTON_SIZE)) + .inner + .on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE)); + resources_updater_button(app, ui); }); }); } +/// The shelf's Resources Updater button: opens or closes its window while a project is open +#[cfg(not(target_arch = "wasm32"))] +fn resources_updater_button(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + let open = app.ui.windows.resources_updater.is_some(); + let label = tr("Resources Updater"); + let button = ui.add_enabled_ui(app.session.project_open, |ui| icon_button(ui, ic::ARROWS_CLOCKWISE, label, open, SHELF_BUTTON_SIZE)).inner; + if button.on_disabled_hover_text(tr("Open a project to check its resources")).clicked() { + crate::resources_updater::toggle(app); + } +} + +/// The browser reads no files from disk, so there is nothing to update +#[cfg(target_arch = "wasm32")] +fn resources_updater_button(_: &mut TextureCraftApp, ui: &mut egui::Ui) { + ui.add_enabled_ui(false, |ui| icon_button(ui, ic::ARROWS_CLOCKWISE, tr("Resources Updater"), false, SHELF_BUTTON_SIZE)) + .inner + .on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE)); +} + /// Width of the icon rail beside the dock const RAIL_WIDTH: f32 = 38.0; diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index f9e8fa5c..5080d2bd 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -23,6 +23,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { { crate::project_config::show(app, ctx); crate::import_resources::show(app, ctx); + crate::resources_updater::show(app, ctx); } crate::keymap::window(app, ctx); crate::export_window::show(app, ctx); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index c8d7f0f3..82c21fcc 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -77,6 +77,7 @@ mod rail; mod reference_order; mod rename_anchor; mod reset_ui; +mod resources_updater; mod settings_window; mod shelf_click; mod shelf_drop; diff --git a/crates/ui-egui/tests/it/resources_updater.rs b/crates/ui-egui/tests/it/resources_updater.rs new file mode 100644 index 00000000..298c1130 --- /dev/null +++ b/crates/ui-egui/tests/it/resources_updater.rs @@ -0,0 +1,137 @@ +//! The Resources Updater window, driven from the keyboard: the shelf button opens it, outdated +//! resources come first, Update reads a changed file again as one undo step and Select new resource +//! follows another file. File pickers are answered by the override, never shown. + +use std::path::{Path, PathBuf}; + +use egui::{Key, Role}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::Session; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::file_dialogs::{Answer, Request}; + +use super::temp_dir::TempDir; + +fn app() -> Harness<'static, TextureCraftApp> { + let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + + h +} + +/// Write a `size` × `size` PNG (each size is a different file size, so a change is seen at once) +fn png(dir: &Path, name: &str, size: u32) -> PathBuf { + let file = dir.join(name); + image::RgbaImage::from_pixel(size, size, image::Rgba([10, 200, 30, 255])).save(&file).unwrap(); + + file +} + +fn import(h: &mut Harness<'_, TextureCraftApp>, file: &Path) { + h.state_mut().run("resource.import", json!({ "path": file.to_str().unwrap() })).unwrap(); + h.run_steps(2); +} + +fn press(h: &mut Harness<'_, TextureCraftApp>, key: Key) { + h.key_press(key); + h.run_steps(3); +} + +/// Move the keyboard focus to button `label` and press Enter +fn activate(h: &mut Harness<'_, TextureCraftApp>, label: &str) { + h.get_by_role_and_label(Role::Button, label).focus(); + h.run_steps(2); + press(h, Key::Enter); +} + +fn shows(h: &Harness<'_, TextureCraftApp>, text: &str) -> bool { + h.query_by_label(text).is_some() +} + +fn width_of(h: &Harness<'_, TextureCraftApp>, name: &str) -> u32 { + h.state().session.images[name].width +} + +#[test] +fn the_window_opens_from_the_keyboard_and_updates_an_outdated_resource_as_one_undo_step() { + let dir = TempDir::new("resources-updater-update"); + let (kept, changed) = (png(&dir, "kept.png", 4), png(&dir, "changed.png", 4)); + let mut h = app(); + import(&mut h, &kept); + import(&mut h, &changed); + png(&dir, "changed.png", 8); + + activate(&mut h, "Resources Updater"); + + let rows = &h.state().ui.windows.resources_updater.as_ref().expect("the window is open").rows; + assert_eq!(rows[0].name, "changed.png", "outdated resources come first"); + assert!(shows(&h, "Project : Test")); + assert!(shows(&h, "(2 resources, 1 outdated)")); + assert!(shows(&h, "Outdated"), "the status is written out, not only coloured"); + assert!(h.get_by_role_and_label(Role::Button, "Update kept.png").accesskit_node().is_disabled(), "only outdated resources update"); + + let steps = h.state().session.history_labels().len(); + activate(&mut h, "Update changed.png"); + + assert_eq!(width_of(&h, "changed.png"), 8, "the new file's pixels are in the project"); + assert_eq!(h.state().session.history_labels().len(), steps + 1, "one undo step"); + assert!(shows(&h, "(2 resources, 0 outdated)")); + + // Undo brings the old pixels back, so the list shows the file as changed again + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(3); + + assert_eq!(width_of(&h, "changed.png"), 4); + assert!(shows(&h, "(2 resources, 1 outdated)")); + + activate(&mut h, "Update All"); + assert_eq!(width_of(&h, "changed.png"), 8); + + press(&mut h, Key::Escape); + assert!(h.state().ui.windows.resources_updater.is_none(), "Escape closes the window"); +} + +#[test] +fn select_new_resource_follows_the_chosen_file_and_the_name_filter_narrows_the_list() { + let dir = TempDir::new("resources-updater-relink"); + let (first, second) = (png(&dir, "first.png", 4), png(&dir, "second.png", 4)); + let other = png(&dir, "other.png", 16); + let mut h = app(); + import(&mut h, &first); + import(&mut h, &second); + activate(&mut h, "Resources Updater"); + + h.state_mut().file_dialogs.set_override(Some(Box::new(move |_: &Request| Answer::Paths(vec![other.clone()])))); + activate(&mut h, "Select new resource first.png"); + h.run_steps(3); + + assert_eq!(width_of(&h, "first.png"), 16, "the resource keeps its name and takes the chosen file's pixels"); + assert!(h.state().session.doc.project.resource_sources["first.png"].path.ends_with("other.png")); + + h.get_by_role_and_label(Role::TextInput, "Name filter:").focus(); + h.run_steps(2); + h.get_by_role_and_label(Role::TextInput, "Name filter:").type_text("SEC"); + h.run_steps(3); + + assert!(h.query_by_label("Update first.png").is_none(), "the filter hides other names"); + assert!(h.query_by_label("Update second.png").is_some(), "names match ignoring case"); +} + +#[test] +fn show_in_folder_shows_the_folder_of_the_resource_file() { + let dir = TempDir::new("resources-updater-folder"); + let file = png(&dir, "bricks.png", 4); + let mut h = app(); + import(&mut h, &file); + activate(&mut h, "Resources Updater"); + + activate(&mut h, "Show in folder bricks.png"); + + let shown = h.state().file_dialogs.shown_folders().to_vec(); + assert_eq!(shown.len(), 1); + assert_eq!(shown[0].file_name(), dir.file_name(), "the file's own folder"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 7873145d..0cf55589 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -222,7 +222,7 @@ keeps its state in a throwaway file. | `session.inspect` | | project, mesh, texture sets, layer stack, tool, camera, display, history | | `ui.inspect` | | UI state, viewport rect, fps, bake progress (`baking`, 0..1), the running bake's stage (`bakeStatus`, e.g. "Baking Ambient Occlusion (2/4)") and live preview (`bakePreview`, see *Live bake preview*), toasts, `titleBar` (who draws the title bar this run: `app`, `integrated` on macOS, or `system`) | | `ui.menu.list` | | the menu catalog: `{menu, submenu, label, id, shortcut, implemented, enabled, checked}` | -| `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question; `file.exportMesh` opens the Mesh Export Options prompt, whose Export asks for the file; `ui.view.export` opens the right bar's Export panel). `{"id": "ui.layout.apply", "name": ""}` switches to a legacy named panel layout (still accessible through assigned shortcuts) (panels only; mode, zoom and wireframes stay) and errors when no layout has that name. `ui.layout.save` still saves the active mode; `ui.layout.save.painting`, `ui.layout.save.rendering` and `ui.layout.save.baking` ask where to save only that mode's panels and view arrangement as a JSON file (without preferences or recent projects); loading preserves the other modes, `ui.layout.load` asks for one to load ("Load UI Layout"); `ui.toolbar.docks` and `ui.toolbar.tools` show or hide the right bar and the painting tools; the disabled Snooze Autosave and Resources Updater buttons stay visible when Tools is off; `ui.view.renderer` toggles the Renderer Settings panel (Rendering Mode only). `{"id": "ui.layout.swap"}` swaps the 3D and 2D views of the split layout (F4) | +| `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question; `file.exportMesh` opens the Mesh Export Options prompt, whose Export asks for the file; `ui.view.export` opens the right bar's Export panel). `{"id": "ui.layout.apply", "name": ""}` switches to a legacy named panel layout (still accessible through assigned shortcuts) (panels only; mode, zoom and wireframes stay) and errors when no layout has that name. `ui.layout.save` still saves the active mode; `ui.layout.save.painting`, `ui.layout.save.rendering` and `ui.layout.save.baking` ask where to save only that mode's panels and view arrangement as a JSON file (without preferences or recent projects); loading preserves the other modes, `ui.layout.load` asks for one to load ("Load UI Layout"); `ui.toolbar.docks` and `ui.toolbar.tools` show or hide the right bar and the painting tools; the disabled Snooze Autosave button and the Resources Updater button (enabled while a project is open) stay visible when Tools is off; `ui.view.renderer` toggles the Renderer Settings panel (Rendering Mode only). `{"id": "ui.layout.swap"}` swaps the 3D and 2D views of the split layout (F4) | | `ui.menu.invoke` id `project.sample` | `{id}` | File > Open Sample Project opens a file picker for a `.tcraft` project. The direct `project.sample` engine command still creates the generated sample for automation. | | `ui.menu.invoke` id `ui.saveAsTemplate` | `{id}` | File > More Save Options > Save As Template opens a save dialog in the user templates folder. The choice supplies the file path and template name to `project.template.save`. `ui.saveReduced` (Save and Reduce File Size) is listed as not implemented and not enabled | | `ui.menu.invoke` ids `ui.help.releaseNotes`, `ui.help.showLog`, `ui.help.exportLog` | `{id}` | Help > Release Notes opens the releases page in the browser; Help > Show Log opens the current desktop run's rolling `log.txt` in the system text-file handler; Help > Export Log exports the session log with each entry’s recorded UTC time, severity and source (a save dialog on desktop with a `Log_TextureCraft____.txt` name, a download on the web) | @@ -348,7 +348,8 @@ with `ui.inspect`, update that field and send the full `prefs` object to `ui.set File › Save. Through `command_run`, every `file.*` command but `file.close` and `file.removeUnused` (and -`file.reimportMesh` without a `path`) is refused, and so is any command given a `path` or `dir`, at the top level or in +`file.reimportMesh` without a `path`) is refused, and so are `resource.status`, `resource.update` and `resource.relink` (they read +the files a project names) and any command given a `path` or `dir`, at the top level or in a `files` entry (`resource.import`, `material.save`, `material.load`, `textureSet.meshMap.import`, …), in both modes: use the workspace tools below. `resource.text` takes a font family, not a path: it reads only the system's font folders. @@ -465,6 +466,23 @@ printf '%s\n' '{"id":1,"method":"command.run","params":{"id":"project.new","para '{"id":2,"method":"render","params":{"width":512,"height":512}}' | texturecraft-cli serve ``` +## Resources Updater + +An image resource imported with `resource.import {path}` remembers that file (its absolute path and +modification time, saved with the project). The shelf's Resources Updater window lists the project's +image resources through these commands and checks them again when it opens, on Refresh, after every +change and when the app gets the focus back; then a notice ("N resources changed on disk", with an +Update button) appears when the set of outdated resources changed since the last notice. + +| Command | Params and result | +|---|---| +| `resource.status` | `{}` → `{resources: [{name, status, path?, error?}], total, outdated}`; `status` is `outdated` (the file's size or contents differ from the resource), `missing` (the file is gone or unreadable, `error` says why), `upToDate` or `noSource` (made in the app or imported without a path); outdated first, then by name. A file is read only when its size matches but its modification time does not | +| `resource.update` | `{names?: [name]}` (default: every outdated resource) → `{updated, failed: [{name, error}]}`: reads the files again and replaces the resources' bytes and pixels under the same names, so every layer, mask and view using them recomposites; one undo step, none when nothing changed. A file that cannot be read fails alone; when none could be read the command is an error. Unknown names and resources without a file are refused | +| `resource.relink` | `{name, path}` → `{name, path}`: the resource takes the image file's pixels (within the image import limits) and follows that file from then on; one undo step | + +These commands read host paths stored in the project, so MCP and `serve` refuse them through +`command_run`; the desktop app's control channel and the trusted local CLI run them. + ## PBR texture folders `file.importPbrFolder` turns a folder, a `.zip` or a list of image files of PBR maps into one fill layer diff --git a/docs/features.md b/docs/features.md index 04702ee9..a3692d83 100644 --- a/docs/features.md +++ b/docs/features.md @@ -98,6 +98,13 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA and alpha images become the brush alpha. Filter by role or remove selected rows before importing. Failed rows stay in the dialog for retry. Color LUT, post effects and asset-library import are unavailable. The browser imports images straight from its file picker. +- **Resources Updater:** the shelf button under the tools lists the project's image resources with + their files, outdated ones first. An imported image remembers its file; when that file changes on + disk, *Update* (or *Update All*) reads it again and every layer using it recomposites, as one undo + step. *Select new resource* points a resource at another file, *Show in folder* opens its folder, + and the list filters by status and name. When the app gets the focus back after files changed, a + notice offers *Update*. Desktop only; there is no Shaders tab, since TextureCraft has no shader + resources. - **Your own library:** right-click a layer or folder, choose *Create smart material*, and it appears under *My smart materials*, pixels and images included. *Create smart mask* in the same menu saves just the layer's mask (all its effects, painted pixels and images); it appears under From cf54cc20de92861e246975e760d1595fd7c07dd7 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 11:16:41 +0100 Subject: [PATCH 2/7] Resources Updater: review fixes Remember file verdicts per size and time so an unchanged file is read once; recheck the open window at most twice a second; outdated rows first. Record image files from PBR folder, MaterialX and mesh map imports too, and resample an imported mesh map from its changed file while it still holds that file's pixels. Relink only image resources; decode updated bytes the way undo and reopening do. Notices carry their project and are reset when another project opens, which is checked once. Escape closes the window only while it has the keyboard. Keep the reference's Shelf line and show the file on its own line. A dedicated automation refusal message, translated status labels, tempfile in tests. --- Cargo.lock | 1 + crates/automation/src/workspace.rs | 13 +- crates/core/src/lib.rs | 2 + crates/core/src/mesh_map_slot.rs | 15 ++ crates/core/src/resource_source.rs | 4 + crates/engine/src/lib.rs | 5 +- crates/engine/src/materialx_cmds.rs | 21 +- crates/engine/src/meshmap_cmds.rs | 17 +- crates/engine/src/meshmap_import_cmds.rs | 5 +- crates/engine/src/pbr_cmds.rs | 39 ++- crates/engine/src/pbr_cmds/native/found.rs | 10 + crates/engine/src/reloaded_file.rs | 9 +- crates/engine/src/resource_check.rs | 23 ++ crates/engine/src/resource_cmds.rs | 4 +- crates/engine/src/resource_state.rs | 1 + crates/engine/src/resource_update_cmds.rs | 203 ++++++++++----- crates/engine/src/session.rs | 5 + crates/engine/tests/it/resource_updater.rs | 232 +++++++++++++----- crates/ui-egui/Cargo.toml | 2 + crates/ui-egui/src/i18n.rs | 3 + crates/ui-egui/src/lib.rs | 21 +- crates/ui-egui/src/menus.rs | 3 - crates/ui-egui/src/resources_updater.rs | 103 +++++--- crates/ui-egui/src/state/resources_updater.rs | 4 + crates/ui-egui/src/toast_action.rs | 33 ++- crates/ui-egui/tests/it/resources_updater.rs | 57 ++++- docs/control-protocol.md | 17 +- docs/features.md | 16 +- 28 files changed, 637 insertions(+), 231 deletions(-) create mode 100644 crates/core/src/mesh_map_slot.rs create mode 100644 crates/engine/src/resource_check.rs diff --git a/Cargo.lock b/Cargo.lock index 59d9a90a..45aedc2d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5313,6 +5313,7 @@ dependencies = [ "skera", "skrifa 0.48.0", "sys-locale", + "tempfile", "texturecraft-engine", "texturecraft-render", "wasm-bindgen", diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 2e590e15..64897380 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -132,15 +132,19 @@ const HOST_PATH_KEYS: [&str; 2] = ["path", "dir"]; /// Refuses engine commands that would reach host paths around the workspace roots, so clients use the workspace tools pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError> { + // The Resources Updater reads the files a project names, which may lie outside the read root + if matches!(id, "resource.status" | "resource.update" | "resource.relink") { + return Err(bad(format!( + "`{id}` reads the image files the project names on this machine, so it is disabled for automation; re-import changed files with resource_import" + ))); + } + let has_path = names_host_path(params) || params.get("files").and_then(Value::as_array).is_some_and(|files| files.iter().any(names_host_path)); // `file.save` is refused even without a path: a headless session's path is workspace-relative, not a host path let allowed = match id { "file.close" | "file.removeUnused" => true, "file.reimportMesh" => !has_path, - - // The Resources Updater reads the files a project names, which may lie outside the read root - "resource.status" | "resource.update" | "resource.relink" => false, _ => !id.starts_with("file.") && !has_path, }; if allowed { @@ -249,7 +253,8 @@ mod tests { assert!(authorize_command("file.reimportMesh", &json!({})).is_ok()); assert!(authorize_command("file.close", &json!({})).is_ok()); for id in ["resource.status", "resource.update", "resource.relink"] { - assert!(authorize_command(id, &json!({})).is_err(), "{id} reads the host paths a project names"); + let error = authorize_command(id, &json!({})).unwrap_err().to_string(); + assert!(error.contains("reads the image files"), "{id}: {error}"); } assert!(authorize_command("layer.add.fill", &json!({"color": "#ff0000", "path": null})).is_ok()); } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 2c5db23b..e6f7a5ce 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -39,6 +39,7 @@ pub mod image_input; pub mod layer; pub mod lighting_output; pub mod mask_outline; +pub mod mesh_map_slot; pub mod mirror; pub mod mirror_corner; pub mod mirror_mode; @@ -120,6 +121,7 @@ pub use layer::{ }; pub use lighting_output::LightingOutput; pub use mask_outline::MaskOutline; +pub use mesh_map_slot::MeshMapSlot; pub use mirror::Mirror; pub use mirror_corner::MirrorCorner; pub use mirror_mode::MirrorMode; diff --git a/crates/core/src/mesh_map_slot.rs b/crates/core/src/mesh_map_slot.rs new file mode 100644 index 00000000..7cade977 --- /dev/null +++ b/crates/core/src/mesh_map_slot.rs @@ -0,0 +1,15 @@ +//! The mesh map an imported image file was resampled into + +use serde::{Deserialize, Serialize}; + +use crate::BakedMap; + +/// A mesh map of a texture set, and the UV tile one image of it covers. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct MeshMapSlot { + /// Index of the texture set. + pub texture_set: usize, + pub map: BakedMap, + /// The UV tile the image covers (1001 on a set without UV tiles). + pub tile: u32, +} diff --git a/crates/core/src/resource_source.rs b/crates/core/src/resource_source.rs index 793122cf..6a8627ed 100644 --- a/crates/core/src/resource_source.rs +++ b/crates/core/src/resource_source.rs @@ -14,4 +14,8 @@ pub struct ResourceSource { /// (0 when unknown). An unchanged time and size skip reading the file again. #[serde(default)] pub modified_ms: u64, + /// The mesh map the file was imported as (`textureSet.meshMap.import`): an update resamples it + /// again while the map still holds what this file gave it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mesh_map: Option, } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 0d2f8d3c..0a87537a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -71,6 +71,9 @@ pub mod quick_mask; // Reloading resource files reads paths on native targets only #[cfg(not(target_arch = "wasm32"))] mod reloaded_file; +// Remembered file comparisons exist on native targets only +#[cfg(not(target_arch = "wasm32"))] +mod resource_check; pub mod resource_cmds; pub mod resource_state; pub mod resource_status; @@ -103,9 +106,9 @@ pub use fill_hit_test::FillHitTest; pub use fill_mode::FillMode; pub use log::{LogEntry, LogLevel, SessionLog}; pub use path_tool::PathState; +pub use project_cmds::sample_session; pub use resource_state::ResourceState; pub use resource_status::ResourceStatus; -pub use project_cmds::sample_session; pub use session::{ CloneFrom, CloneSource, Document, HISTORY_TEMPLATES, NORMAL_HEIGHT_MESH_LABEL, Session, SetCache, StackTarget, StencilLook, StencilState, Tool, ToolState, ViewMode, history_label, stroke_template, diff --git a/crates/engine/src/materialx_cmds.rs b/crates/engine/src/materialx_cmds.rs index 68792d5c..5529b778 100644 --- a/crates/engine/src/materialx_cmds.rs +++ b/crates/engine/src/materialx_cmds.rs @@ -31,8 +31,9 @@ pub fn specs() -> Vec { )] } -/// Loads an image file named in the document (relative to it): its bytes, or why not. -pub type Loader<'a> = &'a dyn Fn(&str) -> std::result::Result, String>; +/// Loads an image file named in the document (relative to it): its bytes and the file they were +/// read from (for the Resources Updater; None when not read from disk), or why not. +pub type Loader<'a> = &'a dyn Fn(&str) -> std::result::Result<(Vec, Option), String>; impl Session { /// Add `material` as a fill layer on the active texture set, loading its images with `load`. @@ -45,6 +46,7 @@ impl Session { // Resources to add (name and encoded bytes), and their decoded images for the session. let mut added: Vec<(String, Arc>)> = Vec::new(); let mut decoded = Vec::new(); + let mut sources = Vec::new(); let mut names: BTreeMap = BTreeMap::new(); let mut channels: Vec = Vec::new(); for (channel, value) in &material.channels { @@ -58,9 +60,10 @@ impl Session { let resource = match names.get(file) { Some(n) => n.clone(), None => { - let loaded = - load(file).and_then(|bytes| texturecraft_formats::decode_image(&bytes).map(|image| (bytes, image)).map_err(|e| e.to_string())); - let (bytes, image) = match loaded { + let loaded = load(file).and_then(|(bytes, source)| { + texturecraft_formats::decode_image(&bytes).map(|image| (bytes, image, source)).map_err(|e| e.to_string()) + }); + let (bytes, image, source) = match loaded { Ok(v) => v, Err(e) => { warnings.push(format!("{} was skipped: {file}: {e}", channel.id())); @@ -74,6 +77,7 @@ impl Session { unique = format!("{n}_{base}"); n += 1; } + sources.extend(source.map(|source| (unique.clone(), source))); added.push((unique.clone(), Arc::new(bytes))); decoded.push((unique.clone(), crate::resource_cmds::decoded(image))); names.insert(file.clone(), unique.clone()); @@ -96,6 +100,7 @@ impl Session { for (n, bytes) in &added { s.doc.resources.insert(n.clone(), bytes.clone()); } + s.doc.project.resource_sources.extend(sources); let id = s.doc.project.alloc_id(); crate::layer_cmds::insert_selected(s, Layer::new(id, layer_name, LayerKind::Fill(fill), &channels)) })?; @@ -123,7 +128,7 @@ fn import(s: &mut Session, p: &Value) -> Result { let material = texturecraft_formats::materialx_read::read_materialx(&bytes, strp(p, "material")).map_err(|e| bad(cmd, format!("{path}: {e}")))?; let folder = Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); let dir = folder.canonicalize().map_err(|e| bad(cmd, format!("cannot read the folder of {path}: {e}")))?; - let load = |file: &str| -> std::result::Result, String> { + let load = |file: &str| -> std::result::Result<(Vec, Option), String> { // `` stands for a tile number; the first tile is read. let file = file.replace("", "1001"); let rel = Path::new(&file); @@ -144,7 +149,9 @@ fn import(s: &mut Session, p: &Value) -> Result { if len > crate::resource_cmds::MAX_BYTES as u64 { return Err(format!("the file is over {} MB", crate::resource_cmds::MAX_BYTES >> 20)); } - std::fs::read(&full).map_err(|e| e.to_string()) + let source = full.to_str().map(crate::resource_update_cmds::file_source); + let bytes = std::fs::read(&full).map_err(|e| e.to_string())?; + Ok((bytes, source)) }; s.import_material(material, strp(p, "name"), &load) } diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index f08d34c4..4b2a209b 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -54,6 +54,17 @@ pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start(); /// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result { + let (width, data) = resampled(s, cmd, ts, map, images)?; + + let entry = s.doc.baked.entry(ts).or_default(); + entry.resolution = width; + entry.maps.insert(map, Arc::new(data)); + s.doc.project.texture_set_mut(ts)?.baked.insert(map); + Ok(width) +} + +/// The pixels [`use_images`] would give mesh map `map` of set `ts`, and their width +pub(crate) fn resampled(s: &Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result<(u32, Vec)> { let texture_set = s.doc.project.texture_set(ts)?; let grid = texture_set.tile_grid(); if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) { @@ -74,11 +85,7 @@ pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, i }), }; - let entry = s.doc.baked.entry(ts).or_default(); - entry.resolution = width; - entry.maps.insert(map, Arc::new(data)); - s.doc.project.texture_set_mut(ts)?.baked.insert(map); - Ok(width) + Ok((width, data)) } /// Dimensions shared by imported mesh maps, checked before allocating the resampled pixels diff --git a/crates/engine/src/meshmap_import_cmds.rs b/crates/engine/src/meshmap_import_cmds.rs index 20913de2..2c9f9b56 100644 --- a/crates/engine/src/meshmap_import_cmds.rs +++ b/crates/engine/src/meshmap_import_cmds.rs @@ -4,12 +4,13 @@ use std::collections::BTreeMap; use std::path::Path; use serde_json::{Value, json}; -use texturecraft_core::BakedMap; +use texturecraft_core::{BakedMap, MeshMapSlot, ResourceSource}; use crate::commands::{CommandSpec, always, bad, strp}; use crate::meshmap_cmds::{FIRST_TILE, image_map_size, tile_number, use_images}; use crate::meshmap_file_name::{baked_map_from_file_name, texture_set_from_file_name}; use crate::resource_cmds::read_image_file; +use crate::resource_update_cmds::file_source; use crate::{Result, Session, cmd}; const CMD: &str = "textureSet.meshMap.import"; @@ -84,11 +85,13 @@ fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result() as u64; let name = s.add_image_resource(path, bytes, remaining_bytes / bytes_per_texel)?; + s.doc.project.resource_sources.insert(name.clone(), source); let image = s.images.get(&name).ok_or_else(|| bad(CMD, format!("no decoded image `{name}`")))?; reserve_bytes(&mut remaining_bytes, u64::from(image.width) * u64::from(image.height) * bytes_per_texel)?; images.insert(*tile, image.clone()); diff --git a/crates/engine/src/pbr_cmds.rs b/crates/engine/src/pbr_cmds.rs index d5b3d4aa..09a0a9e9 100644 --- a/crates/engine/src/pbr_cmds.rs +++ b/crates/engine/src/pbr_cmds.rs @@ -80,6 +80,9 @@ pub fn specs() -> Vec { pub type FileList = Vec<(String, u64)>; /// Reads a file of the list by name. pub type Loader<'a> = &'a dyn Fn(&str) -> std::result::Result, String>; +/// The file on disk a file of the list is read from (None: an archive entry or bytes in memory), +/// asked right before reading it. +type Locator<'a> = &'a dyn Fn(&str) -> Option; mod pbr_options; mod take; @@ -137,10 +140,16 @@ impl Session { /// Import the maps found among `files` as one fill layer on the active texture set; `load` /// reads a file by name. Returns the reply of `file.importPbrFolder`. pub fn import_pbr(&mut self, files: &FileList, load: Loader, options: &PbrOptions) -> Result { - self.import_pbr_with_budget(files, load, options, import_memory_budget()) + self.import_pbr_with_budget(files, load, &|_| None, options, import_memory_budget()) } - fn import_pbr_with_budget(&mut self, files: &FileList, load: Loader, options: &PbrOptions, memory_budget: u64) -> Result { + /// [`Session::import_pbr`] that records the disk files `locate` names, so the Resources Updater can read them again + #[cfg(not(target_arch = "wasm32"))] + fn import_pbr_located(&mut self, files: &FileList, load: Loader, locate: Locator, options: &PbrOptions) -> Result { + self.import_pbr_with_budget(files, load, locate, options, import_memory_budget()) + } + + fn import_pbr_with_budget(&mut self, files: &FileList, load: Loader, locate: Locator, options: &PbrOptions, memory_budget: u64) -> Result { let set = detect_with(files, &options.choose)?; if set.is_empty() { return Err(EngineError::Other(format!( @@ -193,6 +202,10 @@ impl Session { let mut fill = Fill { projection: options.projection.clone(), ..Fill::default() }; let mut added: Vec<(String, Arc>)> = Vec::new(); let mut decoded = Vec::new(); + + // Disk files read by name, and the resources that hold one of them unchanged + let mut file_sources: BTreeMap = BTreeMap::new(); + let mut resource_sources: Vec<(String, texturecraft_core::ResourceSource)> = Vec::new(); let mut channels: Vec = Vec::new(); let mut total_texels = 0u64; let mut retained_bytes = 0u64; @@ -231,6 +244,9 @@ impl Session { let loaded = if allowed_texels == 0 { Err("not enough memory is available to import more textures".to_string()) } else { + if let Some(source) = locate(&file) { + file_sources.insert(file.clone(), source); + } load(&file).and_then(|bytes| { if bytes.len() as u64 > MAX_FILE_BYTES { return Err(format!("the file is over {} MB", MAX_FILE_BYTES >> 20)); @@ -294,6 +310,13 @@ impl Session { suffix_index += 1; } + // Only a resource holding the file's own bytes can be compared with it later + if take == Take::Whole + && let Some(source) = file_sources.get(&file) + { + resource_sources.push((unique.clone(), source.clone())); + } + added.push((unique.clone(), resource_bytes)); decoded.push((unique.clone(), crate::resource_cmds::decoded(resource_image))); made.insert((file.clone(), take), unique.clone()); @@ -316,6 +339,7 @@ impl Session { for (n, bytes) in &added { s.doc.resources.insert(n.clone(), bytes.clone()); } + s.doc.project.resource_sources.extend(resource_sources); let id = s.doc.project.alloc_id(); crate::layer_cmds::insert_selected(s, Layer::new(id, layer_name.clone(), LayerKind::Fill(fill), &channels)) })?; @@ -420,7 +444,12 @@ fn import(s: &mut Session, p: &Value) -> Result { if options.name.is_none() { options.name = found.name.clone(); } - s.import_pbr(&found.files, &|name| found.load(name), &options) + s.import_pbr_located( + &found.files, + &|name| found.load(name), + &|name| found.disk_path(name).map(|path| crate::resource_update_cmds::file_source(&path)), + &options, + ) } #[cfg(not(target_arch = "wasm32"))] @@ -462,7 +491,7 @@ mod tests { let mut session = Session::new_project("test", crate::geom::primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); let load = |_: &str| Ok(bytes.clone()); - let result = session.import_pbr_with_budget(&files, &load, &PbrOptions::default(), 64); + let result = session.import_pbr_with_budget(&files, &load, &|_| None, &PbrOptions::default(), 64); assert!(result.unwrap_err().to_string().contains("more than 1 texels")); assert!(session.doc.resources.is_empty()); @@ -471,7 +500,7 @@ mod tests { assert_eq!(allowed_source_texels(256, 64, 3), 2); let never_load = |_: &str| -> std::result::Result, String> { panic!("no source should load after the budget is spent") }; - let result = session.import_pbr_with_budget(&files, &never_load, &PbrOptions::default(), 0); + let result = session.import_pbr_with_budget(&files, &never_load, &|_| None, &PbrOptions::default(), 0); assert!(result.unwrap_err().to_string().contains("not enough memory")); } diff --git a/crates/engine/src/pbr_cmds/native/found.rs b/crates/engine/src/pbr_cmds/native/found.rs index 454203a6..4f056d92 100644 --- a/crates/engine/src/pbr_cmds/native/found.rs +++ b/crates/engine/src/pbr_cmds/native/found.rs @@ -13,6 +13,16 @@ pub(in crate::pbr_cmds) struct Found { impl Found { /// Reads one file of the list. Archive entries are read through a limit, since their /// declared size can lie. + /// The file on disk `name` is read from (None for an archive entry or a name not in the list) + pub(in crate::pbr_cmds) fn disk_path(&self, name: &str) -> Option { + let path = match &self.source { + Origin::Folder { root } => root.join(name), + Origin::Files(paths) => paths.iter().find(|p| p.file_name().is_some_and(|n| n.to_string_lossy() == name))?.clone(), + Origin::Zip(_) => return None, + }; + path.to_str().map(str::to_string) + } + pub(in crate::pbr_cmds) fn load(&self, name: &str) -> std::result::Result, String> { match &self.source { Origin::Folder { root } => read_regular(&root.join(name), MAX_FILE_BYTES), diff --git a/crates/engine/src/reloaded_file.rs b/crates/engine/src/reloaded_file.rs index b65582d2..048161c1 100644 --- a/crates/engine/src/reloaded_file.rs +++ b/crates/engine/src/reloaded_file.rs @@ -16,13 +16,10 @@ pub(crate) struct ReloadedFile { impl ReloadedFile { /// Read and decode `path` for resource `name` within the resource limits (`cmd` names errors) pub(crate) fn read(cmd: &str, name: String, path: &str) -> Result { - let file_path = std::path::Path::new(path); - - // Taken before reading, so a write during the read still shows as a change later - let modified_ms = crate::resource_update_cmds::modified_ms_of(file_path); - let bytes = crate::resource_cmds::read_resource_file(cmd, file_path, crate::resource_cmds::MAX_BYTES as u64)?; + let source = crate::resource_update_cmds::file_source(path); + let bytes = crate::resource_cmds::read_resource_file(cmd, std::path::Path::new(path), crate::resource_cmds::MAX_BYTES as u64)?; let image = texturecraft_formats::decode_image(&bytes).map_err(|error| crate::commands::bad(cmd, format!("{path}: {error}")))?; - Ok(ReloadedFile { name, bytes, image, source: ResourceSource { path: crate::resource_update_cmds::absolute_path(path), modified_ms } }) + Ok(ReloadedFile { name, bytes, image, source }) } } diff --git a/crates/engine/src/resource_check.rs b/crates/engine/src/resource_check.rs new file mode 100644 index 00000000..f7505daa --- /dev/null +++ b/crates/engine/src/resource_check.rs @@ -0,0 +1,23 @@ +//! A remembered comparison of a resource with its file, so an unchanged file is not read again + +use std::sync::{Arc, Weak}; + +use crate::resource_status::ResourceStatus; + +/// What reading a resource's file found, kept while the file's size and time stay the same +#[derive(Clone, Debug)] +pub(crate) struct ResourceCheck { + pub path: String, + pub size: u64, + pub modified_ms: u64, + /// The resource bytes the file was compared with (an update or undo replaces them) + pub bytes: Weak>, + pub status: ResourceStatus, +} + +impl ResourceCheck { + /// Whether this verdict still holds for the file and the resource's bytes + pub(crate) fn holds_for(&self, path: &str, size: u64, modified_ms: u64, bytes: &Arc>) -> bool { + self.path == path && self.size == size && self.modified_ms == modified_ms && std::ptr::eq(self.bytes.as_ptr(), Arc::as_ptr(bytes)) + } +} diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index d20cb60e..2c708501 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -184,10 +184,8 @@ fn import(s: &mut Session, p: &Value) -> Result { let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?; let prefix = strp(p, "prefix").unwrap_or(""); - // Taken before reading, so a write during the read still shows as a change in the Resources Updater - let modified_ms = crate::resource_update_cmds::modified_ms_of(std::path::Path::new(path)); + let source = crate::resource_update_cmds::file_source(path); let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?; - let source = texturecraft_core::ResourceSource { path: crate::resource_update_cmds::absolute_path(path), modified_ms }; let name = s.edit("Import resource", |session| { let name = session.add_image_resource_prefixed(prefix, path, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)?; diff --git a/crates/engine/src/resource_state.rs b/crates/engine/src/resource_state.rs index 1a3e427c..2e33cb63 100644 --- a/crates/engine/src/resource_state.rs +++ b/crates/engine/src/resource_state.rs @@ -7,6 +7,7 @@ use crate::resource_status::ResourceStatus; pub struct ResourceState { /// The resource's name in the project. pub name: String, + /// How the resource compares with its file now. pub status: ResourceStatus, /// The file it was imported from or relinked to (None: made in the app or imported without a path). pub path: Option, diff --git a/crates/engine/src/resource_update_cmds.rs b/crates/engine/src/resource_update_cmds.rs index ea69042d..0fc56e7d 100644 --- a/crates/engine/src/resource_update_cmds.rs +++ b/crates/engine/src/resource_update_cmds.rs @@ -1,6 +1,7 @@ //! The Resources Updater: compare image resources with the files they came from, read changed //! files again and point a resource at another file. Each change is one undo step, and every -//! layer, mask and view using a changed resource recomposites. +//! layer, mask and view using a changed resource recomposites; a mesh map imported from a changed +//! file is resampled while it still holds what the file gave it. use serde_json::{Value, json}; use texturecraft_core::ResourceSource; @@ -35,7 +36,7 @@ pub fn specs() -> Vec { "Relink resource", [], None, - "{name, path — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr)} → {name, path} — the resource takes the file's pixels and follows it from now on", + "{name: image resource, path — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr)} → {name, path} — the resource takes the file's pixels and follows it from now on", always, relink ), @@ -44,63 +45,134 @@ pub fn specs() -> Vec { impl Session { /// The image resources with their files and how they compare, outdated first, then by name. - /// Reads a file only when its size matches the stored bytes but its modification time does not. - pub fn resource_states(&self) -> Vec { - let sources = &self.doc.project.resource_sources; - let mut states: Vec = self - .doc - .resources - .iter() - .filter(|(name, _)| self.images.contains_key(*name) || sources.contains_key(*name)) - .map(|(name, bytes)| { - let source = sources.get(name); - let (status, error) = source.map_or((ResourceStatus::NoSource, None), |source| compare_with_file(source, bytes)); - ResourceState { name: name.clone(), status, path: source.map(|source| source.path.clone()), error } - }) - .collect(); - + /// A file is read only when its size matches the stored bytes but its modification time does + /// not, and that verdict is kept until the file's size or time changes again. + pub fn resource_states(&mut self) -> Vec { + let mut states = self.compare_resources(); states.sort_by(|a, b| a.status.cmp(&b.status).then_with(|| a.name.cmp(&b.name))); states } - /// Put reloaded files in place of their resources' bytes and pixels as one undo step + /// Whether `name` is an image resource the Resources Updater lists + fn is_image_resource(&self, name: &str) -> bool { + self.doc.resources.contains_key(name) && (self.images.contains_key(name) || self.doc.project.resource_sources.contains_key(name)) + } + + #[cfg(not(target_arch = "wasm32"))] + fn compare_resources(&mut self) -> Vec { + let mut checks = std::mem::take(&mut self.resource_checks); + let names: Vec = self.doc.resources.keys().filter(|name| self.is_image_resource(name)).cloned().collect(); + let mut states = Vec::with_capacity(names.len()); + for name in names { + let (Some(bytes), source) = (self.doc.resources.get(&name), self.doc.project.resource_sources.get(&name)) else { continue }; + let (status, error) = source.map_or((ResourceStatus::NoSource, None), |source| compare_with_file(&name, source, bytes, &mut checks)); + states.push(ResourceState { path: source.map(|source| source.path.clone()), name, status, error }); + } + + checks.retain(|name, _| self.doc.resources.contains_key(name)); + self.resource_checks = checks; + states + } + + #[cfg(target_arch = "wasm32")] + fn compare_resources(&mut self) -> Vec { + let sources = &self.doc.project.resource_sources; + let browser = "file paths are not available in the browser"; + let names = self.doc.resources.keys().filter(|name| self.is_image_resource(name)); + names + .map(|name| match sources.get(name) { + Some(source) => { + ResourceState { name: name.clone(), status: ResourceStatus::Missing, path: Some(source.path.clone()), error: Some(browser.into()) } + } + None => ResourceState { name: name.clone(), status: ResourceStatus::NoSource, path: None, error: None }, + }) + .collect() + } + + /// Put reloaded files in place of their resources' bytes as one undo step, resample the mesh + /// maps imported from them, then decode the stored bytes as undo, redo and reopening do #[cfg(not(target_arch = "wasm32"))] fn install_reloaded(&mut self, label: &str, files: Vec) -> Result> { + use std::collections::{BTreeMap, BTreeSet}; + if files.is_empty() { return Ok(Vec::new()); } - let decoded = self.edit(label, |session| { - let mut decoded = Vec::with_capacity(files.len()); + let names: Vec = files.iter().map(|file| file.name.clone()).collect(); + self.edit(label, |session| { + let mut fresh = BTreeMap::new(); + let mut slots = BTreeSet::new(); for file in files { + slots.extend(file.source.mesh_map.map(|slot| (slot.texture_set, slot.map))); session.doc.resources.insert(file.name.clone(), std::sync::Arc::new(file.bytes)); session.doc.project.resource_sources.insert(file.name.clone(), file.source); - decoded.push((file.name, file.image)); + fresh.insert(file.name, crate::resource_cmds::decoded(file.image)); } - Ok(decoded) + for (texture_set, map) in slots { + session.refresh_mesh_map(texture_set, map, &fresh)?; + } + + Ok(()) })?; - // The edit marked every set using a replaced resource for recompositing; the new pixels are read then - let mut names = Vec::with_capacity(decoded.len()); - for (name, image) in decoded { - if crate::fill_alpha::matches_saved_picture(&name, &image) { - self.library_alphas.insert(name.clone()); - } else { - self.library_alphas.remove(&name); - } + for name in &names { + self.images.remove(name); + } + self.sync_images(); + Ok(names) + } - self.images.insert(name.clone(), crate::resource_cmds::decoded(image)); - names.push(name); + /// Resample mesh map `map` of set `texture_set` from the new pixels of the files it was + /// imported from, unless a bake or another image has replaced it since (it no longer equals + /// what the old pixels give) + #[cfg(not(target_arch = "wasm32"))] + fn refresh_mesh_map( + &mut self, + texture_set: usize, + map: texturecraft_core::BakedMap, + fresh: &std::collections::BTreeMap>, + ) -> Result<()> { + const CMD: &str = "resource.update"; + + let tiles: Vec<(u32, String)> = self + .doc + .project + .resource_sources + .iter() + .filter_map(|(name, source)| { + source.mesh_map.filter(|slot| slot.texture_set == texture_set && slot.map == map).map(|slot| (slot.tile, name.clone())) + }) + .collect(); + let (mut before, mut after) = (std::collections::BTreeMap::new(), std::collections::BTreeMap::new()); + for (tile, name) in tiles { + let Some(old) = self.images.get(&name) else { return Ok(()) }; + + before.insert(tile, old.clone()); + after.insert(tile, fresh.get(&name).unwrap_or(old).clone()); } - Ok(names) + let current = self.doc.baked.get(&texture_set).and_then(|baked| baked.maps.get(&map)); + let unchanged = crate::meshmap_cmds::resampled(self, CMD, texture_set, map, &before).ok(); + let from_these_files = current.zip(unchanged).is_some_and(|(current, (_, unchanged))| current.as_slice() == unchanged.as_slice()); + if from_these_files { + crate::meshmap_cmds::use_images(self, CMD, texture_set, map, &after)?; + } + + Ok(()) } } -/// How `stored` (a resource's bytes) compares with the file `source` names now +/// How `stored` (a resource's bytes) compares with the file `source` names now, reusing the +/// remembered verdict in `checks` while the file's size and time stay the same #[cfg(not(target_arch = "wasm32"))] -fn compare_with_file(source: &ResourceSource, stored: &[u8]) -> (ResourceStatus, Option) { +fn compare_with_file( + name: &str, + source: &ResourceSource, + stored: &std::sync::Arc>, + checks: &mut std::collections::HashMap, +) -> (ResourceStatus, Option) { let path = std::path::Path::new(&source.path); let metadata = match std::fs::metadata(path) { Ok(metadata) if metadata.is_file() => metadata, @@ -108,7 +180,8 @@ fn compare_with_file(source: &ResourceSource, stored: &[u8]) -> (ResourceStatus, Err(error) => return (ResourceStatus::Missing, Some(format!("{}: {error}", source.path))), }; - if metadata.len() != stored.len() as u64 { + let size = metadata.len(); + if size != stored.len() as u64 { return (ResourceStatus::Outdated, None); } @@ -117,17 +190,21 @@ fn compare_with_file(source: &ResourceSource, stored: &[u8]) -> (ResourceStatus, return (ResourceStatus::UpToDate, None); } - // A newer time alone is not a change: the file may have been saved again unchanged - match crate::resource_cmds::read_resource_file("resource.status", path, crate::resource_cmds::MAX_BYTES as u64) { - Ok(bytes) if bytes == stored => (ResourceStatus::UpToDate, None), - Ok(_) => (ResourceStatus::Outdated, None), - Err(error) => (ResourceStatus::Missing, Some(error.to_string())), + if let Some(check) = checks.get(name) + && check.holds_for(&source.path, size, modified_ms, stored) + { + return (check.status, None); } -} -#[cfg(target_arch = "wasm32")] -fn compare_with_file(_: &ResourceSource, _: &[u8]) -> (ResourceStatus, Option) { - (ResourceStatus::Missing, Some("file paths are not available in the browser".to_string())) + // A newer time alone is not a change: the file may have been saved again unchanged + let status = match crate::resource_cmds::read_resource_file("resource.status", path, crate::resource_cmds::MAX_BYTES as u64) { + Ok(bytes) if bytes == **stored => ResourceStatus::UpToDate, + Ok(_) => ResourceStatus::Outdated, + Err(error) => return (ResourceStatus::Missing, Some(error.to_string())), + }; + let bytes = std::sync::Arc::downgrade(stored); + checks.insert(name.to_string(), crate::resource_check::ResourceCheck { path: source.path.clone(), size, modified_ms, bytes, status }); + (status, None) } /// A file's modification time in milliseconds since the Unix epoch (0 when the system has none) @@ -137,19 +214,22 @@ fn modified_ms(metadata: &std::fs::Metadata) -> u64 { since_epoch.map_or(0, |elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)) } -/// [`modified_ms`] of the file at `path` (0 when it cannot be read) +/// The record for an image about to be read from `path`: its absolute path and its current +/// modification time, taken before reading so a write during the read still shows as a change #[cfg(not(target_arch = "wasm32"))] -pub(crate) fn modified_ms_of(path: &std::path::Path) -> u64 { - std::fs::metadata(path).map_or(0, |metadata| modified_ms(&metadata)) +pub(crate) fn file_source(path: &str) -> ResourceSource { + let absolute = std::path::absolute(path).ok().and_then(|absolute| absolute.to_str().map(str::to_string)).unwrap_or_else(|| path.to_string()); + let modified_ms = std::fs::metadata(path).map_or(0, |metadata| modified_ms(&metadata)); + ResourceSource { path: absolute, modified_ms, mesh_map: None } } -/// `path` made absolute against the working folder, so the record does not depend on where the app started -#[cfg(not(target_arch = "wasm32"))] -pub(crate) fn absolute_path(path: &str) -> String { - std::path::absolute(path).ok().and_then(|absolute| absolute.to_str().map(str::to_string)).unwrap_or_else(|| path.to_string()) +/// The browser reads no paths; the record keeps the name it was given +#[cfg(target_arch = "wasm32")] +pub(crate) fn file_source(path: &str) -> ResourceSource { + ResourceSource { path: path.to_string(), modified_ms: 0, mesh_map: None } } -fn status(s: &Session) -> Value { +fn status(s: &mut Session) -> Value { let states = s.resource_states(); let outdated = states.iter().filter(|state| state.status == ResourceStatus::Outdated).count(); let resources: Vec = states @@ -195,11 +275,14 @@ fn update(s: &mut Session, p: &Value) -> Result { // A file that cannot be read fails alone; the others still update let (mut files, mut failed) = (Vec::new(), Vec::new()); for name in names { - let Some(path) = s.doc.project.resource_sources.get(&name).map(|source| source.path.clone()) else { continue }; - match crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), &path) { + let Some(previous) = s.doc.project.resource_sources.get(&name).cloned() else { continue }; + match crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), &previous.path) { // Unchanged contents need no undo step Ok(file) if s.doc.resources.get(&name).is_some_and(|stored| **stored == file.bytes) => {} - Ok(file) => files.push(file), + Ok(mut file) => { + file.source.mesh_map = previous.mesh_map; + files.push(file); + } Err(error) => failed.push(json!({"name": name, "error": error.to_string()})), } } @@ -219,11 +302,13 @@ fn relink(s: &mut Session, p: &Value) -> Result { let name = crate::commands::strp(p, "name").ok_or_else(|| bad(CMD, "`name` is required"))?.to_string(); let path = crate::commands::strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?; - if !s.doc.resources.contains_key(&name) { - return Err(bad(CMD, format!("no resource `{name}`"))); + if !s.is_image_resource(&name) { + return Err(bad(CMD, format!("no image resource `{name}`"))); } - let file = crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), path)?; + // A relinked mesh map file still feeds its mesh map + let mut file = crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), path)?; + file.source.mesh_map = s.doc.project.resource_sources.get(&name).and_then(|source| source.mesh_map); let path = file.source.path.clone(); s.install_reloaded("Relink resource", vec![file])?; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index beb20ab0..4bce1792 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -462,6 +462,9 @@ pub struct Session { pub images: texturecraft_compose::ImageStore, /// Resource names whose decoded pixels match a library alpha. pub(crate) library_alphas: BTreeSet, + /// Resources whose file was read for the Resources Updater, by name: the verdict stays while the file's size and time do + #[cfg(not(target_arch = "wasm32"))] + pub(crate) resource_checks: std::collections::HashMap, /// Temporary texel mask limiting paint strokes (not saved, not in the history). pub quick_mask: crate::quick_mask::QuickMask, /// A path sublayer is being repainted from its paths (the only way to paint into one). @@ -547,6 +550,8 @@ impl Session { blending_clipboard: None, images: Default::default(), library_alphas: BTreeSet::new(), + #[cfg(not(target_arch = "wasm32"))] + resource_checks: std::collections::HashMap::new(), quick_mask: Default::default(), painting_paths: false, path_cache: None, diff --git a/crates/engine/tests/it/resource_updater.rs b/crates/engine/tests/it/resource_updater.rs index c0d0f1dc..93b26908 100644 --- a/crates/engine/tests/it/resource_updater.rs +++ b/crates/engine/tests/it/resource_updater.rs @@ -1,40 +1,20 @@ //! The Resources Updater: image resources remember their files, a changed file shows as outdated, //! Update reads it again (one undo step, recompositing its layers) and Relink follows another file -use std::path::{Path, PathBuf}; +use std::path::Path; +use std::sync::Arc; +use std::time::{Duration, SystemTime}; use serde_json::{Value, json}; -use texturecraft_engine::core::Channel; +use texturecraft_engine::core::{BakedMap, Channel}; use texturecraft_engine::geom::primitives; use texturecraft_engine::{ResourceStatus, Session, execute}; -const RESOLUTION: u32 = 64; -const SAMPLE_STRIDE: usize = 4; +const RESOLUTION: u32 = 128; +const SAMPLE_STRIDE: usize = 8; const RED: [u8; 4] = [255, 0, 0, 255]; const GREEN: [u8; 4] = [0, 255, 0, 255]; -/// A test folder removed when dropped -struct TempDir(PathBuf); - -impl TempDir { - fn new(test: &str) -> TempDir { - let path = std::env::temp_dir().join(format!("tc-resource-updater-{test}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&path); - std::fs::create_dir_all(&path).unwrap(); - TempDir(path) - } - - fn file(&self, name: &str) -> PathBuf { - self.0.join(name) - } -} - -impl Drop for TempDir { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } -} - fn session() -> Session { Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, RESOLUTION).unwrap() } @@ -48,9 +28,22 @@ fn text(path: &Path) -> &str { path.to_str().unwrap() } +/// Give the file at `path` the modification time `time` without changing its contents +fn set_modified(path: &Path, time: SystemTime) { + std::fs::File::options().write(true).open(path).unwrap().set_modified(time).unwrap(); +} + +fn modified(path: &Path) -> SystemTime { + std::fs::metadata(path).unwrap().modified().unwrap() +} + +fn import(s: &mut Session, path: &Path) -> String { + execute(s, "resource.import", &json!({"path": text(path)})).unwrap()["name"].as_str().unwrap().to_string() +} + /// Import `path` and show it as a base colour fill; returns the resource name fn import_as_fill(s: &mut Session, path: &Path) -> String { - let name = execute(s, "resource.import", &json!({"path": text(path)})).unwrap()["name"].as_str().unwrap().to_string(); + let name = import(s, path); execute(s, "layer.add.image", &json!({"name": name})).unwrap(); s.update(); name @@ -62,19 +55,19 @@ fn base_colors(s: &Session) -> Vec<[f32; 3]> { samples().flat_map(|y| samples().map(move |x| (x, y))).map(|(x, y)| composite.value(Channel::BaseColor, x, y)).collect() } -fn status_of(s: &Session, name: &str) -> ResourceStatus { +fn status_of(s: &mut Session, name: &str) -> ResourceStatus { s.resource_states().into_iter().find(|state| state.name == name).expect("the resource is listed").status } #[test] fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() { - let dir = TempDir::new("update"); - let file = dir.file("bricks.png"); + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("bricks.png"); write_png(&file, 4, RED); let mut s = session(); let name = import_as_fill(&mut s, &file); let before = base_colors(&s); - assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate); + assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate); write_png(&file, 8, GREEN); let status = execute(&mut s, "resource.status", &Value::Null).unwrap(); @@ -90,7 +83,7 @@ fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() assert_eq!(updated["updated"], json!([name])); assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); - assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate); + assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate); assert_eq!(s.images[&name].width, 8, "the new pixels are decoded"); assert_ne!(after, before, "the fill using the resource recomposited"); @@ -99,7 +92,7 @@ fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() assert_eq!(s.images[&name].width, 4, "undo brings back the old pixels under the same name"); assert_eq!(base_colors(&s), before); - assert_eq!(status_of(&s, &name), ResourceStatus::Outdated, "the file on disk is still the new one"); + assert_eq!(status_of(&mut s, &name), ResourceStatus::Outdated, "the file on disk is still the new one"); execute(&mut s, "edit.redo", &Value::Null).unwrap(); s.update(); @@ -109,24 +102,60 @@ fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() } #[test] -fn nothing_outdated_adds_no_undo_step() { - let dir = TempDir::new("unchanged"); - let file = dir.file("same.png"); +fn outdated_resources_come_first_then_missing_up_to_date_and_unlinked() { + let dir = tempfile::tempdir().unwrap(); + let [fine, gone, changed] = ["b_fine.png", "c_gone.png", "d_changed.png"].map(|name| dir.path().join(name)); + for file in [&fine, &gone, &changed] { + write_png(file, 4, RED); + } + let mut s = session(); + let png = std::fs::read(&fine).unwrap(); + s.import_resource_bytes("a_unlinked.png", png).unwrap(); + for file in [&fine, &gone, &changed] { + import(&mut s, file); + } + std::fs::remove_file(&gone).unwrap(); + write_png(&changed, 8, GREEN); + + let order: Vec = s.resource_states().into_iter().map(|state| state.name).collect(); + + assert_eq!(order, ["d_changed.png", "c_gone.png", "b_fine.png", "a_unlinked.png"], "by status first, against the name order"); +} + +#[test] +fn a_same_size_file_is_compared_by_contents_once_per_time() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("same.png"); write_png(&file, 4, RED); let mut s = session(); - import_as_fill(&mut s, &file); + let name = import(&mut s, &file); + let original = std::fs::read(&file).unwrap(); + let later = modified(&file) + Duration::from_secs(10); + + // Saved again unchanged: a new time alone is no change, and updating adds no step + set_modified(&file, later); let steps = s.history_labels().len(); - - let updated = execute(&mut s, "resource.update", &json!({})).unwrap(); - - assert_eq!(updated["updated"], json!([])); + assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate); + assert_eq!(execute(&mut s, "resource.update", &json!({})).unwrap()["updated"], json!([])); assert_eq!(s.history_labels().len(), steps); + + // Different bytes of the same size and time are not read again: the verdict for that size and time stands + let mut edited = original.clone(); + let last = edited.len() - 1; + edited[last] ^= 0xff; + std::fs::write(&file, &edited).unwrap(); + set_modified(&file, later); + assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate, "the remembered verdict is used"); + + // Another time reads the file, and its bytes differ + set_modified(&file, later + Duration::from_secs(10)); + assert_eq!(status_of(&mut s, &name), ResourceStatus::Outdated); } #[test] fn a_missing_file_is_reported_and_updating_it_changes_nothing() { - let dir = TempDir::new("missing"); - let file = dir.file("gone.png"); + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("gone.png"); write_png(&file, 4, RED); let mut s = session(); let name = import_as_fill(&mut s, &file); @@ -145,8 +174,8 @@ fn a_missing_file_is_reported_and_updating_it_changes_nothing() { #[test] fn an_unreadable_file_fails_alone_while_the_others_update() { - let dir = TempDir::new("partial"); - let (kept, gone) = (dir.file("kept.png"), dir.file("gone.png")); + let dir = tempfile::tempdir().unwrap(); + let (kept, gone) = (dir.path().join("kept.png"), dir.path().join("gone.png")); write_png(&kept, 4, RED); write_png(&gone, 4, RED); let mut s = session(); @@ -164,8 +193,8 @@ fn an_unreadable_file_fails_alone_while_the_others_update() { #[test] fn relink_reads_another_file_and_follows_it_from_then_on() { - let dir = TempDir::new("relink"); - let (first, second) = (dir.file("first.png"), dir.file("second.png")); + let dir = tempfile::tempdir().unwrap(); + let (first, second) = (dir.path().join("first.png"), dir.path().join("second.png")); write_png(&first, 4, RED); write_png(&second, 8, GREEN); let mut s = session(); @@ -183,45 +212,132 @@ fn relink_reads_another_file_and_follows_it_from_then_on() { // The old file no longer matters, the new one does write_png(&first, 16, GREEN); - assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate); + assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate); write_png(&second, 16, RED); - assert_eq!(status_of(&s, &name), ResourceStatus::Outdated); + assert_eq!(status_of(&mut s, &name), ResourceStatus::Outdated); execute(&mut s, "edit.undo", &Value::Null).unwrap(); assert!(s.doc.project.resource_sources[&name].path.ends_with("first.png"), "undo restores the link"); } +#[test] +fn relink_refuses_resources_that_are_not_images() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("picture.png"); + write_png(&file, 4, RED); + let mut s = session(); + s.doc.resources.insert("material.mcmat".to_string(), Arc::new(vec![1, 2, 3])); + let steps = s.history_labels().len(); + + let error = execute(&mut s, "resource.relink", &json!({"name": "material.mcmat", "path": text(&file)})).unwrap_err(); + + assert!(error.to_string().contains("no image resource"), "{error}"); + assert_eq!(*s.doc.resources["material.mcmat"], vec![1, 2, 3]); + assert_eq!(s.history_labels().len(), steps); +} + #[test] fn resources_without_a_file_cannot_update_and_a_reopened_project_keeps_its_links() { - let dir = TempDir::new("reopen"); - let file = dir.file("kept.png"); + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("kept.png"); write_png(&file, 4, RED); let mut s = session(); let linked = import_as_fill(&mut s, &file); let png = std::fs::read(&file).unwrap(); let unlinked = s.import_resource_bytes("made.png", png).unwrap(); - assert_eq!(status_of(&s, &unlinked), ResourceStatus::NoSource); + assert_eq!(status_of(&mut s, &unlinked), ResourceStatus::NoSource); assert!(execute(&mut s, "resource.update", &json!({"names": [unlinked]})).is_err()); - let reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); write_png(&file, 8, GREEN); - assert_eq!(status_of(&reopened, &linked), ResourceStatus::Outdated); + assert_eq!(status_of(&mut reopened, &linked), ResourceStatus::Outdated); } #[test] fn a_removed_resource_forgets_its_file() { - let dir = TempDir::new("remove"); - let file = dir.file("old.png"); + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("old.png"); write_png(&file, 4, RED); let mut s = session(); - let name = execute(&mut s, "resource.import", &json!({"path": text(&file)})).unwrap()["name"].as_str().unwrap().to_string(); + let name = import(&mut s, &file); execute(&mut s, "resource.remove", &json!({"name": name})).unwrap(); let png = std::fs::read(&file).unwrap(); let reused = s.import_resource_bytes("old.png", png).unwrap(); assert_eq!(reused, name, "the name is free again"); - assert_eq!(status_of(&s, &reused), ResourceStatus::NoSource, "a new resource under the old name does not inherit the file"); + assert_eq!(status_of(&mut s, &reused), ResourceStatus::NoSource, "a new resource under the old name does not inherit the file"); +} + +/// The material ball: texture sets "Ball" and "Base" +fn ball() -> Session { + Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap() +} + +fn ambient_occlusion(s: &Session) -> Vec { + s.doc.baked[&0].maps[&BakedMap::AmbientOcclusion].as_ref().clone() +} + +#[test] +fn an_imported_mesh_map_follows_its_changed_file_until_something_else_replaces_it() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("Ball_ao.png"); + write_png(&file, 4, [60, 60, 60, 255]); + let mut s = ball(); + execute(&mut s, "textureSet.meshMap.import", &json!({"files": [{"path": text(&file)}]})).unwrap(); + let name = s.doc.project.resource_sources.keys().next().expect("the file is remembered").clone(); + let imported = ambient_occlusion(&s); + + write_png(&file, 8, [200, 200, 200, 255]); + execute(&mut s, "resource.update", &json!({})).unwrap(); + let updated = ambient_occlusion(&s); + + assert_ne!(updated, imported, "the mesh map is resampled from the new file"); + + // Another image in the slot is not overwritten by a later change of the file + let other = dir.path().join("other.png"); + write_png(&other, 4, [10, 10, 10, 255]); + let other_name = import(&mut s, &other); + execute(&mut s, "textureSet.meshMap.set", &json!({"ts": 0, "map": "ambientOcclusion", "image": other_name})).unwrap(); + let replaced = ambient_occlusion(&s); + write_png(&file, 16, [120, 120, 120, 255]); + let result = execute(&mut s, "resource.update", &json!({"names": [name]})).unwrap(); + + assert_eq!(result["updated"], json!([name]), "the resource itself still updates"); + assert_eq!(ambient_occlusion(&s), replaced, "the mesh map keeps the image set over it"); +} + +#[test] +fn pbr_folder_and_materialx_imports_remember_their_image_files() { + let dir = tempfile::tempdir().unwrap(); + let color = dir.path().join("moss_col.png"); + write_png(&color, 4, RED); + std::fs::create_dir(dir.path().join("tex")).unwrap(); + let base = dir.path().join("tex").join("base.png"); + write_png(&base, 4, GREEN); + let mtlx = dir.path().join("m.mtlx"); + let document = r#" + + + + +"#; + std::fs::write(&mtlx, document).unwrap(); + let mut s = session(); + + let pbr = execute(&mut s, "file.importPbrFolder", &json!({"files": [text(&color)]})).unwrap(); + let materialx = execute(&mut s, "file.importMaterialX", &json!({"path": text(&mtlx)})).unwrap(); + let pbr_name = pbr["resources"][0].as_str().unwrap().to_string(); + let materialx_name = materialx["resources"][0].as_str().unwrap().to_string(); + + assert!(s.doc.project.resource_sources[&pbr_name].path.ends_with("moss_col.png")); + assert!(s.doc.project.resource_sources[&materialx_name].path.ends_with("base.png")); + + write_png(&color, 8, GREEN); + write_png(&base, 8, RED); + + assert_eq!(status_of(&mut s, &pbr_name), ResourceStatus::Outdated); + assert_eq!(status_of(&mut s, &materialx_name), ResourceStatus::Outdated); } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 9abb472c..50481899 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -82,3 +82,5 @@ egui_kittest = { version = "0.37", features = ["wgpu", "eframe"] } pollster = "0.4" image = { workspace = true } craft-image-codecs = { workspace = true } +# Test folders removed when the test ends +tempfile = "3" diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 235ebc5e..435aac1c 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -237,6 +237,9 @@ mod tests { keys.extend(BlendMode::all().map(|mode| mode.label())); keys.extend(texturecraft_engine::formats::export::VirtualMap::ALL.iter().map(|map| map.label())); keys.extend(texturecraft_engine::Tool::ALL.iter().map(|tool| tool.label())); + keys.extend(texturecraft_engine::ResourceStatus::ALL.iter().map(|status| status.label())); + let notice = crate::toast_action::ToastAction::UpdateResources { project: 0 }; + keys.extend([notice.label(), notice.accessible_name()]); keys.extend(texturecraft_engine::HISTORY_TEMPLATES); keys.extend(ProceduralKind::ALL.iter().map(|kind| kind.label())); keys.extend(GeneratorKind::ALL.iter().map(|kind| kind.label())); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 100d07a5..b10af608 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -325,6 +325,9 @@ pub struct TextureCraftApp { /// The outdated resources the last "changed on disk" notice named, so an unchanged set is not announced again #[cfg(not(target_arch = "wasm32"))] pub(crate) resources_notified: std::collections::BTreeSet, + /// The project the Resources Updater last checked on opening (see `resources_updater::follow_project`) + #[cfg(not(target_arch = "wasm32"))] + pub(crate) resources_project: Option, /// The update check and prompt (desktop only). #[cfg(not(target_arch = "wasm32"))] pub(crate) updates_rt: updates_ui::Runtime, @@ -449,6 +452,8 @@ impl TextureCraftApp { #[cfg(not(target_arch = "wasm32"))] resources_notified: std::collections::BTreeSet::new(), #[cfg(not(target_arch = "wasm32"))] + resources_project: None, + #[cfg(not(target_arch = "wasm32"))] updates_rt: updates_ui::Runtime::default(), #[cfg(not(target_arch = "wasm32"))] file_dialogs: file_dialogs::FileDialogs::new(cc.egui_ctx.clone()), @@ -1130,9 +1135,11 @@ impl eframe::App for TextureCraftApp { // Files may have been edited in another app meanwhile #[cfg(not(target_arch = "wasm32"))] - resources_updater::check_on_focus(self); + resources_updater::check_files(self); } self.focused = focused; + #[cfg(not(target_arch = "wasm32"))] + resources_updater::follow_project(self); let scale = self.ui.prefs.ui_scale.clamp(*UI_SCALE_APPLIED.start(), *UI_SCALE_APPLIED.end()); if (ctx.zoom_factor() - scale).abs() > SAME_ZOOM_TOLERANCE { @@ -1335,11 +1342,13 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { show_log = true; dismissed = Some(i); } - if let Some(action) = t.action - && ui.button(i18n::tr(action.label())).clicked() - { - clicked_action = Some(action); - dismissed = Some(i); + if let Some(action) = t.action { + let button = ui.button(i18n::tr(action.label())); + button.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, i18n::tr(action.accessible_name()))); + if button.clicked() { + clicked_action = Some(action); + dismissed = Some(i); + } } }); if sticky && widgets::icon_button(ui, egui_phosphor::regular::X, i18n::tr("Dismiss"), false, 18.0).clicked() { diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index a0fd80de..1d4588ea 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -526,9 +526,6 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { } else if app.ui.windows.import_resources.is_some() { #[cfg(not(target_arch = "wasm32"))] crate::import_resources::keys_in(app, input, nothing_focused, popup_open); - } else if app.ui.windows.resources_updater.is_some() && !popup_open && input.key_pressed(Key::Escape) { - #[cfg(not(target_arch = "wasm32"))] - crate::resources_updater::keys_in(app, input); } else if !popup_open && app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_color = None; } else if escape_is_free && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { diff --git a/crates/ui-egui/src/resources_updater.rs b/crates/ui-egui/src/resources_updater.rs index 4bb9ce60..c0de777d 100644 --- a/crates/ui-egui/src/resources_updater.rs +++ b/crates/ui-egui/src/resources_updater.rs @@ -7,7 +7,6 @@ mod row_request; use std::collections::BTreeSet; -use egui::{Key, Modifiers}; use serde_json::json; use texturecraft_engine::{ResourceState, ResourceStatus}; @@ -25,7 +24,7 @@ use row_request::RowRequest; const WINDOW_WIDTH_POINTS: f32 = 640.0; /// Height of the resource list const LIST_HEIGHT_POINTS: f32 = 360.0; -// Initial space for the header, tabs, filters and footer +/// Initial space for the header, tabs, filters and footer const WINDOW_CHROME_HEIGHT_POINTS: f32 = 160.0; /// Side of a row's thumbnail const THUMBNAIL_POINTS: f32 = 40.0; @@ -39,6 +38,8 @@ const ROW_MARGIN: egui::Margin = egui::Margin::same(4); const OUTDATED_TINT: f32 = 0.18; /// How long the "changed on disk" notice stays, in seconds: long enough to reach its button const NOTICE_SECONDS: f64 = 12.0; +/// Shortest time between two checks after document changes, in seconds (each check looks at every file) +const RECHECK_SECONDS: f64 = 0.5; /// Opens the window, or closes it when it is open (the shelf button) pub(crate) fn toggle(app: &mut TextureCraftApp) { @@ -54,13 +55,26 @@ pub(crate) fn open(app: &mut TextureCraftApp) { rows: app.session.resource_states(), project: app.session.project_id, checked_revision: app.session.revision, + checked_at: app.last_time, ..window }); } -/// The app has the focus back: check the files again and, when other resources than last time -/// are outdated, show a notice whose button updates them -pub(crate) fn check_on_focus(app: &mut TextureCraftApp) { +/// Check once when another project is open (files may have changed while it was closed), and +/// forget what was announced for the last one +pub(crate) fn follow_project(app: &mut TextureCraftApp) { + if !app.session.project_open || app.resources_project == Some(app.session.project_id) { + return; + } + + app.resources_project = Some(app.session.project_id); + app.resources_notified.clear(); + check_files(app); +} + +/// Check the files again (the app has the focus back, or a project opened) and, when other +/// resources than last time are outdated, show a notice whose button updates them +pub(crate) fn check_files(app: &mut TextureCraftApp) { if !app.session.project_open { return; } @@ -70,6 +84,7 @@ pub(crate) fn check_on_focus(app: &mut TextureCraftApp) { if let Some(window) = app.ui.windows.resources_updater.as_mut() { window.rows = rows; window.checked_revision = app.session.revision; + window.checked_at = app.last_time; } if !outdated.is_empty() && outdated != app.resources_notified { @@ -81,7 +96,7 @@ pub(crate) fn check_on_focus(app: &mut TextureCraftApp) { app.toast(text, false); if let Some(toast) = app.toasts.last_mut() { toast.until = app.last_time + NOTICE_SECONDS; - toast.action = Some(ToastAction::UpdateResources); + toast.action = Some(ToastAction::UpdateResources { project: app.session.project_id }); } } app.resources_notified = outdated; @@ -137,13 +152,6 @@ fn show_in_folder(app: &mut TextureCraftApp, path: &str) { } } -/// The keys of the open window: Escape closes it (an open dropdown takes it first, see `menus`) -pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState) { - if input.consume_key(Modifiers::NONE, Key::Escape) { - app.ui.windows.resources_updater = None; - } -} - /// Whether `row` passes the window's status and name filters fn shown(window: &ResourcesUpdater, row: &ResourceState) -> bool { let name_filter = window.name_filter.trim().to_lowercase(); @@ -164,18 +172,31 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } - // Every change (an update, undo, redo, a removed resource) is checked again + // Every change (an update, undo, redo, a removed resource) is checked again, at most twice a second if window.checked_revision != app.session.revision { - window.rows = app.session.resource_states(); - window.checked_revision = app.session.revision; + let wait = window.checked_at + RECHECK_SECONDS - app.last_time; + if wait <= 0.0 { + window.rows = app.session.resource_states(); + window.checked_revision = app.session.revision; + window.checked_at = app.last_time; + } else { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); + } + } + + // Escape closes the window only while one of its controls had the keyboard (egui takes the focus away on it); otherwise it cancels a stroke as usual + // egui consumes that Escape to take the focus away, so the raw events are read + let escape = ctx.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); + if window.had_keyboard && escape && !egui::Popup::is_any_open(ctx) { + return; } let tokens = Tokens::get(ctx); - let mut open = true; + let mut window_open = true; let (mut refresh, mut update_all) = (false, false); let mut request = None; - crate::windows::dialog(ctx, "resources_updater", tr("Resources Updater"), &mut open) + let shown = crate::windows::dialog(ctx, "resources_updater", tr("Resources Updater"), &mut window_open) .default_size(egui::vec2(WINDOW_WIDTH_POINTS, LIST_HEIGHT_POINTS + WINDOW_CHROME_HEIGHT_POINTS)) .show(ctx, |ui| { ui.label(format!("{} {}", tr("Project :"), app.session.doc.project.name)); @@ -216,7 +237,9 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { ui.horizontal(|ui| { - refresh = ui.button(tr("Refresh")).clicked(); + let refresh_button = ui.button(tr("Refresh")); + refresh_button.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tr("Refresh resources"))); + refresh = refresh_button.clicked(); ui.label(summary(&window.rows)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let outdated = window.rows.iter().any(|row| row.status == ResourceStatus::Outdated); @@ -252,15 +275,16 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }); }); - if !open { + let focused = ctx.memory(|memory| memory.focused()).and_then(|id| ctx.read_response(id)); + window.had_keyboard = shown.as_ref().zip(focused.as_ref()).is_some_and(|(shown, focused)| focused.layer_id == shown.response.layer_id); + if !window_open { return; } app.ui.windows.resources_updater = Some(window); - if refresh { - open(app); - } + // Its own changes and Refresh show at once + let check_now = refresh || update_all || matches!(request, Some(RowRequest::Update(_))); if update_all { update(app, None); } @@ -270,6 +294,10 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { Some(RowRequest::ShowFolder(path)) => show_in_folder(app, &path), None => {} } + + if check_now { + open(app); + } } /// One resource: its thumbnail, number, name, file and status, and its buttons. Outdated rows are @@ -297,8 +325,7 @@ fn row_ui(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, number: } ui.label(number.to_string()); - // Buttons take their room on the right first, so the texts truncate in what is left - // Each button's accessible name says which resource it acts on + // Buttons go first, so the texts truncate in what is left; each accessible name names its resource ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let update = ui.add_enabled(outdated, egui::Button::new(tr("Update"))); let update_name = format!("{} {}", tr("Update"), row.name); @@ -325,6 +352,7 @@ fn row_ui(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, number: ui.vertical(|ui| { ui.add(egui::Label::new(format!("{} {}", tr("Name :"), row.name)).truncate()); + ui.label(format!("{} {}", tr("Shelf :"), tr("project"))); let file = row.path.as_deref().unwrap_or(tr("No source file")); ui.add(egui::Label::new(format!("{} {}", tr("File :"), file)).truncate()).on_hover_text(file); let status = ui.label(tr(row.status.label())); @@ -352,30 +380,35 @@ mod tests { image::RgbaImage::from_pixel(size, size, image::Rgba([10, 200, 30, 255])).save(path).unwrap(); } - fn notices(app: &TextureCraftApp) -> usize { - app.toasts.iter().filter(|toast| toast.action == Some(ToastAction::UpdateResources)).count() + fn notices(app: &TextureCraftApp) -> Vec { + app.toasts.iter().filter_map(|toast| toast.action).collect() } #[test] fn a_changed_file_is_announced_once_and_the_notice_updates_it() { let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(PoisonError::into_inner); - let path = std::env::temp_dir().join(format!("texturecraft-resources-notice-{}.png", std::process::id())); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("notice.png"); write_png(&path, 4); let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); let mut harness = Harness::builder().build_eframe(|cc| TextureCraftApp::new(cc, session)); let app = harness.state_mut(); let name = app.run("resource.import", json!({ "path": path.to_str().unwrap() })).unwrap()["name"].as_str().unwrap().to_string(); - check_on_focus(app); - assert_eq!(notices(app), 0, "nothing changed yet"); + check_files(app); + assert!(notices(app).is_empty(), "nothing changed yet"); write_png(&path, 8); - check_on_focus(app); - check_on_focus(app); - assert_eq!(notices(app), 1, "the same change is announced once"); + check_files(app); + check_files(app); + let announced = notices(app); + assert_eq!(announced, [ToastAction::UpdateResources { project: app.session.project_id }], "the same change is announced once"); - ToastAction::UpdateResources.run(app); - std::fs::remove_file(&path).ok(); + // A notice about another project does nothing + ToastAction::UpdateResources { project: app.session.project_id + 1 }.run(app); + assert_eq!(app.session.images[&name].width, 4); + + announced[0].run(app); assert_eq!(app.session.images[&name].width, 8, "the notice's button updated the resource"); assert_eq!(app.session.history_labels().last().map(String::as_str), Some("Update resources")); diff --git a/crates/ui-egui/src/state/resources_updater.rs b/crates/ui-egui/src/state/resources_updater.rs index 46fb9d12..805ef0b8 100644 --- a/crates/ui-egui/src/state/resources_updater.rs +++ b/crates/ui-egui/src/state/resources_updater.rs @@ -16,4 +16,8 @@ pub struct ResourcesUpdater { pub project: u64, /// The session revision the rows were checked at pub(crate) checked_revision: u64, + /// When the rows were checked, in app seconds + pub(crate) checked_at: f64, + /// Whether a control of the window had the keyboard focus when it was last drawn (Escape then closes it) + pub(crate) had_keyboard: bool, } diff --git a/crates/ui-egui/src/toast_action.rs b/crates/ui-egui/src/toast_action.rs index d360fd7b..e7d05308 100644 --- a/crates/ui-egui/src/toast_action.rs +++ b/crates/ui-egui/src/toast_action.rs @@ -5,30 +5,37 @@ use crate::TextureCraftApp; /// What a toast's button does #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ToastAction { - /// "Update": read every outdated resource file again (the "changed on disk" notice) - #[cfg(not(target_arch = "wasm32"))] - UpdateResources, + /// "Update": read every outdated resource file of `project` again (the desktop's "changed on disk" notice) + UpdateResources { + /// The project the notice is about; the button does nothing once another one is open + project: u64, + }, } impl ToastAction { /// The button's text (English; translated where it is drawn) pub fn label(self) -> &'static str { match self { - #[cfg(not(target_arch = "wasm32"))] - ToastAction::UpdateResources => "Update", + ToastAction::UpdateResources { .. } => "Update", + } + } + + /// The button's accessible name, which says what it acts on (English; translated where it is drawn) + pub fn accessible_name(self) -> &'static str { + match self { + ToastAction::UpdateResources { .. } => "Update resources", } } - #[cfg(not(target_arch = "wasm32"))] pub(crate) fn run(self, app: &mut TextureCraftApp) { match self { - ToastAction::UpdateResources => crate::resources_updater::update(app, None), + // Another project's notice is stale + ToastAction::UpdateResources { project } if project != app.session.project_id => {} + #[cfg(not(target_arch = "wasm32"))] + ToastAction::UpdateResources { .. } => crate::resources_updater::update(app, None), + // The browser has no files to read again + #[cfg(target_arch = "wasm32")] + ToastAction::UpdateResources { .. } => {} } } - - /// The browser's toasts carry no action yet - #[cfg(target_arch = "wasm32")] - pub(crate) fn run(self, _: &mut TextureCraftApp) { - match self {} - } } diff --git a/crates/ui-egui/tests/it/resources_updater.rs b/crates/ui-egui/tests/it/resources_updater.rs index 298c1130..534bd7b1 100644 --- a/crates/ui-egui/tests/it/resources_updater.rs +++ b/crates/ui-egui/tests/it/resources_updater.rs @@ -4,13 +4,14 @@ use std::path::{Path, PathBuf}; -use egui::{Key, Role}; +use egui::{Key, Role, vec2}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use texturecraft_engine::Session; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::file_dialogs::{Answer, Request}; +use texturecraft_ui_egui::state::ViewLayout; use super::temp_dir::TempDir; @@ -59,40 +60,44 @@ fn width_of(h: &Harness<'_, TextureCraftApp>, name: &str) -> u32 { #[test] fn the_window_opens_from_the_keyboard_and_updates_an_outdated_resource_as_one_undo_step() { let dir = TempDir::new("resources-updater-update"); - let (kept, changed) = (png(&dir, "kept.png", 4), png(&dir, "changed.png", 4)); + let (kept, changed) = (png(&dir, "aa_kept.png", 4), png(&dir, "zz_changed.png", 4)); let mut h = app(); import(&mut h, &kept); import(&mut h, &changed); - png(&dir, "changed.png", 8); + png(&dir, "zz_changed.png", 8); activate(&mut h, "Resources Updater"); let rows = &h.state().ui.windows.resources_updater.as_ref().expect("the window is open").rows; - assert_eq!(rows[0].name, "changed.png", "outdated resources come first"); + assert_eq!(rows[0].name, "zz_changed.png", "outdated resources come first, before names that sort earlier"); assert!(shows(&h, "Project : Test")); + assert_eq!(h.get_all_by_label("Shelf : project").count(), 2, "the reference's shelf line, one per row"); assert!(shows(&h, "(2 resources, 1 outdated)")); assert!(shows(&h, "Outdated"), "the status is written out, not only coloured"); - assert!(h.get_by_role_and_label(Role::Button, "Update kept.png").accesskit_node().is_disabled(), "only outdated resources update"); + assert!(h.get_by_role_and_label(Role::Button, "Update aa_kept.png").accesskit_node().is_disabled(), "only outdated resources update"); let steps = h.state().session.history_labels().len(); - activate(&mut h, "Update changed.png"); + activate(&mut h, "Update zz_changed.png"); - assert_eq!(width_of(&h, "changed.png"), 8, "the new file's pixels are in the project"); + assert_eq!(width_of(&h, "zz_changed.png"), 8, "the new file's pixels are in the project"); assert_eq!(h.state().session.history_labels().len(), steps + 1, "one undo step"); assert!(shows(&h, "(2 resources, 0 outdated)")); - // Undo brings the old pixels back, so the list shows the file as changed again + // Undo brings the old pixels back, so Refresh shows the file as changed again h.state_mut().run("edit.undo", json!({})).unwrap(); - h.run_steps(3); + activate(&mut h, "Refresh resources"); - assert_eq!(width_of(&h, "changed.png"), 4); + assert_eq!(width_of(&h, "zz_changed.png"), 4); assert!(shows(&h, "(2 resources, 1 outdated)")); activate(&mut h, "Update All"); - assert_eq!(width_of(&h, "changed.png"), 8); + assert_eq!(width_of(&h, "zz_changed.png"), 8); + // Update All went grey with nothing left to update; the keyboard moves on to another button of the window + h.get_by_role_and_label(Role::Button, "Select new resource aa_kept.png").focus(); + h.run_steps(2); press(&mut h, Key::Escape); - assert!(h.state().ui.windows.resources_updater.is_none(), "Escape closes the window"); + assert!(h.state().ui.windows.resources_updater.is_none(), "Escape closes the window while it has the keyboard"); } #[test] @@ -135,3 +140,31 @@ fn show_in_folder_shows_the_folder_of_the_resource_file() { assert_eq!(shown.len(), 1); assert_eq!(shown[0].file_name(), dir.file_name(), "the file's own folder"); } + +#[test] +fn escape_cancels_a_stroke_while_the_window_is_open_without_the_keyboard() { + const FRAMES_PER_DRAG_EVENT: usize = 2; + + let mut h = app(); + h.state_mut().run("layer.add.paint", json!({})).unwrap(); + h.state_mut().ui.layout = ViewLayout::Only3D; + h.run_steps(3); + let center = h.state().viewport_rect.center(); + h.drag_at(center); + h.run_steps(FRAMES_PER_DRAG_EVENT); + h.hover_at(center + vec2(20.0, 0.0)); + h.run_steps(FRAMES_PER_DRAG_EVENT); + assert!(h.state().session.stroke_active()); + + // Opened from the shelf mid-stroke, the keyboard stays on the shelf button + activate(&mut h, "Resources Updater"); + assert!(h.state().ui.windows.resources_updater.is_some()); + assert!(h.state().session.stroke_active()); + + press(&mut h, Key::Escape); + + assert!(!h.state().session.stroke_active(), "Escape cancels the stroke"); + assert!(h.state().ui.windows.resources_updater.is_some(), "the window keeps open: its controls do not have the keyboard"); + h.drop_at(center + vec2(30.0, 0.0)); + h.run_steps(3); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 0cf55589..ce32a426 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -468,17 +468,22 @@ printf '%s\n' '{"id":1,"method":"command.run","params":{"id":"project.new","para ## Resources Updater -An image resource imported with `resource.import {path}` remembers that file (its absolute path and -modification time, saved with the project). The shelf's Resources Updater window lists the project's -image resources through these commands and checks them again when it opens, on Refresh, after every -change and when the app gets the focus back; then a notice ("N resources changed on disk", with an -Update button) appears when the set of outdated resources changed since the last notice. +An image resource read from a file remembers that file (its absolute path and modification time, +saved with the project): `resource.import {path}`, the images `file.importPbrFolder` stores unchanged +(not ORM channels split out, not archive entries), the images of `file.importMaterialX` and the files of +`textureSet.meshMap.import` (with their mesh map: an update resamples it while it still holds what the +old file gave it, so a bake or another image set over it since is kept). The shelf's Resources Updater +window lists the project's image resources through these commands and checks them when it opens, on +Refresh, after changes (at most twice a second), once after a project opens and when the app gets the +focus back; a notice ("N resources changed on disk", with an Update button) appears when the set of +outdated resources differs from the last notice. A file whose size matches but whose time changed is +read once; its verdict is kept until its size or time changes again. | Command | Params and result | |---|---| | `resource.status` | `{}` → `{resources: [{name, status, path?, error?}], total, outdated}`; `status` is `outdated` (the file's size or contents differ from the resource), `missing` (the file is gone or unreadable, `error` says why), `upToDate` or `noSource` (made in the app or imported without a path); outdated first, then by name. A file is read only when its size matches but its modification time does not | | `resource.update` | `{names?: [name]}` (default: every outdated resource) → `{updated, failed: [{name, error}]}`: reads the files again and replaces the resources' bytes and pixels under the same names, so every layer, mask and view using them recomposites; one undo step, none when nothing changed. A file that cannot be read fails alone; when none could be read the command is an error. Unknown names and resources without a file are refused | -| `resource.relink` | `{name, path}` → `{name, path}`: the resource takes the image file's pixels (within the image import limits) and follows that file from then on; one undo step | +| `resource.relink` | `{name, path}` → `{name, path}`: an image resource takes the image file's pixels (within the image import limits) and follows that file from then on; one undo step | These commands read host paths stored in the project, so MCP and `serve` refuse them through `command_run`; the desktop app's control channel and the trusted local CLI run them. diff --git a/docs/features.md b/docs/features.md index a3692d83..8a25b66a 100644 --- a/docs/features.md +++ b/docs/features.md @@ -98,13 +98,15 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA and alpha images become the brush alpha. Filter by role or remove selected rows before importing. Failed rows stay in the dialog for retry. Color LUT, post effects and asset-library import are unavailable. The browser imports images straight from its file picker. -- **Resources Updater:** the shelf button under the tools lists the project's image resources with - their files, outdated ones first. An imported image remembers its file; when that file changes on - disk, *Update* (or *Update All*) reads it again and every layer using it recomposites, as one undo - step. *Select new resource* points a resource at another file, *Show in folder* opens its folder, - and the list filters by status and name. When the app gets the focus back after files changed, a - notice offers *Update*. Desktop only; there is no Shaders tab, since TextureCraft has no shader - resources. +- **Resources Updater:** the shelf button under the tools lists the project's image resources, + outdated ones first: name, *Shelf : project* as in the reference, and an extra *File :* line with + the file it came from. An image read from a file (Import resources, PBR folders, MaterialX, imported + mesh maps) remembers it; when the file changes on disk, *Update* (or *Update All*) reads it again + and every layer and imported mesh map using it follows, as one undo step. *Select new resource* + points a resource at another file, *Show in folder* opens its folder, and the list filters by status + and name. After a project opens and when the app gets the focus back after files changed, a notice + offers *Update*. Desktop only; there is no Shaders tab (TextureCraft has no shader resources), no + Pin window and no × to clear a link. - **Your own library:** right-click a layer or folder, choose *Create smart material*, and it appears under *My smart materials*, pixels and images included. *Create smart mask* in the same menu saves just the layer's mask (all its effects, painted pixels and images); it appears under From 95fac86e4e4b6d1962b79526305c0ae66692965c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 13:43:31 +0100 Subject: [PATCH 3/7] Resources Updater: recheck files while the window stays open; a mesh map follows its latest imported file --- crates/engine/src/meshmap_import_cmds.rs | 8 ++++- crates/engine/tests/it/resource_updater.rs | 21 +++++++++++++ crates/ui-egui/src/resources_updater.rs | 30 +++++++------------ crates/ui-egui/src/state/resources_updater.rs | 4 +-- crates/ui-egui/tests/it/resources_updater.rs | 18 +++++++++++ docs/control-protocol.md | 2 +- 6 files changed, 59 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/meshmap_import_cmds.rs b/crates/engine/src/meshmap_import_cmds.rs index 2c9f9b56..0f69659e 100644 --- a/crates/engine/src/meshmap_import_cmds.rs +++ b/crates/engine/src/meshmap_import_cmds.rs @@ -85,12 +85,18 @@ fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result() as u64; let name = s.add_image_resource(path, bytes, remaining_bytes / bytes_per_texel)?; + + // The slot follows only its latest file: an earlier import into it no longer feeds it + for earlier in s.doc.project.resource_sources.values_mut().filter(|earlier| earlier.mesh_map == Some(slot)) { + earlier.mesh_map = None; + } s.doc.project.resource_sources.insert(name.clone(), source); let image = s.images.get(&name).ok_or_else(|| bad(CMD, format!("no decoded image `{name}`")))?; reserve_bytes(&mut remaining_bytes, u64::from(image.width) * u64::from(image.height) * bytes_per_texel)?; diff --git a/crates/engine/tests/it/resource_updater.rs b/crates/engine/tests/it/resource_updater.rs index 93b26908..43a9120b 100644 --- a/crates/engine/tests/it/resource_updater.rs +++ b/crates/engine/tests/it/resource_updater.rs @@ -341,3 +341,24 @@ fn pbr_folder_and_materialx_imports_remember_their_image_files() { assert_eq!(status_of(&mut s, &pbr_name), ResourceStatus::Outdated); assert_eq!(status_of(&mut s, &materialx_name), ResourceStatus::Outdated); } + +#[test] +fn a_mesh_map_imported_twice_follows_the_latest_file() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("Ball_ao.png"); + let import_file = |s: &mut Session| execute(s, "textureSet.meshMap.import", &json!({"files": [{"path": text(&file)}]})).unwrap(); + let mut s = ball(); + write_png(&file, 4, [60, 60, 60, 255]); + import_file(&mut s); + let first = s.doc.project.resource_sources.keys().next().unwrap().clone(); + write_png(&file, 8, [200, 200, 200, 255]); + import_file(&mut s); + let latest = s.doc.project.resource_sources.keys().find(|name| **name != first).expect("a second resource").clone(); + let imported = ambient_occlusion(&s); + + write_png(&file, 16, [10, 10, 10, 255]); + execute(&mut s, "resource.update", &json!({"names": [latest]})).unwrap(); + + assert_ne!(ambient_occlusion(&s), imported, "the mesh map follows the file imported last"); + assert!(s.doc.project.resource_sources[&first].mesh_map.is_none(), "the earlier import no longer feeds the slot"); +} diff --git a/crates/ui-egui/src/resources_updater.rs b/crates/ui-egui/src/resources_updater.rs index c0de777d..95840c26 100644 --- a/crates/ui-egui/src/resources_updater.rs +++ b/crates/ui-egui/src/resources_updater.rs @@ -38,7 +38,7 @@ const ROW_MARGIN: egui::Margin = egui::Margin::same(4); const OUTDATED_TINT: f32 = 0.18; /// How long the "changed on disk" notice stays, in seconds: long enough to reach its button const NOTICE_SECONDS: f64 = 12.0; -/// Shortest time between two checks after document changes, in seconds (each check looks at every file) +/// Time between two checks while the window is open, in seconds (each check looks at every file; an unchanged one is not read) const RECHECK_SECONDS: f64 = 0.5; /// Opens the window, or closes it when it is open (the shelf button) @@ -51,13 +51,8 @@ pub(crate) fn toggle(app: &mut TextureCraftApp) { /// Opens the window with the resources checked now (an open window is checked again) pub(crate) fn open(app: &mut TextureCraftApp) { let window = app.ui.windows.resources_updater.take().unwrap_or_default(); - app.ui.windows.resources_updater = Some(ResourcesUpdater { - rows: app.session.resource_states(), - project: app.session.project_id, - checked_revision: app.session.revision, - checked_at: app.last_time, - ..window - }); + app.ui.windows.resources_updater = + Some(ResourcesUpdater { rows: app.session.resource_states(), project: app.session.project_id, checked_at: app.last_time, ..window }); } /// Check once when another project is open (files may have changed while it was closed), and @@ -83,7 +78,6 @@ pub(crate) fn check_files(app: &mut TextureCraftApp) { let outdated: BTreeSet = rows.iter().filter(|row| row.status == ResourceStatus::Outdated).map(|row| row.name.clone()).collect(); if let Some(window) = app.ui.windows.resources_updater.as_mut() { window.rows = rows; - window.checked_revision = app.session.revision; window.checked_at = app.last_time; } @@ -172,16 +166,14 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } - // Every change (an update, undo, redo, a removed resource) is checked again, at most twice a second - if window.checked_revision != app.session.revision { - let wait = window.checked_at + RECHECK_SECONDS - app.last_time; - if wait <= 0.0 { - window.rows = app.session.resource_states(); - window.checked_revision = app.session.revision; - window.checked_at = app.last_time; - } else { - ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); - } + // Files changed on disk and document changes (undo, a removed resource) show while the window stays open + let wait = window.checked_at + RECHECK_SECONDS - app.last_time; + if wait <= 0.0 { + window.rows = app.session.resource_states(); + window.checked_at = app.last_time; + ctx.request_repaint_after(std::time::Duration::from_secs_f64(RECHECK_SECONDS)); + } else { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); } // Escape closes the window only while one of its controls had the keyboard (egui takes the focus away on it); otherwise it cancels a stroke as usual diff --git a/crates/ui-egui/src/state/resources_updater.rs b/crates/ui-egui/src/state/resources_updater.rs index 805ef0b8..3b515d32 100644 --- a/crates/ui-egui/src/state/resources_updater.rs +++ b/crates/ui-egui/src/state/resources_updater.rs @@ -4,7 +4,7 @@ use texturecraft_engine::{ResourceState, ResourceStatus}; #[derive(Clone, Debug, PartialEq, Default)] pub struct ResourcesUpdater { /// The resources and how they compare with their files, outdated first (checked on opening, - /// Refresh, every change and when the app gets the focus back) + /// Refresh, twice a second while open and when the app gets the focus back) pub rows: Vec, /// The status the list is narrowed to (None: all) pub status_filter: Option, @@ -14,8 +14,6 @@ pub struct ResourcesUpdater { pub jump: Option, /// The project that was open when this window opened pub project: u64, - /// The session revision the rows were checked at - pub(crate) checked_revision: u64, /// When the rows were checked, in app seconds pub(crate) checked_at: f64, /// Whether a control of the window had the keyboard focus when it was last drawn (Escape then closes it) diff --git a/crates/ui-egui/tests/it/resources_updater.rs b/crates/ui-egui/tests/it/resources_updater.rs index 534bd7b1..980102a9 100644 --- a/crates/ui-egui/tests/it/resources_updater.rs +++ b/crates/ui-egui/tests/it/resources_updater.rs @@ -168,3 +168,21 @@ fn escape_cancels_a_stroke_while_the_window_is_open_without_the_keyboard() { h.drop_at(center + vec2(30.0, 0.0)); h.run_steps(3); } + +#[test] +fn a_file_changed_while_the_window_stays_open_shows_without_refresh() { + /// Steps of the harness's quarter second: over the window's half-second check + const FRAMES: usize = 4; + + let dir = TempDir::new("resources-updater-idle"); + let file = png(&dir, "bricks.png", 4); + let mut h = app(); + import(&mut h, &file); + activate(&mut h, "Resources Updater"); + assert!(shows(&h, "(1 resources, 0 outdated)")); + + png(&dir, "bricks.png", 8); + h.run_steps(FRAMES); + + assert!(shows(&h, "(1 resources, 1 outdated)"), "no document change, no focus change and no Refresh"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index ce32a426..50825541 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -474,7 +474,7 @@ saved with the project): `resource.import {path}`, the images `file.importPbrFol `textureSet.meshMap.import` (with their mesh map: an update resamples it while it still holds what the old file gave it, so a bake or another image set over it since is kept). The shelf's Resources Updater window lists the project's image resources through these commands and checks them when it opens, on -Refresh, after changes (at most twice a second), once after a project opens and when the app gets the +Refresh, twice a second while it stays open, once after a project opens and when the app gets the focus back; a notice ("N resources changed on disk", with an Update button) appears when the set of outdated resources differs from the last notice. A file whose size matches but whose time changed is read once; its verdict is kept until its size or time changes again. From fbff8906f4a1f3ea442304138998e780712dbd3b Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 18:40:24 +0100 Subject: [PATCH 4/7] Resources Updater: row ids follow the resource name, so the keyboard focus stays with its row --- crates/ui-egui/src/resources_updater.rs | 5 +++- crates/ui-egui/tests/it/resources_updater.rs | 24 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/resources_updater.rs b/crates/ui-egui/src/resources_updater.rs index 95840c26..21cf648b 100644 --- a/crates/ui-egui/src/resources_updater.rs +++ b/crates/ui-egui/src/resources_updater.rs @@ -254,7 +254,10 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.label(tr("No resources match the filters")); } for (index, row) in visible.into_iter().enumerate() { - if let Some(asked) = row_ui(app, ui, &tokens, index + 1, row) { + // Ids from the name alone, so the keyboard focus stays with its resource when a check reorders the rows + let row_scope = egui::UiBuilder::new().scope_id(ui.scope_id().with(("resources_updater_row", &row.name))); + let asked = ui.scope_builder(row_scope, |ui| row_ui(app, ui, &tokens, index + 1, row)).inner; + if let Some(asked) = asked { request = Some(asked); } } diff --git a/crates/ui-egui/tests/it/resources_updater.rs b/crates/ui-egui/tests/it/resources_updater.rs index 980102a9..20609aec 100644 --- a/crates/ui-egui/tests/it/resources_updater.rs +++ b/crates/ui-egui/tests/it/resources_updater.rs @@ -186,3 +186,27 @@ fn a_file_changed_while_the_window_stays_open_shows_without_refresh() { assert!(shows(&h, "(1 resources, 1 outdated)"), "no document change, no focus change and no Refresh"); } + +#[test] +fn the_keyboard_focus_stays_with_its_resource_when_the_rows_reorder() { + /// Steps of the harness's quarter second: over the window's half-second check + const FRAMES: usize = 4; + const SELECT_LATER: &str = "Select new resource zz_later.png"; + + let dir = TempDir::new("resources-updater-focus"); + let (earlier, later) = (png(&dir, "aa_earlier.png", 4), png(&dir, "zz_later.png", 4)); + let mut h = app(); + import(&mut h, &earlier); + import(&mut h, &later); + activate(&mut h, "Resources Updater"); + h.get_by_role_and_label(Role::Button, SELECT_LATER).focus(); + h.run_steps(2); + + // The changed file moves to the top of the list + png(&dir, "zz_later.png", 8); + h.run_steps(FRAMES); + + let rows = &h.state().ui.windows.resources_updater.as_ref().unwrap().rows; + assert_eq!(rows[0].name, "zz_later.png", "the outdated resource moved up"); + assert!(h.get_by_role_and_label(Role::Button, SELECT_LATER).accesskit_node().is_focused(), "the focus moved with it"); +} From c7a896d0789dd8f6654dbac39bd163678374e264 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 26 Nov 2026 21:01:46 +0100 Subject: [PATCH 5/7] Resources Updater tests: install the headless framework runtime in their harnesses Main's ui-contract runtime panics when a harness does not set it up; the notice unit test and the integration tests now use framework::install_headless like main's harness tests. --- crates/ui-egui/src/resources_updater.rs | 2 +- crates/ui-egui/tests/it/resources_updater.rs | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/resources_updater.rs b/crates/ui-egui/src/resources_updater.rs index 21cf648b..75b5a8fc 100644 --- a/crates/ui-egui/src/resources_updater.rs +++ b/crates/ui-egui/src/resources_updater.rs @@ -386,7 +386,7 @@ mod tests { let path = dir.path().join("notice.png"); write_png(&path, 4); let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); - let mut harness = Harness::builder().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session)); let app = harness.state_mut(); let name = app.run("resource.import", json!({ "path": path.to_str().unwrap() })).unwrap()["name"].as_str().unwrap().to_string(); diff --git a/crates/ui-egui/tests/it/resources_updater.rs b/crates/ui-egui/tests/it/resources_updater.rs index 20609aec..27209132 100644 --- a/crates/ui-egui/tests/it/resources_updater.rs +++ b/crates/ui-egui/tests/it/resources_updater.rs @@ -17,7 +17,10 @@ use super::temp_dir::TempDir; fn app() -> Harness<'static, TextureCraftApp> { let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); From f2205d559188c4cc43d6d1c0af16897840ddc6e3 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 26 Nov 2026 21:18:37 +0100 Subject: [PATCH 6/7] Resources Updater: list linked MaterialCraft materials as rows without a file resource.status gains the status material for the package of every linked MaterialCraft material (fill layers and material effects); such a row cannot be updated or relinked from disk, and its status tooltip says it updates when MaterialCraft cooks it again. Tests also check that an environment map and a brush alpha are tracked like other images. --- crates/engine/src/resource_status.rs | 12 +++++++--- crates/engine/src/resource_update_cmds.rs | 25 +++++++++++++++++++- crates/engine/tests/it/resource_updater.rs | 24 ++++++++++++++++--- crates/ui-egui/src/resources_updater.rs | 16 +++++++++---- crates/ui-egui/tests/it/resources_updater.rs | 15 +++++++++++- docs/control-protocol.md | 2 +- 6 files changed, 80 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/resource_status.rs b/crates/engine/src/resource_status.rs index 8e8efc70..b2ae9961 100644 --- a/crates/engine/src/resource_status.rs +++ b/crates/engine/src/resource_status.rs @@ -1,6 +1,6 @@ -//! Whether an image resource still matches the file it was imported from +//! Whether a resource still matches the file it was imported from -/// How an image resource compares with its file on disk. The order is the Resources Updater's +/// How a resource compares with its file on disk (materials have none). The order is the Resources Updater's /// list order: what needs attention first. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum ResourceStatus { @@ -12,10 +12,14 @@ pub enum ResourceStatus { UpToDate, /// Made in the app or imported without a file path: there is nothing to compare with. NoSource, + /// A linked MaterialCraft material's package: it has no file to compare with and updates by + /// cooking it again (`material.link.cook`). + Material, } impl ResourceStatus { - pub const ALL: [ResourceStatus; 4] = [ResourceStatus::Outdated, ResourceStatus::Missing, ResourceStatus::UpToDate, ResourceStatus::NoSource]; + pub const ALL: [ResourceStatus; 5] = + [ResourceStatus::Outdated, ResourceStatus::Missing, ResourceStatus::UpToDate, ResourceStatus::NoSource, ResourceStatus::Material]; /// The id used by the control protocol pub fn id(self) -> &'static str { @@ -24,6 +28,7 @@ impl ResourceStatus { ResourceStatus::Missing => "missing", ResourceStatus::UpToDate => "upToDate", ResourceStatus::NoSource => "noSource", + ResourceStatus::Material => "material", } } @@ -34,6 +39,7 @@ impl ResourceStatus { ResourceStatus::Missing => "Missing", ResourceStatus::UpToDate => "Up to date", ResourceStatus::NoSource => "No source file", + ResourceStatus::Material => "Material", } } } diff --git a/crates/engine/src/resource_update_cmds.rs b/crates/engine/src/resource_update_cmds.rs index 0fc56e7d..665516e3 100644 --- a/crates/engine/src/resource_update_cmds.rs +++ b/crates/engine/src/resource_update_cmds.rs @@ -18,7 +18,7 @@ pub fn specs() -> Vec { "Check resources on disk", [], None, - "{} → {resources: [{name, status: outdated|missing|upToDate|noSource, path?, error?}] (outdated first), total, outdated}", + "{} → {resources: [{name, status: outdated|missing|upToDate|noSource|material, path?, error?}] (outdated first; material: a linked MaterialCraft package, updated by material.link.cook), total, outdated}", always, |s, _| Ok(status(s)) ), @@ -49,10 +49,33 @@ impl Session { /// not, and that verdict is kept until the file's size or time changes again. pub fn resource_states(&mut self) -> Vec { let mut states = self.compare_resources(); + let materials = self.material_packages().into_iter(); + states.extend(materials.map(|name| ResourceState { name, status: ResourceStatus::Material, path: None, error: None })); states.sort_by(|a, b| a.status.cmp(&b.status).then_with(|| a.name.cmp(&b.name))); states } + /// The packages of linked MaterialCraft materials (fill layers and material effects) the project holds + fn material_packages(&self) -> std::collections::BTreeSet { + use texturecraft_core::{EffectKind, Fill, LayerKind}; + + let package_of = |fill: &Fill| fill.link.as_ref().map(|link| link.package.clone()); + let mut packages = std::collections::BTreeSet::new(); + for layer in self.doc.project.layers.values() { + if let LayerKind::Fill(fill) = &layer.kind { + packages.extend(package_of(fill)); + } + for effect in layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects) { + if let EffectKind::Material(fill) = &effect.kind { + packages.extend(package_of(fill)); + } + } + } + + packages.retain(|name| self.doc.resources.contains_key(name)); + packages + } + /// Whether `name` is an image resource the Resources Updater lists fn is_image_resource(&self, name: &str) -> bool { self.doc.resources.contains_key(name) && (self.images.contains_key(name) || self.doc.project.resource_sources.contains_key(name)) diff --git a/crates/engine/tests/it/resource_updater.rs b/crates/engine/tests/it/resource_updater.rs index 43a9120b..aa306838 100644 --- a/crates/engine/tests/it/resource_updater.rs +++ b/crates/engine/tests/it/resource_updater.rs @@ -102,7 +102,7 @@ fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() } #[test] -fn outdated_resources_come_first_then_missing_up_to_date_and_unlinked() { +fn outdated_resources_come_first_then_missing_up_to_date_unlinked_and_materials() { let dir = tempfile::tempdir().unwrap(); let [fine, gone, changed] = ["b_fine.png", "c_gone.png", "d_changed.png"].map(|name| dir.path().join(name)); for file in [&fine, &gone, &changed] { @@ -114,12 +114,30 @@ fn outdated_resources_come_first_then_missing_up_to_date_and_unlinked() { for file in [&fine, &gone, &changed] { import(&mut s, file); } + + // The environment map and the brush alpha are image resources like any other + let environment = format!("{}b_fine.png", texturecraft_engine::core::project::ENV_RESOURCE_PREFIX); + execute(&mut s, "display.set", &json!({"environment": environment})).unwrap(); + execute(&mut s, "tool.brush", &json!({"alpha": {"image": "d_changed.png"}})).unwrap(); + + // A linked MaterialCraft material keeps its package as a resource without a file + s.doc.resources.insert("a_brick.mcmat".to_string(), Arc::new(b"package".to_vec())); + let layer = execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + let link = serde_json::from_value(json!({"name": "Brick", "package": "a_brick.mcmat", "graph": "Brick", "params": [], "size": 4})).unwrap(); + if let texturecraft_engine::core::LayerKind::Fill(fill) = &mut s.doc.project.layers.get_mut(&texturecraft_engine::core::LayerId(layer)).unwrap().kind { + fill.link = Some(link); + } + std::fs::remove_file(&gone).unwrap(); write_png(&changed, 8, GREEN); - let order: Vec = s.resource_states().into_iter().map(|state| state.name).collect(); + let states = s.resource_states(); + let order: Vec<&str> = states.iter().map(|state| state.name.as_str()).collect(); + let statuses: Vec<&str> = states.iter().map(|state| state.status.id()).collect(); - assert_eq!(order, ["d_changed.png", "c_gone.png", "b_fine.png", "a_unlinked.png"], "by status first, against the name order"); + assert_eq!(order, ["d_changed.png", "c_gone.png", "b_fine.png", "a_unlinked.png", "a_brick.mcmat"], "by status first, against the name order"); + assert_eq!(statuses, ["outdated", "missing", "upToDate", "noSource", "material"], "the alpha's and the environment's files are checked too"); + assert!(execute(&mut s, "resource.update", &json!({"names": ["a_brick.mcmat"]})).is_err(), "a material has no file to read again"); } #[test] diff --git a/crates/ui-egui/src/resources_updater.rs b/crates/ui-egui/src/resources_updater.rs index 75b5a8fc..5cf20018 100644 --- a/crates/ui-egui/src/resources_updater.rs +++ b/crates/ui-egui/src/resources_updater.rs @@ -329,11 +329,15 @@ fn row_ui(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, number: request = Some(RowRequest::Update(row.name.clone())); } - let select = ui.button(tr("Select new resource")); - let select_name = format!("{} {}", tr("Select new resource"), row.name); - select.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &select_name)); - if select.clicked() { - request = Some(RowRequest::SelectNew(row.name.clone())); + // A material is no image file, so it cannot point at one + let material = row.status == ResourceStatus::Material; + if !material { + let select = ui.button(tr("Select new resource")); + let select_name = format!("{} {}", tr("Select new resource"), row.name); + select.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &select_name)); + if select.clicked() { + request = Some(RowRequest::SelectNew(row.name.clone())); + } } if let Some(path) = &row.path { @@ -353,6 +357,8 @@ fn row_ui(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, number: let status = ui.label(tr(row.status.label())); if let Some(error) = &row.error { status.on_hover_text(error); + } else if material { + status.on_hover_text(tr("A MaterialCraft material has no file on disk: it updates when MaterialCraft cooks it again")); } }); }); diff --git a/crates/ui-egui/tests/it/resources_updater.rs b/crates/ui-egui/tests/it/resources_updater.rs index 27209132..050fedb4 100644 --- a/crates/ui-egui/tests/it/resources_updater.rs +++ b/crates/ui-egui/tests/it/resources_updater.rs @@ -130,11 +130,21 @@ fn select_new_resource_follows_the_chosen_file_and_the_name_filter_narrows_the_l } #[test] -fn show_in_folder_shows_the_folder_of_the_resource_file() { +fn show_in_folder_shows_the_folder_of_the_resource_file_and_materials_have_no_file() { let dir = TempDir::new("resources-updater-folder"); let file = png(&dir, "bricks.png", 4); let mut h = app(); import(&mut h, &file); + + // A linked MaterialCraft material keeps its package as a resource without a file + let layer = h.state_mut().run("layer.add.fill", json!({})).unwrap()["layer"].as_u64().unwrap(); + let session = &mut h.state_mut().session; + session.doc.resources.insert("brick.mcmat".to_string(), std::sync::Arc::new(b"package".to_vec())); + let link = serde_json::from_value(json!({"name": "Brick", "package": "brick.mcmat", "graph": "Brick", "params": [], "size": 4})).unwrap(); + if let texturecraft_engine::core::LayerKind::Fill(fill) = &mut session.doc.project.layers.get_mut(&texturecraft_engine::core::LayerId(layer)).unwrap().kind + { + fill.link = Some(link); + } activate(&mut h, "Resources Updater"); activate(&mut h, "Show in folder bricks.png"); @@ -142,6 +152,9 @@ fn show_in_folder_shows_the_folder_of_the_resource_file() { let shown = h.state().file_dialogs.shown_folders().to_vec(); assert_eq!(shown.len(), 1); assert_eq!(shown[0].file_name(), dir.file_name(), "the file's own folder"); + assert!(shows(&h, "Name : brick.mcmat"), "the material is listed"); + assert!(h.query_by_label("Select new resource brick.mcmat").is_none(), "a material cannot point at an image file"); + assert!(h.query_by_label("Show in folder brick.mcmat").is_none(), "it has no file"); } #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3db7a106..4bc4d42f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -506,7 +506,7 @@ read once; its verdict is kept until its size or time changes again. | Command | Params and result | |---|---| -| `resource.status` | `{}` → `{resources: [{name, status, path?, error?}], total, outdated}`; `status` is `outdated` (the file's size or contents differ from the resource), `missing` (the file is gone or unreadable, `error` says why), `upToDate` or `noSource` (made in the app or imported without a path); outdated first, then by name. A file is read only when its size matches but its modification time does not | +| `resource.status` | `{}` → `{resources: [{name, status, path?, error?}], total, outdated}`; `status` is `outdated` (the file's size or contents differ from the resource), `missing` (the file is gone or unreadable, `error` says why), `upToDate`, `noSource` (made in the app or imported without a path) or `material` (the package of a linked MaterialCraft material: it has no file and updates with `material.link.cook`); outdated first, then by name. A file is read only when its size matches but its modification time does not | | `resource.update` | `{names?: [name]}` (default: every outdated resource) → `{updated, failed: [{name, error}]}`: reads the files again and replaces the resources' bytes and pixels under the same names, so every layer, mask and view using them recomposites; one undo step, none when nothing changed. A file that cannot be read fails alone; when none could be read the command is an error. Unknown names and resources without a file are refused | | `resource.relink` | `{name, path}` → `{name, path}`: an image resource takes the image file's pixels (within the image import limits) and follows that file from then on; one undo step | From c8fbe38ed70f223f745ec5033f6e9954fea8fd01 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 27 Nov 2026 09:19:38 -0500 Subject: [PATCH 7/7] ci: notify artcraft-services on release state changes (#881) * ci: notify artcraft-services on release state changes * ci: pass only the dispatch token to the notify-services workflow secrets: inherit hands the called workflow every repository secret, including the signing credentials. The reusable workflow only reads ARTCRAFT_SERVICES_DISPATCH_TOKEN, so map just that one. --------- Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- .github/workflows/notify-services.yml | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 .github/workflows/notify-services.yml diff --git a/.github/workflows/notify-services.yml b/.github/workflows/notify-services.yml new file mode 100644 index 00000000..3dc8eaf4 --- /dev/null +++ b/.github/workflows/notify-services.yml @@ -0,0 +1,20 @@ +name: Notify Services on Release Change + +on: + release: + types: + - published + - unpublished + - created + - edited + - deleted + - prereleased + - released + +permissions: {} + +jobs: + notify: + uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main + secrets: + ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}