From 26c28febfef7bb25361f0fedfb8e129009146f56 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:45:34 +0000 Subject: [PATCH 01/16] Assets: right-click menu with the asset's info and Export resource Every tile's menu starts with what the asset is: Name, Usages, Path and, where it has one, Category; a long path is cut in the middle. Export resource writes an image resource's file as it was imported (new resource.export command); built-ins have no file and show it greyed. Add as decal and Remove resource stay for project images. Close closes. Part of #411 --- crates/engine/src/resource_cmds.rs | 32 +++++ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/shelf.rs | 15 +-- crates/ui-egui/src/shelf_entry.rs | 17 ++- crates/ui-egui/src/shelf_menu.rs | 173 ++++++++++++++++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/shelf_menu.rs | 67 ++++++++++ 7 files changed, 292 insertions(+), 14 deletions(-) create mode 100644 crates/ui-egui/src/shelf_menu.rs create mode 100644 crates/ui-egui/tests/it/shelf_menu.rs diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 39d9fb6c..d81263d5 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -24,6 +24,7 @@ pub fn specs() -> Vec { ), cmd!("resource.list", "List resources", [], None, "{}", always, |s, _| Ok(list(s))), cmd!("resource.remove", "Remove resource", [], None, "{name}", always, remove), + cmd!("resource.export", "Export resource", [], None, "{name, path} — the resource's file as it was imported", always, export), cmd!("file.removeUnused", "Remove unused resources...", ["File"], None, "{}", always, remove_unused), cmd!( "layer.add.image", @@ -261,6 +262,24 @@ fn remove(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// Writes resource `name`'s bytes, as imported, to `path` +#[cfg(not(target_arch = "wasm32"))] +fn export(s: &mut Session, p: &Value) -> Result { + let command = "resource.export"; + let name = strp(p, "name").ok_or_else(|| bad(command, "`name` is required"))?; + let path = strp(p, "path").ok_or_else(|| bad(command, "`path` is required"))?; + let bytes = s.doc.resources.get(name).ok_or_else(|| bad(command, format!("no resource `{name}`")))?; + + std::fs::write(path, bytes.as_slice()).map_err(|error| bad(command, format!("cannot write {path}: {error}")))?; + + Ok(json!({ "path": path })) +} + +#[cfg(target_arch = "wasm32")] +fn export(_: &mut Session, _: &Value) -> Result { + Err(bad("resource.export", "file paths are not available in the browser")) +} + /// Drop resources no layer, mask effect, the brush alpha, the projection stencil, the mask brush or the environment uses (one undo step) fn remove_unused(s: &mut Session, _: &Value) -> Result { let mut used = Vec::new(); @@ -331,6 +350,19 @@ fn add_image_fill(s: &mut Session, p: &Value) -> Result { mod tests { use super::*; + #[test] + fn export_writes_the_imported_bytes() { + let mut session = crate::sample_session(128, 32).unwrap(); + let bytes = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + let name = session.import_resource_bytes("icon.png", bytes.clone()).unwrap(); + let path = std::env::temp_dir().join(format!("texturecraft-export-resource-{}.png", std::process::id())); + + crate::commands::execute(&mut session, "resource.export", &json!({"name": name, "path": path.to_str().unwrap()})).unwrap(); + + assert_eq!(std::fs::read(&path).unwrap(), bytes, "the file is the resource as imported"); + std::fs::remove_file(path).unwrap(); + } + #[test] fn file_reads_obey_the_remaining_byte_budget() { let path = std::env::temp_dir().join(format!("texturecraft-read-image-{}.png", std::process::id())); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9bc2866a..ab8d1b99 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -139,6 +139,7 @@ pub mod shader_settings; pub mod shelf; mod shelf_entry; mod shelf_folders; +mod shelf_menu; pub mod shelf_panes; pub mod shelf_preview; mod shelf_tabs; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 3416a106..9099a2f9 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -514,7 +514,7 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str, masks: bool) { #[cfg(target_arch = "wasm32")] fn library(_: &mut TextureCraftApp, _: &mut Ui, _: &str, _: bool) {} -/// The tile of `entry`, outlined when `selected`: a click applies it, an image resource has a context menu +/// The tile of `entry`, outlined when `selected`: a click applies it, a right-click opens its menu fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry, view: ShelfView, selected: bool) { // An image removed this frame has nothing to show if let ShelfEntry::Image(name) = entry @@ -557,18 +557,7 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry entry.activate(app); } - if let ShelfEntry::Image(name) = entry { - response.context_menu(|ui| { - if ui.button(tr("Add as decal (view center)")).clicked() { - app.run("layer.add.decal", json!({"image": name})); - ui.close(); - } - if ui.button(tr("Remove resource")).clicked() { - app.run("resource.remove", json!({"name": name})); - ui.close(); - } - }); - } + crate::shelf_menu::show(app, &response, entry); } /// Asset tile with optional dragging and a larger hover preview, at the medium size diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index 66774efc..32669e7f 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -13,7 +13,7 @@ use texturecraft_engine::paint::presets::{BrushPreset, PRESETS}; use texturecraft_engine::smart_masks::{SMART_MASKS, SmartMask}; use crate::TextureCraftApp; -use crate::i18n::tr; +use crate::i18n::{n_, tr}; use crate::shelf::{Asset, Tab, apply}; use crate::shelf_preview::ShelfPreview; @@ -124,6 +124,21 @@ impl ShelfEntry { path.len() <= own.len() && path.iter().zip(own).all(|(wanted, have)| wanted == have) } + /// What the asset is used as, lowercase (English, shown through `tr`): the menu's Usages row + pub(crate) fn usage(&self) -> &'static str { + match self { + ShelfEntry::Material(material) if material.smart => n_("smart material"), + ShelfEntry::Material(_) => n_("material"), + ShelfEntry::SmartMask(_) => n_("smart mask"), + ShelfEntry::Filter(_) => n_("filter"), + ShelfEntry::Brush(_) | ShelfEntry::SavedBrush { .. } => n_("brush"), + ShelfEntry::Alpha(_) => n_("alpha"), + ShelfEntry::Procedural(_) => n_("procedural"), + ShelfEntry::Environment(_) => n_("environment"), + ShelfEntry::Image(_) => n_("texture"), + } + } + /// The name under the tile, translated where the asset's name is pub(crate) fn label(&self) -> &str { match self { diff --git a/crates/ui-egui/src/shelf_menu.rs b/crates/ui-egui/src/shelf_menu.rs new file mode 100644 index 00000000..22d2af95 --- /dev/null +++ b/crates/ui-egui/src/shelf_menu.rs @@ -0,0 +1,173 @@ +//! An asset tile's right-click menu: what the asset is (name, usages, path, category), then what can be done with it + +use egui::{Align2, Color32, CornerRadius, FontId, Response, Sense, Ui, pos2, vec2}; +use serde_json::json; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::shelf_entry::{LIBRARIES, ShelfEntry}; +use crate::theme::Tokens; + +/// A menu row's height and the inset of its hover face from the menu's sides, in points +const ROW_HEIGHT: f32 = 24.0; +const HOVER_INSET: f32 = 3.0; +const HOVER_ROUNDING: u8 = 3; +/// Where a row's text starts, from the menu's left edge, in points +const TEXT_X: f32 = 10.0; +/// The space after the text of the widest row, in points +const RIGHT_PADDING: f32 = 24.0; +/// The air between the info block's label column and its values, in points +const LABEL_GAP: f32 = 12.0; +/// The widest the info block's values get before the path is cut in the middle, in points +const MAX_VALUE_WIDTH: f32 = 220.0; +/// The menu's text size, in points +const TEXT_SIZE: f32 = 12.0; +/// The air above and below the separators, in points +const SEPARATOR_SPACE: f32 = 3.0; + +/// The right-click menu on the tile whose response is `response` +pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &ShelfEntry) { + response.context_menu(|ui| { + let tokens = Tokens::get(ui.ctx()); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + let info = info_rows(entry); + let width = menu_width(ui, &info, &row_labels(entry)); + ui.set_width(width); + info_block(ui, width, &info, &tokens); + separator(ui, &tokens); + + if let ShelfEntry::Image(name) = entry { + if row(ui, width, tr("Export resource..."), true, &tokens).clicked() { + export_image(app, name); + ui.close(); + } + separator(ui, &tokens); + if row(ui, width, tr("Add as decal (view center)"), true, &tokens).clicked() { + app.run("layer.add.decal", json!({"image": name})); + ui.close(); + } + if row(ui, width, tr("Remove resource"), true, &tokens).clicked() { + app.run("resource.remove", json!({"name": name})); + ui.close(); + } + } else { + row(ui, width, tr("Export resource..."), false, &tokens).on_hover_text(tr("Built-in assets have no file to export")); + } + + separator(ui, &tokens); + if row(ui, width, tr("Close"), true, &tokens).clicked() { + ui.close(); + } + }); +} + +/// The info block's label and value rows: rows only where the asset has the data +fn info_rows(entry: &ShelfEntry) -> Vec<(&'static str, String)> { + let path = entry.path(); + let shown_path: Vec<&str> = path.iter().map(|part| LIBRARIES.iter().find(|(id, _)| id == part).map_or_else(|| tr(part), |(_, name)| tr(name))).collect(); + let mut rows = + vec![(tr("Name"), entry.label().to_string()), (tr("Usages"), tr(entry.usage()).to_string()), (tr("Path"), format!("/{}/", shown_path.join("/")))]; + if let Some(category) = path.get(2) { + rows.push((tr("Category"), tr(category).to_string())); + } + rows +} + +/// The labels of the rows under the info block, for the menu's width +fn row_labels(entry: &ShelfEntry) -> Vec<&'static str> { + let mut labels = vec![tr("Export resource..."), tr("Close")]; + if matches!(entry, ShelfEntry::Image(_)) { + labels.extend([tr("Add as decal (view center)"), tr("Remove resource")]); + } + labels +} + +fn text_width(ui: &Ui, text: &str) -> f32 { + ui.fonts_mut(|fonts| fonts.layout_no_wrap(text.to_owned(), FontId::proportional(TEXT_SIZE), Color32::WHITE).size().x) +} + +/// The label column's width: the longest label and its gap +fn label_column(ui: &Ui, info: &[(&str, String)]) -> f32 { + info.iter().map(|(label, _)| text_width(ui, label)).fold(0.0, f32::max) + LABEL_GAP +} + +/// The widest row, the info block's values capped at [`MAX_VALUE_WIDTH`] +fn menu_width(ui: &Ui, info: &[(&str, String)], labels: &[&str]) -> f32 { + let widest_value = info.iter().map(|(_, value)| text_width(ui, value)).fold(0.0, f32::max).min(MAX_VALUE_WIDTH); + let widest_row = labels.iter().map(|label| text_width(ui, label)).fold(0.0, f32::max); + TEXT_X + (label_column(ui, info) + widest_value).max(widest_row) + RIGHT_PADDING +} + +/// The label (dim) and value rows; a value too wide is cut in the middle with "…" +fn info_block(ui: &mut Ui, width: f32, info: &[(&str, String)], tokens: &Tokens) { + let column = label_column(ui, info); + let value_width = width - TEXT_X - column - RIGHT_PADDING; + for (label, value) in info { + let (rect, response) = ui.allocate_exact_size(vec2(width, ROW_HEIGHT), Sense::hover()); + let shown = cut_middle(ui, value, value_width); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{label} {value}"))); + let painter = ui.painter(); + painter.text(pos2(rect.left() + TEXT_X, rect.center().y), Align2::LEFT_CENTER, *label, FontId::proportional(TEXT_SIZE), tokens.text_dim); + painter.text(pos2(rect.left() + TEXT_X + column, rect.center().y), Align2::LEFT_CENTER, shown, FontId::proportional(TEXT_SIZE), tokens.text); + } +} + +/// `text`, or its start and end around "…" so it fits `width` points +fn cut_middle(ui: &Ui, text: &str, width: f32) -> String { + if text_width(ui, text) <= width { + return text.to_owned(); + } + + let chars: Vec = text.chars().collect(); + let mut kept = chars.len(); + loop { + let head = kept.div_ceil(2); + let tail = kept / 2; + let cut: String = chars[..head].iter().chain(['…'].iter()).chain(chars[chars.len() - tail..].iter()).collect(); + if kept == 0 || text_width(ui, &cut) <= width { + return cut; + } + + kept -= 1; + } +} + +/// A hairline across the menu between groups of rows +fn separator(ui: &mut Ui, tokens: &Tokens) { + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), SEPARATOR_SPACE * 2.0 + 1.0), Sense::hover()); + ui.painter().hline(rect.x_range(), rect.center().y, egui::Stroke::new(1.0, tokens.separator)); +} + +/// One menu row: a hover face inset from the sides, its text dim and unclickable when not `enabled` +fn row(ui: &mut Ui, width: f32, label: &str, enabled: bool, tokens: &Tokens) -> Response { + let sense = if enabled { Sense::click() } else { Sense::hover() }; + let (rect, response) = ui.allocate_exact_size(vec2(width, ROW_HEIGHT), sense); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, label)); + let painter = ui.painter(); + if enabled && (response.hovered() || response.has_focus()) { + painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::same(HOVER_ROUNDING), tokens.button); + } + let color = if enabled { tokens.text } else { tokens.text_dim }; + painter.text(pos2(rect.left() + TEXT_X, rect.center().y), Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), color); + if enabled { response } else { response.on_hover_cursor(egui::CursorIcon::NotAllowed) } +} + +/// Asks where to save image resource `name`, then writes it there as imported +#[cfg(not(target_arch = "wasm32"))] +fn export_image(app: &mut TextureCraftApp, name: &str) { + use crate::file_dialogs::{Bound, FileDialog}; + + let extension = std::path::Path::new(name).extension().and_then(|extension| extension.to_str()).unwrap_or_default().to_owned(); + let name = name.to_owned(); + let dialog = FileDialog::save().filter(tr("Image"), &[extension.as_str()]).file_name(&name); + app.ask_file(dialog, Bound::Project, move |app, paths| { + if let Some(path) = paths.first() { + app.run("resource.export", json!({"name": name, "path": path.to_string_lossy()})); + } + }); +} + +#[cfg(target_arch = "wasm32")] +fn export_image(app: &mut TextureCraftApp, _: &str) { + app.toast(tr("Exporting resources needs the desktop app"), true); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index c8d7f0f3..fd55514b 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -81,6 +81,7 @@ mod settings_window; mod shelf_click; mod shelf_drop; mod shelf_hover_preview; +mod shelf_menu; mod shelf_panel; mod shift_lines_2d; mod shift_lines_3d; diff --git a/crates/ui-egui/tests/it/shelf_menu.rs b/crates/ui-egui/tests/it/shelf_menu.rs new file mode 100644 index 00000000..1acc99ae --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_menu.rs @@ -0,0 +1,67 @@ +//! An asset tile's right-click menu: the info block says what the asset is, and its rows act on it + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::materials::MATERIALS; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::file_dialogs::Answer; + +/// The types' positions in the shelf's type row (its table is crate-private) +const MATERIALS_TYPE: usize = 0; +const TEXTURES_TYPE: usize = 6; + +/// The sample project with the shelf on type `tab` +fn shelf(tab: usize) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.shelf_tab = tab; + harness.run_steps(4); + harness +} + +fn right_click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + harness.get_all_by_label(label).next().unwrap_or_else(|| panic!("no tile {label}")).click_secondary(); + harness.run_steps(3); +} + +#[test] +fn a_built_in_tile_menu_says_what_the_asset_is_and_where_it_lives() { + // The grid's first plain material (by name), so its tile is in view + let material = MATERIALS.iter().filter(|material| !material.smart).min_by_key(|material| material.label.to_lowercase()).unwrap(); + let mut harness = shelf(MATERIALS_TYPE); + + right_click(&mut harness, material.label); + + for row in [ + format!("Name {}", material.label), + "Usages material".to_string(), + format!("Path /Starter assets/Materials/{}/", material.category), + format!("Category {}", material.category), + ] { + assert!(harness.query_by_label(&row).is_some(), "the menu has the info row {row:?}"); + } + assert!(harness.get_by_label("Export resource...").accesskit_node().is_disabled(), "a built-in has no file to export"); + + harness.get_by_label("Close").click(); + harness.run_steps(3); + assert!(harness.query_by_label("Usages material").is_none(), "Close closes the menu"); +} + +#[test] +fn export_resource_writes_the_image_as_imported() { + let mut harness = shelf(TEXTURES_TYPE); + let mut bytes = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([180, 90, 40, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = harness.state_mut().session.import_resource_bytes("plate.png", bytes.clone()).unwrap(); + harness.run_steps(3); + let dir = super::temp_dir::TempDir::new("shelf-export-resource"); + let target = dir.join("exported.png"); + let answer = target.clone(); + harness.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![answer.clone()])))); + + right_click(&mut harness, &name); + harness.get_by_label("Export resource...").click(); + harness.run_steps(4); + + assert_eq!(std::fs::read(&target).unwrap(), bytes, "the exported file is the resource's own bytes"); +} From 2bc7f69dcad33ad8b8a298e167bcbcf23369c051 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:03:25 +0000 Subject: [PATCH 02/16] Assets: rename, replace, delete and export saved brushes from their menu A saved brush's right-click menu has its Name as a field: Enter or a click elsewhere renames the brush, Escape keeps the name. Below the info block: Replace with the current brush and Delete, then Export resource, which writes the preset as a .tcbrush file (new brush.preset.export command). For project images, Delete takes the place of Remove resource and moves up beside the other actions on the image itself. Part of #411 --- crates/engine/src/brush_preset_cmds.rs | 54 ++++++++++ crates/ui-egui/src/shelf_menu.rs | 139 +++++++++++++++++++++---- crates/ui-egui/tests/it/shelf_menu.rs | 62 +++++++++++ 3 files changed, 234 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/brush_preset_cmds.rs b/crates/engine/src/brush_preset_cmds.rs index 28d96d7b..f2f23a67 100644 --- a/crates/engine/src/brush_preset_cmds.rs +++ b/crates/engine/src/brush_preset_cmds.rs @@ -146,6 +146,15 @@ pub fn specs() -> Vec { cmd!("brush.preset.delete", "Delete a brush preset", [], None, "{name} — one of the user's presets (built-ins are read-only)", always, delete), cmd!("brush.preset.save", "Save brush preset", [], None, "{path} — the current brush as a .tcbrush file", always, save), cmd!("brush.preset.load", "Load brush preset", [], None, "{path} — a .tcbrush file's stroke on the brush, keeping the size", always, load), + cmd!( + "brush.preset.export", + "Export brush preset", + [], + None, + "{name, path} — one of the user's presets as a .tcbrush file, as its library folder holds it", + always, + export + ), ] } @@ -325,6 +334,26 @@ fn load(_: &mut Session, _: &Value) -> Result { Err(bad("brush.preset.load", "file paths are not available in the browser")) } +/// Writes user preset `name` to `path` as the library folder holds it +#[cfg(not(target_arch = "wasm32"))] +fn export(session: &mut Session, params: &Value) -> Result { + const CMD: &str = "brush.preset.export"; + let name = name_param(params, "name", CMD)?; + let path = strp(params, "path").ok_or_else(|| bad(CMD, "`path` is required"))?; + let preset = session.brush_presets.find(&name).and_then(|index| session.brush_presets.list.get(index)); + let preset = preset.ok_or_else(|| bad(CMD, format!("no user brush preset `{name}`")))?; + let bytes = serde_json::to_vec_pretty(preset).map_err(|error| bad(CMD, error.to_string()))?; + + std::fs::write(path, bytes).map_err(|error| bad(CMD, format!("cannot write {path}: {error}")))?; + + Ok(json!({ "path": path })) +} + +#[cfg(target_arch = "wasm32")] +fn export(_: &mut Session, _: &Value) -> Result { + Err(bad("brush.preset.export", "file paths are not available in the browser")) +} + #[cfg(test)] mod tests { use super::*; @@ -406,6 +435,31 @@ mod tests { assert_eq!(names(&test_session), ["a/b"]); } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn an_exported_preset_loads_as_the_same_brush() { + let dir = std::env::temp_dir().join(format!("tc-brush-export-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut test_session = session(); + run(&mut test_session, "tool.brush", json!({"size": 41, "hardness": 70})).unwrap(); + run(&mut test_session, "brush.preset.store", json!({"name": "Ink pen"})).unwrap(); + run(&mut test_session, "tool.brush", json!({"size": 5})).unwrap(); + + let path = dir.join("shared.tcbrush"); + run(&mut test_session, "brush.preset.export", json!({"name": "ink pen", "path": path.to_str().unwrap()})).unwrap(); + + let mut fresh = session(); + assert!(fresh.load_brush_presets(dir.clone()).is_empty()); + assert_eq!(names(&fresh), ["Ink pen"], "the file carries the preset's name"); + assert_eq!(fresh.brush_presets.list[0].brush, test_session.brush_presets.list[0].brush, "the stored brush, not the current one"); + assert!( + run(&mut test_session, "brush.preset.export", json!({"name": "Airbrush", "path": path.to_str().unwrap()})).is_err(), + "built-ins are not exported" + ); + let _ = std::fs::remove_dir_all(&dir); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn presets_persist_in_the_folder() { diff --git a/crates/ui-egui/src/shelf_menu.rs b/crates/ui-egui/src/shelf_menu.rs index 22d2af95..35a7ba49 100644 --- a/crates/ui-egui/src/shelf_menu.rs +++ b/crates/ui-egui/src/shelf_menu.rs @@ -1,4 +1,4 @@ -//! An asset tile's right-click menu: what the asset is (name, usages, path, category), then what can be done with it +//! An asset tile's right-click menu: what the asset is (name, usages, path, category), then what can be done with it; the Name of an asset the user owns is a field that renames it use egui::{Align2, Color32, CornerRadius, FontId, Response, Sense, Ui, pos2, vec2}; use serde_json::json; @@ -22,36 +22,74 @@ const LABEL_GAP: f32 = 12.0; const MAX_VALUE_WIDTH: f32 = 220.0; /// The menu's text size, in points const TEXT_SIZE: f32 = 12.0; +/// The Name field's row and field heights, and the air before its text, in points +const FIELD_ROW_HEIGHT: f32 = 28.0; +const FIELD_HEIGHT: f32 = 24.0; +const FIELD_TEXT_INSET: f32 = 8.0; /// The air above and below the separators, in points const SEPARATOR_SPACE: f32 = 3.0; /// The right-click menu on the tile whose response is `response` pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &ShelfEntry) { - response.context_menu(|ui| { + // Clicks inside keep the menu open, so the Name field can be typed in; its rows close it themselves + let menu = egui::Popup::context_menu(response).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); + menu.show(|ui| { let tokens = Tokens::get(ui.ctx()); ui.spacing_mut().item_spacing = vec2(0.0, 0.0); let info = info_rows(entry); let width = menu_width(ui, &info, &row_labels(entry)); ui.set_width(width); - info_block(ui, width, &info, &tokens); + let column = label_column(ui, &info); + + // A saved brush is the user's own: its Name row is a field that renames it + let mut shown_info = info.as_slice(); + if let ShelfEntry::SavedBrush { name, .. } = entry + && let Some((_, rest)) = info.split_first() + { + shown_info = rest; + let field_id = ui.make_persistent_id(("asset_name", entry.identity())); + if let Some(renamed) = name_field(ui, width, column, field_id, name, &tokens) { + app.run("brush.preset.rename", json!({"name": name, "to": renamed})); + } + } + info_block(ui, width, column, shown_info, &tokens); separator(ui, &tokens); - if let ShelfEntry::Image(name) = entry { - if row(ui, width, tr("Export resource..."), true, &tokens).clicked() { - export_image(app, name); - ui.close(); + match entry { + ShelfEntry::Image(name) => { + if row(ui, width, tr("Delete"), true, &tokens).clicked() { + app.run("resource.remove", json!({"name": name})); + ui.close(); + } + separator(ui, &tokens); + if row(ui, width, tr("Export resource..."), true, &tokens).clicked() { + export_image(app, name); + ui.close(); + } + separator(ui, &tokens); + if row(ui, width, tr("Add as decal (view center)"), true, &tokens).clicked() { + app.run("layer.add.decal", json!({"image": name})); + ui.close(); + } } - separator(ui, &tokens); - if row(ui, width, tr("Add as decal (view center)"), true, &tokens).clicked() { - app.run("layer.add.decal", json!({"image": name})); - ui.close(); + ShelfEntry::SavedBrush { name, .. } => { + if row(ui, width, tr("Replace with the current brush"), true, &tokens).clicked() { + app.run("brush.preset.store", json!({"name": name, "overwrite": true})); + ui.close(); + } + if row(ui, width, tr("Delete"), true, &tokens).clicked() { + app.run("brush.preset.delete", json!({"name": name})); + ui.close(); + } + separator(ui, &tokens); + if row(ui, width, tr("Export resource..."), true, &tokens).clicked() { + export_brush(app, name); + ui.close(); + } } - if row(ui, width, tr("Remove resource"), true, &tokens).clicked() { - app.run("resource.remove", json!({"name": name})); - ui.close(); + _ => { + row(ui, width, tr("Export resource..."), false, &tokens).on_hover_text(tr("Built-in assets have no file to export")); } - } else { - row(ui, width, tr("Export resource..."), false, &tokens).on_hover_text(tr("Built-in assets have no file to export")); } separator(ui, &tokens); @@ -76,8 +114,10 @@ fn info_rows(entry: &ShelfEntry) -> Vec<(&'static str, String)> { /// The labels of the rows under the info block, for the menu's width fn row_labels(entry: &ShelfEntry) -> Vec<&'static str> { let mut labels = vec![tr("Export resource..."), tr("Close")]; - if matches!(entry, ShelfEntry::Image(_)) { - labels.extend([tr("Add as decal (view center)"), tr("Remove resource")]); + match entry { + ShelfEntry::Image(_) => labels.extend([tr("Delete"), tr("Add as decal (view center)")]), + ShelfEntry::SavedBrush { .. } => labels.extend([tr("Replace with the current brush"), tr("Delete")]), + _ => {} } labels } @@ -98,9 +138,8 @@ fn menu_width(ui: &Ui, info: &[(&str, String)], labels: &[&str]) -> f32 { TEXT_X + (label_column(ui, info) + widest_value).max(widest_row) + RIGHT_PADDING } -/// The label (dim) and value rows; a value too wide is cut in the middle with "…" -fn info_block(ui: &mut Ui, width: f32, info: &[(&str, String)], tokens: &Tokens) { - let column = label_column(ui, info); +/// The label (dim) and value rows, values `column` points after the labels; a value too wide is cut in the middle with "…" +fn info_block(ui: &mut Ui, width: f32, column: f32, info: &[(&str, String)], tokens: &Tokens) { let value_width = width - TEXT_X - column - RIGHT_PADDING; for (label, value) in info { let (rect, response) = ui.allocate_exact_size(vec2(width, ROW_HEIGHT), Sense::hover()); @@ -112,6 +151,44 @@ fn info_block(ui: &mut Ui, width: f32, info: &[(&str, String)], tokens: &Tokens) } } +/// The Name row of an asset the user owns: a field in the value column that returns the new name once typing ends (Enter or a click elsewhere) with a changed, non-blank name. Escape keeps the old one +fn name_field(ui: &mut Ui, width: f32, column: f32, field_id: egui::Id, name: &str, tokens: &Tokens) -> Option { + let (rect, _) = ui.allocate_exact_size(vec2(width, FIELD_ROW_HEIGHT), Sense::hover()); + let label = tr("Name"); + ui.painter().text(pos2(rect.left() + TEXT_X, rect.center().y), Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), tokens.text_dim); + + // Check raw Escape even if the menu consumed it + let escaped = ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); + if escaped { + ui.data_mut(|data| data.remove::(field_id)); + } + let mut text = ui.data(|data| data.get_temp::(field_id)).unwrap_or_else(|| name.to_owned()); + + // The field's text lines up with the values below it + let field = egui::Rect::from_min_max( + pos2(rect.left() + TEXT_X + column - FIELD_TEXT_INSET, rect.center().y - FIELD_HEIGHT / 2.0), + pos2(rect.right() - TEXT_X, rect.center().y + FIELD_HEIGHT / 2.0), + ); + ui.painter().rect(field, CornerRadius::same(HOVER_ROUNDING), tokens.field, egui::Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); + let edit = egui::TextEdit::singleline(&mut text) + .id(field_id) + .font(FontId::proportional(TEXT_SIZE)) + .text_color(tokens.text) + .frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(FIELD_TEXT_INSET as i8, 0))) + .align(Align2::LEFT_CENTER); + let response = ui.new_child(egui::UiBuilder::new().max_rect(field.shrink(1.0))).add_sized(field.shrink(1.0).size(), edit); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, true, label)); + + if response.has_focus() { + ui.data_mut(|data| data.insert_temp(field_id, text)); + return None; + } + + ui.data_mut(|data| data.remove::(field_id)); + let typed = text.trim(); + (response.lost_focus() && !escaped && !typed.is_empty() && typed != name).then(|| typed.to_owned()) +} + /// `text`, or its start and end around "…" so it fits `width` points fn cut_middle(ui: &Ui, text: &str, width: f32) -> String { if text_width(ui, text) <= width { @@ -171,3 +248,23 @@ fn export_image(app: &mut TextureCraftApp, name: &str) { fn export_image(app: &mut TextureCraftApp, _: &str) { app.toast(tr("Exporting resources needs the desktop app"), true); } + +/// Asks where to save saved brush `name`, then writes it there as a brush preset file +#[cfg(not(target_arch = "wasm32"))] +fn export_brush(app: &mut TextureCraftApp, name: &str) { + use crate::file_dialogs::{Bound, FileDialog}; + use texturecraft_engine::brush_preset_cmds::BRUSH_EXT; + + let name = name.to_owned(); + let dialog = FileDialog::save().filter(tr("Brush preset"), &[BRUSH_EXT]).file_name(format!("{name}.{BRUSH_EXT}")); + app.ask_file(dialog, Bound::App, move |app, paths| { + if let Some(path) = paths.first() { + app.run("brush.preset.export", json!({"name": name, "path": path.to_string_lossy()})); + } + }); +} + +#[cfg(target_arch = "wasm32")] +fn export_brush(app: &mut TextureCraftApp, _: &str) { + app.toast(tr("Exporting resources needs the desktop app"), true); +} diff --git a/crates/ui-egui/tests/it/shelf_menu.rs b/crates/ui-egui/tests/it/shelf_menu.rs index 1acc99ae..51b7bdae 100644 --- a/crates/ui-egui/tests/it/shelf_menu.rs +++ b/crates/ui-egui/tests/it/shelf_menu.rs @@ -1,13 +1,16 @@ //! An asset tile's right-click menu: the info block says what the asset is, and its rows act on it +use egui::{Key, Modifiers}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; use texturecraft_engine::materials::MATERIALS; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::file_dialogs::Answer; /// The types' positions in the shelf's type row (its table is crate-private) const MATERIALS_TYPE: usize = 0; +const BRUSHES_TYPE: usize = 4; const TEXTURES_TYPE: usize = 6; /// The sample project with the shelf on type `tab` @@ -65,3 +68,62 @@ fn export_resource_writes_the_image_as_imported() { assert_eq!(std::fs::read(&target).unwrap(), bytes, "the exported file is the resource's own bytes"); } + +fn preset_names(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.state().session.brush_presets.list.iter().map(|preset| preset.name.clone()).collect() +} + +/// Selects the menu's Name field text and types `text` +fn type_name(harness: &mut Harness<'_, TextureCraftApp>, text: &str) { + harness.get_by_role_and_label(egui::Role::TextInput, "Name").click(); + harness.run_steps(3); + harness.key_press_modifiers(Modifiers::COMMAND, Key::A); + harness.event(egui::Event::Text(text.into())); + harness.run_steps(3); +} + +#[test] +fn a_saved_brush_menu_renames_replaces_and_deletes_it() { + // A name that sorts before every built-in brush, so its tile is in view + let mut harness = shelf(BRUSHES_TYPE); + texturecraft_engine::execute(&mut harness.state_mut().session, "brush.preset.store", &json!({"name": "Aa ink"})).unwrap(); + harness.run_steps(3); + + right_click(&mut harness, "Aa ink"); + type_name(&mut harness, "Never applied"); + harness.key_press(Key::Escape); + harness.run_steps(3); + assert_eq!(preset_names(&harness), ["Aa ink"], "Escape keeps the name"); + + right_click(&mut harness, "Aa ink"); + type_name(&mut harness, "Aa pen"); + harness.key_press(Key::Enter); + harness.run_steps(3); + assert_eq!(preset_names(&harness), ["Aa pen"], "Enter renames the brush"); + + texturecraft_engine::execute(&mut harness.state_mut().session, "tool.brush", &json!({"size": 77})).unwrap(); + right_click(&mut harness, "Aa pen"); + harness.get_by_label("Replace with the current brush").click(); + harness.run_steps(3); + assert_eq!(harness.state().session.brush_presets.list[0].brush, harness.state().session.tool.brush, "the preset holds the current brush"); + + right_click(&mut harness, "Aa pen"); + harness.get_by_label("Delete").click(); + harness.run_steps(3); + assert!(preset_names(&harness).is_empty(), "Delete removes the brush"); +} + +#[test] +fn delete_removes_a_project_image() { + let mut harness = shelf(TEXTURES_TYPE); + let mut bytes = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([180, 90, 40, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = harness.state_mut().session.import_resource_bytes("plate.png", bytes).unwrap(); + harness.run_steps(3); + + right_click(&mut harness, &name); + harness.get_by_label("Delete").click(); + harness.run_steps(3); + + assert!(!harness.state().session.doc.resources.contains_key(&name)); +} From 8abd6ead2613a39fe0f3afcde0c28147fe87329a Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:24:41 +0000 Subject: [PATCH 03/16] Assets: rename and reload project images from their menu The Name row of a project image's menu is a field: resource.rename moves the image and every layer, effect, stored path, environment and tool reference to it in one undo step, and refuses rather than leave a reference behind. Reload (resource.reload) reads the image again from the file it was imported from in this session; it is greyed, with the reason, for images imported before. Undo and redo decode a resource again when the step changed its bytes. --- crates/core/src/layer.rs | 31 ++++ crates/core/src/layer/tile_generator.rs | 5 + crates/engine/src/path_tool.rs | 15 ++ crates/engine/src/resource_cmds.rs | 226 +++++++++++++++++++++++- crates/engine/src/session.rs | 46 +++++ crates/ui-egui/src/shelf_menu.rs | 22 ++- crates/ui-egui/tests/it/shelf_menu.rs | 18 ++ 7 files changed, 352 insertions(+), 11 deletions(-) diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index e352bbc0..56a5147f 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -703,6 +703,15 @@ impl Source { } } + /// [`Source::images`], to rename them + pub fn images_mut(&mut self) -> Vec<&mut String> { + match self { + Source::Image { name, .. } => vec![name], + Source::Procedural { pattern, .. } => pattern.tile.iter_mut().flat_map(|tile| tile.images_mut()).collect(), + Source::Uniform(_) | Source::Anchor { .. } => Vec::new(), + } + } + /// The gradient map stops of a procedural or anchor source (empty: none). pub fn ramp(&self) -> &[[f32; 3]] { match self { @@ -808,6 +817,12 @@ pub struct LinkPreset { } impl Fill { + /// The image resource names the fill holds, to rename them: its sources' and, when linked, its package and cooked outputs + pub fn images_mut(&mut self) -> impl Iterator { + let link = self.link.iter_mut().map(|link| &mut **link).flat_map(|link| std::iter::once(&mut link.package).chain(link.outputs.values_mut())); + self.sources.values_mut().flat_map(Source::images_mut).chain(link) + } + /// Value used for `c` when the fill has no source for it: the channel default. pub fn source(&self, c: Channel) -> Source { self.sources.get(&c).cloned().unwrap_or_else(|| Source::uniform_of(c)) @@ -2053,6 +2068,17 @@ impl EffectKind { sources.into_iter().flat_map(Source::images).chain(id_map) } + /// [`EffectKind::images_read`], to rename them + pub fn images_mut(&mut self) -> Vec<&mut String> { + match self { + EffectKind::Fill { source, .. } => source.images_mut(), + EffectKind::Material(fill) => fill.sources.values_mut().flat_map(Source::images_mut).collect(), + EffectKind::Generator(generator) => generator.inputs.values_mut().flat_map(Source::images_mut).collect(), + EffectKind::ColorSelection(selection) => selection.id_map.iter_mut().collect(), + _ => Vec::new(), + } + } + /// Reads a channel of the layer or of the stack below it (a compare mask's layer sides) pub fn reads_stack(&self) -> bool { matches!(self, EffectKind::Compare { left, right, .. } if left.reads_stack() || right.reads_stack()) @@ -2115,6 +2141,11 @@ impl Effect { self.kind.images_read().chain(self.inputs.values().flat_map(Source::images)) } + /// [`Effect::images_read`], to rename them + pub fn images_mut(&mut self) -> impl Iterator { + self.kind.images_mut().into_iter().chain(self.inputs.values_mut().flat_map(Source::images_mut)) + } + /// Whether a source of the effect, or one of its image inputs, reads anchor point `anchor` (any anchor point when None) pub fn reads(&self, anchor: Option) -> bool { self.kind.reads(anchor) || self.inputs.values().any(|source| source.reads_anchor(anchor)) diff --git a/crates/core/src/layer/tile_generator.rs b/crates/core/src/layer/tile_generator.rs index 6836fcd9..94e25752 100644 --- a/crates/core/src/layer/tile_generator.rs +++ b/crates/core/src/layer/tile_generator.rs @@ -202,6 +202,11 @@ impl TileGenerator { pub fn images(&self) -> impl Iterator { self.inputs.iter().chain(&self.background_image).map(String::as_str) } + + /// [`TileGenerator::images`], to rename them + pub fn images_mut(&mut self) -> impl Iterator { + self.inputs.iter_mut().chain(&mut self.background_image) + } } impl Default for TileGenerator { diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 94b9d930..65c10a71 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -385,6 +385,21 @@ pub(crate) fn path_images(kind: &EffectKind) -> Vec { shapes.iter().filter_map(|shape| read_paint(shape).ok()?.mask_image).collect() } +/// Points the stored paths of `kind` that paint with image resource `from` (as mask image or brush alpha) at `to` +pub(crate) fn rename_path_images(kind: &mut EffectKind, from: &str, to: &str) { + let EffectKind::Path(shapes) = kind else { return }; + + for shape in shapes { + for pointer in ["/mask_image", "/brush/alpha_image"] { + if let Some(image) = shape.paint.pointer_mut(pointer) + && image.as_str() == Some(from) + { + *image = serde_json::Value::String(to.to_string()); + } + } + } +} + /// The Path tool state showing a stored path (finite points only, at most [`MAX_PATH_POINTS`]) fn state_of(shape: &PathShape) -> PathState { let points = shape.points.iter().filter(|p| p.iter().all(|v| v.is_finite())).take(MAX_PATH_POINTS).map(|p| Vec3::from_array(*p)).collect(); diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index d81263d5..da51b8ea 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -25,6 +25,24 @@ pub fn specs() -> Vec { cmd!("resource.list", "List resources", [], None, "{}", always, |s, _| Ok(list(s))), cmd!("resource.remove", "Remove resource", [], None, "{name}", always, remove), cmd!("resource.export", "Export resource", [], None, "{name, path} — the resource's file as it was imported", always, export), + cmd!( + "resource.rename", + "Rename resource", + [], + None, + "{name, to} — everything that uses the image follows it; `to` keeps the old extension when it has none", + always, + rename + ), + cmd!( + "resource.reload", + "Reload resource", + [], + None, + "{name} — read the image again from the file it was imported from in this session", + always, + reload + ), cmd!("file.removeUnused", "Remove unused resources...", ["File"], None, "{}", always, remove_unused), cmd!( "layer.add.image", @@ -97,9 +115,17 @@ impl Session { self.doc.resources.insert(name.clone(), Arc::new(bytes)); self.images.insert(name.clone(), decoded(image)); + // A new resource under a removed one's name has no file of its own until an import says so + self.resource_sources.remove(&name); + Ok(name) } + /// Whether image resource `name` was imported from a file in this session, so `resource.reload` can read it again + pub fn reloadable(&self, name: &str) -> bool { + self.resource_sources.contains_key(name) + } + /// Decode resources that are not decoded yet and forget removed ones (after undo, redo, load). pub fn sync_images(&mut self) { self.images.retain(|name, _| self.doc.resources.contains_key(name)); @@ -175,6 +201,7 @@ 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_prefixed(strp(p, "prefix").unwrap_or(""), path, bytes)?; + s.resource_sources.insert(name.clone(), path.into()); Ok(json!({ "name": name })) } @@ -280,18 +307,143 @@ fn export(_: &mut Session, _: &Value) -> Result { Err(bad("resource.export", "file paths are not available in the browser")) } -/// Drop resources no layer, mask effect, the brush alpha, the projection stencil, the mask brush or the environment uses (one undo step) -fn remove_unused(s: &mut Session, _: &Value) -> Result { - let mut used = Vec::new(); - for set in &s.doc.project.texture_sets { - for root in &set.stack { - crate::material_lib::images_used(&s.doc.project, *root, &mut used, 0); +/// Renames image resource `name` to `to` and every reference to it, in one undo step +fn rename(s: &mut Session, p: &Value) -> Result { + let command = "resource.rename"; + let name = strp(p, "name").ok_or_else(|| bad(command, "`name` is required"))?.to_string(); + let to = strp(p, "to").ok_or_else(|| bad(command, "`to` is required"))?.trim(); + if !s.doc.resources.contains_key(&name) { + return Err(bad(command, format!("no resource `{name}`"))); + } + + let mut to = sanitize_resource_name(to); + if std::path::Path::new(&to).extension().is_none() + && let Some(extension) = std::path::Path::new(&name).extension().and_then(|extension| extension.to_str()) + { + // The stem gives way, so a long name keeps its extension + let stem_room = MAX_RESOURCE_NAME_LEN.saturating_sub(extension.len() + 1); + to.truncate(stem_room); + to = format!("{to}.{extension}"); + } + if to == name { + return Ok(json!({ "name": name })); + } + if s.doc.resources.contains_key(&to) || crate::fill_alpha::library_alpha_of(&to).is_some() { + return Err(bad(command, format!("a resource named `{to}` exists already"))); + } + + s.edit("Rename resource", |s| { + let bytes = s.doc.resources.remove(&name).ok_or_else(|| bad(command, format!("no resource `{name}`")))?; + s.doc.resources.insert(to.clone(), bytes); + rename_references(&mut s.doc.project, &name, &to); + + // Refuse rather than leave a reference this rename does not know about pointing at nothing + if project_images(&s.doc.project).contains(&name) { + return Err(bad(command, format!("`{name}` is used somewhere it can't be renamed"))); + } + + Ok(()) + })?; + + for tool_image in s.tool_images_mut().filter(|tool_image| **tool_image == name) { + tool_image.clone_from(&to); + } + + // The decoded pixels are the same: they move instead of decoding again + if let Some(image) = s.images.remove(&name) { + s.images.insert(to.clone(), image); + } + if s.library_alphas.remove(&name) { + s.library_alphas.insert(to.clone()); + } + if let Some(source) = s.resource_sources.remove(&name) { + s.resource_sources.insert(to.clone(), source); + } + s.path_cache = None; + s.sync_images(); + Ok(json!({ "name": to })) +} + +/// Points every layer, effect, stored path and the environment that read image resource `from` at `to` +fn rename_references(project: &mut texturecraft_core::Project, from: &str, to: &str) { + for layer in project.layers.values_mut() { + let fill_images: Vec<&mut String> = match &mut layer.kind { + LayerKind::Fill(fill) => fill.images_mut().collect(), + _ => Vec::new(), + }; + let effects = layer.mask.iter_mut().flat_map(|mask| mask.effects.iter_mut()).chain(&mut layer.content_effects); + let mut images = fill_images; + for effect in effects { + crate::path_tool::rename_path_images(&mut effect.kind, from, to); + images.extend(effect.images_mut()); + } + + for image in images.into_iter().filter(|image| *image == from) { + *image = to.to_string(); } } + + if project.display.environment_resource() == Some(from) { + project.display.environment = format!("{}{to}", texturecraft_core::project::ENV_RESOURCE_PREFIX); + } +} + +/// Reads image resource `name` again from the file this session imported it from (one undo step) +#[cfg(not(target_arch = "wasm32"))] +fn reload(s: &mut Session, p: &Value) -> Result { + let command = "resource.reload"; + let name = strp(p, "name").ok_or_else(|| bad(command, "`name` is required"))?.to_string(); + if !s.doc.resources.contains_key(&name) { + return Err(bad(command, format!("no resource `{name}`"))); + } + + let path = + s.resource_sources.get(&name).cloned().ok_or_else(|| bad(command, format!("`{name}` was imported before this session: no file to reload from")))?; + let bytes = read_resource_file(command, &path, MAX_BYTES as u64)?; + let image = texturecraft_formats::decode_image_within(&bytes, texturecraft_formats::MAX_RESOURCE_TEXELS) + .map_err(|error| bad(command, format!("{}: {error}", path.display())))?; + s.edit("Reload resource", |s| { + s.doc.resources.insert(name.clone(), Arc::new(bytes)); + Ok(()) + })?; + + s.library_alphas.remove(&name); + if crate::fill_alpha::matches_saved_picture(&name, &image) { + s.library_alphas.insert(name.clone()); + } + s.images.insert(name.clone(), decoded(image)); + Ok(json!({ "name": name })) +} + +#[cfg(target_arch = "wasm32")] +fn reload(_: &mut Session, _: &Value) -> Result { + Err(bad("resource.reload", "file paths are not available in the browser")) +} + +/// Every image resource a layer, mask effect, stored path or the environment of `project` uses +fn project_images(project: &texturecraft_core::Project) -> Vec { + let mut used = Vec::new(); + for set in &project.texture_sets { + for root in &set.stack { + crate::material_lib::images_used(project, *root, &mut used, 0); + } + } + used.extend(project.display.environment_resource().map(str::to_string)); + used +} + +/// [`project_images`] and the images the brush alpha, the projection stencil and the mask brush use +fn images_in_use(s: &Session) -> Vec { + let mut used = project_images(&s.doc.project); used.extend(s.tool.stencil.as_ref().map(|st| st.image.clone())); used.extend(s.tool.brush.alpha_image.clone()); used.extend(s.tool.mask_image.clone()); - used.extend(s.doc.project.display.environment_resource().map(str::to_string)); + used +} + +/// Drop resources no layer, mask effect, the brush alpha, the projection stencil, the mask brush or the environment uses (one undo step) +fn remove_unused(s: &mut Session, _: &Value) -> Result { + let used = images_in_use(s); let unused: Vec = s.doc.resources.keys().filter(|k| !used.contains(k)).cloned().collect(); if !unused.is_empty() { s.edit("Remove unused resources", |s| { @@ -363,6 +515,66 @@ mod tests { std::fs::remove_file(path).unwrap(); } + #[test] + fn a_renamed_image_stays_in_use_everywhere_it_was() { + let mut session = crate::sample_session(128, 32).unwrap(); + let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + let name = session.import_resource_bytes("photo.png", png).unwrap(); + crate::execute(&mut session, "layer.add.image", &json!({"name": name})).unwrap(); + session.tool.brush.alpha_image = Some(name.clone()); + + let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": name, "to": "stone"})).unwrap()["name"].as_str().unwrap().to_string(); + + assert_ne!(renamed, name); + assert!(renamed.ends_with(".png"), "the extension stays: {renamed}"); + let used = images_in_use(&session); + assert!(used.contains(&renamed) && !used.contains(&name), "every use follows the rename: {used:?}"); + assert!(session.images.contains_key(&renamed) && !session.images.contains_key(&name)); + + session.undo().unwrap(); + + assert!(project_images(&session.doc.project).contains(&name), "undo brings the old name back"); + assert!(session.images.contains_key(&name)); + assert_eq!(session.tool.brush.alpha_image.as_ref(), Some(&name), "the brush alpha follows the undo"); + + session.redo().unwrap(); + + assert_eq!(session.tool.brush.alpha_image.as_ref(), Some(&renamed), "the brush alpha follows the redo"); + } + + #[test] + fn reloading_reads_the_file_again_and_undo_restores_the_pixels() { + let mut session = crate::sample_session(128, 32).unwrap(); + let path = std::env::temp_dir().join(format!("texturecraft-reload-resource-{}.png", std::process::id())); + std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.2].into_iter()).unwrap()).unwrap(); + let name = crate::execute(&mut session, "resource.import", &json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + let before = session.images[&name].rgba.clone(); + std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.8].into_iter()).unwrap()).unwrap(); + + crate::execute(&mut session, "resource.reload", &json!({"name": name})).unwrap(); + let reloaded = session.images[&name].rgba.clone(); + session.undo().unwrap(); + + assert_ne!(reloaded, before, "reload decodes the file's new pixels"); + assert_eq!(session.images[&name].rgba, before, "undo shows the old pixels again"); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn a_new_image_under_a_removed_ones_name_does_not_reload_its_file() { + let mut session = crate::sample_session(128, 32).unwrap(); + let path = std::env::temp_dir().join(format!("texturecraft-reused-name-{}.png", std::process::id())); + std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.2].into_iter()).unwrap()).unwrap(); + let name = crate::execute(&mut session, "resource.import", &json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + crate::execute(&mut session, "resource.remove", &json!({"name": name})).unwrap(); + + let reused = session.import_resource_bytes(&name, texturecraft_formats::gray16_png(1, 1, [0.6].into_iter()).unwrap()).unwrap(); + std::fs::remove_file(path).unwrap(); + + assert_eq!(reused, name, "the name is free again"); + assert!(session.resource_source(&reused).is_none(), "the new image has no file to reload from"); + } + #[test] fn file_reads_obey_the_remaining_byte_budget() { let path = std::env::temp_dir().join(format!("texturecraft-read-image-{}.png", std::process::id())); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 58b5cbe7..66b58d6f 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -462,6 +462,8 @@ pub struct Session { pub images: texturecraft_compose::ImageStore, /// Resource names whose decoded pixels match a library alpha. pub(crate) library_alphas: BTreeSet, + /// The file each image resource imported in this session came from, for Reload (not saved) + pub(crate) resource_sources: BTreeMap, /// 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 +549,7 @@ impl Session { blending_clipboard: None, images: Default::default(), library_alphas: BTreeSet::new(), + resource_sources: BTreeMap::new(), quick_mask: Default::default(), painting_paths: false, path_cache: None, @@ -983,6 +986,13 @@ impl Session { } fn after_history(&mut self, other: &Document) { + // A resource whose bytes the step changed (a reload) decodes again + self.images.retain(|name, _| match (other.resources.get(name), self.doc.resources.get(name)) { + (Some(left), Some(right)) => Arc::ptr_eq(left, right), + _ => true, + }); + self.follow_renamed_resources(other); + // Pending operations may still hold layer IDs from the discarded snapshot self.doc.project.next_id = self.doc.project.next_id.max(other.project.next_id); self.modified = true; @@ -1006,6 +1016,42 @@ impl Session { } } + /// The image names the tools and the 2D view read, which a resource rename follows + pub(crate) fn tool_images_mut(&mut self) -> impl Iterator { + [ + self.tool.stencil.as_mut().map(|stencil| &mut stencil.image), + self.tool.brush.alpha_image.as_mut(), + self.tool.mask_image.as_mut(), + self.view_image.as_mut(), + ] + .into_iter() + .flatten() + } + + /// Points tool images and reload sources at a resource's name on this side of an undone or redone rename + fn follow_renamed_resources(&mut self, other: &Document) { + let mut names: Vec = self.tool_images_mut().map(|name| name.clone()).collect(); + names.extend(self.resource_sources.keys().cloned()); + let renames: Vec<(String, String)> = names + .into_iter() + .filter(|name| !self.doc.resources.contains_key(name)) + .filter_map(|name| { + let bytes = other.resources.get(&name)?; + let to = self.doc.resources.iter().find(|(_, here)| Arc::ptr_eq(here, bytes)).map(|(here, _)| here.clone())?; + Some((name, to)) + }) + .collect(); + + for (name, to) in renames { + for tool_image in self.tool_images_mut().filter(|tool_image| **tool_image == name) { + tool_image.clone_from(&to); + } + if let Some(source) = self.resource_sources.remove(&name) { + self.resource_sources.insert(to, source); + } + } + } + // ----------------------------------------------------------------------------------------- // Compositing diff --git a/crates/ui-egui/src/shelf_menu.rs b/crates/ui-egui/src/shelf_menu.rs index 35a7ba49..cd3d8e8e 100644 --- a/crates/ui-egui/src/shelf_menu.rs +++ b/crates/ui-egui/src/shelf_menu.rs @@ -41,15 +41,20 @@ pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &Shelf ui.set_width(width); let column = label_column(ui, &info); - // A saved brush is the user's own: its Name row is a field that renames it + // A saved brush or a project image is the user's own: its Name row is a field that renames it let mut shown_info = info.as_slice(); - if let ShelfEntry::SavedBrush { name, .. } = entry + let rename = match entry { + ShelfEntry::SavedBrush { name, .. } => Some((name.as_str(), "brush.preset.rename")), + ShelfEntry::Image(name) => Some((name.as_str(), "resource.rename")), + _ => None, + }; + if let Some((name, command)) = rename && let Some((_, rest)) = info.split_first() { shown_info = rest; let field_id = ui.make_persistent_id(("asset_name", entry.identity())); if let Some(renamed) = name_field(ui, width, column, field_id, name, &tokens) { - app.run("brush.preset.rename", json!({"name": name, "to": renamed})); + app.run(command, json!({"name": name, "to": renamed})); } } info_block(ui, width, column, shown_info, &tokens); @@ -57,6 +62,15 @@ pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &Shelf match entry { ShelfEntry::Image(name) => { + let reloadable = app.session.reloadable(name); + let reload = row(ui, width, tr("Reload"), reloadable, &tokens); + if reload.clicked() { + app.run("resource.reload", json!({"name": name})); + ui.close(); + } + if !reloadable { + reload.on_hover_text(tr("Imported before this session: no file to reload from")); + } if row(ui, width, tr("Delete"), true, &tokens).clicked() { app.run("resource.remove", json!({"name": name})); ui.close(); @@ -115,7 +129,7 @@ fn info_rows(entry: &ShelfEntry) -> Vec<(&'static str, String)> { fn row_labels(entry: &ShelfEntry) -> Vec<&'static str> { let mut labels = vec![tr("Export resource..."), tr("Close")]; match entry { - ShelfEntry::Image(_) => labels.extend([tr("Delete"), tr("Add as decal (view center)")]), + ShelfEntry::Image(_) => labels.extend([tr("Reload"), tr("Delete"), tr("Add as decal (view center)")]), ShelfEntry::SavedBrush { .. } => labels.extend([tr("Replace with the current brush"), tr("Delete")]), _ => {} } diff --git a/crates/ui-egui/tests/it/shelf_menu.rs b/crates/ui-egui/tests/it/shelf_menu.rs index 51b7bdae..b1db8921 100644 --- a/crates/ui-egui/tests/it/shelf_menu.rs +++ b/crates/ui-egui/tests/it/shelf_menu.rs @@ -127,3 +127,21 @@ fn delete_removes_a_project_image() { assert!(!harness.state().session.doc.resources.contains_key(&name)); } + +#[test] +fn a_project_image_menu_renames_it_and_reloads_only_a_file_from_this_session() { + let mut harness = shelf(TEXTURES_TYPE); + let mut bytes = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([180, 90, 40, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = harness.state_mut().session.import_resource_bytes("plate.png", bytes).unwrap(); + harness.run_steps(3); + + right_click(&mut harness, &name); + assert!(harness.get_by_label("Reload").accesskit_node().is_disabled(), "an image without a file from this session can't reload"); + type_name(&mut harness, "stone"); + harness.key_press(Key::Enter); + harness.run_steps(3); + + let resources = &harness.state().session.doc.resources; + assert!(resources.contains_key("stone.png") && !resources.contains_key(&name), "Enter renames the image, keeping its extension"); +} From fffe60a08608e4d2a84a0c396e9035c0e2de094a Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:45:53 +0000 Subject: [PATCH 04/16] Assets: Show in submenu and keyboard opening for the asset menu Show in opens a submenu with the file manager's own item (Explorer, Finder, file manager), which shows the folder of a saved brush's file or of the file a project image was imported from in this session. The row is greyed, with the reason, for built-in assets and images with no file. Shift+F10 or the Menu key opens the menu on the focused tile, and Escape gives the focus back to it. --- .../src/brush_preset_cmds/user_brushes.rs | 6 + crates/engine/src/resource_cmds.rs | 6 +- crates/ui-egui/src/shelf_menu.rs | 125 ++++++++++++++++-- crates/ui-egui/tests/it/shelf_menu.rs | 48 +++++++ 4 files changed, 172 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/brush_preset_cmds/user_brushes.rs b/crates/engine/src/brush_preset_cmds/user_brushes.rs index 921df2d5..3acb6712 100644 --- a/crates/engine/src/brush_preset_cmds/user_brushes.rs +++ b/crates/engine/src/brush_preset_cmds/user_brushes.rs @@ -45,6 +45,12 @@ impl UserBrushes { self.dir.as_ref().map(|directory| directory.join(format!("{}.{BRUSH_EXT}", sanitize_file_stem(name.trim())))) } + /// The file user preset `name` is mirrored to (None: no such preset, or the presets live in memory only) + pub fn file_for(&self, name: &str) -> Option { + let preset = self.list.get(self.find(name)?)?; + preset.file.clone().or_else(|| self.file_of(&preset.name)) + } + /// The file a preset named `name` that was never written would have. #[cfg(not(target_arch = "wasm32"))] pub(super) fn file_of(&self, name: &str) -> Option { diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index da51b8ea..df7d16ff 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -121,9 +121,9 @@ impl Session { Ok(name) } - /// Whether image resource `name` was imported from a file in this session, so `resource.reload` can read it again - pub fn reloadable(&self, name: &str) -> bool { - self.resource_sources.contains_key(name) + /// The file image resource `name` was imported from in this session (what `resource.reload` reads again) + pub fn resource_source(&self, name: &str) -> Option<&std::path::Path> { + self.resource_sources.get(name).map(std::path::PathBuf::as_path) } /// Decode resources that are not decoded yet and forget removed ones (after undo, redo, load). diff --git a/crates/ui-egui/src/shelf_menu.rs b/crates/ui-egui/src/shelf_menu.rs index cd3d8e8e..3c5cb160 100644 --- a/crates/ui-egui/src/shelf_menu.rs +++ b/crates/ui-egui/src/shelf_menu.rs @@ -1,10 +1,10 @@ //! An asset tile's right-click menu: what the asset is (name, usages, path, category), then what can be done with it; the Name of an asset the user owns is a field that renames it -use egui::{Align2, Color32, CornerRadius, FontId, Response, Sense, Ui, pos2, vec2}; +use egui::{Align2, Color32, CornerRadius, FontId, Id, Response, Sense, Ui, pos2, vec2}; use serde_json::json; use crate::TextureCraftApp; -use crate::i18n::tr; +use crate::i18n::{n_, tr}; use crate::shelf_entry::{LIBRARIES, ShelfEntry}; use crate::theme::Tokens; @@ -29,10 +29,36 @@ const FIELD_TEXT_INSET: f32 = 8.0; /// The air above and below the separators, in points const SEPARATOR_SPACE: f32 = 3.0; +/// A menu just opened from the keyboard gives the focus to its first row that can be picked (ctx temp data) +const FOCUS_FIRST_ROW: &str = "shelf_menu_focus_first_row"; + /// The right-click menu on the tile whose response is `response` pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &ShelfEntry) { // Clicks inside keep the menu open, so the Name field can be typed in; its rows close it themselves - let menu = egui::Popup::context_menu(response).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); + let mut menu = egui::Popup::context_menu(response).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); + response.ctx.accesskit_node_builder(response.id, |node| node.set_has_popup(egui::accesskit::HasPopup::Menu)); + + // The keyboard opens it on the focused tile, and Escape gives the focus back to the tile + let keyboard_id = response.id.with("menu_from_keyboard"); + let return_focus = menu.is_open() && response.ctx.input(|input| input.key_pressed(egui::Key::Escape)); + if response.has_focus() + && response + .ctx + .input_mut(|input| input.consume_key(egui::Modifiers::SHIFT, egui::Key::F10) || input.consume_key(egui::Modifiers::NONE, egui::Key::Menu)) + { + menu = menu.open_memory(Some(egui::SetOpenCommand::Bool(true))); + response.ctx.data_mut(|data| { + data.insert_temp(keyboard_id, true); + data.insert_temp(Id::unique(FOCUS_FIRST_ROW), true); + }); + } else if response.secondary_clicked() { + response.ctx.data_mut(|data| data.remove::(keyboard_id)); + } + + // A menu opened from the keyboard has no pointer position to open at: it opens at the tile + if response.ctx.data(|data| data.get_temp::(keyboard_id)).unwrap_or_default() { + menu = menu.anchor(response); + } menu.show(|ui| { let tokens = Tokens::get(ui.ctx()); ui.spacing_mut().item_spacing = vec2(0.0, 0.0); @@ -62,7 +88,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &Shelf match entry { ShelfEntry::Image(name) => { - let reloadable = app.session.reloadable(name); + let reloadable = app.session.resource_source(name).is_some(); let reload = row(ui, width, tr("Reload"), reloadable, &tokens); if reload.clicked() { app.run("resource.reload", json!({"name": name})); @@ -80,11 +106,6 @@ pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &Shelf export_image(app, name); ui.close(); } - separator(ui, &tokens); - if row(ui, width, tr("Add as decal (view center)"), true, &tokens).clicked() { - app.run("layer.add.decal", json!({"image": name})); - ui.close(); - } } ShelfEntry::SavedBrush { name, .. } => { if row(ui, width, tr("Replace with the current brush"), true, &tokens).clicked() { @@ -105,12 +126,23 @@ pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &Shelf row(ui, width, tr("Export resource..."), false, &tokens).on_hover_text(tr("Built-in assets have no file to export")); } } + show_in(app, ui, width, entry, &tokens); + if let ShelfEntry::Image(name) = entry { + separator(ui, &tokens); + if row(ui, width, tr("Add as decal (view center)"), true, &tokens).clicked() { + app.run("layer.add.decal", json!({"image": name})); + ui.close(); + } + } separator(ui, &tokens); if row(ui, width, tr("Close"), true, &tokens).clicked() { ui.close(); } }); + if return_focus { + response.request_focus(); + } } /// The info block's label and value rows: rows only where the asset has the data @@ -127,7 +159,7 @@ fn info_rows(entry: &ShelfEntry) -> Vec<(&'static str, String)> { /// The labels of the rows under the info block, for the menu's width fn row_labels(entry: &ShelfEntry) -> Vec<&'static str> { - let mut labels = vec![tr("Export resource..."), tr("Close")]; + let mut labels = vec![tr("Export resource..."), tr("Show in"), tr("Close")]; match entry { ShelfEntry::Image(_) => labels.extend([tr("Reload"), tr("Delete"), tr("Add as decal (view center)")]), ShelfEntry::SavedBrush { .. } => labels.extend([tr("Replace with the current brush"), tr("Delete")]), @@ -229,11 +261,84 @@ fn separator(ui: &mut Ui, tokens: &Tokens) { ui.painter().hline(rect.x_range(), rect.center().y, egui::Stroke::new(1.0, tokens.separator)); } +/// The file manager's own name for showing a file in it +fn show_in_folder_label() -> &'static str { + if cfg!(target_os = "windows") { + tr("Show in Explorer...") + } else if cfg!(target_os = "macos") { + tr("Show in Finder...") + } else { + tr("Show in file manager...") + } +} + +/// The Show in row: a submenu that opens the folder of the asset's file, greyed for an asset with no file on this computer +fn show_in(app: &mut TextureCraftApp, ui: &mut Ui, width: f32, entry: &ShelfEntry, tokens: &Tokens) { + let file = match entry { + ShelfEntry::SavedBrush { name, .. } => app.session.brush_presets.file_for(name), + ShelfEntry::Image(name) => app.session.resource_source(name).map(std::path::Path::to_path_buf), + _ => None, + }; + let folder = file.as_deref().and_then(std::path::Path::parent).filter(|folder| folder.is_dir()).map(std::path::Path::to_path_buf); + + // Reserved under the row, so the row stays highlighted while its submenu is open + let open_highlight = ui.painter().add(egui::Shape::Noop); + let response = row(ui, width, tr("Show in"), folder.is_some(), tokens); + let caret_color = if folder.is_some() { tokens.text } else { tokens.text_dim }; + ui.painter().text( + pos2(response.rect.right() - TEXT_X, response.rect.center().y), + Align2::RIGHT_CENTER, + egui_phosphor::regular::CARET_RIGHT, + FontId::proportional(TEXT_SIZE), + caret_color, + ); + let Some(folder) = folder else { + let reason = match (file.is_some(), entry) { + (true, _) => n_("The folder of this asset's file is gone"), + (false, ShelfEntry::Image(_)) => n_("Imported before this session: no file to show"), + (false, ShelfEntry::SavedBrush { .. }) => n_("This brush isn't saved to a file"), + (false, _) => n_("Built-in assets have no file to show"), + }; + + response.on_hover_text(tr(reason)); + return; + }; + + let submenu = egui::containers::menu::SubMenu::new().show(ui, &response, |ui| { + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + let label = show_in_folder_label(); + let submenu_width = text_width(ui, label) + TEXT_X + RIGHT_PADDING; + if row(ui, submenu_width, label, true, tokens).clicked() { + open_folder(app, &folder); + ui.close(); + } + }); + if submenu.is_some() { + let highlight = egui::Shape::rect_filled(response.rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::same(HOVER_ROUNDING), tokens.button); + ui.painter().set(open_highlight, highlight); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn open_folder(app: &mut TextureCraftApp, folder: &std::path::Path) { + if let Err(error) = app.file_dialogs.show_folder(folder) { + app.toast(crate::i18n::trf("Could not open the folder: {error}", &[("error", &error)]), true); + } +} + +#[cfg(target_arch = "wasm32")] +fn open_folder(app: &mut TextureCraftApp, _: &std::path::Path) { + app.toast(tr("Showing files needs the desktop app"), true); +} + /// One menu row: a hover face inset from the sides, its text dim and unclickable when not `enabled` fn row(ui: &mut Ui, width: f32, label: &str, enabled: bool, tokens: &Tokens) -> Response { let sense = if enabled { Sense::click() } else { Sense::hover() }; let (rect, response) = ui.allocate_exact_size(vec2(width, ROW_HEIGHT), sense); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, label)); + if enabled && ui.data_mut(|data| data.remove_temp::(Id::unique(FOCUS_FIRST_ROW))).unwrap_or_default() { + response.request_focus(); + } let painter = ui.painter(); if enabled && (response.hovered() || response.has_focus()) { painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::same(HOVER_ROUNDING), tokens.button); diff --git a/crates/ui-egui/tests/it/shelf_menu.rs b/crates/ui-egui/tests/it/shelf_menu.rs index b1db8921..242acb0c 100644 --- a/crates/ui-egui/tests/it/shelf_menu.rs +++ b/crates/ui-egui/tests/it/shelf_menu.rs @@ -44,6 +44,7 @@ fn a_built_in_tile_menu_says_what_the_asset_is_and_where_it_lives() { assert!(harness.query_by_label(&row).is_some(), "the menu has the info row {row:?}"); } assert!(harness.get_by_label("Export resource...").accesskit_node().is_disabled(), "a built-in has no file to export"); + assert!(harness.get_by_label("Show in").accesskit_node().is_disabled(), "a built-in has no file to show"); harness.get_by_label("Close").click(); harness.run_steps(3); @@ -145,3 +146,50 @@ fn a_project_image_menu_renames_it_and_reloads_only_a_file_from_this_session() { let resources = &harness.state().session.doc.resources; assert!(resources.contains_key("stone.png") && !resources.contains_key(&name), "Enter renames the image, keeping its extension"); } + +#[test] +fn show_in_opens_the_folder_of_a_saved_brush() { + let dir = super::temp_dir::TempDir::new("shelf-show-in"); + let mut harness = shelf(BRUSHES_TYPE); + harness.state_mut().session.brush_presets.dir = Some(dir.to_path_buf()); + texturecraft_engine::execute(&mut harness.state_mut().session, "brush.preset.store", &json!({"name": "Aa ink"})).unwrap(); + harness.run_steps(3); + + right_click(&mut harness, "Aa ink"); + harness.get_by_label("Show in").click(); + harness.run_steps(3); + let item = if cfg!(target_os = "windows") { + "Show in Explorer..." + } else if cfg!(target_os = "macos") { + "Show in Finder..." + } else { + "Show in file manager..." + }; + harness.get_by_label(item).click(); + harness.run_steps(3); + + let shown = harness.state().file_dialogs.shown_folders().to_vec(); + assert!(shown.iter().any(|folder| folder.canonicalize().ok() == dir.canonicalize().ok()), "the brush's folder is shown: {shown:?}"); +} + +#[test] +fn shift_f10_opens_the_menu_of_the_focused_tile_on_its_first_row_and_escape_returns_to_it() { + let mut harness = shelf(TEXTURES_TYPE); + let mut bytes = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([180, 90, 40, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = harness.state_mut().session.import_resource_bytes("plate.png", bytes).unwrap(); + harness.run_steps(3); + + harness.get_all_by_label(&name).next().unwrap().focus(); + harness.run_steps(2); + assert!(harness.get_all_by_label(&name).next().unwrap().is_focused(), "the tile takes the focus"); + harness.key_press_modifiers(Modifiers::SHIFT, Key::F10); + harness.run_steps(3); + assert!(harness.query_by_label("Usages texture").is_some(), "Shift+F10 opens the menu"); + assert!(harness.get_by_label("Delete").is_focused(), "the first row that can be picked takes the focus (Reload can't: no file)"); + + harness.key_press(Key::Escape); + harness.run_steps(3); + assert!(harness.query_by_label("Usages texture").is_none(), "Escape closes it"); + assert!(harness.get_all_by_label(&name).next().unwrap().accesskit_node().is_focused(), "the focus is back on the tile"); +} From 6015c6691c10f6280fa7fe50ad32c7803ad9419f Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:49:38 +0000 Subject: [PATCH 05/16] Assets: favorites with a star, first in their type, and the Favorites saved search Add to favorites / Remove from favorites in the asset menu. Favorites show a star at the thumbnail's top-right, come first in their type (the newest first), are kept in the UI settings, and the Favorites saved search shows only them. --- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/shelf.rs | 20 +++++-- crates/ui-egui/src/shelf_favorite.rs | 78 ++++++++++++++++++++++++++ crates/ui-egui/src/shelf_menu.rs | 11 +++- crates/ui-egui/src/shelf_panes.rs | 33 ++++++++--- crates/ui-egui/src/shelf_toolbar.rs | 1 + crates/ui-egui/src/state.rs | 20 ++++++- crates/ui-egui/tests/it/shelf_menu.rs | 35 ++++++++++++ crates/ui-egui/tests/it/shelf_panel.rs | 30 +++++++++- 9 files changed, 212 insertions(+), 17 deletions(-) create mode 100644 crates/ui-egui/src/shelf_favorite.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ab8d1b99..f9b379a3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -138,6 +138,7 @@ pub mod settings_window; pub mod shader_settings; pub mod shelf; mod shelf_entry; +pub mod shelf_favorite; mod shelf_folders; mod shelf_menu; pub mod shelf_panes; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 9099a2f9..2c32f595 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -273,6 +273,10 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { Vec::new() }; + if app.ui.shelf_favorites_only { + matching.retain(|entry| crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some()); + } + // All libraries includes every result without constructing an asset path if !folder.is_empty() { matching.retain(|entry| entry.in_folder(&folder)); @@ -280,8 +284,9 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let mut counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); - // Saved smart materials and masks count toward their tabs even without tiles - let in_user_library = folder.len() <= 1 && folder.first().is_none_or(|library| library == crate::shelf_entry::USER); + // Saved smart materials and masks count toward their tabs even without tiles; they can't be favorites yet + let favorites_only = app.ui.shelf_favorites_only; + let in_user_library = !favorites_only && folder.len() <= 1 && folder.first().is_none_or(|library| library == crate::shelf_entry::USER); let saved_materials_matching = saved_matching(app, &filter, false); let saved_masks_matching = saved_matching(app, &filter, true); for (tab, saved) in [(Tab::Smart, saved_materials_matching), (Tab::Masks, saved_masks_matching)] { @@ -300,11 +305,14 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let tab = app.ui.shelf_tab; let shown_tab = TABS.get(tab).map(|(shown, _, _)| *shown); - let show_user_brushes = crate::shelf_tabs::shows(tab, Tab::Brushes) + let show_user_brushes = !favorites_only + && crate::shelf_tabs::shows(tab, Tab::Brushes) && folder.len() <= 2 && folder.iter().zip([crate::shelf_entry::USER, "Brushes"]).all(|(selected, part)| selected == part); let mut entries: Vec = matching.into_iter().filter(|entry| crate::shelf_tabs::shows(tab, entry.tab())).collect(); - entries.sort_by_cached_key(|entry| entry.label().to_lowercase()); + // Favorites first, the most recently added first, then by name + let favorites = &app.ui.shelf_favorites; + entries.sort_by_cached_key(|entry| (crate::shelf_favorite::rank(favorites, entry).unwrap_or(usize::MAX), entry.label().to_lowercase())); // The toolbar has its own strip at the panel's bottom, so nothing above it can push it out let area = ui.available_rect_before_wrap(); @@ -548,6 +556,10 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry if entry.includes_randomness() { randomness_badge(ui.painter(), view.thumbnail_rect(response.rect)); } + if crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some() { + crate::shelf_favorite::star(ui.painter(), view.thumbnail_rect(response.rect), Tokens::get(ctx).warning); + ctx.accesskit_node_builder(response.id, |node| node.set_description(tr("Favorite"))); + } if response.clicked() || response.secondary_clicked() { let (kind, id) = entry.identity(); diff --git a/crates/ui-egui/src/shelf_favorite.rs b/crates/ui-egui/src/shelf_favorite.rs new file mode 100644 index 00000000..c3ef0674 --- /dev/null +++ b/crates/ui-egui/src/shelf_favorite.rs @@ -0,0 +1,78 @@ +//! An asset the user marked as a favorite in the Assets panel: it shows a star and comes first in its type + +use egui::{Color32, Painter, Pos2, Rect, Shape, Stroke, epaint::Mesh, vec2}; +use serde::{Deserialize, Serialize}; + +use crate::shelf_entry::ShelfEntry; + +/// The star's outer and inner radius and its centre's inset from the thumbnail's top-right corner, in points +const STAR_OUTER_RADIUS: f32 = 5.5; +const STAR_INNER_RADIUS: f32 = 2.4; +const STAR_INSET: f32 = 4.0; +/// The offset and colour of the star's shadow, which keeps it readable on light thumbnails +const STAR_SHADOW_OFFSET: f32 = 1.0; +const STAR_SHADOW: Color32 = Color32::from_black_alpha(170); +const STAR_POINTS: usize = 5; +/// The width of the outline that smooths the star's edges (a mesh has no anti-aliasing), in points +const STAR_EDGE_WIDTH: f32 = 0.6; + +/// A favorite asset by its [`ShelfEntry::identity`] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ShelfFavorite { + pub kind: String, + pub id: String, +} + +impl ShelfFavorite { + fn is(&self, entry: &ShelfEntry) -> bool { + let (kind, id) = entry.identity(); + self.kind == kind && self.id == id + } +} + +/// Where `entry` is in `favorites` (most recently added first), or None if it isn't one +pub(crate) fn rank(favorites: &[ShelfFavorite], entry: &ShelfEntry) -> Option { + favorites.iter().position(|favorite| favorite.is(entry)) +} + +/// Adds `entry` in front of `favorites`, or removes it if it is one +pub(crate) fn toggle(favorites: &mut Vec, entry: &ShelfEntry) { + if let Some(index) = rank(favorites, entry) { + favorites.remove(index); + return; + } + + let (kind, id) = entry.identity(); + favorites.insert(0, ShelfFavorite { kind: kind.to_owned(), id: id.to_owned() }); +} + +/// A filled star in `color` at the thumbnail's top-right corner, over a dark shadow +pub(crate) fn star(painter: &Painter, thumbnail: Rect, color: Color32) { + let center = thumbnail.right_top() + vec2(-STAR_INSET, STAR_INSET); + star_shape(painter, center + vec2(STAR_SHADOW_OFFSET, STAR_SHADOW_OFFSET), STAR_SHADOW); + star_shape(painter, center, color); +} + +/// A five-pointed star around `center`, point up: a triangle fan from the centre, outlined in its colour +fn star_shape(painter: &Painter, center: Pos2, color: Color32) { + let corner_count = STAR_POINTS * 2; + let corners: Vec = (0..corner_count) + .map(|corner| { + let radius = if corner % 2 == 0 { STAR_OUTER_RADIUS } else { STAR_INNER_RADIUS }; + let angle = corner as f32 * std::f32::consts::TAU / corner_count as f32 - std::f32::consts::FRAC_PI_2; + center + radius * vec2(angle.cos(), angle.sin()) + }) + .collect(); + + let mut mesh = Mesh::default(); + mesh.colored_vertex(center, color); + for corner in &corners { + mesh.colored_vertex(*corner, color); + } + let last = corner_count as u32; + for corner in 1..=last { + mesh.add_triangle(0, corner, corner % last + 1); + } + painter.add(Shape::mesh(mesh)); + painter.add(Shape::closed_line(corners, Stroke::new(STAR_EDGE_WIDTH, color))); +} diff --git a/crates/ui-egui/src/shelf_menu.rs b/crates/ui-egui/src/shelf_menu.rs index 3c5cb160..c486a0df 100644 --- a/crates/ui-egui/src/shelf_menu.rs +++ b/crates/ui-egui/src/shelf_menu.rs @@ -127,6 +127,10 @@ pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &Shelf } } show_in(app, ui, width, entry, &tokens); + if row(ui, width, favorite_label(app, entry), true, &tokens).clicked() { + crate::shelf_favorite::toggle(&mut app.ui.shelf_favorites, entry); + ui.close(); + } if let ShelfEntry::Image(name) = entry { separator(ui, &tokens); if row(ui, width, tr("Add as decal (view center)"), true, &tokens).clicked() { @@ -159,7 +163,7 @@ fn info_rows(entry: &ShelfEntry) -> Vec<(&'static str, String)> { /// The labels of the rows under the info block, for the menu's width fn row_labels(entry: &ShelfEntry) -> Vec<&'static str> { - let mut labels = vec![tr("Export resource..."), tr("Show in"), tr("Close")]; + let mut labels = vec![tr("Export resource..."), tr("Show in"), tr("Add to favorites"), tr("Remove from favorites"), tr("Close")]; match entry { ShelfEntry::Image(_) => labels.extend([tr("Reload"), tr("Delete"), tr("Add as decal (view center)")]), ShelfEntry::SavedBrush { .. } => labels.extend([tr("Replace with the current brush"), tr("Delete")]), @@ -168,6 +172,11 @@ fn row_labels(entry: &ShelfEntry) -> Vec<&'static str> { labels } +/// The row that adds the asset to the favorites, or takes a favorite out +fn favorite_label(app: &TextureCraftApp, entry: &ShelfEntry) -> &'static str { + if crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some() { tr("Remove from favorites") } else { tr("Add to favorites") } +} + fn text_width(ui: &Ui, text: &str) -> f32 { ui.fonts_mut(|fonts| fonts.layout_no_wrap(text.to_owned(), FontId::proportional(TEXT_SIZE), Color32::WHITE).size().x) } diff --git a/crates/ui-egui/src/shelf_panes.rs b/crates/ui-egui/src/shelf_panes.rs index 96f5c25f..118d9bc4 100644 --- a/crates/ui-egui/src/shelf_panes.rs +++ b/crates/ui-egui/src/shelf_panes.rs @@ -17,8 +17,10 @@ const COLUMN_FRACTION: f32 = 0.45; const COLUMN_MIN_WIDTH_POINTS: f32 = 110.0; const SPLITTER_HEIGHT_POINTS: f32 = 6.0; const PANE_MIN_HEIGHT_POINTS: f32 = 40.0; -/// The reference's built-in saved searches after "All", shown greyed until they work -const BUILT_IN_SEARCHES: [&str; 3] = [n_("Favorites"), n_("3D Assets"), n_("Flattened layers")]; +/// The built-in saved search after "All" that shows only the favorite assets +const FAVORITES: &str = n_("Favorites"); +/// The reference's other built-in saved searches, shown greyed until they work +const UNAVAILABLE_SEARCHES: [&str; 2] = [n_("3D Assets"), n_("Flattened layers")]; /// The reference's font libraries after the asset libraries, shown greyed until they work const FONT_LIBRARIES: [&str; 2] = [n_("System fonts"), n_("User fonts")]; /// The pane header's caption size in points @@ -191,7 +193,12 @@ fn header(ui: &mut Ui, title: &str, button: impl FnOnce(&mut Ui)) { }); } -/// "All", then the saved queries; the header's button saves the current one, a right-click deletes one +/// Saved searches' first rows: "All", then Favorites, then the searches that aren't available +const ALL_ROW: usize = 0; +const FAVORITES_ROW: usize = 1; +const FIXED_SEARCH_ROWS: usize = 2; + +/// "All", Favorites, then the saved queries; the header's button saves the current one, a right-click deletes one fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { let size = ui.spacing().interact_size.y; header(ui, tr("Saved searches"), |ui| { @@ -203,8 +210,9 @@ fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { } }); - let all_selected = app.ui.shelf_filter.is_empty() && app.ui.shelf_path.is_empty() && app.ui.shelf_tab == crate::shelf_tabs::NO_TYPE; - let first_saved_row = 1 + BUILT_IN_SEARCHES.len(); + let favorites_only = app.ui.shelf_favorites_only; + let all_selected = !favorites_only && app.ui.shelf_filter.is_empty() && app.ui.shelf_path.is_empty() && app.ui.shelf_tab == crate::shelf_tabs::NO_TYPE; + let first_saved_row = FIXED_SEARCH_ROWS + UNAVAILABLE_SEARCHES.len(); let row_height = ui.spacing().interact_size.y; let total_rows = first_saved_row + app.ui.shelf_saved_searches.len(); let mut deleted_index = None; @@ -216,14 +224,22 @@ fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { total_rows, |ui, visible_rows| { for row in visible_rows { - if row == 0 { + if row == ALL_ROW { if ui.selectable_label(all_selected, tr("All")).clicked() { crate::shelf_toolbar::reset_query(app); } continue; } - if let Some(name) = BUILT_IN_SEARCHES.get(row - 1) { + if row == FAVORITES_ROW { + if ui.selectable_label(favorites_only, tr(FAVORITES)).clicked() { + crate::shelf_toolbar::reset_query(app); + app.ui.shelf_favorites_only = true; + } + continue; + } + + if let Some(name) = UNAVAILABLE_SEARCHES.get(row - FIXED_SEARCH_ROWS) { ui.add_enabled(false, egui::Button::selectable(false, tr(name))).on_disabled_hover_text(tr(NOT_AVAILABLE)); continue; } @@ -231,10 +247,11 @@ fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { let saved_index = row - first_saved_row; let Some(saved) = app.ui.shelf_saved_searches.get(saved_index) else { continue }; - let selected = saved.filter == app.ui.shelf_filter && saved.tab == app.ui.shelf_tab && saved.path == app.ui.shelf_path; + let selected = !favorites_only && saved.filter == app.ui.shelf_filter && saved.tab == app.ui.shelf_tab && saved.path == app.ui.shelf_path; let response = ui.selectable_label(selected, &saved.name); if response.clicked() { (app.ui.shelf_filter, app.ui.shelf_tab, app.ui.shelf_path) = (saved.filter.clone(), saved.tab, saved.path.clone()); + app.ui.shelf_favorites_only = false; } response.context_menu(|ui| { diff --git a/crates/ui-egui/src/shelf_toolbar.rs b/crates/ui-egui/src/shelf_toolbar.rs index a8708685..c7c00b81 100644 --- a/crates/ui-egui/src/shelf_toolbar.rs +++ b/crates/ui-egui/src/shelf_toolbar.rs @@ -40,6 +40,7 @@ pub(crate) fn reset_query(app: &mut TextureCraftApp) { app.ui.shelf_filter.clear(); app.ui.shelf_tab = crate::shelf_tabs::NO_TYPE; app.ui.shelf_path.clear(); + app.ui.shelf_favorites_only = false; } /// Read the user's saved assets from disk again and redraw their thumbnails diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0c767e1b..d51db221 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -6,6 +6,7 @@ use texturecraft_engine::core::{BakedMap, Channel, ChannelBlend, NormalFormat}; use crate::docking::Dock; use crate::keymap::Keymap; use crate::saved_search::SavedSearch; +use crate::shelf_favorite::ShelfFavorite; use crate::shelf_panes::ShelfPanes; use crate::shelf_view::ShelfView; @@ -585,6 +586,12 @@ pub struct UiState { /// The asset shelf's saved queries, in the order they were saved #[serde(default)] pub shelf_saved_searches: Vec, + /// The asset shelf's favorite assets, most recently added first + #[serde(default)] + pub shelf_favorites: Vec, + /// The asset shelf shows only favorites (the Favorites saved search) + #[serde(default)] + pub shelf_favorites_only: bool, /// Saved searches' share of the pane column above Filter by path, set by the splitter between them #[serde(default = "default_shelf_panes_split", deserialize_with = "deserialize_shelf_panes_split")] pub shelf_panes_split: f32, @@ -741,6 +748,8 @@ impl UiState { self.shelf_tab = keep.shelf_tab; self.shelf_path = keep.shelf_path; self.shelf_saved_searches = keep.shelf_saved_searches; + self.shelf_favorites = keep.shelf_favorites; + self.shelf_favorites_only = keep.shelf_favorites_only; } } @@ -775,6 +784,8 @@ impl Default for UiState { shelf_view: ShelfView::default(), shelf_panes: ShelfPanes::default(), shelf_saved_searches: Vec::new(), + shelf_favorites: Vec::new(), + shelf_favorites_only: false, shelf_panes_split: default_shelf_panes_split(), props_tab: PropsTab::Brush, text: TextUi::default(), @@ -902,15 +913,20 @@ mod tests { } #[test] - fn adopting_a_layout_keeps_the_shelf_query_and_saved_searches() { + fn adopting_a_layout_keeps_the_shelf_query_saved_searches_and_favorites() { let saved = crate::saved_search::SavedSearch { name: "rust".into(), filter: "rust".into(), tab: 2, path: vec!["starter".into()] }; - let mut ui = UiState { shelf_filter: "rust".into(), shelf_tab: 2, shelf_path: vec!["starter".into()], ..UiState::default() }; + let favorite = crate::shelf_favorite::ShelfFavorite { kind: "material".into(), id: "gold".into() }; + let mut ui = + UiState { shelf_filter: "rust".into(), shelf_tab: 2, shelf_path: vec!["starter".into()], shelf_favorites_only: true, ..UiState::default() }; ui.shelf_saved_searches.push(saved.clone()); + ui.shelf_favorites.push(favorite.clone()); ui.adopt_layout(UiState::default()); assert_eq!((ui.shelf_filter.as_str(), ui.shelf_tab, ui.shelf_path.as_slice()), ("rust", 2, ["starter".to_string()].as_slice())); assert_eq!(ui.shelf_saved_searches, [saved]); + assert_eq!(ui.shelf_favorites, [favorite], "favorites are the user's own too"); + assert!(ui.shelf_favorites_only, "the Favorites search is part of the query"); } #[test] diff --git a/crates/ui-egui/tests/it/shelf_menu.rs b/crates/ui-egui/tests/it/shelf_menu.rs index 242acb0c..4cd920d6 100644 --- a/crates/ui-egui/tests/it/shelf_menu.rs +++ b/crates/ui-egui/tests/it/shelf_menu.rs @@ -193,3 +193,38 @@ fn shift_f10_opens_the_menu_of_the_focused_tile_on_its_first_row_and_escape_retu assert!(harness.query_by_label("Usages texture").is_none(), "Escape closes it"); assert!(harness.get_all_by_label(&name).next().unwrap().accesskit_node().is_focused(), "the focus is back on the tile"); } + +/// Whether the tile `first` comes before the tile `second` in the grid (rows top to bottom, each left to right) +fn comes_before(harness: &Harness<'_, TextureCraftApp>, first: &str, second: &str) -> bool { + let place = |label: &str| { + let rect = harness.get_by_label(label).rect(); + (rect.top(), rect.left()) + }; + place(first) < place(second) +} + +fn pick_from_menu(harness: &mut Harness<'_, TextureCraftApp>, tile: &str, row: &str) { + right_click(harness, tile); + harness.get_by_label(row).click(); + harness.run_steps(3); +} + +#[test] +fn favorites_come_first_newest_first_with_a_star_until_removed() { + let mut plain: Vec<_> = MATERIALS.iter().filter(|material| !material.smart).collect(); + plain.sort_by_key(|material| material.label.to_lowercase()); + let (first, second, third) = (plain[0].label, plain[1].label, plain[2].label); + let mut harness = shelf(MATERIALS_TYPE); + + pick_from_menu(&mut harness, third, "Add to favorites"); + pick_from_menu(&mut harness, second, "Add to favorites"); + + assert!(comes_before(&harness, second, third) && comes_before(&harness, third, first), "favorites first, the newest first"); + assert_eq!(harness.get_by_label(second).accesskit_node().description().as_deref(), Some("Favorite"), "the star is announced"); + assert_eq!(harness.get_by_label(first).accesskit_node().description(), None); + + pick_from_menu(&mut harness, second, "Remove from favorites"); + + assert!(comes_before(&harness, first, second), "a removed favorite goes back to its place by name"); + assert!(comes_before(&harness, third, first), "the other favorite stays first"); +} diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index cbfdf687..7dcd12a4 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -385,10 +385,10 @@ fn the_panes_list_the_reference_rows_and_grey_the_missing_ones() { let tops: Vec = rows.iter().map(|label| latest_node_with_label(&harness, label).rect().top()).collect(); assert!(tops.windows(2).all(|pair| pair[0] < pair[1]), "{rows:?} run top to bottom: {tops:?}"); } - for label in ["Favorites", "3D Assets", "Flattened layers", "System fonts", "User fonts"] { + for label in ["3D Assets", "Flattened layers", "System fonts", "User fonts"] { assert!(latest_node_with_label(&harness, label).accesskit_node().is_disabled(), "{label} is greyed"); } - for label in ["All", "All libraries", "Project", "Starter assets", "Your assets"] { + for label in ["All", "Favorites", "All libraries", "Project", "Starter assets", "Your assets"] { assert!(!latest_node_with_label(&harness, label).accesskit_node().is_disabled(), "{label} works"); } assert!(shows_not_available(&mut harness, "Flattened layers"), "a greyed saved search explains itself"); @@ -516,3 +516,29 @@ fn the_splitter_is_exposed_as_a_resizable_control() { assert!(harness.state().ui.shelf_panes_split > before); } + +#[test] +fn the_favorites_search_shows_only_favorites_until_all_is_picked() { + let plain = plain_materials(); + let (favorite, other) = (plain[1].label, plain[0].label); + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.run_steps(3); + button(&harness, favorite).click_secondary(); + harness.run_steps(3); + button(&harness, "Add to favorites").click(); + harness.run_steps(3); + + button(&harness, "Favorites").click(); + harness.run_steps(3); + + assert!(harness.query_by_label(favorite).is_some(), "the favorite shows"); + assert!(harness.query_by_label(other).is_none(), "an asset that is no favorite is hidden"); + assert!(harness.query_by_label("My brushes").is_none(), "the saved brushes list is no favorite either"); + + button(&harness, "All").click(); + harness.run_steps(3); + + assert!(harness.query_by_label(other).is_some(), "All shows every asset again"); + assert!(harness.query_by_label("My brushes").is_some(), "All shows the saved brushes list again"); +} From 10e04cacb3d657529b81b124510683d0518a3ad9 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:52:40 +0000 Subject: [PATCH 06/16] Assets: Set custom preview... shows a picked picture on an asset's tile The asset menu's Set custom preview... asks for a picture; the tile shows its centred square instead of the rendered thumbnail until Remove custom preview. The pick is kept in the UI settings; a file that isn't a picture is refused with a message. --- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/shelf.rs | 4 +- crates/ui-egui/src/shelf_custom_preview.rs | 66 +++++++++++++++++ crates/ui-egui/src/shelf_menu.rs | 85 +++++++++++++++++++++- crates/ui-egui/src/state.rs | 11 ++- crates/ui-egui/src/thumbs.rs | 21 ++++++ crates/ui-egui/tests/it/shelf_menu.rs | 37 +++++++++- 7 files changed, 218 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/shelf_custom_preview.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f9b379a3..2441b1d1 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -137,6 +137,7 @@ mod session_log_file; pub mod settings_window; pub mod shader_settings; pub mod shelf; +pub mod shelf_custom_preview; mod shelf_entry; pub mod shelf_favorite; mod shelf_folders; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 2c32f595..3431f405 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -531,7 +531,9 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry return; } - let texture = entry.thumbnail(app, ctx); + // A picture the user picked replaces the thumbnail, unless its file is gone + let custom = crate::shelf_custom_preview::file_for(&app.ui.shelf_custom_previews, entry).and_then(|file| app.thumbs.custom_preview(ctx, file)); + let texture = custom.or_else(|| entry.thumbnail(app, ctx)); let asset = entry.asset(); let session = &app.session; let response = tile_in_view( diff --git a/crates/ui-egui/src/shelf_custom_preview.rs b/crates/ui-egui/src/shelf_custom_preview.rs new file mode 100644 index 00000000..8717b314 --- /dev/null +++ b/crates/ui-egui/src/shelf_custom_preview.rs @@ -0,0 +1,66 @@ +//! A picture the user picked to show on an asset's tile instead of its rendered thumbnail ("Set custom preview..." in the asset menu) + +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +use crate::shelf_entry::ShelfEntry; + +/// The custom preview's size in pixels: the largest tile's thumbnail on a high-density screen +pub(crate) const CUSTOM_PREVIEW_PX: u32 = 164; + +/// The image file shown on the tile of the asset with [`ShelfEntry::identity`] `kind` and `id` +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ShelfCustomPreview { + pub kind: String, + pub id: String, + pub file: PathBuf, +} + +impl ShelfCustomPreview { + fn is(&self, entry: &ShelfEntry) -> bool { + let (kind, id) = entry.identity(); + self.kind == kind && self.id == id + } +} + +/// The image file `entry` shows instead of its thumbnail, if the user picked one +pub(crate) fn file_for<'a>(previews: &'a [ShelfCustomPreview], entry: &ShelfEntry) -> Option<&'a Path> { + previews.iter().find(|preview| preview.is(entry)).map(|preview| preview.file.as_path()) +} + +/// Shows `file` on the tile of the asset with identity `kind` and `id`, replacing an earlier pick +pub(crate) fn set(previews: &mut Vec, kind: String, id: String, file: PathBuf) { + previews.retain(|preview| preview.kind != kind || preview.id != id); + previews.push(ShelfCustomPreview { kind, id, file }); +} + +/// Shows `entry`'s own thumbnail again +pub(crate) fn remove(previews: &mut Vec, entry: &ShelfEntry) { + previews.retain(|preview| !preview.is(entry)); +} + +/// The largest centred square of `image`, scaled to [`CUSTOM_PREVIEW_PX`] (smaller images keep their size) +pub(crate) fn square(image: &image::DynamicImage) -> image::RgbaImage { + let side = image.width().min(image.height()); + let cropped = image.crop_imm((image.width() - side) / 2, (image.height() - side) / 2, side, side); + let size = side.min(CUSTOM_PREVIEW_PX); + cropped.resize_exact(size, size, image::imageops::FilterType::Triangle).to_rgba8() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_wide_picture_keeps_its_middle() { + let red = image::Rgba([255, 0, 0, 255]); + let blue = image::Rgba([0, 0, 255, 255]); + let wide = image::RgbaImage::from_fn(6, 2, |x, _| if (2..4).contains(&x) { blue } else { red }); + + let square = square(&image::DynamicImage::ImageRgba8(wide)); + + assert_eq!(square.width(), square.height(), "the preview is square"); + assert!(square.pixels().all(|pixel| *pixel == blue), "only the middle of a wide picture shows"); + } +} diff --git a/crates/ui-egui/src/shelf_menu.rs b/crates/ui-egui/src/shelf_menu.rs index c486a0df..e7546ecf 100644 --- a/crates/ui-egui/src/shelf_menu.rs +++ b/crates/ui-egui/src/shelf_menu.rs @@ -29,6 +29,9 @@ const FIELD_TEXT_INSET: f32 = 8.0; /// The air above and below the separators, in points const SEPARATOR_SPACE: f32 = 3.0; +/// The category's place in an asset's path: after the library and the type's folder +const CATEGORY_PART: usize = 2; + /// A menu just opened from the keyboard gives the focus to its first row that can be picked (ctx temp data) const FOCUS_FIRST_ROW: &str = "shelf_menu_focus_first_row"; @@ -79,8 +82,11 @@ pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &Shelf { shown_info = rest; let field_id = ui.make_persistent_id(("asset_name", entry.identity())); - if let Some(renamed) = name_field(ui, width, column, field_id, name, &tokens) { - app.run(command, json!({"name": name, "to": renamed})); + if let Some(renamed) = name_field(ui, width, column, field_id, name, &tokens) + && let Some(result) = app.run(command, json!({"name": name, "to": renamed})) + && let Some(new_name) = result["name"].as_str() + { + keep_star_and_preview(app, entry, new_name); } } info_block(ui, width, column, shown_info, &tokens); @@ -126,6 +132,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &Shelf row(ui, width, tr("Export resource..."), false, &tokens).on_hover_text(tr("Built-in assets have no file to export")); } } + custom_preview_rows(app, ui, width, entry, &tokens); show_in(app, ui, width, entry, &tokens); if row(ui, width, favorite_label(app, entry), true, &tokens).clicked() { crate::shelf_favorite::toggle(&mut app.ui.shelf_favorites, entry); @@ -149,13 +156,36 @@ pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &Shelf } } +/// Moves the favorite star and custom preview of `entry`, just renamed to `new_name`, to its new identity +fn keep_star_and_preview(app: &mut TextureCraftApp, entry: &ShelfEntry, new_name: &str) { + let (kind, old_id) = entry.identity(); + let new_id = match entry { + ShelfEntry::SavedBrush { .. } => app + .session + .brush_presets + .list + .iter() + .find(|preset| preset.name == new_name) + .map(|preset| preset.file.as_ref().and_then(|file| file.to_str()).unwrap_or(&preset.name).to_owned()), + _ => Some(new_name.to_owned()), + }; + let Some(new_id) = new_id else { return }; + + let ui = &mut app.ui; + let favorites = ui.shelf_favorites.iter_mut().map(|favorite| (&favorite.kind, &mut favorite.id)); + let previews = ui.shelf_custom_previews.iter_mut().map(|preview| (&preview.kind, &mut preview.id)); + for (_, id) in favorites.chain(previews).filter(|(stored_kind, id)| *stored_kind == kind && *id == old_id) { + id.clone_from(&new_id); + } +} + /// The info block's label and value rows: rows only where the asset has the data fn info_rows(entry: &ShelfEntry) -> Vec<(&'static str, String)> { let path = entry.path(); let shown_path: Vec<&str> = path.iter().map(|part| LIBRARIES.iter().find(|(id, _)| id == part).map_or_else(|| tr(part), |(_, name)| tr(name))).collect(); let mut rows = vec![(tr("Name"), entry.label().to_string()), (tr("Usages"), tr(entry.usage()).to_string()), (tr("Path"), format!("/{}/", shown_path.join("/")))]; - if let Some(category) = path.get(2) { + if let Some(category) = path.get(CATEGORY_PART) { rows.push((tr("Category"), tr(category).to_string())); } rows @@ -163,7 +193,15 @@ fn info_rows(entry: &ShelfEntry) -> Vec<(&'static str, String)> { /// The labels of the rows under the info block, for the menu's width fn row_labels(entry: &ShelfEntry) -> Vec<&'static str> { - let mut labels = vec![tr("Export resource..."), tr("Show in"), tr("Add to favorites"), tr("Remove from favorites"), tr("Close")]; + let mut labels = vec![ + tr("Export resource..."), + tr("Set custom preview..."), + tr("Remove custom preview"), + tr("Show in"), + tr("Add to favorites"), + tr("Remove from favorites"), + tr("Close"), + ]; match entry { ShelfEntry::Image(_) => labels.extend([tr("Reload"), tr("Delete"), tr("Add as decal (view center)")]), ShelfEntry::SavedBrush { .. } => labels.extend([tr("Replace with the current brush"), tr("Delete")]), @@ -172,6 +210,45 @@ fn row_labels(entry: &ShelfEntry) -> Vec<&'static str> { labels } +/// Set custom preview... picks a picture to show on the tile; Remove custom preview, once one is set, shows the asset's own thumbnail again +fn custom_preview_rows(app: &mut TextureCraftApp, ui: &mut Ui, width: f32, entry: &ShelfEntry, tokens: &Tokens) { + if row(ui, width, tr("Set custom preview..."), true, tokens).clicked() { + pick_custom_preview(app, entry); + ui.close(); + } + if crate::shelf_custom_preview::file_for(&app.ui.shelf_custom_previews, entry).is_some() + && row(ui, width, tr("Remove custom preview"), true, tokens).clicked() + { + crate::shelf_custom_preview::remove(&mut app.ui.shelf_custom_previews, entry); + ui.close(); + } +} + +/// Asks for a picture, then shows it on `entry`'s tile +#[cfg(not(target_arch = "wasm32"))] +fn pick_custom_preview(app: &mut TextureCraftApp, entry: &ShelfEntry) { + use crate::file_dialogs::{Bound, FileDialog}; + + let (kind, id) = entry.identity(); + let (kind, id) = (kind.to_owned(), id.to_owned()); + let dialog = FileDialog::open().filter(tr("Images"), crate::web_files::IMAGE_EXTS); + app.ask_file(dialog, Bound::App, move |app, paths| { + let Some(file) = paths.into_iter().next() else { return }; + if image::image_dimensions(&file).is_err() { + app.toast(crate::i18n::trf("Could not read {file} as a picture", &[("file", &file.display())]), true); + return; + } + + app.thumbs.forget_custom_preview(&file); + crate::shelf_custom_preview::set(&mut app.ui.shelf_custom_previews, kind, id, file); + }); +} + +#[cfg(target_arch = "wasm32")] +fn pick_custom_preview(app: &mut TextureCraftApp, _: &ShelfEntry) { + app.toast(tr("Custom previews need the desktop app"), true); +} + /// The row that adds the asset to the favorites, or takes a favorite out fn favorite_label(app: &TextureCraftApp, entry: &ShelfEntry) -> &'static str { if crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some() { tr("Remove from favorites") } else { tr("Add to favorites") } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index d51db221..debef955 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -6,6 +6,7 @@ use texturecraft_engine::core::{BakedMap, Channel, ChannelBlend, NormalFormat}; use crate::docking::Dock; use crate::keymap::Keymap; use crate::saved_search::SavedSearch; +use crate::shelf_custom_preview::ShelfCustomPreview; use crate::shelf_favorite::ShelfFavorite; use crate::shelf_panes::ShelfPanes; use crate::shelf_view::ShelfView; @@ -592,6 +593,9 @@ pub struct UiState { /// The asset shelf shows only favorites (the Favorites saved search) #[serde(default)] pub shelf_favorites_only: bool, + /// Pictures the user picked to show on asset tiles instead of their thumbnails + #[serde(default)] + pub shelf_custom_previews: Vec, /// Saved searches' share of the pane column above Filter by path, set by the splitter between them #[serde(default = "default_shelf_panes_split", deserialize_with = "deserialize_shelf_panes_split")] pub shelf_panes_split: f32, @@ -750,6 +754,7 @@ impl UiState { self.shelf_saved_searches = keep.shelf_saved_searches; self.shelf_favorites = keep.shelf_favorites; self.shelf_favorites_only = keep.shelf_favorites_only; + self.shelf_custom_previews = keep.shelf_custom_previews; } } @@ -786,6 +791,7 @@ impl Default for UiState { shelf_saved_searches: Vec::new(), shelf_favorites: Vec::new(), shelf_favorites_only: false, + shelf_custom_previews: Vec::new(), shelf_panes_split: default_shelf_panes_split(), props_tab: PropsTab::Brush, text: TextUi::default(), @@ -913,13 +919,15 @@ mod tests { } #[test] - fn adopting_a_layout_keeps_the_shelf_query_saved_searches_and_favorites() { + fn adopting_a_layout_keeps_the_shelf_query_saved_searches_favorites_and_custom_previews() { let saved = crate::saved_search::SavedSearch { name: "rust".into(), filter: "rust".into(), tab: 2, path: vec!["starter".into()] }; let favorite = crate::shelf_favorite::ShelfFavorite { kind: "material".into(), id: "gold".into() }; let mut ui = UiState { shelf_filter: "rust".into(), shelf_tab: 2, shelf_path: vec!["starter".into()], shelf_favorites_only: true, ..UiState::default() }; ui.shelf_saved_searches.push(saved.clone()); ui.shelf_favorites.push(favorite.clone()); + let preview = crate::shelf_custom_preview::ShelfCustomPreview { kind: "material".into(), id: "gold".into(), file: "gold.png".into() }; + ui.shelf_custom_previews.push(preview.clone()); ui.adopt_layout(UiState::default()); @@ -927,6 +935,7 @@ mod tests { assert_eq!(ui.shelf_saved_searches, [saved]); assert_eq!(ui.shelf_favorites, [favorite], "favorites are the user's own too"); assert!(ui.shelf_favorites_only, "the Favorites search is part of the query"); + assert_eq!(ui.shelf_custom_previews, [preview], "custom previews are the user's own"); } #[test] diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 875ac6ae..0a711ae2 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -64,6 +64,8 @@ pub struct Thumbs { big_shown: VecDeque, /// The frame that last took in the worker's results received_in_pass: u64, + /// Pictures the user picked as asset previews, by file; None for a file that doesn't load + custom_previews: HashMap>, } impl Thumbs { @@ -288,6 +290,25 @@ impl Thumbs { self.rendered.retain(|key, _| current(key)); self.big_shown.retain(current); self.saved_brush_previews.clear(); + self.custom_previews.clear(); + } + + /// Load the picture at `file` again next time: the user picked it anew, maybe after changing it + pub(crate) fn forget_custom_preview(&mut self, file: &Path) { + self.custom_previews.remove(file); + } + + /// The picture at `file` as an asset's custom preview (its centred square), loaded once; None if it doesn't load + pub(crate) fn custom_preview(&mut self, ctx: &egui::Context, file: &Path) -> Option { + self.custom_previews + .entry(file.to_path_buf()) + .or_insert_with(|| { + let image = crate::shelf_custom_preview::square(&image::open(file).ok()?); + let size = [image.width() as usize, image.height() as usize]; + let pixels = ColorImage::from_rgba_unmultiplied(size, image.as_raw()); + Some(ctx.load_texture(format!("custom_preview_{}", file.display()), pixels, TextureOptions::LINEAR)) + }) + .clone() } /// Smart mask thumbnail; None until the worker returns it diff --git a/crates/ui-egui/tests/it/shelf_menu.rs b/crates/ui-egui/tests/it/shelf_menu.rs index 4cd920d6..3ebea8ef 100644 --- a/crates/ui-egui/tests/it/shelf_menu.rs +++ b/crates/ui-egui/tests/it/shelf_menu.rs @@ -130,12 +130,13 @@ fn delete_removes_a_project_image() { } #[test] -fn a_project_image_menu_renames_it_and_reloads_only_a_file_from_this_session() { +fn a_project_image_menu_renames_it_keeping_its_star_and_greys_reload_without_a_file() { let mut harness = shelf(TEXTURES_TYPE); let mut bytes = Vec::new(); image::RgbaImage::from_pixel(4, 4, image::Rgba([180, 90, 40, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); let name = harness.state_mut().session.import_resource_bytes("plate.png", bytes).unwrap(); harness.run_steps(3); + pick_from_menu(&mut harness, &name, "Add to favorites"); right_click(&mut harness, &name); assert!(harness.get_by_label("Reload").accesskit_node().is_disabled(), "an image without a file from this session can't reload"); @@ -145,6 +146,8 @@ fn a_project_image_menu_renames_it_and_reloads_only_a_file_from_this_session() { let resources = &harness.state().session.doc.resources; assert!(resources.contains_key("stone.png") && !resources.contains_key(&name), "Enter renames the image, keeping its extension"); + let favorites: Vec<&str> = harness.state().ui.shelf_favorites.iter().map(|favorite| favorite.id.as_str()).collect(); + assert_eq!(favorites, ["stone.png"], "the star follows the rename"); } #[test] @@ -228,3 +231,35 @@ fn favorites_come_first_newest_first_with_a_star_until_removed() { assert!(comes_before(&harness, first, second), "a removed favorite goes back to its place by name"); assert!(comes_before(&harness, third, first), "the other favorite stays first"); } + +#[test] +fn set_custom_preview_shows_a_picked_picture_until_removed() { + let material = MATERIALS.iter().filter(|material| !material.smart).min_by_key(|material| material.label.to_lowercase()).unwrap(); + let mut harness = shelf(MATERIALS_TYPE); + let dir = super::temp_dir::TempDir::new("shelf-custom-preview"); + let picture = dir.join("preview.png"); + image::RgbaImage::from_pixel(8, 4, image::Rgba([40, 160, 90, 255])).save(&picture).unwrap(); + let not_a_picture = dir.join("notes.png"); + std::fs::write(¬_a_picture, b"not a picture").unwrap(); + let answers = std::sync::Arc::new(std::sync::Mutex::new(vec![picture.clone(), not_a_picture])); + let pick = answers.clone(); + harness.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![pick.lock().unwrap().remove(0)])))); + let picked = + |harness: &Harness<'_, TextureCraftApp>| harness.state().ui.shelf_custom_previews.iter().map(|preview| preview.file.clone()).collect::>(); + + pick_from_menu(&mut harness, material.label, "Set custom preview..."); + harness.run_steps(2); + + assert_eq!(picked(&harness), std::slice::from_ref(&picture), "the tile shows the picked picture"); + + pick_from_menu(&mut harness, material.label, "Set custom preview..."); + harness.run_steps(2); + + assert_eq!(picked(&harness), [picture], "a file that isn't a picture leaves the preview as it was"); + + pick_from_menu(&mut harness, material.label, "Remove custom preview"); + + assert!(picked(&harness).is_empty(), "the tile shows its own thumbnail again"); + right_click(&mut harness, material.label); + assert!(harness.query_by_label("Remove custom preview").is_none(), "only a tile with a custom preview offers to remove it"); +} From 4f73e0c54117b684cf5567db816ff27b8be5f0bf Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:10:57 +0000 Subject: [PATCH 07/16] Assets: refresh popup with automatic updates of the panel and the project's images The refresh button opens a popup above the toolbar: automatic updates of the Assets panel and of the images used in the project every few minutes, the two updates by hand, and a greyed parameter-mismatch switch whose i says TextureCraft has no assets with parameters to update yet. New command resource.update reads again, in one undo step, every image imported this session whose file changed. --- crates/engine/src/resource_cmds.rs | 115 +++++++++- crates/ui-egui/src/lib.rs | 2 + .../ui-egui/src/property_sheet/info_icon.rs | 54 ++++- crates/ui-egui/src/property_sheet/mod.rs | 3 +- .../section_tabs/section_scope.rs | 2 + .../src/property_sheet/switch_control.rs | 26 ++- crates/ui-egui/src/shelf_toolbar.rs | 19 +- crates/ui-egui/src/shelf_updates.rs | 211 ++++++++++++++++++ crates/ui-egui/src/state.rs | 7 + crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/shelf_panel.rs | 2 + crates/ui-egui/tests/it/shelf_updates.rs | 91 ++++++++ 12 files changed, 498 insertions(+), 35 deletions(-) create mode 100644 crates/ui-egui/src/shelf_updates.rs create mode 100644 crates/ui-egui/tests/it/shelf_updates.rs diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index df7d16ff..1d93ccb9 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -43,6 +43,15 @@ pub fn specs() -> Vec { always, reload ), + cmd!( + "resource.update", + "Update resources used in project", + [], + None, + "{} — read again every image imported from a file in this session whose file changed (one undo step); returns {updated: [names], failed: [{name, error}]}", + always, + update + ), cmd!("file.removeUnused", "Remove unused resources...", ["File"], None, "{}", always, remove_unused), cmd!( "layer.add.image", @@ -399,27 +408,87 @@ fn reload(s: &mut Session, p: &Value) -> Result { let path = s.resource_sources.get(&name).cloned().ok_or_else(|| bad(command, format!("`{name}` was imported before this session: no file to reload from")))?; - let bytes = read_resource_file(command, &path, MAX_BYTES as u64)?; - let image = texturecraft_formats::decode_image_within(&bytes, texturecraft_formats::MAX_RESOURCE_TEXELS) - .map_err(|error| bad(command, format!("{}: {error}", path.display())))?; + let (bytes, image) = read_source(command, &path)?; s.edit("Reload resource", |s| { s.doc.resources.insert(name.clone(), Arc::new(bytes)); Ok(()) })?; - s.library_alphas.remove(&name); - if crate::fill_alpha::matches_saved_picture(&name, &image) { - s.library_alphas.insert(name.clone()); - } - s.images.insert(name.clone(), decoded(image)); + s.show_reloaded(name.clone(), image); Ok(json!({ "name": name })) } +/// Reads again, in one undo step, every image whose source file no longer holds the bytes the project has; nothing changed adds no step +#[cfg(not(target_arch = "wasm32"))] +fn update(s: &mut Session, _: &Value) -> Result { + let command = "resource.update"; + let mut changed = Vec::new(); + let mut failed = Vec::new(); + for (name, path) in &s.resource_sources { + let Some(held) = s.doc.resources.get(name) else { continue }; + // Only a file whose bytes changed is decoded + let read = read_resource_file(command, path, MAX_BYTES as u64) + .and_then(|bytes| if bytes == **held { Ok(None) } else { decode_source(command, path, &bytes).map(|image| Some((bytes, image))) }); + match read { + Ok(None) => {} + Ok(Some((bytes, image))) => changed.push((name.clone(), bytes, image)), + Err(error) => failed.push(json!({ "name": name, "error": error.to_string() })), + } + } + + if !changed.is_empty() { + s.edit("Update resources", |s| { + for (name, bytes, _) in &mut changed { + s.doc.resources.insert(name.clone(), Arc::new(std::mem::take(bytes))); + } + Ok(()) + })?; + } + + let updated: Vec = changed.iter().map(|(name, _, _)| name.clone()).collect(); + for (name, _, image) in changed { + s.show_reloaded(name, image); + } + Ok(json!({ "updated": updated, "failed": failed })) +} + +/// The bytes of the image file at `path` and its decoded pixels +#[cfg(not(target_arch = "wasm32"))] +fn read_source(command: &str, path: &std::path::Path) -> Result<(Vec, texturecraft_formats::DecodedImage)> { + let bytes = read_resource_file(command, path, MAX_BYTES as u64)?; + let image = decode_source(command, path, &bytes)?; + Ok((bytes, image)) +} + +/// The pixels of `bytes` read from the image file at `path` +#[cfg(not(target_arch = "wasm32"))] +fn decode_source(command: &str, path: &std::path::Path, bytes: &[u8]) -> Result { + texturecraft_formats::decode_image_within(bytes, texturecraft_formats::MAX_RESOURCE_TEXELS) + .map_err(|error| bad(command, format!("{}: {error}", path.display()))) +} + +#[cfg(not(target_arch = "wasm32"))] +impl Session { + /// Shows the pixels of image `name` read again from its file, still a saved brush picture when it matches one + fn show_reloaded(&mut self, name: String, image: texturecraft_formats::DecodedImage) { + self.library_alphas.remove(&name); + if crate::fill_alpha::matches_saved_picture(&name, &image) { + self.library_alphas.insert(name.clone()); + } + self.images.insert(name, decoded(image)); + } +} + #[cfg(target_arch = "wasm32")] fn reload(_: &mut Session, _: &Value) -> Result { Err(bad("resource.reload", "file paths are not available in the browser")) } +#[cfg(target_arch = "wasm32")] +fn update(_: &mut Session, _: &Value) -> Result { + Err(bad("resource.update", "file paths are not available in the browser")) +} + /// Every image resource a layer, mask effect, stored path or the environment of `project` uses fn project_images(project: &texturecraft_core::Project) -> Vec { let mut used = Vec::new(); @@ -575,6 +644,36 @@ mod tests { assert!(session.resource_source(&reused).is_none(), "the new image has no file to reload from"); } + #[test] + fn updating_reads_only_changed_files_in_one_undo_step() { + let mut session = crate::sample_session(128, 32).unwrap(); + let import = |session: &mut Session, label: &str, value: f32| { + let path = std::env::temp_dir().join(format!("texturecraft-update-{label}-{}.png", std::process::id())); + std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [value].into_iter()).unwrap()).unwrap(); + let name = crate::execute(session, "resource.import", &json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + (path, name) + }; + let (edited_path, edited) = import(&mut session, "edited", 0.2); + let (kept_path, kept) = import(&mut session, "kept", 0.4); + let unchanged = crate::execute(&mut session, "resource.update", &json!({})).unwrap(); + let steps = session.history_labels().len(); + let before = session.images[&edited].rgba.clone(); + std::fs::write(&edited_path, texturecraft_formats::gray16_png(1, 1, [0.8].into_iter()).unwrap()).unwrap(); + + let result = crate::execute(&mut session, "resource.update", &json!({})).unwrap(); + let updated = session.images[&edited].rgba.clone(); + let steps_after = session.history_labels().len(); + session.undo().unwrap(); + + assert_eq!(unchanged["updated"], json!([]), "files that didn't change aren't read in again"); + assert_eq!(result["updated"], json!([edited]), "only the changed file is read again, not `{kept}`"); + assert_ne!(updated, before, "the changed file's new pixels show"); + assert_eq!(steps_after, steps + 1, "one undo step for the update"); + assert_eq!(session.images[&edited].rgba, before, "undo shows the old pixels again"); + std::fs::remove_file(edited_path).unwrap(); + std::fs::remove_file(kept_path).unwrap(); + } + #[test] fn file_reads_obey_the_remaining_byte_budget() { let path = std::env::temp_dir().join(format!("texturecraft-read-image-{}.png", std::process::id())); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 2441b1d1..f49d4d4e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -146,6 +146,7 @@ pub mod shelf_panes; pub mod shelf_preview; mod shelf_tabs; mod shelf_toolbar; +pub mod shelf_updates; pub mod shelf_view; mod slot_thumbnail; #[cfg(not(target_arch = "wasm32"))] @@ -1090,6 +1091,7 @@ impl eframe::App for TextureCraftApp { self.ui.prefs.apply_resource_limits(); control::poll(self, ctx); + shelf_updates::tick(self, ctx); #[cfg(not(target_arch = "wasm32"))] self.run_file_dialog_answers(); web_files::poll(self); diff --git a/crates/ui-egui/src/property_sheet/info_icon.rs b/crates/ui-egui/src/property_sheet/info_icon.rs index a8cbee52..dc866982 100644 --- a/crates/ui-egui/src/property_sheet/info_icon.rs +++ b/crates/ui-egui/src/property_sheet/info_icon.rs @@ -1,7 +1,7 @@ use egui::{Align2, CornerRadius, FontId, Frame, Margin, Rect, RectAlign, RichText, Role, Sense, Shadow, Stroke, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as ic; -use super::{PropertySheet, ROW_HEIGHT, SMALL_TEXT_SIZE}; +use super::{PropertySheet, ROW_HEIGHT, SIDE_PADDING_POINTS, SMALL_TEXT_SIZE}; use crate::theme::HARD_SHADOW; /// The i's slot at the panel edge; a row with an i at its left starts this much further right @@ -16,6 +16,9 @@ const INFO_ICON_SIZE: f32 = 13.0; /// Room the tooltip leaves at the panel's right edge, so it covers no number, dial or switch const TIP_VALUE_ROOM: f32 = 70.0; +/// Width of a tooltip beside its window +const BESIDE_TIP_WIDTH: f32 = 320.0; + /// How far the tooltip reaches up into its row const TIP_OVERLAP: f32 = 2.0; @@ -47,6 +50,48 @@ impl<'u> PropertySheet<'u> { self.paint_info_in(self.right - INFO_SLOT, self.right - INFO_ICON_SIZE / 2.0, center_y); } + /// Paints an i for the row just laid out in the `column` right of the sheet, its tooltip beside the window the sheet is in + pub(crate) fn beside_info(&mut self, column: f32, tip: &str) { + let center_y = self.cursor_y() - ROW_HEIGHT / 2.0; + let row_top = center_y - ROW_HEIGHT / 2.0; + let edge = self.right + SIDE_PADDING_POINTS + column; + let slot = Rect::from_min_max(pos2(edge - SIDE_PADDING_POINTS - INFO_SLOT, row_top), pos2(edge - SIDE_PADDING_POINTS, row_top + ROW_HEIGHT)); + let id = self.next_id(); + let response = self.ui.interact(slot, id, Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(Role::Image, true, tip)); + + let tokens = self.tokens; + let color = if response.hovered() { tokens.text } else { tokens.text_dim }; + self.ui.painter().text(slot.center(), Align2::CENTER_CENTER, ic::INFO, FontId::proportional(INFO_ICON_SIZE), color); + + // Beside the window, from this row down, so it covers none of the rows under it + let layer = self.ui.layer_id().id; + let window = self.ui.ctx().memory(|memory| memory.area_rect(layer)).unwrap_or(self.ui.clip_rect()); + let anchor = Rect::from_min_max(pos2(window.left(), row_top), pos2(window.right(), row_top + ROW_HEIGHT)); + let mut tooltip = egui::Tooltip::for_enabled(&response); + tooltip.popup = tooltip + .popup + .anchor(anchor) + .align(RectAlign::RIGHT_START) + .align_alternatives(&[RectAlign::LEFT_START]) + .frame(self.tip_frame()) + .width(BESIDE_TIP_WIDTH); + tooltip.show(|ui| { + ui.set_width(BESIDE_TIP_WIDTH); + ui.label(RichText::new(tip).size(SMALL_TEXT_SIZE).color(tokens.text).line_height(Some(TIP_LINE_HEIGHT))); + }); + } + + /// The tooltips' box: the chrome, a hairline, rounded, with a hard shadow + fn tip_frame(&self) -> Frame { + Frame::NONE + .fill(self.tokens.chrome) + .stroke(Stroke::new(1.0, self.tokens.field_border)) + .corner_radius(CornerRadius::same(TIP_ROUNDING)) + .inner_margin(TIP_MARGIN) + .shadow(TIP_SHADOW) + } + /// Paints the pending i at `glyph_x` in its slot from `slot_left` fn paint_info_in(&mut self, slot_left: f32, glyph_x: f32, center_y: f32) { let Some(tip) = self.info.take() else { return }; @@ -63,12 +108,7 @@ impl<'u> PropertySheet<'u> { // Under the row from the i, ending before the value column; above it where the window ends first let anchor = Rect::from_min_max(pos2(self.left, row_top), pos2(self.right - TIP_VALUE_ROOM, row_top + ROW_HEIGHT)); - let frame = Frame::NONE - .fill(tokens.chrome) - .stroke(Stroke::new(1.0, tokens.field_border)) - .corner_radius(CornerRadius::same(TIP_ROUNDING)) - .inner_margin(TIP_MARGIN) - .shadow(TIP_SHADOW); + let frame = self.tip_frame(); let text_width = anchor.width() - TIP_MARGIN.sum().x; let mut tooltip = egui::Tooltip::for_enabled(&response); diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 62c81046..78fb2e4d 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -68,6 +68,7 @@ pub(crate) use section_tabs::{ pub(crate) use sheet::PropertySheet; pub(crate) use slot_response::SlotResponse; pub(crate) use stack_slider::StackSlider; +pub(crate) use switch_control::TOGGLE_ROOM; /// Side padding: every row starts and ends this far inside the panel pub(crate) const SIDE_PADDING_POINTS: f32 = 12.0; @@ -103,7 +104,7 @@ const VALUE_MIN_WIDTH: f32 = 26.0; const TRACK_TO_VALUE: f32 = 14.0; /// Size of regular labels and SemiBold values -const TEXT_SIZE: f32 = 12.0; +pub(crate) const TEXT_SIZE: f32 = 12.0; /// Size of captions, pill names and the switch's words const SMALL_TEXT_SIZE: f32 = 11.0; diff --git a/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs b/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs index 5fe48e1f..bc17fa4f 100644 --- a/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs +++ b/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs @@ -5,4 +5,6 @@ pub(crate) enum SectionScope { Docked, /// The right-click Properties popup over a view Popup, + /// The Assets panel's refresh popup, which has no strip + Shelf, } diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index 7443f9f4..85e007be 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -38,6 +38,9 @@ const TOGGLE_LABEL_AIR: f32 = 10.0; /// From that column to the pill's centre: the pill starts on the column const TOGGLE_CENTER_OFFSET: f32 = PILL_SIZE.x / 2.0; +/// Room a toggle takes right of its label: the air and the switch +pub(crate) const TOGGLE_ROOM: f32 = TOGGLE_LABEL_AIR + PILL_SIZE.x; + /// From one of a pair's toggles to the next, and from its name to its pill's centre const PAIR_PITCH: f32 = 76.0; const PAIR_NAME_TO_PILL: f32 = 32.0; @@ -191,6 +194,15 @@ impl PropertySheet<'_> { /// An on/off beside its label; every toggle in a panel lines up past the longest toggle label pub(crate) fn toggle(&mut self, label: &str, on: &mut bool) -> bool { + self.toggle_in(label, on, true) + } + + /// A [`Self::toggle`] greyed out and off: a setting this app can't act on yet, said in its row's i + pub(crate) fn unavailable_toggle(&mut self, label: &str) { + self.toggle_in(label, &mut false, false); + } + + fn toggle_in(&mut self, label: &str, on: &mut bool, enabled: bool) -> bool { let rect = self.take(ROW_HEIGHT); let center_y = rect.center().y; let label_x = self.left + self.lead_shift(); @@ -201,11 +213,19 @@ impl PropertySheet<'_> { let column = (self.column() - self.left).max(self.used.toggle_label_end).max(label_end); let pill = Rect::from_center_size(pos2(self.left + column + TOGGLE_CENTER_OFFSET, center_y), PILL_SIZE); - let clicked = self.toggle_hit(Rect::from_min_max(pos2(label_x, rect.top()), pos2(pill.right(), rect.bottom())), label, on); + let hit = Rect::from_min_max(pos2(label_x, rect.top()), pos2(pill.right(), rect.bottom())); + let clicked = if enabled { + self.toggle_hit(hit, label, on) + } else { + let id = self.next_id(); + let response = self.ui.interact(hit, id, Sense::hover()); + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, false, false, label)); + false + }; - let text = self.tokens.text; + let text = if enabled { self.tokens.text } else { self.tokens.text_dim }; self.ui.painter().text(pos2(label_x, center_y), Align2::LEFT_CENTER, label, font, text); - self.pill(pill.center(), *on, true); + self.pill(pill.center(), *on, enabled); self.drawn(center_y + PILL_SIZE.y / 2.0); clicked } diff --git a/crates/ui-egui/src/shelf_toolbar.rs b/crates/ui-egui/src/shelf_toolbar.rs index c7c00b81..99a80cb6 100644 --- a/crates/ui-egui/src/shelf_toolbar.rs +++ b/crates/ui-egui/src/shelf_toolbar.rs @@ -1,4 +1,4 @@ -//! The shelf's bottom toolbar: the side pane toggles on the left; refresh, reset query and import on the right +//! The shelf's bottom toolbar: the side pane toggles on the left; refresh with its update settings, reset query and import on the right use egui::Ui; use egui_phosphor::regular as ic; @@ -18,6 +18,7 @@ pub(crate) fn height(ui: &Ui) -> f32 { /// The toolbar pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { let size = ui.spacing().interact_size.y; + let panel = ui.max_rect(); ui.add_space(GAP_ABOVE); ui.horizontal(|ui| { crate::shelf_panes::toggles(app, ui, size); @@ -28,9 +29,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { if icon_button(ui, ic::X_CIRCLE, tr("Reset query"), false, size).clicked() { reset_query(app); } - if icon_button(ui, ic::ARROWS_CLOCKWISE, tr("Refresh"), false, size).clicked() { - refresh(app); - } + crate::shelf_updates::button(app, ui, size, panel); }); }); } @@ -42,15 +41,3 @@ pub(crate) fn reset_query(app: &mut TextureCraftApp) { app.ui.shelf_path.clear(); app.ui.shelf_favorites_only = false; } - -/// Read the user's saved assets from disk again and redraw their thumbnails -fn refresh(app: &mut TextureCraftApp) { - app.library = None; - - #[cfg(not(target_arch = "wasm32"))] - for warning in app.session.load_brush_presets(crate::user_dir("brushes")) { - app.toast(warning, true); - } - - app.thumbs.forget_saved_files(); -} diff --git a/crates/ui-egui/src/shelf_updates.rs b/crates/ui-egui/src/shelf_updates.rs new file mode 100644 index 00000000..8300357d --- /dev/null +++ b/crates/ui-egui/src/shelf_updates.rs @@ -0,0 +1,211 @@ +//! The shelf's refresh popup: read the Assets panel and the project's images again every few minutes, or now by hand + +use egui::{Context, Id, Ui, vec2}; +use egui_phosphor::regular as ic; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +use crate::TextureCraftApp; +use crate::i18n::{n_, tr}; +use crate::property_sheet::{NumberField, PropertySheet, SIDE_PADDING_POINTS, SectionScope, in_scope}; +use crate::widgets::icon_dropdown_button; + +/// Least and most minutes between automatic updates +const MIN_MINUTES: u32 = 1; +const MAX_MINUTES: u32 = 24 * 60; + +/// Air between the popup and the toolbar under it +const POPUP_GAP: f32 = 1.0; + +/// Air between the two update buttons and under the last one +const BUTTON_GAP: f32 = 6.0; + +/// Room right of a row's switch for its i +const INFO_COLUMN: f32 = 28.0; + +/// How soon a run that waited for a stroke tries again +const STROKE_RETRY: std::time::Duration = std::time::Duration::from_millis(250); + +/// A drag of 20 points moves the minutes by one +const MINUTES_PER_DRAG_POINT: f32 = 0.05; + +/// How much shorter a manual update button is than a sheet row, so neighbouring buttons don't touch +const BUTTON_INSET: f32 = 4.0; + +const SKIP_MISMATCH: &str = n_("Skip assets when their parameters mismatch"); + +/// Which automatic updates are on and how often they run +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ShelfUpdates { + /// Read the user's saved assets again + pub assets: bool, + /// Read the images the project imported from files in this session again when a file changed + pub resources: bool, + pub minutes: u32, +} + +impl Default for ShelfUpdates { + fn default() -> Self { + ShelfUpdates { assets: false, resources: false, minutes: MIN_MINUTES } + } +} + +/// When the automatic updates last ran, on egui's clock +fn last_run_id() -> Id { + Id::unique("shelf_updates_last_run") +} + +/// Runs the automatic updates once their minutes have passed since the last run, and wakes the app for the next one +pub(crate) fn tick(app: &mut TextureCraftApp, ctx: &Context) { + let updates = app.ui.shelf_updates; + if !updates.assets && !updates.resources { + ctx.data_mut(|data| data.remove::(last_run_id())); + return; + } + + // An update during a stroke would land in the stroke's undo step: it waits for the stroke to end + if app.session.stroke_active() { + ctx.request_repaint_after(STROKE_RETRY); + return; + } + + let now = ctx.input(|input| input.time); + let every = f64::from(updates.minutes.clamp(MIN_MINUTES, MAX_MINUTES)) * 60.0; + let last = ctx.data_mut(|data| *data.get_temp_mut_or(last_run_id(), now)); + if now - last < every { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(every - (now - last))); + return; + } + + ctx.data_mut(|data| data.insert_temp(last_run_id(), now)); + if updates.assets { + refresh_assets(app); + } + if updates.resources { + update_resources(app, ctx); + } + ctx.request_repaint_after(std::time::Duration::from_secs_f64(every)); +} + +/// Read the user's saved assets from disk again and redraw their thumbnails +pub(crate) fn refresh_assets(app: &mut TextureCraftApp) { + app.library = None; + + #[cfg(not(target_arch = "wasm32"))] + for warning in app.session.load_brush_presets(crate::user_dir("brushes")) { + app.toast(warning, true); + } + + app.thumbs.forget_saved_files(); +} + +/// Reads the project's changed image files again; a file that can't be read says why once, until it reads again +fn update_resources(app: &mut TextureCraftApp, ctx: &Context) { + let Some(result) = app.run("resource.update", json!({})) else { return }; + + let failures: Vec<(String, String)> = result["failed"] + .as_array() + .into_iter() + .flatten() + .map(|failure| (failure["name"].as_str().unwrap_or_default().to_owned(), failure["error"].as_str().unwrap_or_default().to_owned())) + .collect(); + let mut reported: Vec = ctx.data(|data| data.get_temp(reported_failures_id())).unwrap_or_default(); + reported.retain(|name| failures.iter().any(|(failed, _)| failed == name)); + for (name, error) in failures { + if !reported.contains(&name) { + app.toast(format!("{name}: {error}"), true); + reported.push(name); + } + } + ctx.data_mut(|data| data.insert_temp(reported_failures_id(), reported)); +} + +/// The files whose failure to read was already shown (ctx temp data) +fn reported_failures_id() -> Id { + Id::unique("shelf_updates_reported_failures") +} + +/// The refresh button with its popup of update settings, opening upward from the toolbar `panel` with its left edge on the panel's +pub(crate) fn button(app: &mut TextureCraftApp, ui: &mut Ui, size: f32, panel: egui::Rect) { + let label = tr("Refresh"); + let response = icon_dropdown_button(ui, ic::ARROWS_CLOCKWISE, label, false, size).on_hover_text(label); + let width = popup_width(ui, panel.width()); + egui::Popup::from_toggle_button_response(&response) + .anchor(panel) + .align(egui::RectAlign::TOP_START) + .gap(POPUP_GAP) + .width(width) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show(|ui| { + ui.set_width(width); + popup(app, ui); + }); +} + +/// The panel's width, or wider to fit the longest row +fn popup_width(ui: &Ui, panel_width: f32) -> f32 { + let font = egui::FontId::proportional(crate::property_sheet::TEXT_SIZE); + let longest = ui.painter().layout_no_wrap(tr(SKIP_MISMATCH).to_owned(), font, egui::Color32::WHITE).size().x; + panel_width.max(longest + crate::property_sheet::TOGGLE_ROOM + INFO_COLUMN + 2.0 * SIDE_PADDING_POINTS) +} + +fn popup(app: &mut TextureCraftApp, ui: &mut Ui) { + let updates = &mut app.ui.shelf_updates; + let full = ui.available_rect_before_wrap(); + let rows = full.with_max_x(full.right() - INFO_COLUMN); + in_scope(ui, SectionScope::Shelf, |ui| { + ui.scope_builder(egui::UiBuilder::new().max_rect(rows), |ui| { + PropertySheet::show(ui, "shelf_updates", |sheet| { + sheet.section(tr("Automatic updates"), false); + sheet.toggle(tr("Assets panel"), &mut updates.assets); + sheet.beside_info(INFO_COLUMN, tr("Reads your saved assets from disk again every few minutes, so new and changed ones show here.")); + sheet.toggle(tr("Resources used in project"), &mut updates.resources); + sheet.beside_info( + INFO_COLUMN, + tr("Every few minutes, reads again the images this project imported from files in this session whose files changed. Each update is one undo step."), + ); + + let mut minutes = [NumberField { + tag: "", + tag_color: None, + value: updates.minutes as f32, + speed: MINUTES_PER_DRAG_POINT, + decimals: 0, + suffix: tr(" min"), + }]; + if sheet.number_fields(tr("Update every"), &mut minutes, None, false).is_some() { + updates.minutes = (minutes[0].value.round() as u32).clamp(MIN_MINUTES, MAX_MINUTES); + } + sheet.beside_info(INFO_COLUMN, tr("How often the automatic updates above run.")); + + sheet.section(tr("Advanced settings"), false); + sheet.unavailable_toggle(tr(SKIP_MISMATCH)); + sheet.beside_info( + INFO_COLUMN, + tr("For assets with parameters: an update whose parameters were renamed or removed would change your texturing, so it is skipped. TextureCraft doesn't update assets with parameters from their files yet, so there is nothing to skip."), + ); + + sheet.section(tr("Manual"), false); + }); + }); + }); + + let button_size = vec2(full.width() - 2.0 * SIDE_PADDING_POINTS, crate::property_sheet::ROW_HEIGHT - BUTTON_INSET); + let add_button = |ui: &mut Ui, label: &str| { + let clicked = ui + .horizontal(|ui| { + ui.add_space(SIDE_PADDING_POINTS); + ui.add_sized(button_size, egui::Button::new(label)).clicked() + }) + .inner; + ui.add_space(BUTTON_GAP); + clicked + }; + if add_button(ui, tr("Update Assets panel")) { + refresh_assets(app); + } + if add_button(ui, tr("Update resources used in project")) { + update_resources(app, ui.ctx()); + } +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index debef955..7caf4d29 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -593,6 +593,9 @@ pub struct UiState { /// The asset shelf shows only favorites (the Favorites saved search) #[serde(default)] pub shelf_favorites_only: bool, + /// The asset shelf's automatic updates (its refresh popup) + #[serde(default)] + pub shelf_updates: crate::shelf_updates::ShelfUpdates, /// Pictures the user picked to show on asset tiles instead of their thumbnails #[serde(default)] pub shelf_custom_previews: Vec, @@ -755,6 +758,7 @@ impl UiState { self.shelf_favorites = keep.shelf_favorites; self.shelf_favorites_only = keep.shelf_favorites_only; self.shelf_custom_previews = keep.shelf_custom_previews; + self.shelf_updates = keep.shelf_updates; } } @@ -792,6 +796,7 @@ impl Default for UiState { shelf_favorites: Vec::new(), shelf_favorites_only: false, shelf_custom_previews: Vec::new(), + shelf_updates: crate::shelf_updates::ShelfUpdates::default(), shelf_panes_split: default_shelf_panes_split(), props_tab: PropsTab::Brush, text: TextUi::default(), @@ -928,6 +933,7 @@ mod tests { ui.shelf_favorites.push(favorite.clone()); let preview = crate::shelf_custom_preview::ShelfCustomPreview { kind: "material".into(), id: "gold".into(), file: "gold.png".into() }; ui.shelf_custom_previews.push(preview.clone()); + ui.shelf_updates.resources = true; ui.adopt_layout(UiState::default()); @@ -936,6 +942,7 @@ mod tests { assert_eq!(ui.shelf_favorites, [favorite], "favorites are the user's own too"); assert!(ui.shelf_favorites_only, "the Favorites search is part of the query"); assert_eq!(ui.shelf_custom_previews, [preview], "custom previews are the user's own"); + assert!(ui.shelf_updates.resources, "automatic updates are a setting, not part of a layout"); } #[test] diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index fd55514b..580812c5 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -83,6 +83,7 @@ mod shelf_drop; mod shelf_hover_preview; mod shelf_menu; mod shelf_panel; +mod shelf_updates; mod shift_lines_2d; mod shift_lines_3d; mod shortcut_keys; diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index 7dcd12a4..06856a41 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -152,6 +152,8 @@ fn refresh_reads_the_saved_brushes_again() { harness.run_steps(1); button(&harness, "Refresh").click(); + harness.run_steps(2); + button(&harness, "Update Assets panel").click(); harness.run_steps(3); assert!(harness.state().session.brush_presets.find("Stale brush marker").is_none(), "the brushes folder was read again"); diff --git a/crates/ui-egui/tests/it/shelf_updates.rs b/crates/ui-egui/tests/it/shelf_updates.rs new file mode 100644 index 00000000..0a3e06fd --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_updates.rs @@ -0,0 +1,91 @@ +//! The Assets panel's refresh popup: automatic updates of the panel and of the project's images + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::brush_preset_cmds::UserBrush; +use texturecraft_ui_egui::TextureCraftApp; + +/// A little more than the shortest update interval, in seconds +const PAST_A_MINUTE: f64 = 61.0; + +/// The sample project with the Assets panel open and its refresh popup shown +fn refresh_popup() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1920.0, 1032.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(2); + harness.get_all_by_label("Refresh").next().unwrap().click(); + harness.run_steps(2); + harness +} + +/// Moves the app's clock on by more than a minute in one frame, then lets the frames after it settle +fn pass_a_minute(harness: &mut Harness<'_, TextureCraftApp>) { + let now = harness.ctx.input(|input| input.time); + harness.input_mut().time = Some(now + PAST_A_MINUTE); + harness.run_steps(2); +} + +/// A grey one-pixel PNG of `value` +fn grey_png(value: f32) -> Vec { + texturecraft_engine::formats::gray16_png(1, 1, [value].into_iter()).unwrap() +} + +#[test] +fn turning_on_project_resources_reads_a_changed_image_file_again_every_minute() { + let mut harness = refresh_popup(); + let path = std::env::temp_dir().join(format!("texturecraft-auto-update-{}.png", std::process::id())); + std::fs::write(&path, grey_png(0.2)).unwrap(); + let name = harness.state_mut().run("resource.import", json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + let before = harness.state().session.images[&name].rgba.clone(); + std::fs::write(&path, grey_png(0.8)).unwrap(); + + pass_a_minute(&mut harness); + let while_off = harness.state().session.images[&name].rgba.clone(); + harness.get_by_label("Resources used in project").click(); + harness.run_steps(2); + pass_a_minute(&mut harness); + let after = harness.state().session.images[&name].rgba.clone(); + std::fs::remove_file(path).unwrap(); + + assert_eq!(while_off, before, "nothing is read again while automatic updates are off"); + assert!(harness.state().ui.shelf_updates.resources, "the switch turned the update on"); + assert_ne!(after, before, "the changed file was read again within a minute"); +} + +#[test] +fn turning_on_the_assets_panel_reads_the_saved_brushes_again_every_minute() { + let mut harness = refresh_popup(); + let stale = UserBrush { name: "Stale brush marker".into(), brush: Default::default(), channels: None, file: None }; + harness.state_mut().session.brush_presets.list.push(stale); + + harness.get_by_label("Assets panel").click(); + harness.run_steps(2); + pass_a_minute(&mut harness); + + assert!(harness.state().session.brush_presets.find("Stale brush marker").is_none(), "the brushes folder was read again"); +} + +#[test] +fn an_automatic_update_waits_for_the_stroke_under_way_to_end() { + let mut harness = refresh_popup(); + let path = std::env::temp_dir().join(format!("texturecraft-auto-update-stroke-{}.png", std::process::id())); + std::fs::write(&path, grey_png(0.2)).unwrap(); + let name = harness.state_mut().run("resource.import", json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + let before = harness.state().session.images[&name].rgba.clone(); + harness.get_by_label("Resources used in project").click(); + harness.run_steps(2); + std::fs::write(&path, grey_png(0.8)).unwrap(); + + harness.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap(); + pass_a_minute(&mut harness); + let during_stroke = harness.state().session.images[&name].rgba.clone(); + harness.state_mut().session.end_stroke().unwrap(); + harness.run_steps(2); + let after_stroke = harness.state().session.images[&name].rgba.clone(); + std::fs::remove_file(path).unwrap(); + + assert_eq!(during_stroke, before, "nothing is read again while a stroke is under way"); + assert_ne!(after_stroke, before, "the update runs once the stroke ended"); + assert_eq!(harness.state().session.doc.resources[&name].as_slice(), grey_png(0.8).as_slice(), "the stroke's undo state didn't swallow the update"); +} From 9e6aa0f865b0126befde56bed269a2287b101f8a Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:29:05 +0000 Subject: [PATCH 08/16] Assets: dragged assets follow the pointer with a badge saying whether the place under it takes them --- crates/ui-egui/src/dock.rs | 13 +- crates/ui-egui/src/lib.rs | 5 + crates/ui-egui/src/shelf.rs | 32 ++--- crates/ui-egui/src/shelf_drag_ghost.rs | 130 ++++++++++++++++++ crates/ui-egui/src/shelf_drag_verdict.rs | 10 ++ .../ui-egui/tests/it/display_environment.rs | 2 +- crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/shelf_drag_ghost.rs | 66 +++++++++ crates/ui-egui/tests/it/shelf_drop.rs | 2 +- crates/ui-egui/tests/it/stencil.rs | 2 +- crates/ui-egui/tests/ui_snapshots.rs | 58 ++++++++ 11 files changed, 297 insertions(+), 24 deletions(-) create mode 100644 crates/ui-egui/src/shelf_drag_ghost.rs create mode 100644 crates/ui-egui/src/shelf_drag_verdict.rs create mode 100644 crates/ui-egui/tests/it/shelf_drag_ghost.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index e7efb8b9..e904046d 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -174,6 +174,9 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { _ => {} } let material = response.dnd_hover_payload::().is_some_and(|drag| drag.asset.is_material()); + if material { + crate::shelf_drag_ghost::accept(ui.ctx()); + } if response.dnd_hover_payload::().is_some() || material { ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(DROP_STROKE, tokens.accent)); } @@ -740,6 +743,11 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let moving = row.dnd_hover_payload::().is_some_and(|dragged| !in_drag(app, *dragged)); let drop_stroke = Stroke::new(DROP_LINE_WIDTH, tokens.accent); let shelf_material = shelf.as_ref().is_some_and(Asset::is_material); + let shelf_mask = matches!(shelf, Some(Asset::SmartMask(_) | Asset::SavedMask(_))); + let shelf_filter = matches!(shelf, Some(Asset::Filter(_))) && !layer.is_group(); + if shelf_material || shelf_mask || shelf_filter { + crate::shelf_drag_ghost::accept(&row.ctx); + } if moving || shelf_material { if inside { painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside); @@ -748,9 +756,9 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } else { painter.line_segment([rect.left_top(), rect.right_top()], drop_stroke); } - } else if matches!(shelf, Some(Asset::SmartMask(_) | Asset::SavedMask(_))) { + } else if shelf_mask { painter.rect_stroke(mask_rect.expand(HIGHLIGHT_OUTSET), THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Outside); - } else if matches!(shelf, Some(Asset::Filter(_))) && !layer.is_group() { + } else if shelf_filter { painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside); } if let Some(dragged) = dnd_release::(&row) @@ -1790,6 +1798,7 @@ pub(crate) fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { } ui.painter().rect_stroke(resp.rect.shrink(1.0), 3.0, Stroke::new(2.0, Tokens::get(ui.ctx()).accent), egui::StrokeKind::Inside); + crate::shelf_drag_ghost::accept(ui.ctx()); match dnd_release::(resp).map(|d| d.asset.clone()) { Some(Asset::Texture(name)) => Some(name), _ => None, diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f49d4d4e..df72f333 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -138,6 +138,8 @@ pub mod settings_window; pub mod shader_settings; pub mod shelf; pub mod shelf_custom_preview; +pub mod shelf_drag_ghost; +pub mod shelf_drag_verdict; mod shelf_entry; pub mod shelf_favorite; mod shelf_folders; @@ -1197,6 +1199,9 @@ impl eframe::App for TextureCraftApp { egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| if hide_ui { viewport::central(self, ui) } else { docking::show(self, ui) }); windows::show(self, &ctx); + // After every drop target has said whether it takes the dragged asset + shelf_drag_ghost::show(&ctx); + // Finish after the dock and windows have requested their thumbnails self.layer_panel.end(&ctx, &self.session); diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 3431f405..7bed8f3e 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -108,10 +108,12 @@ impl Asset { } /// The drag-and-drop payload of a shelf tile. -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct ShelfDrag { pub asset: Asset, pub label: String, + /// The tile's thumbnail, shown at the pointer while dragging (the name when there is none) + pub thumb: Option, } /// Apply `asset` the way a shelf click does: a simple material becomes the brush's material (no @@ -217,8 +219,14 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response Asset::SmartMask(_) | Asset::SavedMask(_) | Asset::Filter(_) => false, }; let onto_set = |asset: &Asset| zone == DropZone::View3d && asset.goes_onto_set(); - if response.dnd_hover_payload::().is_some_and(|drag| accepts(&drag) && !onto_set(&drag.asset)) { - ui.painter().rect_stroke(response.rect.shrink(1.0), 3.0, Stroke::new(2.0, tokens.accent), egui::StrokeKind::Inside); + if let Some(drag) = response.dnd_hover_payload::().filter(|drag| accepts(drag)) { + // The 3D view outlines the set under the pointer itself; its background takes nothing + if !onto_set(&drag.asset) { + ui.painter().rect_stroke(response.rect.shrink(1.0), 3.0, Stroke::new(2.0, tokens.accent), egui::StrokeKind::Inside); + crate::shelf_drag_ghost::accept(ui.ctx()); + } else if set_under_pointer(app, ui, response).is_some() { + crate::shelf_drag_ghost::accept(ui.ctx()); + } } let pointer = ui.input(|input| input.pointer.interact_pos()); @@ -252,7 +260,6 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response /// The Assets panel body (a dock tab) pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { - let ctx = ui.ctx().clone(); let filter = app.ui.shelf_filter.to_lowercase(); scan_library(app); let all_entries = ShelfEntry::all(app); @@ -334,7 +341,6 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { grid(app, ui, &entries, grid_rect.height(), [saved_materials, saved_masks], show_user_brushes, &filter); }); ui.scope_builder(egui::UiBuilder::new().max_rect(toolbar_rect), |ui| crate::shelf_toolbar::show(app, ui)); - drag_preview(&ctx); } /// The tiles of `entries` in a scroll area `height` high, then user brushes, saved smart materials and saved smart masks when selected @@ -391,18 +397,6 @@ fn search_field(app: &mut TextureCraftApp, ui: &mut Ui) { }); } -/// The dragged asset's name next to the pointer. -fn drag_preview(ctx: &egui::Context) { - let tk = Tokens::get(ctx); - let (Some(d), Some(pos)) = (egui::DragAndDrop::payload::(ctx), ctx.input(|i| i.pointer.hover_pos())) else { return }; - let p = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("shelf_drag"))); - let galley = p.layout_no_wrap(d.label.clone(), egui::FontId::proportional(11.0), tk.text_strong); - let rect = egui::Rect::from_min_size(pos + vec2(14.0, 12.0), galley.size() + vec2(12.0, 6.0)); - p.rect_filled(rect, 3.0, tk.row_selected); - p.rect_stroke(rect, 3.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); - p.galley(rect.min + vec2(6.0, 3.0), galley, tk.text_strong); -} - pub(crate) fn matches(filter: &str, texts: &[&str]) -> bool { filter.is_empty() || texts.iter().any(|t| t.to_lowercase().contains(filter)) } @@ -501,7 +495,7 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str, masks: bool) { let location = path.display().to_string(); let asset = if masks { Asset::SavedMask(location) } else { Asset::Library(location) }; if response.drag_started() { - response.dnd_set_drag_payload(ShelfDrag { asset, label: label.to_owned() }); + response.dnd_set_drag_payload(ShelfDrag { asset, label: label.to_owned(), thumb: None }); } else { selected.push(asset); } @@ -604,7 +598,7 @@ fn tile_in_view( if let Some(asset) = drag && response.drag_started() { - response.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string() }); + response.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string(), thumb: texture.clone() }); } let painter = ui.painter(); diff --git a/crates/ui-egui/src/shelf_drag_ghost.rs b/crates/ui-egui/src/shelf_drag_ghost.rs new file mode 100644 index 00000000..05f311af --- /dev/null +++ b/crates/ui-egui/src/shelf_drag_ghost.rs @@ -0,0 +1,130 @@ +//! The picture that follows the pointer while an asset is dragged from the Assets panel, with a +//! badge on its corner saying whether the place under the pointer takes the asset + +use egui::{Color32, Context, Id, LayerId, Order, Pos2, Rect, Stroke, Vec2, vec2}; + +use crate::shelf::ShelfDrag; +pub use crate::shelf_drag_verdict::Verdict; +use crate::theme::Tokens; + +/// Side of the dragged asset's thumbnail +const GHOST_SIZE: f32 = 48.0; + +/// The thumbnail's top-left corner from the pointer: just under its tip +const GHOST_OFFSET: Vec2 = vec2(4.0, 4.0); + +/// How opaque the thumbnail is, so the target shows through it +const GHOST_OPACITY: f32 = 0.6; + +/// Corner rounding of the name chip +const CHIP_ROUNDING: f32 = 3.0; + +/// Side of the badge +const BADGE_SIZE: f32 = 9.0; + +/// The badge's centre from the pointer: past the pointer arrow's tail, on the thumbnail's corner +const BADGE_OFFSET: Vec2 = vec2(14.0, 22.0); + +/// Size of the badge's icon +const BADGE_ICON_SIZE: f32 = 7.5; + +/// Corner rounding of the square badge +const BADGE_ROUNDING: f32 = 2.0; + +/// Fill of the square badge and colour of the icon on the red one +const BADGE_LIGHT: Color32 = Color32::from_gray(245); + +/// Colour of the icon on the square badge +const BADGE_DARK: Color32 = Color32::from_gray(35); + +/// Opacity of the thin dark outline that keeps the badge apart from whatever is under it +const BADGE_OUTLINE_ALPHA: u8 = 140; + +/// Padding of the name chip shown when the asset has no thumbnail +const CHIP_PADDING: Vec2 = vec2(6.0, 3.0); + +/// Text size of the name chip +const CHIP_TEXT_SIZE: f32 = 11.0; + +/// Pass number of the last drop target that took the dragged asset (ctx temp data) +const ACCEPTED: &str = "shelf_drag_accepted"; + +/// What the last pass painted (ctx temp data) +const SHOWN: &str = "shelf_drag_shown"; + +/// The ghost as the last pass painted it +#[derive(Clone, Copy, Debug)] +pub struct Shown { + /// What the badge says + pub verdict: Verdict, + /// Where the thumbnail (or the name chip) is + pub ghost: Rect, + /// Where the badge is + pub badge: Rect, +} + +/// Note that the drop target being drawn takes the dragged asset, where it paints its drop highlight +pub(crate) fn accept(ctx: &Context) { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|data| data.insert_temp(Id::unique(ACCEPTED), pass)); +} + +/// The ghost painted this pass, if an asset is being dragged +pub fn shown(ctx: &Context) -> Option { + ctx.data(|data| data.get_temp(Id::unique(SHOWN))) +} + +/// Paint the dragged asset and its badge at the pointer, once a pass after every drop target +pub(crate) fn show(ctx: &Context) { + let (Some(drag), Some(pointer)) = (egui::DragAndDrop::payload::(ctx), ctx.input(|input| input.pointer.hover_pos())) else { + ctx.data_mut(|data| data.remove::(Id::unique(SHOWN))); + return; + }; + + let pass = ctx.cumulative_pass_nr(); + let accepted = ctx.data(|data| data.get_temp::(Id::unique(ACCEPTED))) == Some(pass); + let verdict = if accepted { Verdict::Valid } else { Verdict::NotValid }; + let painter = ctx.layer_painter(LayerId::new(Order::Tooltip, Id::unique("shelf_drag_ghost"))); + let tokens = Tokens::get(ctx); + + let ghost = match &drag.thumb { + Some(thumb) => { + let rect = Rect::from_min_size(pointer + GHOST_OFFSET, Vec2::splat(GHOST_SIZE)); + let uv = Rect::from_min_max(Pos2::ZERO, egui::pos2(1.0, 1.0)); + painter.image(thumb.id(), rect, uv, Color32::WHITE.gamma_multiply(GHOST_OPACITY)); + rect + } + None => name_chip(&painter, &tokens, pointer + GHOST_OFFSET, &drag.label), + }; + let badge = badge(&painter, &tokens, pointer + BADGE_OFFSET, verdict); + ctx.data_mut(|data| data.insert_temp(Id::unique(SHOWN), Shown { verdict, ghost, badge })); +} + +/// The asset's name in a chip at `top_left`, for assets without a thumbnail (saved smart materials) +fn name_chip(painter: &egui::Painter, tokens: &Tokens, top_left: Pos2, label: &str) -> Rect { + let galley = painter.layout_no_wrap(label.to_owned(), egui::FontId::proportional(CHIP_TEXT_SIZE), tokens.text_strong); + let rect = Rect::from_min_size(top_left, galley.size() + CHIP_PADDING * 2.0); + painter.rect_filled(rect, CHIP_ROUNDING, tokens.row_selected); + painter.rect_stroke(rect, CHIP_ROUNDING, Stroke::new(1.0, tokens.accent), egui::StrokeKind::Inside); + painter.galley(rect.min + CHIP_PADDING, galley, tokens.text_strong); + rect +} + +/// The badge at `centre`: a crosshair on a light square where a drop works, else a no-entry sign +fn badge(painter: &egui::Painter, tokens: &Tokens, centre: Pos2, verdict: Verdict) -> Rect { + let rect = Rect::from_center_size(centre, Vec2::splat(BADGE_SIZE)); + let outline = Stroke::new(1.0, Color32::from_black_alpha(BADGE_OUTLINE_ALPHA)); + let (icon, color) = match verdict { + Verdict::Valid => { + painter.rect(rect, BADGE_ROUNDING, BADGE_LIGHT, outline, egui::StrokeKind::Outside); + (egui_phosphor::regular::CROSSHAIR_SIMPLE, BADGE_DARK) + } + Verdict::NotValid => { + painter.circle(centre, BADGE_SIZE / 2.0, tokens.danger, outline); + (egui_phosphor::regular::PROHIBIT, BADGE_LIGHT) + } + }; + let glyph = painter.layout_no_wrap(icon.to_owned(), egui::FontId::proportional(BADGE_ICON_SIZE), color); + painter.galley(centre - glyph.mesh_bounds.center().to_vec2(), glyph, color); + rect.expand(outline.width) +} diff --git a/crates/ui-egui/src/shelf_drag_verdict.rs b/crates/ui-egui/src/shelf_drag_verdict.rs new file mode 100644 index 00000000..b6713b95 --- /dev/null +++ b/crates/ui-egui/src/shelf_drag_verdict.rs @@ -0,0 +1,10 @@ +//! What the drag badge says about the place under the pointer + +/// Whether the place under the pointer takes the dragged asset +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Verdict { + /// A drop here does something: a crosshair on a light square + Valid, + /// A drop here does nothing: a no-entry sign on red + NotValid, +} diff --git a/crates/ui-egui/tests/it/display_environment.rs b/crates/ui-egui/tests/it/display_environment.rs index 66cfff9f..46a785ca 100644 --- a/crates/ui-egui/tests/it/display_environment.rs +++ b/crates/ui-egui/tests/it/display_environment.rs @@ -107,7 +107,7 @@ fn an_image_dropped_on_the_slot_becomes_the_environment() { h.run_steps(SETTLE); let slot = h.get_by_role_and_label(Role::Button, "Studio Soft").rect().center(); - egui::DragAndDrop::set_payload(&h.ctx, ShelfDrag { asset: Asset::Texture(name.clone()), label: "Dragged".into() }); + egui::DragAndDrop::set_payload(&h.ctx, ShelfDrag { asset: Asset::Texture(name.clone()), label: "Dragged".into(), thumb: None }); h.hover_at(slot); h.run_steps(2); h.event(Event::PointerButton { pos: slot, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 580812c5..7354a597 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -79,6 +79,7 @@ mod rename_anchor; mod reset_ui; mod settings_window; mod shelf_click; +mod shelf_drag_ghost; mod shelf_drop; mod shelf_hover_preview; mod shelf_menu; diff --git a/crates/ui-egui/tests/it/shelf_drag_ghost.rs b/crates/ui-egui/tests/it/shelf_drag_ghost.rs new file mode 100644 index 00000000..8311846f --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_drag_ghost.rs @@ -0,0 +1,66 @@ +//! Dragging an asset from the Assets panel shows it at the pointer with a badge on its corner that says +//! whether the place under the pointer takes it + +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::materials::MATERIALS; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::shelf_drag_ghost::{Verdict, shown}; + +/// Distance between the view points searched for a set or the background +const SEARCH_STEP: f32 = 8.0; + +/// How far the pointer moves off the tile before it counts as a drag +const DRAG_START: f32 = 12.0; + +/// The sample project at 1600 x 960, the shelf on Materials +fn sample_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + harness +} + +/// The first point of the 3D view showing texture set `set`, or the background when `None` +fn point_over(harness: &Harness<'_, TextureCraftApp>, set: Option) -> Pos2 { + let app = harness.state(); + let rect = app.viewport_rect; + let steps = |length: f32| (1..(length / SEARCH_STEP) as usize).map(|step| step as f32 * SEARCH_STEP); + + steps(rect.height()) + .flat_map(|y| steps(rect.width()).map(move |x| (x, y))) + .find(|&(x, y)| app.session.texture_set_at(Vec2::new(x, y), app.session.viewport) == set) + .map(|(x, y)| rect.min + egui::vec2(x, y)) + .unwrap() +} + +#[test] +fn the_badge_says_whether_the_place_under_the_pointer_takes_the_asset_without_covering_the_pointer() { + // The grid's first plain material (by name), so its tile is in view + let material = MATERIALS.iter().filter(|material| !material.smart).min_by_key(|material| material.label.to_lowercase()).unwrap(); + let mut harness = sample_app(); + let (set, background) = (point_over(&harness, Some(0)), point_over(&harness, None)); + let tile = harness.get_all_by_label(material.label).next().unwrap().rect().center(); + assert!(shown(&harness.ctx).is_none(), "nothing follows the pointer before a drag"); + + harness.event(Event::PointerButton { pos: tile, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + harness.hover_at(tile + vec2(DRAG_START, DRAG_START)); + harness.run_steps(2); + + let mut seen = Vec::new(); + for target in [set, background] { + harness.hover_at(target); + harness.run_steps(2); + let ghost = shown(&harness.ctx).expect("the dragged asset follows the pointer"); + assert!(ghost.badge.min.x > target.x && ghost.badge.min.y > target.y, "the badge leaves the pointer's tip clear"); + seen.push(ghost.verdict); + } + assert_eq!(seen, [Verdict::Valid, Verdict::NotValid], "a texture set takes a material, the background doesn't"); + + harness.event(Event::PointerButton { pos: background, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert!(shown(&harness.ctx).is_none(), "the ghost goes when the drag ends"); +} diff --git a/crates/ui-egui/tests/it/shelf_drop.rs b/crates/ui-egui/tests/it/shelf_drop.rs index d1c732fd..a6c999b0 100644 --- a/crates/ui-egui/tests/it/shelf_drop.rs +++ b/crates/ui-egui/tests/it/shelf_drop.rs @@ -45,7 +45,7 @@ fn drop_material(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { /// Drop shelf `asset` at `position`, as a drag from the shelf ends there fn drop_asset(harness: &mut Harness<'_, TextureCraftApp>, asset: Asset, position: Pos2) { - egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset, label: "Dragged".into() }); + egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset, label: "Dragged".into(), thumb: None }); harness.hover_at(position); harness.run_steps(2); diff --git a/crates/ui-egui/tests/it/stencil.rs b/crates/ui-egui/tests/it/stencil.rs index c746d213..178d1ab3 100644 --- a/crates/ui-egui/tests/it/stencil.rs +++ b/crates/ui-egui/tests/it/stencil.rs @@ -85,7 +85,7 @@ fn an_assets_image_dropped_on_the_stencil_slot_becomes_the_stencil() { assert!(harness.state().session.tool.stencil.is_none()); let slot = harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("None")).unwrap().rect().center(); - egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset: Asset::Texture(name.clone()), label: "Dragged".into() }); + egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset: Asset::Texture(name.clone()), label: "Dragged".into(), thumb: None }); harness.hover_at(slot); harness.run_steps(2); harness.event(Event::PointerButton { pos: slot, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index cda0398b..bffa737b 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -686,6 +686,64 @@ fn smart_material_shelf_snapshot() { save(&mut harness, &output_dir, "smart-material-hover"); } +/// A smart material dragged from the Assets panel over a texture set, then over the background +#[test] +#[ignore] +fn shelf_drag_ghost_snapshots() { + use egui::{Event, Modifiers, PointerButton, vec2}; + use texturecraft_engine::geom::glam::Vec2; + use texturecraft_engine::materials::MATERIALS; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + // The system draws the pointer, not the app + .with_render_cursor(false) + .wgpu() + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.shelf_tab = 1; + let material = MATERIALS.iter().find(|material| material.id == "steel_painted_worn").unwrap(); + let context = harness.ctx.clone(); + let started = std::time::Instant::now(); + while harness.state_mut().thumbs.material(&context, material.id).is_none() { + assert!(started.elapsed() < std::time::Duration::from_secs(120), "the material's thumbnail did not arrive"); + std::thread::sleep(std::time::Duration::from_millis(20)); + harness.run_steps(1); + } + harness.run_steps(2); + + // The first view points showing a texture set and the background + let point_over = |harness: &Harness<'_, TextureCraftApp>, set: Option| { + let app = harness.state(); + let rect = app.viewport_rect; + let steps = |length: f32| (1..(length / 8.0) as usize).map(|step| step as f32 * 8.0); + steps(rect.height()) + .flat_map(|y| steps(rect.width()).map(move |x| (x, y))) + .find(|&(x, y)| app.session.texture_set_at(Vec2::new(x, y), app.session.viewport) == set) + .map(|(x, y)| rect.min + vec2(x, y)) + .unwrap() + }; + let (on_set, background) = (point_over(&harness, Some(0)), point_over(&harness, None)); + let on_set = on_set + vec2(40.0, 40.0); + + let tile = harness.get_by_role_and_label(egui::Role::Button, material.label).rect().center(); + harness.event(Event::PointerButton { pos: tile, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + harness.hover_at(tile + vec2(12.0, 12.0)); + harness.run_steps(2); + for (target, name) in [(on_set, "drag-ghost-valid"), (background, "drag-ghost-not-valid")] { + harness.hover_at(target); + harness.run_steps(2); + save(&mut harness, &output_dir, name); + if let Some(shown) = texturecraft_ui_egui::shelf_drag_ghost::shown(&harness.ctx) { + std::fs::write(output_dir.join(format!("{name}.pointer.txt")), format!("{} {} {:?}", target.x, target.y, shown.verdict)).unwrap(); + } + } +} + /// Compact nested rows must keep their content, mask and effect controls in the panel. #[test] #[ignore] From f7fde16e58e60d91463bc0db44fec2697c2a839f Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:44:05 +0000 Subject: [PATCH 09/16] Assets: the folder button opens a second Assets panel with its own search, type and folder --- crates/ui-egui/src/docking.rs | 19 +++++++---- crates/ui-egui/src/lib.rs | 2 ++ crates/ui-egui/src/shelf_query.rs | 24 ++++++++++++++ crates/ui-egui/src/shelf_second.rs | 23 +++++++++++++ crates/ui-egui/src/shelf_toolbar.rs | 5 ++- crates/ui-egui/src/state.rs | 5 +++ crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/shelf_second.rs | 44 +++++++++++++++++++++++++ 8 files changed, 116 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/shelf_query.rs create mode 100644 crates/ui-egui/src/shelf_second.rs create mode 100644 crates/ui-egui/tests/it/shelf_second.rs diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 761928ec..fd2cc368 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -29,6 +29,8 @@ pub(crate) use shown_group_tab::HEADER_TITLE_LEFT; pub enum Panel { Viewport, Assets, + /// A second Assets panel with its own search, type and folder (the Assets panel's folder button) + AssetsSecond, // Saved layouts name the bake panels by their earlier names #[serde(rename = "BakeMaps")] MeshMapSettings, @@ -82,7 +84,7 @@ impl Panel { use crate::state::Mode; match self { Self::MeshMapSettings | Self::CommonSettings | Self::MeshMapBakers | Self::BakingLog => mode == Mode::Baking, - Self::Assets | Self::Layers | Self::Properties | Self::TextureSetSettings | Self::Export => mode == Mode::Painting, + Self::Assets | Self::AssetsSecond | Self::Layers | Self::Properties | Self::TextureSetSettings | Self::Export => mode == Mode::Painting, Self::History => mode != Mode::Rendering, Self::Shader => mode != Mode::Baking, Self::Renderer => mode == Mode::Rendering, @@ -90,9 +92,10 @@ impl Panel { } } - pub const ALL: [Panel; 16] = [ + pub const ALL: [Panel; 17] = [ Panel::Viewport, Panel::Assets, + Panel::AssetsSecond, Panel::MeshMapSettings, Panel::CommonSettings, Panel::MeshMapBakers, @@ -113,6 +116,8 @@ impl Panel { match self { Panel::Viewport => "Viewport", Panel::Assets => "Assets", + // The second panel shows every type at first, so it's named for that, as the reference names it + Panel::AssetsSecond => "All", Panel::MeshMapSettings => "Mesh Map Settings", Panel::CommonSettings => "Common Settings", Panel::MeshMapBakers => "Mesh Map Bakers", @@ -194,12 +199,12 @@ pub fn default_workspace() -> Workspace { } } - for panel in [MeshMapSettings, CommonSettings, MeshMapBakers] { + for (panel, anchor) in [(MeshMapSettings, TextureSetList), (CommonSettings, TextureSetList), (MeshMapBakers, TextureSetList), (AssetsSecond, Assets)] { workspace.hidden.push(( panel, Location { floating: None, - anchor: Some(TextureSetList), + anchor: Some(anchor), placement: Placement::Tab { before: None }, size: None, stack: None, @@ -328,7 +333,7 @@ impl Dock { /// Texture sets over the bakers, the two settings tabs, the log under both, then the viewport pub(crate) fn for_baking() -> Self { let mut workspace = default_workspace(); - for panel in [Panel::Assets, Panel::Layers, Panel::TextureSetSettings, Panel::Properties] { + for panel in [Panel::Assets, Panel::AssetsSecond, Panel::Layers, Panel::TextureSetSettings, Panel::Properties] { if let Ok(location) = workspace.layout.location(&panel) { workspace.hidden.push((panel, location)); } @@ -558,7 +563,8 @@ fn min_size(panel: Panel) -> Vec2 { /// The body of every panel except the viewport, in the dock or on the rail pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { // No project open: the library and the log work, the other panels about a project stay empty - let works_empty = matches!(panel, Panel::Assets | Panel::Log | Panel::Layers | Panel::TextureSetList | Panel::Properties | Panel::Export); + let works_empty = + matches!(panel, Panel::Assets | Panel::AssetsSecond | Panel::Log | Panel::Layers | Panel::TextureSetList | Panel::Properties | Panel::Export); if !app.session.project_open && !works_empty { return; } @@ -568,6 +574,7 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { egui::Frame::new().inner_margin(margin).show(ui, |ui| match panel { Panel::MeshMapSettings => crate::bake_mode::mesh_map_settings_panel(app, ui), Panel::Assets => crate::shelf::body(app, ui), + Panel::AssetsSecond => crate::shelf_second::body(app, ui), Panel::CommonSettings => crate::bake_mode::common_settings_panel(app, ui), Panel::MeshMapBakers => crate::bake_mode::mesh_map_bakers_panel(app, ui), Panel::TextureSetList if app.ui.mode == crate::state::Mode::Baking => crate::bake_mode::texture_sets(app, ui), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index df72f333..77ec52f8 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -146,6 +146,8 @@ mod shelf_folders; mod shelf_menu; pub mod shelf_panes; pub mod shelf_preview; +pub mod shelf_query; +pub mod shelf_second; mod shelf_tabs; mod shelf_toolbar; pub mod shelf_updates; diff --git a/crates/ui-egui/src/shelf_query.rs b/crates/ui-egui/src/shelf_query.rs new file mode 100644 index 00000000..9e9d4b67 --- /dev/null +++ b/crates/ui-egui/src/shelf_query.rs @@ -0,0 +1,24 @@ +//! One Assets panel's query: search, type, folder and favorites only + +use serde::{Deserialize, Serialize}; + +/// One Assets panel's search, type and folder, and whether it shows only favorites +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ShelfQuery { + /// The search text + pub filter: String, + /// The picked type: an index into the shelf's types, or past them for every type + pub tab: usize, + /// The library folder: a library id, then folder names (empty: all libraries) + pub path: Vec, + /// Only favorites (the Favorites saved search) + pub favorites_only: bool, +} + +impl Default for ShelfQuery { + /// Every asset of every type + fn default() -> Self { + Self { filter: String::new(), tab: crate::shelf_tabs::NO_TYPE, path: Vec::new(), favorites_only: false } + } +} diff --git a/crates/ui-egui/src/shelf_second.rs b/crates/ui-egui/src/shelf_second.rs new file mode 100644 index 00000000..4c129816 --- /dev/null +++ b/crates/ui-egui/src/shelf_second.rs @@ -0,0 +1,23 @@ +//! The second Assets panel, opened by the folder button: the same panel with its own query + +use egui::Ui; + +use crate::TextureCraftApp; +use crate::shelf_query::ShelfQuery; + +/// Swap `query` with the first Assets panel's query in `ui` +fn swap_query(ui: &mut crate::state::UiState, query: &mut ShelfQuery) { + std::mem::swap(&mut ui.shelf_filter, &mut query.filter); + std::mem::swap(&mut ui.shelf_tab, &mut query.tab); + std::mem::swap(&mut ui.shelf_path, &mut query.path); + std::mem::swap(&mut ui.shelf_favorites_only, &mut query.favorites_only); +} + +/// The second Assets panel's body: the Assets panel drawn with its own query +pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { + let mut query = std::mem::take(&mut app.ui.shelf_second); + swap_query(&mut app.ui, &mut query); + ui.push_id("assets_second", |ui| crate::shelf::body(app, ui)); + swap_query(&mut app.ui, &mut query); + app.ui.shelf_second = query; +} diff --git a/crates/ui-egui/src/shelf_toolbar.rs b/crates/ui-egui/src/shelf_toolbar.rs index 99a80cb6..c61d37bc 100644 --- a/crates/ui-egui/src/shelf_toolbar.rs +++ b/crates/ui-egui/src/shelf_toolbar.rs @@ -1,4 +1,4 @@ -//! The shelf's bottom toolbar: the side pane toggles on the left; refresh with its update settings, reset query and import on the right +//! The shelf's bottom toolbar: the side pane toggles on the left; refresh, reset query, new panel and import on the right use egui::Ui; use egui_phosphor::regular as ic; @@ -26,6 +26,9 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { if icon_button(ui, ic::PLUS, tr("Import resources..."), false, size).clicked() { crate::menus::invoke(app, &ui.ctx().clone(), "resource.import"); } + if icon_button(ui, ic::FOLDER, tr("New Assets panel"), false, size).clicked() { + app.ui.dock.focus(crate::docking::Panel::AssetsSecond); + } if icon_button(ui, ic::X_CIRCLE, tr("Reset query"), false, size).clicked() { reset_query(app); } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 7caf4d29..3cdf54db 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -593,6 +593,9 @@ pub struct UiState { /// The asset shelf shows only favorites (the Favorites saved search) #[serde(default)] pub shelf_favorites_only: bool, + /// The second Assets panel's search, type and folder, swapped in while it draws + #[serde(default)] + pub shelf_second: crate::shelf_query::ShelfQuery, /// The asset shelf's automatic updates (its refresh popup) #[serde(default)] pub shelf_updates: crate::shelf_updates::ShelfUpdates, @@ -757,6 +760,7 @@ impl UiState { self.shelf_saved_searches = keep.shelf_saved_searches; self.shelf_favorites = keep.shelf_favorites; self.shelf_favorites_only = keep.shelf_favorites_only; + self.shelf_second = keep.shelf_second; self.shelf_custom_previews = keep.shelf_custom_previews; self.shelf_updates = keep.shelf_updates; } @@ -795,6 +799,7 @@ impl Default for UiState { shelf_saved_searches: Vec::new(), shelf_favorites: Vec::new(), shelf_favorites_only: false, + shelf_second: crate::shelf_query::ShelfQuery::default(), shelf_custom_previews: Vec::new(), shelf_updates: crate::shelf_updates::ShelfUpdates::default(), shelf_panes_split: default_shelf_panes_split(), diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 7354a597..85bf32ed 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -84,6 +84,7 @@ mod shelf_drop; mod shelf_hover_preview; mod shelf_menu; mod shelf_panel; +mod shelf_second; mod shelf_updates; mod shift_lines_2d; mod shift_lines_3d; diff --git a/crates/ui-egui/tests/it/shelf_second.rs b/crates/ui-egui/tests/it/shelf_second.rs new file mode 100644 index 00000000..7095f6bc --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_second.rs @@ -0,0 +1,44 @@ +//! The Assets panel's folder button opens a second Assets panel with its own search + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; + +/// The sample project at 1600 x 960 +fn sample_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + harness +} + +/// Type `text` into the search field of the Assets panel shown left of the 3D view +fn search_shown_panel(harness: &mut Harness<'_, TextureCraftApp>, text: &str) { + let left_of_view = harness.state().viewport_rect.min.x; + harness.get_all_by_role(Role::TextInput).find(|field| field.rect().max.x < left_of_view).expect("the shown Assets panel has a search field").click(); + harness.run_steps(2); + harness.event(egui::Event::Text(text.into())); + harness.run_steps(2); +} + +#[test] +fn the_folder_button_opens_a_second_assets_panel_that_searches_on_its_own() { + let mut harness = sample_app(); + assert!(!harness.state().ui.dock.is_open(Panel::AssetsSecond), "one Assets panel at first"); + + harness.get_by_label("New Assets panel").click(); + harness.run_steps(3); + assert!(harness.state().ui.dock.is_visible(Panel::AssetsSecond), "the folder button shows a second Assets panel"); + + search_shown_panel(&mut harness, "brick"); + let ui = &harness.state().ui; + assert_eq!((ui.shelf_second.filter.as_str(), ui.shelf_filter.as_str()), ("brick", ""), "the second panel's search leaves the first panel's alone"); + + harness.state_mut().ui.dock.focus(Panel::Assets); + harness.run_steps(3); + search_shown_panel(&mut harness, "rust"); + let ui = &harness.state().ui; + assert_eq!((ui.shelf_second.filter.as_str(), ui.shelf_filter.as_str()), ("brick", "rust"), "the first panel's search leaves the second panel's alone"); +} From d42bccb2366a60b48cd71a6e6c2b3f94e1d27a37 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:00:45 +0000 Subject: [PATCH 10/16] Assets: snapshots of every pass 2 screen mid-interaction in the three themes --- crates/ui-egui/tests/ui_snapshots.rs | 274 ++++++++++++++++++++++----- 1 file changed, 227 insertions(+), 47 deletions(-) diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index bffa737b..8f8c6718 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -686,62 +686,242 @@ fn smart_material_shelf_snapshot() { save(&mut harness, &output_dir, "smart-material-hover"); } -/// A smart material dragged from the Assets panel over a texture set, then over the background +/// Writes `name` and, beside it, where the pointer is (`.pointer.txt`: x y), so a picture can draw the system's pointer +fn save_with_pointer(harness: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { + save(harness, dir, name); + if let Some(pointer) = harness.ctx.input(|input| input.pointer.hover_pos()) { + std::fs::write(dir.join(format!("{name}.pointer.txt")), format!("{} {}", pointer.x, pointer.y)).unwrap(); + } +} + +/// Assets types the pass 2 snapshots show, as indexes into the Assets panel's type row +const SMART_MATERIALS_TYPE: usize = 1; +const BRUSHES_TYPE: usize = 4; +const TEXTURES_TYPE: usize = 6; + +/// A move from a pressed tile or row long enough to start a drag +const DRAG_START: egui::Vec2 = egui::vec2(12.0, 12.0); + +/// A point in the window's top bar, so no tile shows its hover outline +const AWAY_FROM_TILES: egui::Pos2 = egui::pos2(800.0, 40.0); + +/// How far down the window a point is inside Properties +const PROPERTIES_HEIGHT_SHARE: f32 = 0.75; + +/// The panes' edge drag: steps and points per step +const EDGE_DRAG_STEPS: usize = 4; +const EDGE_DRAG_STEP: f32 = 15.0; + +/// Assets pass 2, every screen mid-interaction (menus, submenu, favorites, custom preview, drag ghost, refresh popup, second panel); `TC_UI_THEMES` adds dark and light #[test] #[ignore] -fn shelf_drag_ghost_snapshots() { - use egui::{Event, Modifiers, PointerButton, vec2}; - use texturecraft_engine::geom::glam::Vec2; +fn assets_pass_two_snapshots() { + use egui::{Event, Modifiers, PointerButton, Role, vec2}; use texturecraft_engine::materials::MATERIALS; + use texturecraft_ui_egui::file_dialogs::Answer; let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; std::fs::create_dir_all(&output_dir).unwrap(); - let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder() - .with_size(egui::vec2(1600.0, 960.0)) - .with_pixels_per_point(1.0) - // The system draws the pointer, not the app - .with_render_cursor(false) - .wgpu() - .build_eframe(|context| TextureCraftApp::new(context, session)); - harness.state_mut().ui.shelf_tab = 1; - let material = MATERIALS.iter().find(|material| material.id == "steel_painted_worn").unwrap(); - let context = harness.ctx.clone(); - let started = std::time::Instant::now(); - while harness.state_mut().thumbs.material(&context, material.id).is_none() { - assert!(started.elapsed() < std::time::Duration::from_secs(120), "the material's thumbnail did not arrive"); - std::thread::sleep(std::time::Duration::from_millis(20)); - harness.run_steps(1); - } - harness.run_steps(2); - - // The first view points showing a texture set and the background - let point_over = |harness: &Harness<'_, TextureCraftApp>, set: Option| { - let app = harness.state(); - let rect = app.viewport_rect; - let steps = |length: f32| (1..(length / 8.0) as usize).map(|step| step as f32 * 8.0); - steps(rect.height()) - .flat_map(|y| steps(rect.width()).map(move |x| (x, y))) - .find(|&(x, y)| app.session.texture_set_at(Vec2::new(x, y), app.session.viewport) == set) - .map(|(x, y)| rect.min + vec2(x, y)) - .unwrap() + let files = std::env::temp_dir().join(format!("texturecraft-assets-pass-two-{}", std::process::id())); + std::fs::create_dir_all(&files).unwrap(); + let brushes = files.join("brushes"); + let plate = files.join("rust_plate.png"); + image::RgbaImage::from_fn(128, 128, |x, y| { + let grain = ((x * 7 + y * 13) % 23) as u8 * 3; + image::Rgba([120 + grain, 66 + grain / 2, 38, 255]) + }) + .save(&plate) + .unwrap(); + let preview = files.join("brushed_preview.png"); + image::RgbaImage::from_fn(160, 120, |x, y| { + let line = 140 + ((y * 37 + x / 9) % 41) as u8; + image::Rgba([line, line, line + 8, 255]) + }) + .save(&preview) + .unwrap(); + let show_in = if cfg!(target_os = "windows") { + "Show in Explorer..." + } else if cfg!(target_os = "macos") { + "Show in Finder..." + } else { + "Show in file manager..." }; - let (on_set, background) = (point_over(&harness, Some(0)), point_over(&harness, None)); - let on_set = on_set + vec2(40.0, 40.0); - let tile = harness.get_by_role_and_label(egui::Role::Button, material.label).rect().center(); - harness.event(Event::PointerButton { pos: tile, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - harness.run_steps(2); - harness.hover_at(tile + vec2(12.0, 12.0)); - harness.run_steps(2); - for (target, name) in [(on_set, "drag-ghost-valid"), (background, "drag-ghost-not-valid")] { - harness.hover_at(target); - harness.run_steps(2); - save(&mut harness, &output_dir, name); - if let Some(shown) = texturecraft_ui_egui::shelf_drag_ghost::shown(&harness.ctx) { - std::fs::write(output_dir.join(format!("{name}.pointer.txt")), format!("{} {} {:?}", target.x, target.y, shown.verdict)).unwrap(); - } + let mut themes = vec![(Brightness::MediumDark, "medium")]; + if std::env::var_os("TC_UI_THEMES").is_some() { + themes.extend([(Brightness::Dark, "dark"), (Brightness::Light, "light")]); } + for (brightness, theme) in themes { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + // The system draws the pointer, not the app + .with_render_cursor(false) + .wgpu() + .build_eframe(|context| TextureCraftApp::new(context, session)); + let app = harness.state_mut(); + app.ui.prefs.brightness = brightness; + app.ui.prefs.language = "en".into(); + let theme_brushes = brushes.join(theme); + std::fs::create_dir_all(&theme_brushes).unwrap(); + app.session.brush_presets.dir = Some(theme_brushes); + app.run("brush.preset.store", serde_json::json!({"name": "Ink soft"})).unwrap(); + let image = app.run("resource.import", serde_json::json!({"path": plate.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + let answer = preview.clone(); + app.file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![answer.clone()])))); + app.ui.shelf_tab = SMART_MATERIALS_TYPE; + let context = harness.ctx.clone(); + let started = std::time::Instant::now(); + loop { + harness.run_steps(1); + let thumbnails = &mut harness.state_mut().thumbs; + if MATERIALS.iter().filter(|material| material.smart).all(|material| thumbnails.material(&context, material.id).is_some()) { + break; + } + assert!(started.elapsed() < std::time::Duration::from_secs(120), "smart material thumbnails did not arrive"); + std::thread::sleep(std::time::Duration::from_millis(20)); + } + let shot = |harness: &mut Harness<'_, TextureCraftApp>, name: &str| save_with_pointer(harness, &output_dir, &format!("assets-{name}-{theme}")); + let right_click = |harness: &mut Harness<'_, TextureCraftApp>, tile: &str| { + harness.get_all_by_label(tile).next().unwrap_or_else(|| panic!("no tile {tile}")).click_secondary(); + harness.run_steps(3); + }; + let close_menu = |harness: &mut Harness<'_, TextureCraftApp>| { + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + }; + + // 01: a built-in smart material, a row hovered; 03: its greyed Show in + right_click(&mut harness, "Brass Tarnished"); + harness.get_by_label("Export resource...").hover(); + shot(&mut harness, "01-menu-built-in"); + harness.get_by_label("Show in").hover(); + harness.run_steps(30); + shot(&mut harness, "03-show-in-built-in"); + close_menu(&mut harness); + + // 04: two favorites, the newest first, then a favorite's menu; 08: a custom preview on a third tile + for tile in ["Gold Dirty", "Bronze Statue"] { + right_click(&mut harness, tile); + harness.get_by_label("Add to favorites").click(); + harness.run_steps(3); + } + right_click(&mut harness, "Brass Tarnished"); + harness.get_by_label("Set custom preview...").click(); + harness.run_steps(3); + settle_thumbnails(&mut harness); + harness.hover_at(AWAY_FROM_TILES); + shot(&mut harness, "04-favorites-and-custom-preview"); + right_click(&mut harness, "Bronze Statue"); + harness.get_by_label("Remove from favorites").hover(); + shot(&mut harness, "04-menu-favorite"); + close_menu(&mut harness); + + // 05: the drag ghost over the layer stack (takes a material) and over Properties (doesn't) + let viewport_right = harness.state().viewport_rect.max.x; + let layer = harness.get_all_by_role(Role::ListItem).find(|row| row.rect().min.x > viewport_right).expect("a layer row").rect().center(); + // Properties fills the right column under the layer stack, in the window's lower part + let properties = egui::pos2(layer.x, harness.ctx.content_rect().height() * PROPERTIES_HEIGHT_SHARE); + let tile = harness.get_all_by_label("Gold Dirty").next().unwrap().rect().center(); + harness.event(Event::PointerButton { pos: tile, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + harness.hover_at(tile + DRAG_START); + harness.run_steps(2); + for (target, name) in [(layer, "05-drag-valid-layer-stack"), (properties, "05-drag-not-valid-properties")] { + harness.hover_at(target); + harness.run_steps(2); + shot(&mut harness, name); + } + harness.event(Event::PointerButton { pos: properties, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + + // 09: a layer dragged in the layer stack over another row (takes it) and over Properties (doesn't) + harness.state_mut().run("layer.add.paint", serde_json::json!({"name": "Dragged layer"})).unwrap(); + harness.run_steps(3); + let dragged = harness.get_by_role_and_label(Role::ListItem, "Dragged layer").rect().center(); + let rows: Vec<_> = harness.get_all_by_role(Role::ListItem).filter(|row| row.rect().min.x > viewport_right).map(|row| row.rect().center()).collect(); + let other = *rows.iter().find(|at| at.y > dragged.y).expect("a row below it"); + harness.event(Event::PointerButton { pos: dragged, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + harness.hover_at(dragged + DRAG_START); + harness.run_steps(2); + for (target, name) in [(other, "09-layer-drag-valid-row"), (properties, "09-layer-drag-not-valid-properties")] { + harness.hover_at(target); + harness.run_steps(2); + shot(&mut harness, name); + } + harness.event(Event::PointerButton { pos: properties, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + + // 02: a project image and a saved brush; 03: Show in open on the image + harness.state_mut().ui.shelf_tab = TEXTURES_TYPE; + settle_thumbnails(&mut harness); + right_click(&mut harness, &image); + harness.get_by_label("Reload").hover(); + shot(&mut harness, "02-menu-project-image"); + harness.get_by_label("Show in").click(); + harness.run_steps(3); + harness.get_by_label(show_in).hover(); + shot(&mut harness, "03-show-in-image"); + close_menu(&mut harness); + harness.state_mut().ui.shelf_tab = BRUSHES_TYPE; + settle_thumbnails(&mut harness); + right_click(&mut harness, "Ink soft"); + harness.get_by_label("Replace with the current brush").hover(); + shot(&mut harness, "02-menu-saved-brush"); + close_menu(&mut harness); + + // 06: the refresh popup, then with an i hovered + harness.state_mut().ui.shelf_tab = SMART_MATERIALS_TYPE; + harness.run_steps(3); + harness.get_all_by_label("Refresh").next().unwrap().click(); + harness.run_steps(3); + harness.get_by_label("Update Assets panel").hover(); + shot(&mut harness, "06-refresh-popup"); + harness.get_by_label("Reads your saved assets from disk again every few minutes, so new and changed ones show here.").hover(); + harness.run_steps(30); + shot(&mut harness, "06-refresh-info"); + close_menu(&mut harness); + + // 10: both filter panes open, their edge with the grid dragged wider + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.state_mut().ui.shelf_panes.filter_by_path = true; + harness.run_steps(3); + let edge = harness.get_by_label("Resize Assets filter panes and grid").rect().center(); + harness.hover_at(edge); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: edge, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + for step in 1..=EDGE_DRAG_STEPS { + harness.hover_at(edge + vec2(EDGE_DRAG_STEP * step as f32, 0.0)); + harness.run_steps(1); + } + shot(&mut harness, "10-panes-edge-drag"); + harness.event(Event::PointerButton { + pos: edge + vec2(EDGE_DRAG_STEP * EDGE_DRAG_STEPS as f32, 0.0), + button: PointerButton::Primary, + pressed: false, + modifiers: Modifiers::NONE, + }); + harness.state_mut().ui.shelf_panes.saved_searches = false; + harness.state_mut().ui.shelf_panes.filter_by_path = false; + harness.run_steps(3); + + // 07: the folder button hovered, then the second panel searching "brick" + harness.get_by_label("New Assets panel").hover(); + harness.run_steps(30); + shot(&mut harness, "07-folder-button"); + harness.get_all_by_label("New Assets panel").next().unwrap().click(); + harness.run_steps(3); + let left_of_view = harness.state().viewport_rect.min.x; + harness.get_all_by_role(Role::TextInput).find(|field| field.rect().max.x < left_of_view).expect("the second panel's search").click(); + harness.run_steps(2); + harness.event(Event::Text("brick".into())); + settle_thumbnails(&mut harness); + shot(&mut harness, "07-second-panel"); + } + std::fs::remove_dir_all(files).unwrap(); } /// Compact nested rows must keep their content, mask and effect controls in the panel. From e61d99944182cdbb64a622862822bc04f03c57a7 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:37:14 +0000 Subject: [PATCH 11/16] Layers: a layer dragged in the layer stack follows the pointer as a chip with its name and the same badge as dragged assets --- crates/ui-egui/src/dock.rs | 10 +-- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/shelf.rs | 4 +- crates/ui-egui/src/shelf_drag_ghost.rs | 80 +++++++++++++------- crates/ui-egui/src/shelf_drag_ghost_shown.rs | 16 ++++ crates/ui-egui/src/shelf_drag_verdict.rs | 2 +- crates/ui-egui/tests/it/shelf_drag_ghost.rs | 36 ++++++++- 7 files changed, 107 insertions(+), 42 deletions(-) create mode 100644 crates/ui-egui/src/shelf_drag_ghost_shown.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index e904046d..aaa7a3f4 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -174,11 +174,9 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { _ => {} } let material = response.dnd_hover_payload::().is_some_and(|drag| drag.asset.is_material()); - if material { - crate::shelf_drag_ghost::accept(ui.ctx()); - } if response.dnd_hover_payload::().is_some() || material { ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(DROP_STROKE, tokens.accent)); + crate::shelf_drag_ghost::accept(ui.ctx()); } }); select_all_layers(app, ui); @@ -729,6 +727,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } if row.drag_started() && !renaming { row.dnd_set_drag_payload(layer.id.0); + crate::shelf_drag_ghost::start_layer(ui.ctx(), &layer.name); } // A folder midpoint accepts child drops; a smart mask replaces the current mask @@ -745,7 +744,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let shelf_material = shelf.as_ref().is_some_and(Asset::is_material); let shelf_mask = matches!(shelf, Some(Asset::SmartMask(_) | Asset::SavedMask(_))); let shelf_filter = matches!(shelf, Some(Asset::Filter(_))) && !layer.is_group(); - if shelf_material || shelf_mask || shelf_filter { + if moving || shelf_material || shelf_mask || shelf_filter { crate::shelf_drag_ghost::accept(&row.ctx); } if moving || shelf_material { @@ -1797,8 +1796,7 @@ pub(crate) fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { return None; } - ui.painter().rect_stroke(resp.rect.shrink(1.0), 3.0, Stroke::new(2.0, Tokens::get(ui.ctx()).accent), egui::StrokeKind::Inside); - crate::shelf_drag_ghost::accept(ui.ctx()); + crate::shelf_drag_ghost::outline_target(ui, resp.rect); match dnd_release::(resp).map(|d| d.asset.clone()) { Some(Asset::Texture(name)) => Some(name), _ => None, diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 77ec52f8..a16934e2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -139,6 +139,7 @@ pub mod shader_settings; pub mod shelf; pub mod shelf_custom_preview; pub mod shelf_drag_ghost; +pub mod shelf_drag_ghost_shown; pub mod shelf_drag_verdict; mod shelf_entry; pub mod shelf_favorite; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 7bed8f3e..7285787d 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -211,7 +211,6 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response DecalDrop::show_menu(app, ui, response); } - let tokens = Tokens::get(ui.ctx()); let accepts = |drag: &ShelfDrag| match drag.asset { Asset::Alpha(_) => true, Asset::Material(_) | Asset::Library(_) => zone != DropZone::Brush, @@ -222,8 +221,7 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response if let Some(drag) = response.dnd_hover_payload::().filter(|drag| accepts(drag)) { // The 3D view outlines the set under the pointer itself; its background takes nothing if !onto_set(&drag.asset) { - ui.painter().rect_stroke(response.rect.shrink(1.0), 3.0, Stroke::new(2.0, tokens.accent), egui::StrokeKind::Inside); - crate::shelf_drag_ghost::accept(ui.ctx()); + crate::shelf_drag_ghost::outline_target(ui, response.rect); } else if set_under_pointer(app, ui, response).is_some() { crate::shelf_drag_ghost::accept(ui.ctx()); } diff --git a/crates/ui-egui/src/shelf_drag_ghost.rs b/crates/ui-egui/src/shelf_drag_ghost.rs index 05f311af..2c11a2a1 100644 --- a/crates/ui-egui/src/shelf_drag_ghost.rs +++ b/crates/ui-egui/src/shelf_drag_ghost.rs @@ -1,10 +1,10 @@ -//! The picture that follows the pointer while an asset is dragged from the Assets panel, with a -//! badge on its corner saying whether the place under the pointer takes the asset +//! The picture that follows a dragged asset or layer, with a badge saying whether the place under it takes it -use egui::{Color32, Context, Id, LayerId, Order, Pos2, Rect, Stroke, Vec2, vec2}; +use egui::{Color32, Context, Id, LayerId, Order, Pos2, Rect, Stroke, TextureId, Vec2, vec2}; use crate::shelf::ShelfDrag; -pub use crate::shelf_drag_verdict::Verdict; +pub use crate::shelf_drag_ghost_shown::ShelfDragGhostShown; +pub use crate::shelf_drag_verdict::ShelfDragVerdict; use crate::theme::Tokens; /// Side of the dragged asset's thumbnail @@ -46,61 +46,85 @@ const CHIP_PADDING: Vec2 = vec2(6.0, 3.0); /// Text size of the name chip const CHIP_TEXT_SIZE: f32 = 11.0; +/// Width of the outline around a drop target that takes the dragged asset +const TARGET_OUTLINE_WIDTH: f32 = 2.0; + +/// How far the outline sits inside the target's edge, so a neighbouring panel doesn't cut it +const TARGET_OUTLINE_INSET: f32 = 1.0; + +/// Corner rounding of the outline +const TARGET_OUTLINE_ROUNDING: f32 = 3.0; + /// Pass number of the last drop target that took the dragged asset (ctx temp data) const ACCEPTED: &str = "shelf_drag_accepted"; /// What the last pass painted (ctx temp data) const SHOWN: &str = "shelf_drag_shown"; -/// The ghost as the last pass painted it -#[derive(Clone, Copy, Debug)] -pub struct Shown { - /// What the badge says - pub verdict: Verdict, - /// Where the thumbnail (or the name chip) is - pub ghost: Rect, - /// Where the badge is - pub badge: Rect, -} +/// The name of the layer being dragged in the layer stack, whose payload is only its id (ctx temp data) +const LAYER: &str = "shelf_drag_layer"; -/// Note that the drop target being drawn takes the dragged asset, where it paints its drop highlight +/// Note that the drop target being drawn takes the dragged asset or layer, where it paints its drop highlight pub(crate) fn accept(ctx: &Context) { let pass = ctx.cumulative_pass_nr(); ctx.data_mut(|data| data.insert_temp(Id::unique(ACCEPTED), pass)); } -/// The ghost painted this pass, if an asset is being dragged -pub fn shown(ctx: &Context) -> Option { +/// Outlines drop target `rect` while the dragged asset hovers it, and notes that it takes the asset +pub(crate) fn outline_target(ui: &egui::Ui, rect: Rect) { + let stroke = Stroke::new(TARGET_OUTLINE_WIDTH, Tokens::get(ui.ctx()).accent); + ui.painter().rect_stroke(rect.shrink(TARGET_OUTLINE_INSET), TARGET_OUTLINE_ROUNDING, stroke, egui::StrokeKind::Inside); + accept(ui.ctx()); +} + +/// Note the name of the layer whose drag starts: a chip with it follows the pointer, since an empty layer's thumbnail shows nothing +pub(crate) fn start_layer(ctx: &Context, label: &str) { + ctx.data_mut(|data| data.insert_temp(Id::unique(LAYER), label.to_owned())); +} + +/// The picture and name of what is being dragged: an asset, or a layer (its name only) +fn dragged(ctx: &Context) -> Option<(Option, String)> { + if let Some(drag) = egui::DragAndDrop::payload::(ctx) { + return Some((drag.thumb.as_ref().map(egui::TextureHandle::id), drag.label.clone())); + } + if !egui::DragAndDrop::has_payload_of_type::(ctx) { + return None; + } + ctx.data(|data| data.get_temp::(Id::unique(LAYER))).map(|label| (None, label)) +} + +/// The ghost painted this pass, if an asset or a layer is being dragged +pub fn shown(ctx: &Context) -> Option { ctx.data(|data| data.get_temp(Id::unique(SHOWN))) } /// Paint the dragged asset and its badge at the pointer, once a pass after every drop target pub(crate) fn show(ctx: &Context) { - let (Some(drag), Some(pointer)) = (egui::DragAndDrop::payload::(ctx), ctx.input(|input| input.pointer.hover_pos())) else { - ctx.data_mut(|data| data.remove::(Id::unique(SHOWN))); + let (Some((thumb, label)), Some(pointer)) = (dragged(ctx), ctx.input(|input| input.pointer.hover_pos())) else { + ctx.data_mut(|data| data.remove::(Id::unique(SHOWN))); return; }; let pass = ctx.cumulative_pass_nr(); let accepted = ctx.data(|data| data.get_temp::(Id::unique(ACCEPTED))) == Some(pass); - let verdict = if accepted { Verdict::Valid } else { Verdict::NotValid }; + let verdict = if accepted { ShelfDragVerdict::Valid } else { ShelfDragVerdict::NotValid }; let painter = ctx.layer_painter(LayerId::new(Order::Tooltip, Id::unique("shelf_drag_ghost"))); let tokens = Tokens::get(ctx); - let ghost = match &drag.thumb { + let ghost = match thumb { Some(thumb) => { let rect = Rect::from_min_size(pointer + GHOST_OFFSET, Vec2::splat(GHOST_SIZE)); let uv = Rect::from_min_max(Pos2::ZERO, egui::pos2(1.0, 1.0)); - painter.image(thumb.id(), rect, uv, Color32::WHITE.gamma_multiply(GHOST_OPACITY)); + painter.image(thumb, rect, uv, Color32::WHITE.gamma_multiply(GHOST_OPACITY)); rect } - None => name_chip(&painter, &tokens, pointer + GHOST_OFFSET, &drag.label), + None => name_chip(&painter, &tokens, pointer + GHOST_OFFSET, &label), }; let badge = badge(&painter, &tokens, pointer + BADGE_OFFSET, verdict); - ctx.data_mut(|data| data.insert_temp(Id::unique(SHOWN), Shown { verdict, ghost, badge })); + ctx.data_mut(|data| data.insert_temp(Id::unique(SHOWN), ShelfDragGhostShown { verdict, ghost, badge })); } -/// The asset's name in a chip at `top_left`, for assets without a thumbnail (saved smart materials) +/// The name in a chip at `top_left`, for what has no thumbnail (saved smart materials and masks, layers) fn name_chip(painter: &egui::Painter, tokens: &Tokens, top_left: Pos2, label: &str) -> Rect { let galley = painter.layout_no_wrap(label.to_owned(), egui::FontId::proportional(CHIP_TEXT_SIZE), tokens.text_strong); let rect = Rect::from_min_size(top_left, galley.size() + CHIP_PADDING * 2.0); @@ -111,15 +135,15 @@ fn name_chip(painter: &egui::Painter, tokens: &Tokens, top_left: Pos2, label: &s } /// The badge at `centre`: a crosshair on a light square where a drop works, else a no-entry sign -fn badge(painter: &egui::Painter, tokens: &Tokens, centre: Pos2, verdict: Verdict) -> Rect { +fn badge(painter: &egui::Painter, tokens: &Tokens, centre: Pos2, verdict: ShelfDragVerdict) -> Rect { let rect = Rect::from_center_size(centre, Vec2::splat(BADGE_SIZE)); let outline = Stroke::new(1.0, Color32::from_black_alpha(BADGE_OUTLINE_ALPHA)); let (icon, color) = match verdict { - Verdict::Valid => { + ShelfDragVerdict::Valid => { painter.rect(rect, BADGE_ROUNDING, BADGE_LIGHT, outline, egui::StrokeKind::Outside); (egui_phosphor::regular::CROSSHAIR_SIMPLE, BADGE_DARK) } - Verdict::NotValid => { + ShelfDragVerdict::NotValid => { painter.circle(centre, BADGE_SIZE / 2.0, tokens.danger, outline); (egui_phosphor::regular::PROHIBIT, BADGE_LIGHT) } diff --git a/crates/ui-egui/src/shelf_drag_ghost_shown.rs b/crates/ui-egui/src/shelf_drag_ghost_shown.rs new file mode 100644 index 00000000..2e961053 --- /dev/null +++ b/crates/ui-egui/src/shelf_drag_ghost_shown.rs @@ -0,0 +1,16 @@ +//! Where the drag ghost and its badge were painted, and what the badge said + +use egui::Rect; + +use crate::shelf_drag_verdict::ShelfDragVerdict; + +/// The ghost as the last pass painted it +#[derive(Clone, Copy, Debug)] +pub struct ShelfDragGhostShown { + /// What the badge says + pub verdict: ShelfDragVerdict, + /// Where the thumbnail (or the name chip) is + pub ghost: Rect, + /// Where the badge is + pub badge: Rect, +} diff --git a/crates/ui-egui/src/shelf_drag_verdict.rs b/crates/ui-egui/src/shelf_drag_verdict.rs index b6713b95..2af311da 100644 --- a/crates/ui-egui/src/shelf_drag_verdict.rs +++ b/crates/ui-egui/src/shelf_drag_verdict.rs @@ -2,7 +2,7 @@ /// Whether the place under the pointer takes the dragged asset #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Verdict { +pub enum ShelfDragVerdict { /// A drop here does something: a crosshair on a light square Valid, /// A drop here does nothing: a no-entry sign on red diff --git a/crates/ui-egui/tests/it/shelf_drag_ghost.rs b/crates/ui-egui/tests/it/shelf_drag_ghost.rs index 8311846f..8a006eab 100644 --- a/crates/ui-egui/tests/it/shelf_drag_ghost.rs +++ b/crates/ui-egui/tests/it/shelf_drag_ghost.rs @@ -1,5 +1,4 @@ -//! Dragging an asset from the Assets panel shows it at the pointer with a badge on its corner that says -//! whether the place under the pointer takes it +//! A dragged asset or layer shows at the pointer with a badge saying whether the place under it takes it use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; use egui_kittest::Harness; @@ -7,7 +6,7 @@ use egui_kittest::kittest::Queryable; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::materials::MATERIALS; use texturecraft_ui_egui::TextureCraftApp; -use texturecraft_ui_egui::shelf_drag_ghost::{Verdict, shown}; +use texturecraft_ui_egui::shelf_drag_ghost::{ShelfDragVerdict, shown}; /// Distance between the view points searched for a set or the background const SEARCH_STEP: f32 = 8.0; @@ -58,7 +57,36 @@ fn the_badge_says_whether_the_place_under_the_pointer_takes_the_asset_without_co assert!(ghost.badge.min.x > target.x && ghost.badge.min.y > target.y, "the badge leaves the pointer's tip clear"); seen.push(ghost.verdict); } - assert_eq!(seen, [Verdict::Valid, Verdict::NotValid], "a texture set takes a material, the background doesn't"); + assert_eq!(seen, [ShelfDragVerdict::Valid, ShelfDragVerdict::NotValid], "a texture set takes a material, the background doesn't"); + + harness.event(Event::PointerButton { pos: background, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert!(shown(&harness.ctx).is_none(), "the ghost goes when the drag ends"); +} + +#[test] +fn a_layer_dragged_in_the_layer_stack_gets_the_same_ghost_and_badge() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for name in ["Ghost low", "Ghost high"] { + texturecraft_engine::execute(&mut session, "layer.add.paint", &serde_json::json!({ "name": name })).unwrap(); + } + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + let background = point_over(&harness, None); + let (high, low) = (harness.get_by_label("Ghost high").rect().center(), harness.get_by_label("Ghost low").rect().center()); + + harness.event(Event::PointerButton { pos: high, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + harness.hover_at(high + vec2(DRAG_START, DRAG_START)); + harness.run_steps(2); + + let mut seen = Vec::new(); + for target in [low, background] { + harness.hover_at(target); + harness.run_steps(2); + seen.push(shown(&harness.ctx).expect("the dragged layer follows the pointer").verdict); + } + assert_eq!(seen, [ShelfDragVerdict::Valid, ShelfDragVerdict::NotValid], "another row takes the layer, the 3D view doesn't"); harness.event(Event::PointerButton { pos: background, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); harness.run_steps(2); From 4b95153430d49a86ba44eea5b8dccf62768d4455 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:37:14 +0000 Subject: [PATCH 12/16] Assets: the edge between the filter panes and the grid drags to share the panel's width --- crates/ui-egui/src/shelf.rs | 2 +- crates/ui-egui/src/shelf_panes.rs | 29 +++++++++++++++++++++++-- crates/ui-egui/src/state.rs | 16 ++++++++++++++ crates/ui-egui/tests/it/shelf_panel.rs | 30 ++++++++++++++++++++++++++ 4 files changed, 74 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 7285787d..18d61227 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -330,7 +330,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { ui.set_min_size(vec2(width, grid_rect.height())); crate::shelf_panes::column(app, ui, &paths, &applicable); }); - ui.separator(); + crate::shelf_panes::edge(app, ui, width, grid_rect.width()); } // Saved smart materials are files in the user's library, without folders of their own diff --git a/crates/ui-egui/src/shelf_panes.rs b/crates/ui-egui/src/shelf_panes.rs index 118d9bc4..f2a6d42f 100644 --- a/crates/ui-egui/src/shelf_panes.rs +++ b/crates/ui-egui/src/shelf_panes.rs @@ -13,8 +13,11 @@ use crate::theme::Tokens; use crate::unavailable::NOT_AVAILABLE; use crate::widgets::icon_button; -const COLUMN_FRACTION: f32 = 0.45; const COLUMN_MIN_WIDTH_POINTS: f32 = 110.0; +/// Width of the draggable edge between the panes and the grid +const EDGE_WIDTH_POINTS: f32 = 6.0; +/// The grid keeps at least this much width when the edge is dragged right +const GRID_MIN_WIDTH_POINTS: f32 = 80.0; const SPLITTER_HEIGHT_POINTS: f32 = 6.0; const PANE_MIN_HEIGHT_POINTS: f32 = 40.0; /// The built-in saved search after "All" that shows only the favorite assets @@ -49,7 +52,29 @@ pub(crate) fn toggles(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) { /// The width of the panes' column in a panel `width` wide, or None while no pane is open pub(crate) fn column_width(app: &TextureCraftApp, width: f32) -> Option { let panes = &app.ui.shelf_panes; - (panes.saved_searches || panes.filter_by_path).then(|| (width * COLUMN_FRACTION).max(COLUMN_MIN_WIDTH_POINTS).min(width)) + let share = app.ui.shelf_panes_share; + (panes.saved_searches || panes.filter_by_path) + .then(|| (width * share).min(width - EDGE_WIDTH_POINTS - GRID_MIN_WIDTH_POINTS).max(COLUMN_MIN_WIDTH_POINTS).min(width)) +} + +/// The draggable edge between the panes' column (`column` wide) and the grid in a panel `width` wide +pub(crate) fn edge(app: &mut TextureCraftApp, ui: &mut Ui, column: f32, width: f32) { + let (rect, _) = ui.allocate_exact_size(egui::vec2(EDGE_WIDTH_POINTS, ui.available_height()), egui::Sense::hover()); + let visuals = ui.visuals(); + let line_stroke = visuals.widgets.noninteractive.bg_stroke; + let widest = (width - EDGE_WIDTH_POINTS - GRID_MIN_WIDTH_POINTS).max(COLUMN_MIN_WIDTH_POINTS); + if width > 0.0 && widest > COLUMN_MIN_WIDTH_POINTS { + let colors = + ResizeHandleStyle { hovered: visuals.widgets.hovered.bg_fill, dragged: visuals.widgets.active.bg_fill, focused: visuals.selection.bg_fill }; + let resize = ResizeHandle::new(ui.scope_id().with("shelf_panes_edge"), SplitAxis::Horizontal, rect, tr("Resize Assets filter panes and grid"), colors) + .hit_margin(0.0) + .value(column.clamp(COLUMN_MIN_WIDTH_POINTS, widest), COLUMN_MIN_WIDTH_POINTS..=widest) + .show(ui); + if resize.delta != 0.0 { + app.ui.shelf_panes_share = (column + resize.delta).clamp(COLUMN_MIN_WIDTH_POINTS, widest) / width; + } + } + ui.painter().vline(rect.center().x, rect.y_range(), line_stroke); } /// Draws the open panes and a divider when both are visible. diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 3cdf54db..34748b34 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -493,6 +493,18 @@ pub(crate) fn default_shelf_panes_split() -> f32 { 0.45 } +/// The share of the Assets panel's width the filter panes take until their edge is dragged +fn default_shelf_panes_share() -> f32 { + 0.45 +} + +fn deserialize_shelf_panes_share<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { + let share = f32::deserialize(deserializer)?; + + // A finite JSON number can overflow f32 and prevent the next settings save + Ok(if share.is_finite() { share } else { default_shelf_panes_share() }) +} + fn deserialize_shelf_panes_split<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { let share = f32::deserialize(deserializer)?; @@ -605,6 +617,9 @@ pub struct UiState { /// Saved searches' share of the pane column above Filter by path, set by the splitter between them #[serde(default = "default_shelf_panes_split", deserialize_with = "deserialize_shelf_panes_split")] pub shelf_panes_split: f32, + /// The share of the Assets panel's width the filter panes take + #[serde(default = "default_shelf_panes_share", deserialize_with = "deserialize_shelf_panes_share")] + pub shelf_panes_share: f32, pub props_tab: PropsTab, #[serde(default)] pub text: TextUi, @@ -803,6 +818,7 @@ impl Default for UiState { shelf_custom_previews: Vec::new(), shelf_updates: crate::shelf_updates::ShelfUpdates::default(), shelf_panes_split: default_shelf_panes_split(), + shelf_panes_share: default_shelf_panes_share(), props_tab: PropsTab::Brush, text: TextUi::default(), rename: None, diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index 06856a41..23686275 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -544,3 +544,33 @@ fn the_favorites_search_shows_only_favorites_until_all_is_picked() { assert!(harness.query_by_label(other).is_some(), "All shows every asset again"); assert!(harness.query_by_label("My brushes").is_some(), "All shows the saved brushes list again"); } + +#[test] +fn the_edge_between_the_panes_and_the_grid_drags_and_the_width_is_saved() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.run_steps(3); + + const DRAG_DISTANCE_POINTS: f32 = 40.0; + let (initial_share, edge) = (harness.state().ui.shelf_panes_share, harness.get_by_label("Resize Assets filter panes and grid").rect()); + let from = edge.center(); + let to = from + egui::vec2(DRAG_DISTANCE_POINTS, 0.0); + harness.hover_at(from); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + harness.run_steps(1); + for step in 1..=4 { + harness.hover_at(from + (to - from) * (step as f32 / 4.0)); + harness.run_steps(1); + } + harness.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + harness.run_steps(3); + + let moved = harness.get_by_label("Resize Assets filter panes and grid").rect(); + assert!(moved.center().x > edge.center().x, "the edge follows the drag: {edge:?} to {moved:?}"); + assert!(harness.state().ui.shelf_panes_share > initial_share, "the panes take a larger share"); + + let saved = serde_json::to_value(&harness.state().ui).unwrap(); + let restored: texturecraft_ui_egui::state::UiState = serde_json::from_value(saved).unwrap(); + assert_eq!(restored.shelf_panes_share, harness.state().ui.shelf_panes_share, "the width is saved"); +} From 468b016da229aadf5dab73e6c5e98b17a4531ba0 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:17:22 +0000 Subject: [PATCH 13/16] Resources: a reload keeps each image's own file across undo, and renaming a linked material's package moves a material effect's link too The file an image was imported from is kept by the image's bytes instead of its name, so an undo that brings back a removed image reloads it from its own file, not from a later file that took its name. A rename now also points a material effect's link package and cooked outputs at the new name. --- crates/core/src/layer.rs | 2 +- crates/engine/src/resource_cmds.rs | 105 ++++++++++++++++++++++++----- crates/engine/src/session.rs | 14 ++-- 3 files changed, 94 insertions(+), 27 deletions(-) diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 56a5147f..2aded5ac 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -2072,7 +2072,7 @@ impl EffectKind { pub fn images_mut(&mut self) -> Vec<&mut String> { match self { EffectKind::Fill { source, .. } => source.images_mut(), - EffectKind::Material(fill) => fill.sources.values_mut().flat_map(Source::images_mut).collect(), + EffectKind::Material(fill) => fill.images_mut().collect(), EffectKind::Generator(generator) => generator.inputs.values_mut().flat_map(Source::images_mut).collect(), EffectKind::ColorSelection(selection) => selection.id_map.iter_mut().collect(), _ => Vec::new(), diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 1d93ccb9..83f9d180 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -123,16 +123,22 @@ impl Session { self.doc.resources.insert(name.clone(), Arc::new(bytes)); self.images.insert(name.clone(), decoded(image)); - - // A new resource under a removed one's name has no file of its own until an import says so - self.resource_sources.remove(&name); - Ok(name) } /// The file image resource `name` was imported from in this session (what `resource.reload` reads again) pub fn resource_source(&self, name: &str) -> Option<&std::path::Path> { - self.resource_sources.get(name).map(std::path::PathBuf::as_path) + let bytes = self.doc.resources.get(name)?; + self.resource_sources.iter().rev().find(|(source, _)| std::ptr::eq(source.as_ptr(), Arc::as_ptr(bytes))).map(|(_, path)| path.as_path()) + } + + /// Remembers that image resource `name`, with the bytes it holds now, came from the file at `path` + #[cfg(not(target_arch = "wasm32"))] + fn remember_resource_source(&mut self, name: &str, path: &std::path::Path) { + self.resource_sources.retain(|(source, _)| source.strong_count() > 0); + if let Some(bytes) = self.doc.resources.get(name) { + self.resource_sources.push((Arc::downgrade(bytes), path.to_path_buf())); + } } /// Decode resources that are not decoded yet and forget removed ones (after undo, redo, load). @@ -210,7 +216,7 @@ 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_prefixed(strp(p, "prefix").unwrap_or(""), path, bytes)?; - s.resource_sources.insert(name.clone(), path.into()); + s.remember_resource_source(&name, std::path::Path::new(path)); Ok(json!({ "name": name })) } @@ -365,9 +371,6 @@ fn rename(s: &mut Session, p: &Value) -> Result { if s.library_alphas.remove(&name) { s.library_alphas.insert(to.clone()); } - if let Some(source) = s.resource_sources.remove(&name) { - s.resource_sources.insert(to.clone(), source); - } s.path_cache = None; s.sync_images(); Ok(json!({ "name": to })) @@ -406,14 +409,17 @@ fn reload(s: &mut Session, p: &Value) -> Result { return Err(bad(command, format!("no resource `{name}`"))); } - let path = - s.resource_sources.get(&name).cloned().ok_or_else(|| bad(command, format!("`{name}` was imported before this session: no file to reload from")))?; + let path = s + .resource_source(&name) + .map(std::path::Path::to_path_buf) + .ok_or_else(|| bad(command, format!("`{name}` was imported before this session: no file to reload from")))?; let (bytes, image) = read_source(command, &path)?; s.edit("Reload resource", |s| { s.doc.resources.insert(name.clone(), Arc::new(bytes)); Ok(()) })?; + s.remember_resource_source(&name, &path); s.show_reloaded(name.clone(), image); Ok(json!({ "name": name })) } @@ -424,29 +430,30 @@ fn update(s: &mut Session, _: &Value) -> Result { let command = "resource.update"; let mut changed = Vec::new(); let mut failed = Vec::new(); - for (name, path) in &s.resource_sources { - let Some(held) = s.doc.resources.get(name) else { continue }; + for (name, held) in &s.doc.resources { + let Some(path) = s.resource_source(name) else { continue }; // Only a file whose bytes changed is decoded let read = read_resource_file(command, path, MAX_BYTES as u64) .and_then(|bytes| if bytes == **held { Ok(None) } else { decode_source(command, path, &bytes).map(|image| Some((bytes, image))) }); match read { Ok(None) => {} - Ok(Some((bytes, image))) => changed.push((name.clone(), bytes, image)), + Ok(Some((bytes, image))) => changed.push((name.clone(), path.to_path_buf(), bytes, image)), Err(error) => failed.push(json!({ "name": name, "error": error.to_string() })), } } if !changed.is_empty() { s.edit("Update resources", |s| { - for (name, bytes, _) in &mut changed { + for (name, _, bytes, _) in &mut changed { s.doc.resources.insert(name.clone(), Arc::new(std::mem::take(bytes))); } Ok(()) })?; } - let updated: Vec = changed.iter().map(|(name, _, _)| name.clone()).collect(); - for (name, _, image) in changed { + let updated: Vec = changed.iter().map(|(name, _, _, _)| name.clone()).collect(); + for (name, path, _, image) in changed { + s.remember_resource_source(&name, &path); s.show_reloaded(name, image); } Ok(json!({ "updated": updated, "failed": failed })) @@ -611,6 +618,42 @@ mod tests { assert_eq!(session.tool.brush.alpha_image.as_ref(), Some(&renamed), "the brush alpha follows the redo"); } + #[test] + fn renaming_a_linked_materials_package_moves_a_material_effects_link_with_it() { + use std::collections::BTreeMap; + use texturecraft_core::{Effect, EffectKind, MaterialLink}; + + let mut session = crate::sample_session(128, 32).unwrap(); + let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + let package = session.import_resource_bytes("package.png", png).unwrap(); + crate::execute(&mut session, "layer.add.image", &json!({"name": package})).unwrap(); + let layer_id = session.selected_layer().unwrap(); + let link = MaterialLink { + name: "linked".into(), + package: package.clone(), + graph: String::new(), + params: Vec::new(), + presets: Vec::new(), + inputs: Vec::new(), + size: 1, + resolution: None, + mapping: BTreeMap::new(), + outputs: BTreeMap::from([("basecolor".to_string(), package.clone())]), + }; + let effect_id = session.doc.project.alloc_id(); + let material = Effect::new(effect_id, EffectKind::Material(Fill { link: Some(Box::new(link)), ..Fill::default() })); + session.doc.project.layers.get_mut(&layer_id).unwrap().content_effects.push(material); + + let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": package, "to": "stone"})).unwrap()["name"].as_str().unwrap().to_string(); + + let effect = &session.doc.project.layers[&layer_id].content_effects[0]; + let EffectKind::Material(fill) = &effect.kind else { panic!("the effect stays a material") }; + let link = fill.link.as_ref().unwrap(); + assert_ne!(renamed, package); + assert_eq!(link.package, renamed, "the link's package follows the rename"); + assert_eq!(link.outputs.values().collect::>(), [&renamed], "the link's cooked outputs follow the rename"); + } + #[test] fn reloading_reads_the_file_again_and_undo_restores_the_pixels() { let mut session = crate::sample_session(128, 32).unwrap(); @@ -644,6 +687,34 @@ mod tests { assert!(session.resource_source(&reused).is_none(), "the new image has no file to reload from"); } + #[test] + fn undo_gives_an_image_back_its_own_file_after_another_file_took_its_name() { + let mut session = crate::sample_session(128, 32).unwrap(); + let folder = |side: &str| std::env::temp_dir().join(format!("texturecraft-own-file-{side}-{}", std::process::id())); + let import = |session: &mut Session, side: &str, value: f32| { + std::fs::create_dir_all(folder(side)).unwrap(); + let path = folder(side).join("photo.png"); + std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [value].into_iter()).unwrap()).unwrap(); + let name = crate::execute(session, "resource.import", &json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + (path, name) + }; + let (first_path, first) = import(&mut session, "first", 0.2); + crate::execute(&mut session, "resource.remove", &json!({"name": first})).unwrap(); + let (second_path, second) = import(&mut session, "second", 0.6); + + // One undo takes back the second import, the next the removal + session.undo().unwrap(); + session.undo().unwrap(); + let source = session.resource_source(&first).map(std::path::Path::to_path_buf); + for side in ["first", "second"] { + std::fs::remove_dir_all(folder(side)).unwrap(); + } + + assert_eq!(second, first, "the second file takes the removed image's name"); + assert_ne!(first_path, second_path); + assert_eq!(source, Some(first_path), "the image the undo brings back reloads from its own file"); + } + #[test] fn updating_reads_only_changed_files_in_one_undo_step() { let mut session = crate::sample_session(128, 32).unwrap(); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 66b58d6f..68fd8fd9 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -462,8 +462,8 @@ pub struct Session { pub images: texturecraft_compose::ImageStore, /// Resource names whose decoded pixels match a library alpha. pub(crate) library_alphas: BTreeSet, - /// The file each image resource imported in this session came from, for Reload (not saved) - pub(crate) resource_sources: BTreeMap, + /// The file each image resource imported in this session came from, for Reload (not saved). Kept by the resource's bytes, so undo, redo and renames keep each file with its own image + pub(crate) resource_sources: Vec<(std::sync::Weak>, std::path::PathBuf)>, /// 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). @@ -549,7 +549,7 @@ impl Session { blending_clipboard: None, images: Default::default(), library_alphas: BTreeSet::new(), - resource_sources: BTreeMap::new(), + resource_sources: Vec::new(), quick_mask: Default::default(), painting_paths: false, path_cache: None, @@ -1028,10 +1028,9 @@ impl Session { .flatten() } - /// Points tool images and reload sources at a resource's name on this side of an undone or redone rename + /// Points tool images at a resource's name on this side of an undone or redone rename fn follow_renamed_resources(&mut self, other: &Document) { - let mut names: Vec = self.tool_images_mut().map(|name| name.clone()).collect(); - names.extend(self.resource_sources.keys().cloned()); + let names: Vec = self.tool_images_mut().map(|name| name.clone()).collect(); let renames: Vec<(String, String)> = names .into_iter() .filter(|name| !self.doc.resources.contains_key(name)) @@ -1046,9 +1045,6 @@ impl Session { for tool_image in self.tool_images_mut().filter(|tool_image| **tool_image == name) { tool_image.clone_from(&to); } - if let Some(source) = self.resource_sources.remove(&name) { - self.resource_sources.insert(to, source); - } } } From 53d24eac47b4515681bd404531a1b64da5105cf9 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:17:22 +0000 Subject: [PATCH 14/16] Assets: review fixes for saved searches under Favorites, folder hiding, read failures per project and custom previews A saved search keeps the Favorites choice it was saved with. Hide non-applicable folders under Favorites only keeps the favorites' folders. A file that fails to read is reported once per project. A custom preview is read only when its tile shows. A rename in the asset menu stops that frame's rows from acting on the old name. The stroke test also checks that undo takes back the update on its own. --- crates/ui-egui/src/saved_search.rs | 5 +- crates/ui-egui/src/shelf.rs | 18 +++---- crates/ui-egui/src/shelf_menu.rs | 2 + crates/ui-egui/src/shelf_panes.rs | 14 +++-- crates/ui-egui/src/shelf_updates.rs | 11 ++-- crates/ui-egui/src/state.rs | 3 +- crates/ui-egui/tests/it/shelf_panel.rs | 69 ++++++++++++++++++++++-- crates/ui-egui/tests/it/shelf_updates.rs | 33 ++++++++++++ 8 files changed, 132 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/saved_search.rs b/crates/ui-egui/src/saved_search.rs index ec6181b8..b4d4c562 100644 --- a/crates/ui-egui/src/saved_search.rs +++ b/crates/ui-egui/src/saved_search.rs @@ -2,11 +2,14 @@ use serde::{Deserialize, Serialize}; -/// The search text, tab and library folder of a saved shelf query, under the name it lists as +/// The search text, tab, library folder and Favorites choice of a saved shelf query, under the name it lists as #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct SavedSearch { pub name: String, pub filter: String, pub tab: usize, pub path: Vec, + /// Only favorites show; searches saved before favorites show everything + #[serde(default)] + pub favorites_only: bool, } diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 18d61227..28f8a898 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -271,6 +271,10 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let folder = app.ui.shelf_path.clone(); let picked_tab = app.ui.shelf_tab; let mut matching: Vec = all_entries.into_iter().filter(|entry| entry.matches(&filter)).collect(); + if app.ui.shelf_favorites_only { + matching.retain(|entry| crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some()); + } + let path_pane_open = app.ui.shelf_panes.filter_by_path; let mut applicable = if path_pane_open { crate::shelf_folders::paths(matching.iter().filter(|entry| crate::shelf_tabs::shows(picked_tab, entry.tab()))) @@ -278,10 +282,6 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { Vec::new() }; - if app.ui.shelf_favorites_only { - matching.retain(|entry| crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some()); - } - // All libraries includes every result without constructing an asset path if !folder.is_empty() { matching.retain(|entry| entry.in_folder(&folder)); @@ -298,7 +298,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { if in_user_library && let Some(count) = TABS.iter().position(|(shown, _, _)| *shown == tab).and_then(|position| counts.get_mut(position)) { *count += saved; } - if path_pane_open && saved > 0 && crate::shelf_tabs::shows(picked_tab, tab) { + if path_pane_open && !favorites_only && saved > 0 && crate::shelf_tabs::shows(picked_tab, tab) { applicable.push(vec![crate::shelf_entry::USER.to_string()]); } } @@ -523,15 +523,15 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry return; } - // A picture the user picked replaces the thumbnail, unless its file is gone - let custom = crate::shelf_custom_preview::file_for(&app.ui.shelf_custom_previews, entry).and_then(|file| app.thumbs.custom_preview(ctx, file)); - let texture = custom.or_else(|| entry.thumbnail(app, ctx)); + // A picture the user picked replaces the thumbnail, unless its file is gone; it is read only once its tile shows + let thumbnail = entry.thumbnail(app, ctx); + let custom_file = crate::shelf_custom_preview::file_for(&app.ui.shelf_custom_previews, entry); let asset = entry.asset(); let session = &app.session; let response = tile_in_view( ui, &mut app.thumbs, - |_, _| texture, + |ui, thumbs| custom_file.and_then(|file| thumbs.custom_preview(ui.ctx(), file)).or(thumbnail), |thumbs| match entry { ShelfEntry::SavedBrush { path: Some(path), .. } => Some(thumbs.saved_brush_preview(path, &session.images)), _ => entry.preview(session), diff --git a/crates/ui-egui/src/shelf_menu.rs b/crates/ui-egui/src/shelf_menu.rs index e7546ecf..bd6210c4 100644 --- a/crates/ui-egui/src/shelf_menu.rs +++ b/crates/ui-egui/src/shelf_menu.rs @@ -86,7 +86,9 @@ pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &Shelf && let Some(result) = app.run(command, json!({"name": name, "to": renamed})) && let Some(new_name) = result["name"].as_str() { + // The rows below would act on the old name: the menu draws again under the new one next frame keep_star_and_preview(app, entry, new_name); + return; } } info_block(ui, width, column, shown_info, &tokens); diff --git a/crates/ui-egui/src/shelf_panes.rs b/crates/ui-egui/src/shelf_panes.rs index f2a6d42f..a642a731 100644 --- a/crates/ui-egui/src/shelf_panes.rs +++ b/crates/ui-egui/src/shelf_panes.rs @@ -272,11 +272,14 @@ fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { let saved_index = row - first_saved_row; let Some(saved) = app.ui.shelf_saved_searches.get(saved_index) else { continue }; - let selected = !favorites_only && saved.filter == app.ui.shelf_filter && saved.tab == app.ui.shelf_tab && saved.path == app.ui.shelf_path; + let selected = saved.favorites_only == favorites_only + && saved.filter == app.ui.shelf_filter + && saved.tab == app.ui.shelf_tab + && saved.path == app.ui.shelf_path; let response = ui.selectable_label(selected, &saved.name); if response.clicked() { (app.ui.shelf_filter, app.ui.shelf_tab, app.ui.shelf_path) = (saved.filter.clone(), saved.tab, saved.path.clone()); - app.ui.shelf_favorites_only = false; + app.ui.shelf_favorites_only = saved.favorites_only; } response.context_menu(|ui| { @@ -294,18 +297,21 @@ fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { } } -/// The shelf's query, named after its search text, else its folder, else its tab +/// The shelf's query, named after its search text, else its folder, else Favorites, else its tab fn current_query(app: &TextureCraftApp) -> SavedSearch { let filter = &app.ui.shelf_filter; let tab = app.ui.shelf_tab; let path = &app.ui.shelf_path; + let favorites_only = app.ui.shelf_favorites_only; let name = if !filter.is_empty() { filter.as_str() } else if let Some(folder) = path.last() { crate::shelf_folders::name(path.len() - 1, folder) + } else if favorites_only { + tr(FAVORITES) } else { TABS.get(tab).map_or_else(|| tr("All"), |(_, _, label)| tr(label)) }; - SavedSearch { name: name.to_owned(), filter: filter.clone(), tab, path: path.clone() } + SavedSearch { name: name.to_owned(), filter: filter.clone(), tab, path: path.clone(), favorites_only } } diff --git a/crates/ui-egui/src/shelf_updates.rs b/crates/ui-egui/src/shelf_updates.rs index 8300357d..648bd87a 100644 --- a/crates/ui-egui/src/shelf_updates.rs +++ b/crates/ui-egui/src/shelf_updates.rs @@ -110,7 +110,8 @@ fn update_resources(app: &mut TextureCraftApp, ctx: &Context) { .flatten() .map(|failure| (failure["name"].as_str().unwrap_or_default().to_owned(), failure["error"].as_str().unwrap_or_default().to_owned())) .collect(); - let mut reported: Vec = ctx.data(|data| data.get_temp(reported_failures_id())).unwrap_or_default(); + let reported_id = reported_failures_id(app.session.project_id); + let mut reported: Vec = ctx.data(|data| data.get_temp(reported_id)).unwrap_or_default(); reported.retain(|name| failures.iter().any(|(failed, _)| failed == name)); for (name, error) in failures { if !reported.contains(&name) { @@ -118,12 +119,12 @@ fn update_resources(app: &mut TextureCraftApp, ctx: &Context) { reported.push(name); } } - ctx.data_mut(|data| data.insert_temp(reported_failures_id(), reported)); + ctx.data_mut(|data| data.insert_temp(reported_id, reported)); } -/// The files whose failure to read was already shown (ctx temp data) -fn reported_failures_id() -> Id { - Id::unique("shelf_updates_reported_failures") +/// The files of project `project_id` whose failure to read was already shown (ctx temp data) +fn reported_failures_id(project_id: u64) -> Id { + Id::unique(("shelf_updates_reported_failures", project_id)) } /// The refresh button with its popup of update settings, opening upward from the toolbar `panel` with its left edge on the panel's diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 34748b34..0394df49 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -946,7 +946,8 @@ mod tests { #[test] fn adopting_a_layout_keeps_the_shelf_query_saved_searches_favorites_and_custom_previews() { - let saved = crate::saved_search::SavedSearch { name: "rust".into(), filter: "rust".into(), tab: 2, path: vec!["starter".into()] }; + let saved = + crate::saved_search::SavedSearch { name: "rust".into(), filter: "rust".into(), tab: 2, path: vec!["starter".into()], favorites_only: false }; let favorite = crate::shelf_favorite::ShelfFavorite { kind: "material".into(), id: "gold".into() }; let mut ui = UiState { shelf_filter: "rust".into(), shelf_tab: 2, shelf_path: vec!["starter".into()], shelf_favorites_only: true, ..UiState::default() }; diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index 23686275..6a8032bb 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -19,6 +19,8 @@ const MATERIALS_TYPE: usize = 0; const SMART_MASKS_TYPE: usize = 2; const BRUSHES_TYPE: usize = 4; const ENVIRONMENTS_TYPE: usize = 7; +/// The type row with no type picked: every type shows +const EVERY_TYPE: usize = 8; /// How far the saved brush's spacing differs from the current brush's, so loading it shows const SAVED_SPACING_CHANGE: f32 = 0.25; /// Tile columns the reference shows at its panel width @@ -203,7 +205,13 @@ fn many_saved_searches_keep_the_path_filter_reachable() { harness.state_mut().ui.shelf_panes.saved_searches = true; harness.state_mut().ui.shelf_panes.filter_by_path = true; harness.state_mut().ui.shelf_saved_searches = (0..100) - .map(|index| SavedSearch { name: format!("search {index}"), filter: format!("filter {index}"), tab: MATERIALS_TYPE, path: Vec::new() }) + .map(|index| SavedSearch { + name: format!("search {index}"), + filter: format!("filter {index}"), + tab: MATERIALS_TYPE, + path: Vec::new(), + favorites_only: false, + }) .collect(); harness.run_steps(3); @@ -217,7 +225,13 @@ fn a_long_saved_search_list_can_select_the_last_query() { let mut harness = shelf(NARROW_WINDOW); harness.state_mut().ui.shelf_panes.saved_searches = true; harness.state_mut().ui.shelf_saved_searches = (0..1000) - .map(|index| SavedSearch { name: format!("search {index}"), filter: format!("filter {index}"), tab: MATERIALS_TYPE, path: Vec::new() }) + .map(|index| SavedSearch { + name: format!("search {index}"), + filter: format!("filter {index}"), + tab: MATERIALS_TYPE, + path: Vec::new(), + favorites_only: false, + }) .collect(); harness.run_steps(3); assert!(harness.query_by_label("search 500").is_none(), "offscreen searches do not build rows"); @@ -457,7 +471,7 @@ fn the_smallest_saved_search_pane_can_scroll_to_and_select_the_last_query() { harness.state_mut().ui.shelf_panes.filter_by_path = true; harness.state_mut().ui.shelf_panes_split = 0.0; harness.state_mut().ui.shelf_saved_searches = - vec![SavedSearch { name: "Rust search".into(), filter: "rust".into(), tab: MATERIALS_TYPE, path: Vec::new() }]; + vec![SavedSearch { name: "Rust search".into(), filter: "rust".into(), tab: MATERIALS_TYPE, path: Vec::new(), favorites_only: false }]; harness.run_steps(3); scroll_pane_to_end(&mut harness, "SAVED SEARCHES"); @@ -545,6 +559,55 @@ fn the_favorites_search_shows_only_favorites_until_all_is_picked() { assert!(harness.query_by_label("My brushes").is_some(), "All shows the saved brushes list again"); } +/// The shelf on the Materials type with the first plain material made a favorite through its menu +fn shelf_with_a_favorite(session: texturecraft_engine::Session) -> Harness<'static, TextureCraftApp> { + let favorite = plain_materials()[0].label; + let mut harness = Harness::builder().with_size(REFERENCE_WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.shelf_tab = MATERIALS_TYPE; + harness.run_steps(4); + button(&harness, favorite).click_secondary(); + harness.run_steps(3); + button(&harness, "Add to favorites").click(); + harness.run_steps(3); + harness +} + +#[test] +fn a_search_saved_under_favorites_shows_only_favorites_again() { + let mut harness = shelf_with_a_favorite(texturecraft_engine::sample_session(256, 64).unwrap()); + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.run_steps(3); + button(&harness, "Favorites").click(); + harness.run_steps(3); + button(&harness, "Save the current search").click(); + harness.run_steps(2); + button(&harness, "All").click(); + harness.run_steps(3); + + // The saved search lists below the fixed Favorites row, under the same name + harness.get_all_by_label("Favorites").last().unwrap().click(); + harness.run_steps(3); + + assert_eq!(harness.state().ui.shelf_saved_searches.len(), 1); + assert!(harness.state().ui.shelf_favorites_only, "the saved search shows only favorites, as when it was saved"); +} + +#[test] +fn hiding_non_applicable_folders_under_favorites_hides_the_folders_of_other_assets() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let png = texturecraft_engine::formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + session.import_resource_bytes("photo.png", png).unwrap(); + let mut harness = shelf_with_a_favorite(session); + harness.state_mut().ui.shelf_tab = EVERY_TYPE; + harness.state_mut().ui.shelf_favorites_only = true; + harness.state_mut().ui.shelf_panes.filter_by_path = true; + harness.state_mut().ui.shelf_panes.hide_non_applicable = true; + harness.run_steps(4); + + assert!(harness.query_by_label("Starter assets").is_some(), "the favorite's library shows"); + assert!(harness.query_by_label("Project").is_none(), "the project image is no favorite, so its library hides"); +} + #[test] fn the_edge_between_the_panes_and_the_grid_drags_and_the_width_is_saved() { let mut harness = shelf(REFERENCE_WINDOW); diff --git a/crates/ui-egui/tests/it/shelf_updates.rs b/crates/ui-egui/tests/it/shelf_updates.rs index 0a3e06fd..17ad5051 100644 --- a/crates/ui-egui/tests/it/shelf_updates.rs +++ b/crates/ui-egui/tests/it/shelf_updates.rs @@ -77,6 +77,7 @@ fn an_automatic_update_waits_for_the_stroke_under_way_to_end() { harness.run_steps(2); std::fs::write(&path, grey_png(0.8)).unwrap(); + let steps_before_stroke = harness.state().session.history_labels().len(); harness.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap(); pass_a_minute(&mut harness); let during_stroke = harness.state().session.images[&name].rgba.clone(); @@ -88,4 +89,36 @@ fn an_automatic_update_waits_for_the_stroke_under_way_to_end() { assert_eq!(during_stroke, before, "nothing is read again while a stroke is under way"); assert_ne!(after_stroke, before, "the update runs once the stroke ended"); assert_eq!(harness.state().session.doc.resources[&name].as_slice(), grey_png(0.8).as_slice(), "the stroke's undo state didn't swallow the update"); + + harness.state_mut().session.undo().unwrap(); + + assert_eq!(harness.state().session.doc.resources[&name].as_slice(), grey_png(0.2).as_slice(), "one undo takes back the update"); + assert_eq!(harness.state().session.history_labels().len(), steps_before_stroke + 1, "the stroke is still its own step"); +} + +#[test] +fn a_file_that_fails_to_read_is_reported_again_in_the_next_project() { + let mut harness = refresh_popup(); + harness.get_by_label("Resources used in project").click(); + harness.run_steps(2); + + let mut reported = Vec::new(); + for project in ["first", "second"] { + if project == "second" { + harness.state_mut().session = texturecraft_engine::sample_session(256, 64).unwrap(); + } + let folder = std::env::temp_dir().join(format!("texturecraft-failed-read-{project}-{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + let path = folder.join("photo.png"); + std::fs::write(&path, grey_png(0.2)).unwrap(); + let name = harness.state_mut().run("resource.import", json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); + std::fs::remove_dir_all(&folder).unwrap(); + harness.state_mut().toasts.clear(); + + pass_a_minute(&mut harness); + + reported.push(harness.state().toasts.iter().any(|toast| toast.error && toast.text.starts_with(&format!("{name}:")))); + } + + assert_eq!(reported, [true, true], "each project says once that its file can't be read"); } From 145a4db4ec070532e65c60deda4bd290733c3150 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:08:28 +0000 Subject: [PATCH 15/16] Assets: renaming an image also moves a generator's texture, grunge, micro details and Grayscale Conversion image --- crates/core/src/layer.rs | 13 ++++++++++++- crates/core/src/layer/micro_details.rs | 5 +++++ crates/engine/src/resource_cmds.rs | 20 ++++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 1e10a7c8..96c4ea27 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1294,6 +1294,17 @@ impl Generator { self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())).chain(self.grunge.as_ref()).chain(micro) } + /// [`Generator::sources`], to rename the images they read + pub fn sources_mut(&mut self) -> impl Iterator { + let grayscale = match self.controls.as_deref_mut() { + Some(KindControls::Grayscale(grayscale)) if self.kind == GeneratorKind::GrayscaleConversion => grayscale.source.as_mut(), + _ => None, + }; + let micro = self.micro.iter_mut().flat_map(|micro| micro.sources_mut()).chain(grayscale); + let texture = self.texture.as_mut().and_then(|texture| texture.source.as_mut()); + self.inputs.values_mut().chain(texture).chain(self.grunge.as_mut()).chain(micro) + } + /// The micro details as saved, when the generator computes with them: with a slot switched on, except a micro detail saved before Micro Details on a generator still on the earlier model, which [`Generator::earlier_micro`] reads (bring them into range before use: saved files are not trusted) pub fn micro_in_use(&self) -> Option<&MicroDetails> { self.micro.as_deref().filter(|micro| micro.in_use(self.kind) && !(micro.earlier && self.on_earlier_model())) @@ -2360,7 +2371,7 @@ impl EffectKind { match self { EffectKind::Fill { source, .. } => source.images_mut(), EffectKind::Material(fill) => fill.images_mut().collect(), - EffectKind::Generator(generator) => generator.inputs.values_mut().flat_map(Source::images_mut).collect(), + EffectKind::Generator(generator) => generator.sources_mut().flat_map(Source::images_mut).collect(), EffectKind::ColorSelection(selection) => selection.id_map.iter_mut().collect(), _ => Vec::new(), } diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index 36248e27..4ccb0373 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -119,6 +119,11 @@ impl MicroDetails { self.height_source.iter().chain(self.normal_source.as_ref()) } + /// [`MicroDetails::sources`], to rename the images they read + pub fn sources_mut(&mut self) -> impl Iterator { + self.height_source.iter_mut().chain(self.normal_source.as_mut()) + } + /// Every value brought into its range, non-finite ones to the defaults of `kind` pub fn clamped(self, kind: GeneratorKind) -> MicroDetails { let Some(defaults) = MicroDetails::defaults(kind) else { return self }; diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 83f9d180..cca76157 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -654,6 +654,26 @@ mod tests { assert_eq!(link.outputs.values().collect::>(), [&renamed], "the link's cooked outputs follow the rename"); } + #[test] + fn renaming_an_image_a_generator_reads_as_its_grunge_moves_the_grunge_with_it() { + use texturecraft_core::{Effect, EffectKind, Generator, GeneratorKind}; + + let mut session = crate::sample_session(128, 32).unwrap(); + let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + let grunge = session.import_resource_bytes("grunge.png", png).unwrap(); + crate::execute(&mut session, "layer.add.image", &json!({"name": grunge})).unwrap(); + let layer_id = session.selected_layer().unwrap(); + let generator = Generator { grunge: Some(Source::image(grunge.clone())), ..Generator::new(GeneratorKind::EdgeWear) }; + let effect_id = session.doc.project.alloc_id(); + session.doc.project.layers.get_mut(&layer_id).unwrap().content_effects.push(Effect::new(effect_id, EffectKind::Generator(generator))); + + let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": grunge, "to": "worn"})).unwrap()["name"].as_str().unwrap().to_string(); + + let EffectKind::Generator(generator) = &session.doc.project.layers[&layer_id].content_effects[0].kind else { panic!("the effect stays a generator") }; + assert_ne!(renamed, grunge); + assert_eq!(generator.grunge, Some(Source::image(renamed)), "the generator's grunge follows the rename"); + } + #[test] fn reloading_reads_the_file_again_and_undo_restores_the_pixels() { let mut session = crate::sample_session(128, 32).unwrap(); From 7e0bd1e6a2ba8077091c0b2351304ef276b25be5 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:33:49 +0000 Subject: [PATCH 16/16] Assets: the refresh popup's tests move a rewritten file's time on Main's Resources Updater counts an equal-size file whose modification time didn't move as unchanged, so a rewrite in the same millisecond as the import read as up to date and the test failed on the gate. --- crates/engine/src/resource_cmds.rs | 3 +++ crates/ui-egui/tests/it/shelf_updates.rs | 11 +++++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 75614716..024243c3 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -538,6 +538,9 @@ mod tests { let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": name, "to": "stone"})).unwrap()["name"].as_str().unwrap().to_string(); std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.75].into_iter()).unwrap()).unwrap(); + // An equal-size file counts as changed once its time moved, as a later save's does + let later = std::time::SystemTime::now() + std::time::Duration::from_secs(10); + std::fs::File::options().write(true).open(&path).unwrap().set_modified(later).unwrap(); let updated = crate::execute(&mut session, "resource.update", &json!({"names": [renamed]})).unwrap(); std::fs::remove_file(&path).unwrap(); diff --git a/crates/ui-egui/tests/it/shelf_updates.rs b/crates/ui-egui/tests/it/shelf_updates.rs index 01a208a7..717a6d4a 100644 --- a/crates/ui-egui/tests/it/shelf_updates.rs +++ b/crates/ui-egui/tests/it/shelf_updates.rs @@ -29,6 +29,13 @@ fn pass_a_minute(harness: &mut Harness<'_, TextureCraftApp>) { harness.run_steps(2); } +/// Writes `bytes` over the file at `path` with a later time, as a later save would (an equal-size file keeping its time reads as unchanged) +fn rewrite(path: &std::path::Path, bytes: &[u8]) { + std::fs::write(path, bytes).unwrap(); + let later = std::time::SystemTime::now() + std::time::Duration::from_secs(10); + std::fs::File::options().write(true).open(path).unwrap().set_modified(later).unwrap(); +} + /// A grey one-pixel PNG of `value` fn grey_png(value: f32) -> Vec { texturecraft_engine::formats::gray16_png(1, 1, [value].into_iter()).unwrap() @@ -41,7 +48,7 @@ fn turning_on_project_resources_reads_a_changed_image_file_again_every_minute() std::fs::write(&path, grey_png(0.2)).unwrap(); let name = harness.state_mut().run("resource.import", json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); let before = harness.state().session.images[&name].rgba.clone(); - std::fs::write(&path, grey_png(0.8)).unwrap(); + rewrite(&path, &grey_png(0.8)); pass_a_minute(&mut harness); let while_off = harness.state().session.images[&name].rgba.clone(); @@ -78,7 +85,7 @@ fn an_automatic_update_waits_for_the_stroke_under_way_to_end() { let before = harness.state().session.images[&name].rgba.clone(); harness.get_by_label("Resources used in project").click(); harness.run_steps(2); - std::fs::write(&path, grey_png(0.8)).unwrap(); + rewrite(&path, &grey_png(0.8)); let steps_before_stroke = harness.state().session.history_labels().len(); harness.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap();