Assets: right-click menu with the asset's info and Export resource

Every tile's menu starts with what the asset is: Name, Usages, Path and,
where it has one, Category; a long path is cut in the middle. Export
resource writes an image resource's file as it was imported (new
resource.export command); built-ins have no file and show it greyed.
Add as decal and Remove resource stay for project images. Close closes.

Part of #411
This commit is contained in:
Rebornim committed 2026-11-25 20:12:27 +00:00
1 parent 71e2e3f2bc
commit 26c28febfe
7 files changed
+292 -14

No files matched your search

+32
View File
@@ -24,6 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
),
cmd!("resource.list", "List resources", [], None, "{}", always, |s, _| Ok(list(s))),
cmd!("resource.remove", "Remove resource", [], None, "{name}", always, remove),
cmd!("resource.export", "Export resource", [], None, "{name, path} — the resource's file as it was imported", always, export),
cmd!("file.removeUnused", "Remove unused resources...", ["File"], None, "{}", always, remove_unused),
cmd!(
"layer.add.image",
@@ -261,6 +262,24 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}
/// Writes resource `name`'s bytes, as imported, to `path`
#[cfg(not(target_arch = "wasm32"))]
fn export(s: &mut Session, p: &Value) -> Result<Value> {
let command = "resource.export";
let name = strp(p, "name").ok_or_else(|| bad(command, "`name` is required"))?;
let path = strp(p, "path").ok_or_else(|| bad(command, "`path` is required"))?;
let bytes = s.doc.resources.get(name).ok_or_else(|| bad(command, format!("no resource `{name}`")))?;
std::fs::write(path, bytes.as_slice()).map_err(|error| bad(command, format!("cannot write {path}: {error}")))?;
Ok(json!({ "path": path }))
}
#[cfg(target_arch = "wasm32")]
fn export(_: &mut Session, _: &Value) -> Result<Value> {
Err(bad("resource.export", "file paths are not available in the browser"))
}
/// Drop resources no layer, mask effect, the brush alpha, the projection stencil, the mask brush or the environment uses (one undo step)
fn remove_unused(s: &mut Session, _: &Value) -> Result<Value> {
let mut used = Vec::new();
@@ -331,6 +350,19 @@ fn add_image_fill(s: &mut Session, p: &Value) -> Result<Value> {
mod tests {
use super::*;
#[test]
fn export_writes_the_imported_bytes() {
let mut session = crate::sample_session(128, 32).unwrap();
let bytes = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap();
let name = session.import_resource_bytes("icon.png", bytes.clone()).unwrap();
let path = std::env::temp_dir().join(format!("texturecraft-export-resource-{}.png", std::process::id()));
crate::commands::execute(&mut session, "resource.export", &json!({"name": name, "path": path.to_str().unwrap()})).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), bytes, "the file is the resource as imported");
std::fs::remove_file(path).unwrap();
}
#[test]
fn file_reads_obey_the_remaining_byte_budget() {
let path = std::env::temp_dir().join(format!("texturecraft-read-image-{}.png", std::process::id()));
+1
View File
@@ -139,6 +139,7 @@ pub mod shader_settings;
pub mod shelf;
mod shelf_entry;
mod shelf_folders;
mod shelf_menu;
pub mod shelf_panes;
pub mod shelf_preview;
mod shelf_tabs;
+2 -13
View File
@@ -514,7 +514,7 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str, masks: bool) {
#[cfg(target_arch = "wasm32")]
fn library(_: &mut TextureCraftApp, _: &mut Ui, _: &str, _: bool) {}
/// The tile of `entry`, outlined when `selected`: a click applies it, an image resource has a context menu
/// The tile of `entry`, outlined when `selected`: a click applies it, a right-click opens its menu
fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry, view: ShelfView, selected: bool) {
// An image removed this frame has nothing to show
if let ShelfEntry::Image(name) = entry
@@ -557,18 +557,7 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry
entry.activate(app);
}
if let ShelfEntry::Image(name) = entry {
response.context_menu(|ui| {
if ui.button(tr("Add as decal (view center)")).clicked() {
app.run("layer.add.decal", json!({"image": name}));
ui.close();
}
if ui.button(tr("Remove resource")).clicked() {
app.run("resource.remove", json!({"name": name}));
ui.close();
}
});
}
crate::shelf_menu::show(app, &response, entry);
}
/// Asset tile with optional dragging and a larger hover preview, at the medium size
+16 -1
View File
@@ -13,7 +13,7 @@ use texturecraft_engine::paint::presets::{BrushPreset, PRESETS};
use texturecraft_engine::smart_masks::{SMART_MASKS, SmartMask};
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::i18n::{n_, tr};
use crate::shelf::{Asset, Tab, apply};
use crate::shelf_preview::ShelfPreview;
@@ -124,6 +124,21 @@ impl ShelfEntry {
path.len() <= own.len() && path.iter().zip(own).all(|(wanted, have)| wanted == have)
}
/// What the asset is used as, lowercase (English, shown through `tr`): the menu's Usages row
pub(crate) fn usage(&self) -> &'static str {
match self {
ShelfEntry::Material(material) if material.smart => n_("smart material"),
ShelfEntry::Material(_) => n_("material"),
ShelfEntry::SmartMask(_) => n_("smart mask"),
ShelfEntry::Filter(_) => n_("filter"),
ShelfEntry::Brush(_) | ShelfEntry::SavedBrush { .. } => n_("brush"),
ShelfEntry::Alpha(_) => n_("alpha"),
ShelfEntry::Procedural(_) => n_("procedural"),
ShelfEntry::Environment(_) => n_("environment"),
ShelfEntry::Image(_) => n_("texture"),
}
}
/// The name under the tile, translated where the asset's name is
pub(crate) fn label(&self) -> &str {
match self {
+173
View File
@@ -0,0 +1,173 @@
//! An asset tile's right-click menu: what the asset is (name, usages, path, category), then what can be done with it
use egui::{Align2, Color32, CornerRadius, FontId, Response, Sense, Ui, pos2, vec2};
use serde_json::json;
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::shelf_entry::{LIBRARIES, ShelfEntry};
use crate::theme::Tokens;
/// A menu row's height and the inset of its hover face from the menu's sides, in points
const ROW_HEIGHT: f32 = 24.0;
const HOVER_INSET: f32 = 3.0;
const HOVER_ROUNDING: u8 = 3;
/// Where a row's text starts, from the menu's left edge, in points
const TEXT_X: f32 = 10.0;
/// The space after the text of the widest row, in points
const RIGHT_PADDING: f32 = 24.0;
/// The air between the info block's label column and its values, in points
const LABEL_GAP: f32 = 12.0;
/// The widest the info block's values get before the path is cut in the middle, in points
const MAX_VALUE_WIDTH: f32 = 220.0;
/// The menu's text size, in points
const TEXT_SIZE: f32 = 12.0;
/// The air above and below the separators, in points
const SEPARATOR_SPACE: f32 = 3.0;
/// The right-click menu on the tile whose response is `response`
pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &ShelfEntry) {
response.context_menu(|ui| {
let tokens = Tokens::get(ui.ctx());
ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
let info = info_rows(entry);
let width = menu_width(ui, &info, &row_labels(entry));
ui.set_width(width);
info_block(ui, width, &info, &tokens);
separator(ui, &tokens);
if let ShelfEntry::Image(name) = entry {
if row(ui, width, tr("Export resource..."), true, &tokens).clicked() {
export_image(app, name);
ui.close();
}
separator(ui, &tokens);
if row(ui, width, tr("Add as decal (view center)"), true, &tokens).clicked() {
app.run("layer.add.decal", json!({"image": name}));
ui.close();
}
if row(ui, width, tr("Remove resource"), true, &tokens).clicked() {
app.run("resource.remove", json!({"name": name}));
ui.close();
}
} else {
row(ui, width, tr("Export resource..."), false, &tokens).on_hover_text(tr("Built-in assets have no file to export"));
}
separator(ui, &tokens);
if row(ui, width, tr("Close"), true, &tokens).clicked() {
ui.close();
}
});
}
/// The info block's label and value rows: rows only where the asset has the data
fn info_rows(entry: &ShelfEntry) -> Vec<(&'static str, String)> {
let path = entry.path();
let shown_path: Vec<&str> = path.iter().map(|part| LIBRARIES.iter().find(|(id, _)| id == part).map_or_else(|| tr(part), |(_, name)| tr(name))).collect();
let mut rows =
vec![(tr("Name"), entry.label().to_string()), (tr("Usages"), tr(entry.usage()).to_string()), (tr("Path"), format!("/{}/", shown_path.join("/")))];
if let Some(category) = path.get(2) {
rows.push((tr("Category"), tr(category).to_string()));
}
rows
}
/// The labels of the rows under the info block, for the menu's width
fn row_labels(entry: &ShelfEntry) -> Vec<&'static str> {
let mut labels = vec![tr("Export resource..."), tr("Close")];
if matches!(entry, ShelfEntry::Image(_)) {
labels.extend([tr("Add as decal (view center)"), tr("Remove resource")]);
}
labels
}
fn text_width(ui: &Ui, text: &str) -> f32 {
ui.fonts_mut(|fonts| fonts.layout_no_wrap(text.to_owned(), FontId::proportional(TEXT_SIZE), Color32::WHITE).size().x)
}
/// The label column's width: the longest label and its gap
fn label_column(ui: &Ui, info: &[(&str, String)]) -> f32 {
info.iter().map(|(label, _)| text_width(ui, label)).fold(0.0, f32::max) + LABEL_GAP
}
/// The widest row, the info block's values capped at [`MAX_VALUE_WIDTH`]
fn menu_width(ui: &Ui, info: &[(&str, String)], labels: &[&str]) -> f32 {
let widest_value = info.iter().map(|(_, value)| text_width(ui, value)).fold(0.0, f32::max).min(MAX_VALUE_WIDTH);
let widest_row = labels.iter().map(|label| text_width(ui, label)).fold(0.0, f32::max);
TEXT_X + (label_column(ui, info) + widest_value).max(widest_row) + RIGHT_PADDING
}
/// The label (dim) and value rows; a value too wide is cut in the middle with "…"
fn info_block(ui: &mut Ui, width: f32, info: &[(&str, String)], tokens: &Tokens) {
let column = label_column(ui, info);
let value_width = width - TEXT_X - column - RIGHT_PADDING;
for (label, value) in info {
let (rect, response) = ui.allocate_exact_size(vec2(width, ROW_HEIGHT), Sense::hover());
let shown = cut_middle(ui, value, value_width);
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{label} {value}")));
let painter = ui.painter();
painter.text(pos2(rect.left() + TEXT_X, rect.center().y), Align2::LEFT_CENTER, *label, FontId::proportional(TEXT_SIZE), tokens.text_dim);
painter.text(pos2(rect.left() + TEXT_X + column, rect.center().y), Align2::LEFT_CENTER, shown, FontId::proportional(TEXT_SIZE), tokens.text);
}
}
/// `text`, or its start and end around "…" so it fits `width` points
fn cut_middle(ui: &Ui, text: &str, width: f32) -> String {
if text_width(ui, text) <= width {
return text.to_owned();
}
let chars: Vec<char> = text.chars().collect();
let mut kept = chars.len();
loop {
let head = kept.div_ceil(2);
let tail = kept / 2;
let cut: String = chars[..head].iter().chain(['…'].iter()).chain(chars[chars.len() - tail..].iter()).collect();
if kept == 0 || text_width(ui, &cut) <= width {
return cut;
}
kept -= 1;
}
}
/// A hairline across the menu between groups of rows
fn separator(ui: &mut Ui, tokens: &Tokens) {
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), SEPARATOR_SPACE * 2.0 + 1.0), Sense::hover());
ui.painter().hline(rect.x_range(), rect.center().y, egui::Stroke::new(1.0, tokens.separator));
}
/// One menu row: a hover face inset from the sides, its text dim and unclickable when not `enabled`
fn row(ui: &mut Ui, width: f32, label: &str, enabled: bool, tokens: &Tokens) -> Response {
let sense = if enabled { Sense::click() } else { Sense::hover() };
let (rect, response) = ui.allocate_exact_size(vec2(width, ROW_HEIGHT), sense);
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, label));
let painter = ui.painter();
if enabled && (response.hovered() || response.has_focus()) {
painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::same(HOVER_ROUNDING), tokens.button);
}
let color = if enabled { tokens.text } else { tokens.text_dim };
painter.text(pos2(rect.left() + TEXT_X, rect.center().y), Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), color);
if enabled { response } else { response.on_hover_cursor(egui::CursorIcon::NotAllowed) }
}
/// Asks where to save image resource `name`, then writes it there as imported
#[cfg(not(target_arch = "wasm32"))]
fn export_image(app: &mut TextureCraftApp, name: &str) {
use crate::file_dialogs::{Bound, FileDialog};
let extension = std::path::Path::new(name).extension().and_then(|extension| extension.to_str()).unwrap_or_default().to_owned();
let name = name.to_owned();
let dialog = FileDialog::save().filter(tr("Image"), &[extension.as_str()]).file_name(&name);
app.ask_file(dialog, Bound::Project, move |app, paths| {
if let Some(path) = paths.first() {
app.run("resource.export", json!({"name": name, "path": path.to_string_lossy()}));
}
});
}
#[cfg(target_arch = "wasm32")]
fn export_image(app: &mut TextureCraftApp, _: &str) {
app.toast(tr("Exporting resources needs the desktop app"), true);
}
+1
View File
@@ -81,6 +81,7 @@ mod settings_window;
mod shelf_click;
mod shelf_drop;
mod shelf_hover_preview;
mod shelf_menu;
mod shelf_panel;
mod shift_lines_2d;
mod shift_lines_3d;
+67
View File
@@ -0,0 +1,67 @@
//! An asset tile's right-click menu: the info block says what the asset is, and its rows act on it
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use texturecraft_engine::materials::MATERIALS;
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::file_dialogs::Answer;
/// The types' positions in the shelf's type row (its table is crate-private)
const MATERIALS_TYPE: usize = 0;
const TEXTURES_TYPE: usize = 6;
/// The sample project with the shelf on type `tab`
fn shelf(tab: usize) -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.shelf_tab = tab;
harness.run_steps(4);
harness
}
fn right_click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) {
harness.get_all_by_label(label).next().unwrap_or_else(|| panic!("no tile {label}")).click_secondary();
harness.run_steps(3);
}
#[test]
fn a_built_in_tile_menu_says_what_the_asset_is_and_where_it_lives() {
// The grid's first plain material (by name), so its tile is in view
let material = MATERIALS.iter().filter(|material| !material.smart).min_by_key(|material| material.label.to_lowercase()).unwrap();
let mut harness = shelf(MATERIALS_TYPE);
right_click(&mut harness, material.label);
for row in [
format!("Name {}", material.label),
"Usages material".to_string(),
format!("Path /Starter assets/Materials/{}/", material.category),
format!("Category {}", material.category),
] {
assert!(harness.query_by_label(&row).is_some(), "the menu has the info row {row:?}");
}
assert!(harness.get_by_label("Export resource...").accesskit_node().is_disabled(), "a built-in has no file to export");
harness.get_by_label("Close").click();
harness.run_steps(3);
assert!(harness.query_by_label("Usages material").is_none(), "Close closes the menu");
}
#[test]
fn export_resource_writes_the_image_as_imported() {
let mut harness = shelf(TEXTURES_TYPE);
let mut bytes = Vec::new();
image::RgbaImage::from_pixel(4, 4, image::Rgba([180, 90, 40, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
let name = harness.state_mut().session.import_resource_bytes("plate.png", bytes.clone()).unwrap();
harness.run_steps(3);
let dir = super::temp_dir::TempDir::new("shelf-export-resource");
let target = dir.join("exported.png");
let answer = target.clone();
harness.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![answer.clone()]))));
right_click(&mut harness, &name);
harness.get_by_label("Export resource...").click();
harness.run_steps(4);
assert_eq!(std::fs::read(&target).unwrap(), bytes, "the exported file is the resource's own bytes");
}