diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 2c973280..8fe1fe5a 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -12,7 +12,15 @@ use crate::{EngineError, Result, Session, cmd}; pub fn specs() -> Vec { vec![ - cmd!("resource.import", "Import resources", ["File"], None, "{path} — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr)", always, import), + cmd!( + "resource.import", + "Import resources", + ["File"], + None, + "{path — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr), prefix?: put in front of the resource name (anything outside A-Z a-z 0-9 _ . - becomes _)}", + always, + import + ), cmd!("resource.list", "List resources", [], None, "{}", always, |s, _| Ok(list(s))), cmd!("resource.remove", "Remove resource", [], None, "{name}", always, remove), cmd!("file.removeUnused", "Remove unused resources...", ["File"], None, "{}", always, remove_unused), @@ -38,18 +46,33 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { impl Session { /// Add an image resource from bytes (one undo step); returns its unique, sanitized name pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { - self.edit("Import resource", |session| session.add_image_resource(file_name, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)) + self.import_resource_bytes_prefixed("", file_name, bytes) + } + + /// Like [`Self::import_resource_bytes`], with `prefix` put in front of the resource's name + pub fn import_resource_bytes_prefixed(&mut self, prefix: &str, file_name: &str, bytes: Vec) -> Result { + self.edit("Import resource", |session| session.add_image_resource_prefixed(prefix, file_name, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)) } /// Add an image within a decoded texel budget, inside the caller's edit pub(crate) fn add_image_resource(&mut self, file_name: &str, bytes: Vec, max_texels: u64) -> Result { + self.add_image_resource_prefixed("", file_name, bytes, max_texels) + } + + fn add_image_resource_prefixed(&mut self, prefix: &str, file_name: &str, bytes: Vec, max_texels: u64) -> Result { if bytes.len() > MAX_BYTES { return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20))); } let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|error| EngineError::Other(format!("{file_name}: {error}")))?; let leaf = std::path::Path::new(file_name).file_name().and_then(|name| name.to_str()).unwrap_or("image"); - let base = texturecraft_formats::sanitize_resource_name(leaf); + let mut base = texturecraft_formats::sanitize_resource_name(leaf); + if !prefix.trim().is_empty() { + // Names stay within the sanitized length; the file name keeps its room + let room = 120usize.saturating_sub(base.chars().count()); + let prefix: String = texturecraft_formats::sanitize_resource_name(prefix.trim()).chars().take(room).collect(); + base = format!("{prefix}{base}"); + } let mut name = base.clone(); let mut duplicate_index = 2; while self.doc.resources.contains_key(&name) { @@ -101,7 +124,7 @@ fn list(s: &Session) -> Value { fn import(s: &mut Session, p: &Value) -> Result { let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?; let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?; - let name = s.import_resource_bytes(path, bytes)?; + let name = s.import_resource_bytes_prefixed(strp(p, "prefix").unwrap_or(""), path, bytes)?; Ok(json!({ "name": name })) } diff --git a/crates/ui-egui/src/import_resources.rs b/crates/ui-egui/src/import_resources.rs new file mode 100644 index 00000000..c08f4973 --- /dev/null +++ b/crates/ui-egui/src/import_resources.rs @@ -0,0 +1,332 @@ +//! File > Import resources...: a window to collect files, set what each is for, and import them +//! together. Images become project resources; materials load as smart materials. + +use std::collections::BTreeSet; +use std::sync::atomic::{AtomicU64, Ordering}; + +use egui::{Key, Modifiers}; +use serde_json::json; + +use crate::TextureCraftApp; +use crate::file_dialogs::{Bound, FileDialog}; +use crate::i18n::{tr, trf}; +use crate::state::{ImportResources, ImportRow, ImportTarget, ResourceUsage}; +use crate::web_files::{IMAGE_EXTS, MATERIAL_EXTS}; +use crate::widgets::primary_button; + +/// Width of the window +const WINDOW_WIDTH_POINTS: f32 = 640.0; +/// Height of the file list +const LIST_HEIGHT_POINTS: f32 = 300.0; +/// Width of a row's prefix field and usage dropdown +const PREFIX_WIDTH_POINTS: f32 = 160.0; +const USAGE_WIDTH_POINTS: f32 = 110.0; +/// Room beside the dropdown of the target +const TARGET_WIDTH_POINTS: f32 = 190.0; + +/// Opens the window with an empty list (an open window stays as it is) +pub(crate) fn open(app: &mut TextureCraftApp) { + static NEXT_OPENING_ID: AtomicU64 = AtomicU64::new(1); + + if app.ui.windows.import_resources.is_none() { + app.ui.windows.import_resources = Some(ImportResources { + project: app.session.project_id, + opening_id: NEXT_OPENING_ID.fetch_add(1, Ordering::Relaxed), + ..ImportResources::default() + }); + } +} + +/// The keys of the open window: Escape closes it, Enter imports unless a text field or button had +/// the keyboard. An open dropdown takes both first. +pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState, nothing_focused: bool, popup_open: bool) { + if popup_open { + return; + } + + let escape = input.consume_key(Modifiers::NONE, Key::Escape); + let enter = input.consume_key(Modifiers::NONE, Key::Enter); + if escape { + app.ui.windows.import_resources = None; + } else if enter + && nothing_focused + && let Some(window) = app.ui.windows.import_resources.as_mut() + { + window.confirm = true; + } +} + +/// Whether the file is a material (loaded as a smart material, so it has no usage or prefix) +fn is_material(row: &ImportRow) -> bool { + row.path.extension().and_then(|e| e.to_str()).is_some_and(|e| MATERIAL_EXTS.contains(&e.to_ascii_lowercase().as_str())) +} + +fn file_name(row: &ImportRow) -> String { + row.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| row.path.display().to_string()) +} + +/// A click on row `id` of the `visible` rows: plain selects only it, Ctrl toggles it, Shift +/// selects from the anchor to it +fn click_row(window: &mut ImportResources, visible: &[u64], id: u64, modifiers: Modifiers) { + let ctrl = modifiers.command || modifiers.ctrl; + let from = window.anchor.and_then(|anchor| visible.iter().position(|v| *v == anchor)); + let to = visible.iter().position(|v| *v == id); + + match (modifiers.shift, from, to) { + (true, Some(from), Some(to)) => { + let range: BTreeSet = visible[from.min(to)..=from.max(to)].iter().copied().collect(); + if ctrl { + window.selected.extend(range); + } else { + window.selected = range; + } + } + _ if ctrl => { + if !window.selected.remove(&id) { + window.selected.insert(id); + } + window.anchor = Some(id); + } + _ => { + window.selected = BTreeSet::from([id]); + window.anchor = Some(id); + } + } +} + +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(mut window) = app.ui.windows.import_resources.clone() else { return }; + + // Files chosen for another project cannot be imported here + if window.project != app.session.project_id { + app.ui.windows.import_resources = None; + return; + } + + // A filter whose rows are gone shows everything again + if window.filter.is_some_and(|usage| !window.rows.iter().any(|row| row.usage == usage)) { + window.filter = None; + } + + let mut open = true; + let (mut import, mut cancel, mut add) = (std::mem::take(&mut window.confirm), false, false); + let mut remove = false; + + crate::windows::dialog("import_resources", tr("Import resources"), &mut open).default_width(WINDOW_WIDTH_POINTS).show(ctx, |ui| { + ui.set_min_width(WINDOW_WIDTH_POINTS); + ui.horizontal(|ui| { + ui.label(tr("Import your resources and set their usage")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_enabled_ui(!window.selected.is_empty(), |ui| { + remove = ui.button(tr("Remove selected resources")).clicked(); + }); + add = ui.button(tr("Add resources")).clicked(); + }); + }); + ui.add_space(4.0); + + let all_label = trf("All imported resources ({count})", &[("count", &window.rows.len().to_string())]); + let filter_text = match window.filter { + None => all_label.clone(), + Some(usage) => { + trf("{usage} ({count})", &[("usage", &usage.name()), ("count", &window.rows.iter().filter(|r| r.usage == usage).count().to_string())]) + } + }; + egui::ComboBox::from_id_salt("import_filter").width(ui.available_width()).selected_text(filter_text).show_ui(ui, |ui| { + if ui.selectable_label(window.filter.is_none(), &all_label).clicked() { + window.filter = None; + } + + // Only usages some row has, so the list is never empty by filter + for usage in ResourceUsage::ALL { + let count = window.rows.iter().filter(|row| row.usage == usage).count(); + if count > 0 && ui.selectable_label(window.filter == Some(usage), format!("{} ({count})", usage.name())).clicked() { + window.filter = Some(usage); + } + } + }); + ui.add_space(4.0); + + let visible: Vec = window.rows.iter().filter(|row| window.filter.is_none_or(|usage| row.usage == usage)).map(|row| row.id).collect(); + let modifiers = ui.input(|i| i.modifiers); + let mut clicked = None; + + egui::ScrollArea::vertical().min_scrolled_height(LIST_HEIGHT_POINTS).max_height(LIST_HEIGHT_POINTS).auto_shrink([false, false]).show(ui, |ui| { + for row in window.rows.iter_mut().filter(|row| visible.contains(&row.id)) { + let material = is_material(row); + let selected = window.selected.contains(&row.id); + ui.horizontal(|ui| { + let name_width = (ui.available_width() - PREFIX_WIDTH_POINTS - USAGE_WIDTH_POINTS - 2.0 * ui.spacing().item_spacing.x).max(40.0); + let name = ui.add_sized([name_width, ui.spacing().interact_size.y], egui::Button::selectable(selected, file_name(row)).truncate()); + if name.on_hover_text(row.path.display().to_string()).clicked() { + clicked = Some(row.id); + } + + let prefix = ui.add_enabled( + !material, + egui::TextEdit::singleline(&mut row.prefix).hint_text(tr("Optional prefix/path...")).desired_width(PREFIX_WIDTH_POINTS), + ); + if material { + prefix.on_disabled_hover_text(tr("Materials keep their own name")); + } else { + prefix.on_hover_text(tr("Put in front of the resource's name. Characters other than letters, digits and _ . - become _")); + } + + ui.add_enabled_ui(!material, |ui| { + egui::ComboBox::from_id_salt(("import_usage", row.id)).width(USAGE_WIDTH_POINTS).selected_text(row.usage.name()).show_ui(ui, |ui| { + for usage in ResourceUsage::ALL { + let item = ui.add_enabled(usage.available(), egui::Button::selectable(row.usage == usage, usage.name())); + if usage.available() { + if item.clicked() { + row.usage = usage; + ui.close(); + } + } else { + item.on_disabled_hover_text(tr("Not available yet")); + } + } + }); + }) + .response + .on_disabled_hover_text(tr("Materials need no usage")); + }); + } + }); + if let Some(id) = clicked { + click_row(&mut window, &visible, id, modifiers); + } + + ui.add_space(8.0); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + egui::ComboBox::from_id_salt("import_target") + .width(TARGET_WIDTH_POINTS) + .selected_text(match window.target { + ImportTarget::Session => tr("current session"), + ImportTarget::Library => tr("library 'Your assets'"), + }) + .show_ui(ui, |ui| { + if ui.selectable_label(window.target == ImportTarget::Session, tr("current session")).clicked() { + window.target = ImportTarget::Session; + } + // Your assets hold smart materials and brush presets, not images + ui.add_enabled(false, egui::Button::selectable(false, tr("library 'Your assets'"))).on_disabled_hover_text(tr("Not available yet")); + }); + ui.label(tr("Import your resources to:")); + }); + }); + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + cancel = ui.button(tr("Cancel")).clicked(); + import |= ui.add_enabled(!window.rows.is_empty(), primary_button(ui, tr("Import"))).clicked(); + }); + }); + }); + + if remove { + window.rows.retain(|row| !window.selected.contains(&row.id)); + window.selected.clear(); + window.anchor = None; + } + + if add { + let mut extensions: Vec<&str> = IMAGE_EXTS.to_vec(); + extensions.extend_from_slice(MATERIAL_EXTS); + let opening_id = window.opening_id; + app.ask_file(FileDialog::open_many().filter(tr("Resources"), &extensions), Bound::Project, move |app, paths| { + let Some(stored) = app.ui.windows.import_resources.as_mut().filter(|stored| stored.opening_id == opening_id) else { return }; + for path in paths { + if stored.rows.iter().any(|row| row.path == path) { + continue; + } + stored.rows.push(ImportRow { id: stored.next_row, path, prefix: String::new(), usage: ResourceUsage::Undefined }); + stored.next_row += 1; + } + }); + } + + if import && !window.rows.is_empty() { + import_rows(app, &window); + } + + if (import && !window.rows.is_empty()) || cancel || !open { + app.ui.windows.import_resources = None; + } else { + // A file answer only arrives between frames, so nothing was added meanwhile + app.ui.windows.import_resources = Some(window); + } +} + +/// Imports every row in order, each by its usage +fn import_rows(app: &mut TextureCraftApp, window: &ImportResources) { + for row in &window.rows { + let path = row.path.display().to_string(); + if is_material(row) { + app.run("material.load", json!({ "path": path })); + continue; + } + + let mut params = json!({ "path": path }); + if !row.prefix.trim().is_empty() { + params["prefix"] = json!(row.prefix); + } + let Some(result) = app.run("resource.import", params) else { continue }; + let name = result.get("name").and_then(|n| n.as_str()).unwrap_or_default().to_string(); + app.toast(trf("Imported {name}", &[("name", &name)]), false); + + match row.usage { + ResourceUsage::Environment => crate::web_files::use_environment(app, &name), + ResourceUsage::Alpha => { + if app.run("tool.brush", json!({ "alpha": { "image": name } })).is_some() { + app.toast(trf("Brush alpha: {name}", &[("name", &name)]), false); + } + } + ResourceUsage::Undefined | ResourceUsage::Texture | ResourceUsage::ColorLut | ResourceUsage::PostFx => {} + } + } + app.ui.dock.focus(crate::docking::Panel::Assets); +} + +#[cfg(test)] +mod tests { + use super::*; + + const CTRL: Modifiers = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + const SHIFT: Modifiers = Modifiers { shift: true, ..Modifiers::NONE }; + + fn selected(window: &ImportResources) -> Vec { + window.selected.iter().copied().collect() + } + + #[test] + fn a_plain_click_selects_one_row() { + let mut window = ImportResources::default(); + click_row(&mut window, &[1, 2, 3], 1, Modifiers::NONE); + click_row(&mut window, &[1, 2, 3], 3, Modifiers::NONE); + + assert_eq!(selected(&window), [3]); + } + + #[test] + fn ctrl_toggles_rows() { + let mut window = ImportResources::default(); + click_row(&mut window, &[1, 2, 3], 1, CTRL); + click_row(&mut window, &[1, 2, 3], 3, CTRL); + assert_eq!(selected(&window), [1, 3]); + + click_row(&mut window, &[1, 2, 3], 1, CTRL); + assert_eq!(selected(&window), [3]); + } + + #[test] + fn shift_selects_from_the_anchor_in_either_direction() { + let mut window = ImportResources::default(); + click_row(&mut window, &[1, 2, 3, 4], 2, Modifiers::NONE); + click_row(&mut window, &[1, 2, 3, 4], 4, SHIFT); + assert_eq!(selected(&window), [2, 3, 4]); + + click_row(&mut window, &[1, 2, 3, 4], 1, SHIFT); + assert_eq!(selected(&window), [1, 2]); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9f0da289..24f69692 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -25,6 +25,8 @@ pub mod gpu; mod grid_tile; pub mod i18n; pub mod id_color_pick; +#[cfg(not(target_arch = "wasm32"))] +mod import_resources; pub mod keymap; pub mod layer_panel; mod levels_editor; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 9c429075..eeed4f4b 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -385,6 +385,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { // Its keys are Escape (close) and Enter (OK); a stroke in progress isn't touched #[cfg(not(target_arch = "wasm32"))] crate::project_config::keys_in(app, input, nothing_focused, popup_open); + } 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 !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; } else if !popup_open && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 086d4c9d..2b31705b 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -9,7 +9,9 @@ use crate::saved_search::SavedSearch; use crate::shelf_panes::ShelfPanes; use crate::shelf_view::ShelfView; +mod import_resources; mod project_config; +pub use import_resources::{ImportResources, ImportRow, ImportTarget, ResourceUsage}; pub use project_config::ProjectConfig; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] @@ -85,6 +87,9 @@ pub struct Windows { /// Edit > Project Configuration: what is chosen so far, applied by OK. #[serde(skip)] pub project_config: Option, + /// File > Import resources: the files added so far, imported by Import. + #[serde(skip)] + pub import_resources: 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/import_resources.rs b/crates/ui-egui/src/state/import_resources.rs new file mode 100644 index 00000000..a3654d0e --- /dev/null +++ b/crates/ui-egui/src/state/import_resources.rs @@ -0,0 +1,81 @@ +use std::collections::BTreeSet; +use std::path::PathBuf; + +/// What an imported resource is for +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum ResourceUsage { + /// Imported as an image resource, nothing more + #[default] + Undefined, + /// An image resource that also becomes the brush alpha + Alpha, + /// Color lookup tables (not available yet) + ColorLut, + /// An image resource that also lights the scene + Environment, + /// Post effect resources (not available yet) + PostFx, + /// An image resource for fills and stencils + Texture, +} + +impl ResourceUsage { + /// The usages in the dropdown's order + pub const ALL: [ResourceUsage; 6] = [Self::Undefined, Self::Alpha, Self::ColorLut, Self::Environment, Self::PostFx, Self::Texture]; + + /// The name shown in the dropdowns (the same in every language, as in the reference) + pub fn name(self) -> &'static str { + match self { + Self::Undefined => "undefined", + Self::Alpha => "alpha", + Self::ColorLut => "colorlut", + Self::Environment => "environment", + Self::PostFx => "postfx", + Self::Texture => "texture", + } + } + + /// Whether the app can do something with resources of this usage + pub fn available(self) -> bool { + !matches!(self, Self::ColorLut | Self::PostFx) + } +} + +/// Where the resources go +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum ImportTarget { + /// The open project's resources + #[default] + Session, + /// The user's asset library (not available for images yet) + Library, +} + +/// One file waiting in the window +#[derive(Clone, Debug, PartialEq)] +pub struct ImportRow { + pub id: u64, + pub path: PathBuf, + pub prefix: String, + pub usage: ResourceUsage, +} + +/// File > Import resources: the files added so far, imported by the Import button +#[derive(Clone, Debug, PartialEq, Default)] +pub struct ImportResources { + pub rows: Vec, + /// Ids of the selected rows + pub selected: BTreeSet, + /// The row a Shift click extends from + pub anchor: Option, + /// The usage the list is narrowed to (None: all) + pub filter: Option, + pub target: ImportTarget, + /// Whether Enter requested the import in the next frame + pub confirm: bool, + /// The project that was open when this window opened + pub project: u64, + /// This opening's identity, used to reject late file picker answers + pub(crate) opening_id: u64, + pub(crate) next_row: u64, +} diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index bf6eb356..76e12e3a 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -114,7 +114,7 @@ pub fn import_environment(app: &mut TextureCraftApp, _ctx: &egui::Context) { } /// Make image resource `name` the environment. -fn use_environment(app: &mut TextureCraftApp, name: &str) { +pub(crate) fn use_environment(app: &mut TextureCraftApp, name: &str) { let env = format!("{}{name}", texturecraft_engine::core::project::ENV_RESOURCE_PREFIX); if app.run("display.set", serde_json::json!({ "environment": env })).is_some() { app.toast(trf("Environment: {name}", &[("name", &name)]), false); diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 306c0266..9b26e3be 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -23,7 +23,10 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { about(app, ctx); settings(app, ctx); #[cfg(not(target_arch = "wasm32"))] - crate::project_config::show(app, ctx); + { + crate::project_config::show(app, ctx); + crate::import_resources::show(app, ctx); + } crate::keymap::window(app, ctx); crate::windows::export(app, ctx); #[cfg(target_arch = "wasm32")] @@ -786,19 +789,7 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> true } "file.importResources" | "resource.import" => { - app.ask_file(FileDialog::open_many().filter(tr("Images"), crate::web_files::IMAGE_EXTS), Bound::Project, |app, paths| { - if paths.is_empty() { - return; - } - - for p in paths { - if let Some(r) = app.run("resource.import", json!({"path": p.display().to_string()})) { - let name = r.get("name").and_then(|n| n.as_str()).unwrap_or_default().to_string(); - app.toast(trf("Imported {name}", &[("name", &name)]), false); - } - } - app.ui.dock.focus(crate::docking::Panel::Assets); - }); + crate::import_resources::open(app); true } "file.importMaterialX" => { diff --git a/crates/ui-egui/tests/it/file_dialogs.rs b/crates/ui-egui/tests/it/file_dialogs.rs index 5c13c6d8..bf21686e 100644 --- a/crates/ui-egui/tests/it/file_dialogs.rs +++ b/crates/ui-egui/tests/it/file_dialogs.rs @@ -146,7 +146,7 @@ fn answered_after_the_project_changed(ask: impl FnOnce(&mut Harness<'_, TextureC #[test] fn every_project_dialog_does_nothing_for_a_replaced_project() { let file = temp_file("replaced-actions", "chosen.obj"); - for id in ["material.load", "resource.import", "file.importMaterialX", "file.exportMesh", "file.reimportMesh"] { + for id in ["material.load", "file.importMaterialX", "file.exportMesh", "file.reimportMesh"] { let h = answered_after_the_project_changed(|h| invoke(h, id), &file); assert!(h.state().toasts.iter().any(|t| t.error && t.text.starts_with(PROJECT_CHANGED)), "{id}"); assert!(!file.exists(), "{id} wrote nothing"); diff --git a/crates/ui-egui/tests/it/import_resources.rs b/crates/ui-egui/tests/it/import_resources.rs new file mode 100644 index 00000000..b5b72e75 --- /dev/null +++ b/crates/ui-egui/tests/it/import_resources.rs @@ -0,0 +1,229 @@ +//! File > Import resources...: the window that collects files and imports them together. File +//! pickers are answered by the override, never shown. + +use std::path::{Path, PathBuf}; + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::Session; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::file_dialogs::{Answer, Request}; + +/// A test folder removed when its owner drops +struct TempDir(PathBuf); + +impl TempDir { + fn new(test: &str) -> Self { + let path = std::env::temp_dir().join(format!("texturecraft-{test}-{}", std::process::id())); + std::fs::create_dir_all(&path).unwrap(); + + Self(path) + } + + fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).ok(); + } +} + +const TITLE: &str = "Import resources"; +/// The prefix field's tooltip, which is its accessible label. +const PREFIX_HINT: &str = "Put in front of the resource's name. Characters other than letters, digits and _ . - become _"; + +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 +} + +fn png(dir: &Path, name: &str) -> PathBuf { + let file = dir.join(name); + image::RgbaImage::from_pixel(4, 4, image::Rgba([10, 200, 30, 255])).save(&file).unwrap(); + + file +} + +fn invoke(h: &mut Harness<'_, TextureCraftApp>) { + let ctx = h.ctx.clone(); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "resource.import"); + h.run_steps(3); +} + +fn is_open(h: &Harness<'_, TextureCraftApp>) -> bool { + h.query_by_label(TITLE).is_some() +} + +fn click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { + h.get_by_role_and_label(Role::Button, label).click(); + h.run_steps(3); +} + +/// Add resources, answered with `files`. +fn add(h: &mut Harness<'_, TextureCraftApp>, files: &[PathBuf]) { + let files = files.to_vec(); + h.state_mut().file_dialogs.set_override(Some(Box::new(move |_: &Request| Answer::Paths(files.clone())))); + click(h, "Add resources"); +} + +/// The dropdowns showing `value` (they have no label, only a value). +fn combos<'h>(h: &'h Harness<'_, TextureCraftApp>, value: &'h str) -> impl Iterator> { + h.get_all_by_role(Role::ComboBox).filter(move |node| node.value().as_deref() == Some(value)) +} + +fn resources(h: &Harness<'_, TextureCraftApp>) -> Vec { + h.state().session.doc.resources.keys().cloned().collect() +} + +/// Pick `usage` in the dropdown of the `n`th row (the dropdowns show "undefined" until changed). +fn choose_usage(h: &mut Harness<'_, TextureCraftApp>, n: usize, usage: &str) { + let combo = combos(h, "undefined").nth(n).expect("a usage dropdown"); + combo.click(); + h.run_steps(3); + h.get_by_label(usage).click(); + h.run_steps(3); +} + +#[test] +fn the_menu_opens_the_window_without_importing_or_asking() { + let mut h = app(); + invoke(&mut h); + + assert!(is_open(&h)); + assert!(resources(&h).is_empty()); + assert!(h.query_by_label("Import your resources and set their usage").is_some()); + assert!(combos(&h, "All imported resources (0)").next().is_some()); + assert!(h.get_by_label("Remove selected resources").accesskit_node().is_disabled(), "nothing is selected"); +} + +#[test] +fn added_files_are_listed_and_import_keeps_their_names() { + let dir = TempDir::new("import-resources-add"); + let (a, b) = (png(dir.path(), "bluenoise.png"), png(dir.path(), "scratch.png")); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[a.clone(), b]); + + assert!(combos(&h, "All imported resources (2)").next().is_some()); + assert!(h.query_by_label("bluenoise.png").is_some() && h.query_by_label("scratch.png").is_some()); + assert!(resources(&h).is_empty(), "adding only lists"); + + // The same file twice is one row + add(&mut h, &[a]); + assert!(combos(&h, "All imported resources (2)").next().is_some()); + + click(&mut h, "Import"); + assert!(!is_open(&h)); + assert_eq!(resources(&h), ["bluenoise.png", "scratch.png"]); +} + +#[test] +fn remove_selected_drops_only_the_selected_rows() { + let dir = TempDir::new("import-resources-remove"); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[png(dir.path(), "one.png"), png(dir.path(), "two.png")]); + + h.get_by_label("one.png").click(); + h.run_steps(3); + click(&mut h, "Remove selected resources"); + + assert!(h.query_by_label("one.png").is_none()); + assert!(h.query_by_label("two.png").is_some()); + assert!(combos(&h, "All imported resources (1)").next().is_some()); + click(&mut h, "Import"); + assert_eq!(resources(&h), ["two.png"]); +} + +#[test] +fn the_usage_defaults_to_undefined_and_the_choice_reaches_the_import() { + let dir = TempDir::new("import-resources-usage"); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[png(dir.path(), "plain.png"), png(dir.path(), "brush.png"), png(dir.path(), "sky.png")]); + assert_eq!(combos(&h, "undefined").count(), 3); + + choose_usage(&mut h, 1, "alpha"); + choose_usage(&mut h, 1, "environment"); + click(&mut h, "Import"); + + assert_eq!(resources(&h), ["brush.png", "plain.png", "sky.png"]); + let project = &h.state().session.doc.project; + assert_eq!(project.display.environment_resource(), Some("sky.png"), "the environment usage lights the scene"); + assert_eq!(h.state().session.tool.brush.alpha_image.as_deref(), Some("brush.png"), "the alpha usage sets the brush alpha"); +} + +#[test] +fn a_prefix_goes_in_front_of_the_resource_name() { + let dir = TempDir::new("import-resources-prefix"); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[png(dir.path(), "dust.png")]); + + h.get_by_role_and_label(Role::TextInput, PREFIX_HINT).click(); + h.run_steps(2); + h.get_by_role_and_label(Role::TextInput, PREFIX_HINT).type_text("wear/"); + h.run_steps(3); + click(&mut h, "Import"); + + assert_eq!(resources(&h), ["wear_dust.png"]); +} + +#[test] +fn unsupported_usages_and_the_user_library_are_listed_but_disabled() { + let dir = TempDir::new("import-resources-disabled"); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[png(dir.path(), "x.png")]); + + combos(&h, "undefined").next().expect("the dropdown").click(); + h.run_steps(3); + for usage in ["colorlut", "postfx"] { + assert!(h.get_by_label(usage).accesskit_node().is_disabled(), "{usage}"); + } + assert!(!h.get_by_label("texture").accesskit_node().is_disabled()); + h.get_by_label("texture").click(); + h.run_steps(3); + + combos(&h, "current session").next().expect("the dropdown").click(); + h.run_steps(3); + assert!(h.get_by_label("library 'Your assets'").accesskit_node().is_disabled()); +} + +#[test] +fn cancel_imports_nothing() { + let dir = TempDir::new("import-resources-cancel"); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[png(dir.path(), "never.png")]); + click(&mut h, "Cancel"); + + assert!(!is_open(&h)); + assert!(resources(&h).is_empty()); + + // Reopening starts empty + invoke(&mut h); + assert!(combos(&h, "All imported resources (0)").next().is_some()); +} + +#[test] +fn the_engine_command_still_imports_a_path_with_an_optional_prefix() { + let dir = TempDir::new("import-resources-command"); + let file = png(dir.path(), "tile.png"); + let mut session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + + let plain = texturecraft_engine::execute(&mut session, "resource.import", &serde_json::json!({"path": file.display().to_string()})).unwrap(); + let prefixed = + texturecraft_engine::execute(&mut session, "resource.import", &serde_json::json!({"path": file.display().to_string(), "prefix": "a/b/"})).unwrap(); + + assert_eq!(plain["name"], "tile.png"); + assert_eq!(prefixed["name"], "a_b_tile.png"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index cdf59747..56cee771 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -17,6 +17,7 @@ mod fill_projection_section; mod filter_picker; mod generator_panel; mod history_panel; +mod import_resources; mod layer_clipboard; mod layer_rename; mod layers_panel; diff --git a/docs/features.md b/docs/features.md index 2d1f8098..83f95eac 100644 --- a/docs/features.md +++ b/docs/features.md @@ -67,6 +67,11 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA brick and stone, sun-faded paint…) and **24 smart masks**, all procedural, so they work at any resolution. Drag them from the tabbed, searchable shelf onto the layer stack or straight onto the model. +- **Import resources:** *File › Import resources...* opens a window: *Add resources* (images and + materials), an optional name prefix and a usage per file (texture, environment and alpha also + light the scene or set the brush alpha), a filter by usage, *Remove selected resources*, then + *Import*. Not yet available: the colorlut and postfx usages and the "Your assets" target (shown + disabled). The browser imports images straight from its file picker. - **Your own library:** right-click a layer or folder, choose *Create smart material*, and it appears under *My smart materials*, pixels and images included. - **MaterialCraft materials:** *File › Import material*, a drop on the window, or MaterialCraft's diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e6762be8..776e0b59 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -59,6 +59,15 @@ The relevant implementations are [layer rows, menus and fill/brush editors](../c | UI-12 | Generator depth and property coverage | **UI + source.** The picker contains seven kinds. Switching to Position, changing Global balance and duplicating the effect worked. Shared global adjustments, resolution and input slots already exist; that does not establish the richer generator/control inventory in [#374](https://github.com/storytold/texturecraft/issues/374) | Audit each generator's inputs, micro-detail behavior and controls against the reference; do not count seven shared implementations as equivalent to its whole catalog | | UI-13 | Narrow workspace readability | **UI.** At 1280 × 800 the app rendered, both views stayed visible and the toolbar exposed scroll arrows. Layer names/types became heavily truncated, the layer toolbar wrapped, and Properties needed scrolling. This was not an input-failure or docking-persistence test | Repeat the editing tasks at smaller sizes, widen/rearrange panels, check full-name tooltips and keyboard access, and retain the layout after restart | +File > Import resources (#638) is a window like the reference's: add files, an optional +name prefix and a usage per file, a filter by usage, Remove selected resources, and Import or +Cancel. Usages `texture` and `undefined` import an image resource, `environment` also lights the +scene with it, `alpha` also makes it the brush alpha. `colorlut` and `postfx` have no feature +behind them and are listed disabled, as is the target "library 'Your assets'" (that library holds +smart materials and brush presets, not images). The prefix goes in front of the resource's name, +because resources have no folders. Materials (`.tcmat`, `.mcmat`, `.mcraft`) can be added too and +load as smart materials. The browser build still imports images straight from its file picker. + Broader properties/filter work remains tracked in [#433](https://github.com/storytold/texturecraft/issues/433). Its individual rows need checking against current code; an open issue is not proof that every control it lists is still missing.