Texture Set list rows: size and shader dropdowns per row, rename in place, a right-click menu, descriptions, and a UV tile set's tiles under it with their own size

This commit is contained in:
Rebornim committed 2026-11-27 06:14:29 +00:00
1 parent 8cb65c3c40
commit 3ff32d91cc
21 files changed
+927 -210

No files matched your search

+12
View File
@@ -350,6 +350,18 @@ impl TextureSet {
self.channels.iter().map(|(channel, format)| (*channel, held(*format))).collect()
}
/// Add channel `c` in its default format (16-bit or more until a format is set, see [`TextureSet::formats`]); false when present
pub fn add_channel(&mut self, c: Channel) -> bool {
if self.has_channel(c) {
return false;
}
let format = ChannelFormat::default_for(c);
self.channels.push((c, if self.format_precision { format.at_least_16_bit() } else { format }));
self.channels.sort_by_key(|(c, _)| c.index());
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) {
+6 -16
View File
@@ -264,6 +264,8 @@ pub fn texture_set(session: &Session, index: usize) -> Value {
json!({
"index": index,
"name": texture_set.name,
"originalName": session.original_set_name(index),
"description": texture_set.description,
"resolution": texture_set.resolution,
"height": texture_set.height(),
"size": texture_set.size(),
@@ -275,22 +277,10 @@ pub fn texture_set(session: &Session, index: usize) -> Value {
"parts": crate::set_cmds::parts(session, index),
"baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)),
"visible": texture_set.visible,
"normalMixing": match texture_set.normal_mixing {
texturecraft_core::NormalMixing::Combine => "combine",
texturecraft_core::NormalMixing::Replace => "replace",
},
"aoMixing": match texture_set.ao_mixing {
texturecraft_core::AoMixing::Multiply => "multiply",
texturecraft_core::AoMixing::None => "none",
},
"heightToNormal": match texture_set.height_to_normal {
texturecraft_core::HeightToNormalMethod::Sharp => "sharp",
texturecraft_core::HeightToNormalMethod::Smooth => "smooth",
},
"uvPadding": match texture_set.uv_padding {
texturecraft_core::UvPaddingMode::Space3d => "3d",
texturecraft_core::UvPaddingMode::Space2d => "2d",
},
"normalMixing": texture_set.normal_mixing.id(),
"aoMixing": texture_set.ao_mixing.id(),
"heightToNormal": texture_set.height_to_normal.id(),
"uvPadding": texture_set.uv_padding.id(),
"active": index == session.ts(),
})
}
+104 -61
View File
@@ -20,7 +20,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Inspect texture set",
[],
None,
"{ts?} → {index, name, resolution, height, size: [w, h], uvTiles: [UDIM numbers] (empty: no UV tiles), tiles: [{udim, block: [x, y]}], channels, layers, baked, visible, 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, 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")?))
),
@@ -47,7 +47,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
visibility
),
cmd!("textureSet.rename", "Rename texture set", [], None, "{ts?, name}", always, rename),
cmd!(
"textureSet.rename",
"Rename texture set",
[],
None,
"{ts?, name} or {ts?, reset: true} (back to the mesh material's name, `originalName` in inspect)",
always,
rename
),
cmd!(
"textureSet.settings",
"Texture set settings",
@@ -121,9 +129,9 @@ pub(crate) fn select_set(s: &mut Session, ts: usize) -> Result<()> {
fn resolution(s: &mut Session, p: &Value) -> Result<Value> {
let ts = ts_param(s, p, "textureSet.resolution")?;
let r = u64p(p, "resolution").ok_or_else(|| bad("textureSet.resolution", "`resolution` is required"))?;
let height = u64p(p, "height").unwrap_or(r);
let task = s.resize_task_to(ts, u32::try_from(r).unwrap_or(0), u32::try_from(height).unwrap_or(0))?;
let width = u64p(p, "resolution").ok_or_else(|| bad("textureSet.resolution", "`resolution` is required"))?;
let height = u64p(p, "height").unwrap_or(width);
let task = s.resize_task_to(ts, u32::try_from(width).unwrap_or(0), u32::try_from(height).unwrap_or(0))?;
let out = task.run(&texturecraft_bake::Progress::new())?;
s.apply_resize(out)
}
@@ -190,12 +198,12 @@ impl ResizeOutput {
}
impl Session {
/// Prepare resizing texture set `ts` to a square `resolution` (a power of two, 128..8192).
/// Prepare resizing texture set `ts` to a square `resolution` (a power of two, 128..8192)
pub fn resize_task(&mut self, ts: usize, resolution: u32) -> Result<ResizeTask> {
self.resize_task_to(ts, resolution, resolution)
}
/// Prepare resizing texture set `ts` to `width × height` texels (powers of two, 128..8192).
/// Prepare resizing texture set `ts` to `width × height` texels (powers of two, 128..8192)
pub fn resize_task_to(&mut self, ts: usize, width: u32, height: u32) -> Result<ResizeTask> {
let (resolution, height) = (check_resolution(width)?, check_resolution(height)?);
self.doc.project.texture_set(ts)?;
@@ -262,15 +270,19 @@ fn channels(s: &mut Session, p: &Value) -> Result<Value> {
Some(_) => Err(bad(cmd, format!("`{key}` must be a list of channels"))),
}
};
let add = list("add")?;
let remove = list("remove")?;
if remove.contains(&Channel::BaseColor) {
return Err(bad(cmd, "base color can't be removed"));
}
if let Some(both) = add.iter().find(|c| remove.contains(c)) {
return Err(bad(cmd, format!("{} is both added and removed", both.label())));
}
let sets: Vec<usize> = if boolp(p, "allSets").unwrap_or(false) { (0..s.set_count()).collect() } else { vec![ts_param(s, p, cmd)?] };
s.edit("Add or remove channels", |s| {
for &ts in &sets {
for &c in &add {
@@ -280,6 +292,7 @@ fn channels(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(())
})?;
Ok(json!({ "ts": sets }))
}
@@ -291,6 +304,7 @@ fn channel_format(s: &mut Session, p: &Value) -> Result<Value> {
let name = strp(p, "format").ok_or_else(|| bad(cmd, "`format` is required"))?;
let all = || ChannelFormat::ALL.map(ChannelFormat::label).join(", ");
let format = ChannelFormat::parse(name).ok_or_else(|| bad(cmd, format!("unknown format {name:?} ({})", all())))?;
s.edit("Channel format", |s| {
if s.doc.project.texture_set_mut(ts)?.set_channel_format(c, format) {
Ok(())
@@ -298,6 +312,7 @@ fn channel_format(s: &mut Session, p: &Value) -> Result<Value> {
Err(bad(cmd, format!("the texture set has no {} channel", c.label())))
}
})?;
let float = matches!(format, ChannelFormat::L16F | ChannelFormat::Rgb16F | ChannelFormat::L32F | ChannelFormat::Rgb32F);
Ok(if float { json!({"note": "float formats are stored at 16 bits for now, and values stay in the channel's range"}) } else { Value::Null })
}
@@ -305,11 +320,8 @@ fn channel_format(s: &mut Session, p: &Value) -> Result<Value> {
/// Add channel `c` to texture set `ts` (no-op when present) and enable it on the set's layers.
/// Call inside [`Session::edit`].
pub(crate) fn add_channel(s: &mut Session, ts: usize, c: Channel) -> Result<()> {
let set = s.doc.project.texture_set_mut(ts)?;
if !set.has_channel(c) {
set.channels.push((c, ChannelFormat::default_for(c)));
set.channels.sort_by_key(|(c, _)| c.index());
}
s.doc.project.texture_set_mut(ts)?.add_channel(c);
// Existing layers get the new channel enabled.
let ids: Vec<_> = s.doc.project.walk(ts).into_iter().map(|(id, _)| id).collect();
for id in ids {
@@ -349,13 +361,23 @@ fn visibility(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "visible": s.doc.project.texture_sets.iter().map(|t| t.visible).collect::<Vec<_>>() }))
}
/// Longest texture set name and description, in characters
const MAX_NAME_CHARS: usize = 128;
const MAX_DESCRIPTION_CHARS: usize = 4096;
/// Highest height strength a set takes
const MAX_HEIGHT_STRENGTH: f32 = 100.0;
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
let ts = ts_param(s, p, "textureSet.rename")?;
let name = strp(p, "name")
.map(str::trim)
.filter(|n| !n.is_empty() && n.chars().count() <= 128)
.ok_or_else(|| bad("textureSet.rename", "`name` is required"))?
.to_string();
let name = if boolp(p, "reset") == Some(true) {
s.original_set_name(ts).ok_or_else(|| bad("textureSet.rename", "the mesh has no material name for this set"))?.to_string()
} else {
strp(p, "name")
.map(str::trim)
.filter(|name| !name.is_empty() && name.chars().count() <= MAX_NAME_CHARS)
.ok_or_else(|| bad("textureSet.rename", "`name` or `reset: true` is required"))?
.to_string()
};
s.edit("Rename texture set", |s| {
s.doc.project.texture_set_mut(ts)?.name = name;
Ok(())
@@ -363,44 +385,32 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {
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> {
let set = self.doc.project.texture_sets.get(ts)?;
self.mesh.materials.get(set.material).map(String::as_str).filter(|name| !name.trim().is_empty())
}
}
fn settings(s: &mut Session, p: &Value) -> Result<Value> {
let ts = ts_param(s, p, "textureSet.settings")?;
let nf = normal_format_param("textureSet.settings", p)?;
let ao_mixing_before = s.doc.project.texture_set(ts)?.ao_mixing;
let normal_mixing = match strp(p, "normalMixing") {
None => None,
Some("combine") => Some(NormalMixing::Combine),
Some("replace") => Some(NormalMixing::Replace),
Some(other) => return Err(bad("textureSet.settings", format!("unknown normal mixing {other:?} (combine or replace)"))),
};
let ao_mixing = match strp(p, "aoMixing") {
None => None,
Some("multiply") => Some(AoMixing::Multiply),
Some("none") => Some(AoMixing::None),
Some(other) => return Err(bad("textureSet.settings", format!("unknown ambient occlusion mixing {other:?} (multiply or none)"))),
};
let height_to_normal = match strp(p, "heightToNormal") {
None => None,
Some("sharp") => Some(HeightToNormalMethod::Sharp),
Some("smooth") => Some(HeightToNormalMethod::Smooth),
Some(other) => return Err(bad("textureSet.settings", format!("unknown height to normal method {other:?} (sharp or smooth)"))),
};
let uv_padding = match strp(p, "uvPadding") {
None => None,
Some("3d") => Some(UvPaddingMode::Space3d),
Some("2d") => Some(UvPaddingMode::Space2d),
Some(other) => return Err(bad("textureSet.settings", format!("unknown UV padding {other:?} (3d or 2d)"))),
};
let normal_format = normal_format_param("textureSet.settings", p)?;
let normal_mixing = choice_param(p, "normalMixing", "normal mixing", NormalMixing::parse, &NormalMixing::ALL.map(NormalMixing::id))?;
let ao_mixing = choice_param(p, "aoMixing", "ambient occlusion mixing", AoMixing::parse, &AoMixing::ALL.map(AoMixing::id))?;
let height_to_normal =
choice_param(p, "heightToNormal", "height to normal method", HeightToNormalMethod::parse, &HeightToNormalMethod::ALL.map(HeightToNormalMethod::id))?;
let uv_padding = choice_param(p, "uvPadding", "UV padding", UvPaddingMode::parse, &UvPaddingMode::ALL.map(UvPaddingMode::id))?;
s.edit("Texture set settings", |s| {
if let Some(n) = nf {
s.doc.project.normal_format = n;
if let Some(format) = normal_format {
s.doc.project.normal_format = format;
}
let set = s.doc.project.texture_set_mut(ts)?;
if let Some(d) = strp(p, "description") {
set.description = d.chars().take(4096).collect();
if let Some(description) = strp(p, "description") {
set.description = description.chars().take(MAX_DESCRIPTION_CHARS).collect();
}
if let Some(h) = f32p(p, "heightStrength") {
set.height_strength = h.clamp(0.0, 100.0);
if let Some(strength) = f32p(p, "heightStrength") {
set.height_strength = strength.clamp(0.0, MAX_HEIGHT_STRENGTH);
}
if let Some(mixing) = normal_mixing {
set.normal_mixing = mixing;
@@ -416,16 +426,16 @@ fn settings(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(())
})?;
// The viewport's occlusion texture mixes the baked map in: resend the set
if s.doc.project.texture_set(ts)?.ao_mixing != ao_mixing_before
&& let Some(cache) = s.caches.get_mut(ts)
{
cache.upload.extend(texturecraft_compose::all_tiles(cache.size.0, cache.size.1));
}
Ok(Value::Null)
}
/// The optional setting `key` of `textureSet.settings`, one of `ids`
fn choice_param<T>(p: &Value, key: &str, what: &str, parse: fn(&str) -> Option<T>, ids: &[&str]) -> Result<Option<T>> {
let Some(id) = strp(p, key) else { return Ok(None) };
parse(id).map(Some).ok_or_else(|| bad("textureSet.settings", format!("unknown {what} {id:?} ({})", ids.join(" or "))))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -453,6 +463,18 @@ mod tests {
assert!(crate::execute(&mut s, "textureSet.channels", &json!({"add": ["nope"]})).is_err());
}
#[test]
fn rename_reset_restores_the_mesh_material_name() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let original = crate::execute(&mut s, "textureSet.inspect", &json!({"ts": 1})).unwrap()["name"].clone();
crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "Renamed"})).unwrap();
let inspect = crate::execute(&mut s, "textureSet.inspect", &json!({"ts": 1})).unwrap();
assert_eq!((&inspect["name"], &inspect["originalName"]), (&json!("Renamed"), &original));
crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1, "reset": true})).unwrap();
assert_eq!(crate::execute(&mut s, "textureSet.inspect", &json!({"ts": 1})).unwrap()["name"], original);
assert!(crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1})).is_err());
}
#[test]
fn visibility_shows_hides_inverts_and_solos() {
// The material ball has two texture sets.
@@ -516,7 +538,10 @@ mod tests {
#[test]
fn channel_format_changes_what_the_viewport_holds_and_undoes() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let format = |s: &Session| crate::inspect::texture_set(s, 0)["channels"][2]["format"].clone();
let format = |s: &Session| {
let channels = crate::inspect::texture_set(s, 0)["channels"].clone();
channels.as_array().and_then(|list| list.iter().find(|entry| entry["channel"] == "roughness")).map(|entry| entry["format"].clone())
};
let roughness = |s: &mut Session| {
s.update();
let img = &s.caches[0].composite.channels[&Channel::Roughness];
@@ -524,15 +549,17 @@ mod tests {
img.tile(tile.0, tile.1).map(<[u16]>::to_vec).unwrap_or_default()
};
crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "roughness", "format": "L16"})).unwrap();
// A roughness off the 8-bit grid, so 8 bits visibly round it
crate::execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3013})).unwrap();
let sixteen = roughness(&mut s);
assert_eq!(format(&s), json!("L16"));
assert_eq!(format(&s), Some(json!("L16")));
crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "Roughness", "format": "l8"})).unwrap();
let eight = roughness(&mut s);
assert_eq!(format(&s), json!("L8"));
assert_eq!(format(&s), Some(json!("L8")));
assert_ne!(eight, sixteen, "the composite holds 8 bits");
assert!(eight.iter().all(|v| v % 257 == 0), "every texel is on an 8-bit step");
let eight_bit_step = u16::MAX / u16::from(u8::MAX);
assert!(eight.iter().all(|v| v % eight_bit_step == 0), "every texel is on an 8-bit step");
let float = crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "height", "format": "L32F"})).unwrap();
assert!(float["note"].is_string(), "a float format says it holds 16 bits");
@@ -540,7 +567,23 @@ mod tests {
assert!(crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "roughness", "format": "L4"})).is_err());
assert!(crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "emissive", "format": "L8"})).is_err());
crate::execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!((format(&s), roughness(&mut s)), (json!("L16"), sixteen));
assert_eq!((format(&s), roughness(&mut s)), (Some(json!("L16")), sixteen));
}
#[test]
fn channels_added_after_a_format_is_set_keep_16_bits() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let format = |s: &Session, id: &str| {
let channels = crate::inspect::texture_set(s, 0)["channels"].clone();
channels.as_array().and_then(|list| list.iter().find(|entry| entry["channel"] == id)).map(|entry| entry["format"].clone())
};
crate::execute(&mut s, "textureSet.channel.format", &json!({"ts": 0, "channel": "roughness", "format": "L8"})).unwrap();
crate::execute(&mut s, "textureSet.channel.add", &json!({"ts": 0, "channel": "user3"})).unwrap();
crate::execute(&mut s, "textureSet.channels", &json!({"ts": 0, "add": ["user4"]})).unwrap();
assert_eq!((format(&s, "user3"), format(&s, "user4")), (Some(json!("L16")), Some(json!("L16"))));
assert_eq!(format(&s, "roughness"), Some(json!("L8")), "the set format stays");
}
#[test]
+1 -94
View File
@@ -36,100 +36,7 @@ const TAG_COLORS: [Color32; 8] = [
];
pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) {
// The empty state lists nothing
if !app.session.project_open {
return;
}
let tk = Tokens::get(ui.ctx());
let sets: Vec<(String, String, bool)> = app
.session
.doc
.project
.texture_sets
.iter()
.map(|t| {
let (width, height) = (t.resolution, t.height());
let size = match t.uv_tiles.len() {
0 => format!("{width}x{height}"),
n => format!("{width}x{height}, {n} UDIM"),
};
(t.name.clone(), size, t.visible)
})
.collect();
let active = app.session.ts();
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 4.0;
ui.menu_button(RichText::new(ic::EYE).size(14.0), |ui| {
for (label, mode) in [(tr("Show all"), "showAll"), (tr("Hide all"), "hideAll"), (tr("Invert show/hide"), "invert")] {
if ui.button(label).clicked() {
app.run("textureSet.visibility", json!({ "mode": mode }));
ui.close();
}
}
})
.response
.on_hover_text(tr("Show or hide texture sets"));
let solo = sets.iter().enumerate().all(|(i, s)| s.2 == (i == active));
if icon_button(ui, ic::FRAME_CORNERS, tr("Focus: show only the active texture set"), solo && sets.len() > 1, 22.0).clicked() {
app.run("textureSet.visibility", json!({ "mode": "solo" }));
}
});
egui::ScrollArea::vertical().id_salt("ts_scroll").show(ui, |ui| {
for (i, (name, size, visible)) in sets.into_iter().enumerate() {
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, ui.is_enabled(), &name));
ui.ctx().accesskit_node_builder(resp.id, |node| node.set_selected(i == active));
let p = ui.painter();
let bg = if i == active {
tk.row_selected
} else if resp.hovered() {
tk.row_hover
} else {
tk.panel
};
p.rect_filled(rect, 2.0, bg);
if i == active {
p.rect_stroke(rect, 2.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside);
}
if resp.has_focus() {
p.rect_stroke(rect.shrink(2.0), 2.0, Stroke::new(1.0, tk.text_strong), egui::StrokeKind::Inside);
}
let eye = Rect::from_min_size(rect.min + vec2(4.0, 3.0), vec2(16.0, 16.0));
let eye_resp = ui.interact(eye, ui.scope_id().with(("ts_eye", i)), Sense::click()).on_hover_text(tr("Show or hide the texture set"));
p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(13.0), tk.text);
if ui.is_enabled() && (resp.contains_pointer() || eye_resp.contains_pointer()) {
app.next_hovered_texture_set = Some((app.session.project_id, i));
}
// Narrow panels drop the shader label, then the resolution, before cutting the name
let cy = rect.center().y;
let mut right = rect.right() - 6.0;
if rect.width() >= 260.0 {
let g = p.layout_no_wrap(tr("Main shader").into(), egui::FontId::proportional(11.0), tk.text_dim);
right -= g.size().x;
p.galley(pos2(right, cy - g.size().y * 0.5), g, tk.text_dim);
right -= 10.0;
}
if rect.width() >= 170.0 {
let g = p.layout_no_wrap(size, egui::FontId::proportional(11.0), tk.text_dim);
let x = (rect.left() + rect.width() * 0.48).min(right - g.size().x);
p.galley(pos2(x, cy - g.size().y * 0.5), g, tk.text_dim);
right = x - 8.0;
}
let color = if i == active { tk.text_strong } else { tk.text };
let g = elided(p, name, 12.0, color, right - rect.left() - 26.0);
p.galley(pos2(rect.left() + 26.0, cy - g.size().y * 0.5), g, color);
if eye_resp.clicked() {
app.run("textureSet.visible", json!({"ts": i}));
} else if resp.clicked() {
app.run("textureSet.select", json!({"ts": i}));
}
}
});
crate::texture_set_list::show(app, ui);
}
// ---------------------------------------------------------------------------------------------
+3 -2
View File
@@ -168,10 +168,11 @@ pub fn default_workspace() -> Workspace {
// 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;
// Three texture set rows show at the default window height
const TEXTURE_SET_SPLIT_RATIO: f32 = 0.2;
// Leave room for three layer rows and the fill's channel controls
const LAYERS_SPLIT_RATIO: f32 = 0.31;
const LAYERS_SPLIT_RATIO: f32 = 0.34;
let column = split(
Axis::Y,
+27 -13
View File
@@ -22,11 +22,11 @@ mod item_icon;
mod menu_icon;
mod pick;
use add_item::AddItem;
pub(crate) use add_item::AddItem;
use bitmap_choice::BitmapChoice;
use item_icon::ItemIcon;
use menu_icon::MenuIcon;
use pick::Pick;
pub(crate) use item_icon::ItemIcon;
pub(crate) use menu_icon::MenuIcon;
pub(crate) use pick::Pick;
/// The row's height and its controls' height
const BAR_HEIGHT: f32 = 40.0;
@@ -64,7 +64,7 @@ const LAYER_BUTTONS_WIDTH: f32 = 4.0 * BUTTON_WIDTH + 3.0 * BUTTON_GAP;
const ONE_ROW_WIDTH: f32 = MENUS_ROW_WIDTH + CHANNEL_WIDTH + GROUP_GAP + LAYER_BUTTONS_WIDTH;
/// A hanging menu: its caption, rows, icon and text columns and its smallest width
const MENU_PADDING: f32 = 4.0;
pub(crate) const MENU_PADDING: f32 = 4.0;
const MENU_CAPTION_HEIGHT: f32 = 22.0;
const MENU_CAPTION_X: f32 = 12.0;
const MENU_CAPTION_SIZE: f32 = 10.0;
@@ -201,7 +201,15 @@ const TAB_SEAM_COVER: f32 = 2.5;
const TAB_BORDER_WIDTH: f32 = 1.0;
/// A button with its icon and a caret whose menu hangs from it (caption, then the `items` built while it is open); the item picked
fn menu_button(ui: &mut Ui, rect: Rect, label: &str, icon: MenuIcon, caption: &str, items: impl FnOnce() -> Vec<AddItem>, tokens: &Tokens) -> Option<Pick> {
pub(crate) fn menu_button(
ui: &mut Ui,
rect: Rect,
label: &str,
icon: MenuIcon,
caption: &str,
items: impl FnOnce() -> Vec<AddItem>,
tokens: &Tokens,
) -> Option<Pick> {
let response = tip_above(ui.interact(rect, ui.scope_id().with(("layer_toolbar_menu", label)), Sense::click()), label);
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));
let popup = ui.scope_id().with(("layer_toolbar_menu_popup", label));
@@ -215,11 +223,7 @@ fn menu_button(ui: &mut Ui, rect: Rect, label: &str, icon: MenuIcon, caption: &s
// A click opens the menu this frame
let items = if open || response.clicked() { items() } else { Vec::new() };
let width = menu_width(ui, &items);
let frame = Frame::NONE
.fill(tokens.chrome)
.stroke(Stroke::new(1.0, tokens.field_border))
.corner_radius(CornerRadius { nw: 0, ..CornerRadius::same(MENU_ROUNDING) })
.shadow(Shadow { offset: SHADOW_OFFSET, blur: 0, spread: 0, color: HARD_SHADOW });
let frame = menu_frame(tokens).corner_radius(CornerRadius { nw: 0, ..CornerRadius::same(MENU_ROUNDING) });
let mut picked = None;
let shown = egui::Popup::menu(&response).id(popup).align(egui::RectAlign::BOTTOM_START).gap(MENU_TAB_OVERLAP).frame(frame).width(width).show(|ui| {
ui.set_width(width);
@@ -256,6 +260,16 @@ fn menu_button(ui: &mut Ui, rect: Rect, label: &str, icon: MenuIcon, caption: &s
picked
}
/// The toolbar menus' frame: chrome fill, field border, hard shadow
pub(crate) fn menu_frame(tokens: &Tokens) -> Frame {
Frame::NONE.fill(tokens.chrome).stroke(Stroke::new(1.0, tokens.field_border)).corner_radius(CornerRadius::same(MENU_ROUNDING)).shadow(Shadow {
offset: SHADOW_OFFSET,
blur: 0,
spread: 0,
color: HARD_SHADOW,
})
}
/// A menu button's icon and caret
fn button_face(painter: &Painter, rect: Rect, icon: MenuIcon, tokens: &Tokens) {
let icon_at = pos2(rect.left() + MENU_ICON_X, rect.center().y);
@@ -269,7 +283,7 @@ fn button_face(painter: &Painter, rect: Rect, icon: MenuIcon, tokens: &Tokens) {
}
/// The menu's width: its longest item, with room for the icons and the right edge
fn menu_width(ui: &Ui, items: &[AddItem]) -> f32 {
pub(crate) fn menu_width(ui: &Ui, items: &[AddItem]) -> f32 {
let widest = items
.iter()
.map(|item| ui.fonts_mut(|fonts| fonts.layout_no_wrap(tr(item.short).to_owned(), FontId::proportional(TEXT_SIZE), Color32::WHITE).size().x))
@@ -278,7 +292,7 @@ fn menu_width(ui: &Ui, items: &[AddItem]) -> f32 {
}
/// One menu row: hover face, icon, name; dim and unclickable when it can't go where the selection is
fn menu_row(ui: &mut Ui, width: f32, item: &AddItem, tokens: &Tokens) -> Response {
pub(crate) fn menu_row(ui: &mut Ui, width: f32, item: &AddItem, tokens: &Tokens) -> Response {
let sense = if item.enabled { Sense::click() } else { Sense::hover() };
let (rect, response) = ui.allocate_exact_size(vec2(width, MENU_ROW), sense);
let label = tr(item.short);
+7 -7
View File
@@ -3,12 +3,12 @@ use serde_json::Value;
use super::ItemIcon;
/// One item of the Add effect or Add mask menu
pub(super) struct AddItem {
pub(super) icon: ItemIcon,
pub(crate) struct AddItem {
pub(crate) icon: ItemIcon,
/// The toolbar menu's name (the button says "Add effect" / "Add mask") and the layer context menu's
pub(super) short: &'static str,
pub(super) long: &'static str,
pub(super) command: &'static str,
pub(super) params: Value,
pub(super) enabled: bool,
pub(crate) short: &'static str,
pub(crate) long: &'static str,
pub(crate) command: &'static str,
pub(crate) params: Value,
pub(crate) enabled: bool,
}
@@ -1,6 +1,6 @@
/// What an Add menu item shows at its left
#[derive(Clone, Copy)]
pub(super) enum ItemIcon {
pub(crate) enum ItemIcon {
Glyph(&'static str),
/// A gray swatch (Add mask's White and Black)
Swatch(u8),
@@ -1,6 +1,6 @@
/// The icon of a menu button
#[derive(Clone, Copy)]
pub(super) enum MenuIcon {
pub(crate) enum MenuIcon {
Glyph(&'static str),
/// Add mask's square, half of it filled corner to corner
Mask,
+1 -1
View File
@@ -1,7 +1,7 @@
use serde_json::Value;
/// What a click in one of the row's menus asks for, done once the menu has closed
pub(super) enum Pick {
pub(crate) enum Pick {
Run { command: &'static str, params: Value },
Bitmap,
}
+1
View File
@@ -172,6 +172,7 @@ mod source_slot;
pub mod state;
mod surface_paint_point;
pub mod symmetry;
mod texture_set_list;
pub mod theme;
pub mod thumbs;
mod tile_edits;
+31 -13
View File
@@ -77,6 +77,36 @@ const CHOSEN_BAR_RADIUS: u8 = 1;
/// The hovered option's eye glyph size
const EYE_SIZE: f32 = 13.0;
/// An option's hover fill, the chosen one's accent bar and its keyboard focus outline
fn paint_option(painter: &Painter, rect: Rect, response: &Response, chosen: bool, tokens: &crate::theme::Tokens) {
if response.hovered() {
let fill = Rect::from_min_max(pos2(rect.left() + HOVER_INSET, rect.top()), pos2(rect.right() - HOVER_INSET, rect.bottom() - HOVER_BOTTOM_GAP));
painter.rect_filled(fill, CornerRadius::same(CONTROL_RADIUS), tokens.button);
}
if chosen {
let bar = Rect::from_min_max(
pos2(rect.left() + CHOSEN_BAR_LEFT, rect.top() + CHOSEN_BAR_TOP),
pos2(rect.left() + CHOSEN_BAR_RIGHT, rect.bottom() - CHOSEN_BAR_BOTTOM),
);
painter.rect_filled(bar, CornerRadius::same(CHOSEN_BAR_RADIUS), tokens.accent);
}
if response.has_focus() {
painter.rect_stroke(rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(OPTION_FOCUS_WIDTH, tokens.text_strong), StrokeKind::Inside);
}
}
/// One option of a list drawn outside a sheet (a menu popup), the full width of `ui`, looking like a sheet dropdown's option
pub(crate) fn option_row(ui: &mut egui::Ui, text: &str, chosen: bool) -> Response {
let tokens = crate::theme::Tokens::get(ui.ctx());
let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), OPTION_HEIGHT), Sense::click());
response.widget_info(|| WidgetInfo::selected(Role::ListBoxOption, true, chosen, text));
let painter = ui.painter();
paint_option(painter, rect, &response, chosen, &tokens);
let font = if chosen { semibold(TEXT_SIZE) } else { FontId::proportional(TEXT_SIZE) };
painter.text(pos2(rect.left() + VALUE_INSET, rect.top() + OPTION_HEIGHT / 2.0 - OPTION_TEXT_LIFT), Align2::LEFT_CENTER, text, font, tokens.text);
response
}
impl PropertySheet<'_> {
/// A set-once choice whose list hangs from its button; returns the picked and the hovered option
pub(crate) fn dropdown<T: Copy + PartialEq>(
@@ -225,20 +255,8 @@ impl PropertySheet<'_> {
response.widget_info(|| WidgetInfo::selected(Role::ListBoxOption, true, chosen, name(option)));
if response.hovered() {
hovered = Some(option);
let fill =
Rect::from_min_max(pos2(rect.left() + HOVER_INSET, rect.top()), pos2(rect.right() - HOVER_INSET, rect.bottom() - HOVER_BOTTOM_GAP));
painter.rect_filled(fill, CornerRadius::same(CONTROL_RADIUS), tokens.button);
}
if chosen {
let bar = Rect::from_min_max(
pos2(rect.left() + CHOSEN_BAR_LEFT, rect.top() + CHOSEN_BAR_TOP),
pos2(rect.left() + CHOSEN_BAR_RIGHT, rect.bottom() - CHOSEN_BAR_BOTTOM),
);
painter.rect_filled(bar, CornerRadius::same(CHOSEN_BAR_RADIUS), tokens.accent);
}
if response.has_focus() {
painter.rect_stroke(rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(OPTION_FOCUS_WIDTH, tokens.text_strong), StrokeKind::Inside);
}
paint_option(painter, rect, &response, chosen, &tokens);
// Align the option text and picture with the button despite the list border
let button_left = rect.left() - LIST_BORDER;
+1
View File
@@ -62,6 +62,7 @@ mod tests;
pub(crate) use action_row_response::ActionRowResponse;
pub(crate) use band_response::BandResponse;
pub(crate) use button_icon::ButtonIcon;
pub(crate) use choice::option_row;
pub(crate) use compare_row_response::CompareRowResponse;
pub(crate) use file_list_add::FileListAdd;
pub(crate) use file_list_response::FileListResponse;
+646
View File
@@ -0,0 +1,646 @@
//! The Texture Set list: a toolbar, one row per set with its dropdowns, edits in place, a menu and a UV tile set's tiles
use egui::{Align2, CornerRadius, FontId, Popup, Rect, Response, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
use egui_phosphor::regular as ic;
use serde_json::json;
use texturecraft_engine::core::project::{MAX_RESOLUTION, MIN_RESOLUTION};
use crate::TextureCraftApp;
use crate::i18n::{tr, trf};
use crate::layer_toolbar::{AddItem, ItemIcon, MENU_PADDING, MenuIcon, Pick, menu_button, menu_frame, menu_row, menu_width};
use crate::property_sheet::option_row;
use crate::theme::{Tokens, semibold};
use crate::widgets::elided;
mod description_mode;
mod list_state;
mod row_action;
mod row_edit;
mod set_row;
mod tile_action;
use description_mode::DescriptionMode;
pub(crate) use list_state::ListState;
use row_action::RowAction;
use row_edit::RowEdit;
use set_row::SetRow;
use tile_action::TileAction;
/// The layer toolbar's height and its menu buttons, so both panels' toolbars line up
const BAR_HEIGHT: f32 = 40.0;
const BAR_PADDING: f32 = 8.0;
const MENU_BUTTON: egui::Vec2 = vec2(32.0, 26.0);
const SOLO_SIZE: f32 = 24.0;
const SOLO_GAP: f32 = 6.0;
/// Row geometry: a set row, the description line under it and a UV tile row
const ROW_HEIGHT: f32 = 28.0;
const DESCRIPTION_HEIGHT: f32 = 14.0;
const TILE_ROW_HEIGHT: f32 = 24.0;
const ROW_GAP: f32 = 2.0;
const ROW_INSET: f32 = 6.0;
const ROW_ROUNDING: u8 = 4;
const GLYPH_SIZE: f32 = 20.0;
const GLYPH_FONT: f32 = 14.0;
const NAME_GAP: f32 = 8.0;
const FOLD_WIDTH: f32 = 14.0;
const TILE_INDENT: f32 = 34.0;
const TILE_BRANCH: f32 = 12.0;
const NAME_SIZE: f32 = 12.0;
const DESCRIPTION_SIZE: f32 = 11.0;
const CARET_SIZE: f32 = 11.0;
/// A row dropdown: its text, the caret after it and the air around both
const DROPDOWN_HEIGHT: f32 = 22.0;
const DROPDOWN_TEXT_X: f32 = 6.0;
const DROPDOWN_CARET_GAP: f32 = 4.0;
const DROPDOWN_RIGHT: f32 = 6.0;
const DROPDOWN_GAP: f32 = 4.0;
const SIZE_LIST_WIDTH: f32 = 72.0;
/// Narrow panels drop the shader dropdown, then the size, before cutting the name
const SHADER_MIN_ROW_WIDTH: f32 = 240.0;
const SIZE_MIN_ROW_WIDTH: f32 = 160.0;
/// From an edit field's left edge to its text: the field starts this far left of the drawn text
const EDIT_TEXT_X: f32 = 4.0;
/// The name field's air above and below inside the row
const EDIT_FIELD_INSET: f32 = 3.0;
/// The description line starts this far up into the set row and stops this far above the row's end
const DESCRIPTION_OVERLAP: f32 = 4.0;
const DESCRIPTION_BOTTOM: f32 = 1.0;
/// The description field's air above and below its text
const DESCRIPTION_FIELD_AIR: f32 = 1.0;
/// How far an empty description's placeholder fades from the dim text
const PLACEHOLDER_FADE: f32 = 0.7;
/// Keyboard focus ring: inset from the row's edge
const FOCUS_INSET: f32 = 2.0;
/// Space between a dropdown and its list
const MENU_GAP: f32 = 1.0;
/// The project's one shader, which every set uses
const SHADER_NAME: &str = "Main shader";
pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
// The empty state lists nothing
if !app.session.project_open {
return;
}
let tokens = Tokens::get(ui.ctx());
let mut state = ListState::load(ui.ctx());
let rows: Vec<SetRow> = (0..app.session.doc.project.texture_sets.len())
.filter_map(|index| {
let set = app.session.doc.project.texture_sets.get(index)?;
Some(SetRow {
name: set.name.clone(),
description: set.description.clone(),
original_name: app.session.original_set_name(index).map(str::to_owned),
width: set.resolution,
height: set.height(),
visible: set.visible,
tiles: set.uv_tiles.iter().map(|tile| (*tile, set.tile_resolution(*tile))).collect(),
})
})
.collect();
// A picked UV tile only stays picked while its set is the active one
let active = app.session.ts();
if state.tile.is_some_and(|(set, tile)| set != active || !rows.get(set).is_some_and(|row| row.tiles.iter().any(|(udim, _)| *udim == tile))) {
state.tile = None;
}
toolbar(app, ui, &mut state, &rows, active, &tokens);
egui::ScrollArea::vertical().id_salt("ts_scroll").show(ui, |ui| {
ui.spacing_mut().item_spacing = vec2(0.0, ROW_GAP);
for (index, row) in rows.iter().enumerate() {
let action = set_row(app, ui, &mut state, index, row, index == active, &tokens);
if !row.tiles.is_empty() && !state.folded.contains(&index) {
for (udim, resolution) in &row.tiles {
let selected = state.tile == Some((index, *udim));
match tile_row(ui, index, *udim, *resolution, row.width, selected, &tokens) {
Some(TileAction::Select) => {
app.run("textureSet.select", json!({"ts": index}));
state.tile = Some((index, *udim));
}
Some(TileAction::Resize(size)) => {
app.run("textureSet.tile.resolution", json!({"ts": index, "tile": udim, "resolution": size}));
}
None => {}
}
}
}
match action {
Some(RowAction::Select) => {
app.run("textureSet.select", json!({"ts": index}));
state.tile = None;
}
Some(RowAction::ToggleVisible) => {
app.run("textureSet.visible", json!({"ts": index}));
}
Some(RowAction::Resize(width)) => {
app.start_resize(index, width);
}
Some(RowAction::Edit(edit)) => {
let text = if edit == RowEdit::Name { row.name.clone() } else { row.description.clone() };
state.edit = Some((index, edit, text, true));
}
Some(RowAction::ResetName) => {
app.run("textureSet.rename", json!({"ts": index, "reset": true}));
}
Some(RowAction::ToggleFold) => {
if state.folded.contains(&index) {
state.folded.remove(&index);
} else {
state.folded.insert(index);
}
}
None => {}
}
}
});
state.store(ui.ctx());
}
/// Visibility menu and solo at the left, the descriptions menu at the right
fn toolbar(app: &mut TextureCraftApp, ui: &mut Ui, state: &mut ListState, rows: &[SetRow], active: usize, tokens: &Tokens) {
let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), BAR_HEIGHT), Sense::hover());
let visibility = Rect::from_min_size(pos2(bar.left() + BAR_PADDING, bar.center().y - MENU_BUTTON.y * 0.5), MENU_BUTTON);
let items = || {
[(ic::EYE, "Show All", "showAll"), (ic::EYE_SLASH, "Hide All", "hideAll"), (ic::SWAP, "Invert Show/Hide", "invert")]
.into_iter()
.map(|(glyph, short, mode)| AddItem {
icon: ItemIcon::Glyph(glyph),
short,
long: short,
command: "textureSet.visibility",
params: json!({ "mode": mode }),
enabled: true,
})
.collect()
};
if let Some(Pick::Run { command, params }) =
menu_button(ui, visibility, tr("Show or hide texture sets"), MenuIcon::Glyph(ic::EYE), tr("Visibility"), items, tokens)
{
app.run(command, params);
}
let solo_rect = Rect::from_min_size(pos2(visibility.right() + SOLO_GAP, bar.center().y - SOLO_SIZE * 0.5), vec2(SOLO_SIZE, SOLO_SIZE));
let solo = rows.len() > 1 && rows.iter().enumerate().all(|(index, row)| row.visible == (index == active));
if glyph_button(ui, "ts_solo", solo_rect, ic::NUMBER_CIRCLE_ONE, tr("Show only the selected texture set"), solo, tokens).clicked() {
app.run("textureSet.visibility", json!({ "mode": "solo" }));
}
// The descriptions choice is the list's own look, so it stays in the UI
let menu = Rect::from_min_size(pos2(bar.right() - BAR_PADDING - MENU_BUTTON.x, bar.center().y - MENU_BUTTON.y * 0.5), MENU_BUTTON);
let modes = [
(DescriptionMode::HideEmpty, "Hide Empty Descriptions"),
(DescriptionMode::ShowAll, "Show All Descriptions"),
(DescriptionMode::HideAll, "Hide All Descriptions"),
];
let current = state.descriptions;
let items = || {
modes
.iter()
.enumerate()
.map(|(index, (mode, short))| AddItem {
icon: ItemIcon::Glyph(if *mode == current { ic::CHECK } else { "" }),
short,
long: short,
command: "",
params: json!(index),
enabled: true,
})
.collect()
};
if let Some(Pick::Run { params, .. }) = menu_button(ui, menu, tr("Texture set list settings"), MenuIcon::Glyph(ic::LIST), tr("Descriptions"), items, tokens)
&& let Some((mode, _)) = params.as_u64().and_then(|index| modes.get(usize::try_from(index).ok()?))
{
state.descriptions = *mode;
}
}
/// One texture set: eye, fold caret for UV tiles, name (or its field), size and shader dropdowns, description line
fn set_row(app: &mut TextureCraftApp, ui: &mut Ui, state: &mut ListState, index: usize, row: &SetRow, selected: bool, tokens: &Tokens) -> Option<RowAction> {
let editing_description = matches!(state.edit, Some((set, RowEdit::Description, ..)) if set == index);
let description_line = editing_description || state.descriptions.shows(&row.description);
let height = if description_line { ROW_HEIGHT + DESCRIPTION_HEIGHT } else { ROW_HEIGHT };
let (full, response) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::click());
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, ui.is_enabled(), &row.name));
ui.ctx().accesskit_node_builder(response.id, |node| node.set_selected(selected));
let rect = Rect::from_min_size(full.min, vec2(full.width(), ROW_HEIGHT));
let painter = ui.painter();
if selected {
painter.rect(full, CornerRadius::same(ROW_ROUNDING), tokens.row_selected, Stroke::new(1.0, tokens.accent), StrokeKind::Inside);
} else if response.hovered() {
painter.rect_filled(full, CornerRadius::same(ROW_ROUNDING), tokens.row_hover);
}
if response.has_focus() {
painter.rect_stroke(full.shrink(FOCUS_INSET), CornerRadius::same(ROW_ROUNDING), Stroke::new(1.0, tokens.text_strong), StrokeKind::Inside);
}
let mut action = None;
let eye = Rect::from_center_size(pos2(rect.left() + ROW_INSET + GLYPH_SIZE * 0.5, rect.center().y), vec2(GLYPH_SIZE, GLYPH_SIZE));
let eye_label = if row.visible { tr("Hide texture set") } else { tr("Show texture set") };
let eye_response = glyph_button(ui, ("ts_eye", index), eye, if row.visible { ic::EYE } else { ic::EYE_SLASH }, eye_label, false, tokens);
if eye_response.clicked() {
action = Some(RowAction::ToggleVisible);
}
if ui.is_enabled() && (response.contains_pointer() || eye_response.contains_pointer()) {
app.next_hovered_texture_set = Some((app.session.project_id, index));
}
let mut name_x = eye.right() + NAME_GAP;
if !row.tiles.is_empty() {
let folded = state.folded.contains(&index);
let fold = Rect::from_min_size(pos2(name_x - NAME_GAP * 0.5, rect.top()), vec2(FOLD_WIDTH, ROW_HEIGHT));
let label = if folded { tr("Show UV tiles") } else { tr("Hide UV tiles") };
if glyph_button(ui, ("ts_fold", index), fold, if folded { ic::CARET_RIGHT } else { ic::CARET_DOWN }, label, false, tokens).clicked() {
action = Some(RowAction::ToggleFold);
}
name_x = fold.right() + NAME_GAP * 0.5;
}
// Dropdowns from the right edge: shader, then size
let mut right = rect.right() - ROW_INSET;
let name_color = if !row.visible {
tokens.text_dim
} else if selected {
tokens.text_strong
} else {
tokens.text
};
if rect.width() >= SHADER_MIN_ROW_WIDTH {
let shader = tr(SHADER_NAME);
let name = trf("Shader of {name}", &[("name", &row.name)]);
let dropdown = row_dropdown(ui, ("ts_shader", index), pos2(right, rect.center().y), (shader, &name), true, tokens, |ui| {
let _ = option_row(ui, shader, true);
});
right = dropdown.left() - DROPDOWN_GAP;
}
if rect.width() >= SIZE_MIN_ROW_WIDTH {
let text = if row.width == row.height { row.width.to_string() } else { format!("{}x{}", row.width, row.height) };
let mut picked = None;
let name = trf("Size of {name}", &[("name", &row.name)]);
let dropdown = row_dropdown(ui, ("ts_size", index), pos2(right, rect.center().y), (&text, &name), true, tokens, |ui| {
picked = size_list(ui, row.width);
});
if let Some(size) = picked {
action = Some(RowAction::Resize(size));
}
right = dropdown.left() - DROPDOWN_GAP;
}
let editing_name = matches!(state.edit, Some((set, RowEdit::Name, ..)) if set == index);
if editing_name {
let field = Rect::from_min_max(pos2(name_x - EDIT_TEXT_X, rect.top() + EDIT_FIELD_INSET), pos2(right, rect.bottom() - EDIT_FIELD_INSET));
if let Some(name) = edit_field(ui, state, field, NAME_SIZE)
&& name.trim() != row.name
{
app.run("textureSet.rename", json!({"ts": index, "name": name}));
}
} else {
let font = if selected { semibold(NAME_SIZE) } else { FontId::proportional(NAME_SIZE) };
let mut job = egui::text::LayoutJob::simple_singleline(row.name.clone(), font, name_color);
job.wrap = egui::text::TextWrapping::truncate_at_width((right - name_x).max(0.0));
let galley = ui.painter().layout_job(job);
ui.painter().galley(pos2(name_x, rect.center().y - galley.size().y * 0.5), galley, name_color);
}
if description_line {
let line = Rect::from_min_max(pos2(name_x, rect.bottom() - DESCRIPTION_OVERLAP), pos2(full.right() - ROW_INSET, full.bottom() - DESCRIPTION_BOTTOM));
if editing_description {
if let Some(description) = edit_field(ui, state, line.expand2(vec2(EDIT_TEXT_X, DESCRIPTION_FIELD_AIR)), DESCRIPTION_SIZE)
&& description.trim() != row.description
{
app.run("textureSet.settings", json!({"ts": index, "description": description.trim()}));
}
} else {
let (text, color) = if row.description.trim().is_empty() {
(tr("No description").to_owned(), tokens.text_dim.gamma_multiply(PLACEHOLDER_FADE))
} else {
(row.description.clone(), tokens.text_dim)
};
let galley = elided(ui.painter(), text, DESCRIPTION_SIZE, color, line.width());
ui.painter().galley(pos2(line.left(), line.center().y - galley.size().y * 0.5), galley, color);
}
}
// F2 renames the focused row, as a double click does
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 {
action = Some(RowAction::Edit(RowEdit::Name));
} else if action.is_none() && (response.clicked() || response.secondary_clicked()) {
action = Some(RowAction::Select);
}
context_menu(ui, &response, row, tokens).or(action)
}
/// The row's right-click menu (Shift+F10 or the Menu key on a focused row), in the toolbar menus' look
fn context_menu(ui: &Ui, response: &Response, row: &SetRow, tokens: &Tokens) -> Option<RowAction> {
let renamed = row.original_name.as_ref().is_some_and(|original| *original != row.name);
let visibility = if row.visible { (ic::EYE_SLASH, "Hide Texture Set") } else { (ic::EYE, "Show Texture Set") };
let entries = [
(visibility.0, visibility.1, true, RowAction::ToggleVisible),
(ic::PENCIL_SIMPLE, "Edit Name", true, RowAction::Edit(RowEdit::Name)),
(ic::ARROW_COUNTER_CLOCKWISE, "Reset Name to Original", renamed, RowAction::ResetName),
(ic::NOTE_PENCIL, "Edit Description", true, RowAction::Edit(RowEdit::Description)),
];
let items = entries.map(|(glyph, short, enabled, _)| AddItem {
icon: ItemIcon::Glyph(glyph),
short,
long: short,
command: "",
params: serde_json::Value::Null,
enabled,
});
ui.ctx().accesskit_node_builder(response.id, |node| node.set_has_popup(egui::accesskit::HasPopup::Menu));
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));
// A menu opened from the keyboard has no pointer to open at: it hangs under the row while it stays open
let from_keyboard = response.id.with("ts_menu_from_keyboard");
let menu_key =
|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(menu_key) {
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::<bool>(from_keyboard));
}
if ui.data(|data| data.get_temp::<bool>(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
}
/// A UV tile under its set: a branch from the set's fold caret, its UDIM and its own size dropdown
fn tile_row(ui: &mut Ui, set: usize, udim: u32, resolution: u32, set_width: u32, selected: bool, tokens: &Tokens) -> Option<TileAction> {
let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), TILE_ROW_HEIGHT), Sense::click());
let label = trf("UV tile {udim}", &[("udim", &udim)]);
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, ui.is_enabled(), &label));
ui.ctx().accesskit_node_builder(response.id, |node| node.set_selected(selected));
let face = rect.with_min_x(rect.left() + TILE_INDENT - ROW_INSET);
let painter = ui.painter();
if selected {
painter.rect(face, CornerRadius::same(ROW_ROUNDING), tokens.row_selected, Stroke::new(1.0, tokens.accent), StrokeKind::Inside);
} else if response.hovered() {
painter.rect_filled(face, CornerRadius::same(ROW_ROUNDING), tokens.row_hover);
}
if response.has_focus() {
painter.rect_stroke(face.shrink(FOCUS_INSET), CornerRadius::same(ROW_ROUNDING), Stroke::new(1.0, tokens.text_strong), StrokeKind::Inside);
}
let branch_x = rect.left() + ROW_INSET + GLYPH_SIZE + NAME_GAP * 0.5 + FOLD_WIDTH * 0.5;
painter.vline(branch_x, rect.top() - ROW_GAP..=rect.center().y, Stroke::new(1.0, tokens.separator));
painter.hline(branch_x..=branch_x + TILE_BRANCH, rect.center().y, Stroke::new(1.0, tokens.separator));
let color = if selected { tokens.text_strong } else { tokens.text };
let font = if selected { semibold(NAME_SIZE) } else { FontId::proportional(NAME_SIZE) };
painter.text(pos2(rect.left() + TILE_INDENT, rect.center().y), Align2::LEFT_CENTER, &label, font, color);
// An overridden tile shows its size in full text colour, one that follows the set dims it
let mut picked = None;
let text = resolution.to_string();
let name = trf("Size of UV tile {udim}", &[("udim", &udim)]);
let size_right = rect.right() - ROW_INSET - shader_column_width(ui, rect.width());
let dim = resolution == set_width;
row_dropdown(ui, ("ts_tile_size", set, udim), pos2(size_right, rect.center().y), (&text, &name), dim, tokens, |ui| {
picked = size_list(ui, resolution);
});
if let Some(size) = picked {
return Some(TileAction::Resize(size));
}
(response.clicked() || response.secondary_clicked()).then_some(TileAction::Select)
}
/// The shader dropdown's width on set rows, so tile sizes line up under set sizes
fn shader_column_width(ui: &Ui, row_width: f32) -> f32 {
if row_width < SHADER_MIN_ROW_WIDTH {
return 0.0;
}
dropdown_width(ui, tr(SHADER_NAME)) + DROPDOWN_GAP
}
fn dropdown_width(ui: &Ui, text: &str) -> f32 {
let text_width = ui.fonts_mut(|fonts| fonts.layout_no_wrap(text.to_owned(), FontId::proportional(NAME_SIZE), egui::Color32::WHITE).size().x);
DROPDOWN_TEXT_X + text_width + DROPDOWN_CARET_GAP + CARET_SIZE + DROPDOWN_RIGHT
}
/// A dropdown drawn as its text (`labels`: shown text, then what it sets) and a small caret, its right end middle at `anchor`: a button face only while hovered or open
fn row_dropdown(
ui: &mut Ui,
id: impl egui::AsIdSalt,
anchor: egui::Pos2,
labels: (&str, &str),
dim: bool,
tokens: &Tokens,
list: impl FnOnce(&mut Ui),
) -> Rect {
let (text, name) = labels;
let width = dropdown_width(ui, text);
let rect = Rect::from_min_size(pos2(anchor.x - width, anchor.y - DROPDOWN_HEIGHT * 0.5), vec2(width, DROPDOWN_HEIGHT));
let response = ui.interact(rect, ui.scope_id().with(id), Sense::click()).on_hover_text(name);
let accessible = format!("{text}, {name}");
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, ui.is_enabled(), &accessible));
let popup = Popup::menu(&response).frame(menu_frame(tokens)).width(SIZE_LIST_WIDTH.max(width)).gap(MENU_GAP).align(egui::RectAlign::BOTTOM_END);
let open = popup.is_open();
let painter = ui.painter();
if open || response.hovered() {
painter.rect(rect, CornerRadius::same(ROW_ROUNDING), tokens.button, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside);
}
let color = if dim && !response.hovered() && !open { tokens.text_dim } else { tokens.text };
painter.text(pos2(rect.left() + DROPDOWN_TEXT_X, rect.center().y), Align2::LEFT_CENTER, text, FontId::proportional(NAME_SIZE), color);
painter.text(
pos2(rect.right() - DROPDOWN_RIGHT - CARET_SIZE * 0.5, rect.center().y),
Align2::CENTER_CENTER,
ic::CARET_DOWN,
FontId::proportional(CARET_SIZE),
tokens.text_dim,
);
popup.show(|ui| {
ui.set_min_width(SIZE_LIST_WIDTH.max(width));
ui.add_space(MENU_PADDING);
list(ui);
ui.add_space(MENU_PADDING);
});
rect
}
/// The sizes a set or tile can take, the current one ticked; the one picked
fn size_list(ui: &mut Ui, current: u32) -> Option<u32> {
let mut picked = None;
let mut size = MIN_RESOLUTION;
while size <= MAX_RESOLUTION {
if option_row(ui, &size.to_string(), size == current).clicked() && size != current {
picked = Some(size);
}
size *= 2;
}
picked
}
/// The field of the row's text being edited: Enter (or clicking away) gives the text, Esc drops it
fn edit_field(ui: &mut Ui, state: &mut ListState, rect: Rect, size: f32) -> Option<String> {
let (_, _, text, needs_focus) = state.edit.as_mut()?;
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect));
// The text sits where the drawn name or description sat, centred in the field
let font = FontId::proportional(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(text).font(font).margin(margin));
if std::mem::take(needs_focus) {
response.request_focus();
}
if !response.lost_focus() {
return None;
}
let edit = state.edit.take()?;
(!ui.input(|input| input.key_pressed(egui::Key::Escape))).then_some(edit.2)
}
/// A glyph button of the list: dim glyph, bright and framed when hovered or lit
fn glyph_button(ui: &mut Ui, id: impl egui::AsIdSalt, rect: Rect, glyph: &str, label: &str, lit: bool, tokens: &Tokens) -> Response {
let response = ui.interact(rect, ui.scope_id().with(id), Sense::click()).on_hover_text(label);
response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), lit, label));
if lit || response.hovered() {
ui.painter().rect(rect, CornerRadius::same(ROW_ROUNDING), tokens.button, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside);
}
let color = if lit || response.hovered() { tokens.text_strong } else { tokens.text_dim };
ui.painter().text(rect.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(GLYPH_FONT), color);
response
}
#[cfg(test)]
mod tests {
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable as _;
use super::*;
fn harness(mesh: &str) -> Harness<'static, TextureCraftApp> {
let mesh_ref = format!("builtin:{mesh}");
let geometry = texturecraft_engine::geom::primitives::builtin(mesh).unwrap();
let session = texturecraft_engine::Session::new_project("Texture set list", geometry, &mesh_ref, None, 128).unwrap();
let mut harness = Harness::builder()
// Tall enough that every row clears the panel under the list
.with_size(vec2(1600.0, 2400.0))
.with_context_setup(crate::framework::install_headless)
.build_eframe(|context| TextureCraftApp::new(context, session));
harness.run_steps(4);
harness
}
/// Presses and lets go on `label`'s node through the real pointer path, as a person's click lands on a control drawn over its row
fn click(harness: &mut Harness<'static, TextureCraftApp>, role: egui::Role, label: &str, button: egui::PointerButton) {
let rect = harness.get_by_role_and_label(role, label).rect();
// A row's middle is under its size dropdown in a narrow panel: aim at its name
let at = if role == egui::Role::ListItem { egui::pos2(rect.left() + rect.width() * 0.25, rect.center().y) } else { rect.center() };
let modifiers = egui::Modifiers::NONE;
harness.event(egui::Event::PointerMoved(at));
harness.event(egui::Event::PointerButton { pos: at, button, pressed: true, modifiers });
harness.run_steps(1);
harness.event(egui::Event::PointerButton { pos: at, button, pressed: false, modifiers });
harness.run_steps(2);
}
#[test]
fn the_row_size_dropdown_resizes_its_set() {
let mut harness = harness("material_ball");
let name = harness.state().session.doc.project.texture_sets[1].name.clone();
click(&mut harness, egui::Role::ComboBox, &format!("128, Size of {name}"), egui::PointerButton::Primary);
click(&mut harness, egui::Role::ListBoxOption, "512", egui::PointerButton::Primary);
// The resize runs on a worker, as the settings' size does
for _ in 0..200 {
harness.run_steps(1);
if harness.state().resize.is_none() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
harness.run_steps(2);
let sets = &harness.state().session.doc.project.texture_sets;
assert!(sets[1].resolution > 128 && sets[1].height() == sets[1].resolution, "the set grew and stayed square");
assert_eq!(sets[0].resolution, 128, "the other set kept its size");
}
#[test]
fn the_right_click_menu_renames_in_place_and_resets_to_the_material_name() {
let mut harness = harness("material_ball");
let original = harness.state().session.doc.project.texture_sets[1].name.clone();
click(&mut harness, egui::Role::ListItem, &original, egui::PointerButton::Secondary);
click(&mut harness, egui::Role::Button, "Edit Name", egui::PointerButton::Primary);
harness.run_steps(3);
// The field took focus, so typed text goes to it
harness.event(egui::Event::Text("x".into()));
harness.run_steps(1);
harness.key_press(egui::Key::Enter);
harness.run_steps(3);
let renamed = harness.state().session.doc.project.texture_sets[1].name.clone();
assert!(renamed != original && renamed.contains('x'), "{renamed}");
click(&mut harness, egui::Role::ListItem, &renamed, egui::PointerButton::Secondary);
click(&mut harness, egui::Role::Button, "Reset Name to Original", egui::PointerButton::Primary);
harness.run_steps(3);
assert_eq!(harness.state().session.doc.project.texture_sets[1].name, original);
}
#[test]
fn a_focused_row_renames_with_f2_and_opens_its_menu_from_the_keyboard() {
let mut harness = harness("material_ball");
let original = harness.state().session.doc.project.texture_sets[1].name.clone();
harness.get_by_role_and_label(egui::Role::ListItem, &original).focus();
harness.run_steps(2);
harness.key_press(egui::Key::F2);
harness.run_steps(3);
harness.event(egui::Event::Text("y".into()));
harness.run_steps(1);
harness.key_press(egui::Key::Enter);
harness.run_steps(3);
let renamed = harness.state().session.doc.project.texture_sets[1].name.clone();
assert!(renamed != original && renamed.contains('y'), "{renamed}");
harness.get_by_role_and_label(egui::Role::ListItem, &renamed).focus();
harness.run_steps(2);
assert!(harness.query_by_role_and_label(egui::Role::Button, "Edit Description").is_none());
harness.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::F10);
harness.run_steps(3);
assert!(harness.query_by_role_and_label(egui::Role::Button, "Edit Description").is_some(), "Shift+F10 opens the row's menu");
}
#[test]
fn a_uv_tile_row_sizes_its_own_tile() {
let mut harness = harness("udim_plane");
let tiles = harness.state().session.doc.project.texture_sets[0].uv_tiles.clone();
assert!(harness.query_by_role_and_label(egui::Role::ListItem, &format!("UV tile {}", tiles[1])).is_some());
click(&mut harness, egui::Role::ComboBox, &format!("128, Size of UV tile {}", tiles[1]), egui::PointerButton::Primary);
click(&mut harness, egui::Role::ListBoxOption, "256", egui::PointerButton::Primary);
harness.run_steps(3);
let set = &harness.state().session.doc.project.texture_sets[0];
assert!(set.tile_resolution(tiles[1]) > set.tile_resolution(tiles[0]), "only the picked tile grew");
}
}
@@ -0,0 +1,19 @@
/// Which rows show their description line under the name (the list menu's choice)
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub(crate) enum DescriptionMode {
#[default]
HideEmpty,
ShowAll,
HideAll,
}
impl DescriptionMode {
/// Whether a row with `description` shows the line
pub(crate) fn shows(self, description: &str) -> bool {
match self {
Self::HideEmpty => !description.trim().is_empty(),
Self::ShowAll => true,
Self::HideAll => false,
}
}
}
@@ -0,0 +1,29 @@
use std::collections::BTreeSet;
use super::{DescriptionMode, RowEdit};
/// The list's UI state: the row being edited, which descriptions show, folded UV tile sets and the selected tile
#[derive(Clone, Default)]
pub(crate) struct ListState {
/// Set, what it edits, the text so far, and whether the field still needs focus
pub(crate) edit: Option<(usize, RowEdit, String, bool)>,
pub(crate) descriptions: DescriptionMode,
/// UV tile sets whose tile rows are folded away
pub(crate) folded: BTreeSet<usize>,
/// Set and UDIM of the selected UV tile row
pub(crate) tile: Option<(usize, u32)>,
}
impl ListState {
fn id() -> egui::Id {
egui::Id::unique("texture_set_list_state")
}
pub(crate) fn load(ctx: &egui::Context) -> Self {
ctx.data(|data| data.get_temp::<Self>(Self::id())).unwrap_or_default()
}
pub(crate) fn store(self, ctx: &egui::Context) {
ctx.data_mut(|data| data.insert_temp(Self::id(), self));
}
}
@@ -0,0 +1,12 @@
use super::RowEdit;
/// What a set row asks for once it has drawn
#[derive(Clone, Copy)]
pub(super) enum RowAction {
Select,
ToggleVisible,
Resize(u32),
Edit(RowEdit),
ResetName,
ToggleFold,
}
@@ -0,0 +1,6 @@
/// The text a row is editing in place
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum RowEdit {
Name,
Description,
}
@@ -0,0 +1,12 @@
/// What one texture set row shows, read before drawing so commands can run while the rows draw
pub(crate) struct SetRow {
pub(crate) name: String,
pub(crate) description: String,
/// The mesh material's name, when the set has one to go back to
pub(crate) original_name: Option<String>,
pub(crate) width: u32,
pub(crate) height: u32,
pub(crate) visible: bool,
/// UDIM and resolution of each UV tile, in UDIM order
pub(crate) tiles: Vec<(u32, u32)>,
}
@@ -0,0 +1,5 @@
/// What a UV tile row asks for
pub(super) enum TileAction {
Select,
Resize(u32),
}
+2 -1
View File
@@ -570,7 +570,8 @@ fn uv_tiles_are_shown_read_only() {
hover_uv_tile_box(&mut h);
assert!(h.query_by_label_contains("No UV tiles").is_none());
assert!(h.query_by_label_contains("1001").is_some(), "the tile list of a UDIM project");
// The hint's own text, not the Texture Sets list's tile rows
assert!(h.query_all_by_label_contains("1001").any(|node| node.accesskit_node().role() == Role::Label), "the tile list of a UDIM project");
}
/// Hover the disabled Use UV Tile workflow box, whose hint lists the project's UV tiles.