From 8039420a2b75b776ed8c60186a7e6e504cddca74 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 06:50:27 +0000 Subject: [PATCH 01/22] Assets: tiles on the reference's 68 x 78 grid step with 60 pt thumbnails --- crates/ui-egui/src/shelf.rs | 13 +++++++------ crates/ui-egui/src/thumbs.rs | 2 +- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 9a36df2a..609e5878 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -27,14 +27,15 @@ use crate::theme::Tokens; use crate::thumbs::Thumbs; use crate::widgets::{dnd_release, icon_button}; -/// A shelf tile's size in points -const TILE_WIDTH: f32 = 72.0; -const TILE_HEIGHT: f32 = 86.0; +/// A shelf tile's size and the gap between tiles in points: a 68 x 78 grid step, as in the reference +const TILE_WIDTH: f32 = 66.0; +const TILE_HEIGHT: f32 = 76.0; +const TILE_GAP: f32 = 2.0; /// Corner radius of a tile's hover and selection highlights, in points const TILE_ROUNDING: f32 = 3.0; /// The thumbnail's size in a tile and its center below the tile's top, in points -const THUMBNAIL_SIZE: f32 = 56.0; -const THUMBNAIL_CENTER_Y: f32 = 32.0; +const THUMBNAIL_SIZE: f32 = 60.0; +const THUMBNAIL_CENTER_Y: f32 = 31.0; /// Loading icon size relative to the thumbnail width, and its opacity over the dim text color const LOADING_ICON_SCALE: f32 = 0.9; const LOADING_ICON_OPACITY: f32 = 0.5; @@ -303,7 +304,7 @@ pub(crate) fn header(ui: &mut Ui, text: &str) { pub(crate) fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing = vec2(4.0, 4.0); + ui.spacing_mut().item_spacing = vec2(TILE_GAP, TILE_GAP); body(ui); }); ui.add_space(6.0); diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index d0067411..059cc0a3 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -21,7 +21,7 @@ const PER_FRAME: usize = 2; /// Shelf sphere and smart mask thumbnail size in pixels const SPHERE_PX: usize = 72; /// Shelf procedural swatch size in pixels -const PROCEDURAL_PX: usize = 56; +const PROCEDURAL_PX: usize = 64; /// Shelf alpha and brush stroke swatch size in pixels const SWATCH_PX: usize = 64; /// Image resource preview size in pixels From a3eac9d2fb8d5fdd45dfa0ddb92706c6041754b2 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 06:50:35 +0000 Subject: [PATCH 02/22] Assets: one-line tile labels cut with an ellipsis --- crates/ui-egui/src/shelf.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 609e5878..51700285 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -633,13 +633,20 @@ pub(crate) fn tile( } let image_rect = egui::Rect::from_center_size(rect.center_top() + vec2(0.0, THUMBNAIL_CENTER_Y), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); thumbnail(painter, tex, image_rect, &tk); - let galley = painter.layout(label.to_string(), egui::FontId::proportional(LABEL_FONT_SIZE), tk.text, rect.width() - LABEL_MARGIN); + let galley = painter.layout_job(one_line(label, rect.width() - LABEL_MARGIN, tk.text)); painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tk.text); let big = if resp.hovered() { big_preview(ui, thumbs, preview) } else { None }; resp.on_hover_ui(|ui| hover_preview(ui, tex, big.as_ref(), label)) } +/// A tile label on one line, cut with "…" past `width` points (the hover popup shows the whole name) +fn one_line(label: &str, width: f32, color: Color32) -> egui::text::LayoutJob { + let mut job = egui::text::LayoutJob::single_section(label.to_string(), egui::TextFormat::simple(egui::FontId::proportional(LABEL_FONT_SIZE), color)); + job.wrap = egui::text::TextWrapping::truncate_at_width(width); + job +} + /// Start rendering during the popup delay once the pointer rests fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPreview) -> Option { let ctx = ui.ctx(); From 4ac09bf4f702599dc735f9d2f39f13028481d113 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 06:59:40 +0000 Subject: [PATCH 03/22] Assets: one grid per tab sorted by name, without category headers; search results in one grid --- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/shelf.rs | 255 ++++-------------- crates/ui-egui/src/shelf_entry.rs | 150 +++++++++++ .../ui-egui/tests/it/shelf_hover_preview.rs | 14 +- 4 files changed, 217 insertions(+), 203 deletions(-) create mode 100644 crates/ui-egui/src/shelf_entry.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 815ba793..c47ddd4f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -47,6 +47,7 @@ mod resource_picker; mod resource_picker_item; mod running_bake; pub mod shelf; +mod shelf_entry; pub mod shelf_preview; mod soft_box; pub mod state; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 51700285..7afff1f2 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -1,27 +1,23 @@ //! The asset shelf (the Assets dock tab): tabs (materials, smart materials, smart //! masks, filters, alphas, procedurals, environments, textures), all built in and procedural. -//! Search filters across every tab. Materials (built in and saved), smart masks, filters, alphas +//! Each tab is one grid sorted by name; a search shows the matches of every tab in one grid. +//! Materials (built in and saved), smart masks, filters, alphas //! and textures drag onto the layer stack, a layer row, the viewport or the brush properties //! ([`ShelfDrag`]); a texture dropped on the 3D view becomes a decal there, in the channel picked from a menu use egui::{Color32, RichText, Sense, Stroke, Ui, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -use texturecraft_engine::core::ProceduralKind; -use texturecraft_engine::filter_lib::FILTERS; #[cfg(not(target_arch = "wasm32"))] use texturecraft_engine::formats::mcmat::MCMAT_EXT; use texturecraft_engine::geom::glam::Vec2; -use texturecraft_engine::materials::MATERIALS; use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; -use texturecraft_engine::paint::alphas; -use texturecraft_engine::paint::presets::{BrushPreset, PRESETS}; -use texturecraft_engine::smart_masks::SMART_MASKS; use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; use crate::decal_drop::DecalDrop; use crate::i18n::{tr, trf}; +use crate::shelf_entry::ShelfEntry; use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; use crate::thumbs::Thumbs; @@ -248,28 +244,30 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { ui.add_space(4.0); let filter = app.ui.shelf_filter.to_lowercase(); - egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).show(ui, |ui| { - // Searching shows matches from every tab, each under its tab's name - for (i, (t, _, title)) in TABS.iter().enumerate() { - if filter.is_empty() && i != tab { - continue; - } + let shown_tab = TABS[tab].0; + // Searching shows matches from every tab in one grid + let mut entries: Vec = + ShelfEntry::all(app).into_iter().filter(|entry| (searching || entry.tab() == shown_tab) && entry.matches(&filter)).collect(); + entries.sort_by_cached_key(|entry| entry.label().to_lowercase()); - let title = tr(title); - match t { - Tab::Materials => materials(app, ui, &ctx, &filter, false, title), - Tab::Smart => { - materials(app, ui, &ctx, &filter, true, title); - library(app, ui, &filter); - } - Tab::Masks => smart_masks(app, ui, &ctx, &filter, title), - Tab::Filters => filters(app, ui, &ctx, &filter, title), - Tab::Brushes => brushes(app, ui, &ctx, &filter, title), - Tab::Alphas => alpha_library(app, ui, &ctx, &filter, title), - Tab::Procedurals => procedurals(app, ui, &ctx, &filter, title), - Tab::Environments => environments(app, ui, &filter, title), - Tab::Textures => textures(app, ui, &ctx, &filter, title), + egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).show(ui, |ui| { + if !searching && shown_tab == Tab::Textures { + import_images(app, ui, &ctx, entries.is_empty()); + } + tiles(ui, |ui| { + for entry in &entries { + entry_tile(app, ui, &ctx, entry); } + }); + + if searching || shown_tab == Tab::Smart { + library(app, ui, &filter); + } + if searching || shown_tab == Tab::Brushes { + my_brushes(app, ui, &filter); + } + if searching || shown_tab == Tab::Environments { + environments(app, ui, &filter); } }); drag_preview(&ctx); @@ -291,11 +289,6 @@ pub(crate) fn matches(filter: &str, texts: &[&str]) -> bool { filter.is_empty() || texts.iter().any(|t| t.to_lowercase().contains(filter)) } -fn title(ui: &mut Ui, text: &str) { - let tk = Tokens::get(ui.ctx()); - ui.label(RichText::new(text).strong().color(tk.text_strong)); -} - pub(crate) fn header(ui: &mut Ui, text: &str) { let tk = Tokens::get(ui.ctx()); ui.add_space(2.0); @@ -321,29 +314,6 @@ pub(crate) fn categories(items: &[T], category: impl Fn(&T) -> &'static str) out } -/// Built-in materials or smart materials, grouped by category -fn materials(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, smart: bool, name: &str) { - let shown: Vec<_> = - MATERIALS.iter().filter(|material| material.smart == smart && matches(filter, &[material.label, material.category, material.id])).collect(); - if shown.is_empty() { - return; - } - - title(ui, name); - for category in categories(&shown, |material| material.category) { - header(ui, category); - tiles(ui, |ui| { - for material in shown.iter().filter(|material| material.category == category) { - let texture = app.thumbs.material(ctx, material.id); - let asset = Asset::Material(material.id); - if tile(ui, &mut app.thumbs, texture.as_ref(), || ShelfPreview::material(material.id), material.label, Some(&asset)).clicked() { - apply(app, &asset); - } - } - }); - } -} - /// The user's saved smart materials (desktop library folder). #[cfg(not(target_arch = "wasm32"))] fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { @@ -393,66 +363,6 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { #[cfg(target_arch = "wasm32")] fn library(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {} -fn smart_masks(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let shown: Vec<_> = SMART_MASKS.iter().filter(|m| matches(filter, &[m.label, m.id])).collect(); - if shown.is_empty() { - return; - } - title(ui, name); - tiles(ui, |ui| { - for m in shown { - let tex = app.thumbs.smart_mask(ctx, m.id); - let asset = Asset::SmartMask(m.id); - if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::SmartMask(m.id), m.label, Some(&asset)).clicked() { - apply(app, &asset); - } - } - }); -} - -/// The filter library, grouped: a click adds the filter to the selected layer's content (or its -/// mask when the mask is selected), a drop onto a layer to that layer's content. -fn filters(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let shown: Vec<_> = FILTERS.iter().filter(|f| matches(filter, &[f.label, f.group, f.id, tr(f.label), tr(f.group)])).collect(); - if shown.is_empty() { - return; - } - title(ui, name); - for group in categories(&shown, |f| f.group) { - header(ui, tr(group)); - tiles(ui, |ui| { - for f in shown.iter().filter(|f| f.group == group) { - let tex = app.thumbs.filter(ctx, f.id); - let asset = Asset::Filter(f.id); - if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Filter(f.id), tr(f.label), Some(&asset)).clicked() { - apply(app, &asset); - } - } - }); - } -} - -/// Brush presets, grouped by category, then the user's own: a click sets the brush's stroke -/// (alpha, spacing, flow, jitters…) and keeps its size. -fn brushes(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let shown: Vec<&BrushPreset> = PRESETS.iter().filter(|p| matches(filter, &[p.label, p.category, p.id])).collect(); - if !shown.is_empty() { - title(ui, name); - for cat in categories(&shown, |p| p.category) { - header(ui, cat); - tiles(ui, |ui| { - for p in shown.iter().filter(|p| p.category == cat) { - let tex = app.thumbs.brush_preset(ctx, p); - if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Brush(p), p.label, None).clicked() { - app.run("brush.preset.apply", json!({"preset": p.id})); - } - } - }); - } - } - my_brushes(app, ui, filter); -} - /// The user's saved brush presets (desktop brushes folder) and saving the current brush there. #[cfg(not(target_arch = "wasm32"))] fn my_brushes(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { @@ -508,57 +418,8 @@ fn my_brushes(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { #[cfg(target_arch = "wasm32")] fn my_brushes(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {} -/// The built-in alpha library, grouped by category; the brush's alpha is outlined. -fn alpha_library(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let tk = Tokens::get(ctx); - let shown: Vec<&'static alphas::LibraryAlpha> = alphas::library().iter().filter(|a| matches(filter, &[&a.label, a.category, &a.id])).collect(); - if shown.is_empty() { - return; - } - title(ui, name); - let brush = &app.session.tool.brush; - let current = if brush.alpha_image.is_none() { brush.alpha_library.clone() } else { None }; - for cat in categories(&shown, |a| a.category) { - header(ui, cat); - tiles(ui, |ui| { - for &a in shown.iter().filter(|a| a.category == cat) { - let tex = app.thumbs.alpha(ctx, a); - let asset = Asset::Alpha(&a.id); - let r = tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Alpha(a), &a.label, Some(&asset)); - if current.as_deref() == Some(a.id.as_str()) { - ui.painter().rect_stroke(r.rect, TILE_ROUNDING, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); - } - if r.clicked() { - apply(app, &asset); - } - } - }); - } -} - -fn procedurals(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { - let shown: Vec = ProceduralKind::ALL.into_iter().filter(|k| matches(filter, &[k.label(), tr(k.label())])).collect(); - if shown.is_empty() { - return; - } - title(ui, name); - tiles(ui, |ui| { - for k in shown { - let tex = app.thumbs.procedural(ctx, k); - if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Procedural(k), tr(k.label()), None).clicked() { - app.run("layer.add.fill", json!({"name": k.label()})); - app.run("layer.fill.set", json!({"channel": "baseColor", "procedural": k.label(), "low": [0.1, 0.1, 0.1], "high": [0.9, 0.9, 0.9]})); - } - } - }); -} - -fn environments(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str, name: &str) { +fn environments(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { let shown: Vec<&&str> = ENVIRONMENTS.iter().filter(|e| matches(filter, &[e])).collect(); - if shown.is_empty() { - return; - } - title(ui, name); for env in shown { let on = app.session.doc.project.display.environment == **env; if ui.selectable_label(on, format!("{} {env}", ic::SUN_HORIZON)).clicked() { @@ -568,44 +429,44 @@ fn environments(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str, name: &str ui.add_space(6.0); } -fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { +/// The Textures tab's import button, and a hint while the project has no images +fn import_images(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, empty: bool) { let tk = Tokens::get(ctx); - let names: Vec = app.session.doc.resources.keys().filter(|n| matches(filter, &[n])).cloned().collect(); - if !filter.is_empty() && names.is_empty() { - return; + if ui.small_button(tr("Import...")).clicked() { + crate::menus::invoke(app, ctx, "resource.import"); } - ui.horizontal(|ui| { - title(ui, name); - if ui.small_button(tr("Import...")).clicked() { - crate::menus::invoke(app, ctx, "resource.import"); - } - }); - if names.is_empty() { + if empty { ui.label(RichText::new(tr("Import images to use them in fills and masks")).size(10.0).color(tk.text_dim)); } - tiles(ui, |ui| { - for name in names { - let Some(img) = app.session.images.get(&name).cloned() else { continue }; +} - let tex = app.thumbs.image(ctx, &name, &img); - let asset = Asset::Texture(name.clone()); - let preview = || ShelfPreview::Image(name.clone(), img); - let r = tile(ui, &mut app.thumbs, Some(&tex), preview, &name, Some(&asset)); - if r.clicked() { - apply(app, &asset); +/// The tile of `entry`: a click applies it, an image resource has a context menu +fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry) { + // An image removed this frame has nothing to show + let (Some(preview), texture) = (entry.preview(app), entry.thumbnail(app, ctx)) else { return }; + + let asset = entry.asset(); + let response = tile(ui, &mut app.thumbs, texture.as_ref(), || preview, entry.label(), asset.as_ref()); + if entry.in_use(app) { + let tk = Tokens::get(ctx); + ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); + } + if response.clicked() { + 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(); } - r.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(); - } - }); - } - }); + if ui.button(tr("Remove resource")).clicked() { + app.run("resource.remove", json!({"name": name})); + ui.close(); + } + }); + } } /// Asset tile with optional dragging and a larger hover preview diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs new file mode 100644 index 00000000..554cc6a4 --- /dev/null +++ b/crates/ui-egui/src/shelf_entry.rs @@ -0,0 +1,150 @@ +//! One asset on the shelf: its name, the tab it belongs to, and how it previews, drags and applies + +use serde_json::json; +use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::filter_lib::{FILTERS, FilterDef}; +use texturecraft_engine::materials::{MATERIALS, SmartMaterial}; +use texturecraft_engine::paint::alphas::{self, LibraryAlpha}; +use texturecraft_engine::paint::presets::{BrushPreset, PRESETS}; +use texturecraft_engine::smart_masks::{SMART_MASKS, SmartMask}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::shelf::{Asset, Tab, apply}; +use crate::shelf_preview::ShelfPreview; + +/// A shelf tile's asset +#[derive(Clone)] +pub(crate) enum ShelfEntry { + Material(&'static SmartMaterial), + SmartMask(&'static SmartMask), + Filter(&'static FilterDef), + Brush(&'static BrushPreset), + Alpha(&'static LibraryAlpha), + Procedural(ProceduralKind), + /// An image resource of the project, by name + Image(String), +} + +impl ShelfEntry { + /// Every built-in asset and the project's images + pub(crate) fn all(app: &TextureCraftApp) -> Vec { + let built_in = MATERIALS + .iter() + .map(ShelfEntry::Material) + .chain(SMART_MASKS.iter().map(ShelfEntry::SmartMask)) + .chain(FILTERS.iter().map(ShelfEntry::Filter)) + .chain(PRESETS.iter().map(ShelfEntry::Brush)) + .chain(alphas::library().iter().map(ShelfEntry::Alpha)) + .chain(ProceduralKind::ALL.into_iter().map(ShelfEntry::Procedural)); + built_in.chain(app.session.doc.resources.keys().cloned().map(ShelfEntry::Image)).collect() + } + + /// The tab that lists the asset + pub(crate) fn tab(&self) -> Tab { + match self { + ShelfEntry::Material(material) if material.smart => Tab::Smart, + ShelfEntry::Material(_) => Tab::Materials, + ShelfEntry::SmartMask(_) => Tab::Masks, + ShelfEntry::Filter(_) => Tab::Filters, + ShelfEntry::Brush(_) => Tab::Brushes, + ShelfEntry::Alpha(_) => Tab::Alphas, + ShelfEntry::Procedural(_) => Tab::Procedurals, + ShelfEntry::Image(_) => Tab::Textures, + } + } + + /// The name under the tile, translated where the asset's name is + pub(crate) fn label(&self) -> &str { + match self { + ShelfEntry::Material(material) => material.label, + ShelfEntry::SmartMask(mask) => mask.label, + ShelfEntry::Filter(filter) => tr(filter.label), + ShelfEntry::Brush(preset) => preset.label, + ShelfEntry::Alpha(alpha) => &alpha.label, + ShelfEntry::Procedural(kind) => tr(kind.label()), + ShelfEntry::Image(name) => name, + } + } + + /// Whether `filter` (lowercase) matches the asset's name, id or category, in English or translated + pub(crate) fn matches(&self, filter: &str) -> bool { + let texts: &[&str] = match self { + ShelfEntry::Material(material) => &[material.label, material.category, material.id], + ShelfEntry::SmartMask(mask) => &[mask.label, mask.id], + ShelfEntry::Filter(filter) => &[filter.label, filter.group, filter.id, tr(filter.label), tr(filter.group)], + ShelfEntry::Brush(preset) => &[preset.label, preset.category, preset.id], + ShelfEntry::Alpha(alpha) => &[&alpha.label, alpha.category, &alpha.id], + ShelfEntry::Procedural(kind) => &[kind.label(), tr(kind.label())], + ShelfEntry::Image(name) => &[name], + }; + crate::shelf::matches(filter, texts) + } + + /// The thumbnail, or None while it renders + pub(crate) fn thumbnail(&self, app: &mut TextureCraftApp, ctx: &egui::Context) -> Option { + match self { + ShelfEntry::Material(material) => app.thumbs.material(ctx, material.id), + ShelfEntry::SmartMask(mask) => app.thumbs.smart_mask(ctx, mask.id), + ShelfEntry::Filter(filter) => app.thumbs.filter(ctx, filter.id), + ShelfEntry::Brush(preset) => app.thumbs.brush_preset(ctx, preset), + ShelfEntry::Alpha(alpha) => app.thumbs.alpha(ctx, alpha), + ShelfEntry::Procedural(kind) => app.thumbs.procedural(ctx, *kind), + ShelfEntry::Image(name) => { + let image = app.session.images.get(name).cloned()?; + Some(app.thumbs.image(ctx, name, &image)) + } + } + } + + /// What the hover popup renders; None for an image that is gone + pub(crate) fn preview(&self, app: &TextureCraftApp) -> Option { + Some(match self { + ShelfEntry::Material(material) => ShelfPreview::material(material.id), + ShelfEntry::SmartMask(mask) => ShelfPreview::SmartMask(mask.id), + ShelfEntry::Filter(filter) => ShelfPreview::Filter(filter.id), + ShelfEntry::Brush(preset) => ShelfPreview::Brush(preset), + ShelfEntry::Alpha(alpha) => ShelfPreview::Alpha(alpha), + ShelfEntry::Procedural(kind) => ShelfPreview::Procedural(*kind), + ShelfEntry::Image(name) => ShelfPreview::Image(name.clone(), app.session.images.get(name).cloned()?), + }) + } + + /// The drag payload's asset; brushes and procedurals don't drag + pub(crate) fn asset(&self) -> Option { + match self { + ShelfEntry::Material(material) => Some(Asset::Material(material.id)), + ShelfEntry::SmartMask(mask) => Some(Asset::SmartMask(mask.id)), + ShelfEntry::Filter(filter) => Some(Asset::Filter(filter.id)), + ShelfEntry::Alpha(alpha) => Some(Asset::Alpha(&alpha.id)), + ShelfEntry::Image(name) => Some(Asset::Texture(name.clone())), + ShelfEntry::Brush(_) | ShelfEntry::Procedural(_) => None, + } + } + + /// Whether the tile is outlined as in use: the brush's library alpha + pub(crate) fn in_use(&self, app: &TextureCraftApp) -> bool { + let ShelfEntry::Alpha(alpha) = self else { return false }; + + let brush = &app.session.tool.brush; + brush.alpha_image.is_none() && brush.alpha_library.as_deref() == Some(alpha.id.as_str()) + } + + /// What a click on the tile does + pub(crate) fn activate(&self, app: &mut TextureCraftApp) { + match self { + ShelfEntry::Brush(preset) => { + app.run("brush.preset.apply", json!({"preset": preset.id})); + } + ShelfEntry::Procedural(kind) => { + app.run("layer.add.fill", json!({"name": kind.label()})); + app.run("layer.fill.set", json!({"channel": "baseColor", "procedural": kind.label(), "low": [0.1, 0.1, 0.1], "high": [0.9, 0.9, 0.9]})); + } + entry => { + if let Some(asset) = entry.asset() { + apply(app, &asset); + } + } + } + } +} diff --git a/crates/ui-egui/tests/it/shelf_hover_preview.rs b/crates/ui-egui/tests/it/shelf_hover_preview.rs index c7ad071a..4deda09a 100644 --- a/crates/ui-egui/tests/it/shelf_hover_preview.rs +++ b/crates/ui-egui/tests/it/shelf_hover_preview.rs @@ -20,20 +20,22 @@ const REST: f32 = 0.1; /// Real time the worker gets to render const WORKER_TIMEOUT: Duration = Duration::from_secs(60); -/// Open the Materials tab and find two labels unique to shelf tiles +/// Open the Materials tab and find the first two labels (the grid is sorted by name) unique to shelf tiles fn materials_shelf(step_seconds: f32, pixels_per_point: f32) -> (Harness<'static, TextureCraftApp>, Vec<&'static SmartMaterial>) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder() + let mut harness = Harness::builder() .with_size(egui::vec2(1600.0, 960.0)) .with_step_dt(step_seconds) .with_pixels_per_point(pixels_per_point) .build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.state_mut().ui.shelf_tab = MATERIALS_TAB; - h.run_steps(4); + harness.state_mut().ui.shelf_tab = MATERIALS_TAB; + harness.run_steps(4); - let unique: Vec<_> = MATERIALS.iter().filter(|m| !m.smart && h.query_all_by_label(m.label).count() == 1).take(2).collect(); + let mut plain: Vec<_> = MATERIALS.iter().filter(|material| !material.smart).collect(); + plain.sort_by_key(|material| material.label.to_lowercase()); + let unique: Vec<_> = plain.into_iter().filter(|material| harness.query_all_by_label(material.label).count() == 1).take(2).collect(); assert_eq!(unique.len(), 2, "two materials with unique names"); - (h, unique) + (harness, unique) } /// Largest drawn texture in pixels, excluding fonts and images below `min_width` points From 3bcd57de006c3e361da190eb0e3375e3a8119374 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 06:59:51 +0000 Subject: [PATCH 04/22] Assets: a wider default panel, four tile columns in a 1920 px window; the right column gives up the width --- crates/ui-egui/src/docking.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 5bebfd98..1b6e9b2a 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -133,7 +133,7 @@ fn split(axis: SplitAxis, size: SplitSize, first: Node, second: Node Workspace { use Panel::*; let column = split( @@ -143,7 +143,7 @@ pub fn default_workspace() -> Workspace { split(SplitAxis::Vertical, SplitSize::Ratio(0.57), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])), ); let root = - split(SplitAxis::Horizontal, SplitSize::Ratio(0.115), tabs(&[Assets]), split(SplitAxis::Horizontal, SplitSize::Ratio(0.78), tabs(&[Viewport]), column)); + split(SplitAxis::Horizontal, SplitSize::Ratio(0.16), tabs(&[Assets]), split(SplitAxis::Horizontal, SplitSize::Ratio(0.80), tabs(&[Viewport]), column)); let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() }); for panel in Panel::ALL { From 0a327746c6303059000fd85e6baa73eeef7c6c06 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 07:02:42 +0000 Subject: [PATCH 05/22] Assets: outline the last clicked or right-clicked tile --- crates/ui-egui/src/shelf.rs | 17 +++++++++++++++-- crates/ui-egui/src/shelf_entry.rs | 13 +++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 7afff1f2..1890c30e 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -29,6 +29,11 @@ const TILE_HEIGHT: f32 = 76.0; const TILE_GAP: f32 = 2.0; /// Corner radius of a tile's hover and selection highlights, in points const TILE_ROUNDING: f32 = 3.0; +/// The last clicked or right-clicked tile's [`ShelfEntry::key`], kept in egui's memory under this id +const SELECTED_TILE: &str = "shelf_selected_tile"; +/// The outline widths of the selected tile and of the one in use (the brush's alpha, the shown environment), in points +const SELECTED_OUTLINE_WIDTH: f32 = 1.5; +const IN_USE_OUTLINE_WIDTH: f32 = 1.0; /// The thumbnail's size in a tile and its center below the tile's top, in points const THUMBNAIL_SIZE: f32 = 60.0; const THUMBNAIL_CENTER_Y: f32 = 31.0; @@ -447,9 +452,17 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry let asset = entry.asset(); let response = tile(ui, &mut app.thumbs, texture.as_ref(), || preview, entry.label(), asset.as_ref()); - if entry.in_use(app) { + let selected_id = egui::Id::unique(SELECTED_TILE); + let key = entry.key(); + let selected = ctx.data(|data| data.get_temp::(selected_id)).is_some_and(|selected| selected == key); + if selected || entry.in_use(app) { let tk = Tokens::get(ctx); - ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); + let width = if selected { SELECTED_OUTLINE_WIDTH } else { IN_USE_OUTLINE_WIDTH }; + ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(width, tk.accent), egui::StrokeKind::Inside); + } + + if response.clicked() || response.secondary_clicked() { + ctx.data_mut(|data| data.insert_temp(selected_id, key)); } if response.clicked() { entry.activate(app); diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index 554cc6a4..be43977b 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -54,6 +54,19 @@ impl ShelfEntry { } } + /// The asset's identity across frames: its kind and id + pub(crate) fn key(&self) -> String { + match self { + ShelfEntry::Material(material) => format!("material:{}", material.id), + ShelfEntry::SmartMask(mask) => format!("mask:{}", mask.id), + ShelfEntry::Filter(filter) => format!("filter:{}", filter.id), + ShelfEntry::Brush(preset) => format!("brush:{}", preset.id), + ShelfEntry::Alpha(alpha) => format!("alpha:{}", alpha.id), + ShelfEntry::Procedural(kind) => format!("procedural:{kind:?}"), + ShelfEntry::Image(name) => format!("image:{name}"), + } + } + /// The name under the tile, translated where the asset's name is pub(crate) fn label(&self) -> &str { match self { From 1be96b8248d6d23eeba5c281b672c8d700d68076 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 07:10:52 +0000 Subject: [PATCH 06/22] Assets: environments as tiles with their panorama, the shown one outlined --- crates/ui-egui/src/preview_image.rs | 17 ++++++++++++++++ crates/ui-egui/src/shelf.rs | 15 -------------- crates/ui-egui/src/shelf_entry.rs | 31 ++++++++++++++++++++++------- crates/ui-egui/src/shelf_preview.rs | 7 ++++++- crates/ui-egui/src/thumbs.rs | 5 +++++ 5 files changed, 52 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs index 9b753b74..16709385 100644 --- a/crates/ui-egui/src/preview_image.rs +++ b/crates/ui-egui/src/preview_image.rs @@ -194,3 +194,20 @@ pub fn stroke_preview(b: &BrushSettings, n: usize) -> ColorImage { } ColorImage::new([n, n], cover.into_iter().map(|v| Color32::from_gray((v * b.opacity * 255.0 + 0.5) as u8)).collect()) } + +/// Environment `name`'s panorama across a `size²` swatch, transparent above and below +pub fn environment_image(name: &str, size: usize) -> ColorImage { + let panorama = texturecraft_render::ibl::environment(name, u32::try_from(size).unwrap_or(u32::MAX)); + let (width, height) = (panorama.width as usize, panorama.height as usize); + let mut image = ColorImage::filled([size, size], Color32::TRANSPARENT); + let top = size.saturating_sub(height) / 2; + for (y, row) in panorama.data.chunks(width.max(1)).enumerate() { + for (x, linear) in row.iter().enumerate().take(size) { + let Some(pixel) = image.pixels.get_mut((top + y) * size + x) else { continue }; + + let [r, g, b] = linear.map(|component| (linear_to_srgb(aces(component * EXPOSURE)) * 255.0 + 0.5) as u8); + *pixel = Color32::from_rgb(r, g, b); + } + } + image +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 1890c30e..0ff1cc6a 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -12,7 +12,6 @@ use serde_json::json; use texturecraft_engine::formats::mcmat::MCMAT_EXT; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; -use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; use crate::decal_drop::DecalDrop; @@ -271,9 +270,6 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { if searching || shown_tab == Tab::Brushes { my_brushes(app, ui, &filter); } - if searching || shown_tab == Tab::Environments { - environments(app, ui, &filter); - } }); drag_preview(&ctx); } @@ -423,17 +419,6 @@ fn my_brushes(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { #[cfg(target_arch = "wasm32")] fn my_brushes(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {} -fn environments(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { - let shown: Vec<&&str> = ENVIRONMENTS.iter().filter(|e| matches(filter, &[e])).collect(); - for env in shown { - let on = app.session.doc.project.display.environment == **env; - if ui.selectable_label(on, format!("{} {env}", ic::SUN_HORIZON)).clicked() { - app.run("display.set", json!({"environment": env})); - } - } - ui.add_space(6.0); -} - /// The Textures tab's import button, and a hint while the project has no images fn import_images(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, empty: bool) { let tk = Tokens::get(ctx); diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index be43977b..c44ecb1c 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -2,6 +2,7 @@ use serde_json::json; use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::core::project::ENVIRONMENTS; use texturecraft_engine::filter_lib::{FILTERS, FilterDef}; use texturecraft_engine::materials::{MATERIALS, SmartMaterial}; use texturecraft_engine::paint::alphas::{self, LibraryAlpha}; @@ -22,6 +23,8 @@ pub(crate) enum ShelfEntry { Brush(&'static BrushPreset), Alpha(&'static LibraryAlpha), Procedural(ProceduralKind), + /// A built-in lighting environment, by name + Environment(&'static str), /// An image resource of the project, by name Image(String), } @@ -36,7 +39,8 @@ impl ShelfEntry { .chain(FILTERS.iter().map(ShelfEntry::Filter)) .chain(PRESETS.iter().map(ShelfEntry::Brush)) .chain(alphas::library().iter().map(ShelfEntry::Alpha)) - .chain(ProceduralKind::ALL.into_iter().map(ShelfEntry::Procedural)); + .chain(ProceduralKind::ALL.into_iter().map(ShelfEntry::Procedural)) + .chain(ENVIRONMENTS.into_iter().map(ShelfEntry::Environment)); built_in.chain(app.session.doc.resources.keys().cloned().map(ShelfEntry::Image)).collect() } @@ -50,6 +54,7 @@ impl ShelfEntry { ShelfEntry::Brush(_) => Tab::Brushes, ShelfEntry::Alpha(_) => Tab::Alphas, ShelfEntry::Procedural(_) => Tab::Procedurals, + ShelfEntry::Environment(_) => Tab::Environments, ShelfEntry::Image(_) => Tab::Textures, } } @@ -63,6 +68,7 @@ impl ShelfEntry { ShelfEntry::Brush(preset) => format!("brush:{}", preset.id), ShelfEntry::Alpha(alpha) => format!("alpha:{}", alpha.id), ShelfEntry::Procedural(kind) => format!("procedural:{kind:?}"), + ShelfEntry::Environment(name) => format!("environment:{name}"), ShelfEntry::Image(name) => format!("image:{name}"), } } @@ -76,6 +82,7 @@ impl ShelfEntry { ShelfEntry::Brush(preset) => preset.label, ShelfEntry::Alpha(alpha) => &alpha.label, ShelfEntry::Procedural(kind) => tr(kind.label()), + ShelfEntry::Environment(name) => name, ShelfEntry::Image(name) => name, } } @@ -89,6 +96,7 @@ impl ShelfEntry { ShelfEntry::Brush(preset) => &[preset.label, preset.category, preset.id], ShelfEntry::Alpha(alpha) => &[&alpha.label, alpha.category, &alpha.id], ShelfEntry::Procedural(kind) => &[kind.label(), tr(kind.label())], + ShelfEntry::Environment(name) => &[name], ShelfEntry::Image(name) => &[name], }; crate::shelf::matches(filter, texts) @@ -103,6 +111,7 @@ impl ShelfEntry { ShelfEntry::Brush(preset) => app.thumbs.brush_preset(ctx, preset), ShelfEntry::Alpha(alpha) => app.thumbs.alpha(ctx, alpha), ShelfEntry::Procedural(kind) => app.thumbs.procedural(ctx, *kind), + ShelfEntry::Environment(name) => app.thumbs.environment(ctx, name), ShelfEntry::Image(name) => { let image = app.session.images.get(name).cloned()?; Some(app.thumbs.image(ctx, name, &image)) @@ -119,6 +128,7 @@ impl ShelfEntry { ShelfEntry::Brush(preset) => ShelfPreview::Brush(preset), ShelfEntry::Alpha(alpha) => ShelfPreview::Alpha(alpha), ShelfEntry::Procedural(kind) => ShelfPreview::Procedural(*kind), + ShelfEntry::Environment(name) => ShelfPreview::Environment(name), ShelfEntry::Image(name) => ShelfPreview::Image(name.clone(), app.session.images.get(name).cloned()?), }) } @@ -131,16 +141,20 @@ impl ShelfEntry { ShelfEntry::Filter(filter) => Some(Asset::Filter(filter.id)), ShelfEntry::Alpha(alpha) => Some(Asset::Alpha(&alpha.id)), ShelfEntry::Image(name) => Some(Asset::Texture(name.clone())), - ShelfEntry::Brush(_) | ShelfEntry::Procedural(_) => None, + ShelfEntry::Brush(_) | ShelfEntry::Procedural(_) | ShelfEntry::Environment(_) => None, } } - /// Whether the tile is outlined as in use: the brush's library alpha + /// Whether the tile is outlined as in use: the brush's library alpha, the shown environment pub(crate) fn in_use(&self, app: &TextureCraftApp) -> bool { - let ShelfEntry::Alpha(alpha) = self else { return false }; - - let brush = &app.session.tool.brush; - brush.alpha_image.is_none() && brush.alpha_library.as_deref() == Some(alpha.id.as_str()) + match self { + ShelfEntry::Alpha(alpha) => { + let brush = &app.session.tool.brush; + brush.alpha_image.is_none() && brush.alpha_library.as_deref() == Some(alpha.id.as_str()) + } + ShelfEntry::Environment(name) => app.session.doc.project.display.environment == *name, + _ => false, + } } /// What a click on the tile does @@ -153,6 +167,9 @@ impl ShelfEntry { app.run("layer.add.fill", json!({"name": kind.label()})); app.run("layer.fill.set", json!({"channel": "baseColor", "procedural": kind.label(), "low": [0.1, 0.1, 0.1], "high": [0.9, 0.9, 0.9]})); } + ShelfEntry::Environment(name) => { + app.run("display.set", json!({"environment": name})); + } entry => { if let Some(asset) = entry.asset() { apply(app, &asset); diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index b512f250..c4b4ae36 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -11,7 +11,7 @@ use texturecraft_engine::paint::alphas::LibraryAlpha; use texturecraft_engine::paint::presets::BrushPreset; use texturecraft_engine::preview; -use crate::preview_image::{alpha_image, image_preview, procedural_image, sphere_image, stroke_preview}; +use crate::preview_image::{alpha_image, environment_image, image_preview, procedural_image, sphere_image, stroke_preview}; /// The asset a shelf tile previews pub enum ShelfPreview { @@ -31,6 +31,8 @@ pub enum ShelfPreview { Brush(&'static BrushPreset), /// An image resource by name Image(String, Arc), + /// A built-in lighting environment's panorama + Environment(&'static str), } impl ShelfPreview { @@ -53,6 +55,7 @@ impl ShelfPreview { ShelfPreview::Alpha(alpha) => format!("alpha:{}", alpha.id), ShelfPreview::Brush(preset) => format!("brush:{}", preset.id), ShelfPreview::Image(name, _) => format!("image:{name}"), + ShelfPreview::Environment(name) => format!("environment:{name}"), } } @@ -67,6 +70,7 @@ impl ShelfPreview { ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)), ShelfPreview::Brush(preset) => Some(stroke_preview(&preset.applied(&BrushSettings::default()), size)), ShelfPreview::Image(_, image) => Some(image_preview(image, size)), + ShelfPreview::Environment(name) => Some(environment_image(name, size)), } } } @@ -93,6 +97,7 @@ mod tests { ShelfPreview::Alpha(&alphas::library()[0]), ShelfPreview::Brush(&PRESETS[0]), ShelfPreview::Image("image".into(), Arc::new(image)), + ShelfPreview::Environment(texturecraft_engine::core::project::ENVIRONMENTS[0]), ]; for preview in previews { let key = preview.key(); diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 059cc0a3..3aa97413 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -212,6 +212,11 @@ impl Thumbs { self.shelf(ctx, ShelfPreview::Alpha(alpha), SWATCH_PX) } + /// A lighting environment's panorama + pub fn environment(&mut self, ctx: &egui::Context, name: &'static str) -> Option { + self.shelf(ctx, ShelfPreview::Environment(name), SWATCH_PX) + } + /// A brush preset's stroke along an S curve pub fn brush_preset(&mut self, ctx: &egui::Context, preset: &'static BrushPreset) -> Option { self.shelf(ctx, ShelfPreview::Brush(preset), SWATCH_PX) From 73e15193decc79776e37eba8ca835c6c2ca047e3 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 07:11:53 +0000 Subject: [PATCH 07/22] =?UTF-8?q?Assets:=20saved=20brushes=20as=20tiles;?= =?UTF-8?q?=20saving=20the=20current=20brush=20moves=20to=20Properties=20?= =?UTF-8?q?=E2=80=BA=20Brush=20=E2=80=BA=20Preset?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-egui/src/brush_preset_save.rs | 34 ++++++++++++++ crates/ui-egui/src/dock.rs | 4 ++ crates/ui-egui/src/i18n/ar.rs | 2 - crates/ui-egui/src/i18n/de.rs | 2 - crates/ui-egui/src/i18n/es.rs | 2 - crates/ui-egui/src/i18n/fr.rs | 2 - crates/ui-egui/src/i18n/it.rs | 2 - crates/ui-egui/src/i18n/ja.rs | 2 - crates/ui-egui/src/i18n/ko.rs | 2 - crates/ui-egui/src/i18n/pt_br.rs | 2 - crates/ui-egui/src/i18n/zh_hans.rs | 2 - crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/shelf.rs | 62 +++++-------------------- crates/ui-egui/src/shelf_entry.rs | 24 ++++++++-- crates/ui-egui/src/shelf_preview.rs | 28 +++++++++++ crates/ui-egui/src/thumbs.rs | 5 ++ 16 files changed, 105 insertions(+), 72 deletions(-) create mode 100644 crates/ui-egui/src/brush_preset_save.rs diff --git a/crates/ui-egui/src/brush_preset_save.rs b/crates/ui-egui/src/brush_preset_save.rs new file mode 100644 index 00000000..7bc0faaa --- /dev/null +++ b/crates/ui-egui/src/brush_preset_save.rs @@ -0,0 +1,34 @@ +//! Saving the current brush as a preset (Properties › Brush › Preset); presets show on the shelf's Brushes tab + +use egui::Ui; +use serde_json::json; +use texturecraft_engine::brush_preset_cmds::BRUSH_EXT; + +use crate::TextureCraftApp; +use crate::i18n::tr; + +/// The preset name field's width in points +const NAME_WIDTH: f32 = 110.0; + +/// A name field and a button that saves the current brush under that name +pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui) { + let dir = crate::user_dir("brushes"); + ui.horizontal(|ui| { + let name_id = ui.make_persistent_id("brush_preset_name"); + let mut new_name: String = ui.data_mut(|data| data.get_temp(name_id)).unwrap_or_default(); + ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(NAME_WIDTH)); + + let file = texturecraft_engine::formats::export::sanitize_file_stem(new_name.trim()); + if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() { + let path = dir.join(format!("{file}.{BRUSH_EXT}")); + // A folder that can't be made fails the save, which reports it + let _ = std::fs::create_dir_all(&dir); + if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_some() { + new_name.clear(); + app.brushes = None; + } + } + + ui.data_mut(|data| data.insert_temp(name_id, new_name)); + }); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 53932f4e..61d39ced 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1583,6 +1583,10 @@ fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { } *brush = brush.sanitized(); + + // Presets are files, which the browser doesn't have + #[cfg(not(target_arch = "wasm32"))] + section(ui, "sec_brush_preset", tr("Preset"), false, |ui| crate::brush_preset_save::row(app, ui)); } /// One alpha in the picker: a 52×64 tile with the shape drawn by `paint` and a label. diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 95373f3d..68e95d5c 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -919,8 +919,6 @@ pub const TABLE: &[(&str, &str)] = &[ "استخدام إطار وأزرار نافذة نظام التشغيل بدلاً من شريط عنوان TextureCraft الخاص", ), ("Brushes", "الفرش"), - ("My brushes", "فرشي"), - ("Use this brush (keeps its size)", "استخدام هذه الفرشاة (مع الحفاظ على حجمها)"), ("Brush name", "اسم الفرشاة"), ("Save current brush", "حفظ الفرشاة الحالية"), ("Start window", "نافذة البدء"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 0f7e7c35..e0f15ab8 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -959,8 +959,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Fensterrahmen und Fenstertasten des Betriebssystems statt der eigenen Titelleiste von TextureCraft verwenden", ), ("Brushes", "Pinsel"), - ("My brushes", "Meine Pinsel"), - ("Use this brush (keeps its size)", "Diesen Pinsel verwenden (Größe bleibt)"), ("Brush name", "Pinselname"), ("Save current brush", "Aktuellen Pinsel speichern"), ("Start window", "Startfenster"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index b5361801..2bd6fc75 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -947,8 +947,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Usar el marco y los botones de ventana del sistema operativo en lugar de la barra de título propia de TextureCraft", ), ("Brushes", "Pinceles"), - ("My brushes", "Mis pinceles"), - ("Use this brush (keeps its size)", "Usar este pincel (conserva su tamaño)"), ("Brush name", "Nombre del pincel"), ("Save current brush", "Guardar el pincel actual"), ("Start window", "Ventana de inicio"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 00b8c2af..73c6b199 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -968,8 +968,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Utiliser le cadre et les boutons de fenêtre du système d'exploitation au lieu de la barre de titre de TextureCraft", ), ("Brushes", "Pinceaux"), - ("My brushes", "Mes pinceaux"), - ("Use this brush (keeps its size)", "Utiliser ce pinceau (garde sa taille)"), ("Brush name", "Nom du pinceau"), ("Save current brush", "Enregistrer le pinceau actuel"), ("Start window", "Fenêtre de démarrage"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index e067cf67..d785fb4a 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -953,8 +953,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Usa la cornice e i pulsanti della finestra del sistema operativo invece della barra del titolo di TextureCraft", ), ("Brushes", "Pennelli"), - ("My brushes", "I miei pennelli"), - ("Use this brush (keeps its size)", "Usa questo pennello (mantiene la dimensione)"), ("Brush name", "Nome del pennello"), ("Save current brush", "Salva il pennello attuale"), ("Start window", "Finestra iniziale"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 0e60e132..c437a9a5 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -941,8 +941,6 @@ pub const TABLE: &[(&str, &str)] = &[ "TextureCraft 独自のタイトルバーの代わりに、OS のウィンドウ枠とボタンを使います", ), ("Brushes", "ブラシ一覧"), - ("My brushes", "マイブラシ"), - ("Use this brush (keeps its size)", "このブラシを使用(サイズはそのまま)"), ("Brush name", "ブラシ名"), ("Save current brush", "現在のブラシを保存"), ("Start window", "スタートウィンドウ"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 7f80b6be..df46e2f1 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -929,8 +929,6 @@ pub const TABLE: &[(&str, &str)] = &[ "TextureCraft 자체 제목 표시줄 대신 운영 체제의 창 테두리와 버튼을 사용합니다", ), ("Brushes", "브러시 목록"), - ("My brushes", "내 브러시"), - ("Use this brush (keeps its size)", "이 브러시 사용 (크기 유지)"), ("Brush name", "브러시 이름"), ("Save current brush", "현재 브러시 저장"), ("Start window", "시작 창"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index e5b023af..87b0fc93 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -944,8 +944,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Usar a moldura e os botões de janela do sistema operacional em vez da barra de título própria do TextureCraft", ), ("Brushes", "Pincéis"), - ("My brushes", "Meus pincéis"), - ("Use this brush (keeps its size)", "Usar este pincel (mantém o tamanho)"), ("Brush name", "Nome do pincel"), ("Save current brush", "Salvar o pincel atual"), ("Start window", "Janela inicial"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index ef4209e4..3f1e89f7 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -884,8 +884,6 @@ pub const TABLE: &[(&str, &str)] = &[ "使用操作系统的窗口边框和按钮,而不是 TextureCraft 自己的标题栏", ), ("Brushes", "笔刷库"), - ("My brushes", "我的笔刷"), - ("Use this brush (keeps its size)", "使用此笔刷(保留大小)"), ("Brush name", "笔刷名称"), ("Save current brush", "保存当前笔刷"), ("Start window", "启动窗口"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c47ddd4f..cbfc80a8 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -10,6 +10,8 @@ mod bake_job; pub mod bake_mode; mod bake_scene; +#[cfg(not(target_arch = "wasm32"))] +mod brush_preset_save; mod color_selection_editor; pub mod control; mod decal_drop; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 0ff1cc6a..2e8f6a82 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -249,6 +249,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let filter = app.ui.shelf_filter.to_lowercase(); let shown_tab = TABS[tab].0; + scan_brushes(app); // Searching shows matches from every tab in one grid let mut entries: Vec = ShelfEntry::all(app).into_iter().filter(|entry| (searching || entry.tab() == shown_tab) && entry.matches(&filter)).collect(); @@ -267,9 +268,6 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { if searching || shown_tab == Tab::Smart { library(app, ui, &filter); } - if searching || shown_tab == Tab::Brushes { - my_brushes(app, ui, &filter); - } }); drag_preview(&ctx); } @@ -364,60 +362,24 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { #[cfg(target_arch = "wasm32")] fn library(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {} -/// The user's saved brush presets (desktop brushes folder) and saving the current brush there. +/// Read the user's saved brush presets (desktop brushes folder) unless they are already listed #[cfg(not(target_arch = "wasm32"))] -fn my_brushes(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { +fn scan_brushes(app: &mut TextureCraftApp) { use texturecraft_engine::brush_preset_cmds::BRUSH_EXT; - let dir = crate::user_dir("brushes"); - if app.brushes.is_none() { - let mut files: Vec = std::fs::read_dir(&dir) - .map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == BRUSH_EXT)).collect()) - .unwrap_or_default(); - files.sort(); - app.brushes = Some(files); - } - let files = app.brushes.clone().unwrap_or_default(); - let name = |f: &std::path::PathBuf| f.file_stem().and_then(|s| s.to_str()).unwrap_or("brush").to_string(); - let shown: Vec<_> = files.iter().filter(|f| matches(filter, &[&name(f)])).collect(); - if !filter.is_empty() && shown.is_empty() { + + if app.brushes.is_some() { return; } - ui.horizontal(|ui| { - header(ui, tr("My brushes")); - if ui.small_button(ic::ARROW_CLOCKWISE).on_hover_text(tr("Rescan the library folder")).clicked() { - app.brushes = None; - } - }); - for f in shown { - if ui - .add(egui::Button::selectable(false, format!("{} {}", ic::PAINT_BRUSH_BROAD, name(f)))) - .on_hover_text(tr("Use this brush (keeps its size)")) - .clicked() - { - app.run("brush.preset.load", json!({"path": f.display().to_string()})); - } - } - ui.horizontal(|ui| { - let id = ui.make_persistent_id("brush_preset_name"); - let mut new_name: String = ui.data_mut(|d| d.get_temp(id)).unwrap_or_default(); - ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(110.0)); - let file = texturecraft_engine::formats::export::sanitize_file_stem(new_name.trim()); - if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() { - let path = dir.join(format!("{file}.{BRUSH_EXT}")); - // A folder that can't be made fails the save, which reports it. - let _ = std::fs::create_dir_all(&dir); - if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_some() { - new_name.clear(); - app.brushes = None; - } - } - ui.data_mut(|d| d.insert_temp(id, new_name)); - }); - ui.add_space(6.0); + + let mut files: Vec = std::fs::read_dir(crate::user_dir("brushes")) + .map(|dir| dir.flatten().map(|entry| entry.path()).filter(|path| path.extension().is_some_and(|extension| extension == BRUSH_EXT)).collect()) + .unwrap_or_default(); + files.sort(); + app.brushes = Some(files); } #[cfg(target_arch = "wasm32")] -fn my_brushes(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {} +fn scan_brushes(_: &mut TextureCraftApp) {} /// The Textures tab's import button, and a hint while the project has no images fn import_images(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, empty: bool) { diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index c44ecb1c..a8d4cacc 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -1,5 +1,7 @@ //! One asset on the shelf: its name, the tab it belongs to, and how it previews, drags and applies +use std::path::PathBuf; + use serde_json::json; use texturecraft_engine::core::ProceduralKind; use texturecraft_engine::core::project::ENVIRONMENTS; @@ -14,6 +16,9 @@ use crate::i18n::tr; use crate::shelf::{Asset, Tab, apply}; use crate::shelf_preview::ShelfPreview; +/// The name of a saved brush whose file name isn't text +const SAVED_BRUSH_NAME: &str = "brush"; + /// A shelf tile's asset #[derive(Clone)] pub(crate) enum ShelfEntry { @@ -21,6 +26,8 @@ pub(crate) enum ShelfEntry { SmartMask(&'static SmartMask), Filter(&'static FilterDef), Brush(&'static BrushPreset), + /// A brush preset file the user saved + SavedBrush(PathBuf), Alpha(&'static LibraryAlpha), Procedural(ProceduralKind), /// A built-in lighting environment, by name @@ -30,7 +37,7 @@ pub(crate) enum ShelfEntry { } impl ShelfEntry { - /// Every built-in asset and the project's images + /// Every built-in asset, the user's saved brushes and the project's images pub(crate) fn all(app: &TextureCraftApp) -> Vec { let built_in = MATERIALS .iter() @@ -41,7 +48,8 @@ impl ShelfEntry { .chain(alphas::library().iter().map(ShelfEntry::Alpha)) .chain(ProceduralKind::ALL.into_iter().map(ShelfEntry::Procedural)) .chain(ENVIRONMENTS.into_iter().map(ShelfEntry::Environment)); - built_in.chain(app.session.doc.resources.keys().cloned().map(ShelfEntry::Image)).collect() + let saved = app.brushes.iter().flatten().cloned().map(ShelfEntry::SavedBrush); + built_in.chain(saved).chain(app.session.doc.resources.keys().cloned().map(ShelfEntry::Image)).collect() } /// The tab that lists the asset @@ -51,7 +59,7 @@ impl ShelfEntry { ShelfEntry::Material(_) => Tab::Materials, ShelfEntry::SmartMask(_) => Tab::Masks, ShelfEntry::Filter(_) => Tab::Filters, - ShelfEntry::Brush(_) => Tab::Brushes, + ShelfEntry::Brush(_) | ShelfEntry::SavedBrush(_) => Tab::Brushes, ShelfEntry::Alpha(_) => Tab::Alphas, ShelfEntry::Procedural(_) => Tab::Procedurals, ShelfEntry::Environment(_) => Tab::Environments, @@ -66,6 +74,7 @@ impl ShelfEntry { ShelfEntry::SmartMask(mask) => format!("mask:{}", mask.id), ShelfEntry::Filter(filter) => format!("filter:{}", filter.id), ShelfEntry::Brush(preset) => format!("brush:{}", preset.id), + ShelfEntry::SavedBrush(path) => format!("saved-brush:{}", path.display()), ShelfEntry::Alpha(alpha) => format!("alpha:{}", alpha.id), ShelfEntry::Procedural(kind) => format!("procedural:{kind:?}"), ShelfEntry::Environment(name) => format!("environment:{name}"), @@ -77,6 +86,7 @@ impl ShelfEntry { pub(crate) fn label(&self) -> &str { match self { ShelfEntry::Material(material) => material.label, + ShelfEntry::SavedBrush(path) => path.file_stem().and_then(|stem| stem.to_str()).unwrap_or(SAVED_BRUSH_NAME), ShelfEntry::SmartMask(mask) => mask.label, ShelfEntry::Filter(filter) => tr(filter.label), ShelfEntry::Brush(preset) => preset.label, @@ -91,6 +101,7 @@ impl ShelfEntry { pub(crate) fn matches(&self, filter: &str) -> bool { let texts: &[&str] = match self { ShelfEntry::Material(material) => &[material.label, material.category, material.id], + ShelfEntry::SavedBrush(_) => &[self.label()], ShelfEntry::SmartMask(mask) => &[mask.label, mask.id], ShelfEntry::Filter(filter) => &[filter.label, filter.group, filter.id, tr(filter.label), tr(filter.group)], ShelfEntry::Brush(preset) => &[preset.label, preset.category, preset.id], @@ -109,6 +120,7 @@ impl ShelfEntry { ShelfEntry::SmartMask(mask) => app.thumbs.smart_mask(ctx, mask.id), ShelfEntry::Filter(filter) => app.thumbs.filter(ctx, filter.id), ShelfEntry::Brush(preset) => app.thumbs.brush_preset(ctx, preset), + ShelfEntry::SavedBrush(path) => app.thumbs.saved_brush(ctx, path), ShelfEntry::Alpha(alpha) => app.thumbs.alpha(ctx, alpha), ShelfEntry::Procedural(kind) => app.thumbs.procedural(ctx, *kind), ShelfEntry::Environment(name) => app.thumbs.environment(ctx, name), @@ -126,6 +138,7 @@ impl ShelfEntry { ShelfEntry::SmartMask(mask) => ShelfPreview::SmartMask(mask.id), ShelfEntry::Filter(filter) => ShelfPreview::Filter(filter.id), ShelfEntry::Brush(preset) => ShelfPreview::Brush(preset), + ShelfEntry::SavedBrush(path) => ShelfPreview::SavedBrush(path.clone()), ShelfEntry::Alpha(alpha) => ShelfPreview::Alpha(alpha), ShelfEntry::Procedural(kind) => ShelfPreview::Procedural(*kind), ShelfEntry::Environment(name) => ShelfPreview::Environment(name), @@ -141,7 +154,7 @@ impl ShelfEntry { ShelfEntry::Filter(filter) => Some(Asset::Filter(filter.id)), ShelfEntry::Alpha(alpha) => Some(Asset::Alpha(&alpha.id)), ShelfEntry::Image(name) => Some(Asset::Texture(name.clone())), - ShelfEntry::Brush(_) | ShelfEntry::Procedural(_) | ShelfEntry::Environment(_) => None, + ShelfEntry::Brush(_) | ShelfEntry::SavedBrush(_) | ShelfEntry::Procedural(_) | ShelfEntry::Environment(_) => None, } } @@ -163,6 +176,9 @@ impl ShelfEntry { ShelfEntry::Brush(preset) => { app.run("brush.preset.apply", json!({"preset": preset.id})); } + ShelfEntry::SavedBrush(path) => { + app.run("brush.preset.load", json!({"path": path.display().to_string()})); + } ShelfEntry::Procedural(kind) => { app.run("layer.add.fill", json!({"name": kind.label()})); app.run("layer.fill.set", json!({"channel": "baseColor", "procedural": kind.label(), "low": [0.1, 0.1, 0.1], "high": [0.9, 0.9, 0.9]})); diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index c4b4ae36..076ea14f 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -1,5 +1,6 @@ //! Shelf assets and their preview renderers +use std::path::PathBuf; use std::sync::Arc; use egui::ColorImage; @@ -13,6 +14,10 @@ use texturecraft_engine::preview; use crate::preview_image::{alpha_image, environment_image, image_preview, procedural_image, sphere_image, stroke_preview}; +/// Larger brush preset files aren't read (the `brush.preset.load` command's limit) +#[cfg(not(target_arch = "wasm32"))] +const MAX_SAVED_BRUSH_BYTES: u64 = 1 << 20; + /// The asset a shelf tile previews pub enum ShelfPreview { /// A built-in plain material on a sphere @@ -29,6 +34,8 @@ pub enum ShelfPreview { Alpha(&'static LibraryAlpha), /// A brush preset's stroke along an S curve Brush(&'static BrushPreset), + /// A brush preset file the user saved, its stroke along an S curve + SavedBrush(PathBuf), /// An image resource by name Image(String, Arc), /// A built-in lighting environment's panorama @@ -54,6 +61,7 @@ impl ShelfPreview { ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"), ShelfPreview::Alpha(alpha) => format!("alpha:{}", alpha.id), ShelfPreview::Brush(preset) => format!("brush:{}", preset.id), + ShelfPreview::SavedBrush(path) => format!("saved-brush:{}", path.display()), ShelfPreview::Image(name, _) => format!("image:{name}"), ShelfPreview::Environment(name) => format!("environment:{name}"), } @@ -69,12 +77,32 @@ impl ShelfPreview { ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)), ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)), ShelfPreview::Brush(preset) => Some(stroke_preview(&preset.applied(&BrushSettings::default()), size)), + ShelfPreview::SavedBrush(path) => Some(stroke_preview(&saved_brush(path)?, size)), ShelfPreview::Image(_, image) => Some(image_preview(image, size)), ShelfPreview::Environment(name) => Some(environment_image(name, size)), } } } +/// A saved brush preset's settings; None when the file can't be read (or in the browser, which has no files) +#[cfg(not(target_arch = "wasm32"))] +fn saved_brush(path: &std::path::Path) -> Option { + use std::io::Read as _; + + let mut bytes = Vec::new(); + std::fs::File::open(path).and_then(|file| file.take(MAX_SAVED_BRUSH_BYTES + 1).read_to_end(&mut bytes)).ok()?; + if bytes.len() as u64 > MAX_SAVED_BRUSH_BYTES { + return None; + } + + serde_json::from_slice::(&bytes).ok().map(|settings| settings.sanitized()) +} + +#[cfg(target_arch = "wasm32")] +fn saved_brush(_: &std::path::Path) -> Option { + None +} + #[cfg(test)] mod tests { use texturecraft_engine::filter_lib::FILTERS; diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 3aa97413..a6bd93cb 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -217,6 +217,11 @@ impl Thumbs { self.shelf(ctx, ShelfPreview::Environment(name), SWATCH_PX) } + /// A saved brush preset's stroke along an S curve; None while it renders, empty when the file is unreadable + pub fn saved_brush(&mut self, ctx: &egui::Context, path: &std::path::Path) -> Option { + self.shelf(ctx, ShelfPreview::SavedBrush(path.to_path_buf()), SWATCH_PX) + } + /// A brush preset's stroke along an S curve pub fn brush_preset(&mut self, ctx: &egui::Context, preset: &'static BrushPreset) -> Option { self.shelf(ctx, ShelfPreview::Brush(preset), SWATCH_PX) From e8fd3b0074abbbf260a2fdb99007d08e39b59692 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 10 Nov 2026 07:12:48 +0000 Subject: [PATCH 08/22] Assets: a dots badge on procedurals whose result depends on the random seed --- crates/ui-egui/src/shelf.rs | 27 ++++++++++++++++++- crates/ui-egui/src/shelf_entry.rs | 43 +++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 2e8f6a82..33cac185 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -33,6 +33,14 @@ const SELECTED_TILE: &str = "shelf_selected_tile"; /// The outline widths of the selected tile and of the one in use (the brush's alpha, the shown environment), in points const SELECTED_OUTLINE_WIDTH: f32 = 1.5; const IN_USE_OUTLINE_WIDTH: f32 = 1.0; +/// The randomness badge's dot radius, dot spacing and inset from the thumbnail's corner, in points +const BADGE_DOT_RADIUS: f32 = 1.3; +const BADGE_DOT_SPACING: f32 = 3.6; +const BADGE_INSET: f32 = 2.5; +/// The randomness badge's dot colour and its rim's width (points) and colour +const BADGE_DOT_FILL: Color32 = Color32::from_gray(205); +const BADGE_DOT_RIM: f32 = 0.8; +const BADGE_DOT_RIM_COLOR: Color32 = Color32::from_black_alpha(170); /// The thumbnail's size in a tile and its center below the tile's top, in points const THUMBNAIL_SIZE: f32 = 60.0; const THUMBNAIL_CENTER_Y: f32 = 31.0; @@ -408,6 +416,10 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(width, tk.accent), egui::StrokeKind::Inside); } + if entry.includes_randomness() { + randomness_badge(ui.painter(), response.rect); + } + if response.clicked() || response.secondary_clicked() { ctx.data_mut(|data| data.insert_temp(selected_id, key)); } @@ -452,7 +464,7 @@ pub(crate) fn tile( if resp.hovered() || resp.dragged() { painter.rect_filled(rect, TILE_ROUNDING, tk.row_hover); } - let image_rect = egui::Rect::from_center_size(rect.center_top() + vec2(0.0, THUMBNAIL_CENTER_Y), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); + let image_rect = thumbnail_rect(rect); thumbnail(painter, tex, image_rect, &tk); let galley = painter.layout_job(one_line(label, rect.width() - LABEL_MARGIN, tk.text)); painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tk.text); @@ -461,6 +473,19 @@ pub(crate) fn tile( resp.on_hover_ui(|ui| hover_preview(ui, tex, big.as_ref(), label)) } +/// Where a tile's thumbnail goes in the tile's `rect` +fn thumbnail_rect(rect: egui::Rect) -> egui::Rect { + egui::Rect::from_center_size(rect.center_top() + vec2(0.0, THUMBNAIL_CENTER_Y), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)) +} + +/// Three light, dark-rimmed dots at the thumbnail's bottom-right corner: the asset includes randomness +fn randomness_badge(painter: &egui::Painter, tile: egui::Rect) { + let corner = thumbnail_rect(tile).right_bottom() - vec2(BADGE_INSET, BADGE_INSET); + for offset in [vec2(0.0, 0.0), vec2(-BADGE_DOT_SPACING, 0.0), vec2(-BADGE_DOT_SPACING * 0.5, -BADGE_DOT_SPACING)] { + painter.circle(corner + offset, BADGE_DOT_RADIUS, BADGE_DOT_FILL, Stroke::new(BADGE_DOT_RIM, BADGE_DOT_RIM_COLOR)); + } +} + /// A tile label on one line, cut with "…" past `width` points (the hover popup shows the whole name) fn one_line(label: &str, width: f32, color: Color32) -> egui::text::LayoutJob { let mut job = egui::text::LayoutJob::single_section(label.to_string(), egui::TextFormat::simple(egui::FontId::proportional(LABEL_FONT_SIZE), color)); diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index a8d4cacc..cd147fde 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -19,6 +19,12 @@ use crate::shelf_preview::ShelfPreview; /// The name of a saved brush whose file name isn't text const SAVED_BRUSH_NAME: &str = "brush"; +/// Probes per side of the grid that compares a procedural under two seeds, off the pattern's grid lines +const SEED_PROBES: usize = 4; +const SEED_PROBE_OFFSET: f32 = 0.13; +/// A smaller difference between the two seeds' samples is rounding +const SEED_TOLERANCE: f32 = 1e-4; + /// A shelf tile's asset #[derive(Clone)] pub(crate) enum ShelfEntry { @@ -170,6 +176,14 @@ impl ShelfEntry { } } + /// Whether applying the asset gives a different result per random seed (the tile's dots badge) + pub(crate) fn includes_randomness(&self) -> bool { + match self { + ShelfEntry::Procedural(kind) => SEEDED_PROCEDURALS.contains(kind), + _ => false, + } + } + /// What a click on the tile does pub(crate) fn activate(&self, app: &mut TextureCraftApp) { match self { @@ -194,3 +208,32 @@ impl ShelfEntry { } } } + +/// The procedurals whose pattern depends on the seed, worked out once +static SEEDED_PROCEDURALS: std::sync::LazyLock> = + std::sync::LazyLock::new(|| ProceduralKind::ALL.into_iter().filter(|kind| seed_changes(*kind)).collect()); + +/// Whether procedural `kind` samples differently under two seeds +fn seed_changes(kind: ProceduralKind) -> bool { + use texturecraft_engine::compose::pattern::{Coords, procedural}; + use texturecraft_engine::core::{Procedural, Projection}; + use texturecraft_engine::geom::glam::{Vec2, Vec3}; + + let sample = |seed: u32, i: usize| { + let uv = Vec2::new((i % SEED_PROBES) as f32 / SEED_PROBES as f32, (i / SEED_PROBES) as f32 / SEED_PROBES as f32) + SEED_PROBE_OFFSET; + procedural(&Procedural { seed, ..Procedural::new(kind) }, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y }) + }; + (0..SEED_PROBES * SEED_PROBES).any(|i| (sample(1, i) - sample(2, i)).abs() > SEED_TOLERANCE) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_seeded_procedurals_include_randomness() { + let seeded = &*SEEDED_PROCEDURALS; + assert!(seeded.contains(&ProceduralKind::Clouds), "{seeded:?}"); + assert!(!seeded.contains(&ProceduralKind::Checker), "{seeded:?}"); + } +} From 0ec76bb05e4f3042a11d650656c167d39eff68cf Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 02:38:21 +0000 Subject: [PATCH 09/22] Assets: procedurals and the project's images share one Textures tab --- crates/ui-egui/src/i18n/ar.rs | 1 - crates/ui-egui/src/i18n/de.rs | 1 - crates/ui-egui/src/i18n/es.rs | 1 - crates/ui-egui/src/i18n/fr.rs | 1 - crates/ui-egui/src/i18n/it.rs | 1 - crates/ui-egui/src/i18n/ja.rs | 1 - crates/ui-egui/src/i18n/ko.rs | 1 - crates/ui-egui/src/i18n/pt_br.rs | 1 - crates/ui-egui/src/i18n/zh_hans.rs | 1 - crates/ui-egui/src/shelf.rs | 16 +++++----------- crates/ui-egui/src/shelf_entry.rs | 2 +- 11 files changed, 6 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 68e95d5c..46a167de 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -615,7 +615,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "اضطراب الموضع"), ("Posterize", "تبسيط الألوان (Posterize)"), ("Press a key...", "اضغط على مفتاح..."), - ("Procedurals", "إجرائيات"), ("Project", "المشروع"), ("Project Configuration...", "تكوين المشروع..."), ("Project opened", "تم فتح المشروع"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index e0f15ab8..7ad71027 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -651,7 +651,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "Positionsstreuung"), ("Posterize", "Tontrennung"), ("Press a key...", "Taste drücken..."), - ("Procedurals", "Prozedurale"), ("Project", "Projekt"), ("Project Configuration...", "Projektkonfiguration..."), ("Project opened", "Projekt geöffnet"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 2bd6fc75..d1c35108 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -642,7 +642,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "Variación de posición"), ("Posterize", "Posterizar"), ("Press a key...", "Pulsa una tecla..."), - ("Procedurals", "Procedurales"), ("Project", "Proyecto"), ("Project Configuration...", "Configuración del proyecto..."), ("Project opened", "Proyecto abierto"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 73c6b199..182e71e8 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -657,7 +657,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "Variation de position"), ("Posterize", "Postérisation"), ("Press a key...", "Appuyez sur une touche..."), - ("Procedurals", "Procéduraux"), ("Project", "Projet"), ("Project Configuration...", "Configuration du projet..."), ("Project opened", "Projet ouvert"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index d785fb4a..1e243196 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -648,7 +648,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "Variazione posizione"), ("Posterize", "Posterizza"), ("Press a key...", "Premi un tasto..."), - ("Procedurals", "Procedurali"), ("Project", "Progetto"), ("Project Configuration...", "Configurazione progetto..."), ("Project opened", "Progetto aperto"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index c437a9a5..c705d024 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -633,7 +633,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "位置ジッター"), ("Posterize", "ポスタリゼーション"), ("Press a key...", "キーを押してください..."), - ("Procedurals", "プロシージャル"), ("Project", "プロジェクト"), ("Project Configuration...", "プロジェクト構成..."), ("Project opened", "プロジェクトを開きました"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index df46e2f1..20e114da 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -624,7 +624,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "위치 지터"), ("Posterize", "포스터화"), ("Press a key...", "키를 누르세요..."), - ("Procedurals", "프로시저럴"), ("Project", "프로젝트"), ("Project Configuration...", "프로젝트 구성..."), ("Project opened", "프로젝트를 열었습니다"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 87b0fc93..2de14047 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -639,7 +639,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "Variação de posição"), ("Posterize", "Posterizar"), ("Press a key...", "Pressione uma tecla..."), - ("Procedurals", "Procedurais"), ("Project", "Projeto"), ("Project Configuration...", "Configuração do projeto..."), ("Project opened", "Projeto aberto"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 3f1e89f7..c1925515 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -582,7 +582,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Position jitter", "位置抖动"), ("Posterize", "色调分离"), ("Press a key...", "请按下一个键..."), - ("Procedurals", "程序纹理"), ("Project", "项目"), ("Project Configuration...", "项目配置..."), ("Project opened", "项目已打开"), diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 33cac185..6543b230 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -1,9 +1,4 @@ -//! The asset shelf (the Assets dock tab): tabs (materials, smart materials, smart -//! masks, filters, alphas, procedurals, environments, textures), all built in and procedural. -//! Each tab is one grid sorted by name; a search shows the matches of every tab in one grid. -//! Materials (built in and saved), smart masks, filters, alphas -//! and textures drag onto the layer stack, a layer row, the viewport or the brush properties -//! ([`ShelfDrag`]); a texture dropped on the 3D view becomes a decal there, in the channel picked from a menu +//! The Assets panel: built-in, saved and project assets in one grid by type, library and search, dragged onto the layer stack, the views or the brush use egui::{Color32, RichText, Sense, Stroke, Ui, vec2}; use egui_phosphor::regular as ic; @@ -65,22 +60,21 @@ pub(crate) enum Tab { Filters, Brushes, Alphas, - Procedurals, - Environments, + /// Procedural patterns and the project's images Textures, + Environments, } /// The shelf tabs: icon and (English, translated where shown) name. -pub(crate) const TABS: [(Tab, &str, &str); 9] = [ +pub(crate) const TABS: [(Tab, &str, &str); 8] = [ (Tab::Materials, ic::SPHERE, "Materials"), (Tab::Smart, ic::STACK, "Smart materials"), (Tab::Masks, ic::CIRCLE_HALF, "Smart masks"), (Tab::Filters, ic::FUNNEL, "Filters"), (Tab::Brushes, ic::PAINT_BRUSH_BROAD, "Brushes"), (Tab::Alphas, ic::SHAPES, "Alphas"), - (Tab::Procedurals, ic::CHECKERBOARD, "Procedurals"), - (Tab::Environments, ic::SUN_HORIZON, "Environments"), (Tab::Textures, ic::IMAGE, "Textures"), + (Tab::Environments, ic::SUN_HORIZON, "Environments"), ]; /// A shelf asset: built in (by id), a saved smart material (file path) or an image resource. diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index cd147fde..0def726c 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -67,7 +67,7 @@ impl ShelfEntry { ShelfEntry::Filter(_) => Tab::Filters, ShelfEntry::Brush(_) | ShelfEntry::SavedBrush(_) => Tab::Brushes, ShelfEntry::Alpha(_) => Tab::Alphas, - ShelfEntry::Procedural(_) => Tab::Procedurals, + ShelfEntry::Procedural(_) => Tab::Textures, ShelfEntry::Environment(_) => Tab::Environments, ShelfEntry::Image(_) => Tab::Textures, } From 6077efb3adfde8c8117d3f0cd512173da25a9735 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 02:44:17 +0000 Subject: [PATCH 10/22] Assets: type tab row: a click on the picked type shows every type again, types with nothing matching greyed, one dropdown when narrow --- crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/shelf.rs | 34 +++++--------- crates/ui-egui/src/shelf_tabs.rs | 71 ++++++++++++++++++++++++++++++ crates/ui-egui/src/state.rs | 2 +- 13 files changed, 94 insertions(+), 23 deletions(-) create mode 100644 crates/ui-egui/src/shelf_tabs.rs diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 46a167de..e1f581d2 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1129,4 +1129,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Maximum decompressed project data. Increase this limit to open larger projects.", "الحد الأقصى لبيانات المشروع بعد فك الضغط. ارفع هذا الحد لفتح مشاريع أكبر.", ), + ("Filter by type", "تصفية حسب النوع"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 7ad71027..8064b888 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1175,4 +1175,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Maximum decompressed project data. Increase this limit to open larger projects.", "Maximale entpackte Projektdaten. Erhöhen Sie diesen Grenzwert, um größere Projekte zu öffnen.", ), + ("Filter by type", "Nach Typ filtern"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index d1c35108..8fb206d4 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1166,4 +1166,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Maximum decompressed project data. Increase this limit to open larger projects.", "Máximo de datos descomprimidos del proyecto. Aumenta este límite para abrir proyectos más grandes.", ), + ("Filter by type", "Filtrar por tipo"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 182e71e8..da1da090 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1190,4 +1190,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Maximum decompressed project data. Increase this limit to open larger projects.", "Volume maximal des données décompressées du projet. Augmentez cette limite pour ouvrir des projets plus volumineux.", ), + ("Filter by type", "Filtrer par type"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 1e243196..82437ae6 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1172,4 +1172,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Maximum decompressed project data. Increase this limit to open larger projects.", "Quantità massima di dati decompressi del progetto. Aumenta questo limite per aprire progetti più grandi.", ), + ("Filter by type", "Filtra per tipo"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index c705d024..92ceb5c1 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1157,4 +1157,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Maximum decompressed project data. Increase this limit to open larger projects.", "展開後のプロジェクトデータの上限です。大きなプロジェクトを開くには、この上限を引き上げてください。", ), + ("Filter by type", "種類で絞り込む"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 20e114da..6bb57959 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1142,4 +1142,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Maximum decompressed project data. Increase this limit to open larger projects.", "압축 해제된 프로젝트 데이터의 최대 크기입니다. 더 큰 프로젝트를 열려면 이 한도를 높이세요.", ), + ("Filter by type", "유형별 필터"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 2de14047..8ba06687 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1160,4 +1160,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Maximum decompressed project data. Increase this limit to open larger projects.", "Limite de dados descompactados do projeto. Aumente este limite para abrir projetos maiores.", ), + ("Filter by type", "Filtrar por tipo"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index c1925515..3842e2c7 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1085,4 +1085,5 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Max project size on open", "打开项目的大小上限"), ("Maximum decompressed project data. Increase this limit to open larger projects.", "解压后项目数据的大小上限。提高此限制以打开更大的项目。"), + ("Filter by type", "按类型筛选"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index cbfc80a8..5b87b257 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -51,6 +51,7 @@ mod running_bake; pub mod shelf; mod shelf_entry; pub mod shelf_preview; +mod shelf_tabs; mod soft_box; pub mod state; pub mod symmetry; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 6543b230..fd085ad8 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -15,7 +15,7 @@ use crate::shelf_entry::ShelfEntry; use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; use crate::thumbs::Thumbs; -use crate::widgets::{dnd_release, icon_button}; +use crate::widgets::dnd_release; /// A shelf tile's size and the gap between tiles in points: a 68 x 78 grid step, as in the reference const TILE_WIDTH: f32 = 66.0; @@ -65,7 +65,7 @@ pub(crate) enum Tab { Environments, } -/// The shelf tabs: icon and (English, translated where shown) name. +/// The shelf tabs: icon and (English, translated where shown) name pub(crate) const TABS: [(Tab, &str, &str); 8] = [ (Tab::Materials, ic::SPHERE, "Materials"), (Tab::Smart, ic::STACK, "Smart materials"), @@ -228,20 +228,12 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let ctx = ui.ctx().clone(); - let mut tab = app.ui.shelf_tab.min(TABS.len() - 1); let searching = !app.ui.shelf_filter.is_empty(); - - ui.horizontal_wrapped(|ui| { - let button_size = ui.spacing().interact_size.y; - ui.spacing_mut().item_spacing = vec2(2.0, 2.0); - for (i, (_, icon, label)) in TABS.iter().enumerate() { - if icon_button(ui, icon, tr(label), i == tab && !searching, button_size).clicked() { - tab = i; - app.ui.shelf_filter.clear(); - } - } - }); - app.ui.shelf_tab = tab; + let filter = app.ui.shelf_filter.to_lowercase(); + scan_brushes(app); + let matching: Vec = ShelfEntry::all(app).into_iter().filter(|entry| entry.matches(&filter)).collect(); + let counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); + crate::shelf_tabs::row(app, ui, &counts, |_, _, _| {}); ui.horizontal(|ui| { ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tokens.text_dim)); @@ -249,16 +241,14 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { }); ui.add_space(4.0); - let filter = app.ui.shelf_filter.to_lowercase(); - let shown_tab = TABS[tab].0; - scan_brushes(app); + let tab = app.ui.shelf_tab; + let shown_tab = TABS.get(tab).map(|(shown, _, _)| *shown); // Searching shows matches from every tab in one grid - let mut entries: Vec = - ShelfEntry::all(app).into_iter().filter(|entry| (searching || entry.tab() == shown_tab) && entry.matches(&filter)).collect(); + let mut entries: Vec = matching.into_iter().filter(|entry| searching || crate::shelf_tabs::shows(tab, entry.tab())).collect(); entries.sort_by_cached_key(|entry| entry.label().to_lowercase()); egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).show(ui, |ui| { - if !searching && shown_tab == Tab::Textures { + if !searching && shown_tab == Some(Tab::Textures) { import_images(app, ui, &ctx, entries.is_empty()); } tiles(ui, |ui| { @@ -267,7 +257,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { } }); - if searching || shown_tab == Tab::Smart { + if searching || shown_tab.is_none_or(|shown| shown == Tab::Smart) { library(app, ui, &filter); } }); diff --git a/crates/ui-egui/src/shelf_tabs.rs b/crates/ui-egui/src/shelf_tabs.rs new file mode 100644 index 00000000..4e2c3e07 --- /dev/null +++ b/crates/ui-egui/src/shelf_tabs.rs @@ -0,0 +1,71 @@ +//! The shelf's type row: one icon per type (none picked shows every type), greyed without matches, one dropdown when narrow + +use egui::{Ui, vec2}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::shelf::{TABS, Tab}; +use crate::widgets::{icon_button, icon_dropdown_button}; + +/// The gap between the row's icons in points +const ICON_GAP: f32 = 2.0; +/// The size of the dot that marks the collapsed row's dropdown while a type is picked, in points +const FILTER_DOT_RADIUS: f32 = 2.5; + +/// `app.ui.shelf_tab` while no type is picked: every type shows +pub(crate) const NO_TYPE: usize = TABS.len(); + +/// The row, then `trailing` at its right end; `counts[i]` is how many assets of `TABS[i]` match the search +pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui, counts: &[usize], trailing: impl FnOnce(&mut TextureCraftApp, &mut Ui, f32)) { + let size = ui.spacing().interact_size.y; + // The type icons and one icon after them + let row_width = (TABS.len() + 1) as f32 * (size + ICON_GAP); + let mut picked = app.ui.shelf_tab.min(NO_TYPE); + + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing = vec2(ICON_GAP, ICON_GAP); + if ui.available_width() >= row_width { + for (i, (_, icon, label)) in TABS.iter().enumerate() { + // The picked type stays clickable so it can be unpicked + let empty = i != picked && counts.get(i).is_none_or(|count| *count == 0); + if ui.add_enabled_ui(!empty, |ui| icon_button(ui, icon, tr(label), i == picked, size)).inner.clicked() { + picked = if i == picked { NO_TYPE } else { i }; + } + } + } else { + collapsed(ui, &mut picked, counts, size); + } + + let rest = ui.available_width() - size; + ui.add_space(rest.max(0.0)); + trailing(app, ui, size); + }); + app.ui.shelf_tab = picked; +} + +/// One dropdown listing the types, dotted while one is picked +fn collapsed(ui: &mut Ui, picked: &mut usize, counts: &[usize], size: f32) { + let filtering = *picked != NO_TYPE; + let response = icon_dropdown_button(ui, egui_phosphor::regular::FUNNEL_SIMPLE, tr("Filter by type"), filtering, size); + let response = response.on_hover_text(tr("Filter by type")); + if filtering { + let tk = crate::theme::Tokens::get(ui.ctx()); + let dot = response.rect.left_top() + vec2(size - FILTER_DOT_RADIUS, FILTER_DOT_RADIUS); + ui.painter().circle_filled(dot, FILTER_DOT_RADIUS, tk.accent); + } + + egui::Popup::menu(&response).show(|ui| { + for (i, (_, icon, label)) in TABS.iter().enumerate() { + let empty = i != *picked && counts.get(i).is_none_or(|count| *count == 0); + if ui.add_enabled(!empty, egui::Button::selectable(i == *picked, format!("{icon} {}", tr(label)))).clicked() { + *picked = if i == *picked { NO_TYPE } else { i }; + ui.close(); + } + } + }); +} + +/// Whether `tab` (an index into [`TABS`], or [`NO_TYPE`]) shows assets of type `kind` +pub(crate) fn shows(tab: usize, kind: Tab) -> bool { + TABS.get(tab).is_none_or(|(shown, _, _)| *shown == kind) +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index e52a2907..2c03dc45 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -297,7 +297,7 @@ pub struct UiState { /// Channel whose blending the layer rows show. pub layer_channel: Channel, pub shelf_filter: String, - /// The asset shelf's open tab. + /// The asset shelf's picked type: an index into the shelf's types, or past them for every type #[serde(default)] pub shelf_tab: usize, pub props_tab: PropsTab, From a401d36f9ccd64b5131280687304275ecd74b5ce Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 02:56:58 +0000 Subject: [PATCH 11/22] Assets: search above the tabs, with a clear button; the search narrows the picked tab and a tab click keeps it --- crates/ui-egui/src/i18n/ar.rs | 1 - crates/ui-egui/src/i18n/de.rs | 1 - crates/ui-egui/src/i18n/es.rs | 1 - crates/ui-egui/src/i18n/fr.rs | 1 - crates/ui-egui/src/i18n/it.rs | 1 - crates/ui-egui/src/i18n/ja.rs | 1 - crates/ui-egui/src/i18n/ko.rs | 1 - crates/ui-egui/src/i18n/pt_br.rs | 1 - crates/ui-egui/src/i18n/zh_hans.rs | 1 - crates/ui-egui/src/shelf.rs | 29 ++++++++++++++++++----------- 10 files changed, 18 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index e1f581d2..de036796 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -696,7 +696,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screen", "شاشة (Screen)"), ("Screenshot of the viewport", "لقطة شاشة لمنفذ العرض"), ("Search", "بحث"), - ("Search all assets", "البحث في جميع الأصول"), ("Search commands or keys", "البحث في الأوامر أو المفاتيح"), ("Seed", "البذرة العشوائية (Seed)"), ("Select a layer", "تحديد طبقة"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 8064b888..dab5a9fc 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -732,7 +732,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screen", "Negativ multiplizieren"), ("Screenshot of the viewport", "Screenshot des Ansichtsfensters"), ("Search", "Suchen"), - ("Search all assets", "Alle Assets durchsuchen"), ("Search commands or keys", "Befehle oder Tasten suchen"), ("Seed", "Startwert"), ("Select a layer", "Ebene auswählen"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 8fb206d4..b7869bbf 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -723,7 +723,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screen", "Trama"), ("Screenshot of the viewport", "Captura de la ventana gráfica"), ("Search", "Buscar"), - ("Search all assets", "Buscar en todos los recursos"), ("Search commands or keys", "Buscar comandos o teclas"), ("Seed", "Semilla"), ("Select a layer", "Selecciona una capa"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index da1da090..84e49d0c 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -741,7 +741,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screen", "Superposition"), ("Screenshot of the viewport", "Capture de la fenêtre d'affichage"), ("Search", "Rechercher"), - ("Search all assets", "Rechercher dans toutes les ressources"), ("Search commands or keys", "Rechercher des commandes ou des touches"), ("Seed", "Graine"), ("Select a layer", "Sélectionnez un calque"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 82437ae6..44047bf9 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -729,7 +729,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screen", "Scolora"), ("Screenshot of the viewport", "Screenshot della viewport"), ("Search", "Cerca"), - ("Search all assets", "Cerca in tutte le risorse"), ("Search commands or keys", "Cerca comandi o tasti"), ("Seed", "Seme"), ("Select a layer", "Seleziona un livello"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 92ceb5c1..c2b07952 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -714,7 +714,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screen", "スクリーン"), ("Screenshot of the viewport", "ビューポートのスクリーンショット"), ("Search", "検索"), - ("Search all assets", "すべてのアセットを検索"), ("Search commands or keys", "コマンドまたはキーを検索"), ("Seed", "シード"), ("Select a layer", "レイヤーを選択"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 6bb57959..27aab276 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -705,7 +705,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screen", "스크린"), ("Screenshot of the viewport", "뷰포트 스크린샷"), ("Search", "검색"), - ("Search all assets", "모든 에셋 검색"), ("Search commands or keys", "명령 또는 키 검색"), ("Seed", "시드"), ("Select a layer", "레이어를 선택하세요"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 8ba06687..7ad61770 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -720,7 +720,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screen", "Tela"), ("Screenshot of the viewport", "Captura de tela da viewport"), ("Search", "Pesquisar"), - ("Search all assets", "Pesquisar em todos os recursos"), ("Search commands or keys", "Pesquisar comandos ou teclas"), ("Seed", "Semente"), ("Select a layer", "Selecione uma camada"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 3842e2c7..4e407b12 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -663,7 +663,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screen", "滤色"), ("Screenshot of the viewport", "视口截图"), ("Search", "搜索"), - ("Search all assets", "搜索所有资产"), ("Search commands or keys", "搜索命令或按键"), ("Seed", "随机种子"), ("Select a layer", "选择图层"), diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index fd085ad8..74a4ad83 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -226,29 +226,22 @@ 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 tokens = Tokens::get(ui.ctx()); let ctx = ui.ctx().clone(); - let searching = !app.ui.shelf_filter.is_empty(); let filter = app.ui.shelf_filter.to_lowercase(); scan_brushes(app); let matching: Vec = ShelfEntry::all(app).into_iter().filter(|entry| entry.matches(&filter)).collect(); let counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); + search_field(app, ui); crate::shelf_tabs::row(app, ui, &counts, |_, _, _| {}); - - ui.horizontal(|ui| { - ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tokens.text_dim)); - ui.add(egui::TextEdit::singleline(&mut app.ui.shelf_filter).hint_text(tr("Search all assets")).desired_width(f32::INFINITY)); - }); ui.add_space(4.0); let tab = app.ui.shelf_tab; let shown_tab = TABS.get(tab).map(|(shown, _, _)| *shown); - // Searching shows matches from every tab in one grid - let mut entries: Vec = matching.into_iter().filter(|entry| searching || crate::shelf_tabs::shows(tab, entry.tab())).collect(); + 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()); egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).show(ui, |ui| { - if !searching && shown_tab == Some(Tab::Textures) { + if filter.is_empty() && shown_tab == Some(Tab::Textures) { import_images(app, ui, &ctx, entries.is_empty()); } tiles(ui, |ui| { @@ -257,13 +250,27 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { } }); - if searching || shown_tab.is_none_or(|shown| shown == Tab::Smart) { + if shown_tab.is_none_or(|shown| shown == Tab::Smart) { library(app, ui, &filter); } }); drag_preview(&ctx); } +/// The search field: a live filter on names (and categories) with a clear button while it has text +fn search_field(app: &mut TextureCraftApp, ui: &mut Ui) { + let tk = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tk.text_dim)); + let clear_width = if app.ui.shelf_filter.is_empty() { 0.0 } else { ui.spacing().interact_size.y + ui.spacing().item_spacing.x }; + let field = egui::TextEdit::singleline(&mut app.ui.shelf_filter).hint_text(tr("Search")).desired_width(ui.available_width() - clear_width); + ui.add(field); + if !app.ui.shelf_filter.is_empty() && ui.add(egui::Button::new(ic::X).frame(false)).on_hover_text(tr("Clear")).clicked() { + app.ui.shelf_filter.clear(); + } + }); +} + /// The dragged asset's name next to the pointer. fn drag_preview(ctx: &egui::Context) { let tk = Tokens::get(ctx); From 3277ef725324fb6138afe11c79da715fcd4fe23d Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 03:05:16 +0000 Subject: [PATCH 12/22] Assets: a library breadcrumb above the search (All libraries, Project, Starter assets, Your assets, then folders) --- crates/ui-egui/src/i18n/ar.rs | 4 ++ crates/ui-egui/src/i18n/de.rs | 4 ++ crates/ui-egui/src/i18n/es.rs | 4 ++ crates/ui-egui/src/i18n/fr.rs | 4 ++ crates/ui-egui/src/i18n/it.rs | 4 ++ crates/ui-egui/src/i18n/ja.rs | 4 ++ crates/ui-egui/src/i18n/ko.rs | 4 ++ crates/ui-egui/src/i18n/pt_br.rs | 4 ++ crates/ui-egui/src/i18n/zh_hans.rs | 4 ++ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/shelf.rs | 16 ++++- crates/ui-egui/src/shelf_entry.rs | 30 ++++++++++ crates/ui-egui/src/shelf_folders.rs | 92 +++++++++++++++++++++++++++++ crates/ui-egui/src/state.rs | 4 ++ 14 files changed, 177 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/src/shelf_folders.rs diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index de036796..65caff11 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1129,4 +1129,8 @@ pub const TABLE: &[(&str, &str)] = &[ "الحد الأقصى لبيانات المشروع بعد فك الضغط. ارفع هذا الحد لفتح مشاريع أكبر.", ), ("Filter by type", "تصفية حسب النوع"), + ("All libraries", "كل المكتبات"), + ("Browse folders", "تصفح المجلدات"), + ("Starter assets", "الأصول المضمّنة"), + ("Your assets", "أصولك"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index dab5a9fc..477792d7 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1175,4 +1175,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Maximale entpackte Projektdaten. Erhöhen Sie diesen Grenzwert, um größere Projekte zu öffnen.", ), ("Filter by type", "Nach Typ filtern"), + ("All libraries", "Alle Bibliotheken"), + ("Browse folders", "Ordner durchsuchen"), + ("Starter assets", "Mitgelieferte Assets"), + ("Your assets", "Eigene Assets"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index b7869bbf..639d4dbc 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1166,4 +1166,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Máximo de datos descomprimidos del proyecto. Aumenta este límite para abrir proyectos más grandes.", ), ("Filter by type", "Filtrar por tipo"), + ("All libraries", "Todas las bibliotecas"), + ("Browse folders", "Explorar carpetas"), + ("Starter assets", "Recursos incluidos"), + ("Your assets", "Tus recursos"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 84e49d0c..00ef31a2 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1190,4 +1190,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Volume maximal des données décompressées du projet. Augmentez cette limite pour ouvrir des projets plus volumineux.", ), ("Filter by type", "Filtrer par type"), + ("All libraries", "Toutes les bibliothèques"), + ("Browse folders", "Parcourir les dossiers"), + ("Starter assets", "Ressources fournies"), + ("Your assets", "Vos ressources"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 44047bf9..9a7831d7 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1172,4 +1172,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Quantità massima di dati decompressi del progetto. Aumenta questo limite per aprire progetti più grandi.", ), ("Filter by type", "Filtra per tipo"), + ("All libraries", "Tutte le librerie"), + ("Browse folders", "Sfoglia cartelle"), + ("Starter assets", "Risorse incluse"), + ("Your assets", "Le tue risorse"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index c2b07952..2e86d12b 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1157,4 +1157,8 @@ pub const TABLE: &[(&str, &str)] = &[ "展開後のプロジェクトデータの上限です。大きなプロジェクトを開くには、この上限を引き上げてください。", ), ("Filter by type", "種類で絞り込む"), + ("All libraries", "すべてのライブラリ"), + ("Browse folders", "フォルダーを参照"), + ("Starter assets", "付属アセット"), + ("Your assets", "マイアセット"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 27aab276..8c4b29f1 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1142,4 +1142,8 @@ pub const TABLE: &[(&str, &str)] = &[ "압축 해제된 프로젝트 데이터의 최대 크기입니다. 더 큰 프로젝트를 열려면 이 한도를 높이세요.", ), ("Filter by type", "유형별 필터"), + ("All libraries", "모든 라이브러리"), + ("Browse folders", "폴더 찾아보기"), + ("Starter assets", "기본 에셋"), + ("Your assets", "내 에셋"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7ad61770..e13f812d 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1160,4 +1160,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Limite de dados descompactados do projeto. Aumente este limite para abrir projetos maiores.", ), ("Filter by type", "Filtrar por tipo"), + ("All libraries", "Todas as bibliotecas"), + ("Browse folders", "Navegar pelas pastas"), + ("Starter assets", "Recursos incluídos"), + ("Your assets", "Seus recursos"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 4e407b12..4160195e 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1085,4 +1085,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Max project size on open", "打开项目的大小上限"), ("Maximum decompressed project data. Increase this limit to open larger projects.", "解压后项目数据的大小上限。提高此限制以打开更大的项目。"), ("Filter by type", "按类型筛选"), + ("All libraries", "所有库"), + ("Browse folders", "浏览文件夹"), + ("Starter assets", "内置资源"), + ("Your assets", "我的资源"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b87b257..51848cdb 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -50,6 +50,7 @@ mod resource_picker_item; mod running_bake; pub mod shelf; mod shelf_entry; +mod shelf_folders; pub mod shelf_preview; mod shelf_tabs; mod soft_box; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 74a4ad83..d4648c97 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -229,8 +229,19 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let ctx = ui.ctx().clone(); let filter = app.ui.shelf_filter.to_lowercase(); scan_brushes(app); - let matching: Vec = ShelfEntry::all(app).into_iter().filter(|entry| entry.matches(&filter)).collect(); + let all = ShelfEntry::all(app); + let paths = crate::shelf_folders::with_every_library(crate::shelf_folders::paths(&all)); + + // A folder that is gone (its last image removed) shows everything again + if !paths.iter().any(|path| path.starts_with(&app.ui.shelf_path)) { + app.ui.shelf_path.clear(); + } + + let folder = app.ui.shelf_path.clone(); + let matching: Vec = all.into_iter().filter(|entry| entry.in_folder(&folder) && entry.matches(&filter)).collect(); let counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); + + crate::shelf_folders::breadcrumb(app, ui, &paths); search_field(app, ui); crate::shelf_tabs::row(app, ui, &counts, |_, _, _| {}); ui.add_space(4.0); @@ -250,7 +261,8 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { } }); - if shown_tab.is_none_or(|shown| shown == Tab::Smart) { + let in_user_library = folder.first().is_none_or(|library| library == crate::shelf_entry::USER); + if in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Smart) { library(app, ui, &filter); } }); diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index 0def726c..e9bbcbec 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -25,6 +25,13 @@ const SEED_PROBE_OFFSET: f32 = 0.13; /// A smaller difference between the two seeds' samples is rounding const SEED_TOLERANCE: f32 = 1e-4; +/// The libraries' ids: the open project's images, the built-in assets, the user's saved assets +pub(crate) const PROJECT: &str = "project"; +pub(crate) const STARTER: &str = "starter"; +pub(crate) const USER: &str = "user"; +/// The libraries in the picker's order: id and (English, translated where shown) name +pub(crate) const LIBRARIES: [(&str, &str); 3] = [(PROJECT, "Project"), (STARTER, "Starter assets"), (USER, "Your assets")]; + /// A shelf tile's asset #[derive(Clone)] pub(crate) enum ShelfEntry { @@ -88,6 +95,29 @@ impl ShelfEntry { } } + /// Where the asset lives: its library id ([`LIBRARIES`]), its type's folder, then its category if it has one (names in English, shown through `tr`) + pub(crate) fn path(&self) -> Vec<&str> { + let (library, folder, category) = match self { + ShelfEntry::Material(material) if material.smart => (STARTER, "Smart materials", Some(material.category)), + ShelfEntry::Material(material) => (STARTER, "Materials", Some(material.category)), + ShelfEntry::SmartMask(_) => (STARTER, "Smart masks", None), + ShelfEntry::Filter(filter) => (STARTER, "Filters", Some(filter.group)), + ShelfEntry::Brush(preset) => (STARTER, "Brushes", Some(preset.category)), + ShelfEntry::SavedBrush(_) => (USER, "Brushes", None), + ShelfEntry::Alpha(alpha) => (STARTER, "Alphas", Some(alpha.category)), + ShelfEntry::Procedural(_) => (STARTER, "Procedurals", None), + ShelfEntry::Environment(_) => (STARTER, "Environments", None), + ShelfEntry::Image(_) => (PROJECT, "Textures", None), + }; + [library, folder].into_iter().chain(category).collect() + } + + /// Whether the asset is in folder `path` (a library id, then folder names) or below it + pub(crate) fn in_folder(&self, path: &[String]) -> bool { + let own = self.path(); + path.len() <= own.len() && path.iter().zip(own).all(|(wanted, have)| wanted == have) + } + /// 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_folders.rs b/crates/ui-egui/src/shelf_folders.rs new file mode 100644 index 00000000..de8c2144 --- /dev/null +++ b/crates/ui-egui/src/shelf_folders.rs @@ -0,0 +1,92 @@ +//! The shelf's library folders ([`ShelfEntry::path`]) for the breadcrumb above the search and the Filter by path tree + +use egui::{RichText, Ui}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::shelf_entry::{LIBRARIES, ShelfEntry}; +use crate::theme::Tokens; +use crate::widgets::icon_button; + +/// The breadcrumb arrows' size relative to an icon button +const ARROW_SCALE: f32 = 0.8; + +/// The folder paths of `entries`, each a library id then folder names +pub(crate) fn paths(entries: &[ShelfEntry]) -> Vec> { + let mut paths: Vec> = entries.iter().map(|entry| entry.path().into_iter().map(str::to_string).collect()).collect(); + paths.sort(); + paths.dedup(); + paths +} + +/// `paths` and every library, even one with nothing in it (the picker always lists them all) +pub(crate) fn with_every_library(mut paths: Vec>) -> Vec> { + paths.extend(LIBRARIES.iter().map(|(id, _)| vec![id.to_string()])); + paths.sort(); + paths.dedup(); + paths +} + +/// The folders right below `prefix` (libraries in their usual order, folders by name) +pub(crate) fn children(paths: &[Vec], prefix: &[String]) -> Vec { + let mut out: Vec = Vec::new(); + for path in paths.iter().filter(|path| path.len() > prefix.len() && path.starts_with(prefix)) { + if let Some(next) = path.get(prefix.len()) + && !out.contains(next) + { + out.push(next.clone()); + } + } + if prefix.is_empty() { + out.sort_by_key(|library| LIBRARIES.iter().position(|(id, _)| id == library)); + } + out +} + +/// A folder's shown name: libraries by their name, folders (type and category names) translated +pub(crate) fn name(level: usize, segment: &str) -> &str { + match LIBRARIES.iter().find(|(id, _)| *id == segment) { + Some((_, library)) if level == 0 => tr(library), + _ => tr(segment), + } +} + +/// "› All libraries › …": each arrow lists the folders at its level, the names are plain text, a last arrow lists the folders inside +pub(crate) fn breadcrumb(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec]) { + let tk = Tokens::get(ui.ctx()); + let size = ui.spacing().interact_size.y * ARROW_SCALE; + let mut picked: Option> = None; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = ui.spacing().item_spacing.x * 0.5; + let path = app.ui.shelf_path.clone(); + for level in 0..=path.len() { + let options = children(paths, &path[..level]); + if level > 0 && options.is_empty() { + break; + } + + let current = path.get(level); + let response = icon_button(ui, egui_phosphor::regular::CARET_RIGHT, tr("Browse folders"), false, size); + egui::Popup::menu(&response).show(|ui| { + if level == 0 && ui.selectable_label(current.is_none(), tr("All libraries")).clicked() { + picked = Some(Vec::new()); + } + for option in &options { + if ui.selectable_label(current == Some(option), name(level, option)).clicked() { + picked = Some(path[..level].iter().cloned().chain([option.clone()]).collect()); + } + } + }); + + let shown = match current { + Some(segment) => name(level, segment), + None if level == 0 => tr("All libraries"), + None => continue, + }; + ui.label(RichText::new(shown).strong().color(tk.text_strong)); + } + }); + if let Some(path) = picked { + app.ui.shelf_path = path; + } +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 2c03dc45..f9b75653 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -300,6 +300,9 @@ pub struct UiState { /// The asset shelf's picked type: an index into the shelf's types, or past them for every type #[serde(default)] pub shelf_tab: usize, + /// The asset shelf's library folder: a library id, then folder names (empty: all libraries) + #[serde(default)] + pub shelf_path: Vec, pub props_tab: PropsTab, #[serde(default)] pub text: TextUi, @@ -390,6 +393,7 @@ impl Default for UiState { layer_channel: Channel::BaseColor, shelf_filter: String::new(), shelf_tab: 0, + shelf_path: Vec::new(), props_tab: PropsTab::Brush, text: TextUi::default(), rename: None, From 8223882c99e17d53db0b4ede190df07d4a5791be Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 03:07:29 +0000 Subject: [PATCH 13/22] Assets: a bottom toolbar with refresh, reset query and import; the Textures tab's import button moves there --- crates/ui-egui/src/brush_preset_save.rs | 2 + crates/ui-egui/src/i18n/ar.rs | 3 +- crates/ui-egui/src/i18n/de.rs | 3 +- crates/ui-egui/src/i18n/es.rs | 3 +- crates/ui-egui/src/i18n/fr.rs | 3 +- crates/ui-egui/src/i18n/it.rs | 3 +- crates/ui-egui/src/i18n/ja.rs | 3 +- crates/ui-egui/src/i18n/ko.rs | 3 +- crates/ui-egui/src/i18n/pt_br.rs | 3 +- crates/ui-egui/src/i18n/zh_hans.rs | 3 +- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/shelf.rs | 40 +++++++++----------- crates/ui-egui/src/shelf_toolbar.rs | 49 +++++++++++++++++++++++++ crates/ui-egui/src/thumbs.rs | 10 +++++ 14 files changed, 97 insertions(+), 32 deletions(-) create mode 100644 crates/ui-egui/src/shelf_toolbar.rs diff --git a/crates/ui-egui/src/brush_preset_save.rs b/crates/ui-egui/src/brush_preset_save.rs index 7bc0faaa..1372e0e5 100644 --- a/crates/ui-egui/src/brush_preset_save.rs +++ b/crates/ui-egui/src/brush_preset_save.rs @@ -25,7 +25,9 @@ pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui) { let _ = std::fs::create_dir_all(&dir); if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_some() { new_name.clear(); + // Saving over a preset keeps its file name, so its tile must redraw app.brushes = None; + app.thumbs.forget_saved_files(); } } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 65caff11..8b575955 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -412,7 +412,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import HDR...", "استيراد HDR..."), ("Import a template (.json)", "استيراد قالب (.json)"), ("Import an image (File > Import resources) to project it onto the mesh.", "استورد صورة (ملف > استيراد الموارد) لإسقاطها على المجسم."), - ("Import images to use them in fills and masks", "استورد الصور لاستخدامها في التعبئة والأقنعة"), ("Import resources...", "استيراد الموارد..."), ("Import MaterialX material...", "استيراد مادة MaterialX..."), ("MaterialX materials", "مواد MaterialX"), @@ -1133,4 +1132,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Browse folders", "تصفح المجلدات"), ("Starter assets", "الأصول المضمّنة"), ("Your assets", "أصولك"), + ("Reset query", "إعادة تعيين الاستعلام"), + ("Refresh", "تحديث"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 477792d7..c06ab830 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -439,7 +439,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Import an image (File > Import resources) to project it onto the mesh.", "Ein Bild importieren (Datei > Ressourcen importieren), um es auf das Mesh zu projizieren.", ), - ("Import images to use them in fills and masks", "Bilder importieren, um sie in Füllungen und Masken zu verwenden"), ("Import resources...", "Ressourcen importieren..."), ("Import MaterialX material...", "MaterialX-Material importieren..."), ("MaterialX materials", "MaterialX-Materialien"), @@ -1179,4 +1178,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Browse folders", "Ordner durchsuchen"), ("Starter assets", "Mitgelieferte Assets"), ("Your assets", "Eigene Assets"), + ("Reset query", "Abfrage zurücksetzen"), + ("Refresh", "Aktualisieren"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 639d4dbc..587d098a 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -430,7 +430,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Import an image (File > Import resources) to project it onto the mesh.", "Importa una imagen (Archivo > Importar recursos) para proyectarla sobre la malla.", ), - ("Import images to use them in fills and masks", "Importar imágenes para usarlas en rellenos y máscaras"), ("Import resources...", "Importar recursos..."), ("Import MaterialX material...", "Importar material MaterialX..."), ("MaterialX materials", "Materiales MaterialX"), @@ -1170,4 +1169,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Browse folders", "Explorar carpetas"), ("Starter assets", "Recursos incluidos"), ("Your assets", "Tus recursos"), + ("Reset query", "Restablecer consulta"), + ("Refresh", "Actualizar"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 00ef31a2..62540c43 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -442,7 +442,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Import an image (File > Import resources) to project it onto the mesh.", "Importez une image (Fichier > Importer des ressources) pour la projeter sur le maillage.", ), - ("Import images to use them in fills and masks", "Importez des images pour les utiliser dans les remplissages et les masques"), ("Import resources...", "Importer des ressources..."), ("Import MaterialX material...", "Importer un matériau MaterialX..."), ("MaterialX materials", "Matériaux MaterialX"), @@ -1194,4 +1193,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Browse folders", "Parcourir les dossiers"), ("Starter assets", "Ressources fournies"), ("Your assets", "Vos ressources"), + ("Reset query", "Réinitialiser la requête"), + ("Refresh", "Actualiser"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 9a7831d7..6923de3f 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -433,7 +433,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import HDR...", "Importa HDR..."), ("Import a template (.json)", "Importa un modello (.json)"), ("Import an image (File > Import resources) to project it onto the mesh.", "Importa un'immagine (File > Importa risorse) per proiettarla sulla mesh."), - ("Import images to use them in fills and masks", "Importa immagini per usarle in riempimenti e maschere"), ("Import resources...", "Importa risorse..."), ("Import MaterialX material...", "Importa materiale MaterialX..."), ("MaterialX materials", "Materiali MaterialX"), @@ -1176,4 +1175,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Browse folders", "Sfoglia cartelle"), ("Starter assets", "Risorse incluse"), ("Your assets", "Le tue risorse"), + ("Reset query", "Reimposta query"), + ("Refresh", "Aggiorna"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 2e86d12b..58dcfdee 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -424,7 +424,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Import an image (File > Import resources) to project it onto the mesh.", "画像をインポートすると (ファイル > リソースをインポート)、メッシュに投影できます。", ), - ("Import images to use them in fills and masks", "画像をインポートして塗りつぶしやマスクで使用"), ("Import resources...", "リソースをインポート..."), ("Import MaterialX material...", "MaterialX マテリアルをインポート..."), ("MaterialX materials", "MaterialX マテリアル"), @@ -1161,4 +1160,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Browse folders", "フォルダーを参照"), ("Starter assets", "付属アセット"), ("Your assets", "マイアセット"), + ("Reset query", "クエリをリセット"), + ("Refresh", "更新"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 8c4b29f1..2905d226 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -418,7 +418,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import HDR...", "HDR 가져오기..."), ("Import a template (.json)", "템플릿을 가져옵니다 (.json)"), ("Import an image (File > Import resources) to project it onto the mesh.", "메시에 투영할 이미지를 가져오세요 (파일 > 리소스 가져오기)."), - ("Import images to use them in fills and masks", "채우기와 마스크에 사용할 이미지를 가져옵니다"), ("Import resources...", "리소스 가져오기..."), ("Import MaterialX material...", "MaterialX 머티리얼 가져오기..."), ("MaterialX materials", "MaterialX 머티리얼"), @@ -1146,4 +1145,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Browse folders", "폴더 찾아보기"), ("Starter assets", "기본 에셋"), ("Your assets", "내 에셋"), + ("Reset query", "쿼리 초기화"), + ("Refresh", "새로 고침"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index e13f812d..e6edc0f4 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -427,7 +427,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import HDR...", "Importar HDR..."), ("Import a template (.json)", "Importar um modelo (.json)"), ("Import an image (File > Import resources) to project it onto the mesh.", "Importe uma imagem (Arquivo > Importar recursos) para projetá-la na malha."), - ("Import images to use them in fills and masks", "Importe imagens para usá-las em preenchimentos e máscaras"), ("Import resources...", "Importar recursos..."), ("Import MaterialX material...", "Importar material MaterialX..."), ("MaterialX materials", "Materiais MaterialX"), @@ -1164,4 +1163,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Browse folders", "Navegar pelas pastas"), ("Starter assets", "Recursos incluídos"), ("Your assets", "Seus recursos"), + ("Reset query", "Redefinir consulta"), + ("Refresh", "Atualizar"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 4160195e..5e07fb3b 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -382,7 +382,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import HDR...", "导入 HDR..."), ("Import a template (.json)", "导入模板(.json)"), ("Import an image (File > Import resources) to project it onto the mesh.", "导入图像(文件 > 导入资源)以将其投影到网格上。"), - ("Import images to use them in fills and masks", "导入图像以在填充和遮罩中使用"), ("Import resources...", "导入资源..."), ("Import MaterialX material...", "导入 MaterialX 材质..."), ("MaterialX materials", "MaterialX 材质"), @@ -1089,4 +1088,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Browse folders", "浏览文件夹"), ("Starter assets", "内置资源"), ("Your assets", "我的资源"), + ("Reset query", "重置查询"), + ("Refresh", "刷新"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 51848cdb..e1d42983 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -53,6 +53,7 @@ mod shelf_entry; mod shelf_folders; pub mod shelf_preview; mod shelf_tabs; +mod shelf_toolbar; mod soft_box; pub mod state; pub mod symmetry; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index d4648c97..ebd4cc0d 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -251,21 +251,26 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { 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()); - egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).show(ui, |ui| { - if filter.is_empty() && shown_tab == Some(Tab::Textures) { - import_images(app, ui, &ctx, entries.is_empty()); - } - tiles(ui, |ui| { - for entry in &entries { - entry_tile(app, ui, &ctx, entry); + // 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(); + let toolbar_top = (area.bottom() - crate::shelf_toolbar::height(ui)).max(area.top()); + let grid_rect = egui::Rect::from_min_max(area.min, egui::pos2(area.right(), toolbar_top)); + let toolbar_rect = egui::Rect::from_min_max(egui::pos2(area.left(), toolbar_top), area.max); + ui.scope_builder(egui::UiBuilder::new().max_rect(grid_rect), |ui| { + egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).max_height(grid_rect.height()).show(ui, |ui| { + tiles(ui, |ui| { + for entry in &entries { + entry_tile(app, ui, &ctx, entry); + } + }); + + let in_user_library = folder.first().is_none_or(|library| library == crate::shelf_entry::USER); + if in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Smart) { + library(app, ui, &filter); } }); - - let in_user_library = folder.first().is_none_or(|library| library == crate::shelf_entry::USER); - if in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Smart) { - library(app, ui, &filter); - } }); + ui.scope_builder(egui::UiBuilder::new().max_rect(toolbar_rect), |ui| crate::shelf_toolbar::show(app, ui)); drag_preview(&ctx); } @@ -392,17 +397,6 @@ fn scan_brushes(app: &mut TextureCraftApp) { #[cfg(target_arch = "wasm32")] fn scan_brushes(_: &mut TextureCraftApp) {} -/// The Textures tab's import button, and a hint while the project has no images -fn import_images(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, empty: bool) { - let tk = Tokens::get(ctx); - if ui.small_button(tr("Import...")).clicked() { - crate::menus::invoke(app, ctx, "resource.import"); - } - if empty { - ui.label(RichText::new(tr("Import images to use them in fills and masks")).size(10.0).color(tk.text_dim)); - } -} - /// The tile of `entry`: a click applies it, an image resource has a context menu fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry) { // An image removed this frame has nothing to show diff --git a/crates/ui-egui/src/shelf_toolbar.rs b/crates/ui-egui/src/shelf_toolbar.rs new file mode 100644 index 00000000..93a5afcd --- /dev/null +++ b/crates/ui-egui/src/shelf_toolbar.rs @@ -0,0 +1,49 @@ +//! The shelf's bottom toolbar: refresh, reset query and import on the right + +use egui::Ui; +use egui_phosphor::regular as ic; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::widgets::icon_button; + +/// The gap above the toolbar in points +const GAP_ABOVE: f32 = 4.0; + +/// The toolbar's height for a `ui` (one icon button and the gap above it) +pub(crate) fn height(ui: &Ui) -> f32 { + ui.spacing().interact_size.y + GAP_ABOVE +} + +/// The toolbar +pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { + let size = ui.spacing().interact_size.y; + ui.add_space(GAP_ABOVE); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |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::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); + } + }); + }); +} + +/// Show every asset again: no search, no type picked, all libraries +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(); +} + +/// Read the user's saved assets from disk again and redraw their thumbnails +fn refresh(app: &mut TextureCraftApp) { + app.library = None; + app.brushes = None; + app.thumbs.forget_saved_files(); +} diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index a6bd93cb..4c7bab4b 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -26,6 +26,8 @@ const PROCEDURAL_PX: usize = 64; const SWATCH_PX: usize = 64; /// Image resource preview size in pixels const IMAGE_PX: usize = 64; +/// The [`ShelfPreview::key`] prefix of the user's saved files +const SAVED_FILE_KEY_PREFIX: &str = "saved-"; /// Big hover previews kept at most (the least recently shown go first) const BIG_PREVIEWS_KEPT: usize = 32; @@ -192,6 +194,14 @@ impl Thumbs { } } + /// Drop the thumbnails and hover previews of the user's saved files, which may have changed on disk + pub fn forget_saved_files(&mut self) { + let current = |key: &String| !key.starts_with(SAVED_FILE_KEY_PREFIX); + self.shelf.retain(|key, _| current(key)); + self.rendered.retain(|key, _| current(key)); + self.big_shown.retain(current); + } + /// Smart mask thumbnail; None until the worker returns it pub fn smart_mask(&mut self, ctx: &egui::Context, id: &'static str) -> Option { self.worker_rendered(ctx, ShelfPreview::SmartMask(id), SPHERE_PX, false) From 77cf7a8d33b948de8ed98dc81e85ae31c324ee97 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 03:11:21 +0000 Subject: [PATCH 14/22] Assets: a Saved searches pane: All, then saved queries (search, tab and folder), saved from its header --- crates/ui-egui/src/i18n/ar.rs | 3 + crates/ui-egui/src/i18n/de.rs | 3 + crates/ui-egui/src/i18n/es.rs | 3 + crates/ui-egui/src/i18n/fr.rs | 3 + crates/ui-egui/src/i18n/it.rs | 3 + crates/ui-egui/src/i18n/ja.rs | 3 + crates/ui-egui/src/i18n/ko.rs | 3 + crates/ui-egui/src/i18n/pt_br.rs | 3 + crates/ui-egui/src/i18n/zh_hans.rs | 3 + crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/saved_search.rs | 12 ++++ crates/ui-egui/src/shelf.rs | 37 ++++++---- crates/ui-egui/src/shelf_panes.rs | 102 ++++++++++++++++++++++++++++ crates/ui-egui/src/shelf_toolbar.rs | 3 +- crates/ui-egui/src/state.rs | 32 ++++++++- 15 files changed, 199 insertions(+), 16 deletions(-) create mode 100644 crates/ui-egui/src/saved_search.rs create mode 100644 crates/ui-egui/src/shelf_panes.rs diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 8b575955..b43d7e94 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1134,4 +1134,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Your assets", "أصولك"), ("Reset query", "إعادة تعيين الاستعلام"), ("Refresh", "تحديث"), + ("Saved searches", "عمليات البحث المحفوظة"), + ("Save the current search", "حفظ البحث الحالي"), + ("Delete", "حذف"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index c06ab830..9caa8d4f 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1180,4 +1180,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Your assets", "Eigene Assets"), ("Reset query", "Abfrage zurücksetzen"), ("Refresh", "Aktualisieren"), + ("Saved searches", "Gespeicherte Suchen"), + ("Save the current search", "Aktuelle Suche speichern"), + ("Delete", "Löschen"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 587d098a..b80856ba 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1171,4 +1171,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Your assets", "Tus recursos"), ("Reset query", "Restablecer consulta"), ("Refresh", "Actualizar"), + ("Saved searches", "Búsquedas guardadas"), + ("Save the current search", "Guardar la búsqueda actual"), + ("Delete", "Eliminar"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 62540c43..5ee27626 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1195,4 +1195,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Your assets", "Vos ressources"), ("Reset query", "Réinitialiser la requête"), ("Refresh", "Actualiser"), + ("Saved searches", "Recherches enregistrées"), + ("Save the current search", "Enregistrer la recherche actuelle"), + ("Delete", "Supprimer"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 6923de3f..ca3f7186 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1177,4 +1177,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Your assets", "Le tue risorse"), ("Reset query", "Reimposta query"), ("Refresh", "Aggiorna"), + ("Saved searches", "Ricerche salvate"), + ("Save the current search", "Salva la ricerca attuale"), + ("Delete", "Elimina"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 58dcfdee..285401bf 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1162,4 +1162,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Your assets", "マイアセット"), ("Reset query", "クエリをリセット"), ("Refresh", "更新"), + ("Saved searches", "保存した検索"), + ("Save the current search", "現在の検索を保存"), + ("Delete", "削除"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 2905d226..39933670 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1147,4 +1147,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Your assets", "내 에셋"), ("Reset query", "쿼리 초기화"), ("Refresh", "새로 고침"), + ("Saved searches", "저장된 검색"), + ("Save the current search", "현재 검색 저장"), + ("Delete", "삭제"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index e6edc0f4..4c3be582 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1165,4 +1165,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Your assets", "Seus recursos"), ("Reset query", "Redefinir consulta"), ("Refresh", "Atualizar"), + ("Saved searches", "Pesquisas salvas"), + ("Save the current search", "Salvar a pesquisa atual"), + ("Delete", "Excluir"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 5e07fb3b..d9a04f78 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1090,4 +1090,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Your assets", "我的资源"), ("Reset query", "重置查询"), ("Refresh", "刷新"), + ("Saved searches", "已保存的搜索"), + ("Save the current search", "保存当前搜索"), + ("Delete", "删除"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e1d42983..e57b5189 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -48,9 +48,11 @@ pub mod render_mode; mod resource_picker; mod resource_picker_item; mod running_bake; +pub mod saved_search; pub mod shelf; mod shelf_entry; mod shelf_folders; +pub mod shelf_panes; pub mod shelf_preview; mod shelf_tabs; mod shelf_toolbar; diff --git a/crates/ui-egui/src/saved_search.rs b/crates/ui-egui/src/saved_search.rs new file mode 100644 index 00000000..ec6181b8 --- /dev/null +++ b/crates/ui-egui/src/saved_search.rs @@ -0,0 +1,12 @@ +//! A shelf query the user saved in the Saved searches pane + +use serde::{Deserialize, Serialize}; + +/// The search text, tab and library folder 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, +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index ebd4cc0d..a5eed2d0 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -256,24 +256,37 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let toolbar_top = (area.bottom() - crate::shelf_toolbar::height(ui)).max(area.top()); let grid_rect = egui::Rect::from_min_max(area.min, egui::pos2(area.right(), toolbar_top)); let toolbar_rect = egui::Rect::from_min_max(egui::pos2(area.left(), toolbar_top), area.max); - ui.scope_builder(egui::UiBuilder::new().max_rect(grid_rect), |ui| { - egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).max_height(grid_rect.height()).show(ui, |ui| { - tiles(ui, |ui| { - for entry in &entries { - entry_tile(app, ui, &ctx, entry); - } + ui.scope_builder(egui::UiBuilder::new().max_rect(grid_rect).layout(egui::Layout::left_to_right(egui::Align::Min)), |ui| { + if let Some(width) = crate::shelf_panes::column_width(app, ui.available_width()) { + ui.allocate_ui_with_layout(vec2(width, grid_rect.height()), egui::Layout::top_down(egui::Align::Min), |ui| { + ui.set_min_size(vec2(width, grid_rect.height())); + crate::shelf_panes::column(app, ui); }); - - let in_user_library = folder.first().is_none_or(|library| library == crate::shelf_entry::USER); - if in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Smart) { - library(app, ui, &filter); - } - }); + ui.separator(); + } + // Saved smart materials are files in the user's library, without folders of their own + let in_user_library = folder.len() <= 1 && folder.first().is_none_or(|library| library == crate::shelf_entry::USER); + let saved_materials = in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Smart); + grid(app, ui, &ctx, &entries, grid_rect.height(), saved_materials, &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 the saved smart materials when `saved_materials` +fn grid(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entries: &[ShelfEntry], height: f32, saved_materials: bool, filter: &str) { + egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).max_height(height).show(ui, |ui| { + tiles(ui, |ui| { + for entry in entries { + entry_tile(app, ui, ctx, entry); + } + }); + if saved_materials { + library(app, ui, filter); + } + }); +} + /// The search field: a live filter on names (and categories) with a clear button while it has text fn search_field(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/shelf_panes.rs b/crates/ui-egui/src/shelf_panes.rs new file mode 100644 index 00000000..eb02b3e7 --- /dev/null +++ b/crates/ui-egui/src/shelf_panes.rs @@ -0,0 +1,102 @@ +//! The shelf's side panes, toggled from the bottom toolbar and stacked left of the grid: saved +//! searches (one click restores a query) + +use egui::{RichText, Ui}; +use egui_phosphor::regular as ic; +use serde::{Deserialize, Serialize}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::saved_search::SavedSearch; +use crate::shelf::TABS; +use crate::theme::Tokens; +use crate::widgets::icon_button; + +/// The panes' column width as a fraction of the panel, and its least width in points +const COLUMN_FRACTION: f32 = 0.45; +const COLUMN_MIN_WIDTH: f32 = 110.0; +/// The pane header's caption size in points +const HEADER_SIZE: f32 = 10.0; + +/// Which side panes are open +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ShelfPanes { + pub saved_searches: bool, +} + +/// The toolbar's buttons that open and close the panes +pub(crate) fn toggles(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) { + let panes = &mut app.ui.shelf_panes; + if icon_button(ui, ic::BOOKMARKS_SIMPLE, tr("Saved searches"), panes.saved_searches, size).clicked() { + panes.saved_searches = !panes.saved_searches; + } +} + +/// 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 { + app.ui.shelf_panes.saved_searches.then(|| (width * COLUMN_FRACTION).max(COLUMN_MIN_WIDTH).min(width)) +} + +/// The open panes, top to bottom +pub(crate) fn column(app: &mut TextureCraftApp, ui: &mut Ui) { + // Names past the narrow column end in "…" rather than breaking mid-word + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); + if app.ui.shelf_panes.saved_searches { + saved_searches(app, ui); + } +} + +/// A pane's caption with a button at its right +fn header(ui: &mut Ui, title: &str, button: impl FnOnce(&mut Ui)) { + let tk = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.label(RichText::new(title.to_uppercase()).size(HEADER_SIZE).color(tk.text_dim)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), button); + }); +} + +/// "All", 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; + let current = current_query(app); + header(ui, tr("Saved searches"), |ui| { + if icon_button(ui, ic::FLOPPY_DISK, tr("Save the current search"), false, size).clicked() && !app.ui.shelf_saved_searches.contains(¤t) { + app.ui.shelf_saved_searches.push(current.clone()); + } + }); + + let everything = current.filter.is_empty() && current.path.is_empty() && current.tab == crate::shelf_tabs::NO_TYPE; + if ui.selectable_label(everything, tr("All")).clicked() { + crate::shelf_toolbar::reset_query(app); + } + let mut deleted = None; + for (i, saved) in app.ui.shelf_saved_searches.iter().enumerate() { + let same = saved.filter == current.filter && saved.tab == current.tab && saved.path == current.path; + let response = ui.selectable_label(same, &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()); + } + response.context_menu(|ui| { + if ui.button(tr("Delete")).clicked() { + deleted = Some(i); + ui.close(); + } + }); + } + if let Some(i) = deleted { + app.ui.shelf_saved_searches.remove(i); + } +} + +/// The shelf's query, named after its search text, else its folder, else its tab +fn current_query(app: &TextureCraftApp) -> SavedSearch { + let (filter, tab, path) = (app.ui.shelf_filter.clone(), app.ui.shelf_tab, app.ui.shelf_path.clone()); + let name = if !filter.is_empty() { + filter.clone() + } else if let Some(folder) = path.last() { + crate::shelf_folders::name(path.len() - 1, folder).to_string() + } else { + TABS.get(tab).map_or(tr("All"), |(_, _, label)| tr(label)).to_string() + }; + SavedSearch { name, filter, tab, path } +} diff --git a/crates/ui-egui/src/shelf_toolbar.rs b/crates/ui-egui/src/shelf_toolbar.rs index 93a5afcd..5e185bf9 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: refresh, reset query and import on the right +//! The shelf's bottom toolbar: the side pane toggles on the left; refresh, reset query and import on the right use egui::Ui; use egui_phosphor::regular as ic; @@ -20,6 +20,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { let size = ui.spacing().interact_size.y; ui.add_space(GAP_ABOVE); ui.horizontal(|ui| { + crate::shelf_panes::toggles(app, ui, size); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if icon_button(ui, ic::PLUS, tr("Import resources..."), false, size).clicked() { crate::menus::invoke(app, &ui.ctx().clone(), "resource.import"); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f9b75653..0d2acd6f 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -5,6 +5,8 @@ use texturecraft_engine::core::{BakedMap, Channel, NormalFormat}; use crate::docking::Dock; use crate::keymap::Keymap; +use crate::saved_search::SavedSearch; +use crate::shelf_panes::ShelfPanes; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum Mode { @@ -303,6 +305,12 @@ pub struct UiState { /// The asset shelf's library folder: a library id, then folder names (empty: all libraries) #[serde(default)] pub shelf_path: Vec, + /// The asset shelf's open side panes + #[serde(default)] + pub shelf_panes: ShelfPanes, + /// The asset shelf's saved queries, in the order they were saved + #[serde(default)] + pub shelf_saved_searches: Vec, pub props_tab: PropsTab, #[serde(default)] pub text: TextUi, @@ -360,17 +368,21 @@ impl UiState { self.bake_layout_version = BAKE_LAYOUT_VERSION; } - /// Take `layout`'s panels, windows and view settings, keeping this state's dialogs, export - /// settings and recent files. + /// Take `layout`'s panels, windows and view settings, keeping this state's dialogs, settings, files and shelf query pub fn adopt_layout(&mut self, layout: UiState) { let keep = std::mem::replace(self, layout); self.new_project = keep.new_project; self.export = keep.export; self.recent = keep.recent; - self.shelf_filter = keep.shelf_filter; self.prefs = keep.prefs; self.keymap = keep.keymap; self.rename = None; + + // The shelf's search, type and folder are one query, and saved searches are the user's own + self.shelf_filter = keep.shelf_filter; + self.shelf_tab = keep.shelf_tab; + self.shelf_path = keep.shelf_path; + self.shelf_saved_searches = keep.shelf_saved_searches; } } @@ -394,6 +406,8 @@ impl Default for UiState { shelf_filter: String::new(), shelf_tab: 0, shelf_path: Vec::new(), + shelf_panes: ShelfPanes::default(), + shelf_saved_searches: Vec::new(), props_tab: PropsTab::Brush, text: TextUi::default(), rename: None, @@ -430,6 +444,18 @@ mod tests { assert_eq!(ui.keymap.get("file.save").map(String::as_str), Some("F5")); } + #[test] + fn adopting_a_layout_keeps_the_shelf_query_and_saved_searches() { + 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() }; + ui.shelf_saved_searches.push(saved.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]); + } + #[test] fn the_data_folder_is_an_absolute_choice_or_documents_texturecraft() { let default = crate::data_folder(""); From 880da2706166a66c2fd56df712d5655a8c3bd80e Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 03:15:04 +0000 Subject: [PATCH 15/22] Assets: a Filter by path pane: the library folders as a tree, optionally only those with matching assets --- crates/ui-egui/src/i18n/ar.rs | 2 + crates/ui-egui/src/i18n/de.rs | 2 + crates/ui-egui/src/i18n/es.rs | 2 + crates/ui-egui/src/i18n/fr.rs | 2 + crates/ui-egui/src/i18n/it.rs | 2 + crates/ui-egui/src/i18n/ja.rs | 2 + crates/ui-egui/src/i18n/ko.rs | 2 + crates/ui-egui/src/i18n/pt_br.rs | 2 + crates/ui-egui/src/i18n/zh_hans.rs | 2 + crates/ui-egui/src/shelf.rs | 4 +- crates/ui-egui/src/shelf_folders.rs | 4 +- crates/ui-egui/src/shelf_panes.rs | 72 +++++++++++++++++++++++++++-- 12 files changed, 90 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index b43d7e94..5f58de6a 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1137,4 +1137,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Saved searches", "عمليات البحث المحفوظة"), ("Save the current search", "حفظ البحث الحالي"), ("Delete", "حذف"), + ("Filter by path", "تصفية حسب المسار"), + ("Hide non-applicable folders", "إخفاء المجلدات غير المطابقة"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 9caa8d4f..d9cf04a3 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1183,4 +1183,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Saved searches", "Gespeicherte Suchen"), ("Save the current search", "Aktuelle Suche speichern"), ("Delete", "Löschen"), + ("Filter by path", "Nach Pfad filtern"), + ("Hide non-applicable folders", "Nicht zutreffende Ordner ausblenden"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index b80856ba..029d56c2 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1174,4 +1174,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Saved searches", "Búsquedas guardadas"), ("Save the current search", "Guardar la búsqueda actual"), ("Delete", "Eliminar"), + ("Filter by path", "Filtrar por ruta"), + ("Hide non-applicable folders", "Ocultar carpetas no aplicables"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 5ee27626..6ef7af9b 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1198,4 +1198,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Saved searches", "Recherches enregistrées"), ("Save the current search", "Enregistrer la recherche actuelle"), ("Delete", "Supprimer"), + ("Filter by path", "Filtrer par chemin"), + ("Hide non-applicable folders", "Masquer les dossiers non applicables"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index ca3f7186..40e041b1 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1180,4 +1180,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Saved searches", "Ricerche salvate"), ("Save the current search", "Salva la ricerca attuale"), ("Delete", "Elimina"), + ("Filter by path", "Filtra per percorso"), + ("Hide non-applicable folders", "Nascondi le cartelle non pertinenti"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 285401bf..b890c371 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1165,4 +1165,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Saved searches", "保存した検索"), ("Save the current search", "現在の検索を保存"), ("Delete", "削除"), + ("Filter by path", "パスで絞り込む"), + ("Hide non-applicable folders", "該当しないフォルダーを隠す"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 39933670..8b93a6ab 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1150,4 +1150,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Saved searches", "저장된 검색"), ("Save the current search", "현재 검색 저장"), ("Delete", "삭제"), + ("Filter by path", "경로별 필터"), + ("Hide non-applicable folders", "해당 없는 폴더 숨기기"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 4c3be582..3514e942 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1168,4 +1168,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Saved searches", "Pesquisas salvas"), ("Save the current search", "Salvar a pesquisa atual"), ("Delete", "Excluir"), + ("Filter by path", "Filtrar por caminho"), + ("Hide non-applicable folders", "Ocultar pastas não aplicáveis"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index d9a04f78..aeca1b5e 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1093,4 +1093,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Saved searches", "已保存的搜索"), ("Save the current search", "保存当前搜索"), ("Delete", "删除"), + ("Filter by path", "按路径筛选"), + ("Hide non-applicable folders", "隐藏不适用的文件夹"), ]; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index a5eed2d0..9e8d2390 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -238,6 +238,8 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { } let folder = app.ui.shelf_path.clone(); + let picked_tab = app.ui.shelf_tab; + let applicable = crate::shelf_folders::paths(all.iter().filter(|entry| entry.matches(&filter) && crate::shelf_tabs::shows(picked_tab, entry.tab()))); let matching: Vec = all.into_iter().filter(|entry| entry.in_folder(&folder) && entry.matches(&filter)).collect(); let counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); @@ -260,7 +262,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { if let Some(width) = crate::shelf_panes::column_width(app, ui.available_width()) { ui.allocate_ui_with_layout(vec2(width, grid_rect.height()), egui::Layout::top_down(egui::Align::Min), |ui| { ui.set_min_size(vec2(width, grid_rect.height())); - crate::shelf_panes::column(app, ui); + crate::shelf_panes::column(app, ui, &paths, &applicable); }); ui.separator(); } diff --git a/crates/ui-egui/src/shelf_folders.rs b/crates/ui-egui/src/shelf_folders.rs index de8c2144..0f029033 100644 --- a/crates/ui-egui/src/shelf_folders.rs +++ b/crates/ui-egui/src/shelf_folders.rs @@ -12,8 +12,8 @@ use crate::widgets::icon_button; const ARROW_SCALE: f32 = 0.8; /// The folder paths of `entries`, each a library id then folder names -pub(crate) fn paths(entries: &[ShelfEntry]) -> Vec> { - let mut paths: Vec> = entries.iter().map(|entry| entry.path().into_iter().map(str::to_string).collect()).collect(); +pub(crate) fn paths<'a>(entries: impl IntoIterator) -> Vec> { + let mut paths: Vec> = entries.into_iter().map(|entry| entry.path().into_iter().map(str::to_string).collect()).collect(); paths.sort(); paths.dedup(); paths diff --git a/crates/ui-egui/src/shelf_panes.rs b/crates/ui-egui/src/shelf_panes.rs index eb02b3e7..dee1eb62 100644 --- a/crates/ui-egui/src/shelf_panes.rs +++ b/crates/ui-egui/src/shelf_panes.rs @@ -1,5 +1,4 @@ -//! The shelf's side panes, toggled from the bottom toolbar and stacked left of the grid: saved -//! searches (one click restores a query) +//! The shelf's side panes left of the grid, toggled from the toolbar: saved searches and the folder tree use egui::{RichText, Ui}; use egui_phosphor::regular as ic; @@ -22,6 +21,9 @@ const HEADER_SIZE: f32 = 10.0; #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct ShelfPanes { pub saved_searches: bool, + pub filter_by_path: bool, + /// Filter by path lists only the folders with assets matching the search and tab + pub hide_non_applicable: bool, } /// The toolbar's buttons that open and close the panes @@ -30,20 +32,80 @@ pub(crate) fn toggles(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) { if icon_button(ui, ic::BOOKMARKS_SIMPLE, tr("Saved searches"), panes.saved_searches, size).clicked() { panes.saved_searches = !panes.saved_searches; } + if icon_button(ui, ic::TREE_STRUCTURE, tr("Filter by path"), panes.filter_by_path, size).clicked() { + panes.filter_by_path = !panes.filter_by_path; + } } /// 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 { - app.ui.shelf_panes.saved_searches.then(|| (width * COLUMN_FRACTION).max(COLUMN_MIN_WIDTH).min(width)) + let panes = &app.ui.shelf_panes; + (panes.saved_searches || panes.filter_by_path).then(|| (width * COLUMN_FRACTION).max(COLUMN_MIN_WIDTH).min(width)) } -/// The open panes, top to bottom -pub(crate) fn column(app: &mut TextureCraftApp, ui: &mut Ui) { +/// The open panes, top to bottom; the tree shows `paths`, or `applicable` while it hides folders with nothing matching +pub(crate) fn column(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec], applicable: &[Vec]) { // Names past the narrow column end in "…" rather than breaking mid-word ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); if app.ui.shelf_panes.saved_searches { saved_searches(app, ui); } + if app.ui.shelf_panes.filter_by_path { + if app.ui.shelf_panes.saved_searches { + ui.separator(); + } + let shown = if app.ui.shelf_panes.hide_non_applicable { applicable } else { paths }; + filter_by_path(app, ui, shown); + } +} + +/// "All libraries", then each library's folders as a tree; a click shows that folder +fn filter_by_path(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec]) { + let size = ui.spacing().interact_size.y; + header(ui, tr("Filter by path"), |ui| { + let hiding = app.ui.shelf_panes.hide_non_applicable; + if icon_button(ui, ic::EYE_SLASH, tr("Hide non-applicable folders"), hiding, size).clicked() { + app.ui.shelf_panes.hide_non_applicable = !hiding; + } + }); + + let mut picked = None; + egui::ScrollArea::vertical().id_salt("shelf_path_tree").auto_shrink([false, true]).show(ui, |ui| { + if ui.selectable_label(app.ui.shelf_path.is_empty(), tr("All libraries")).clicked() { + picked = Some(Vec::new()); + } + folders(ui, paths, &[], &app.ui.shelf_path, &mut picked); + }); + if let Some(path) = picked { + app.ui.shelf_path = path; + } +} + +/// The folders below `prefix`: one with folders inside opens and closes, a click on a name picks it +fn folders(ui: &mut Ui, paths: &[Vec], prefix: &[String], current: &[String], picked: &mut Option>) { + for child in crate::shelf_folders::children(paths, prefix) { + let path: Vec = prefix.iter().cloned().chain([child.clone()]).collect(); + let name = crate::shelf_folders::name(prefix.len(), &child); + let selected = current == path.as_slice(); + if crate::shelf_folders::children(paths, &path).is_empty() { + ui.indent(("shelf_path_leaf", &path), |ui| { + if ui.selectable_label(selected, name).clicked() { + *picked = Some(path.clone()); + } + }); + continue; + } + + let id = ui.make_persistent_id(("shelf_path", &path)); + let open_by_default = current.starts_with(&path); + egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, open_by_default) + .show_header(ui, |ui| { + if ui.selectable_label(selected, name).clicked() { + *picked = Some(path.clone()); + } + }) + .body(|ui| folders(ui, paths, &path, current, picked)); + } } /// A pane's caption with a button at its right From 0fb7d9205772445341d809c32dc8dad508acdbd5 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 03:16:34 +0000 Subject: [PATCH 16/22] Assets: the grid's scrollbar always shows --- crates/ui-egui/src/shelf.rs | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 9e8d2390..aa753acd 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -277,16 +277,21 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { /// The tiles of `entries` in a scroll area `height` high, then the saved smart materials when `saved_materials` fn grid(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entries: &[ShelfEntry], height: f32, saved_materials: bool, filter: &str) { - egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).max_height(height).show(ui, |ui| { - tiles(ui, |ui| { - for entry in entries { - entry_tile(app, ui, ctx, entry); + egui::ScrollArea::vertical() + .id_salt("shelf_scroll") + .auto_shrink([false, false]) + .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible) + .max_height(height) + .show(ui, |ui| { + tiles(ui, |ui| { + for entry in entries { + entry_tile(app, ui, ctx, entry); + } + }); + if saved_materials { + library(app, ui, filter); } }); - if saved_materials { - library(app, ui, filter); - } - }); } /// The search field: a live filter on names (and categories) with a clear button while it has text From 751f7937442dda2a06fe13dfddcd4ded634d07ff Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 05:33:11 +0000 Subject: [PATCH 17/22] Assets: a thumbnail size menu at the end of the type row: small, medium or large tiles, or a list --- crates/ui-egui/src/grid_tile.rs | 9 ++++ crates/ui-egui/src/i18n/ar.rs | 6 +++ crates/ui-egui/src/i18n/de.rs | 6 +++ crates/ui-egui/src/i18n/es.rs | 6 +++ crates/ui-egui/src/i18n/fr.rs | 6 +++ crates/ui-egui/src/i18n/it.rs | 6 +++ crates/ui-egui/src/i18n/ja.rs | 6 +++ crates/ui-egui/src/i18n/ko.rs | 6 +++ crates/ui-egui/src/i18n/pt_br.rs | 6 +++ crates/ui-egui/src/i18n/zh_hans.rs | 6 +++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/shelf.rs | 73 +++++++++++++++----------- crates/ui-egui/src/shelf_view.rs | 83 ++++++++++++++++++++++++++++++ crates/ui-egui/src/state.rs | 5 ++ 14 files changed, 196 insertions(+), 30 deletions(-) create mode 100644 crates/ui-egui/src/grid_tile.rs create mode 100644 crates/ui-egui/src/shelf_view.rs diff --git a/crates/ui-egui/src/grid_tile.rs b/crates/ui-egui/src/grid_tile.rs new file mode 100644 index 00000000..45fd9bf6 --- /dev/null +++ b/crates/ui-egui/src/grid_tile.rs @@ -0,0 +1,9 @@ +//! A grid tile's measurements in the shelf's small, medium and large views + +/// A grid tile's size and its thumbnail's size and center below the tile's top, in points +pub(crate) struct GridTile { + pub(crate) width: f32, + pub(crate) height: f32, + pub(crate) thumbnail_size: f32, + pub(crate) thumbnail_center_y: f32, +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 5f58de6a..b63df18c 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1139,4 +1139,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Delete", "حذف"), ("Filter by path", "تصفية حسب المسار"), ("Hide non-applicable folders", "إخفاء المجلدات غير المطابقة"), + ("Thumbnail size", "حجم الصورة المصغّرة"), + ("Small", "صغير"), + ("Medium", "متوسط"), + ("Large", "كبير"), + ("List", "قائمة"), + ("Procedurals", "إجرائيات"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index d9cf04a3..81e62b2c 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1185,4 +1185,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Delete", "Löschen"), ("Filter by path", "Nach Pfad filtern"), ("Hide non-applicable folders", "Nicht zutreffende Ordner ausblenden"), + ("Thumbnail size", "Vorschaugröße"), + ("Small", "Klein"), + ("Medium", "Mittel"), + ("Large", "Groß"), + ("List", "Liste"), + ("Procedurals", "Prozedurale"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 029d56c2..ed759054 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1176,4 +1176,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Delete", "Eliminar"), ("Filter by path", "Filtrar por ruta"), ("Hide non-applicable folders", "Ocultar carpetas no aplicables"), + ("Thumbnail size", "Tamaño de miniatura"), + ("Small", "Pequeño"), + ("Medium", "Mediano"), + ("Large", "Grande"), + ("List", "Lista"), + ("Procedurals", "Procedurales"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 6ef7af9b..ebcb248a 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1200,4 +1200,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Delete", "Supprimer"), ("Filter by path", "Filtrer par chemin"), ("Hide non-applicable folders", "Masquer les dossiers non applicables"), + ("Thumbnail size", "Taille des miniatures"), + ("Small", "Petit"), + ("Medium", "Moyen"), + ("Large", "Grand"), + ("List", "Liste"), + ("Procedurals", "Procéduraux"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 40e041b1..55fe9abd 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1182,4 +1182,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Delete", "Elimina"), ("Filter by path", "Filtra per percorso"), ("Hide non-applicable folders", "Nascondi le cartelle non pertinenti"), + ("Thumbnail size", "Dimensione miniature"), + ("Small", "Piccolo"), + ("Medium", "Medio"), + ("Large", "Grande"), + ("List", "Elenco"), + ("Procedurals", "Procedurali"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index b890c371..bb4f5152 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1167,4 +1167,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Delete", "削除"), ("Filter by path", "パスで絞り込む"), ("Hide non-applicable folders", "該当しないフォルダーを隠す"), + ("Thumbnail size", "サムネイルのサイズ"), + ("Small", "小"), + ("Medium", "中"), + ("Large", "大"), + ("List", "リスト"), + ("Procedurals", "プロシージャル"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 8b93a6ab..4273f92c 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1152,4 +1152,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Delete", "삭제"), ("Filter by path", "경로별 필터"), ("Hide non-applicable folders", "해당 없는 폴더 숨기기"), + ("Thumbnail size", "썸네일 크기"), + ("Small", "작게"), + ("Medium", "보통"), + ("Large", "크게"), + ("List", "목록"), + ("Procedurals", "프로시저럴"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 3514e942..70d68d21 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1170,4 +1170,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Delete", "Excluir"), ("Filter by path", "Filtrar por caminho"), ("Hide non-applicable folders", "Ocultar pastas não aplicáveis"), + ("Thumbnail size", "Tamanho da miniatura"), + ("Small", "Pequeno"), + ("Medium", "Médio"), + ("Large", "Grande"), + ("List", "Lista"), + ("Procedurals", "Procedurais"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index aeca1b5e..0b582484 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1095,4 +1095,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Delete", "删除"), ("Filter by path", "按路径筛选"), ("Hide non-applicable folders", "隐藏不适用的文件夹"), + ("Thumbnail size", "缩略图大小"), + ("Small", "小"), + ("Medium", "中"), + ("Large", "大"), + ("List", "列表"), + ("Procedurals", "程序纹理"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e57b5189..efdfbf65 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -23,6 +23,7 @@ pub mod file_dialogs; mod filter_slot; pub mod fonts; pub mod gpu; +mod grid_tile; pub mod i18n; pub mod id_color_pick; pub mod keymap; @@ -56,6 +57,7 @@ pub mod shelf_panes; pub mod shelf_preview; mod shelf_tabs; mod shelf_toolbar; +pub mod shelf_view; mod soft_box; pub mod state; pub mod symmetry; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index aa753acd..5902452b 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -13,13 +13,12 @@ use crate::decal_drop::DecalDrop; use crate::i18n::{tr, trf}; use crate::shelf_entry::ShelfEntry; use crate::shelf_preview::ShelfPreview; +use crate::shelf_view::ShelfView; use crate::theme::Tokens; use crate::thumbs::Thumbs; use crate::widgets::dnd_release; -/// A shelf tile's size and the gap between tiles in points: a 68 x 78 grid step, as in the reference -const TILE_WIDTH: f32 = 66.0; -const TILE_HEIGHT: f32 = 76.0; +/// The gap between tiles in points (their sizes are [`ShelfView`]'s) const TILE_GAP: f32 = 2.0; /// Corner radius of a tile's hover and selection highlights, in points const TILE_ROUNDING: f32 = 3.0; @@ -36,9 +35,6 @@ const BADGE_INSET: f32 = 2.5; const BADGE_DOT_FILL: Color32 = Color32::from_gray(205); const BADGE_DOT_RIM: f32 = 0.8; const BADGE_DOT_RIM_COLOR: Color32 = Color32::from_black_alpha(170); -/// The thumbnail's size in a tile and its center below the tile's top, in points -const THUMBNAIL_SIZE: f32 = 60.0; -const THUMBNAIL_CENTER_Y: f32 = 31.0; /// Loading icon size relative to the thumbnail width, and its opacity over the dim text color const LOADING_ICON_SCALE: f32 = 0.9; const LOADING_ICON_OPACITY: f32 = 0.5; @@ -245,7 +241,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { crate::shelf_folders::breadcrumb(app, ui, &paths); search_field(app, ui); - crate::shelf_tabs::row(app, ui, &counts, |_, _, _| {}); + crate::shelf_tabs::row(app, ui, &counts, crate::shelf_view::menu); ui.add_space(4.0); let tab = app.ui.shelf_tab; @@ -277,6 +273,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { /// The tiles of `entries` in a scroll area `height` high, then the saved smart materials when `saved_materials` fn grid(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entries: &[ShelfEntry], height: f32, saved_materials: bool, filter: &str) { + let view = app.ui.shelf_view; egui::ScrollArea::vertical() .id_salt("shelf_scroll") .auto_shrink([false, false]) @@ -285,7 +282,7 @@ fn grid(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entries: &[ .show(ui, |ui| { tiles(ui, |ui| { for entry in entries { - entry_tile(app, ui, ctx, entry); + entry_tile(app, ui, ctx, entry, view); } }); if saved_materials { @@ -418,12 +415,13 @@ fn scan_brushes(app: &mut TextureCraftApp) { fn scan_brushes(_: &mut TextureCraftApp) {} /// The tile of `entry`: a click applies it, an image resource has a context menu -fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry) { +fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry, view: ShelfView) { // An image removed this frame has nothing to show let (Some(preview), texture) = (entry.preview(app), entry.thumbnail(app, ctx)) else { return }; let asset = entry.asset(); - let response = tile(ui, &mut app.thumbs, texture.as_ref(), || preview, entry.label(), asset.as_ref()); + let response = tile_in_view(ui, &mut app.thumbs, texture.as_ref(), || preview, entry.label(), asset.as_ref(), view); + let selected_id = egui::Id::unique(SELECTED_TILE); let key = entry.key(); let selected = ctx.data(|data| data.get_temp::(selected_id)).is_some_and(|selected| selected == key); @@ -434,7 +432,7 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry } if entry.includes_randomness() { - randomness_badge(ui.painter(), response.rect); + randomness_badge(ui.painter(), view.thumbnail_rect(response.rect)); } if response.clicked() || response.secondary_clicked() { @@ -458,46 +456,61 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry } } -/// Asset tile with optional dragging and a larger hover preview +/// Asset tile with optional dragging and a larger hover preview, at the medium size pub(crate) fn tile( ui: &mut Ui, thumbs: &mut Thumbs, - tex: Option<&egui::TextureHandle>, + texture: Option<&egui::TextureHandle>, preview: impl FnOnce() -> ShelfPreview, label: &str, drag: Option<&Asset>, +) -> egui::Response { + tile_in_view(ui, thumbs, texture, preview, label, drag, ShelfView::Medium) +} + +/// [`tile`] at `view`'s size: a grid tile with the name under the thumbnail, or a list row with it beside +fn tile_in_view( + ui: &mut Ui, + thumbs: &mut Thumbs, + texture: Option<&egui::TextureHandle>, + preview: impl FnOnce() -> ShelfPreview, + label: &str, + drag: Option<&Asset>, + view: ShelfView, ) -> egui::Response { let tk = Tokens::get(ui.ctx()); let sense = if drag.is_some() { Sense::click_and_drag() } else { Sense::click() }; - let (rect, resp) = ui.allocate_exact_size(vec2(TILE_WIDTH, TILE_HEIGHT), sense); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); + let (rect, response) = ui.allocate_exact_size(view.tile_size(ui.available_width()), sense); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); if let Some(asset) = drag - && resp.drag_started() + && response.drag_started() { - resp.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() }); } let painter = ui.painter(); - if resp.hovered() || resp.dragged() { + if response.hovered() || response.dragged() { painter.rect_filled(rect, TILE_ROUNDING, tk.row_hover); } - let image_rect = thumbnail_rect(rect); - thumbnail(painter, tex, image_rect, &tk); - let galley = painter.layout_job(one_line(label, rect.width() - LABEL_MARGIN, tk.text)); - painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tk.text); - let big = if resp.hovered() { big_preview(ui, thumbs, preview) } else { None }; - resp.on_hover_ui(|ui| hover_preview(ui, tex, big.as_ref(), label)) -} + let image_rect = view.thumbnail_rect(rect); + thumbnail(painter, texture, image_rect, &tk); + if view.name_beside() { + let left = image_rect.right() + crate::shelf_view::LIST_NAME_GAP; + let galley = painter.layout_job(one_line(label, rect.right() - left - LABEL_MARGIN, tk.text)); + painter.galley(egui::pos2(left, rect.center().y - galley.size().y * 0.5), galley, tk.text); + } else { + let galley = painter.layout_job(one_line(label, rect.width() - LABEL_MARGIN, tk.text)); + painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tk.text); + } -/// Where a tile's thumbnail goes in the tile's `rect` -fn thumbnail_rect(rect: egui::Rect) -> egui::Rect { - egui::Rect::from_center_size(rect.center_top() + vec2(0.0, THUMBNAIL_CENTER_Y), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)) + let big = if response.hovered() { big_preview(ui, thumbs, preview) } else { None }; + response.on_hover_ui(|ui| hover_preview(ui, texture, big.as_ref(), label)) } /// Three light, dark-rimmed dots at the thumbnail's bottom-right corner: the asset includes randomness -fn randomness_badge(painter: &egui::Painter, tile: egui::Rect) { - let corner = thumbnail_rect(tile).right_bottom() - vec2(BADGE_INSET, BADGE_INSET); +fn randomness_badge(painter: &egui::Painter, thumbnail: egui::Rect) { + let corner = thumbnail.right_bottom() - vec2(BADGE_INSET, BADGE_INSET); for offset in [vec2(0.0, 0.0), vec2(-BADGE_DOT_SPACING, 0.0), vec2(-BADGE_DOT_SPACING * 0.5, -BADGE_DOT_SPACING)] { painter.circle(corner + offset, BADGE_DOT_RADIUS, BADGE_DOT_FILL, Stroke::new(BADGE_DOT_RIM, BADGE_DOT_RIM_COLOR)); } diff --git a/crates/ui-egui/src/shelf_view.rs b/crates/ui-egui/src/shelf_view.rs new file mode 100644 index 00000000..036c498b --- /dev/null +++ b/crates/ui-egui/src/shelf_view.rs @@ -0,0 +1,83 @@ +//! How the shelf shows its assets: small, medium or large tiles, or a list (the menu at the type row's end) + +use egui::{Rect, Ui, Vec2, vec2}; +use egui_phosphor::regular as ic; +use serde::{Deserialize, Serialize}; + +use crate::TextureCraftApp; +use crate::grid_tile::GridTile; +use crate::i18n::tr; +use crate::widgets::icon_button; + +/// A list row's height and its thumbnail's size, in points +const LIST_ROW_HEIGHT: f32 = 30.0; +const LIST_THUMBNAIL_SIZE: f32 = 26.0; +/// The gap between a list row's thumbnail and its name, in points +pub(crate) const LIST_NAME_GAP: f32 = 6.0; + +/// The shelf's tile size, or the list +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ShelfView { + Small, + /// A 68 x 78 grid step, as in the reference + #[default] + Medium, + Large, + List, +} + +/// The views in the menu's order: icon and (English, translated where shown) name +const VIEWS: [(ShelfView, &str, &str); 4] = [ + (ShelfView::Small, ic::GRID_NINE, "Small"), + (ShelfView::Medium, ic::GRID_FOUR, "Medium"), + (ShelfView::Large, ic::SQUARE, "Large"), + (ShelfView::List, ic::LIST, "List"), +]; + +impl ShelfView { + /// A grid tile's measurements; None for the list + fn grid(self) -> Option { + match self { + ShelfView::Small => Some(GridTile { width: 50.0, height: 58.0, thumbnail_size: 44.0, thumbnail_center_y: 23.0 }), + ShelfView::Medium => Some(GridTile { width: 66.0, height: 76.0, thumbnail_size: 60.0, thumbnail_center_y: 31.0 }), + ShelfView::Large => Some(GridTile { width: 88.0, height: 100.0, thumbnail_size: 82.0, thumbnail_center_y: 42.0 }), + ShelfView::List => None, + } + } + + /// A tile's size in a grid `width` points wide (a list row spans it) + pub(crate) fn tile_size(self, width: f32) -> Vec2 { + match self.grid() { + Some(tile) => vec2(tile.width, tile.height), + None => vec2(width.max(LIST_ROW_HEIGHT), LIST_ROW_HEIGHT), + } + } + + /// Where the thumbnail goes in the tile `rect` + pub(crate) fn thumbnail_rect(self, rect: Rect) -> Rect { + match self.grid() { + Some(tile) => Rect::from_center_size(rect.center_top() + vec2(0.0, tile.thumbnail_center_y), vec2(tile.thumbnail_size, tile.thumbnail_size)), + None => Rect::from_center_size(rect.left_center() + vec2(LIST_ROW_HEIGHT * 0.5, 0.0), vec2(LIST_THUMBNAIL_SIZE, LIST_THUMBNAIL_SIZE)), + } + } + + /// Whether the name sits right of the thumbnail (a list) rather than under it + pub(crate) fn name_beside(self) -> bool { + self == ShelfView::List + } +} + +/// The view menu button: its icon is the current view's +pub(crate) fn menu(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) { + let current = app.ui.shelf_view; + let icon = VIEWS.iter().find(|(view, _, _)| *view == current).map_or(ic::GRID_FOUR, |(_, icon, _)| icon); + let response = icon_button(ui, icon, tr("Thumbnail size"), false, size); + egui::Popup::menu(&response).show(|ui| { + for (view, icon, label) in VIEWS { + if ui.selectable_label(view == current, format!("{icon} {}", tr(label))).clicked() { + app.ui.shelf_view = view; + ui.close(); + } + } + }); +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0d2acd6f..a8b43813 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -7,6 +7,7 @@ use crate::docking::Dock; use crate::keymap::Keymap; use crate::saved_search::SavedSearch; use crate::shelf_panes::ShelfPanes; +use crate::shelf_view::ShelfView; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum Mode { @@ -305,6 +306,9 @@ pub struct UiState { /// The asset shelf's library folder: a library id, then folder names (empty: all libraries) #[serde(default)] pub shelf_path: Vec, + /// The asset shelf's tile size, or its list + #[serde(default)] + pub shelf_view: ShelfView, /// The asset shelf's open side panes #[serde(default)] pub shelf_panes: ShelfPanes, @@ -406,6 +410,7 @@ impl Default for UiState { shelf_filter: String::new(), shelf_tab: 0, shelf_path: Vec::new(), + shelf_view: ShelfView::default(), shelf_panes: ShelfPanes::default(), shelf_saved_searches: Vec::new(), props_tab: PropsTab::Brush, From accfb51aba74332e3d99c037dccbd8352880a6ff Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 05:56:10 +0000 Subject: [PATCH 18/22] Assets: tests for the panel layout: columns at the reference width, one-line labels, type row, breadcrumb, size menu, panes and toolbar --- crates/ui-egui/src/shelf.rs | 21 +++ crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/shelf_panel.rs | 239 +++++++++++++++++++++++++ 3 files changed, 261 insertions(+) create mode 100644 crates/ui-egui/tests/it/shelf_panel.rs diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 5902452b..75958d99 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -573,3 +573,24 @@ fn hover_preview(ui: &mut Ui, small: Option<&egui::TextureHandle>, big: Option<& ui.label(label); }); } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_long_label_stays_on_one_line_ending_in_an_ellipsis() { + let width = 60.0; + let mut laid_out = None; + let mut output = egui::Context::default().run_ui(egui::RawInput::default(), |ui| { + laid_out = Some(ui.painter().layout_job(one_line("Steel Painted Rust Leaks Extra", width, Color32::WHITE))); + }); + // The font atlas upload is not under test + output.textures_delta.clear(); + let galley = laid_out.unwrap(); + + assert_eq!(galley.rows.len(), 1); + assert!(galley.size().x <= width); + assert_eq!(galley.rows[0].glyphs.last().map(|glyph| glyph.chr), Some('…')); + } +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 6f1c5092..da067f4d 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -29,6 +29,7 @@ mod properties_popup; mod rail; mod shelf_drop; mod shelf_hover_preview; +mod shelf_panel; mod shift_lines_2d; mod shortcut_keys; mod skew_paint; diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs new file mode 100644 index 00000000..94e3edd7 --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -0,0 +1,239 @@ +//! The Assets panel's layout: columns at the reference width, type row, size menu, breadcrumb, side panes and toolbar + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::core::project::ENVIRONMENTS; +use texturecraft_engine::materials::{MATERIALS, SmartMaterial}; +use texturecraft_engine::smart_masks::SMART_MASKS; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::shelf_view::ShelfView; + +/// The reference's capture window: its Assets panel shows four columns there +const REFERENCE_WINDOW: egui::Vec2 = egui::vec2(1920.0, 1032.0); +/// A window whose default Assets panel is too narrow for the full type row +const NARROW_WINDOW: egui::Vec2 = egui::vec2(1100.0, 1032.0); +/// The shelf's Materials and Smart masks types +const MATERIALS_TYPE: usize = 0; +const SMART_MASKS_TYPE: usize = 2; +const BRUSHES_TYPE: usize = 4; +const TEXTURES_TYPE: usize = 6; +const ENVIRONMENTS_TYPE: usize = 7; +/// Tile columns the reference shows at its panel width +const REFERENCE_COLUMNS: usize = 4; + +/// The sample project with the shelf on the Materials type +fn shelf(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.shelf_tab = MATERIALS_TYPE; + harness.run_steps(4); + harness +} + +/// The plain materials in the grid's order (by name) +fn plain_materials() -> Vec<&'static SmartMaterial> { + let mut plain: Vec<_> = MATERIALS.iter().filter(|material| !material.smart).collect(); + plain.sort_by_key(|material| material.label.to_lowercase()); + plain +} + +/// A clickable node labelled `label` (its tooltip, once shown, has the same label) +fn button<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &'a str) -> egui_kittest::Node<'a> { + harness.get_all_by_label(label).next().unwrap_or_else(|| panic!("no {label}")) +} + +#[test] +fn the_default_panel_shows_the_reference_column_count() { + let harness = shelf(REFERENCE_WINDOW); + let tops: Vec = plain_materials().iter().take(REFERENCE_COLUMNS + 1).map(|material| harness.get_by_label(material.label).rect().top()).collect(); + + assert!(tops[..REFERENCE_COLUMNS].iter().all(|top| *top == tops[0]), "the first {REFERENCE_COLUMNS} tiles share a row: {tops:?}"); + assert!(tops[REFERENCE_COLUMNS] > tops[0], "the next tile starts a row: {tops:?}"); +} + +#[test] +fn a_click_on_the_picked_type_shows_every_type() { + let mut harness = shelf(REFERENCE_WINDOW); + let mask = SMART_MASKS[0].label; + assert!(harness.query_by_label(mask).is_none(), "the Materials type hides smart masks"); + + button(&harness, "Materials").click(); + harness.run_steps(3); + + assert!(harness.query_by_label(mask).is_some(), "no type picked shows smart masks too"); +} + +#[test] +fn the_search_narrows_the_picked_type_and_greys_types_without_matches() { + let mut harness = shelf(REFERENCE_WINDOW); + let material = plain_materials().into_iter().find(|material| material.label.to_lowercase().contains("rust")).unwrap(); + let mask = SMART_MASKS.iter().find(|mask| mask.label.to_lowercase().contains("rust")).unwrap(); + harness.state_mut().ui.shelf_filter = "rust".into(); + harness.state_mut().ui.shelf_tab = SMART_MASKS_TYPE; + harness.run_steps(3); + + assert!(harness.query_by_label(mask.label).is_some(), "the matching mask shows"); + assert!(harness.query_by_label(material.label).is_none(), "a matching material of another type does not"); + assert!(button(&harness, "Environments").accesskit_node().is_disabled(), "no environment matches"); + assert!(!button(&harness, "Materials").accesskit_node().is_disabled()); + + button(&harness, "Materials").click(); + harness.run_steps(3); + assert_eq!(harness.state().ui.shelf_filter, "rust", "picking a type keeps the search"); + assert!(harness.query_by_label(material.label).is_some()); +} + +#[test] +fn the_breadcrumb_arrow_picks_a_library() { + let mut harness = shelf(REFERENCE_WINDOW); + let material = plain_materials()[0].label; + + button(&harness, "Browse folders").click(); + harness.run_steps(2); + for library in ["Project", "Starter assets", "Your assets"] { + assert!(harness.query_by_label(library).is_some(), "the list offers {library}"); + } + harness.get_by_label("Project").click(); + harness.run_steps(3); + + assert_eq!(harness.state().ui.shelf_path, ["project"]); + assert!(harness.query_by_label(material).is_none(), "built-in materials are not in the project"); +} + +#[test] +fn the_thumbnail_size_menu_switches_to_the_list() { + let mut harness = shelf(REFERENCE_WINDOW); + let material = plain_materials()[0].label; + let tile_width = harness.get_by_label(material).rect().width(); + + button(&harness, "Thumbnail size").click(); + harness.run_steps(2); + harness.get_by_label_contains("List").click(); + harness.run_steps(3); + + assert_eq!(harness.state().ui.shelf_view, ShelfView::List); + assert!(harness.get_by_label(material).rect().width() > tile_width * 2.0, "a list row spans the panel"); +} + +#[test] +fn reset_query_shows_every_asset_again() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().ui.shelf_filter = "rust".into(); + harness.state_mut().ui.shelf_path = vec!["starter".into()]; + harness.run_steps(2); + + button(&harness, "Reset query").click(); + harness.run_steps(3); + + let ui = &harness.state().ui; + assert!(ui.shelf_filter.is_empty() && ui.shelf_path.is_empty()); + assert!(harness.query_by_label(SMART_MASKS[0].label).is_some(), "every type shows"); +} + +#[test] +fn refresh_reads_the_saved_brushes_again() { + let mut harness = shelf(REFERENCE_WINDOW); + let stale = vec![std::path::PathBuf::from("gone.tcbrush")]; + harness.state_mut().brushes = Some(stale.clone()); + harness.run_steps(1); + + button(&harness, "Refresh").click(); + harness.run_steps(3); + + assert_ne!(harness.state().brushes, Some(stale), "the brushes folder was read again"); + assert!(harness.query_by_label("Import resources...").is_some(), "the toolbar has the import button"); +} + +#[test] +fn a_saved_search_restores_its_query() { + let mut harness = shelf(REFERENCE_WINDOW); + button(&harness, "Saved searches").click(); + harness.state_mut().ui.shelf_filter = "rust".into(); + harness.run_steps(3); + + button(&harness, "Save the current search").click(); + harness.run_steps(2); + assert_eq!(harness.state().ui.shelf_saved_searches.len(), 1); + harness.state_mut().ui.shelf_filter.clear(); + harness.run_steps(2); + + harness.get_by_label("rust").click(); + harness.run_steps(2); + assert_eq!(harness.state().ui.shelf_filter, "rust"); + + harness.get_by_label("rust").click_secondary(); + harness.run_steps(2); + // The context menu opens last, so its Delete is the newest node with that label + harness.get_all_by_label("Delete").last().unwrap().click(); + harness.run_steps(2); + assert!(harness.state().ui.shelf_saved_searches.is_empty()); +} + +#[test] +fn filter_by_path_picks_a_folder() { + let mut harness = shelf(REFERENCE_WINDOW); + button(&harness, "Filter by path").click(); + harness.run_steps(3); + + harness.get_by_label("Starter assets").click(); + harness.run_steps(2); + + assert_eq!(harness.state().ui.shelf_path, ["starter"]); +} + +#[test] +fn a_narrow_panel_keeps_the_toolbar_and_folds_the_type_row() { + let mut harness = shelf(NARROW_WINDOW); + harness.state_mut().ui.shelf_panes.saved_searches = true; + harness.state_mut().ui.shelf_panes.filter_by_path = true; + harness.run_steps(3); + + for label in ["Refresh", "Reset query", "Import resources...", "Saved searches", "Filter by path"] { + let rect = button(&harness, label).rect(); + assert!(rect.bottom() <= NARROW_WINDOW.y, "{label} is inside the window: {rect:?}"); + } + assert!(harness.query_by_label("Filter by type").is_some(), "the type row folds into one dropdown"); + assert!(harness.query_by_label("Environments").is_none()); +} + +#[test] +fn an_environment_tile_switches_the_lighting() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().ui.shelf_tab = ENVIRONMENTS_TYPE; + harness.run_steps(3); + let shown = harness.state().session.doc.project.display.environment.clone(); + let other = ENVIRONMENTS.iter().find(|name| **name != shown).unwrap(); + + harness.get_by_label(other).click(); + harness.run_steps(2); + + assert_eq!(harness.state().session.doc.project.display.environment, *other); +} + +#[test] +fn a_saved_brush_is_a_tile_that_loads_the_preset() { + let mut harness = shelf(REFERENCE_WINDOW); + let mut saved = harness.state().session.tool.brush.clone(); + saved.spacing = (saved.spacing + 0.25).min(1.0); + let path = std::env::temp_dir().join(format!("shelf-panel-{}.tcbrush", std::process::id())); + std::fs::write(&path, serde_json::to_vec(&saved).unwrap()).unwrap(); + harness.state_mut().brushes = Some(vec![path.clone()]); + harness.state_mut().ui.shelf_tab = BRUSHES_TYPE; + harness.run_steps(3); + + harness.get_by_label(path.file_stem().unwrap().to_str().unwrap()).click(); + harness.run_steps(2); + std::fs::remove_file(&path).unwrap(); + + assert_eq!(harness.state().session.tool.brush.spacing, saved.spacing, "the click loads the saved stroke"); +} + +#[test] +fn procedurals_are_in_the_textures_type() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().ui.shelf_tab = TEXTURES_TYPE; + harness.run_steps(3); + + assert!(harness.query_by_label(ProceduralKind::ALL[0].label()).is_some()); +} From 49e9de6be509c7ec22e266324f014bed55d55176 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 07:19:33 +0000 Subject: [PATCH 19/22] Assets: saved smart materials count toward the Smart materials type and Your assets, so neither greys out while they match --- crates/ui-egui/src/shelf.rs | 88 ++++++++++++++++++-------- crates/ui-egui/tests/it/shelf_panel.rs | 27 +++++++- 2 files changed, 88 insertions(+), 27 deletions(-) diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 75958d99..9d9e3628 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -20,6 +20,11 @@ use crate::widgets::dnd_release; /// The gap between tiles in points (their sizes are [`ShelfView`]'s) const TILE_GAP: f32 = 2.0; +/// The gap after a grid or a list of rows, and the size of a hint under a header, in points +const SECTION_GAP: f32 = 6.0; +const HINT_SIZE: f32 = 10.0; +/// The name of a saved material whose file name isn't text +const SAVED_MATERIAL_NAME: &str = "material"; /// Corner radius of a tile's hover and selection highlights, in points const TILE_ROUNDING: f32 = 3.0; /// The last clicked or right-clicked tile's [`ShelfEntry::key`], kept in egui's memory under this id @@ -224,6 +229,7 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response 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); scan_brushes(app); let all = ShelfEntry::all(app); let paths = crate::shelf_folders::with_every_library(crate::shelf_folders::paths(&all)); @@ -235,9 +241,19 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let folder = app.ui.shelf_path.clone(); let picked_tab = app.ui.shelf_tab; - let applicable = crate::shelf_folders::paths(all.iter().filter(|entry| entry.matches(&filter) && crate::shelf_tabs::shows(picked_tab, entry.tab()))); + let mut applicable = crate::shelf_folders::paths(all.iter().filter(|entry| entry.matches(&filter) && crate::shelf_tabs::shows(picked_tab, entry.tab()))); let matching: Vec = all.into_iter().filter(|entry| entry.in_folder(&folder) && entry.matches(&filter)).collect(); - let counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); + let mut counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); + + // Saved smart materials list under the grid rather than as tiles, so they count apart + let in_user_library = folder.len() <= 1 && folder.first().is_none_or(|library| library == crate::shelf_entry::USER); + let saved_materials_matching = saved_materials_matching(app, &filter); + if in_user_library && let Some(smart) = TABS.iter().position(|(tab, _, _)| *tab == Tab::Smart).and_then(|smart| counts.get_mut(smart)) { + *smart += saved_materials_matching; + } + if saved_materials_matching > 0 && crate::shelf_tabs::shows(picked_tab, Tab::Smart) { + applicable.push(vec![crate::shelf_entry::USER.to_string()]); + } crate::shelf_folders::breadcrumb(app, ui, &paths); search_field(app, ui); @@ -263,7 +279,6 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { ui.separator(); } // Saved smart materials are files in the user's library, without folders of their own - let in_user_library = folder.len() <= 1 && folder.first().is_none_or(|library| library == crate::shelf_entry::USER); let saved_materials = in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Smart); grid(app, ui, &ctx, &entries, grid_rect.height(), saved_materials, &filter); }); @@ -291,6 +306,11 @@ fn grid(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entries: &[ }); } +/// How many of the user's saved smart materials match `filter` (none until the library is read) +fn saved_materials_matching(app: &TextureCraftApp, filter: &str) -> usize { + app.library.iter().flatten().filter(|path| matches(filter, &[saved_material_name(path)])).count() +} + /// The search field: a live filter on names (and categories) with a clear button while it has text fn search_field(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); @@ -332,7 +352,7 @@ pub(crate) fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { ui.spacing_mut().item_spacing = vec2(TILE_GAP, TILE_GAP); body(ui); }); - ui.add_space(6.0); + ui.add_space(SECTION_GAP); } /// The distinct categories of `items`, in order of first appearance. @@ -346,23 +366,38 @@ pub(crate) fn categories(items: &[T], category: impl Fn(&T) -> &'static str) out } -/// The user's saved smart materials (desktop library folder). +/// Read the user's saved smart materials (desktop library folder) unless they are already listed +#[cfg(not(target_arch = "wasm32"))] +fn scan_library(app: &mut TextureCraftApp) { + if app.library.is_some() { + return; + } + + let saved_material = |path: &std::path::PathBuf| path.extension().is_some_and(|extension| extension == "tcmat" || extension == MCMAT_EXT); + let mut files: Vec = + std::fs::read_dir(crate::library_dir()).map(|dir| dir.flatten().map(|entry| entry.path()).filter(saved_material).collect()).unwrap_or_default(); + files.sort(); + app.library = Some(files); +} + +#[cfg(target_arch = "wasm32")] +fn scan_library(_: &mut TextureCraftApp) {} + +/// A saved smart material's name: its file name without the extension +fn saved_material_name(path: &std::path::Path) -> &str { + path.file_stem().and_then(|stem| stem.to_str()).unwrap_or(SAVED_MATERIAL_NAME) +} + +/// The user's saved smart materials matching `filter`, as rows under the grid #[cfg(not(target_arch = "wasm32"))] fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { - let tk = Tokens::get(ui.ctx()); - if app.library.is_none() { - let mut files: Vec = std::fs::read_dir(crate::library_dir()) - .map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "tcmat" || x == MCMAT_EXT)).collect()) - .unwrap_or_default(); - files.sort(); - app.library = Some(files); - } + let tokens = Tokens::get(ui.ctx()); let files = app.library.clone().unwrap_or_default(); - let name = |f: &std::path::PathBuf| f.file_stem().and_then(|s| s.to_str()).unwrap_or("material").to_string(); - let shown: Vec<_> = files.iter().filter(|f| matches(filter, &[&name(f)])).collect(); + let shown: Vec<_> = files.iter().filter(|path| matches(filter, &[saved_material_name(path)])).collect(); if !filter.is_empty() && shown.is_empty() { return; } + ui.horizontal(|ui| { header(ui, tr("My smart materials")); if ui.small_button(ic::ARROW_CLOCKWISE).on_hover_text(tr("Rescan the library folder")).clicked() { @@ -370,26 +405,27 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { } }); if files.is_empty() { - ui.label(RichText::new(tr("Right-click a layer > Create smart material")).size(10.0).color(tk.text_dim)); + ui.label(RichText::new(tr("Right-click a layer > Create smart material")).size(HINT_SIZE).color(tokens.text_dim)); } - for f in shown { - let (label, asset) = (name(f), Asset::Library(f.display().to_string())); - // MaterialCraft materials (sent from MaterialCraft) show a graph. - let glyph = if f.extension().is_some_and(|x| x == MCMAT_EXT) { ic::GRAPH } else { ic::SPHERE }; - let r = ui.add(egui::Button::selectable(false, format!("{glyph} {label}")).sense(Sense::click_and_drag())).on_hover_ui(|ui| { + + for path in shown { + let (label, asset) = (saved_material_name(path).to_string(), Asset::Library(path.display().to_string())); + // MaterialCraft materials (sent from MaterialCraft) show a graph + let glyph = if path.extension().is_some_and(|extension| extension == MCMAT_EXT) { ic::GRAPH } else { ic::SPHERE }; + let response = ui.add(egui::Button::selectable(false, format!("{glyph} {label}")).sense(Sense::click_and_drag())).on_hover_ui(|ui| { ui.label(crate::i18n::trf( "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", - &[("file", &f.display())], + &[("file", &path.display())], )); }); - if r.drag_started() { - r.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label }); + if response.drag_started() { + response.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label }); } - if r.clicked() { + if response.clicked() { apply(app, &asset); } } - ui.add_space(6.0); + ui.add_space(SECTION_GAP); } #[cfg(target_arch = "wasm32")] diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index 94e3edd7..47c61410 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -19,6 +19,8 @@ const SMART_MASKS_TYPE: usize = 2; const BRUSHES_TYPE: usize = 4; const TEXTURES_TYPE: usize = 6; const ENVIRONMENTS_TYPE: usize = 7; +/// 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 const REFERENCE_COLUMNS: usize = 4; @@ -215,7 +217,7 @@ fn an_environment_tile_switches_the_lighting() { fn a_saved_brush_is_a_tile_that_loads_the_preset() { let mut harness = shelf(REFERENCE_WINDOW); let mut saved = harness.state().session.tool.brush.clone(); - saved.spacing = (saved.spacing + 0.25).min(1.0); + saved.spacing += SAVED_SPACING_CHANGE; let path = std::env::temp_dir().join(format!("shelf-panel-{}.tcbrush", std::process::id())); std::fs::write(&path, serde_json::to_vec(&saved).unwrap()).unwrap(); harness.state_mut().brushes = Some(vec![path.clone()]); @@ -229,6 +231,29 @@ fn a_saved_brush_is_a_tile_that_loads_the_preset() { assert_eq!(harness.state().session.tool.brush.spacing, saved.spacing, "the click loads the saved stroke"); } +#[test] +fn saved_smart_materials_keep_their_type_pickable_in_your_assets() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().library = Some(vec![std::path::PathBuf::from("Mine.tcmat")]); + harness.state_mut().ui.shelf_path = vec!["user".into()]; + harness.state_mut().ui.shelf_tab = BRUSHES_TYPE; + harness.run_steps(3); + + assert!(!button(&harness, "Smart materials").accesskit_node().is_disabled(), "a saved smart material is in Your assets"); + assert!(button(&harness, "Materials").accesskit_node().is_disabled(), "no plain material is"); +} + +#[test] +fn saved_smart_materials_are_read_whatever_the_type_and_after_a_refresh() { + let mut harness = shelf(REFERENCE_WINDOW); + assert!(harness.state().library.is_some(), "read on the Materials type"); + + button(&harness, "Refresh").click(); + harness.run_steps(2); + + assert!(harness.state().library.is_some(), "read again after a refresh"); +} + #[test] fn procedurals_are_in_the_textures_type() { let mut harness = shelf(REFERENCE_WINDOW); From 3bb40ccce7e82c6514df6d445f4abe2476d1e1a2 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 07:19:33 +0000 Subject: [PATCH 20/22] Assets: tiles build their hover preview only on hover, read the selection once per frame and search each asset once --- crates/ui-egui/src/shelf.rs | 61 ++++++++++++++------------ crates/ui-egui/src/shelf_entry.rs | 26 +++++------ crates/ui-egui/src/shelf_folders.rs | 4 +- crates/ui-egui/src/shelf_panes.rs | 5 ++- crates/ui-egui/src/shelf_tabs.rs | 4 +- crates/ui-egui/tests/it/shelf_panel.rs | 2 +- 6 files changed, 55 insertions(+), 47 deletions(-) diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 9d9e3628..0209b61c 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -27,7 +27,7 @@ const HINT_SIZE: f32 = 10.0; const SAVED_MATERIAL_NAME: &str = "material"; /// Corner radius of a tile's hover and selection highlights, in points const TILE_ROUNDING: f32 = 3.0; -/// The last clicked or right-clicked tile's [`ShelfEntry::key`], kept in egui's memory under this id +/// The last clicked or right-clicked tile's [`ShelfEntry::identity`], kept in egui's memory under this id const SELECTED_TILE: &str = "shelf_selected_tile"; /// The outline widths of the selected tile and of the one in use (the brush's alpha, the shown environment), in points const SELECTED_OUTLINE_WIDTH: f32 = 1.5; @@ -241,8 +241,9 @@ 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 applicable = crate::shelf_folders::paths(all.iter().filter(|entry| entry.matches(&filter) && crate::shelf_tabs::shows(picked_tab, entry.tab()))); - let matching: Vec = all.into_iter().filter(|entry| entry.in_folder(&folder) && entry.matches(&filter)).collect(); + let searched: Vec = all.into_iter().filter(|entry| entry.matches(&filter)).collect(); + let mut applicable = crate::shelf_folders::paths(searched.iter().filter(|entry| crate::shelf_tabs::shows(picked_tab, entry.tab()))); + let matching: Vec = searched.into_iter().filter(|entry| entry.in_folder(&folder)).collect(); let mut counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); // Saved smart materials list under the grid rather than as tiles, so they count apart @@ -289,6 +290,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { /// The tiles of `entries` in a scroll area `height` high, then the saved smart materials when `saved_materials` fn grid(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entries: &[ShelfEntry], height: f32, saved_materials: bool, filter: &str) { let view = app.ui.shelf_view; + let selected: Option<(String, String)> = ctx.data(|data| data.get_temp(egui::Id::unique(SELECTED_TILE))); egui::ScrollArea::vertical() .id_salt("shelf_scroll") .auto_shrink([false, false]) @@ -297,7 +299,8 @@ fn grid(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entries: &[ .show(ui, |ui| { tiles(ui, |ui| { for entry in entries { - entry_tile(app, ui, ctx, entry, view); + let is_selected = selected.as_ref().is_some_and(|(kind, id)| entry.identity() == (kind.as_str(), id.as_str())); + entry_tile(app, ui, ctx, entry, view, is_selected); } }); if saved_materials { @@ -313,9 +316,9 @@ fn saved_materials_matching(app: &TextureCraftApp, filter: &str) -> usize { /// The search field: a live filter on names (and categories) with a clear button while it has text fn search_field(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); ui.horizontal(|ui| { - ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tk.text_dim)); + ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tokens.text_dim)); let clear_width = if app.ui.shelf_filter.is_empty() { 0.0 } else { ui.spacing().interact_size.y + ui.spacing().item_spacing.x }; let field = egui::TextEdit::singleline(&mut app.ui.shelf_filter).hint_text(tr("Search")).desired_width(ui.available_width() - clear_width); ui.add(field); @@ -450,21 +453,24 @@ fn scan_brushes(app: &mut TextureCraftApp) { #[cfg(target_arch = "wasm32")] fn scan_brushes(_: &mut TextureCraftApp) {} -/// The tile of `entry`: a click applies it, an image resource has a context menu -fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry, view: ShelfView) { +/// The tile of `entry`, outlined when `selected`: a click applies it, an image resource has a context 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 - let (Some(preview), texture) = (entry.preview(app), entry.thumbnail(app, ctx)) else { return }; + if let ShelfEntry::Image(name) = entry + && !app.session.images.contains_key(name) + { + return; + } + let texture = entry.thumbnail(app, ctx); let asset = entry.asset(); - let response = tile_in_view(ui, &mut app.thumbs, texture.as_ref(), || preview, entry.label(), asset.as_ref(), view); + let session = &app.session; + let response = tile_in_view(ui, &mut app.thumbs, texture.as_ref(), || entry.preview(session), entry.label(), asset.as_ref(), view); - let selected_id = egui::Id::unique(SELECTED_TILE); - let key = entry.key(); - let selected = ctx.data(|data| data.get_temp::(selected_id)).is_some_and(|selected| selected == key); if selected || entry.in_use(app) { - let tk = Tokens::get(ctx); + let tokens = Tokens::get(ctx); let width = if selected { SELECTED_OUTLINE_WIDTH } else { IN_USE_OUTLINE_WIDTH }; - ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(width, tk.accent), egui::StrokeKind::Inside); + ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(width, tokens.accent), egui::StrokeKind::Inside); } if entry.includes_randomness() { @@ -472,7 +478,8 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry } if response.clicked() || response.secondary_clicked() { - ctx.data_mut(|data| data.insert_temp(selected_id, key)); + let (kind, id) = entry.identity(); + ctx.data_mut(|data| data.insert_temp(egui::Id::unique(SELECTED_TILE), (kind.to_string(), id.to_string()))); } if response.clicked() { entry.activate(app); @@ -501,20 +508,20 @@ pub(crate) fn tile( label: &str, drag: Option<&Asset>, ) -> egui::Response { - tile_in_view(ui, thumbs, texture, preview, label, drag, ShelfView::Medium) + tile_in_view(ui, thumbs, texture, || Some(preview()), label, drag, ShelfView::Medium) } -/// [`tile`] at `view`'s size: a grid tile with the name under the thumbnail, or a list row with it beside +/// [`tile`] at `view`'s size: a grid tile with the name under the thumbnail, or a list row with it beside; `preview` runs on hover fn tile_in_view( ui: &mut Ui, thumbs: &mut Thumbs, texture: Option<&egui::TextureHandle>, - preview: impl FnOnce() -> ShelfPreview, + preview: impl FnOnce() -> Option, label: &str, drag: Option<&Asset>, view: ShelfView, ) -> egui::Response { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); let sense = if drag.is_some() { Sense::click_and_drag() } else { Sense::click() }; let (rect, response) = ui.allocate_exact_size(view.tile_size(ui.available_width()), sense); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); @@ -526,21 +533,21 @@ fn tile_in_view( let painter = ui.painter(); if response.hovered() || response.dragged() { - painter.rect_filled(rect, TILE_ROUNDING, tk.row_hover); + painter.rect_filled(rect, TILE_ROUNDING, tokens.row_hover); } let image_rect = view.thumbnail_rect(rect); - thumbnail(painter, texture, image_rect, &tk); + thumbnail(painter, texture, image_rect, &tokens); if view.name_beside() { let left = image_rect.right() + crate::shelf_view::LIST_NAME_GAP; - let galley = painter.layout_job(one_line(label, rect.right() - left - LABEL_MARGIN, tk.text)); - painter.galley(egui::pos2(left, rect.center().y - galley.size().y * 0.5), galley, tk.text); + let galley = painter.layout_job(one_line(label, rect.right() - left - LABEL_MARGIN, tokens.text)); + painter.galley(egui::pos2(left, rect.center().y - galley.size().y * 0.5), galley, tokens.text); } else { - let galley = painter.layout_job(one_line(label, rect.width() - LABEL_MARGIN, tk.text)); - painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tk.text); + let galley = painter.layout_job(one_line(label, rect.width() - LABEL_MARGIN, tokens.text)); + painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tokens.text); } - let big = if response.hovered() { big_preview(ui, thumbs, preview) } else { None }; + let big = if response.hovered() { preview().and_then(|preview| big_preview(ui, thumbs, || preview)) } else { None }; response.on_hover_ui(|ui| hover_preview(ui, texture, big.as_ref(), label)) } diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index e9bbcbec..cad9e30a 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -3,6 +3,7 @@ use std::path::PathBuf; use serde_json::json; +use texturecraft_engine::Session; use texturecraft_engine::core::ProceduralKind; use texturecraft_engine::core::project::ENVIRONMENTS; use texturecraft_engine::filter_lib::{FILTERS, FilterDef}; @@ -33,7 +34,6 @@ pub(crate) const USER: &str = "user"; pub(crate) const LIBRARIES: [(&str, &str); 3] = [(PROJECT, "Project"), (STARTER, "Starter assets"), (USER, "Your assets")]; /// A shelf tile's asset -#[derive(Clone)] pub(crate) enum ShelfEntry { Material(&'static SmartMaterial), SmartMask(&'static SmartMask), @@ -81,17 +81,17 @@ impl ShelfEntry { } /// The asset's identity across frames: its kind and id - pub(crate) fn key(&self) -> String { + pub(crate) fn identity(&self) -> (&'static str, &str) { match self { - ShelfEntry::Material(material) => format!("material:{}", material.id), - ShelfEntry::SmartMask(mask) => format!("mask:{}", mask.id), - ShelfEntry::Filter(filter) => format!("filter:{}", filter.id), - ShelfEntry::Brush(preset) => format!("brush:{}", preset.id), - ShelfEntry::SavedBrush(path) => format!("saved-brush:{}", path.display()), - ShelfEntry::Alpha(alpha) => format!("alpha:{}", alpha.id), - ShelfEntry::Procedural(kind) => format!("procedural:{kind:?}"), - ShelfEntry::Environment(name) => format!("environment:{name}"), - ShelfEntry::Image(name) => format!("image:{name}"), + ShelfEntry::Material(material) => ("material", material.id), + ShelfEntry::SmartMask(mask) => ("mask", mask.id), + ShelfEntry::Filter(filter) => ("filter", filter.id), + ShelfEntry::Brush(preset) => ("brush", preset.id), + ShelfEntry::SavedBrush(path) => ("saved-brush", path.to_str().unwrap_or_default()), + ShelfEntry::Alpha(alpha) => ("alpha", &alpha.id), + ShelfEntry::Procedural(kind) => ("procedural", kind.label()), + ShelfEntry::Environment(name) => ("environment", name), + ShelfEntry::Image(name) => ("image", name), } } @@ -168,7 +168,7 @@ impl ShelfEntry { } /// What the hover popup renders; None for an image that is gone - pub(crate) fn preview(&self, app: &TextureCraftApp) -> Option { + pub(crate) fn preview(&self, session: &Session) -> Option { Some(match self { ShelfEntry::Material(material) => ShelfPreview::material(material.id), ShelfEntry::SmartMask(mask) => ShelfPreview::SmartMask(mask.id), @@ -178,7 +178,7 @@ impl ShelfEntry { ShelfEntry::Alpha(alpha) => ShelfPreview::Alpha(alpha), ShelfEntry::Procedural(kind) => ShelfPreview::Procedural(*kind), ShelfEntry::Environment(name) => ShelfPreview::Environment(name), - ShelfEntry::Image(name) => ShelfPreview::Image(name.clone(), app.session.images.get(name).cloned()?), + ShelfEntry::Image(name) => ShelfPreview::Image(name.clone(), session.images.get(name).cloned()?), }) } diff --git a/crates/ui-egui/src/shelf_folders.rs b/crates/ui-egui/src/shelf_folders.rs index 0f029033..317d109b 100644 --- a/crates/ui-egui/src/shelf_folders.rs +++ b/crates/ui-egui/src/shelf_folders.rs @@ -53,7 +53,7 @@ pub(crate) fn name(level: usize, segment: &str) -> &str { /// "› All libraries › …": each arrow lists the folders at its level, the names are plain text, a last arrow lists the folders inside pub(crate) fn breadcrumb(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec]) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); let size = ui.spacing().interact_size.y * ARROW_SCALE; let mut picked: Option> = None; ui.horizontal(|ui| { @@ -83,7 +83,7 @@ pub(crate) fn breadcrumb(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec tr("All libraries"), None => continue, }; - ui.label(RichText::new(shown).strong().color(tk.text_strong)); + ui.label(RichText::new(shown).strong().color(tokens.text_strong)); } }); if let Some(path) = picked { diff --git a/crates/ui-egui/src/shelf_panes.rs b/crates/ui-egui/src/shelf_panes.rs index dee1eb62..9368bddc 100644 --- a/crates/ui-egui/src/shelf_panes.rs +++ b/crates/ui-egui/src/shelf_panes.rs @@ -110,9 +110,9 @@ fn folders(ui: &mut Ui, paths: &[Vec], prefix: &[String], current: &[Str /// A pane's caption with a button at its right fn header(ui: &mut Ui, title: &str, button: impl FnOnce(&mut Ui)) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); ui.horizontal(|ui| { - ui.label(RichText::new(title.to_uppercase()).size(HEADER_SIZE).color(tk.text_dim)); + ui.label(RichText::new(title.to_uppercase()).size(HEADER_SIZE).color(tokens.text_dim)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), button); }); } @@ -131,6 +131,7 @@ fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) { if ui.selectable_label(everything, tr("All")).clicked() { crate::shelf_toolbar::reset_query(app); } + let mut deleted = None; for (i, saved) in app.ui.shelf_saved_searches.iter().enumerate() { let same = saved.filter == current.filter && saved.tab == current.tab && saved.path == current.path; diff --git a/crates/ui-egui/src/shelf_tabs.rs b/crates/ui-egui/src/shelf_tabs.rs index 4e2c3e07..cb620500 100644 --- a/crates/ui-egui/src/shelf_tabs.rs +++ b/crates/ui-egui/src/shelf_tabs.rs @@ -49,9 +49,9 @@ fn collapsed(ui: &mut Ui, picked: &mut usize, counts: &[usize], size: f32) { let response = icon_dropdown_button(ui, egui_phosphor::regular::FUNNEL_SIMPLE, tr("Filter by type"), filtering, size); let response = response.on_hover_text(tr("Filter by type")); if filtering { - let tk = crate::theme::Tokens::get(ui.ctx()); + let tokens = crate::theme::Tokens::get(ui.ctx()); let dot = response.rect.left_top() + vec2(size - FILTER_DOT_RADIUS, FILTER_DOT_RADIUS); - ui.painter().circle_filled(dot, FILTER_DOT_RADIUS, tk.accent); + ui.painter().circle_filled(dot, FILTER_DOT_RADIUS, tokens.accent); } egui::Popup::menu(&response).show(|ui| { diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index 47c61410..e241293f 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -13,7 +13,7 @@ use texturecraft_ui_egui::shelf_view::ShelfView; const REFERENCE_WINDOW: egui::Vec2 = egui::vec2(1920.0, 1032.0); /// A window whose default Assets panel is too narrow for the full type row const NARROW_WINDOW: egui::Vec2 = egui::vec2(1100.0, 1032.0); -/// The shelf's Materials and Smart masks types +/// The types' positions in the shelf's type row (its table is crate-private) const MATERIALS_TYPE: usize = 0; const SMART_MASKS_TYPE: usize = 2; const BRUSHES_TYPE: usize = 4; From df2c0b81db9e9eca4f714a944ff5ec7f72b7a9b1 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 15 Nov 2026 21:09:57 +0000 Subject: [PATCH 21/22] Auto: Reconcile Assets shelf with main and repair presets Keep main's shared translation integration while merging the Assets layout. Guard preset overwrites, restore legacy tab selection, filter unavailable images, and render saved image alphas. Deduplicate folder paths before allocating and render only visible saved-search rows. Validated with release UI tests, clippy, wasm, layers, panic_hunt, and offscreen window snapshots. --- crates/ui-egui/src/brush_preset_save.rs | 126 +++++++++++++++++++--- crates/ui-egui/src/docking.rs | 19 +++- crates/ui-egui/src/preview_image.rs | 71 ++++++++----- crates/ui-egui/src/shelf.rs | 32 ++++-- crates/ui-egui/src/shelf_entry.rs | 7 +- crates/ui-egui/src/shelf_folders.rs | 23 ++-- crates/ui-egui/src/shelf_panes.rs | 34 +++--- crates/ui-egui/src/shelf_preview.rs | 38 +++++-- crates/ui-egui/src/shelf_tabs.rs | 1 + crates/ui-egui/src/state.rs | 2 + crates/ui-egui/src/thumbs.rs | 130 ++++++++++++++++++++++- crates/ui-egui/src/ui_state_store.rs | 69 +++++++++++- crates/ui-egui/tests/it/shelf_panel.rs | 52 +++++++++ crates/ui-egui/tests/it/split_divider.rs | 20 ++++ 14 files changed, 540 insertions(+), 84 deletions(-) diff --git a/crates/ui-egui/src/brush_preset_save.rs b/crates/ui-egui/src/brush_preset_save.rs index 1372e0e5..f8d76d78 100644 --- a/crates/ui-egui/src/brush_preset_save.rs +++ b/crates/ui-egui/src/brush_preset_save.rs @@ -2,6 +2,7 @@ use egui::Ui; use serde_json::json; +use std::path::Path; use texturecraft_engine::brush_preset_cmds::BRUSH_EXT; use crate::TextureCraftApp; @@ -13,24 +14,125 @@ const NAME_WIDTH: f32 = 110.0; /// A name field and a button that saves the current brush under that name pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui) { let dir = crate::user_dir("brushes"); + let name_id = ui.make_persistent_id("brush_preset_name"); + let confirm_id = ui.make_persistent_id("brush_preset_overwrite"); + let mut new_name: String = ui.data_mut(|data| data.get_temp(name_id)).unwrap_or_default(); + let mut pending_path: Option = ui.data_mut(|data| data.get_temp(confirm_id)); + ui.horizontal(|ui| { - let name_id = ui.make_persistent_id("brush_preset_name"); - let mut new_name: String = ui.data_mut(|data| data.get_temp(name_id)).unwrap_or_default(); ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(NAME_WIDTH)); - let file = texturecraft_engine::formats::export::sanitize_file_stem(new_name.trim()); if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() { - let path = dir.join(format!("{file}.{BRUSH_EXT}")); - // A folder that can't be made fails the save, which reports it - let _ = std::fs::create_dir_all(&dir); - if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_some() { - new_name.clear(); - // Saving over a preset keeps its file name, so its tile must redraw - app.brushes = None; - app.thumbs.forget_saved_files(); + let path = dir.join(format!("{}.{BRUSH_EXT}", preset_file_stem(new_name.trim()))); + match std::fs::symlink_metadata(&path) { + Ok(_) => pending_path = Some(path), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + if save_brush(app, &dir, &path) { + new_name.clear(); + } + } + Err(_) => pending_path = Some(path), } } + }); - ui.data_mut(|data| data.insert_temp(name_id, new_name)); + if let Some(path) = pending_path.clone() { + let mut replace = false; + let mut cancel = false; + egui::Window::new(tr("Replace")) + .id(ui.make_persistent_id("brush_preset_replace_dialog")) + .collapsible(false) + .resizable(false) + .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO) + .show(ui.ctx(), |ui| { + ui.label(path.file_name().and_then(|name| name.to_str()).unwrap_or_default()); + ui.horizontal(|ui| { + replace = ui.button(tr("Replace")).clicked(); + cancel = ui.button(tr("Cancel")).clicked(); + }); + }); + if replace { + if save_brush(app, &dir, &path) { + new_name.clear(); + } + pending_path = None; + } else if cancel { + pending_path = None; + } + } + + ui.data_mut(|data| { + data.insert_temp(name_id, new_name); + data.insert_temp(confirm_id, pending_path); }); } + +/// Preserve Unicode names and encode filename punctuation without collisions +fn preset_file_stem(name: &str) -> String { + let mut stem = String::new(); + + // Six digits cover every Unicode scalar and separate adjacent escapes + for character in name.chars() { + if character.is_alphanumeric() || character == '-' || character == '_' || character == ' ' { + stem.push(character); + } else { + stem.push_str(&format!("~{:06X}", character as u32)); + } + } + let uppercase = stem.to_ascii_uppercase(); + if matches!( + uppercase.as_str(), + "CON" + | "PRN" + | "AUX" + | "NUL" + | "COM1" + | "COM2" + | "COM3" + | "COM4" + | "COM5" + | "COM6" + | "COM7" + | "COM8" + | "COM9" + | "LPT1" + | "LPT2" + | "LPT3" + | "LPT4" + | "LPT5" + | "LPT6" + | "LPT7" + | "LPT8" + | "LPT9" + ) { + stem.insert_str(0, "brush-"); + } + stem +} + +/// Save a preset and invalidate cached tiles only when the write succeeds +fn save_brush(app: &mut TextureCraftApp, dir: &Path, path: &Path) -> bool { + // A folder that cannot be made is reported by the save command + let _ = std::fs::create_dir_all(dir); + if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_none() { + return false; + } + + app.brushes = None; + app.thumbs.forget_saved_files(); + true +} + +#[cfg(test)] +mod tests { + use super::preset_file_stem; + + #[test] + fn distinct_unicode_brush_names_have_distinct_safe_file_stems() { + assert_ne!(preset_file_stem("水彩"), preset_file_stem("油画")); + assert_ne!(preset_file_stem("a/b"), preset_file_stem("a~00002Fb")); + assert_eq!(preset_file_stem("水彩"), "水彩"); + assert!(!preset_file_stem("a/b").contains('/')); + assert_eq!(preset_file_stem("CON"), "brush-CON"); + } +} diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 1b6e9b2a..d5061e17 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -136,14 +136,25 @@ fn split(axis: SplitAxis, size: SplitSize, first: Node, second: Node Workspace { use Panel::*; + + // The Assets split keeps four tiles visible at the reference window width + const ASSETS_SPLIT_RATIO: f32 = 0.16; + const VIEWPORT_SPLIT_RATIO: f32 = 0.80; + const TEXTURE_SET_SPLIT_RATIO: f32 = 0.125; + const LAYERS_SPLIT_RATIO: f32 = 0.57; + let column = split( SplitAxis::Vertical, - SplitSize::Ratio(0.125), + SplitSize::Ratio(TEXTURE_SET_SPLIT_RATIO), tabs(&[TextureSetList]), - split(SplitAxis::Vertical, SplitSize::Ratio(0.57), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])), + split(SplitAxis::Vertical, SplitSize::Ratio(LAYERS_SPLIT_RATIO), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])), + ); + let root = split( + SplitAxis::Horizontal, + SplitSize::Ratio(ASSETS_SPLIT_RATIO), + tabs(&[Assets]), + split(SplitAxis::Horizontal, SplitSize::Ratio(VIEWPORT_SPLIT_RATIO), tabs(&[Viewport]), column), ); - let root = - split(SplitAxis::Horizontal, SplitSize::Ratio(0.16), tabs(&[Assets]), split(SplitAxis::Horizontal, SplitSize::Ratio(0.80), tabs(&[Viewport]), column)); let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() }); for panel in Panel::ALL { diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs index 16709385..7e6469d6 100644 --- a/crates/ui-egui/src/preview_image.rs +++ b/crates/ui-egui/src/preview_image.rs @@ -153,46 +153,69 @@ pub fn image_preview(img: &ImageRes, size: usize) -> ColorImage { preview } -/// Preview the brush along an S curve in an `n`-pixel square -pub fn stroke_preview(b: &BrushSettings, n: usize) -> ColorImage { - let library = b.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); - let radius = n as f32 * 0.11; - let shape = Shape { alpha: b.alpha, image: None, library, level: 0 }.at_radius(radius); - let curve = |t: f32| (n as f32 * (0.15 + 0.7 * t), n as f32 * (0.5 - 0.22 * (t * std::f32::consts::TAU).sin())); - let mut cover = vec![0f32; n * n]; - // Stable jitter keeps the preview reproducible - let rnd = |i: u32, k: u32| (i.wrapping_mul(0x9E37_79B9) ^ k.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32; - let step = (b.spacing * 2.0 * radius).max(0.5); +/// Preview the brush along an S curve in a `size_px` square +pub fn stroke_preview(brush: &BrushSettings, size_px: usize, image: Option<&ImageRes>) -> ColorImage { + // Leave room around the S curve and cap work for a single preview + const STROKE_RADIUS_FRACTION: f32 = 0.11; + const CURVE_SAMPLE_STEP: f32 = 0.002; + const MIN_STAMP_SPACING_PX: f32 = 0.5; + const MAX_STAMPS: u32 = 2000; + const CURVE_HORIZONTAL_INSET: f32 = 0.15; + const CURVE_HORIZONTAL_SPAN: f32 = 0.7; + const CURVE_WAVE_AMPLITUDE: f32 = 0.22; + + let library = brush.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); + let radius = size_px as f32 * STROKE_RADIUS_FRACTION; + let shape = Shape { alpha: brush.alpha, image, library, level: 0 }.at_radius(radius); + + // The horizontal inset and vertical wave keep the S curve inside the swatch + let curve = |t: f32| { + ( + size_px as f32 * (CURVE_HORIZONTAL_INSET + CURVE_HORIZONTAL_SPAN * t), + size_px as f32 * (0.5 - CURVE_WAVE_AMPLITUDE * (t * std::f32::consts::TAU).sin()), + ) + }; + let mut cover = vec![0f32; size_px * size_px]; + + // Odd multipliers decorrelate reproducible jitter across stamps and channels + let jitter_sample = |stamp_index: u32, channel: u32| { + (stamp_index.wrapping_mul(0x9E37_79B9) ^ channel.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32 + }; + let step = (brush.spacing * 2.0 * radius).max(MIN_STAMP_SPACING_PX); let (mut t, mut travelled, mut i) = (0.0f32, step, 0u32); let mut last = curve(0.0); - while t <= 1.0 && i < 2000 { + + while t <= 1.0 && i < MAX_STAMPS { let p = curve(t); travelled += (p.0 - last.0).hypot(p.1 - last.1); last = p; - t += 0.002; + t += CURVE_SAMPLE_STEP; if travelled < step { continue; } travelled = 0.0; i += 1; - let r = radius * (1.0 - b.jitter_size * rnd(i, 1)); - let tangent = if b.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 }; - let angle = b.angle.to_radians() + tangent + b.jitter_angle * std::f32::consts::TAU * rnd(i, 2); - let (cx, cy) = (p.0 + b.jitter_position * radius * (rnd(i, 3) * 2.0 - 1.0), p.1 + b.jitter_position * radius * (rnd(i, 4) * 2.0 - 1.0)); - let flow = b.flow * (1.0 - b.jitter_flow * rnd(i, 5)); + let stamp_radius = radius * (1.0 - brush.jitter_size * jitter_sample(i, 1)); + let tangent = if brush.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 }; + let angle = brush.angle.to_radians() + tangent + brush.jitter_angle * std::f32::consts::TAU * jitter_sample(i, 2); + let (cx, cy) = ( + p.0 + brush.jitter_position * radius * (jitter_sample(i, 3) * 2.0 - 1.0), + p.1 + brush.jitter_position * radius * (jitter_sample(i, 4) * 2.0 - 1.0), + ); + let flow = brush.flow * (1.0 - brush.jitter_flow * jitter_sample(i, 5)); let (sin, cos) = angle.sin_cos(); - let (x0, x1) = ((cx - r).floor().max(0.0) as usize, ((cx + r).ceil() as usize).min(n)); - let (y0, y1) = ((cy - r).floor().max(0.0) as usize, ((cy + r).ceil() as usize).min(n)); + let (x0, x1) = ((cx - stamp_radius).floor().max(0.0) as usize, ((cx + stamp_radius).ceil() as usize).min(size_px)); + let (y0, y1) = ((cy - stamp_radius).floor().max(0.0) as usize, ((cy + stamp_radius).ceil() as usize).min(size_px)); for y in y0..y1 { for x in x0..x1 { - let (dx, dy) = ((x as f32 + 0.5 - cx) / r, (cy - y as f32 - 0.5) / r); - let a = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, b.hardness, i) * flow; - let c = &mut cover[y * n + x]; - *c = 1.0 - (1.0 - *c) * (1.0 - a.clamp(0.0, 1.0)); + let (dx, dy) = ((x as f32 + 0.5 - cx) / stamp_radius, (cy - y as f32 - 0.5) / stamp_radius); + let alpha = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, brush.hardness, i) * flow; + let coverage = &mut cover[y * size_px + x]; + *coverage = 1.0 - (1.0 - *coverage) * (1.0 - alpha.clamp(0.0, 1.0)); } } } - ColorImage::new([n, n], cover.into_iter().map(|v| Color32::from_gray((v * b.opacity * 255.0 + 0.5) as u8)).collect()) + ColorImage::new([size_px, size_px], cover.into_iter().map(|v| Color32::from_gray((v * brush.opacity * 255.0 + 0.5) as u8)).collect()) } /// Environment `name`'s panorama across a `size²` swatch, transparent above and below diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 0209b61c..c32de5f6 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -20,8 +20,12 @@ use crate::widgets::dnd_release; /// The gap between tiles in points (their sizes are [`ShelfView`]'s) const TILE_GAP: f32 = 2.0; -/// The gap after a grid or a list of rows, and the size of a hint under a header, in points +/// The gap after a grid or a list of rows, in points const SECTION_GAP: f32 = 6.0; +/// The gap between the type row and asset grid, in points +const TYPE_GRID_GAP: f32 = 4.0; +/// The saved material hint's font size, in points +#[cfg(not(target_arch = "wasm32"))] const HINT_SIZE: f32 = 10.0; /// The name of a saved material whose file name isn't text const SAVED_MATERIAL_NAME: &str = "material"; @@ -121,7 +125,7 @@ pub fn apply(app: &mut TextureCraftApp, asset: &Asset) { && content && let Some(name) = unpainted_paint_layer(app) { - // Otherwise the filter seems to do nothing: it has nothing to change yet. + // Otherwise the filter seems to do nothing: it has nothing to change yet app.toast(trf("\"{layer}\" has no paint yet: the filter changes what you paint on it.", &[("layer", &name)]), false); } return; @@ -259,7 +263,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { crate::shelf_folders::breadcrumb(app, ui, &paths); search_field(app, ui); crate::shelf_tabs::row(app, ui, &counts, crate::shelf_view::menu); - ui.add_space(4.0); + ui.add_space(TYPE_GRID_GAP); let tab = app.ui.shelf_tab; let shown_tab = TABS.get(tab).map(|(shown, _, _)| *shown); @@ -279,6 +283,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { }); ui.separator(); } + // Saved smart materials are files in the user's library, without folders of their own let saved_materials = in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Smart); grid(app, ui, &ctx, &entries, grid_rect.height(), saved_materials, &filter); @@ -413,6 +418,7 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { for path in shown { let (label, asset) = (saved_material_name(path).to_string(), Asset::Library(path.display().to_string())); + // MaterialCraft materials (sent from MaterialCraft) show a graph let glyph = if path.extension().is_some_and(|extension| extension == MCMAT_EXT) { ic::GRAPH } else { ic::SPHERE }; let response = ui.add(egui::Button::selectable(false, format!("{glyph} {label}")).sense(Sense::click_and_drag())).on_hover_ui(|ui| { @@ -465,7 +471,18 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry let texture = entry.thumbnail(app, ctx); let asset = entry.asset(); let session = &app.session; - let response = tile_in_view(ui, &mut app.thumbs, texture.as_ref(), || entry.preview(session), entry.label(), asset.as_ref(), view); + let response = tile_in_view( + ui, + &mut app.thumbs, + texture.as_ref(), + |thumbs| match entry { + ShelfEntry::SavedBrush(path) => Some(thumbs.saved_brush_preview(path, &session.images)), + _ => entry.preview(session), + }, + entry.label(), + asset.as_ref(), + view, + ); if selected || entry.in_use(app) { let tokens = Tokens::get(ctx); @@ -508,7 +525,7 @@ pub(crate) fn tile( label: &str, drag: Option<&Asset>, ) -> egui::Response { - tile_in_view(ui, thumbs, texture, || Some(preview()), label, drag, ShelfView::Medium) + tile_in_view(ui, thumbs, texture, |_| Some(preview()), label, drag, ShelfView::Medium) } /// [`tile`] at `view`'s size: a grid tile with the name under the thumbnail, or a list row with it beside; `preview` runs on hover @@ -516,7 +533,7 @@ fn tile_in_view( ui: &mut Ui, thumbs: &mut Thumbs, texture: Option<&egui::TextureHandle>, - preview: impl FnOnce() -> Option, + preview: impl FnOnce(&mut Thumbs) -> Option, label: &str, drag: Option<&Asset>, view: ShelfView, @@ -547,7 +564,7 @@ fn tile_in_view( painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tokens.text); } - let big = if response.hovered() { preview().and_then(|preview| big_preview(ui, thumbs, || preview)) } else { None }; + let big = if response.hovered() { preview(thumbs).and_then(|preview| big_preview(ui, thumbs, || preview)) } else { None }; response.on_hover_ui(|ui| hover_preview(ui, texture, big.as_ref(), label)) } @@ -628,6 +645,7 @@ mod tests { let mut output = egui::Context::default().run_ui(egui::RawInput::default(), |ui| { laid_out = Some(ui.painter().layout_job(one_line("Steel Painted Rust Leaks Extra", width, Color32::WHITE))); }); + // The font atlas upload is not under test output.textures_delta.clear(); let galley = laid_out.unwrap(); diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index cad9e30a..2ea615a6 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -62,7 +62,8 @@ impl ShelfEntry { .chain(ProceduralKind::ALL.into_iter().map(ShelfEntry::Procedural)) .chain(ENVIRONMENTS.into_iter().map(ShelfEntry::Environment)); let saved = app.brushes.iter().flatten().cloned().map(ShelfEntry::SavedBrush); - built_in.chain(saved).chain(app.session.doc.resources.keys().cloned().map(ShelfEntry::Image)).collect() + let images = app.session.doc.resources.keys().filter(|name| app.session.images.contains_key(*name)).cloned().map(ShelfEntry::Image); + built_in.chain(saved).chain(images).collect() } /// The tab that lists the asset @@ -156,7 +157,7 @@ impl ShelfEntry { ShelfEntry::SmartMask(mask) => app.thumbs.smart_mask(ctx, mask.id), ShelfEntry::Filter(filter) => app.thumbs.filter(ctx, filter.id), ShelfEntry::Brush(preset) => app.thumbs.brush_preset(ctx, preset), - ShelfEntry::SavedBrush(path) => app.thumbs.saved_brush(ctx, path), + ShelfEntry::SavedBrush(path) => app.thumbs.saved_brush(ctx, path, &app.session.images), ShelfEntry::Alpha(alpha) => app.thumbs.alpha(ctx, alpha), ShelfEntry::Procedural(kind) => app.thumbs.procedural(ctx, *kind), ShelfEntry::Environment(name) => app.thumbs.environment(ctx, name), @@ -174,7 +175,7 @@ impl ShelfEntry { ShelfEntry::SmartMask(mask) => ShelfPreview::SmartMask(mask.id), ShelfEntry::Filter(filter) => ShelfPreview::Filter(filter.id), ShelfEntry::Brush(preset) => ShelfPreview::Brush(preset), - ShelfEntry::SavedBrush(path) => ShelfPreview::SavedBrush(path.clone()), + ShelfEntry::SavedBrush(path) => ShelfPreview::saved_brush(path, &session.images), ShelfEntry::Alpha(alpha) => ShelfPreview::Alpha(alpha), ShelfEntry::Procedural(kind) => ShelfPreview::Procedural(*kind), ShelfEntry::Environment(name) => ShelfPreview::Environment(name), diff --git a/crates/ui-egui/src/shelf_folders.rs b/crates/ui-egui/src/shelf_folders.rs index 317d109b..e581f480 100644 --- a/crates/ui-egui/src/shelf_folders.rs +++ b/crates/ui-egui/src/shelf_folders.rs @@ -1,5 +1,7 @@ //! The shelf's library folders ([`ShelfEntry::path`]) for the breadcrumb above the search and the Filter by path tree +use std::collections::BTreeSet; + use egui::{RichText, Ui}; use crate::TextureCraftApp; @@ -13,10 +15,9 @@ const ARROW_SCALE: f32 = 0.8; /// The folder paths of `entries`, each a library id then folder names pub(crate) fn paths<'a>(entries: impl IntoIterator) -> Vec> { - let mut paths: Vec> = entries.into_iter().map(|entry| entry.path().into_iter().map(str::to_string).collect()).collect(); - paths.sort(); - paths.dedup(); - paths + let unique_paths: BTreeSet> = entries.into_iter().map(ShelfEntry::path).collect(); + + unique_paths.into_iter().map(|segments| segments.into_iter().map(str::to_string).collect()).collect() } /// `paths` and every library, even one with nothing in it (the picker always lists them all) @@ -29,18 +30,19 @@ pub(crate) fn with_every_library(mut paths: Vec>) -> Vec /// The folders right below `prefix` (libraries in their usual order, folders by name) pub(crate) fn children(paths: &[Vec], prefix: &[String]) -> Vec { - let mut out: Vec = Vec::new(); + let mut children = Vec::new(); for path in paths.iter().filter(|path| path.len() > prefix.len() && path.starts_with(prefix)) { - if let Some(next) = path.get(prefix.len()) - && !out.contains(next) + if let Some(child) = path.get(prefix.len()) + && !children.contains(child) { - out.push(next.clone()); + children.push(child.clone()); } } + if prefix.is_empty() { - out.sort_by_key(|library| LIBRARIES.iter().position(|(id, _)| id == library)); + children.sort_by_key(|library| LIBRARIES.iter().position(|(id, _)| id == library)); } - out + children } /// A folder's shown name: libraries by their name, folders (type and category names) translated @@ -86,6 +88,7 @@ pub(crate) fn breadcrumb(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec, image: Option> }, /// An image resource by name Image(String, Arc), /// A built-in lighting environment's panorama @@ -43,6 +45,13 @@ pub enum ShelfPreview { } impl ShelfPreview { + /// Resolve a saved brush's image alpha while the project images are available + pub fn saved_brush(path: &std::path::Path, images: &ImageStore) -> Self { + let settings = read_saved_brush(path); + let image = settings.as_ref().and_then(|brush| brush.alpha_image.as_ref()).and_then(|name| images.get(name)).cloned(); + ShelfPreview::SavedBrush { path: path.to_path_buf(), settings, image } + } + /// Smart materials preview on the orb, plain materials on a sphere pub fn material(id: &'static str) -> ShelfPreview { match materials::find(id) { @@ -61,7 +70,7 @@ impl ShelfPreview { ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"), ShelfPreview::Alpha(alpha) => format!("alpha:{}", alpha.id), ShelfPreview::Brush(preset) => format!("brush:{}", preset.id), - ShelfPreview::SavedBrush(path) => format!("saved-brush:{}", path.display()), + ShelfPreview::SavedBrush { path, .. } => format!("saved-brush:{}", path.display()), ShelfPreview::Image(name, _) => format!("image:{name}"), ShelfPreview::Environment(name) => format!("environment:{name}"), } @@ -76,8 +85,14 @@ impl ShelfPreview { ShelfPreview::Filter(id) => Some(sphere_image(size, &preview::filter(id, size)?)), ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)), ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)), - ShelfPreview::Brush(preset) => Some(stroke_preview(&preset.applied(&BrushSettings::default()), size)), - ShelfPreview::SavedBrush(path) => Some(stroke_preview(&saved_brush(path)?, size)), + ShelfPreview::Brush(preset) => Some(stroke_preview(&preset.applied(&BrushSettings::default()), size, None)), + ShelfPreview::SavedBrush { settings, image, .. } => { + let settings = settings.as_ref()?; + if settings.alpha_image.is_some() && image.is_none() { + return None; + } + Some(stroke_preview(settings, size, image.as_deref())) + } ShelfPreview::Image(_, image) => Some(image_preview(image, size)), ShelfPreview::Environment(name) => Some(environment_image(name, size)), } @@ -86,7 +101,7 @@ impl ShelfPreview { /// A saved brush preset's settings; None when the file can't be read (or in the browser, which has no files) #[cfg(not(target_arch = "wasm32"))] -fn saved_brush(path: &std::path::Path) -> Option { +pub(crate) fn read_saved_brush(path: &std::path::Path) -> Option { use std::io::Read as _; let mut bytes = Vec::new(); @@ -99,7 +114,7 @@ fn saved_brush(path: &std::path::Path) -> Option { } #[cfg(target_arch = "wasm32")] -fn saved_brush(_: &std::path::Path) -> Option { +pub(crate) fn read_saved_brush(_: &std::path::Path) -> Option { None } @@ -150,4 +165,15 @@ mod tests { assert_eq!(on_the_orb, material.smart, "{}", material.id); } } + + #[test] + fn saved_brush_preview_uses_its_project_image_alpha() { + let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() }; + let transparent = Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[1.0, 1.0, 1.0, 0.0]; 4], srgb: false }); + let preview = ShelfPreview::SavedBrush { path: PathBuf::from("brush.tcbrush"), settings: Some(settings.clone()), image: Some(transparent) }; + + assert!(preview.image(64).is_some_and(|image| image.pixels.iter().all(|pixel| pixel.r() == 0))); + let missing = ShelfPreview::SavedBrush { path: PathBuf::from("brush.tcbrush"), settings: Some(settings), image: None }; + assert!(missing.image(64).is_none()); + } } diff --git a/crates/ui-egui/src/shelf_tabs.rs b/crates/ui-egui/src/shelf_tabs.rs index cb620500..5898a943 100644 --- a/crates/ui-egui/src/shelf_tabs.rs +++ b/crates/ui-egui/src/shelf_tabs.rs @@ -18,6 +18,7 @@ pub(crate) const NO_TYPE: usize = TABS.len(); /// The row, then `trailing` at its right end; `counts[i]` is how many assets of `TABS[i]` match the search pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui, counts: &[usize], trailing: impl FnOnce(&mut TextureCraftApp, &mut Ui, f32)) { let size = ui.spacing().interact_size.y; + // The type icons and one icon after them let row_width = (TABS.len() + 1) as f32 * (size + ICON_GAP); let mut picked = app.ui.shelf_tab.min(NO_TYPE); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index a8b43813..70748428 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -442,7 +442,9 @@ mod tests { ui.keymap.insert("file.save".into(), "F5".into()); let mut layout = UiState::default(); layout.dock.close(crate::docking::Panel::Assets); + ui.adopt_layout(layout); + assert!(!ui.dock.is_open(crate::docking::Panel::Assets)); assert_eq!(ui.recent, vec!["a.tcraft".to_string()]); assert_eq!(ui.export.preset, "Mine"); diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 4c7bab4b..75693775 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -3,11 +3,14 @@ //! Smart masks, smart materials and hover previews use [`PreviewWorker`] use std::collections::{HashMap, VecDeque}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Weak}; use egui::{Color32, ColorImage, Painter, Pos2, Rect, TextureHandle, TextureOptions}; +use texturecraft_engine::compose::{ImageRes, ImageStore}; use texturecraft_engine::core::ProceduralKind; use texturecraft_engine::paint::presets::BrushPreset; -use texturecraft_engine::paint::{BrushAlpha, alphas}; +use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; use texturecraft_engine::texel::linear_to_srgb; use crate::preview_image::{aces, image_preview, shade}; @@ -36,6 +39,8 @@ const BIG_PREVIEWS_KEPT: usize = 32; pub struct Thumbs { /// Shelf thumbnails by [`ShelfPreview::key`] shelf: HashMap, + /// Parsed saved brushes and weak project-image identities, reused by tile and hover previews + saved_brush_previews: HashMap, Option>)>, images: HashMap, /// (frame, thumbnails rendered in it) budget: (u64, usize), @@ -200,6 +205,7 @@ impl Thumbs { self.shelf.retain(|key, _| current(key)); self.rendered.retain(|key, _| current(key)); self.big_shown.retain(current); + self.saved_brush_previews.clear(); } /// Smart mask thumbnail; None until the worker returns it @@ -228,8 +234,43 @@ impl Thumbs { } /// A saved brush preset's stroke along an S curve; None while it renders, empty when the file is unreadable - pub fn saved_brush(&mut self, ctx: &egui::Context, path: &std::path::Path) -> Option { - self.shelf(ctx, ShelfPreview::SavedBrush(path.to_path_buf()), SWATCH_PX) + pub fn saved_brush(&mut self, ctx: &egui::Context, path: &Path, images: &ImageStore) -> Option { + let key = format!("saved-brush:{}", path.display()); + let cached_preview = self.saved_brush_previews.contains_key(path).then(|| self.saved_brush_preview(path, images)); + if let Some(texture) = self.shelf.get(&key) { + return Some(texture.clone()); + } + if !self.spend_budget(ctx, 1) { + return None; + } + + let preview = cached_preview.unwrap_or_else(|| self.saved_brush_preview(path, images)); + let image = preview.image(SWATCH_PX).unwrap_or_else(|| ColorImage::filled([SWATCH_PX, SWATCH_PX], Color32::TRANSPARENT)); + let texture = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR); + self.shelf.insert(key, texture.clone()); + Some(texture) + } + + /// Reuse parsed settings until refresh; rebuild previews when their project image changes + pub fn saved_brush_preview(&mut self, path: &Path, images: &ImageStore) -> ShelfPreview { + let cached = self.saved_brush_previews.entry(path.to_path_buf()).or_insert_with(|| (crate::shelf_preview::read_saved_brush(path), None)); + let (settings, previous_image) = cached; + let image = settings.as_ref().and_then(|brush| brush.alpha_image.as_ref()).and_then(|name| images.get(name)); + let image_changed = match (previous_image.as_ref(), image) { + (Some(previous), Some(current)) => previous.upgrade().is_none_or(|previous| !Arc::ptr_eq(&previous, current)), + (None, None) => false, + _ => true, + }; + *previous_image = image.map(Arc::downgrade); + if image_changed { + let key = format!("saved-brush:{}", path.display()); + let rendered_prefix = format!("{key}@"); + self.shelf.remove(&key); + self.rendered.retain(|rendered, _| !rendered.starts_with(&rendered_prefix)); + self.big_shown.retain(|rendered| !rendered.starts_with(&rendered_prefix)); + } + + ShelfPreview::SavedBrush { path: path.to_path_buf(), settings: settings.clone(), image: image.cloned() } } /// A brush preset's stroke along an S curve @@ -296,3 +337,86 @@ pub fn paint_alpha(p: &Painter, rect: Rect, a: BrushAlpha, hardness: f32) { } } } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + static NEXT_FILE: AtomicUsize = AtomicUsize::new(0); + + #[test] + fn saved_brush_file_read_waits_for_the_thumbnail_budget() { + let path = std::env::temp_dir().join(format!("texturecraft-brush-budget-{}-{}.tcbrush", std::process::id(), NEXT_FILE.fetch_add(1, Ordering::Relaxed))); + std::fs::write(&path, serde_json::to_vec(&BrushSettings::default()).unwrap()).unwrap(); + let context = egui::Context::default(); + let mut thumbs = Thumbs::default(); + thumbs.budget = (context.cumulative_pass_nr(), PER_FRAME); + + assert!(thumbs.saved_brush(&context, &path, &ImageStore::new()).is_none()); + assert!(thumbs.saved_brush_previews.is_empty(), "a deferred thumbnail has not read its file"); + + std::fs::remove_file(&path).unwrap(); + } + + #[test] + fn saved_brush_settings_are_read_once_until_refresh() { + let path = + std::env::temp_dir().join(format!("texturecraft-brush-preview-{}-{}.tcbrush", std::process::id(), NEXT_FILE.fetch_add(1, Ordering::Relaxed))); + std::fs::write(&path, serde_json::to_vec(&BrushSettings::default()).unwrap()).unwrap(); + let mut thumbs = Thumbs::default(); + let images = ImageStore::new(); + + assert!(matches!(thumbs.saved_brush_preview(&path, &images), ShelfPreview::SavedBrush { settings: Some(_), .. })); + std::fs::remove_file(&path).unwrap(); + assert!( + matches!(thumbs.saved_brush_preview(&path, &images), ShelfPreview::SavedBrush { settings: Some(_), .. }), + "cached settings avoid a second file read" + ); + + thumbs.forget_saved_files(); + assert!(matches!(thumbs.saved_brush_preview(&path, &images), ShelfPreview::SavedBrush { settings: None, .. }), "refresh reads the file again"); + } + + #[test] + fn saved_brush_cache_releases_old_images_on_change_and_refresh() { + const IMAGE_SIDE: u32 = 512; + const IMAGE_TEXELS: usize = IMAGE_SIDE as usize * IMAGE_SIDE as usize; + const IMAGE_BYTES: usize = IMAGE_TEXELS * std::mem::size_of::<[f32; 4]>(); + + let mut thumbs = Thumbs::default(); + let first_path = PathBuf::from("first.tcbrush"); + let second_path = PathBuf::from("second.tcbrush"); + let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() }; + let old_image = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[1.0; 4]; IMAGE_TEXELS], srgb: false }); + let other_image = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[0.5; 4]; IMAGE_TEXELS], srgb: false }); + let old_weak = Arc::downgrade(&old_image); + let other_weak = Arc::downgrade(&other_image); + assert!(old_image.rgba.iter().map(|pixel| std::hint::black_box(pixel[0])).sum::() > 0.0); + assert!(other_image.rgba.iter().map(|pixel| std::hint::black_box(pixel[0])).sum::() > 0.0); + + thumbs.saved_brush_previews.insert(first_path.clone(), (Some(settings.clone()), None)); + thumbs.saved_brush_previews.insert(second_path.clone(), (Some(settings), None)); + let mut images: ImageStore = [("alpha.png".into(), old_image.clone())].into(); + drop(thumbs.saved_brush_preview(&first_path, &images)); + images.insert("alpha.png".into(), other_image.clone()); + drop(thumbs.saved_brush_preview(&second_path, &images)); + drop(old_image); + drop(other_image); + assert!(old_weak.upgrade().is_none(), "cached settings do not retain a replaced image"); + assert!(other_weak.upgrade().is_some(), "the project still owns its current image"); + eprintln!( + "saved brush cache after first replacement: 0 of {IMAGE_BYTES} old image bytes retained, {} current image strong owners", + Arc::strong_count(&images["alpha.png"]) + ); + + let replacement = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[0.0; 4]; IMAGE_TEXELS], srgb: false }); + images.insert("alpha.png".into(), replacement); + drop(thumbs.saved_brush_preview(&first_path, &images)); + assert!(other_weak.upgrade().is_none(), "another saved brush does not retain the old project image"); + eprintln!("saved brush cache after second replacement: 0 of {IMAGE_BYTES} previous image bytes retained"); + + thumbs.forget_saved_files(); + assert!(thumbs.saved_brush_previews.is_empty(), "refresh releases parsed brush settings"); + } +} diff --git a/crates/ui-egui/src/ui_state_store.rs b/crates/ui-egui/src/ui_state_store.rs index dcce58df..7bd1a539 100644 --- a/crates/ui-egui/src/ui_state_store.rs +++ b/crates/ui-egui/src/ui_state_store.rs @@ -13,6 +13,9 @@ const STORAGE_STEM: &str = "ui"; /// eframe storage key under which earlier builds kept the UI state, as RON const RON_STORAGE_KEY: &str = "ui"; +/// Textures moved from index 8 to index 6 when procedurals joined that type +const LEGACY_TEXTURES_TAB: usize = 8; +const TEXTURES_TAB: usize = 6; /// Maximum encoded UI state size for both reads and writes; typical states are a few kilobytes const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024; @@ -65,7 +68,7 @@ impl UiStateStore { return None; } - let ui = serde_json::from_slice::(&bytes).ok(); + let ui = decode_json_ui(&bytes); if !ui.as_ref().is_some_and(fully_read) { self.unreadable = Some((bytes, "json")); } @@ -75,7 +78,10 @@ impl UiStateStore { /// Preserve the original RON when decoding loses either dock, even if other settings load fn load_ron(&mut self, storage: &dyn eframe::Storage) -> Option { let text = storage.get_string(RON_STORAGE_KEY)?; - let ui = eframe::get_value::(storage, RON_STORAGE_KEY); + let mut ui = eframe::get_value::(storage, RON_STORAGE_KEY); + if let Some(ui) = &mut ui { + migrate_shelf_tab(ui, ron_has_shelf_path(&text)); + } if !ui.as_ref().is_some_and(fully_read) { self.unreadable = Some((text.into_bytes(), "ron")); } @@ -158,9 +164,52 @@ impl UiStateStore { } } +/// Old saved states have no shelf path, so their former Textures index needs remapping +fn migrate_shelf_tab(ui: &mut UiState, has_shelf_path: bool) { + if ui.shelf_tab == LEGACY_TEXTURES_TAB && !has_shelf_path { + ui.shelf_tab = TEXTURES_TAB; + } +} + +/// Decode JSON settings and map the old Textures index only when its new fields are absent +fn decode_json_ui(bytes: &[u8]) -> Option { + let mut ui = serde_json::from_slice::(bytes).ok()?; + if ui.shelf_tab == LEGACY_TEXTURES_TAB { + let has_shelf_path = serde_json::from_slice::(bytes) + .ok() + .and_then(|state| state.as_object().map(|fields| fields.contains_key("shelf_path"))) + .unwrap_or(true); + migrate_shelf_tab(&mut ui, has_shelf_path); + } + Some(ui) +} + +/// Ignore user text while looking for the field in legacy RON settings +fn ron_has_shelf_path(text: &str) -> bool { + let bytes = text.as_bytes(); + let mut quoted = false; + let mut escaped = false; + for (index, byte) in bytes.iter().enumerate() { + if quoted { + if escaped { + escaped = false; + } else if *byte == b'\\' { + escaped = true; + } else if *byte == b'"' { + quoted = false; + } + } else if *byte == b'"' { + quoted = true; + } else if bytes[index..].starts_with(b"shelf_path:") && (index == 0 || matches!(bytes[index - 1], b',' | b'(' | b' ' | b'\n')) { + return true; + } + } + false +} + /// The UI state saved in `file`, if it reads pub fn read(file: &Path) -> Option { - serde_json::from_slice(&read_bytes(file).ok()?).ok() + decode_json_ui(&read_bytes(file).ok()?) } /// eframe's browser storage reports write failures only through logging, so verify before discarding old settings @@ -311,6 +360,20 @@ pub(crate) mod tests { assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded); } + #[test] + fn legacy_ron_textures_index_migrates_to_the_combined_type() { + let mut storage = MemoryStorage::default(); + let legacy = include_str!("../tests/fixture/ui_state_before_json.ron") + .replace("shelf_tab:0", "shelf_tab:8") + .replace("shelf_filter:\"\"", "shelf_filter:\"shelf_path:\""); + assert!(legacy.contains("shelf_tab:8") && !ron_has_shelf_path(&legacy)); + storage.values.insert(RON_STORAGE_KEY.into(), legacy); + + let loaded = UiStateStore::default().load(Some(&storage)).expect("the legacy state loads"); + + assert_eq!(loaded.shelf_tab, TEXTURES_TAB); + } + #[test] fn an_unreadable_layout_loads_the_default_and_is_kept_beside_the_file() { let folder = test_folder("unreadable"); diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index e241293f..a33068b7 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -7,6 +7,7 @@ use texturecraft_engine::core::project::ENVIRONMENTS; use texturecraft_engine::materials::{MATERIALS, SmartMaterial}; use texturecraft_engine::smart_masks::SMART_MASKS; use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::saved_search::SavedSearch; use texturecraft_ui_egui::shelf_view::ShelfView; /// The reference's capture window: its Assets panel shows four columns there @@ -86,6 +87,17 @@ fn the_search_narrows_the_picked_type_and_greys_types_without_matches() { assert!(harness.query_by_label(material.label).is_some()); } +#[test] +fn unavailable_project_images_do_not_make_textures_match() { + let mut harness = shelf(REFERENCE_WINDOW); + harness.state_mut().session.doc.resources.insert("unavailable-preview.png".into(), vec![0].into()); + harness.state_mut().ui.shelf_filter = "unavailable-preview.png".into(); + harness.run_steps(3); + + assert!(button(&harness, "Textures").accesskit_node().is_disabled()); + assert!(harness.query_by_label("unavailable-preview.png").is_none()); +} + #[test] fn the_breadcrumb_arrow_picks_a_library() { let mut harness = shelf(REFERENCE_WINDOW); @@ -184,6 +196,46 @@ fn filter_by_path_picks_a_folder() { assert_eq!(harness.state().ui.shelf_path, ["starter"]); } +#[test] +fn many_saved_searches_keep_the_path_filter_reachable() { + let mut harness = shelf(NARROW_WINDOW); + 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() }) + .collect(); + harness.run_steps(3); + + let heading = harness.get_by_label("FILTER BY PATH").rect(); + assert!(heading.bottom() < NARROW_WINDOW.y, "the path pane heading stays on screen: {heading:?}"); + assert!(harness.query_by_label("Starter assets").is_some(), "the folder tree remains reachable"); +} + +#[test] +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() }) + .collect(); + harness.run_steps(3); + assert!(harness.query_by_label("search 500").is_none(), "offscreen searches do not build rows"); + + harness.get_by_label("search 0").hover(); + harness.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -50_000.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: egui::Modifiers::NONE, + }); + harness.run_steps(3); + harness.get_by_label("search 999").click(); + harness.run_steps(2); + + assert_eq!(harness.state().ui.shelf_filter, "filter 999"); +} + #[test] fn a_narrow_panel_keeps_the_toolbar_and_folds_the_type_row() { let mut harness = shelf(NARROW_WINDOW); diff --git a/crates/ui-egui/tests/it/split_divider.rs b/crates/ui-egui/tests/it/split_divider.rs index e0a487fc..4e8c0364 100644 --- a/crates/ui-egui/tests/it/split_divider.rs +++ b/crates/ui-egui/tests/it/split_divider.rs @@ -157,6 +157,26 @@ fn the_divider_position_survives_a_restart_and_old_saved_states_load_centred() { assert_eq!(restored.split_ratio, 0.5); } +#[test] +fn old_textures_tab_index_migrates_without_changing_new_all_types() { + let mut storage = MemoryStorage::default(); + let mut state = UiState::default(); + state.shelf_tab = 8; + UiStateStore::default().save(&state, &mut storage); + + assert_eq!(UiStateStore::default().load(Some(&storage)).map(|ui| ui.shelf_tab), Some(8)); + + let mut legacy: serde_json::Value = serde_json::from_str(&storage.0["ui.json"]).unwrap(); + legacy.as_object_mut().unwrap().remove("shelf_path"); + legacy.as_object_mut().unwrap().insert("shelf_filter".into(), "shelf_path".into()); + storage.0.insert("ui.json".into(), legacy.to_string()); + assert_eq!(UiStateStore::default().load(Some(&storage)).map(|ui| ui.shelf_tab), Some(6)); + + state.shelf_tab = 0; + UiStateStore::default().save(&state, &mut storage); + assert_eq!(UiStateStore::default().load(Some(&storage)).map(|ui| ui.shelf_tab), Some(0)); +} + #[test] fn dragging_the_divider_keeps_the_uv_texture_size_and_offset_on_screen() { // Zoomed in, a 2D sliver needs a zoom far past the one the view starts with From 000361d4e150e5354459e90b8f846a05c2a62b21 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 15 Nov 2026 23:27:06 +0000 Subject: [PATCH 22/22] Auto: Reject stale saved-brush preview results --- crates/ui-egui/src/thumbs.rs | 89 ++++++++++++++++++++++++++++++------ 1 file changed, 75 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index d7f91c5b..9a7bda37 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -36,13 +36,18 @@ const STENCIL_MAX_SIZE_PX: f32 = 1024.0; /// Big hover previews kept at most (the least recently shown go first) const BIG_PREVIEWS_KEPT: usize = 32; +/// Parsed settings, weak image identity and preview revision for a saved brush +type SavedBrushCacheEntry = (Option, Option>, u64); + /// The shelf's and the brush panel's preview textures #[derive(Default)] pub struct Thumbs { /// Shelf thumbnails by [`ShelfPreview::key`] shelf: HashMap, - /// Parsed saved brushes and weak project-image identities, reused by tile and hover previews - saved_brush_previews: HashMap, Option>)>, + /// Parsed settings, weak image identity and preview revision for each saved brush + saved_brush_previews: HashMap, + /// Refresh generation; queued results from earlier generations must not match new requests + saved_files_epoch: u64, images: HashMap, TextureHandle)>, images_revision: Option, /// (frame, thumbnails rendered in it) @@ -150,7 +155,7 @@ impl Thumbs { fn worker_rendered(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize, hover: bool) -> Option { self.receive(ctx); - let key = worker_key(&preview, size_px); + let key = self.worker_key(&preview, size_px); if !self.rendered.contains_key(&key) && self.may_request(ctx) { let queued = self.worker.request(ctx, PreviewRequest { key: key.clone(), preview, size_px, hover }); self.rendered.insert(key.clone(), if queued { WorkerPreview::Rendering } else { WorkerPreview::Failed }); @@ -199,7 +204,7 @@ impl Thumbs { /// Request a hover preview and evict the least recently shown beyond the cache limit pub fn big(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { - let key = worker_key(&preview, size_px); + let key = self.worker_key(&preview, size_px); self.big_shown.retain(|k| *k != key); self.big_shown.push_back(key); while self.big_shown.len() > BIG_PREVIEWS_KEPT { @@ -214,7 +219,7 @@ impl Thumbs { /// The big preview of `preview` if the worker already rendered it (requests nothing) pub fn rendered_big(&mut self, ctx: &egui::Context, preview: &ShelfPreview, size_px: usize) -> Option { self.receive(ctx); - self.ready(&worker_key(preview, size_px)) + self.ready(&self.worker_key(preview, size_px)) } /// Material thumbnail: smart materials come from the worker's orb, plain ones are spheres @@ -227,6 +232,7 @@ impl Thumbs { /// Drop the thumbnails and hover previews of the user's saved files, which may have changed on disk pub fn forget_saved_files(&mut self) { + self.saved_files_epoch = self.saved_files_epoch.wrapping_add(1); let current = |key: &String| !key.starts_with(SAVED_FILE_KEY_PREFIX); self.shelf.retain(|key, _| current(key)); self.rendered.retain(|key, _| current(key)); @@ -279,8 +285,8 @@ impl Thumbs { /// Reuse parsed settings until refresh; rebuild previews when their project image changes pub fn saved_brush_preview(&mut self, path: &Path, images: &ImageStore) -> ShelfPreview { - let cached = self.saved_brush_previews.entry(path.to_path_buf()).or_insert_with(|| (crate::shelf_preview::read_saved_brush(path), None)); - let (settings, previous_image) = cached; + let cached = self.saved_brush_previews.entry(path.to_path_buf()).or_insert_with(|| (crate::shelf_preview::read_saved_brush(path), None, 0)); + let (settings, previous_image, revision) = cached; let image = settings.as_ref().and_then(|brush| brush.alpha_image.as_ref()).and_then(|name| images.get(name)); let image_changed = match (previous_image.as_ref(), image) { (Some(previous), Some(current)) => previous.upgrade().is_none_or(|previous| !Arc::ptr_eq(&previous, current)), @@ -289,6 +295,7 @@ impl Thumbs { }; *previous_image = image.map(Arc::downgrade); if image_changed { + *revision = revision.wrapping_add(1); let key = format!("saved-brush:{}", path.display()); let rendered_prefix = format!("{key}@"); self.shelf.remove(&key); @@ -299,17 +306,23 @@ impl Thumbs { ShelfPreview::SavedBrush { path: path.to_path_buf(), settings: settings.clone(), image: image.cloned() } } + /// A saved-brush key also identifies the refresh and image version of its request + fn worker_key(&self, preview: &ShelfPreview, size_px: usize) -> String { + let key = format!("{}@{size_px}", preview.key()); + if let ShelfPreview::SavedBrush { path, .. } = preview { + let revision = self.saved_brush_previews.get(path).map_or(0, |(_, _, revision)| *revision); + format!("{key}#{}:{revision}", self.saved_files_epoch) + } else { + key + } + } + /// A brush preset's stroke along an S curve pub fn brush_preset(&mut self, ctx: &egui::Context, preset: &'static BrushPreset) -> Option { self.shelf(ctx, ShelfPreview::Brush(preset), SWATCH_PX) } } -/// The key of a worker-rendered preview: one per asset and size -fn worker_key(preview: &ShelfPreview, size_px: usize) -> String { - format!("{}@{size_px}", preview.key()) -} - /// A small shaded sphere drawn with a vertex-colored mesh (layer thumbnails, previews). pub fn paint_sphere(p: &Painter, c: Pos2, r: f32, base: [f32; 3]) { let mut mesh = egui::Mesh::default(); @@ -369,8 +382,56 @@ mod tests { use super::*; use std::sync::atomic::{AtomicUsize, Ordering}; + use crate::orb_shape::OrbShape; + static NEXT_FILE: AtomicUsize = AtomicUsize::new(0); + #[test] + fn saved_brush_refresh_discards_old_worker_result() { + let ctx = egui::Context::default(); + let mut thumbs = Thumbs { worker: PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() }, ..Thumbs::default() }; + let preview = ShelfPreview::SavedBrush { path: PathBuf::from("refreshed.tcbrush"), settings: None, image: None }; + + assert!(thumbs.big(&ctx, preview.clone(), 8).is_none()); + thumbs.forget_saved_files(); + assert!(thumbs.big(&ctx, preview.clone(), 8).is_none()); + + let PreviewWorker::Inline { results, .. } = &mut thumbs.worker else { panic!("test worker must render inline") }; + let old_key = results[0].0.clone(); + let current_key = results[1].0.clone(); + *results = vec![(current_key, None), (old_key, Some(ColorImage::filled([8, 8], Color32::RED)))]; + + let mut output = ctx.run_pass(Default::default(), |_| {}); + output.textures_delta.clear(); + assert!(thumbs.rendered_big(&ctx, &preview, 8).is_none(), "an old completion must not replace the current failed result"); + } + + #[test] + fn saved_brush_image_replacement_preserves_current_worker_result() { + let ctx = egui::Context::default(); + let mut thumbs = Thumbs { worker: PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() }, ..Thumbs::default() }; + let path = PathBuf::from("changed-alpha.tcbrush"); + let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() }; + thumbs.saved_brush_previews.insert(path.clone(), (Some(settings), None, 0)); + let image = |value| Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[value; 4]; 4], srgb: false }); + let mut images: ImageStore = [("alpha.png".into(), image(0.2))].into(); + + let old_preview = thumbs.saved_brush_preview(&path, &images); + assert!(thumbs.big(&ctx, old_preview, 8).is_none()); + images.insert("alpha.png".into(), image(0.8)); + let current_preview = thumbs.saved_brush_preview(&path, &images); + assert!(thumbs.big(&ctx, current_preview.clone(), 8).is_none()); + + let PreviewWorker::Inline { results, .. } = &mut thumbs.worker else { panic!("test worker must render inline") }; + let old_key = results[0].0.clone(); + let current_key = results[1].0.clone(); + *results = vec![(current_key, Some(ColorImage::filled([8, 8], Color32::RED))), (old_key, None)]; + + let mut output = ctx.run_pass(Default::default(), |_| {}); + output.textures_delta.clear(); + assert!(thumbs.rendered_big(&ctx, ¤t_preview, 8).is_some(), "the current completion must survive an old failure"); + } + #[test] fn saved_brush_file_read_waits_for_the_thumbnail_budget() { let path = std::env::temp_dir().join(format!("texturecraft-brush-budget-{}-{}.tcbrush", std::process::id(), NEXT_FILE.fetch_add(1, Ordering::Relaxed))); @@ -421,8 +482,8 @@ mod tests { assert!(old_image.rgba.iter().map(|pixel| std::hint::black_box(pixel[0])).sum::() > 0.0); assert!(other_image.rgba.iter().map(|pixel| std::hint::black_box(pixel[0])).sum::() > 0.0); - thumbs.saved_brush_previews.insert(first_path.clone(), (Some(settings.clone()), None)); - thumbs.saved_brush_previews.insert(second_path.clone(), (Some(settings), None)); + thumbs.saved_brush_previews.insert(first_path.clone(), (Some(settings.clone()), None, 0)); + thumbs.saved_brush_previews.insert(second_path.clone(), (Some(settings), None, 0)); let mut images: ImageStore = [("alpha.png".into(), old_image.clone())].into(); drop(thumbs.saved_brush_preview(&first_path, &images)); images.insert("alpha.png".into(), other_image.clone());