From 2bc7f69dcad33ad8b8a298e167bcbcf23369c051 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:03:25 +0000 Subject: [PATCH] Assets: rename, replace, delete and export saved brushes from their menu A saved brush's right-click menu has its Name as a field: Enter or a click elsewhere renames the brush, Escape keeps the name. Below the info block: Replace with the current brush and Delete, then Export resource, which writes the preset as a .tcbrush file (new brush.preset.export command). For project images, Delete takes the place of Remove resource and moves up beside the other actions on the image itself. Part of #411 --- crates/engine/src/brush_preset_cmds.rs | 54 ++++++++++ crates/ui-egui/src/shelf_menu.rs | 139 +++++++++++++++++++++---- crates/ui-egui/tests/it/shelf_menu.rs | 62 +++++++++++ 3 files changed, 234 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/brush_preset_cmds.rs b/crates/engine/src/brush_preset_cmds.rs index 28d96d7b..f2f23a67 100644 --- a/crates/engine/src/brush_preset_cmds.rs +++ b/crates/engine/src/brush_preset_cmds.rs @@ -146,6 +146,15 @@ pub fn specs() -> Vec { cmd!("brush.preset.delete", "Delete a brush preset", [], None, "{name} — one of the user's presets (built-ins are read-only)", always, delete), cmd!("brush.preset.save", "Save brush preset", [], None, "{path} — the current brush as a .tcbrush file", always, save), cmd!("brush.preset.load", "Load brush preset", [], None, "{path} — a .tcbrush file's stroke on the brush, keeping the size", always, load), + cmd!( + "brush.preset.export", + "Export brush preset", + [], + None, + "{name, path} — one of the user's presets as a .tcbrush file, as its library folder holds it", + always, + export + ), ] } @@ -325,6 +334,26 @@ fn load(_: &mut Session, _: &Value) -> Result { Err(bad("brush.preset.load", "file paths are not available in the browser")) } +/// Writes user preset `name` to `path` as the library folder holds it +#[cfg(not(target_arch = "wasm32"))] +fn export(session: &mut Session, params: &Value) -> Result { + const CMD: &str = "brush.preset.export"; + let name = name_param(params, "name", CMD)?; + let path = strp(params, "path").ok_or_else(|| bad(CMD, "`path` is required"))?; + let preset = session.brush_presets.find(&name).and_then(|index| session.brush_presets.list.get(index)); + let preset = preset.ok_or_else(|| bad(CMD, format!("no user brush preset `{name}`")))?; + let bytes = serde_json::to_vec_pretty(preset).map_err(|error| bad(CMD, error.to_string()))?; + + std::fs::write(path, bytes).map_err(|error| bad(CMD, format!("cannot write {path}: {error}")))?; + + Ok(json!({ "path": path })) +} + +#[cfg(target_arch = "wasm32")] +fn export(_: &mut Session, _: &Value) -> Result { + Err(bad("brush.preset.export", "file paths are not available in the browser")) +} + #[cfg(test)] mod tests { use super::*; @@ -406,6 +435,31 @@ mod tests { assert_eq!(names(&test_session), ["a/b"]); } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn an_exported_preset_loads_as_the_same_brush() { + let dir = std::env::temp_dir().join(format!("tc-brush-export-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut test_session = session(); + run(&mut test_session, "tool.brush", json!({"size": 41, "hardness": 70})).unwrap(); + run(&mut test_session, "brush.preset.store", json!({"name": "Ink pen"})).unwrap(); + run(&mut test_session, "tool.brush", json!({"size": 5})).unwrap(); + + let path = dir.join("shared.tcbrush"); + run(&mut test_session, "brush.preset.export", json!({"name": "ink pen", "path": path.to_str().unwrap()})).unwrap(); + + let mut fresh = session(); + assert!(fresh.load_brush_presets(dir.clone()).is_empty()); + assert_eq!(names(&fresh), ["Ink pen"], "the file carries the preset's name"); + assert_eq!(fresh.brush_presets.list[0].brush, test_session.brush_presets.list[0].brush, "the stored brush, not the current one"); + assert!( + run(&mut test_session, "brush.preset.export", json!({"name": "Airbrush", "path": path.to_str().unwrap()})).is_err(), + "built-ins are not exported" + ); + let _ = std::fs::remove_dir_all(&dir); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn presets_persist_in_the_folder() { diff --git a/crates/ui-egui/src/shelf_menu.rs b/crates/ui-egui/src/shelf_menu.rs index 22d2af95..35a7ba49 100644 --- a/crates/ui-egui/src/shelf_menu.rs +++ b/crates/ui-egui/src/shelf_menu.rs @@ -1,4 +1,4 @@ -//! An asset tile's right-click menu: what the asset is (name, usages, path, category), then what can be done with it +//! An asset tile's right-click menu: what the asset is (name, usages, path, category), then what can be done with it; the Name of an asset the user owns is a field that renames it use egui::{Align2, Color32, CornerRadius, FontId, Response, Sense, Ui, pos2, vec2}; use serde_json::json; @@ -22,36 +22,74 @@ const LABEL_GAP: f32 = 12.0; const MAX_VALUE_WIDTH: f32 = 220.0; /// The menu's text size, in points const TEXT_SIZE: f32 = 12.0; +/// The Name field's row and field heights, and the air before its text, in points +const FIELD_ROW_HEIGHT: f32 = 28.0; +const FIELD_HEIGHT: f32 = 24.0; +const FIELD_TEXT_INSET: f32 = 8.0; /// The air above and below the separators, in points const SEPARATOR_SPACE: f32 = 3.0; /// The right-click menu on the tile whose response is `response` pub(crate) fn show(app: &mut TextureCraftApp, response: &Response, entry: &ShelfEntry) { - response.context_menu(|ui| { + // Clicks inside keep the menu open, so the Name field can be typed in; its rows close it themselves + let menu = egui::Popup::context_menu(response).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); + menu.show(|ui| { let tokens = Tokens::get(ui.ctx()); ui.spacing_mut().item_spacing = vec2(0.0, 0.0); let info = info_rows(entry); let width = menu_width(ui, &info, &row_labels(entry)); ui.set_width(width); - info_block(ui, width, &info, &tokens); + let column = label_column(ui, &info); + + // A saved brush is the user's own: its Name row is a field that renames it + let mut shown_info = info.as_slice(); + if let ShelfEntry::SavedBrush { name, .. } = entry + && let Some((_, rest)) = info.split_first() + { + shown_info = rest; + let field_id = ui.make_persistent_id(("asset_name", entry.identity())); + if let Some(renamed) = name_field(ui, width, column, field_id, name, &tokens) { + app.run("brush.preset.rename", json!({"name": name, "to": renamed})); + } + } + info_block(ui, width, column, shown_info, &tokens); separator(ui, &tokens); - if let ShelfEntry::Image(name) = entry { - if row(ui, width, tr("Export resource..."), true, &tokens).clicked() { - export_image(app, name); - ui.close(); + match entry { + ShelfEntry::Image(name) => { + if row(ui, width, tr("Delete"), true, &tokens).clicked() { + app.run("resource.remove", json!({"name": name})); + ui.close(); + } + separator(ui, &tokens); + if row(ui, width, tr("Export resource..."), true, &tokens).clicked() { + export_image(app, name); + ui.close(); + } + separator(ui, &tokens); + if row(ui, width, tr("Add as decal (view center)"), true, &tokens).clicked() { + app.run("layer.add.decal", json!({"image": name})); + ui.close(); + } } - separator(ui, &tokens); - if row(ui, width, tr("Add as decal (view center)"), true, &tokens).clicked() { - app.run("layer.add.decal", json!({"image": name})); - ui.close(); + ShelfEntry::SavedBrush { name, .. } => { + if row(ui, width, tr("Replace with the current brush"), true, &tokens).clicked() { + app.run("brush.preset.store", json!({"name": name, "overwrite": true})); + ui.close(); + } + if row(ui, width, tr("Delete"), true, &tokens).clicked() { + app.run("brush.preset.delete", json!({"name": name})); + ui.close(); + } + separator(ui, &tokens); + if row(ui, width, tr("Export resource..."), true, &tokens).clicked() { + export_brush(app, name); + ui.close(); + } } - if row(ui, width, tr("Remove resource"), true, &tokens).clicked() { - app.run("resource.remove", json!({"name": name})); - ui.close(); + _ => { + row(ui, width, tr("Export resource..."), false, &tokens).on_hover_text(tr("Built-in assets have no file to export")); } - } else { - row(ui, width, tr("Export resource..."), false, &tokens).on_hover_text(tr("Built-in assets have no file to export")); } separator(ui, &tokens); @@ -76,8 +114,10 @@ fn info_rows(entry: &ShelfEntry) -> Vec<(&'static str, String)> { /// The labels of the rows under the info block, for the menu's width fn row_labels(entry: &ShelfEntry) -> Vec<&'static str> { let mut labels = vec![tr("Export resource..."), tr("Close")]; - if matches!(entry, ShelfEntry::Image(_)) { - labels.extend([tr("Add as decal (view center)"), tr("Remove resource")]); + match entry { + ShelfEntry::Image(_) => labels.extend([tr("Delete"), tr("Add as decal (view center)")]), + ShelfEntry::SavedBrush { .. } => labels.extend([tr("Replace with the current brush"), tr("Delete")]), + _ => {} } labels } @@ -98,9 +138,8 @@ fn menu_width(ui: &Ui, info: &[(&str, String)], labels: &[&str]) -> f32 { TEXT_X + (label_column(ui, info) + widest_value).max(widest_row) + RIGHT_PADDING } -/// The label (dim) and value rows; a value too wide is cut in the middle with "…" -fn info_block(ui: &mut Ui, width: f32, info: &[(&str, String)], tokens: &Tokens) { - let column = label_column(ui, info); +/// The label (dim) and value rows, values `column` points after the labels; a value too wide is cut in the middle with "…" +fn info_block(ui: &mut Ui, width: f32, column: f32, info: &[(&str, String)], tokens: &Tokens) { let value_width = width - TEXT_X - column - RIGHT_PADDING; for (label, value) in info { let (rect, response) = ui.allocate_exact_size(vec2(width, ROW_HEIGHT), Sense::hover()); @@ -112,6 +151,44 @@ fn info_block(ui: &mut Ui, width: f32, info: &[(&str, String)], tokens: &Tokens) } } +/// The Name row of an asset the user owns: a field in the value column that returns the new name once typing ends (Enter or a click elsewhere) with a changed, non-blank name. Escape keeps the old one +fn name_field(ui: &mut Ui, width: f32, column: f32, field_id: egui::Id, name: &str, tokens: &Tokens) -> Option { + let (rect, _) = ui.allocate_exact_size(vec2(width, FIELD_ROW_HEIGHT), Sense::hover()); + let label = tr("Name"); + ui.painter().text(pos2(rect.left() + TEXT_X, rect.center().y), Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), tokens.text_dim); + + // Check raw Escape even if the menu consumed it + let escaped = ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); + if escaped { + ui.data_mut(|data| data.remove::(field_id)); + } + let mut text = ui.data(|data| data.get_temp::(field_id)).unwrap_or_else(|| name.to_owned()); + + // The field's text lines up with the values below it + let field = egui::Rect::from_min_max( + pos2(rect.left() + TEXT_X + column - FIELD_TEXT_INSET, rect.center().y - FIELD_HEIGHT / 2.0), + pos2(rect.right() - TEXT_X, rect.center().y + FIELD_HEIGHT / 2.0), + ); + ui.painter().rect(field, CornerRadius::same(HOVER_ROUNDING), tokens.field, egui::Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); + let edit = egui::TextEdit::singleline(&mut text) + .id(field_id) + .font(FontId::proportional(TEXT_SIZE)) + .text_color(tokens.text) + .frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(FIELD_TEXT_INSET as i8, 0))) + .align(Align2::LEFT_CENTER); + let response = ui.new_child(egui::UiBuilder::new().max_rect(field.shrink(1.0))).add_sized(field.shrink(1.0).size(), edit); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, true, label)); + + if response.has_focus() { + ui.data_mut(|data| data.insert_temp(field_id, text)); + return None; + } + + ui.data_mut(|data| data.remove::(field_id)); + let typed = text.trim(); + (response.lost_focus() && !escaped && !typed.is_empty() && typed != name).then(|| typed.to_owned()) +} + /// `text`, or its start and end around "…" so it fits `width` points fn cut_middle(ui: &Ui, text: &str, width: f32) -> String { if text_width(ui, text) <= width { @@ -171,3 +248,23 @@ fn export_image(app: &mut TextureCraftApp, name: &str) { fn export_image(app: &mut TextureCraftApp, _: &str) { app.toast(tr("Exporting resources needs the desktop app"), true); } + +/// Asks where to save saved brush `name`, then writes it there as a brush preset file +#[cfg(not(target_arch = "wasm32"))] +fn export_brush(app: &mut TextureCraftApp, name: &str) { + use crate::file_dialogs::{Bound, FileDialog}; + use texturecraft_engine::brush_preset_cmds::BRUSH_EXT; + + let name = name.to_owned(); + let dialog = FileDialog::save().filter(tr("Brush preset"), &[BRUSH_EXT]).file_name(format!("{name}.{BRUSH_EXT}")); + app.ask_file(dialog, Bound::App, move |app, paths| { + if let Some(path) = paths.first() { + app.run("brush.preset.export", json!({"name": name, "path": path.to_string_lossy()})); + } + }); +} + +#[cfg(target_arch = "wasm32")] +fn export_brush(app: &mut TextureCraftApp, _: &str) { + app.toast(tr("Exporting resources needs the desktop app"), true); +} diff --git a/crates/ui-egui/tests/it/shelf_menu.rs b/crates/ui-egui/tests/it/shelf_menu.rs index 1acc99ae..51b7bdae 100644 --- a/crates/ui-egui/tests/it/shelf_menu.rs +++ b/crates/ui-egui/tests/it/shelf_menu.rs @@ -1,13 +1,16 @@ //! An asset tile's right-click menu: the info block says what the asset is, and its rows act on it +use egui::{Key, Modifiers}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; use texturecraft_engine::materials::MATERIALS; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::file_dialogs::Answer; /// The types' positions in the shelf's type row (its table is crate-private) const MATERIALS_TYPE: usize = 0; +const BRUSHES_TYPE: usize = 4; const TEXTURES_TYPE: usize = 6; /// The sample project with the shelf on type `tab` @@ -65,3 +68,62 @@ fn export_resource_writes_the_image_as_imported() { assert_eq!(std::fs::read(&target).unwrap(), bytes, "the exported file is the resource's own bytes"); } + +fn preset_names(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.state().session.brush_presets.list.iter().map(|preset| preset.name.clone()).collect() +} + +/// Selects the menu's Name field text and types `text` +fn type_name(harness: &mut Harness<'_, TextureCraftApp>, text: &str) { + harness.get_by_role_and_label(egui::Role::TextInput, "Name").click(); + harness.run_steps(3); + harness.key_press_modifiers(Modifiers::COMMAND, Key::A); + harness.event(egui::Event::Text(text.into())); + harness.run_steps(3); +} + +#[test] +fn a_saved_brush_menu_renames_replaces_and_deletes_it() { + // A name that sorts before every built-in brush, so its tile is in view + let mut harness = shelf(BRUSHES_TYPE); + texturecraft_engine::execute(&mut harness.state_mut().session, "brush.preset.store", &json!({"name": "Aa ink"})).unwrap(); + harness.run_steps(3); + + right_click(&mut harness, "Aa ink"); + type_name(&mut harness, "Never applied"); + harness.key_press(Key::Escape); + harness.run_steps(3); + assert_eq!(preset_names(&harness), ["Aa ink"], "Escape keeps the name"); + + right_click(&mut harness, "Aa ink"); + type_name(&mut harness, "Aa pen"); + harness.key_press(Key::Enter); + harness.run_steps(3); + assert_eq!(preset_names(&harness), ["Aa pen"], "Enter renames the brush"); + + texturecraft_engine::execute(&mut harness.state_mut().session, "tool.brush", &json!({"size": 77})).unwrap(); + right_click(&mut harness, "Aa pen"); + harness.get_by_label("Replace with the current brush").click(); + harness.run_steps(3); + assert_eq!(harness.state().session.brush_presets.list[0].brush, harness.state().session.tool.brush, "the preset holds the current brush"); + + right_click(&mut harness, "Aa pen"); + harness.get_by_label("Delete").click(); + harness.run_steps(3); + assert!(preset_names(&harness).is_empty(), "Delete removes the brush"); +} + +#[test] +fn delete_removes_a_project_image() { + let mut harness = shelf(TEXTURES_TYPE); + let mut bytes = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([180, 90, 40, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = harness.state_mut().session.import_resource_bytes("plate.png", bytes).unwrap(); + harness.run_steps(3); + + right_click(&mut harness, &name); + harness.get_by_label("Delete").click(); + harness.run_steps(3); + + assert!(!harness.state().session.doc.resources.contains_key(&name)); +}