diff --git a/crates/core/src/channel.rs b/crates/core/src/channel.rs index 28f7d6d6d..465921451 100644 --- a/crates/core/src/channel.rs +++ b/crates/core/src/channel.rs @@ -573,6 +573,11 @@ impl Channel { pub fn is_shaded(self) -> bool { self.index() < Channel::SHADED_COUNT } + + /// Whether this is one of the 32 user channels (`User0`..`User31`) + pub fn is_user(self) -> bool { + (Channel::User0..=Channel::User31).contains(&self) + } } /// Storage format of a channel in a texture set (what export and the UI report). diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 205db3d25..c1e66c740 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -94,6 +94,9 @@ pub struct TextureSet { pub resolution_height: Option, /// Channels and their storage formats; see [`TextureSet::formats`] for what they hold pub channels: Vec<(Channel, ChannelFormat)>, + /// Custom display names of user channels (`User0`..`User31`); omitted when none are renamed + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub channel_names: BTreeMap, /// Whether channels hold their formats' precision; until a format is set every channel keeps 16 bits, what TextureCraft always stored #[serde(default)] pub format_precision: bool, @@ -220,6 +223,7 @@ impl TextureSet { resolution, resolution_height: None, channels: Channel::DEFAULT_SET.iter().map(|c| (*c, ChannelFormat::default_for(*c))).collect(), + channel_names: BTreeMap::new(), format_precision: false, stack: Vec::new(), normal_mixing: NormalMixing::Combine, @@ -405,6 +409,41 @@ impl TextureSet { true } + /// Remove channel `c` and any custom name it had (false when the set lacks it) + pub fn remove_channel(&mut self, c: Channel) -> bool { + let before = self.channels.len(); + self.channels.retain(|(x, _)| *x != c); + self.channel_names.remove(&c); + self.channels.len() != before + } + + /// Custom display name of user channel `channel`, if renamed + pub fn custom_channel_name(&self, channel: Channel) -> Option<&str> { + channel.is_user().then(|| self.channel_names.get(&channel).map(String::as_str).filter(|name| !name.is_empty())).flatten() + } + + /// Display name of `channel`: its custom name when renamed, else its default label + pub fn channel_name(&self, channel: Channel) -> &str { + self.custom_channel_name(channel).unwrap_or_else(|| channel.label()) + } + + /// Set or clear (`None`) the custom display name of user channel `channel`; false for non-user or absent channels + pub fn set_channel_name(&mut self, channel: Channel, name: Option) -> bool { + if !channel.is_user() || !self.has_channel(channel) { + return false; + } + + match name.filter(|name| !name.is_empty() && name != channel.label()) { + Some(name) => { + self.channel_names.insert(channel, name); + } + None => { + self.channel_names.remove(&channel); + } + } + true + } + /// Store channel `target` in `format` (false when the set lacks it); the other channels keep what they hold pub fn set_channel_format(&mut self, target: Channel, format: ChannelFormat) -> bool { if !self.has_channel(target) { @@ -1350,6 +1389,37 @@ mod tests { assert_eq!(p.texture_sets[0].resolution_height, None); } + #[test] + fn user_channel_names_round_trip_omit_when_empty_and_drop_on_remove() { + let mut set = TextureSet::new("a", 0, 128); + assert!(serde_json::to_value(&set).unwrap().get("channel_names").is_none(), "unchanged sets omit channel_names"); + assert!(!set.set_channel_name(Channel::BaseColor, Some("Albedo".into())), "non-user channels are refused"); + assert!(!set.set_channel_name(Channel::User0, Some("Wear".into())), "absent user channels are refused"); + + assert!(set.add_channel(Channel::User0)); + assert_eq!(set.channel_name(Channel::User0), "User0"); + assert!(set.set_channel_name(Channel::User0, Some("Wear".into()))); + assert_eq!(set.channel_name(Channel::User0), "Wear"); + + let json = serde_json::to_string(&set).unwrap(); + let back: TextureSet = serde_json::from_str(&json).unwrap(); + assert_eq!(back.channel_name(Channel::User0), "Wear"); + + // Setting back to the default label or removing drops the entry + assert!(set.set_channel_name(Channel::User0, Some("User0".into()))); + assert!(set.channel_names.is_empty()); + assert!(set.set_channel_name(Channel::User0, Some("Dirt".into()))); + assert!(set.remove_channel(Channel::User0)); + assert!(set.channel_names.is_empty()); + assert_eq!(set.channel_name(Channel::User0), "User0"); + + // Old projects without channel_names deserialize cleanly + let mut old = serde_json::to_value(&back).unwrap(); + old.as_object_mut().unwrap().remove("channel_names"); + let loaded: TextureSet = serde_json::from_value(old).unwrap(); + assert_eq!(loaded.channel_name(Channel::User0), "User0"); + } + #[test] fn validate_rejects_newer_formats_and_dangling_ids() { let mut p = project(); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 95737d88c..7c302d7a8 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -279,7 +279,11 @@ pub fn texture_set(session: &Session, index: usize) -> Value { "blockResolution": texture_set.block_resolution(), "uvTiles": texture_set.uv_tiles, "tiles": tiles, - "channels": texture_set.formats().iter().map(|(channel, format)| json!({ "channel": channel.id(), "format": format.label(), "shaded": channel.is_shaded() })).collect::>(), + "channels": texture_set + .formats() + .iter() + .map(|(channel, format)| json!({ "channel": channel.id(), "name": texture_set.channel_name(*channel), "format": format.label(), "shaded": channel.is_shaded() })) + .collect::>(), "layers": session.doc.project.walk(index).len(), "parts": crate::set_cmds::parts(session, index), "baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)), diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 91a7527c5..b095e3ef0 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -22,7 +22,7 @@ pub fn specs() -> Vec { "Inspect texture set", [], None, - "{ts?} → {index, name, originalName, description, resolution, height, size: [w, h], blockResolution, uvTiles: [UDIM numbers] (empty: no UV tiles), tiles: [{udim, block: [x, y], resolution, bakeEnabled}], channels: [{channel, format, shaded}], layers, parts, baked, visible, normalMixing, aoMixing, heightToNormal, uvPadding, active}", + "{ts?} → {index, name, originalName, description, resolution, height, size: [w, h], blockResolution, uvTiles: [UDIM numbers] (empty: no UV tiles), tiles: [{udim, block: [x, y], resolution, bakeEnabled}], channels: [{channel, name, format, shaded}], layers, parts, baked, visible, normalMixing, aoMixing, heightToNormal, uvPadding, active}", always, |s, p| Ok(crate::inspect::texture_set(s, ts_param(s, p, "textureSet.inspect")?)) ), @@ -58,6 +58,15 @@ pub fn specs() -> Vec { always, rename ), + cmd!( + "textureSet.renameChannel", + "Rename user channel", + [], + None, + "{ts?, channel, name} or {ts?, channel, reset: true} (empty name or reset restores the default label)", + always, + rename_channel + ), cmd!( "textureSet.settings", "Texture set settings", @@ -366,7 +375,7 @@ fn channel(s: &mut Session, p: &Value, add: bool) -> Result { if c == Channel::BaseColor { return Err(bad("textureSet.channel.remove", "base color can't be removed")); } - s.doc.project.texture_set_mut(ts)?.channels.retain(|(x, _)| *x != c); + s.doc.project.texture_set_mut(ts)?.remove_channel(c); Ok(()) })?; Ok(Value::Null) @@ -414,7 +423,10 @@ fn channels(s: &mut Session, p: &Value) -> Result { add_channel(s, ts, c)?; } } - s.doc.project.texture_set_mut(ts)?.channels.retain(|(c, _)| !remove.contains(c)); + let set = s.doc.project.texture_set_mut(ts)?; + for &c in &remove { + set.remove_channel(c); + } } Ok(()) })?; @@ -512,6 +524,36 @@ fn rename(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +fn rename_channel(s: &mut Session, p: &Value) -> Result { + let cmd = "textureSet.renameChannel"; + let ts = ts_param(s, p, cmd)?; + let channel = channel_param(cmd, p, "channel")?.ok_or_else(|| bad(cmd, "`channel` is required"))?; + if !channel.is_user() { + return Err(bad(cmd, format!("{} is not a user channel", channel.label()))); + } + + if !s.doc.project.texture_set(ts)?.has_channel(channel) { + return Err(bad(cmd, format!("the texture set has no {} channel", channel.label()))); + } + + let custom = if boolp(p, "reset") == Some(true) { + None + } else { + let name = strp(p, "name").ok_or_else(|| bad(cmd, "`name` or `reset: true` is required"))?.trim(); + if name.chars().count() > MAX_NAME_CHARS { + return Err(bad(cmd, format!("`name` is at most {MAX_NAME_CHARS} characters"))); + } + + (!name.is_empty() && name != channel.label()).then(|| name.to_owned()) + }; + + s.edit("Rename channel", |s| { + s.doc.project.texture_set_mut(ts)?.set_channel_name(channel, custom); + Ok(()) + })?; + Ok(Value::Null) +} + impl Session { /// The name set `ts` had when the mesh loaded: its material's name in the mesh pub fn original_set_name(&self, ts: usize) -> Option<&str> { diff --git a/crates/engine/src/template_cmds.rs b/crates/engine/src/template_cmds.rs index df34546c2..7efdb6da5 100644 --- a/crates/engine/src/template_cmds.rs +++ b/crates/engine/src/template_cmds.rs @@ -211,6 +211,7 @@ impl Session { for set_index in 0..project.texture_sets.len() { if let Some(set) = project.texture_sets.get_mut(set_index) { set.channels = template.channels.clone(); + set.channel_names.retain(|channel, _| template.channels.iter().any(|(wanted, _)| wanted == channel)); set.format_precision = template.format_precision; } diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index fb7647c6a..96a68815a 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -72,6 +72,7 @@ mod polygon_fill; mod project_recovery; mod rebuilt_uv_layout; mod rename_project; +mod rename_user_channel; mod resource_updater; mod resources_used; mod sample; diff --git a/crates/engine/tests/it/rename_user_channel.rs b/crates/engine/tests/it/rename_user_channel.rs new file mode 100644 index 000000000..6bfdd50fd --- /dev/null +++ b/crates/engine/tests/it/rename_user_channel.rs @@ -0,0 +1,125 @@ +//! `textureSet.renameChannel`: custom display names for user channels (`User0`..`User31`). + +use std::io::{Cursor, Read, Write}; + +use serde_json::{Value, json}; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +fn channel_name_in_inspect(session: &mut Session, ts: usize, channel_id: &str) -> String { + let inspect = execute(session, "textureSet.inspect", &json!({"ts": ts})).unwrap(); + inspect["channels"].as_array().unwrap().iter().find(|entry| entry["channel"] == channel_id).unwrap()["name"].as_str().unwrap().to_owned() +} + +#[test] +fn renaming_a_user_channel_updates_inspect_and_undoes() { + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + execute(&mut session, "textureSet.channel.add", &json!({"ts": 1, "channel": "user0"})).unwrap(); + assert_eq!(channel_name_in_inspect(&mut session, 1, "user0"), "User0"); + + execute(&mut session, "textureSet.renameChannel", &json!({"ts": 1, "channel": "user0", "name": " Wear Mask "})).unwrap(); + assert_eq!(channel_name_in_inspect(&mut session, 1, "user0"), "Wear Mask"); + assert_eq!(session.doc.project.texture_sets[1].channel_name(Channel::User0), "Wear Mask"); + assert_eq!(session.doc.project.texture_sets[0].channel_name(Channel::User0), "User0"); + + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(channel_name_in_inspect(&mut session, 1, "user0"), "User0"); + + execute(&mut session, "edit.redo", &Value::Null).unwrap(); + assert_eq!(channel_name_in_inspect(&mut session, 1, "user0"), "Wear Mask"); + + // Empty name restores the default label in one undo step + execute(&mut session, "textureSet.renameChannel", &json!({"ts": 1, "channel": "user0", "name": " "})).unwrap(); + assert_eq!(channel_name_in_inspect(&mut session, 1, "user0"), "User0"); + assert!(session.doc.project.texture_sets[1].channel_names.is_empty()); + + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(channel_name_in_inspect(&mut session, 1, "user0"), "Wear Mask"); + + // `reset: true` also restores the default label + execute(&mut session, "textureSet.renameChannel", &json!({"ts": 1, "channel": "user0", "reset": true})).unwrap(); + assert_eq!(channel_name_in_inspect(&mut session, 1, "user0"), "User0"); +} + +#[test] +fn renamed_user_channel_survives_save_and_reopen_and_old_projects_load() { + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + + // Unchanged projects omit `channel_names` in project.json + let clean_bytes = session.to_project_bytes().unwrap(); + let mut clean_zip = zip::ZipArchive::new(Cursor::new(&clean_bytes)).unwrap(); + let mut clean_json = String::new(); + clean_zip.by_name("project.json").unwrap().read_to_string(&mut clean_json).unwrap(); + assert!(!clean_json.contains("channel_names"), "unchanged projects must not serialize channel_names"); + + execute(&mut session, "textureSet.channel.add", &json!({"ts": 0, "channel": "user2"})).unwrap(); + execute(&mut session, "textureSet.renameChannel", &json!({"ts": 0, "channel": "user2", "name": "Rust / Dirt"})).unwrap(); + + let saved = session.to_project_bytes().unwrap(); + let mut reopened = Session::from_project_bytes(&saved).unwrap(); + assert_eq!(channel_name_in_inspect(&mut reopened, 0, "user2"), "Rust / Dirt"); + + // Strip `channel_names` from project.json to simulate an older .tcraft file + let mut old_zip_bytes = Vec::new(); + { + let mut reader = zip::ZipArchive::new(Cursor::new(&saved)).unwrap(); + let mut writer = zip::ZipWriter::new(Cursor::new(&mut old_zip_bytes)); + for index in 0..reader.len() { + let mut entry = reader.by_index(index).unwrap(); + let name = entry.name().unwrap().into_owned(); + let mut data = Vec::new(); + entry.read_to_end(&mut data).unwrap(); + if name == "project.json" { + let mut project: Value = serde_json::from_slice(&data).unwrap(); + for set in project["texture_sets"].as_array_mut().unwrap() { + set.as_object_mut().unwrap().remove("channel_names"); + } + data = serde_json::to_vec_pretty(&project).unwrap(); + } + writer.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + writer.write_all(&data).unwrap(); + } + writer.finish().unwrap(); + } + + let mut old_loaded = Session::from_project_bytes(&old_zip_bytes).unwrap(); + assert_eq!(channel_name_in_inspect(&mut old_loaded, 0, "user2"), "User2"); +} + +#[test] +fn invalid_renames_fail_and_removing_a_channel_drops_its_name() { + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + execute(&mut session, "textureSet.channels", &json!({"ts": 0, "add": ["user0", "user1"]})).unwrap(); + let before = session.doc.project.texture_sets[0].clone(); + let steps = session.history_labels().len(); + + let refused = [ + json!({"ts": 0, "channel": "baseColor", "name": "Albedo"}), + json!({"ts": 0, "channel": "user5", "name": "Missing"}), + json!({"ts": 0, "channel": "user0"}), + json!({"ts": 0, "channel": "user0", "name": 42}), + json!({"ts": 0, "channel": "user0", "name": "a".repeat(129)}), + json!({"ts": 99, "channel": "user0", "name": "BadSet"}), + ]; + for params in &refused { + assert!(execute(&mut session, "textureSet.renameChannel", params).is_err(), "{params}"); + } + assert_eq!(session.doc.project.texture_sets[0], before); + assert_eq!(session.history_labels().len(), steps); + + // 128 characters is accepted + let at_limit = "界".repeat(128); + execute(&mut session, "textureSet.renameChannel", &json!({"ts": 0, "channel": "user0", "name": at_limit})).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].channel_name(Channel::User0), at_limit); + + // Removing through either channel-removal command drops the custom name + execute(&mut session, "textureSet.renameChannel", &json!({"ts": 0, "channel": "user1", "name": "Glow Mask"})).unwrap(); + execute(&mut session, "textureSet.channel.remove", &json!({"ts": 0, "channel": "user0"})).unwrap(); + execute(&mut session, "textureSet.channels", &json!({"ts": 0, "remove": ["user1"]})).unwrap(); + assert!(session.doc.project.texture_sets[0].channel_names.is_empty()); + + execute(&mut session, "textureSet.channels", &json!({"ts": 0, "add": ["user0", "user1"]})).unwrap(); + assert_eq!(channel_name_in_inspect(&mut session, 0, "user0"), "User0"); + assert_eq!(channel_name_in_inspect(&mut session, 0, "user1"), "User1"); +} diff --git a/crates/ui-egui/src/channel_manager.rs b/crates/ui-egui/src/channel_manager.rs index 1e47ca880..390b75deb 100644 --- a/crates/ui-egui/src/channel_manager.rs +++ b/crates/ui-egui/src/channel_manager.rs @@ -88,10 +88,10 @@ impl ChannelManager { return; }; - if manager.mesh_id != app.session.mesh_id || manager.ts >= app.session.set_count() { + let Some(set) = app.session.doc.project.texture_sets.get(manager.ts).cloned().filter(|_| manager.mesh_id == app.session.mesh_id) else { ctx.data_mut(|data| data.remove::>(Self::id())); return; - } + }; let opening = ctx.memory(|memory| memory.top_modal_layer().is_none()); let tokens = Tokens::get(ctx); @@ -112,7 +112,7 @@ impl ChannelManager { let window_height = ctx.content_rect().height(); let room = window_height - TITLE_BAR_HEIGHT - BODY_AIR - FOOTER_AIR - footer.height() - EDGE_AIR; let max_height = (window_height * MAX_HEIGHT_SHARE).min(room).max(0.0); - egui::ScrollArea::both().auto_shrink([false, true]).min_scrolled_height(0.0).max_height(max_height).show(ui, |ui| manager.columns(ui)); + egui::ScrollArea::both().auto_shrink([false, true]).min_scrolled_height(0.0).max_height(max_height).show(ui, |ui| manager.columns(ui, &set)); ui.add_space(FOOTER_AIR); let (apply, cancel) = manager.footer(ui, &tokens, footer); ui.add_space(EDGE_AIR); @@ -120,8 +120,8 @@ impl ChannelManager { }); let (apply, cancel) = modal.inner; - if apply && let Some(set) = app.session.doc.project.texture_sets.get(manager.ts) { - let (add, remove) = manager.edits(set); + if apply { + let (add, remove) = manager.edits(&set); if !add.is_empty() || !remove.is_empty() { let ids = |list: Vec| list.into_iter().map(Channel::id).collect::>(); app.run("textureSet.channels", json!({ "ts": manager.ts, "add": ids(add), "remove": ids(remove), "allSets": manager.all_sets })); @@ -151,7 +151,7 @@ impl ChannelManager { } /// The groups side by side, a check per channel; a dim ⊘ marks the material channels our shader doesn't read - fn columns(&mut self, ui: &mut Ui) { + fn columns(&mut self, ui: &mut Ui, set: &TextureSet) { let mut user_rows_top = None; ui.horizontal_top(|ui| { for (column, (groups, width)) in COLUMNS.iter().enumerate() { @@ -163,7 +163,7 @@ impl ChannelManager { let channels = group.channels(); let shown = if *group == ChannelGroup::User { &channels[..USER_ROWS_PER_COLUMN] } else { channels }; for (row, channel) in shown.iter().enumerate() { - let response = self.check(sheet, *channel); + let response = self.check(sheet, set, *channel); if *group == ChannelGroup::User && row == 0 { user_rows_top = Some(response.rect.top()); } @@ -181,25 +181,26 @@ impl ChannelManager { } PropertySheet::show(ui, ("channel_manager", COLUMNS.len()), |sheet| { for channel in &ChannelGroup::User.channels()[USER_ROWS_PER_COLUMN..] { - self.check(sheet, *channel); + self.check(sheet, set, *channel); } }); }); }); } - fn check(&mut self, sheet: &mut PropertySheet<'_>, channel: Channel) -> egui::Response { + fn check(&mut self, sheet: &mut PropertySheet<'_>, set: &TextureSet, channel: Channel) -> egui::Response { let Some(on) = self.ticked.get(channel.index()).copied() else { return sheet.ui.allocate_response(egui::Vec2::ZERO, Sense::hover()); }; // User channels are the user's own data for export: reading them is never the shader's job, so they carry no mark - let user = ChannelGroup::User.channels().contains(&channel); + let user = channel.is_user(); let note = (!channel.is_shaded() && !user).then_some(icon::PROHIBIT); // Base color stays: every set has it let fixed = channel == Channel::BaseColor; - let response = sheet.greyed(!fixed, fixed.then(|| tr("Base color can't be removed")), |sheet| sheet.check_noted(tr(channel.label()), Some(on), note)); + let label = crate::texture_set_settings::channel_display_name(set, channel); + let response = sheet.greyed(!fixed, fixed.then(|| tr("Base color can't be removed")), |sheet| sheet.check_noted(label, Some(on), note)); if note.is_some() { sheet.ui.ctx().accesskit_node_builder(response.id, |node| node.set_description(tr("Not used by the shader"))); } diff --git a/crates/ui-egui/src/channel_name_edit.rs b/crates/ui-egui/src/channel_name_edit.rs new file mode 100644 index 000000000..1d1742387 --- /dev/null +++ b/crates/ui-egui/src/channel_name_edit.rs @@ -0,0 +1,45 @@ +//! In-progress inline rename of a user channel in Texture Set Settings + +use texturecraft_engine::core::Channel; + +/// The user channel name being edited in place, scoped to its project, mesh and texture set +#[derive(Clone, Debug)] +pub(crate) struct ChannelNameEdit { + owner: (u64, u64), + ts: usize, + pub(crate) channel: Channel, + pub(crate) text: String, + pub(crate) needs_focus: bool, +} + +impl ChannelNameEdit { + fn id() -> egui::Id { + egui::Id::unique("tss_channel_name_edit") + } + + pub(crate) fn start(owner: (u64, u64), ts: usize, channel: Channel, text: String) -> Self { + ChannelNameEdit { owner, ts, channel, text, needs_focus: true } + } + + /// Active edit for `owner` and `ts`; drops any edit belonging to another project, mesh or set + pub(crate) fn load(ctx: &egui::Context, owner: (u64, u64), ts: usize) -> Option { + let edit = ctx.data(|data| data.get_temp::>(Self::id())).flatten()?; + if edit.owner == owner && edit.ts == ts { + return Some(edit); + } + + ctx.data_mut(|data| data.remove::>(Self::id())); + None + } + + pub(crate) fn save(ctx: &egui::Context, edit: Option) { + ctx.data_mut(|data| match edit { + Some(edit) => { + data.insert_temp(Self::id(), Some(edit)); + } + None => { + data.remove::>(Self::id()); + } + }); + } +} diff --git a/crates/ui-egui/src/channel_row_action.rs b/crates/ui-egui/src/channel_row_action.rs new file mode 100644 index 000000000..d2ad32ee7 --- /dev/null +++ b/crates/ui-egui/src/channel_row_action.rs @@ -0,0 +1,11 @@ +//! What a channel row in Texture Set Settings asks for once it has drawn + +use texturecraft_engine::core::ChannelFormat; + +/// Action emitted by a single channel row in Texture Set Settings +pub(crate) enum ChannelRowAction { + Format(ChannelFormat), + Rename(String), + ResetName, + Remove, +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f2bae6d73..89f33b11b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -28,6 +28,8 @@ mod brush_pictures; mod brush_sheet; mod brush_stroke_preview; mod channel_manager; +mod channel_name_edit; +mod channel_row_action; mod color_management; mod color_picker; mod color_selection_editor; diff --git a/crates/ui-egui/src/property_sheet/stacked_rows.rs b/crates/ui-egui/src/property_sheet/stacked_rows.rs index 6b961630a..cdbf78264 100644 --- a/crates/ui-egui/src/property_sheet/stacked_rows.rs +++ b/crates/ui-egui/src/property_sheet/stacked_rows.rs @@ -356,10 +356,20 @@ impl PropertySheet<'_> { pub(crate) fn check_noted(&mut self, label: &str, state: Option, note: Option<&str>) -> Response { let line = self.take(CHECK_LINE); let center_y = line.center().y; - let text = self.ui.painter().layout_no_wrap(label.to_owned(), FontId::proportional(TEXT_SIZE), self.tokens.text); - let hit = Rect::from_min_max(pos2(self.left, line.top()), pos2(self.left + CHECK_SIZE + CHECK_TO_LABEL + text.size().x, line.bottom())); + let note_galley = note.map(|note| self.ui.painter().layout_no_wrap(note.to_owned(), FontId::proportional(SMALL_TEXT_SIZE), self.tokens.text_dim)); + let text_left = self.left + CHECK_SIZE + CHECK_TO_LABEL; + let text_right = match ¬e_galley { + Some(note_galley) => self.right - note_galley.size().x - CHECK_TO_LABEL, + None => self.right, + }; + let mut job = egui::text::LayoutJob::simple_singleline(label.to_owned(), FontId::proportional(TEXT_SIZE), self.tokens.text); + job.wrap = egui::text::TextWrapping::truncate_at_width((text_right - text_left).max(0.0)); + let text = self.ui.painter().layout_job(job); + let elided = text.elided; + let hit = Rect::from_min_max(pos2(self.left, line.top()), pos2(text_left + text.size().x, line.bottom())); let id = self.next_id(); let response = self.ui.interact(hit, id, Sense::click()); + let response = if elided { response.on_hover_text(label) } else { response }; let enabled = self.ui.is_enabled(); response.widget_info(|| match state { Some(on) => WidgetInfo::selected(egui::Role::CheckBox, enabled, on, label), @@ -369,9 +379,9 @@ impl PropertySheet<'_> { let check = Rect::from_min_size(pos2(self.left, center_y - CHECK_SIZE / 2.0), vec2(CHECK_SIZE, CHECK_SIZE)); paint_check(self.ui.painter(), &self.tokens, check, state, response.hovered()); self.ui.painter().galley(pos2(check.right() + CHECK_TO_LABEL, center_y - text.size().y / 2.0), text, self.tokens.text); - if let Some(note) = note { + if let (Some(note), Some(note_galley)) = (note, note_galley) { self.ui.ctx().accesskit_node_builder(response.id, |node| node.set_description(note)); - self.ui.painter().text(pos2(self.right, center_y), Align2::RIGHT_CENTER, note, FontId::proportional(SMALL_TEXT_SIZE), self.tokens.text_dim); + self.ui.painter().galley(pos2(self.right - note_galley.size().x, center_y - note_galley.size().y / 2.0), note_galley, self.tokens.text_dim); } self.paint_control_focus(&response); self.drawn(line.bottom()); diff --git a/crates/ui-egui/src/texture_set_settings.rs b/crates/ui-egui/src/texture_set_settings.rs index 8abd249a4..0e6b5a6ba 100644 --- a/crates/ui-egui/src/texture_set_settings.rs +++ b/crates/ui-egui/src/texture_set_settings.rs @@ -8,11 +8,13 @@ use texturecraft_engine::core::{ }; use crate::TextureCraftApp; -use crate::i18n::{baked_map_label, tr, trf}; -use crate::layer_toolbar::menu_frame; +use crate::channel_name_edit::ChannelNameEdit; +use crate::channel_row_action::ChannelRowAction; +use crate::i18n::{baked_map_label, n_, tr, trf}; +use crate::layer_toolbar::{AddItem, ItemIcon, menu_frame, menu_row, menu_width}; use crate::picker_group::PickerGroup; use crate::picker_tab::PickerTab; -use crate::property_sheet::{PropertySheet, option_row}; +use crate::property_sheet::{PropertySheet, option_row, paint_keyboard_focus}; use crate::resource_picker; use crate::resource_picker_item::ResourcePickerItem; use crate::shader_settings::INSTANCE_NAME; @@ -35,6 +37,11 @@ const MENU_PADDING: f32 = 3.0; /// Space between a channel's gear and its format list const MENU_GAP: f32 = 1.0; +/// Inline rename field geometry: horizontal text inset, vertical padding, and minimum width before hiding format text +const EDIT_TEXT_X: f32 = 4.0; +const EDIT_FIELD_INSET: f32 = 3.0; +const MIN_EDIT_WIDTH: f32 = 60.0; + /// Height to normal strength's slider range const HEIGHT_STRENGTH_RANGE: std::ops::RangeInclusive = 0.0..=10.0; @@ -109,6 +116,11 @@ fn general(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, ts: usize, sheet.dropdown(tr("Shader Instance"), 0, &[0], |_| tr(INSTANCE_NAME).to_owned(), None); } +/// Display name of `channel` in `set`: the user's custom name (untranslated) or the translated built-in label +pub(crate) fn channel_display_name(set: &TextureSet, channel: Channel) -> &str { + set.custom_channel_name(channel).unwrap_or_else(|| tr(channel.label())) +} + /// Add or remove channels, a row per channel (name, format and its list, ×), then how they mix fn channels(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, ts: usize, set: &TextureSet) { sheet.section(tr("Channels"), false); @@ -116,15 +128,30 @@ fn channels(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, ts: usize, if manage.clicked() { crate::channel_manager::ChannelManager::open(app, &manage, ts); } + + let owner = (app.session.project_id, app.session.mesh_id); + let mut edit = ChannelNameEdit::load(sheet.ui.ctx(), owner, ts).filter(|active| set.has_channel(active.channel)); for (channel, format) in set.formats() { - let (picked, remove) = channel_row(sheet, channel, format); - if let Some(picked) = picked { - app.run("textureSet.channel.format", json!({"ts": ts, "channel": channel.id(), "format": picked.label()})); - } - if remove { - app.run("textureSet.channel.remove", json!({"ts": ts, "channel": channel.id()})); + match channel_row(sheet, set, owner, ts, channel, format, &mut edit) { + Some(ChannelRowAction::Format(picked)) => { + app.run("textureSet.channel.format", json!({"ts": ts, "channel": channel.id(), "format": picked.label()})); + } + Some(ChannelRowAction::Rename(name)) => { + app.run("textureSet.renameChannel", json!({"ts": ts, "channel": channel.id(), "name": name})); + } + Some(ChannelRowAction::ResetName) => { + app.run("textureSet.renameChannel", json!({"ts": ts, "channel": channel.id(), "reset": true})); + } + Some(ChannelRowAction::Remove) => { + if edit.as_ref().is_some_and(|active| active.channel == channel) { + edit = None; + } + app.run("textureSet.channel.remove", json!({"ts": ts, "channel": channel.id()})); + } + None => {} } } + ChannelNameEdit::save(sheet.ui.ctx(), edit); let mixing = NormalMixing::ALL; let mixing_name = |mixing| tr(if mixing == NormalMixing::Combine { "Combine" } else { "Replace" }).to_owned(); @@ -168,24 +195,31 @@ fn channels(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, ts: usize, } } -/// A channel: its name, its format with the gear that lists the formats, and × (Base color stays); returns the format picked and whether × was clicked -fn channel_row(sheet: &mut PropertySheet<'_>, channel: Channel, format: ChannelFormat) -> (Option, bool) { +/// A channel: its name (editable inline for user channels), its format with the gear that lists the formats, and × (Base color stays) +fn channel_row( + sheet: &mut PropertySheet<'_>, + set: &TextureSet, + owner: (u64, u64), + ts: usize, + channel: Channel, + format: ChannelFormat, + edit: &mut Option, +) -> Option { sheet.embed(|ui| { if ui.available_width() < 2.0 * GLYPH_BUTTON + GLYPH_GAP { - return (None, false); + return None; } let tokens = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), CHANNEL_ROW_HEIGHT), Sense::hover()); - let name = tr(channel.label()); - let mut picked = None; - let mut removed = false; + let name = channel_display_name(set, channel); + let mut action = None; let remove = Rect::from_center_size(pos2(rect.right() - GLYPH_BUTTON * 0.5, rect.center().y), vec2(GLYPH_BUTTON, GLYPH_BUTTON)); if channel != Channel::BaseColor && glyph_button(ui, ("tss_remove", channel.id()), remove, ic::X, &trf("Remove {channel}", &[("channel", &name)]), &tokens).clicked() { - removed = true; + action = Some(ChannelRowAction::Remove); } let gear = remove.translate(vec2(-GLYPH_BUTTON - GLYPH_GAP, 0.0)); @@ -196,28 +230,165 @@ fn channel_row(sheet: &mut PropertySheet<'_>, channel: Channel, format: ChannelF ui.add_space(MENU_PADDING); for option in ChannelFormat::ALL { if option_row(ui, option.label(), option == format).clicked() && option != format { - picked = Some(option); + action = Some(ChannelRowAction::Format(option)); } } ui.add_space(MENU_PADDING); }); let painter = ui.painter().clone(); - let format_at = pos2(gear.left() - FORMAT_GAP, rect.center().y); - let format_rect = painter.text(format_at, Align2::RIGHT_CENTER, format.label(), FontId::proportional(CHANNEL_TEXT_SIZE), tokens.text_dim); - let name_rect = painter.text(pos2(rect.left(), rect.center().y), Align2::LEFT_CENTER, name, semibold(CHANNEL_TEXT_SIZE), tokens.text); - painter.hline(rect.x_range(), rect.bottom(), Stroke::new(1.0, tokens.separator)); + let format_galley = painter.layout_no_wrap(format.label().to_owned(), FontId::proportional(CHANNEL_TEXT_SIZE), tokens.text_dim); + let format_pos = pos2(gear.left() - FORMAT_GAP - format_galley.size().x, rect.center().y - format_galley.size().y * 0.5); + let format_rect = Rect::from_min_size(format_pos, format_galley.size()); + + let name_right = (format_rect.left() - FORMAT_GAP).max(rect.left()); + let name_id = ui.scope_id().with(("tss_channel_name", channel.id())); + let editing = edit.as_ref().is_some_and(|active| active.channel == channel); + let show_format = !editing || name_right - rect.left() >= MIN_EDIT_WIDTH; + if show_format { + painter.galley(format_pos, format_galley, tokens.text_dim); + let format_label = ui.interact(format_rect, ui.scope_id().with(("tss_channel_format", channel.id())), Sense::hover()); + format_label.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format.label())); + } + + if editing { + let field_right = if show_format { name_right } else { (gear.left() - FORMAT_GAP).max(rect.left()) }; + let field = Rect::from_min_max(pos2(rect.left() - EDIT_TEXT_X, rect.top() + EDIT_FIELD_INSET), pos2(field_right, rect.bottom() - EDIT_FIELD_INSET)); + if let Some(submitted) = channel_edit_field(ui, edit, field, name_id, channel) { + let trimmed = submitted.trim(); + if trimmed.is_empty() { + if set.custom_channel_name(channel).is_some() { + action = Some(ChannelRowAction::ResetName); + } + } else if trimmed != set.channel_name(channel) { + action = Some(ChannelRowAction::Rename(trimmed.to_owned())); + } + } + } else { + let mut job = egui::text::LayoutJob::simple_singleline(name.to_owned(), semibold(CHANNEL_TEXT_SIZE), tokens.text); + job.wrap = egui::text::TextWrapping::truncate_at_width((name_right - rect.left()).max(0.0)); + let galley = painter.layout_job(job); + let name_elided = galley.elided; + let name_pos = pos2(rect.left(), rect.center().y - galley.size().y * 0.5); + let name_rect = Rect::from_min_size(name_pos, galley.size()); + + if channel.is_user() { + let name_hit = Rect::from_min_max(pos2(rect.left(), rect.top()), pos2(name_right, rect.bottom())); + let response = ui.interact(name_hit, name_id, Sense::click()); + let response = if name_elided { response.on_hover_text(name) } else { response }; + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, ui.is_enabled(), name)); + ui.ctx().accesskit_node_builder(response.id, |node| { + node.set_has_popup(egui::accesskit::HasPopup::Menu); + if set.custom_channel_name(channel).is_some() { + node.set_description(channel.label()); + } + }); + if response.hovered() { + painter.rect_filled(name_hit.shrink2(vec2(0.0, EDIT_FIELD_INSET)), CornerRadius::same(GLYPH_ROUNDING), tokens.row_hover); + } + painter.galley(name_pos, galley, tokens.text); + paint_keyboard_focus(ui, &response, &tokens); - // The drawn name and format read as labels - for (salt, text_rect, text) in [("tss_channel_name", name_rect, name), ("tss_channel_format", format_rect, format.label())] { - let label = ui.interact(text_rect, ui.scope_id().with((salt, channel.id())), Sense::hover()); - label.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, text)); + let rename_key = response.has_focus() && ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::F2)); + if response.double_clicked() || rename_key { + *edit = Some(ChannelNameEdit::start(owner, ts, channel, set.channel_name(channel).to_owned())); + } + let renamed = set.custom_channel_name(channel).is_some(); + match channel_context_menu(ui, &response, renamed, &tokens) { + Some(true) => *edit = Some(ChannelNameEdit::start(owner, ts, channel, set.channel_name(channel).to_owned())), + Some(false) => action = Some(ChannelRowAction::ResetName), + None => {} + } + } else { + painter.galley(name_pos, galley, tokens.text); + let label = ui.interact(name_rect, name_id, Sense::hover()); + if name_elided { + label.clone().on_hover_text(name); + } + label.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, name)); + } } - (picked, removed) + painter.hline(rect.x_range(), rect.bottom(), Stroke::new(1.0, tokens.separator)); + action }) } +/// Inline text field for renaming a user channel: Enter or clicking away returns the text, Escape drops it +fn channel_edit_field(ui: &mut Ui, edit: &mut Option, rect: Rect, return_to: egui::Id, channel: Channel) -> Option { + let active = edit.as_mut()?; + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect)); + let font = FontId::proportional(CHANNEL_TEXT_SIZE); + let text_height = ui.fonts_mut(|fonts| fonts.row_height(&font)); + let margin = vec2(EDIT_TEXT_X, ((rect.height() - text_height) * 0.5).max(0.0)); + let response = child.add_sized(rect.size(), egui::TextEdit::singleline(&mut active.text).font(font).margin(margin)); + let label = trf("Rename {channel}", &[("channel", &channel.label())]); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_label(label)); + if std::mem::take(&mut active.needs_focus) { + response.request_focus(); + } + if !response.lost_focus() { + return None; + } + + let finished = edit.take()?; + let raw_key = |key| { + ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: pressed_key, pressed: true, .. } if *pressed_key == key))) + }; + let entered = raw_key(egui::Key::Enter); + let escaped = raw_key(egui::Key::Escape); + if entered || escaped { + ui.memory_mut(|memory| memory.request_focus(return_to)); + } + (!escaped).then_some(finished.text) +} + +/// Right-click (and Shift+F10 / Menu key) menu for a user channel row: Some(true) = Rename, Some(false) = Reset Name +fn channel_context_menu(ui: &Ui, response: &egui::Response, renamed: bool, tokens: &Tokens) -> Option { + let entries = [(ic::PENCIL_SIMPLE, n_("Rename"), true, true), (ic::ARROW_COUNTER_CLOCKWISE, n_("Reset Name"), renamed, false)]; + let items = entries.map(|(glyph, short, enabled, _)| AddItem { + icon: ItemIcon::Glyph(glyph), + short, + long: short, + command: "", + params: serde_json::Value::Null, + enabled, + }); + let mut popup = Popup::context_menu(response).frame(menu_frame(tokens)); + let return_focus = popup.is_open() && ui.input(|input| input.key_pressed(egui::Key::Escape)); + + let from_keyboard = response.id.with("tss_channel_menu_from_keyboard"); + let pressed = + |input: &mut egui::InputState| input.consume_key(egui::Modifiers::SHIFT, egui::Key::F10) || input.consume_key(egui::Modifiers::NONE, egui::Key::Menu); + if response.has_focus() && ui.input_mut(pressed) { + ui.data_mut(|data| data.insert_temp(from_keyboard, true)); + popup = popup.open_memory(Some(egui::SetOpenCommand::Bool(true))); + } else if !popup.is_open() { + ui.data_mut(|data| data.remove::(from_keyboard)); + } + if ui.data(|data| data.get_temp::(from_keyboard)).unwrap_or(false) { + popup = popup.anchor(response); + } + + let mut picked = None; + popup.show(|ui| { + let width = menu_width(ui, &items); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + ui.add_space(MENU_PADDING); + for (item, (.., action)) in items.iter().zip(entries) { + if menu_row(ui, width, item, tokens).clicked() { + picked = Some(action); + ui.close(); + } + } + ui.add_space(MENU_PADDING); + }); + if return_focus { + response.request_focus(); + } + picked +} + /// The Bake Mesh Maps button (the bake mode's own icon), then a slot per map: a click lists the images, × clears it fn mesh_maps(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, ts: usize, set: &TextureSet) { sheet.section(tr("Mesh Maps"), false); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 577eae45c..ff2436b12 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -272,10 +272,16 @@ mode keep island-edge padding. `textureSet.channels {ts: 0, add: ["user0"]}` adds a stored, exportable channel. Use `remove` to remove channels and `allSets: true` to apply the same edits to -every set. Inspect reports `shaded: false` for channels the viewport shader -does not use. `textureSet.channel.format {ts: 0, channel: "user0", format: "L8"}` -sets the composite format without lowering the precision of the painted layer -data. Float format selections currently store 16-bit precision. +every set. Inspect reports each channel's display `name` and `shaded: false` for +channels the viewport shader does not use. `textureSet.channel.format {ts: 0, +channel: "user0", format: "L8"}` sets the composite format without lowering the +precision of the painted layer data. Float format selections currently store +16-bit precision. `textureSet.renameChannel {ts?, channel, name}` (or `{ts?, +channel, reset: true}`) gives a user channel (`user0`..`user31`) present in the +set a custom display name of up to 128 characters after trimming; an empty +`name` or `reset: true` restores the default label. Renaming is one undo step, +removing the channel drops its custom name, and export `$channel` naming stays +unchanged. ## Control channel (desktop app) diff --git a/docs/features.md b/docs/features.md index 169b099db..03d202d4f 100644 --- a/docs/features.md +++ b/docs/features.md @@ -167,7 +167,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Texture sets** from 128 to 8192 px per material, square or with a height of their own (`textureSet.resolution {resolution, height}`), resampled when you change them, with 72 channel types to add or remove: the 21 the shader reads, more material channels that are stored and - exported, and User0 to User31 (*Add or remove channels*, `textureSet.channels`). Each channel + exported, and User0 to User31 (*Add or remove channels*, `textureSet.channels`; + double-click, press F2 or right-click a user channel in Texture Set Settings to + rename it or reset its name, `textureSet.renameChannel`). Each channel has a storage format (`textureSet.channel.format`), and each set its normal mixing, ambient occlusion mixing, height to normal method and UV padding, across seams (3D) or from island edges (2D) (`textureSet.settings`). Rename a set in the list, or reset it to the mesh