diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index d8777926..01148e5d 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -10,7 +10,7 @@ use texturecraft_engine::core::{ LinkParam, MaterialLink, ProceduralKind, Projection, Source, }; use texturecraft_engine::filter_lib::scalar_params; -use texturecraft_engine::paint::{BrushAlpha, alphas}; +use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; use texturecraft_engine::{CloneFrom, StackTarget, Tool}; use crate::TextureCraftApp; @@ -19,7 +19,8 @@ use crate::layer_panel::{effect_preview_size, effect_row_height, layer_preview_s use crate::shelf::{Asset, ShelfDrag}; 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}; +use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; +use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, histogram, icon_button, section, section_with_reset, slider, slider_edit}; /// The filter Add filter adds: at its defaults it changes nothing, and its slot opens the picker to swap it const NEW_FILTER: &str = "hsl"; @@ -1136,6 +1137,8 @@ pub(crate) fn properties_title(app: &TextureCraftApp) -> String { } pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { + // A floating scroll bar would cover the right-aligned slider values and section reset icons + ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui)); } @@ -1456,104 +1459,150 @@ fn polygon_fill_paints_mask(app: &TextureCraftApp) -> Result { } } +/// Font size of the dim hint line under the Brush caption +const HINT_TEXT_SIZE: f32 = 10.5; + fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { - let b = &mut app.session.tool.brush; + let brush = &mut app.session.tool.brush; + let defaults = BrushSettings::default(); ui.label(caption(tr("Brush"))); let hint = tr("Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle."); - ui.label(RichText::new(hint).size(10.5).color(Tokens::get(ui.ctx()).text_dim)); - section(ui, "sec_size", tr("Size"), true, |ui| { - let mut size = b.size / 0.25 * 100.0; - if slider(ui, tr("Size"), &mut size, 0.05..=100.0, 1).changed() { - b.size = (size / 100.0 * 0.25).clamp(0.0005, 0.25); + ui.label(RichText::new(hint).size(HINT_TEXT_SIZE).color(Tokens::get(ui.ctx()).text_dim)); + + // Each section's reset puts back only the fields it shows + let size_fields = |settings: &BrushSettings| (settings.size, settings.min_size, settings.screen_space); + if section_with_reset(ui, "sec_size", tr("Size"), true, size_fields(brush) == size_fields(&defaults), |ui| { + let mut size_percent = brush.size / MAX_BRUSH_SIZE * 100.0; + if slider(ui, tr("Size"), &mut size_percent, 0.05..=100.0, 1).changed() { + brush.size = (size_percent / 100.0 * MAX_BRUSH_SIZE).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } - let mut ms = b.min_size * 100.0; - if slider(ui, tr("Minimum size (%)"), &mut ms, 0.0..=100.0, 0).changed() { - b.min_size = ms / 100.0; + + let mut min_size_percent = brush.min_size * 100.0; + if slider(ui, tr("Minimum size (%)"), &mut min_size_percent, 0.0..=100.0, 0).changed() { + brush.min_size = min_size_percent / 100.0; } - ui.checkbox(&mut b.screen_space, tr("Size in screen space")); - }); - section(ui, "sec_flow", tr("Flow and opacity"), true, |ui| { - let mut f = b.flow * 100.0; - if slider(ui, tr("Flow"), &mut f, 0.0..=100.0, 0).changed() { - b.flow = f / 100.0; + + ui.checkbox(&mut brush.screen_space, tr("Size in screen space")); + }) { + (brush.size, brush.min_size, brush.screen_space) = size_fields(&defaults); + } + + let flow_fields = |settings: &BrushSettings| (settings.flow, settings.opacity, settings.spacing, settings.hardness); + if section_with_reset(ui, "sec_flow", tr("Flow and opacity"), true, flow_fields(brush) == flow_fields(&defaults), |ui| { + let mut flow_percent = brush.flow * 100.0; + if slider(ui, tr("Flow"), &mut flow_percent, 0.0..=100.0, 0).changed() { + brush.flow = flow_percent / 100.0; } - let mut o = b.opacity * 100.0; - if slider(ui, tr("Stroke opacity"), &mut o, 0.0..=100.0, 0).changed() { - b.opacity = o / 100.0; + + let mut opacity_percent = brush.opacity * 100.0; + if slider(ui, tr("Stroke opacity"), &mut opacity_percent, 0.0..=100.0, 0).changed() { + brush.opacity = opacity_percent / 100.0; } - let mut s = b.spacing * 100.0; - if slider(ui, tr("Spacing"), &mut s, 1.0..=1000.0, 0).changed() { - b.spacing = s / 100.0; + + let mut spacing_percent = brush.spacing * 100.0; + if slider(ui, tr("Spacing"), &mut spacing_percent, 1.0..=1000.0, 0).changed() { + brush.spacing = spacing_percent / 100.0; } - let mut h = b.hardness * 100.0; - if slider(ui, tr("Hardness"), &mut h, 0.0..=99.9, 0).changed() { - b.hardness = h / 100.0; + + let mut hardness_percent = brush.hardness * 100.0; + if slider(ui, tr("Hardness"), &mut hardness_percent, 0.0..=99.9, 0).changed() { + brush.hardness = hardness_percent / 100.0; } - }); - section(ui, "sec_angle", tr("Angle"), false, |ui| { - slider(ui, tr("Angle"), &mut b.angle, -180.0..=180.0, 0); - ui.checkbox(&mut b.follow_path, tr("Follow path")); - }); - section(ui, "sec_jitter", tr("Jitters"), false, |ui| { - for (label, v) in [(tr("Size jitter"), &mut b.jitter_size), (tr("Angle jitter"), &mut b.jitter_angle), (tr("Flow jitter"), &mut b.jitter_flow)] { - let mut x = *v * 100.0; - if slider(ui, label, &mut x, 0.0..=100.0, 0).changed() { - *v = x / 100.0; + }) { + (brush.flow, brush.opacity, brush.spacing, brush.hardness) = flow_fields(&defaults); + } + + let angle_fields = |settings: &BrushSettings| (settings.angle, settings.follow_path); + if section_with_reset(ui, "sec_angle", tr("Angle"), false, angle_fields(brush) == angle_fields(&defaults), |ui| { + slider(ui, tr("Angle"), &mut brush.angle, -180.0..=180.0, 0); + ui.checkbox(&mut brush.follow_path, tr("Follow path")); + }) { + (brush.angle, brush.follow_path) = angle_fields(&defaults); + } + + let jitter_fields = |settings: &BrushSettings| (settings.jitter_size, settings.jitter_angle, settings.jitter_flow, settings.jitter_position); + if section_with_reset(ui, "sec_jitter", tr("Jitters"), false, jitter_fields(brush) == jitter_fields(&defaults), |ui| { + let jitters = [(tr("Size jitter"), &mut brush.jitter_size), (tr("Angle jitter"), &mut brush.jitter_angle), (tr("Flow jitter"), &mut brush.jitter_flow)]; + for (label, jitter) in jitters { + let mut jitter_percent = *jitter * 100.0; + if slider(ui, label, &mut jitter_percent, 0.0..=100.0, 0).changed() { + *jitter = jitter_percent / 100.0; } } - let mut pj = b.jitter_position * 100.0; - if slider(ui, tr("Position jitter"), &mut pj, 0.0..=400.0, 0).changed() { - b.jitter_position = pj / 100.0; + + let mut position_jitter_percent = brush.jitter_position * 100.0; + if slider(ui, tr("Position jitter"), &mut position_jitter_percent, 0.0..=400.0, 0).changed() { + brush.jitter_position = position_jitter_percent / 100.0; } - }); - section(ui, "sec_align", tr("Alignment and culling"), false, |ui| { + }) { + (brush.jitter_size, brush.jitter_angle, brush.jitter_flow, brush.jitter_position) = jitter_fields(&defaults); + } + + let alignment_fields = |settings: &BrushSettings| (settings.alignment, settings.backface_culling, settings.angle_fade, settings.depth); + if section_with_reset(ui, "sec_align", tr("Alignment and culling"), false, alignment_fields(brush) == alignment_fields(&defaults), |ui| { use texturecraft_engine::paint::Alignment; let alignments = [(Alignment::Tangent, tr("Tangent | Wrap")), (Alignment::Camera, tr("Camera"))]; - let shown = alignments.iter().find(|(a, _)| *a == b.alignment).map_or("", |(_, l)| l); + let shown = alignments.iter().find(|(alignment, _)| *alignment == brush.alignment).map_or("", |(_, label)| label); combo(ui, tr("Alignment"), shown, |ui| { - for (a, l) in alignments { - ui.selectable_value(&mut b.alignment, a, l); + for (alignment, label) in alignments { + ui.selectable_value(&mut brush.alignment, alignment, label); } }); - ui.checkbox(&mut b.backface_culling, tr("Backface culling")); - slider(ui, tr("Angle fade from"), &mut b.angle_fade.0, 0.0..=90.0, 0); - slider(ui, tr("Angle fade to"), &mut b.angle_fade.1, 0.0..=90.0, 0); - slider(ui, tr("Stamp depth"), &mut b.depth, 0.05..=4.0, 2); - }); - section(ui, "sec_particles", tr("Particles"), false, |ui| { - let pt = &mut b.particles; - ui.checkbox(&mut pt.enabled, tr("Particle brush (slides down the surface)")); - let mut count = pt.count as f32; + + ui.checkbox(&mut brush.backface_culling, tr("Backface culling")); + slider(ui, tr("Angle fade from"), &mut brush.angle_fade.0, 0.0..=90.0, 0); + slider(ui, tr("Angle fade to"), &mut brush.angle_fade.1, 0.0..=90.0, 0); + slider(ui, tr("Stamp depth"), &mut brush.depth, 0.05..=4.0, 2); + }) { + (brush.alignment, brush.backface_culling, brush.angle_fade, brush.depth) = alignment_fields(&defaults); + } + + if section_with_reset(ui, "sec_particles", tr("Particles"), false, brush.particles == defaults.particles, |ui| { + let particles = &mut brush.particles; + ui.checkbox(&mut particles.enabled, tr("Particle brush (slides down the surface)")); + + let mut count = particles.count as f32; if slider(ui, tr("Count per stamp"), &mut count, 1.0..=16.0, 0).changed() { - pt.count = count as u32; + particles.count = count as u32; } - let mut life = pt.lifetime as f32; - if slider(ui, tr("Lifetime (steps)"), &mut life, 1.0..=128.0, 0).changed() { - pt.lifetime = life as u32; + + let mut lifetime_steps = particles.lifetime as f32; + if slider(ui, tr("Lifetime (steps)"), &mut lifetime_steps, 1.0..=128.0, 0).changed() { + particles.lifetime = lifetime_steps as u32; } - slider(ui, tr("Gravity"), &mut pt.gravity, 0.0..=2.0, 2); - }); - section(ui, "sec_lazy", tr("Lazy mouse and symmetry"), false, |ui| { - slider(ui, tr("Lazy mouse distance"), &mut b.lazy, 0.0..=200.0, 0); + + slider(ui, tr("Gravity"), &mut particles.gravity, 0.0..=2.0, 2); + }) { + brush.particles = defaults.particles; + } + + let lazy_fields = |settings: &BrushSettings| (settings.lazy, settings.symmetry); + if section_with_reset(ui, "sec_lazy", tr("Lazy mouse and symmetry"), false, lazy_fields(brush) == lazy_fields(&defaults), |ui| { + slider(ui, tr("Lazy mouse distance"), &mut brush.lazy, 0.0..=200.0, 0); ui.horizontal(|ui| { - ui.checkbox(&mut b.symmetry.x, tr("Mirror X")); - ui.checkbox(&mut b.symmetry.y, tr("Mirror Y")); - ui.checkbox(&mut b.symmetry.z, tr("Mirror Z")); + ui.checkbox(&mut brush.symmetry.x, tr("Mirror X")); + ui.checkbox(&mut brush.symmetry.y, tr("Mirror Y")); + ui.checkbox(&mut brush.symmetry.z, tr("Mirror Z")); }); - let mut copies = f32::from(b.symmetry.radial); + + let mut copies = f32::from(brush.symmetry.radial); if slider(ui, tr("Radial copies"), &mut copies, 0.0..=32.0, 0).changed() { - b.symmetry.radial = copies as u8; + brush.symmetry.radial = copies as u8; } - ui.add_enabled_ui(b.symmetry.radial > 1, |ui| { + + ui.add_enabled_ui(brush.symmetry.radial > 1, |ui| { ui.horizontal(|ui| { ui.label(tr("Radial axis")); - for (k, name) in ["X", "Y", "Z"].into_iter().enumerate() { - ui.selectable_value(&mut b.symmetry.axis, k as u8, name); + for (axis_index, name) in ["X", "Y", "Z"].into_iter().enumerate() { + ui.selectable_value(&mut brush.symmetry.axis, axis_index as u8, name); } }); }); - }); - *b = b.sanitized(); + }) { + (brush.lazy, brush.symmetry) = lazy_fields(&defaults); + } + + *brush = brush.sanitized(); } /// One alpha in the picker: a 52×64 tile with the shape drawn by `paint` and a label. diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index bd24fac4..874fed90 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -662,6 +662,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "إعادة فحص مجلد المكتبة"), ("Reset UI", "إعادة ضبط واجهة المستخدم"), ("Reset all", "إعادة ضبط الكل"), + ("Reset to defaults", "إعادة الضبط إلى الإعدادات الافتراضية"), ("Reset to {shortcut}", "إعادة الضبط إلى {shortcut}"), ("Resizing", "تغيير الحجم"), ("Restore every default shortcut", "استعادة كل الاختصارات الافتراضية"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index eb2ad522..8e5abd07 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -701,6 +701,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "Bibliotheksordner neu einlesen"), ("Reset UI", "UI zurücksetzen"), ("Reset all", "Alle zurücksetzen"), + ("Reset to defaults", "Auf Standardwerte zurücksetzen"), ("Reset to {shortcut}", "Auf {shortcut} zurücksetzen"), ("Resizing", "Größe wird geändert"), ("Restore every default shortcut", "Alle Standard-Tastenkürzel wiederherstellen"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 9caa0c24..8eff44ec 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -689,6 +689,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "Volver a examinar la carpeta de la biblioteca"), ("Reset UI", "Restablecer interfaz"), ("Reset all", "Restablecer todo"), + ("Reset to defaults", "Restablecer valores predeterminados"), ("Reset to {shortcut}", "Restablecer a {shortcut}"), ("Resizing", "Redimensionando"), ("Restore every default shortcut", "Restaurar todos los atajos predeterminados"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index cfe98e5e..6759c6a5 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -704,6 +704,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "Réanalyser le dossier de la bibliothèque"), ("Reset UI", "Réinitialiser l'interface"), ("Reset all", "Tout réinitialiser"), + ("Reset to defaults", "Rétablir les valeurs par défaut"), ("Reset to {shortcut}", "Réinitialiser à {shortcut}"), ("Resizing", "Redimensionnement"), ("Restore every default shortcut", "Restaurer tous les raccourcis par défaut"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index a2814264..724dc6fe 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -698,6 +698,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "Ripeti la scansione della cartella della libreria"), ("Reset UI", "Ripristina interfaccia"), ("Reset all", "Ripristina tutto"), + ("Reset to defaults", "Ripristina i valori predefiniti"), ("Reset to {shortcut}", "Ripristina {shortcut}"), ("Resizing", "Ridimensionamento"), ("Restore every default shortcut", "Ripristina tutte le scorciatoie predefinite"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 1a71f4f9..95cbacaa 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -680,6 +680,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "ライブラリフォルダーを再スキャン"), ("Reset UI", "UIをリセット"), ("Reset all", "すべてリセット"), + ("Reset to defaults", "デフォルトに戻す"), ("Reset to {shortcut}", "{shortcut} にリセット"), ("Resizing", "サイズ変更中"), ("Restore every default shortcut", "すべてのショートカットをデフォルトに戻す"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 26ac5b31..dc391122 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -671,6 +671,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "라이브러리 폴더를 다시 검색합니다"), ("Reset UI", "UI 초기화"), ("Reset all", "모두 초기화"), + ("Reset to defaults", "기본값으로 초기화"), ("Reset to {shortcut}", "{shortcut}(으)로 초기화"), ("Resizing", "크기 조정 중"), ("Restore every default shortcut", "모든 기본 단축키를 복원합니다"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 64c5e270..897d2396 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -686,6 +686,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "Reexaminar a pasta da biblioteca"), ("Reset UI", "Redefinir interface"), ("Reset all", "Redefinir tudo"), + ("Reset to defaults", "Redefinir para o padrão"), ("Reset to {shortcut}", "Redefinir para {shortcut}"), ("Resizing", "Redimensionando"), ("Restore every default shortcut", "Restaurar todos os atalhos padrão"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index c03465b7..acb7b99b 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -629,6 +629,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "重新扫描库文件夹"), ("Reset UI", "重置界面"), ("Reset all", "全部重置"), + ("Reset to defaults", "恢复默认值"), ("Reset to {shortcut}", "重置为 {shortcut}"), ("Resizing", "正在调整大小"), ("Restore every default shortcut", "恢复所有默认快捷键"), diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 79aa7eab..fdaf1eb7 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -4,6 +4,7 @@ use craft_ui::buttons::{ButtonVisuals, IconButton, IconButtonStyle}; use egui::{Color32, CornerRadius, Response, RichText, Sense, Stroke, Ui, vec2}; +use crate::i18n::tr; use crate::theme::Tokens; /// The drag-and-drop payload of type `T` released on `resp` this frame. Unlike @@ -261,23 +262,102 @@ pub(crate) fn section_chevron(ui: &Ui, is_open: bool) -> RichText { /// A collapsible section header with a chevron pub fn section(ui: &mut Ui, id: &str, title: &str, default_open: bool, body: impl FnOnce(&mut Ui)) { + collapsible_section(ui, id, title, default_open, None, body); +} + +/// A [`section`] whose header ends in a reset icon, inert while `at_default`; true when clicked +pub fn section_with_reset(ui: &mut Ui, id: &str, title: &str, default_open: bool, at_default: bool, body: impl FnOnce(&mut Ui)) -> bool { + collapsible_section(ui, id, title, default_open, Some(at_default), body) +} + +/// Glyph size of a section header's reset icon +const SECTION_RESET_ICON_SIZE: f32 = 14.0; + +/// How much of `text_dim` the reset icon keeps while its section is at its defaults +const SECTION_RESET_AT_DEFAULT_OPACITY: f32 = 0.4; + +/// Gap between the reset icon's glyph and its keyboard focus outline +const SECTION_RESET_FOCUS_MARGIN: f32 = 2.0; + +/// Corner radius of the reset icon's keyboard focus outline +const SECTION_RESET_FOCUS_CORNER_RADIUS: u8 = 3; + +/// The header row and body of [`section`]; `reset_at_default` adds the reset icon +fn collapsible_section(ui: &mut Ui, id: &str, title: &str, default_open: bool, reset_at_default: Option, body: impl FnOnce(&mut Ui)) -> bool { let tokens = Tokens::get(ui.ctx()); let id = ui.make_persistent_id(id); let mut collapsing_state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, default_open); - let response = ui - .horizontal(|ui| { + + // Register focus from creation so the next frame does not clear the header's focus + let mut header_builder = egui::UiBuilder::new().id_salt(id.with("header")).sense(Sense::click()); + if reset_at_default.is_some() { + // Earlier controls can widen the content beyond the UI's original visible bounds + let visible_bounds = ui.stack().max_rect.intersect(ui.clip_rect()); + let mut header_bounds = ui.available_rect_before_wrap(); + header_bounds.min.x = header_bounds.min.x.max(visible_bounds.min.x); + header_bounds.max.x = header_bounds.max.x.min(visible_bounds.max.x).max(header_bounds.min.x); + header_builder = header_builder.max_rect(header_bounds); + } + + let mut reset_rect = None; + let header = ui.scope_builder(header_builder, |ui| { + ui.horizontal(|ui| { ui.add(egui::Label::new(section_chevron(ui, collapsing_state.is_open())).selectable(false)); - ui.add(egui::Label::new(RichText::new(title).strong().color(tokens.text_strong)).selectable(false)); - }) - .response - .interact(Sense::click()); - if response.clicked() { + let title = egui::Label::new(RichText::new(title).strong().color(tokens.text_strong)).selectable(false); + if reset_at_default.is_some() { + let icon_size = vec2(SECTION_RESET_ICON_SIZE, SECTION_RESET_ICON_SIZE); + let title_width = (ui.available_width() - icon_size.x - ui.spacing().item_spacing.x).max(0.0); + + // Long titles must not extend into the reset target in narrow panels + ui.allocate_ui_with_layout(vec2(title_width, icon_size.y), *ui.layout(), |ui| { + ui.set_width(title_width); + ui.add(title.truncate()); + }); + reset_rect = Some(ui.allocate_exact_size(icon_size, Sense::hover()).0); + } else { + ui.add(title); + } + }); + }); + if header.response.clicked() { collapsing_state.toggle(ui); } + // Registered after the header so the icon, not the header, takes its clicks + let mut reset_clicked = false; + if let (Some(at_default), Some(rect)) = (reset_at_default, reset_rect) { + // At the defaults the icon is inert, so Tab skips it + let sense = if at_default { Sense::CLICK } else { Sense::click() }; + let response = ui.interact(rect, id.with("reset"), sense).on_hover_text(tr("Reset to defaults")); + + // A focused reset must identify its section without relying on nearby visual text + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, !at_default, format_args!("{title}: {}", tr("Reset to defaults")))); + + let focused = response.has_focus(); + let color = if at_default { + tokens.text_dim.gamma_multiply(SECTION_RESET_AT_DEFAULT_OPACITY) + } else if response.hovered() || focused { + tokens.text_strong + } else { + tokens.text_dim + }; + let font = egui::FontId::proportional(SECTION_RESET_ICON_SIZE); + ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, egui_phosphor::regular::CLOCK_COUNTER_CLOCKWISE, font, color); + + // Enter or Space on the focused icon resets, so keyboard focus needs an outline + if focused { + let outline = rect.expand(SECTION_RESET_FOCUS_MARGIN); + ui.painter().rect_stroke(outline, CornerRadius::same(SECTION_RESET_FOCUS_CORNER_RADIUS), ui.visuals().selection.stroke, egui::StrokeKind::Outside); + } + + reset_clicked = response.clicked() && !at_default; + } + collapsing_state.show_body_unindented(ui, |ui| { ui.indent(id.with("in"), body); }); + + reset_clicked } /// A channel chip ("color", "metal", "rough"…): toggled = the accent-tinted well. diff --git a/crates/ui-egui/tests/it/brush_section_reset.rs b/crates/ui-egui/tests/it/brush_section_reset.rs new file mode 100644 index 00000000..643f0c42 --- /dev/null +++ b/crates/ui-egui/tests/it/brush_section_reset.rs @@ -0,0 +1,295 @@ +//! Each brush section header has a reset icon that puts only that section's settings back to their defaults + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::paint::{Alignment, BrushAlpha, BrushSettings, Particles, Symmetry}; +use texturecraft_ui_egui::TextureCraftApp; + +/// The default window; Properties shows only the top of the brush there, so lower headers are scrolled to +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// Frames for the first layout and fonts to settle +const STARTUP_FRAMES: usize = 4; + +/// Frames for a click to reach the brush settings and the panel +const SETTLE_FRAMES: usize = 3; + +/// Puts one section's fields of the first brush back to the second's values +type SectionReset = fn(&mut BrushSettings, &BrushSettings); + +/// Each brush section's title, a label shown only while it is open, whether it starts open, and its reset +const SECTIONS: [(&str, &str, bool, SectionReset); 7] = [ + ("Size", "Minimum size (%)", true, |brush, defaults| { + (brush.size, brush.min_size, brush.screen_space) = (defaults.size, defaults.min_size, defaults.screen_space) + }), + ("Flow and opacity", "Stroke opacity", true, |brush, defaults| { + (brush.flow, brush.opacity, brush.spacing, brush.hardness) = (defaults.flow, defaults.opacity, defaults.spacing, defaults.hardness) + }), + ("Angle", "Follow path", false, |brush, defaults| (brush.angle, brush.follow_path) = (defaults.angle, defaults.follow_path)), + ("Jitters", "Size jitter", false, |brush, defaults| { + (brush.jitter_size, brush.jitter_angle, brush.jitter_flow, brush.jitter_position) = + (defaults.jitter_size, defaults.jitter_angle, defaults.jitter_flow, defaults.jitter_position) + }), + ("Alignment and culling", "Backface culling", false, |brush, defaults| { + (brush.alignment, brush.backface_culling, brush.angle_fade, brush.depth) = + (defaults.alignment, defaults.backface_culling, defaults.angle_fade, defaults.depth) + }), + ("Particles", "Gravity", false, |brush, defaults| brush.particles = defaults.particles), + ("Lazy mouse and symmetry", "Lazy mouse distance", false, |brush, defaults| (brush.lazy, brush.symmetry) = (defaults.lazy, defaults.symmetry)), +]; + +/// A valid brush with every section field changed and a custom alpha that resets must preserve +fn changed_brush() -> BrushSettings { + BrushSettings { + size: 0.1, + min_size: 0.5, + screen_space: true, + flow: 0.5, + opacity: 0.6, + spacing: 0.5, + hardness: 0.9, + angle: 45.0, + follow_path: true, + jitter_size: 0.5, + jitter_angle: 0.4, + jitter_flow: 0.3, + jitter_position: 1.0, + alignment: Alignment::Camera, + backface_culling: false, + angle_fade: (30.0, 60.0), + depth: 2.0, + particles: Particles { enabled: true, count: 8, lifetime: 12, gravity: 0.5 }, + lazy: 50.0, + symmetry: Symmetry { x: true, y: true, z: true, radial: 4, axis: 2 }, + alpha: BrushAlpha::Star, + ..BrushSettings::default() + } +} + +/// The app showing the brush in Properties, set to `brush` +fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().session.tool.brush = brush; + harness.run_steps(STARTUP_FRAMES); + + harness +} + +/// The reset icon on the header row titled `title` +fn reset_icon<'tree>(harness: &'tree Harness<'_, TextureCraftApp>, title: &str) -> egui_kittest::Node<'tree> { + let label = format!("{title}: Reset to defaults"); + harness + .query_all_by_role(egui::Role::Button) + .find(|node| node.accesskit_node().label().as_deref() == Some(label.as_str())) + .unwrap_or_else(|| panic!("no reset icon on the {title} header")) +} + +/// Scrolls the header titled `title` into view and clicks its reset icon +fn click_reset(harness: &mut Harness<'_, TextureCraftApp>, title: &str) { + reset_icon(harness, title).scroll_to_me(); + harness.run_steps(SETTLE_FRAMES); + + reset_icon(harness, title).click(); + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn each_reset_puts_back_only_its_own_section() { + let defaults = BrushSettings::default(); + + for (title, _, _, reset_section) in SECTIONS { + let mut harness = app_with_brush(changed_brush()); + assert!(!reset_icon(&harness, title).accesskit_node().is_disabled(), "the {title} reset is enabled once its section changed"); + let history = harness.state().session.history_labels(); + + click_reset(&mut harness, title); + + let mut expected = changed_brush(); + reset_section(&mut expected, &defaults); + assert_eq!(harness.state().session.tool.brush, expected, "resetting {title}"); + assert_eq!(harness.state().session.history_labels(), history, "resetting {title} adds no undo step"); + } +} + +/// Scrolls the header titled `title` into view and clicks the header itself, folding or unfolding it +fn click_header(harness: &mut Harness<'_, TextureCraftApp>, title: &str) { + reset_icon(harness, title).scroll_to_me(); + harness.run_steps(SETTLE_FRAMES); + + let icon = reset_icon(harness, title).rect(); + harness.query_all_by_label(title).find(|label| label.rect().y_range().intersects(icon.y_range())).unwrap_or_else(|| panic!("no {title} header")).click(); + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn clicking_the_reset_icon_does_not_fold_or_unfold_the_section() { + for flip_first in [false, true] { + let mut harness = app_with_brush(changed_brush()); + if flip_first { + for (title, _, _, _) in SECTIONS { + click_header(&mut harness, title); + } + } + + for (title, body_label, starts_open, _) in SECTIONS { + let open = starts_open != flip_first; + + click_reset(&mut harness, title); + + assert_eq!(harness.query_by_label(body_label).is_some(), open, "{title} stays {}", if open { "open" } else { "closed" }); + } + } +} + +#[test] +fn at_the_defaults_the_reset_icons_are_inert() { + let mut harness = app_with_brush(BrushSettings::default()); + + for (title, body_label, starts_open, _) in SECTIONS { + assert!(reset_icon(&harness, title).accesskit_node().is_disabled(), "the {title} reset is disabled at the defaults"); + + click_reset(&mut harness, title); + + assert_eq!(harness.query_by_label(body_label).is_some(), starts_open, "the click doesn't reach the {title} header"); + assert_eq!(harness.state().session.tool.brush, BrushSettings::default(), "the {title} reset is inert"); + } +} + +#[test] +fn enter_and_space_on_the_focused_reset_icon_reset_only_its_section() { + for key in [egui::Key::Enter, egui::Key::Space] { + let mut harness = app_with_brush(changed_brush()); + reset_icon(&harness, "Size").focus(); + harness.run_steps(SETTLE_FRAMES); + assert!(reset_icon(&harness, "Size").is_focused()); + + harness.key_press(key); + harness.run_steps(SETTLE_FRAMES); + + let defaults = BrushSettings::default(); + let mut expected = changed_brush(); + (expected.size, expected.min_size, expected.screen_space) = (defaults.size, defaults.min_size, defaults.screen_space); + assert_eq!(harness.state().session.tool.brush, expected, "resetting Size with {key:?}"); + } +} + +#[test] +fn reset_icons_identify_their_sections() { + let harness = app_with_brush(changed_brush()); + + for (title, _, _, _) in SECTIONS { + let label = format!("{title}: Reset to defaults"); + assert!(harness.query_by_role_and_label(egui::Role::Button, &label).is_some(), "the reset button must name its {title} section"); + } +} + +#[test] +fn narrow_headers_keep_title_clicks_separate_from_reset() { + use texturecraft_ui_egui::widgets::section_with_reset; + + for right_to_left in [false, true] { + for width in [120.0, 180.0, 300.0] { + let title = "Lazy mouse and symmetry"; + let mut harness = Harness::builder().with_size(egui::vec2(width, 180.0)).with_context_setup(texturecraft_ui_egui::theme::install).build_ui_state( + |ui, resets| { + let alignment = if right_to_left { egui::Align::RIGHT } else { egui::Align::LEFT }; + ui.with_layout(egui::Layout::top_down(alignment), |ui| { + ui.style_mut().right_to_left = right_to_left; + if section_with_reset(ui, "narrow_section", title, false, false, |ui| { + ui.label("Section contents"); + }) { + *resets += 1; + } + }); + }, + 0_u32, + ); + harness.run_steps(STARTUP_FRAMES); + + let title_rect = harness.get_by_label(title).rect(); + let reset_label = format!("{title}: Reset to defaults"); + let reset_rect = harness.get_by_role_and_label(egui::Role::Button, &reset_label).rect(); + assert!(!title_rect.intersects(reset_rect), "title and reset overlap at width {width}, right_to_left={right_to_left}"); + assert!(reset_rect.left() >= 0.0 && reset_rect.right() <= width, "reset must stay inside the panel"); + + harness.get_by_label(title).click(); + harness.run_steps(SETTLE_FRAMES); + + assert_eq!(*harness.state(), 0, "clicking the title must not reset settings"); + assert!(harness.query_by_label("Section contents").is_some(), "clicking the title unfolds the section"); + + harness.get_by_role_and_label(egui::Role::Button, &reset_label).click(); + harness.run_steps(SETTLE_FRAMES); + + assert_eq!(*harness.state(), 1, "the reset remains clickable in a narrow panel"); + assert!(harness.query_by_label("Section contents").is_some(), "resetting leaves the section open"); + } + } +} + +#[test] +fn tab_visits_changed_resets_and_skips_default_resets() { + use texturecraft_ui_egui::widgets::section_with_reset; + + for at_default in [false, true] { + let mut harness = Harness::builder().with_size(egui::vec2(300.0, 180.0)).with_context_setup(texturecraft_ui_egui::theme::install).build_ui(|ui| { + let _ = ui.button("Before section"); + section_with_reset(ui, "tab_section", "Size", false, at_default, |_| {}); + let _ = ui.button("After section"); + }); + harness.run_steps(STARTUP_FRAMES); + harness.get_by_role_and_label(egui::Role::Button, "Before section").focus(); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.get_by_role_and_label(egui::Role::Button, "Before section").is_focused()); + let mut reset_was_focused = false; + + // Screen-reader mode also puts the header's labels in the focus order + for _ in 0..8 { + harness.key_press(egui::Key::Tab); + harness.run_steps(SETTLE_FRAMES); + reset_was_focused |= harness.get_by_role_and_label(egui::Role::Button, "Size: Reset to defaults").is_focused(); + if harness.get_by_role_and_label(egui::Role::Button, "After section").is_focused() { + break; + } + } + + assert!(harness.get_by_role_and_label(egui::Role::Button, "After section").is_focused(), "Tab reaches the next control"); + assert_eq!(reset_was_focused, !at_default, "only an enabled reset belongs in the Tab order"); + } +} + +#[test] +fn overflowing_contents_do_not_push_resets_outside_the_panel() { + use texturecraft_ui_egui::widgets::section_with_reset; + + for right_to_left in [false, true] { + let width = 120.0; + let mut harness = Harness::builder().with_size(egui::vec2(width, 180.0)).with_context_setup(texturecraft_ui_egui::theme::install).build_ui_state( + |ui, resets| { + let alignment = if right_to_left { egui::Align::RIGHT } else { egui::Align::LEFT }; + ui.with_layout(egui::Layout::top_down(alignment), |ui| { + ui.style_mut().right_to_left = right_to_left; + + // A slider in an earlier section can expand the scroll area's content width + ui.allocate_exact_size(egui::vec2(400.0, 1.0), egui::Sense::hover()); + if section_with_reset(ui, "overflow_section", "Size", false, false, |_| {}) { + *resets += 1; + } + }); + }, + 0_u32, + ); + harness.run_steps(STARTUP_FRAMES); + let reset_rect = harness.get_by_role_and_label(egui::Role::Button, "Size: Reset to defaults").rect(); + assert!(reset_rect.left() >= 0.0 && reset_rect.right() <= width, "reset must stay visible when content overflows, right_to_left={right_to_left}"); + + harness.get_by_role_and_label(egui::Role::Button, "Size: Reset to defaults").click(); + harness.run_steps(SETTLE_FRAMES); + + assert_eq!(*harness.state(), 1, "overflowing contents must not block the reset"); + } +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 36898836..7cf504e9 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -3,6 +3,7 @@ mod bake_mode; mod brush_drag; +mod brush_section_reset; mod close_unsaved; mod color_picker; mod color_selection_editor;