fix(engine): resolve resource stem and list available names in layer.add.image (#337) (#391)

* fix(engine): resolve resource stem and list available names in layer.add.image (#337)

Accept an unambiguous file stem in layer.add.image alongside the full resource name with extension. When the requested resource is not found, list the available resources or guide the user to resource.import.

* fix(engine): filter image lookup stems and hints to decoded images (#337)
This commit is contained in:
test-bit-sys authored and GitHub committed 2026-11-12 17:56:34 +01:00
1 parent e03e6fae6a
commit a969983a52
2 files changed
+90 -5

No files matched your search

+29 -5
View File
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add fill layer from image",
[],
None,
"{name, channel?: baseColor, projection?: uv|triplanar|planar, scale?}",
"{name (exact resource name with extension or unique stem), channel?: baseColor, projection?: uv|triplanar|planar, scale?}",
always,
add_image_fill
),
@@ -179,11 +179,35 @@ fn remove_unused(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "removed": unused }))
}
fn add_image_fill(s: &mut Session, p: &Value) -> Result<Value> {
let name = strp(p, "name").ok_or_else(|| bad("layer.add.image", "`name` is required"))?.to_string();
if !s.doc.resources.contains_key(&name) {
return Err(bad("layer.add.image", format!("no resource `{name}`")));
#[cfg(not(target_arch = "wasm32"))]
const IMPORT_HINT: &str = "resource.import";
#[cfg(target_arch = "wasm32")]
const IMPORT_HINT: &str = "File > Import resources";
/// Resolve an image resource by exact name or unique file stem.
fn resolve_resource_name(s: &Session, name: &str) -> Result<String> {
if s.images.contains_key(name) {
return Ok(name.to_string());
}
let matches: Vec<&String> = s.images.keys().filter(|k| std::path::Path::new(k).file_stem().and_then(|stem| stem.to_str()) == Some(name)).collect();
match matches.as_slice() {
[single] => Ok((*single).clone()),
[] => {
let available: Vec<&str> = s.images.keys().map(String::as_str).collect();
let hint =
if available.is_empty() { format!(" (no resources imported: use {IMPORT_HINT})") } else { format!(" (available: {})", available.join(", ")) };
Err(bad("layer.add.image", format!("no resource `{name}`{hint}")))
}
multiple => {
let matches_str = multiple.iter().map(|m| format!("`{m}`")).collect::<Vec<_>>().join(", ");
Err(bad("layer.add.image", format!("ambiguous resource `{name}` matches {matches_str}: give the full name with extension")))
}
}
}
fn add_image_fill(s: &mut Session, p: &Value) -> Result<Value> {
let raw_name = strp(p, "name").ok_or_else(|| bad("layer.add.image", "`name` is required"))?;
let name = resolve_resource_name(s, raw_name)?;
let ch = channel_param("layer.add.image", p, "channel")?.unwrap_or(Channel::BaseColor);
let projection = crate::layer_cmds::projection_from(p, "layer.add.image", None)?;
let ts = s.ts();
+61
View File
@@ -308,6 +308,67 @@ fn image_resources_fill_layers_and_round_trip() {
assert!(s.import_resource_bytes("bad.png", vec![1, 2, 3]).is_err());
}
#[test]
fn image_resource_lookup_accepts_extension_and_stem() {
let mut s = session();
// No resources imported yet
let err = execute(&mut s, "layer.add.image", &json!({"name": "missing"})).unwrap_err();
assert!(err.to_string().contains("no resource `missing` (no resources imported: use resource.import)"));
let mut png = Vec::new();
let img = image::RgbaImage::from_fn(4, 4, |_, _| image::Rgba([0, 255, 0, 255]));
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
s.import_resource_bytes("tile.png", png.clone()).unwrap();
// Lookup by stem
let r = execute(&mut s, "layer.add.image", &json!({"name": "tile"})).unwrap();
assert!(r["layer"].as_u64().is_some());
// Lookup by full name
let r2 = execute(&mut s, "layer.add.image", &json!({"name": "tile.png"})).unwrap();
assert!(r2["layer"].as_u64().is_some());
// Missing resource lists available
let err = execute(&mut s, "layer.add.image", &json!({"name": "wood"})).unwrap_err();
assert!(err.to_string().contains("no resource `wood` (available: tile.png)"));
// Ambiguous stem resolution
s.import_resource_bytes("tile.jpg", png).unwrap();
let err = execute(&mut s, "layer.add.image", &json!({"name": "tile"})).unwrap_err();
assert!(err.to_string().contains("ambiguous resource `tile`"));
}
#[test]
fn image_resource_lookup_ignores_linked_packages() {
use std::sync::Arc;
use texturecraft_engine::core::{LayerId, LayerKind, Source};
let mut s = session();
s.doc.resources.insert("wood.mcraft".into(), Arc::new(b"package bytes".to_vec()));
s.sync_images();
assert!(!s.images.contains_key("wood.mcraft"));
let err = execute(&mut s, "layer.add.image", &json!({"name": "wood"})).unwrap_err();
assert!(err.to_string().contains("no resources imported"), "{err}");
let err = execute(&mut s, "layer.add.image", &json!({"name": "wood.mcraft"})).unwrap_err();
assert!(err.to_string().contains("no resource `wood.mcraft` (no resources imported"), "{err}");
let mut png = Vec::new();
let img = image::RgbaImage::from_fn(4, 4, |_, _| image::Rgba([0, 255, 0, 255]));
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
s.import_resource_bytes("wood.png", png).unwrap();
let err = execute(&mut s, "layer.add.image", &json!({"name": "missing"})).unwrap_err();
assert!(err.to_string().contains("no resource `missing` (available: wood.png)"), "{err}");
let res = execute(&mut s, "layer.add.image", &json!({"name": "wood"})).unwrap();
let id = LayerId(res["layer"].as_u64().unwrap());
let LayerKind::Fill(fill) = &s.doc.project.layer(id).unwrap().kind else { panic!("expected fill layer") };
assert_eq!(fill.sources.get(&Channel::BaseColor), Some(&Source::image("wood.png")));
}
#[test]
fn brush_presets_apply_save_and_load() {
let mut s = session();