diff --git a/crates/engine/src/filter_lib.rs b/crates/engine/src/filter_lib.rs index f3168c9d..0f0fd952 100644 --- a/crates/engine/src/filter_lib.rs +++ b/crates/engine/src/filter_lib.rs @@ -19,6 +19,13 @@ pub struct FilterDef { pub mask: bool, } +impl FilterDef { + /// Whether it builds a filter effect (levels and material finishes are effect types of their own) + pub fn is_filter_effect(&self) -> bool { + matches!(build(self.id, &Value::Null), Ok(EffectKind::Filter(_))) + } +} + const fn def(id: &'static str, label: &'static str, group: &'static str, mask: bool) -> FilterDef { FilterDef { id, label, group, mask } } diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 2656bd15..bd545fbc 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -94,7 +94,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, name?, level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity), level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", has_layer, set ), @@ -413,55 +413,76 @@ fn histogram(s: &mut Session, p: &Value) -> Result { Ok(if content { json!({"target": "content", "channel": channel.id(), "bins": counts}) } else { json!({"target": "mask", "bins": counts}) }) } +/// Edits effect `effect`: visibility, blending, name, its kind's parameters, or a filter's type fn set(s: &mut Session, p: &Value) -> Result { - let eid = effect_id(s, p, "effect.set")?; - let blend = blend_param("effect.set", p, "blend")?; - // A fill reading an anchor: `anchor` picks the anchor point, `anchorChannel` alone - // re-targets the current one. - let anchor = match s.doc.project.effect(eid) { + const CMD: &str = "effect.set"; + let effect = effect_id(s, p, CMD)?; + let blend = blend_param(CMD, p, "blend")?; + + // `anchor` picks a fill's anchor point, `anchorChannel` alone re-targets the current one + let anchor = match s.doc.project.effect(effect) { Some((owner, Effect { kind: EffectKind::Fill { source, .. }, .. })) => { let (current, channel) = match source { Source::Anchor { anchor, channel } => (Some(*anchor), *channel), _ => (None, Channel::Height), }; - let channel_param = channel_param("effect.set", p, "anchorChannel")?; + let channel_param = channel_param(CMD, p, "anchorChannel")?; match u64p(p, "anchor").map(LayerId).or(current.filter(|_| channel_param.is_some())) { - Some(a) => Some(anchor_source(s, "effect.set", owner, a, channel_param.unwrap_or(channel))?), + Some(anchor) => Some(anchor_source(s, CMD, owner, anchor, channel_param.unwrap_or(channel))?), None => None, } } _ => None, }; + + let swapped = match strp(p, "filter") { + Some(filter) => Some(swapped_filter(s, effect, filter, p)?), + None => None, + }; + let swaps_filter = swapped.is_some(); + s.edit("Edit effect", |s| { - let e = s.doc.project.effect_mut(eid).ok_or_else(|| bad("effect.set", format!("no effect {}", eid.0)))?; - if let Some(v) = boolp(p, "visible") { - e.visible = v; + let edited = s.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; + if let Some((kind, label)) = swapped { + if let EffectKind::Filter(old) = &edited.kind + && edited.name == old.label() + { + edited.name = label.to_string(); + } + edited.kind = kind; } - if let Some(b) = blend { - e.blend = b; + + if let Some(visible) = boolp(p, "visible") { + edited.visible = visible; } - if let Some(o) = f32p(p, "opacity") { - e.opacity = o.clamp(0.0, 1.0); + if let Some(blend) = blend { + edited.blend = blend; } - if let Some(n) = name_param(p) { - e.name = n.to_string(); + if let Some(opacity) = f32p(p, "opacity") { + edited.opacity = opacity.clamp(0.0, 1.0); } - match &mut e.kind { - EffectKind::Generator(g) => generator_from(p, g), - EffectKind::Levels(l) => levels_from(p, l), - EffectKind::Filter(f) => crate::filter_lib::apply(p, f, "effect.set")?, + if let Some(name) = name_param(p) { + edited.name = name.to_string(); + } + + match &mut edited.kind { + EffectKind::Generator(generator) => generator_from(p, generator), + EffectKind::Levels(levels) => levels_from(p, levels), + // The swapped filter was built with the parameters already + EffectKind::Filter(_) if swaps_filter => {} + EffectKind::Filter(filter) => crate::filter_lib::apply(p, filter, CMD)?, EffectKind::Fill { source, .. } => { - if let Some(a) = anchor { - *source = a; - } else if let Some(x) = f32p(p, "value") + if let Some(anchor) = anchor { + *source = anchor; + } else if let Some(value) = f32p(p, "value") && matches!(source, Source::Uniform(_) | Source::Anchor { .. }) { - *source = Source::Uniform([x.clamp(0.0, 1.0); 3]); + *source = Source::Uniform([value.clamp(0.0, 1.0); 3]); } } EffectKind::ColorSelection { tolerance, .. } | EffectKind::Compare { tolerance, .. } => { - if let Some(x) = f32p(p, "tolerance") { - *tolerance = x.clamp(0.0, 1.0); + if let Some(value) = f32p(p, "tolerance") { + *tolerance = value.clamp(0.0, 1.0); } } _ => {} @@ -471,6 +492,27 @@ fn set(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// Filter `id` built with `p` and its label, to replace filter effect `effect` +fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<(EffectKind, &'static str)> { + const CMD: &str = "effect.set"; + let (owner, current) = s.doc.project.effect(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; + if !matches!(current.kind, EffectKind::Filter(_)) { + return Err(bad(CMD, format!("`filter` changes filter effects only, not {}", current.kind.name().to_ascii_lowercase()))); + } + + let def = crate::filter_lib::find(id).ok_or_else(|| bad(CMD, format!("unknown filter `{id}` (see filter.list)")))?; + if !def.is_filter_effect() { + return Err(bad(CMD, format!("{} is its own effect type: add it with effect.add.filter", def.label))); + } + + let mask = s.doc.project.layer(owner)?.mask.as_ref(); + let on_mask = mask.is_some_and(|mask| mask.effects.iter().any(|masked| masked.id == effect)); + if on_mask && !def.mask { + return Err(bad(CMD, format!("{} goes on layer content, not on masks", def.label))); + } + Ok((crate::filter_lib::build(def.id, p)?, def.label)) +} + /// The stack (a mask's or a layer's content effects) holding effect `eid`, and its position there. fn stack_of(project: &mut Project, eid: LayerId) -> Option<(&mut Vec, usize)> { project.layers.values_mut().find_map(|l| { diff --git a/crates/engine/tests/filter_swap.rs b/crates/engine/tests/filter_swap.rs new file mode 100644 index 00000000..87341c60 --- /dev/null +++ b/crates/engine/tests/filter_swap.rs @@ -0,0 +1,94 @@ +//! Swapping a filter effect's type in place through `effect.set {filter}` + +use serde_json::{Value, json}; +use texturecraft_engine::core::{BlendMode, Effect, EffectKind, Filter, LayerId}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, StackTarget, execute}; + +/// A sphere project with its default layer selected +fn session() -> Session { + Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 256).unwrap() +} + +/// Runs effect-adding `command` and returns the new effect, which it selects +fn add(s: &mut Session, command: &str, params: Value) -> LayerId { + execute(s, command, ¶ms).unwrap(); + let StackTarget::Effect(added) = s.target else { panic!("adding an effect selects it: {:?}", s.target) }; + + added +} + +/// A copy of effect `id` +fn effect(s: &Session, id: LayerId) -> Effect { + s.doc.project.effect(id).unwrap().1.clone() +} + +/// Ids of the selected layer's content effects, bottom first +fn content_order(s: &Session) -> Vec { + let layer = s.selected_layer().unwrap(); + s.doc.project.layer(layer).unwrap().content_effects.iter().map(|effect| effect.id).collect() +} + +#[test] +fn swapping_a_filter_keeps_its_place_blend_opacity_and_visibility() { + let mut s = session(); + let below = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + let swapped = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + let above = add(&mut s, "effect.add.filter", json!({"filter": "grayscale", "target": "content"})); + execute(&mut s, "effect.set", &json!({"effect": swapped.0, "blend": "Multiply", "opacity": 0.4, "visible": false})).unwrap(); + + execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur", "radius": 5.0})).unwrap(); + + let blur = effect(&s, swapped); + assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius }) if radius == 5.0), "{:?}", blur.kind); + assert_eq!(blur.name, "Blur", "a default name follows the new filter"); + assert_eq!((blur.blend, blur.opacity, blur.visible), (BlendMode::Multiply, 0.4, false)); + assert_eq!(content_order(&s), vec![below, swapped, above]); +} + +#[test] +fn swapping_a_filter_keeps_a_name_the_user_chose() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content", "name": "Flip"})); + + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "threshold"})).unwrap(); + + assert_eq!(effect(&s, id).name, "Flip"); +} + +#[test] +fn one_undo_restores_the_old_filter() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "threshold", "target": "content", "level": 0.3})); + + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "sharpen"})).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + + let restored = effect(&s, id); + assert!(matches!(restored.kind, EffectKind::Filter(Filter::Threshold { level }) if level == 0.3), "{:?}", restored.kind); + assert_eq!(restored.name, "Threshold"); +} + +#[test] +fn a_mask_refuses_a_content_only_filter() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + + let err = execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "grayscale"})).unwrap_err(); + + assert!(err.to_string().contains("not on masks"), "{err}"); + assert!(matches!(effect(&s, id).kind, EffectKind::Filter(Filter::Invert))); + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur"})).expect("a mask takes a filter that works on masks"); +} + +#[test] +fn only_filter_effects_swap_and_only_to_filters() { + let mut s = session(); + let levels = add(&mut s, "effect.add.levels", json!({"target": "content"})); + let filter = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + + assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "blur"})).is_err(), "levels is not a filter effect"); + assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "matFinishGrind"})).is_err(), "a material finish is a fill"); + assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "nope"})).is_err()); + assert!(matches!(effect(&s, filter).kind, EffectKind::Filter(Filter::Invert))); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 976a3035..13604e91 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -8,7 +8,7 @@ use texturecraft_engine::core::{ BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, Projection, Source, }; -use texturecraft_engine::filter_lib::{FILTERS, scalar_params}; +use texturecraft_engine::filter_lib::scalar_params; use texturecraft_engine::paint::{BrushAlpha, alphas}; use texturecraft_engine::{CloneFrom, StackTarget, Tool}; @@ -19,6 +19,13 @@ use crate::state::PropsTab; use crate::theme::{Tokens, caption}; use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, histogram, icon_button, section, slider, slider_edit}; +/// The filter Add filter adds: at its defaults it changes nothing until the slot swaps it +const NEW_FILTER: &str = "hsl"; +const FILTER_SWATCH_WIDTH: f32 = 36.0; +const FILTER_HINT_SIZE: f32 = 10.5; +/// The most colors `effect.set {colors}` takes for a gradient map +const MAX_GRADIENT_STOPS: usize = 16; + const TAG_COLORS: [Color32; 8] = [ Color32::from_rgb(0xc0, 0x40, 0x40), Color32::from_rgb(0xd0, 0x80, 0x30), @@ -208,48 +215,34 @@ pub(crate) fn targets_content(app: &TextureCraftApp) -> bool { } } -/// "Add effect" items for `layer` (toolbar and context menu). Effects that fit both stacks go -/// to the content when it is the selected target; generators and compare always go to the -/// mask, anchor points to the content. +/// "Add effect" items for `layer`: content when it is the selected target, else the mask fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { let content = !layer.is_group() && app.session.selected_layer() == Some(layer.id) && targets_content(app); - let t = if content { "content" } else { "mask" }; + let target = if content { "content" } else { "mask" }; ui.label(caption(if content { tr("Add to the layer content") } else { tr("Add to the mask") })); + + // Generators and compare masks always go to the mask, anchor points to the content let items = [ (tr("Add generator"), "effect.add.generator", json!({})), - (tr("Add paint"), "effect.add.paint", json!({"target": t})), - (tr("Add fill"), "effect.add.fill", json!({"target": t})), - (tr("Add levels"), "effect.add.levels", json!({"target": t})), + (tr("Add paint"), "effect.add.paint", json!({"target": target})), + (tr("Add fill"), "effect.add.fill", json!({"target": target})), + (tr("Add levels"), "effect.add.levels", json!({"target": target})), (tr("Add compare mask"), "effect.add.compare", json!({})), + (tr("Add filter"), "effect.add.filter", json!({"target": target, "filter": NEW_FILTER})), (tr("Add anchor point"), "effect.add.anchor", json!({})), ]; - let run = |app: &mut TextureCraftApp, id: &str, p: &Value| { + for (label, command, params) in items { + let enabled = command != "effect.add.anchor" || !layer.is_group(); + if !ui.add_enabled(enabled, egui::Button::new(label)).clicked() { + continue; + } + if app.session.selected_layer() != Some(layer.id) { app.run("layer.select", json!({"layer": layer.id.0})); } - app.run(id, with(p, json!({"layer": layer.id.0}))); - }; - for (label, id, p) in items { - let enabled = id != "effect.add.anchor" || !layer.is_group(); - if ui.add_enabled(enabled, egui::Button::new(label)).clicked() { - run(app, id, &p); - ui.close(); - } + app.run(command, with(¶ms, json!({"layer": layer.id.0}))); + ui.close(); } - // The filter library (material finishes only fill content). - ui.menu_button(tr("Add filter"), |ui| { - let mut group = ""; - for f in FILTERS.iter().filter(|f| content || f.mask) { - if f.group != group { - ui.label(caption(tr(f.group))); - group = f.group; - } - if ui.button(tr(f.label)).clicked() { - run(app, "effect.add.filter", &json!({"target": t, "filter": f.id})); - ui.close(); - } - } - }); } fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize) { @@ -2058,82 +2051,85 @@ fn levels_histogram(app: &TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: Laye } } -/// The parameters of filter effect `id`. -fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter) { +/// The filter slot and the parameters of filter effect `id` +fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, filter: &Filter) { let tk = Tokens::get(ui.ctx()); - let set = |app: &mut TextureCraftApp, key: &str, v: Value, merge: bool| { - let mut p = json!({ "effect": id, "merge": merge }); - p[key] = v; - app.run("effect.set", p); + let set = |app: &mut TextureCraftApp, key: &str, value: Value, merge: bool| { + let mut params = json!({ "effect": id, "merge": merge }); + params[key] = value; + app.run("effect.set", params); }; - ui.label(caption(tr(f.label()))); - if let Filter::Hsl { hue, .. } = f { - let mut h = hue * 360.0; - if let Some(merge) = slider_edit(ui, tr("Hue shift (degrees)"), &mut h, -180.0..=180.0, 0) { - set(app, "hue", json!(h / 360.0), merge); + crate::filter_slot::show(app, ui, id, filter); + + if let Filter::Hsl { hue, .. } = filter { + let mut degrees = hue * 360.0; + if let Some(merge) = slider_edit(ui, tr("Hue shift (degrees)"), &mut degrees, -180.0..=180.0, 0) { + set(app, "hue", json!(degrees / 360.0), merge); } } - for (key, label, mut v, lo, hi) in scalar_params(f) { + + for (key, label, mut value, min, max) in scalar_params(filter) { let decimals = if matches!(key, "seed" | "levels") { 0 - } else if hi - lo > 10.0 { + } else if max - min > 10.0 { 1 } else { 2 }; - if let Some(merge) = slider_edit(ui, tr(label), &mut v, lo..=hi, decimals) { - set(app, key, json!(v), merge); + if let Some(merge) = slider_edit(ui, tr(label), &mut value, min..=max, decimals) { + set(app, key, json!(value), merge); } } - match f { + + match filter { Filter::ColorBalance { shadows, midtones, highlights } => { for (key, label, rgb) in [("shadows", tr("Shadows"), shadows), ("midtones", tr("Midtones"), midtones), ("highlights", tr("Highlights"), highlights)] { ui.label(RichText::new(label).strong()); - let mut v = *rgb; + let mut balance = *rgb; let mut edit = None; - for (x, name) in v.iter_mut().zip([tr("Cyan / red"), tr("Magenta / green"), tr("Yellow / blue")]) { - edit = edit.or(slider_edit(ui, name, x, -1.0..=1.0, 2)); + for (component, name) in balance.iter_mut().zip([tr("Cyan / red"), tr("Magenta / green"), tr("Yellow / blue")]) { + edit = edit.or(slider_edit(ui, name, component, -1.0..=1.0, 2)); } if let Some(merge) = edit { - set(app, key, json!(v), merge); + set(app, key, json!(balance), merge); } } } Filter::ReplaceColor { from, to, .. } => { for (key, label, rgb) in [("from", tr("Color to replace"), from), ("to", tr("Replacement color"), to)] { - let mut v = *rgb; + let mut color = *rgb; ui.horizontal(|ui| { - if color_swatch(ui, &format!("replace_{key}_{id}"), &mut v, 36.0) { - set(app, key, json!(v), false); + if color_swatch(ui, &format!("replace_{key}_{id}"), &mut color, FILTER_SWATCH_WIDTH) { + set(app, key, json!(color), false); } ui.label(label); }); } - ui.label(RichText::new(tr("Colors near the first shift towards the second, keeping their shading.")).size(10.5).color(tk.text_dim)); + ui.label(RichText::new(tr("Colors near the first shift towards the second, keeping their shading.")).size(FILTER_HINT_SIZE).color(tk.text_dim)); } Filter::GradientMap { colors } => { - let mut c = colors.clone(); + let mut stops = colors.clone(); let mut changed = false; ui.horizontal_wrapped(|ui| { - for (i, col) in c.iter_mut().enumerate() { - changed |= color_swatch(ui, &format!("gradient_{id}_{i}"), col, 36.0); + for (i, stop) in stops.iter_mut().enumerate() { + changed |= color_swatch(ui, &format!("gradient_{id}_{i}"), stop, FILTER_SWATCH_WIDTH); } }); ui.horizontal(|ui| { - if ui.add_enabled(c.len() < 16, egui::Button::new(format!("{} {}", ic::PLUS, tr("Add color")))).clicked() { - c.push(c.last().copied().unwrap_or([1.0; 3])); + if ui.add_enabled(stops.len() < MAX_GRADIENT_STOPS, egui::Button::new(format!("{} {}", ic::PLUS, tr("Add color")))).clicked() { + stops.push(stops.last().copied().unwrap_or([1.0; 3])); changed = true; } - if ui.add_enabled(c.len() > 1, egui::Button::new(format!("{} {}", ic::MINUS, tr("Remove last")))).clicked() { - c.pop(); + if ui.add_enabled(stops.len() > 1, egui::Button::new(format!("{} {}", ic::MINUS, tr("Remove last")))).clicked() { + stops.pop(); changed = true; } }); if changed { - set(app, "colors", json!(c), false); + set(app, "colors", json!(stops), false); } - ui.label(RichText::new(tr("Dark to light: the content's luminance picks a color along these stops.")).size(10.5).color(tk.text_dim)); + ui.label(RichText::new(tr("Dark to light: the content's luminance picks a color along these stops.")).size(FILTER_HINT_SIZE).color(tk.text_dim)); } Filter::Warp { .. } | Filter::DirectionalBlur { .. } @@ -2144,7 +2140,7 @@ fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter | Filter::Bevel { .. } | Filter::Mosaic { .. } | Filter::Glow { .. } => { - ui.label(RichText::new(tr("Works in texture space, like the blur: it does not cross UV seams.")).size(10.5).color(tk.text_dim)); + ui.label(RichText::new(tr("Works in texture space, like the blur: it does not cross UV seams.")).size(FILTER_HINT_SIZE).color(tk.text_dim)); } _ => {} } diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs new file mode 100644 index 00000000..7a143612 --- /dev/null +++ b/crates/ui-egui/src/filter_slot.rs @@ -0,0 +1,83 @@ +//! The filter slot atop a filter's properties: thumbnail and name, opening a picker that swaps it + +use egui::{Align2, FontId, Rect, Sense, Stroke, Ui, pos2, vec2}; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::core::{Filter, LayerId}; +use texturecraft_engine::filter_lib::{FILTERS, find}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::resource_picker; +use crate::resource_picker_item::ResourcePickerItem; +use crate::shelf_preview::ShelfPreview; +use crate::theme::Tokens; +use crate::thumbs::Thumbs; + +const SLOT_HEIGHT: f32 = 52.0; +const SLOT_ROUNDING: f32 = 3.0; +const THUMBNAIL_SIZE: f32 = 40.0; +const THUMBNAIL_INSET: f32 = 6.0; +const CAPTION_FONT_SIZE: f32 = 11.0; +const NAME_FONT_SIZE: f32 = 13.0; +/// Gap between the caption's and the name's centers +const LINE_GAP: f32 = 15.0; +const CARET_INSET: f32 = 14.0; +const CARET_FONT_SIZE: f32 = 14.0; + +/// The slot of filter effect `effect`: a pick runs `effect.set {filter}`, masks offer only mask filters +pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: &Filter) { + let ctx = ui.ctx().clone(); + let on_mask = is_on_mask(app, effect); + let current = find(filter.label()).map(|def| def.id); + let thumbnail = current.and_then(|id| app.thumbs.filter(&ctx, id)); + let name = tr(filter.label()); + + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), SLOT_HEIGHT), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, name)); + paint(ui, rect, response.hovered(), thumbnail.as_ref(), name); + + let popup = ui.make_persistent_id(("filter_picker", effect)); + if response.clicked() { + resource_picker::toggle(&ctx, popup); + } + + let items = |thumbs: &mut Thumbs| { + FILTERS + .iter() + .filter(|def| def.is_filter_effect() && (def.mask || !on_mask)) + .map(|def| ResourcePickerItem { id: def.id, label: tr(def.label), group: tr(def.group), thumbnail: thumbs.filter(&ctx, def.id) }) + .collect() + }; + let picked = resource_picker::show(&response, popup, &mut app.thumbs, current, items, ShelfPreview::Filter); + if let Some(id) = picked.filter(|id| Some(*id) != current) { + app.run("effect.set", json!({"effect": effect, "filter": id})); + } +} + +/// Whether filter effect `effect` sits in a mask rather than the layer content +fn is_on_mask(app: &TextureCraftApp, effect: u64) -> bool { + let project = &app.session.doc.project; + let owner = project.effect(LayerId(effect)).and_then(|(owner, _)| project.layers.get(&owner)); + owner.and_then(|layer| layer.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|masked| masked.id.0 == effect)) +} + +/// The slot's box: thumbnail, "Filter" over the name, caret +fn paint(ui: &Ui, rect: Rect, hovered: bool, thumbnail: Option<&egui::TextureHandle>, name: &str) { + let tk = Tokens::get(ui.ctx()); + let painter = ui.painter(); + let (fill, border) = if hovered { (tk.row_hover, tk.button_border) } else { (tk.field, tk.field_border) }; + painter.rect(rect, SLOT_ROUNDING, fill, Stroke::new(1.0, border), egui::StrokeKind::Inside); + + if let Some(texture) = thumbnail { + let image = Rect::from_min_size(pos2(rect.left() + THUMBNAIL_INSET, rect.center().y - THUMBNAIL_SIZE * 0.5), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); + painter.image(texture.id(), image, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + } + + let center = rect.center(); + painter.text(center - vec2(0.0, LINE_GAP * 0.5), Align2::CENTER_CENTER, tr("Filter"), FontId::proportional(CAPTION_FONT_SIZE), tk.text_dim); + painter.text(center + vec2(0.0, LINE_GAP * 0.5), Align2::CENTER_CENTER, name, FontId::proportional(NAME_FONT_SIZE), tk.text_strong); + + let caret_color = if hovered { tk.text } else { tk.text_dim }; + painter.text(pos2(rect.right() - CARET_INSET, center.y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(CARET_FONT_SIZE), caret_color); +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..c61f4ce3 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -304,6 +304,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "تعبئة"), ("Fill the closed path (lasso)", "تعبئة المسار المغلق (حبل التحديد)"), ("Fill the path (close it first)", "تعبئة المسار (أغلقه أولاً)"), + ("Filter", "مرشح"), ("Filter the remaining noise while keeping edges and texture detail", "تصفية الضوضاء المتبقية مع الحفاظ على الحواف وتفاصيل الخامة"), ("Filters", "مرشحات"), ("Fine noise", "ضوضاء دقيقة"), @@ -677,6 +678,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "خدوش"), ("Screen", "شاشة (Screen)"), ("Screenshot of the viewport", "لقطة شاشة لمنفذ العرض"), + ("Search", "بحث"), ("Search all assets", "البحث في جميع الأصول"), ("Search commands or keys", "البحث في الأوامر أو المفاتيح"), ("Seed", "البذرة العشوائية (Seed)"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..18a2c94b 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -328,6 +328,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Füllung"), ("Fill the closed path (lasso)", "Geschlossenen Pfad füllen (Lasso)"), ("Fill the path (close it first)", "Pfad füllen (zuerst schließen)"), + ("Filter", "Filter"), ("Filter the remaining noise while keeping edges and texture detail", "Restrauschen filtern und dabei Kanten und Texturdetails erhalten"), ("Filters", "Filter"), ("Fine noise", "Feines Rauschen"), @@ -716,6 +717,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Kratzer"), ("Screen", "Negativ multiplizieren"), ("Screenshot of the viewport", "Screenshot des Ansichtsfensters"), + ("Search", "Suchen"), ("Search all assets", "Alle Assets durchsuchen"), ("Search commands or keys", "Befehle oder Tasten suchen"), ("Seed", "Startwert"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..e0c7842b 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -319,6 +319,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Relleno"), ("Fill the closed path (lasso)", "Rellenar el trazado cerrado (lazo)"), ("Fill the path (close it first)", "Rellenar el trazado (ciérralo antes)"), + ("Filter", "Filtro"), ("Filter the remaining noise while keeping edges and texture detail", "Filtrar el ruido restante conservando los bordes y el detalle de la textura"), ("Filters", "Filtros"), ("Fine noise", "Ruido fino"), @@ -704,6 +705,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Arañazos"), ("Screen", "Trama"), ("Screenshot of the viewport", "Captura de la ventana gráfica"), + ("Search", "Buscar"), ("Search all assets", "Buscar en todos los recursos"), ("Search commands or keys", "Buscar comandos o teclas"), ("Seed", "Semilla"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..20209ab5 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -331,6 +331,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Remplissage"), ("Fill the closed path (lasso)", "Remplir le tracé fermé (lasso)"), ("Fill the path (close it first)", "Remplir le tracé (le fermer d'abord)"), + ("Filter", "Filtre"), ("Filter the remaining noise while keeping edges and texture detail", "Filtrer le bruit restant en préservant les contours et les détails de texture"), ("Filters", "Filtres"), ("Fine noise", "Bruit fin"), @@ -722,6 +723,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Rayures"), ("Screen", "Superposition"), ("Screenshot of the viewport", "Capture de la fenêtre d'affichage"), + ("Search", "Rechercher"), ("Search all assets", "Rechercher dans toutes les ressources"), ("Search commands or keys", "Rechercher des commandes ou des touches"), ("Seed", "Graine"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..8388adcc 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -325,6 +325,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Riempimento"), ("Fill the closed path (lasso)", "Riempi il tracciato chiuso (lazo)"), ("Fill the path (close it first)", "Riempi il tracciato (prima chiudilo)"), + ("Filter", "Filtro"), ("Filter the remaining noise while keeping edges and texture detail", "Filtra il rumore residuo preservando i bordi e i dettagli della texture"), ("Filters", "Filtri"), ("Fine noise", "Rumore fine"), @@ -713,6 +714,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Graffi"), ("Screen", "Scolora"), ("Screenshot of the viewport", "Screenshot della viewport"), + ("Search", "Cerca"), ("Search all assets", "Cerca in tutte le risorse"), ("Search commands or keys", "Cerca comandi o tasti"), ("Seed", "Seme"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..b20c9d55 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -316,6 +316,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "塗りつぶし"), ("Fill the closed path (lasso)", "閉じたパスを塗りつぶし (なげなわ)"), ("Fill the path (close it first)", "パスを塗りつぶし (先にパスを閉じる)"), + ("Filter", "フィルター"), ("Filter the remaining noise while keeping edges and texture detail", "エッジとテクスチャのディテールを保ちながら残りのノイズを除去"), ("Filters", "フィルター"), ("Fine noise", "細かいノイズ"), @@ -695,6 +696,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "引っかき傷"), ("Screen", "スクリーン"), ("Screenshot of the viewport", "ビューポートのスクリーンショット"), + ("Search", "検索"), ("Search all assets", "すべてのアセットを検索"), ("Search commands or keys", "コマンドまたはキーを検索"), ("Seed", "シード"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..9837b49f 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -313,6 +313,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "채우기"), ("Fill the closed path (lasso)", "닫힌 패스를 채웁니다 (올가미)"), ("Fill the path (close it first)", "패스를 채웁니다 (먼저 패스를 닫으세요)"), + ("Filter", "필터"), ("Filter the remaining noise while keeping edges and texture detail", "가장자리와 텍스처 디테일을 유지하면서 남은 노이즈를 걸러냅니다"), ("Filters", "필터"), ("Fine noise", "미세 노이즈"), @@ -686,6 +687,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "스크래치"), ("Screen", "스크린"), ("Screenshot of the viewport", "뷰포트 스크린샷"), + ("Search", "검색"), ("Search all assets", "모든 에셋 검색"), ("Search commands or keys", "명령 또는 키 검색"), ("Seed", "시드"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..7badff49 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -319,6 +319,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Preenchimento"), ("Fill the closed path (lasso)", "Preencher o caminho fechado (laço)"), ("Fill the path (close it first)", "Preencher o caminho (feche-o primeiro)"), + ("Filter", "Filtro"), ("Filter the remaining noise while keeping edges and texture detail", "Filtrar o ruído restante preservando bordas e detalhes de textura"), ("Filters", "Filtros"), ("Fine noise", "Ruído fino"), @@ -701,6 +702,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Arranhões"), ("Screen", "Tela"), ("Screenshot of the viewport", "Captura de tela da viewport"), + ("Search", "Pesquisar"), ("Search all assets", "Pesquisar em todos os recursos"), ("Search commands or keys", "Pesquisar comandos ou teclas"), ("Seed", "Semente"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..4afec91d 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -286,6 +286,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "填充"), ("Fill the closed path (lasso)", "填充闭合路径(套索)"), ("Fill the path (close it first)", "填充路径(请先闭合)"), + ("Filter", "滤镜"), ("Filter the remaining noise while keeping edges and texture detail", "在保留边缘和纹理细节的同时过滤剩余噪点"), ("Filters", "滤镜"), ("Fine noise", "细噪波"), @@ -647,6 +648,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "划痕"), ("Screen", "滤色"), ("Screenshot of the viewport", "视口截图"), + ("Search", "搜索"), ("Search all assets", "搜索所有资产"), ("Search commands or keys", "搜索命令或按键"), ("Seed", "随机种子"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..4db0acd7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -12,6 +12,7 @@ pub mod control; pub mod dock; pub mod docking; pub mod export_templates; +mod filter_slot; pub mod fonts; pub mod gpu; pub mod i18n; @@ -26,6 +27,8 @@ mod preview_worker; pub mod profile; pub mod properties_popup; pub mod render_mode; +mod resource_picker; +mod resource_picker_item; pub mod shelf; pub mod shelf_preview; pub mod state; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index b74aa300..3f645eeb 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -305,6 +305,7 @@ fn effect_command<'a>(app: &TextureCraftApp, id: &'a str) -> &'a str { } } +/// Runs the commands bound to the keys pressed this frame, outside text fields and key capture pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { if crate::keymap::capturing(ctx) || (ctx.memory(|memory| memory.focused().is_some()) && ctx.egui_wants_keyboard_input()) { return; @@ -319,6 +320,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } + // Escape closes an open popup first, before the Properties popup or the stroke + let popup_open = egui::Popup::is_any_open(ctx); + let active_shortcuts = crate::keymap::active(&app.ui.keymap); let mut commands_to_invoke: Vec<&str> = Vec::new(); ctx.input_mut(|input| { @@ -337,9 +341,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } - if app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; - } else if app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if app.ui.mode == Mode::Painting && !popup_open && input.consume_key(Modifiers::NONE, Key::Escape) { app.session.cancel_stroke(); app.session.tool.path.points.clear(); app.session.tool.path.editing = None; diff --git a/crates/ui-egui/src/resource_picker.rs b/crates/ui-egui/src/resource_picker.rs new file mode 100644 index 00000000..5b119c2f --- /dev/null +++ b/crates/ui-egui/src/resource_picker.rs @@ -0,0 +1,126 @@ +//! A popup under a slot that picks a resource, such as a filter, from grouped shelf tiles searched by name + +use egui::{Id, Response, Stroke, Ui}; + +use crate::i18n::tr; +use crate::resource_picker_item::ResourcePickerItem; +use crate::shelf; +use crate::shelf_preview::ShelfPreview; +use crate::theme::Tokens; +use crate::thumbs::Thumbs; + +/// Four shelf tiles and the scrollbar +const PICKER_WIDTH: f32 = 320.0; +/// The grid's height, fixed so the popup keeps its place while searching +const PICKER_HEIGHT: f32 = 340.0; +const CURRENT_OUTLINE_WIDTH: f32 = 1.5; +const TILE_ROUNDING: f32 = 3.0; + +/// Opens the picker `popup_id` with an empty, focused search field, or closes it +pub(crate) fn toggle(ctx: &egui::Context, popup_id: Id) { + if egui::Popup::is_id_open(ctx, popup_id) { + egui::Popup::close_id(ctx, popup_id); + return; + } + + egui::Popup::open_id(ctx, popup_id); + ctx.data_mut(|data| { + data.insert_temp(search_id(popup_id), String::new()); + data.insert_temp(focus_id(popup_id), true); + }); +} + +/// Draws picker `popup_id` at `slot` while open and returns the id clicked (`items` runs only then) +pub(crate) fn show( + slot: &Response, + popup_id: Id, + thumbs: &mut Thumbs, + current: Option<&str>, + items: impl FnOnce(&mut Thumbs) -> Vec, + preview: impl Fn(&'static str) -> ShelfPreview, +) -> Option<&'static str> { + let ctx = slot.ctx.clone(); + if !egui::Popup::is_id_open(&ctx, popup_id) { + return None; + } + + let items = items(thumbs); + let mut picked = None; + egui::Popup::from_response(slot) + .id(popup_id) + .open_memory(None) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .align(egui::RectAlign::BOTTOM_END) + .width(PICKER_WIDTH) + .show(|ui| { + ui.set_width(PICKER_WIDTH); + let just_opened = ui.data_mut(|data| data.remove_temp::(focus_id(popup_id))).unwrap_or(false); + let query = search_field(ui, popup_id, just_opened); + egui::ScrollArea::vertical().max_height(PICKER_HEIGHT).show(ui, |ui| { + // A search that leaves few tiles must not shrink the popup, or egui moves it + ui.set_min_height(PICKER_HEIGHT); + picked = grid(ui, thumbs, &items, &query, current, just_opened, &preview); + }); + }); + + if picked.is_some() { + egui::Popup::close_id(&ctx, popup_id); + } + picked +} + +/// The search field, focused the frame the picker opens; returns the lowercase query +fn search_field(ui: &mut Ui, popup_id: Id, just_opened: bool) -> String { + let mut search: String = ui.data(|data| data.get_temp(search_id(popup_id))).unwrap_or_default(); + let field = ui.add(egui::TextEdit::singleline(&mut search).hint_text(tr("Search")).desired_width(f32::INFINITY)); + if just_opened { + field.request_focus(); + } + + let query = search.trim().to_lowercase(); + ui.data_mut(|data| data.insert_temp(search_id(popup_id), search)); + query +} + +/// The items matching `query` as tiles under group headers, `current` outlined; returns the one clicked +fn grid( + ui: &mut Ui, + thumbs: &mut Thumbs, + items: &[ResourcePickerItem], + query: &str, + current: Option<&str>, + reveal_current: bool, + preview: &impl Fn(&'static str) -> ShelfPreview, +) -> Option<&'static str> { + let tk = Tokens::get(ui.ctx()); + let shown: Vec<&ResourcePickerItem> = items.iter().filter(|item| shelf::matches(query, &[item.label, item.id])).collect(); + let mut picked = None; + for group in shelf::categories(&shown, |item| item.group) { + shelf::header(ui, group); + shelf::tiles(ui, |ui| { + for item in shown.iter().filter(|item| item.group == group) { + let response = shelf::tile(ui, thumbs, item.thumbnail.as_ref(), || preview(item.id), item.label, None); + if current == Some(item.id) { + if reveal_current { + response.scroll_to_me(Some(egui::Align::Center)); + } + ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(CURRENT_OUTLINE_WIDTH, tk.accent), egui::StrokeKind::Inside); + } + if response.clicked() { + picked = Some(item.id); + } + } + }); + } + picked +} + +/// Where the picker keeps its search text +fn search_id(popup_id: Id) -> Id { + popup_id.with("search") +} + +/// Set while the picker waits for its first frame open +fn focus_id(popup_id: Id) -> Id { + popup_id.with("focus") +} diff --git a/crates/ui-egui/src/resource_picker_item.rs b/crates/ui-egui/src/resource_picker_item.rs new file mode 100644 index 00000000..5b9e8071 --- /dev/null +++ b/crates/ui-egui/src/resource_picker_item.rs @@ -0,0 +1,9 @@ +//! One choice offered by a resource picker + +/// A resource the picker offers: its id, translated label and group, and its thumbnail +pub(crate) struct ResourcePickerItem { + pub id: &'static str, + pub label: &'static str, + pub group: &'static str, + pub thumbnail: Option, +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 46ced908..55ef400f 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -266,7 +266,7 @@ fn drag_preview(ctx: &egui::Context) { p.galley(rect.min + vec2(6.0, 3.0), galley, tk.text_strong); } -fn matches(filter: &str, texts: &[&str]) -> bool { +pub(crate) fn matches(filter: &str, texts: &[&str]) -> bool { filter.is_empty() || texts.iter().any(|t| t.to_lowercase().contains(filter)) } @@ -275,13 +275,13 @@ fn title(ui: &mut Ui, text: &str) { ui.label(RichText::new(text).strong().color(tk.text_strong)); } -fn header(ui: &mut Ui, text: &str) { +pub(crate) fn header(ui: &mut Ui, text: &str) { let tk = Tokens::get(ui.ctx()); ui.add_space(2.0); ui.label(RichText::new(text).size(11.0).color(tk.text_dim)); } -fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { +pub(crate) fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing = vec2(4.0, 4.0); body(ui); @@ -290,7 +290,7 @@ fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { } /// The distinct categories of `items`, in order of first appearance. -fn categories(items: &[T], category: impl Fn(&T) -> &'static str) -> Vec<&'static str> { +pub(crate) fn categories(items: &[T], category: impl Fn(&T) -> &'static str) -> Vec<&'static str> { let mut out: Vec<&'static str> = Vec::new(); for c in items.iter().map(category) { if !out.contains(&c) { @@ -586,7 +586,7 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: } /// Asset tile with optional dragging and a larger hover preview -fn tile( +pub(crate) fn tile( ui: &mut Ui, thumbs: &mut Thumbs, tex: Option<&egui::TextureHandle>, diff --git a/crates/ui-egui/tests/filter_picker.rs b/crates/ui-egui/tests/filter_picker.rs new file mode 100644 index 00000000..31daef69 --- /dev/null +++ b/crates/ui-egui/tests/filter_picker.rs @@ -0,0 +1,81 @@ +//! The filter slot in Properties swaps a filter through its picker, and Add filter adds one + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, Filter, LayerId}; +use texturecraft_engine::{StackTarget, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +/// The app with an Invert filter on a fill layer's content, selected so Properties shows its slot +fn app_with_invert() -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + let effect = execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(); + let effect = LayerId(effect["effect"].as_u64().unwrap()); + execute(&mut session, "layer.select", &json!({"layer": layer["layer"]})).unwrap(); + session.target = StackTarget::Effect(effect); + + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + (harness, effect) +} + +/// The kind of effect `effect` now +fn kind(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> EffectKind { + harness.state().session.doc.project.effect(effect).unwrap().1.kind.clone() +} + +/// Clicks the Invert slot, which opens its picker +fn open_picker(harness: &mut Harness<'_, TextureCraftApp>) { + harness.get_by_role_and_label(Role::ComboBox, "Invert").click(); + harness.run_steps(3); + assert!(egui::Popup::is_any_open(&harness.ctx), "clicking the slot opens the picker"); +} + +#[test] +fn picking_from_the_slot_swaps_the_filter() { + let (mut harness, effect) = app_with_invert(); + open_picker(&mut harness); + + // The picker's search field has the focus as it opens + harness.event(egui::Event::Text("sharp".into())); + harness.run_steps(3); + assert_eq!(harness.query_all_by_label("Blur").count(), 0, "the search hides filters that don't match"); + + harness.get_by_label("Sharpen").click(); + harness.run_steps(3); + + assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Sharpen { .. })), "{:?}", kind(&harness, effect)); + assert!(!egui::Popup::is_any_open(&harness.ctx), "a pick closes the picker"); +} + +#[test] +fn escape_closes_the_picker_without_changes() { + let (mut harness, effect) = app_with_invert(); + open_picker(&mut harness); + + // Without the search field's focus, the painting shortcuts see Escape first + harness.ctx.memory_mut(|memory| memory.stop_text_input()); + harness.run_steps(2); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + assert!(!egui::Popup::is_any_open(&harness.ctx)); + assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Invert))); +} + +#[test] +fn add_filter_adds_a_filter_and_selects_it() { + let (mut harness, _) = app_with_invert(); + harness.get_by_label(egui_phosphor::regular::MAGIC_WAND).click(); + harness.run_steps(3); + + harness.get_by_label("Add filter").click(); + harness.run_steps(3); + + let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter is selected") }; + assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added)); + assert!(harness.query_by_role_and_label(Role::ComboBox, "HSL Perceptive").is_some(), "Properties shows the new filter's slot"); +}