diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index d779bf77..b4f64ad4 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -12,7 +12,7 @@ use craft_ui::docking::{Action, DockArea, DockContent, DockStyle, Layout, Location, Node, PanelLimits, PanelState, Permissions, Placement}; use craft_ui::layout::{SplitAxis, SplitSize}; -use egui::{Id, Margin, RichText, Ui, vec2}; +use egui::{Id, Margin, RichText, Ui, Vec2, vec2}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -20,6 +20,11 @@ use crate::TextureCraftApp; use crate::i18n::tr; use crate::theme::Tokens; +mod header_band; +mod shown_group_tab; + +pub(crate) use shown_group_tab::HEADER_TITLE_LEFT; + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum Panel { Viewport, @@ -160,7 +165,9 @@ pub fn default_workspace() -> Workspace { const ASSETS_SPLIT_RATIO: f32 = 0.16; const VIEWPORT_SPLIT_RATIO: f32 = 0.80; const TEXTURE_SET_SPLIT_RATIO: f32 = 0.125; - const LAYERS_SPLIT_RATIO: f32 = 0.57; + + // Layers' share under the texture sets: Properties' 69% shows a fill down to its channels, Layers keeps three rows + const LAYERS_SPLIT_RATIO: f32 = 0.31; let column = split( SplitAxis::Vertical, @@ -412,15 +419,17 @@ const TAB_TEXT_SIZE: f32 = 12.5; /// Narrowest panel tab, in points const MIN_TAB_WIDTH: f32 = 54.0; -/// The dock look: each panel group a card on the window's frame colour, tab strips without hard lines, the shown tab a pill +/// The dock look: every panel group is a card under one chrome-coloured header bar, names in capitals at the left, a close × at the right fn style(ui: &Ui, tokens: &Tokens) -> DockStyle { let mut dock_style = DockStyle::from_ui(ui); dock_style.gap = f32::from(crate::theme::GUTTER); dock_style.min_pane = MIN_PANE_EXTENT; dock_style.background = tokens.panel; - dock_style.tab_background = tokens.panel; - dock_style.active_background = tokens.button; + dock_style.tab_background = tokens.chrome; + + // The shown and the hovered tab keep the bar's colour; their names brighten instead + dock_style.active_background = tokens.chrome; dock_style.text = tokens.text_strong; dock_style.inactive_text = tokens.text_dim; dock_style.border = egui::Stroke::NONE; @@ -468,7 +477,7 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { if let Some(panel) = app.ui.dock.raise.take() { area = area.raise_panel(panel); } - let output = area.show_content(ui, &layout, &style, &mut Panels { app, tokens }); + let output = area.show_content(ui, &layout, &style, &mut Panels { app, tokens, style: style.clone() }); crate::rail_popup::hand_drag_to_dock(&context, area_id()); // After the dock, which records the viewport the popup reaches into, and before a changed layout returns early @@ -491,15 +500,51 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { } } +/// Size of the panel names on a header bar +const HEADER_TITLE_SIZE: f32 = 12.0; + +/// Side of the close × at the right end of a header bar +const HEADER_CLOSE_SIZE: f32 = 22.0; + +/// Room right of the close × button, so its glyph ends where the Properties controls end (side padding plus scroll bar gutter) +const HEADER_CLOSE_RIGHT_MARGIN: f32 = 18.0; + +/// Whether a docked group's header bar ends in a close × (floating windows have one on their title bar; the viewport never closes) +fn header_closes(active: &Panel, floating: bool) -> bool { + !floating && permissions(active).closable +} + /// The panels' contents, names and limits for the dock area struct Panels<'a> { app: &'a mut TextureCraftApp, tokens: Tokens, + style: DockStyle, } /// Room between a panel's edges and its contents const PANEL_BODY_MARGIN: Margin = Margin::symmetric(8, 4); +/// Narrowest Properties panel and so its dock column: the 300 point design width plus the solid scroll bar; narrower, the 3D projection settings' X, Y, Z fields (the widest row) overlap +pub const PROPERTIES_MIN_WIDTH: f32 = 310.0; + +/// Least size of a docked or floating panel other than the 3D view and Properties +const PANEL_MIN_SIZE: Vec2 = vec2(120.0, 60.0); + +/// Least size of the 3D view +const VIEWPORT_MIN_SIZE: Vec2 = vec2(200.0, 150.0); + +/// Size a panel opens at when it floats +const FLOATING_SIZE: Vec2 = vec2(300.0, 380.0); + +/// Least size of `panel`, docked or floating; a dock column or split stops shrinking at its panels' largest +fn min_size(panel: Panel) -> Vec2 { + match panel { + Panel::Viewport => VIEWPORT_MIN_SIZE, + Panel::Properties => vec2(PROPERTIES_MIN_WIDTH, PANEL_MIN_SIZE.y), + _ => PANEL_MIN_SIZE, + } +} + /// The body of every panel except the viewport, in the dock or on the rail pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { // No project open: the library and the log work, the other panels about a project stay empty @@ -508,7 +553,9 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { return; } - egui::Frame::new().inner_margin(PANEL_BODY_MARGIN).show(ui, |ui| match panel { + // Properties draws full-width bands and tabs, so it keeps its own margins + let margin = if panel == Panel::Properties { Margin::ZERO } else { PANEL_BODY_MARGIN }; + egui::Frame::new().inner_margin(margin).show(ui, |ui| match panel { Panel::MeshMapSettings => crate::bake_mode::mesh_map_settings_panel(app, ui), Panel::Assets => crate::shelf::body(app, ui), Panel::CommonSettings => crate::bake_mode::common_settings_panel(app, ui), @@ -532,15 +579,16 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { impl DockContent for Panels<'_> { fn body(&mut self, ui: &mut Ui, panel: &Panel) { - let app = &mut *self.app; if *panel == Panel::Viewport { crate::rail_popup::remember_viewport(ui.ctx(), ui.max_rect()); ui.painter().rect_filled(ui.max_rect(), 0.0, self.tokens.viewport); - crate::viewport::central(app, ui); + crate::viewport::central(self.app, ui); return; } - panel_body(app, ui, *panel); + // Before the rows, which draw over the foot of the shown tab's box + self.paint_shown_group_tab(ui, *panel); + panel_body(self.app, ui, *panel); } fn logical_label(&self, panel: &Panel) -> String { @@ -550,8 +598,58 @@ impl DockContent for Panels<'_> { } } - fn label(&mut self, _ui: &Ui, _panel: &Panel, logical: &str, font: &egui::FontId, color: egui::Color32) -> egui::WidgetText { - RichText::new(logical).font(font.clone()).color(color).into() + fn label(&mut self, ui: &Ui, panel: &Panel, logical: &str, _font: &egui::FontId, color: egui::Color32) -> egui::WidgetText { + // Capitals on the bar only: menus and screen readers keep the logical name + let name = logical.to_uppercase(); + let font = crate::theme::semibold(HEADER_TITLE_SIZE); + + // Menus list the panels by these names too, in popups; only a header bar's names, docked or floating, centre on its band + if matches!(ui.layer_id().order, egui::Order::Foreground | egui::Order::Tooltip) { + return RichText::new(name).font(font).color(color).into(); + } + + header_band::header_name(ui, &name, font, color, self.header_lift(*panel)).into() + } + + fn group_header_width(&self, panels: &[Panel], active: &Panel, floating: bool, _strip_width: f32) -> f32 { + if header_closes(active, floating) { + HEADER_CLOSE_SIZE + HEADER_CLOSE_RIGHT_MARGIN + } else if redocks(panels, active, floating) { + DOCK_BUTTON_SIZE + DOCK_BUTTON_MARGIN + } else { + 0.0 + } + } + + /// A docked group's bar ends in its close ×; a rail panel floating on its own carries the Dock button that sends it back to the rail + fn group_header(&mut self, ui: &mut Ui, panels: &[Panel], active: &Panel, floating: bool) { + if redocks(panels, active, floating) { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::widgets::icon_button(ui, egui_phosphor::regular::ARROW_SQUARE_IN, tr("Dock"), false, DOCK_BUTTON_SIZE).clicked() { + self.app.ui.dock.close(*active); + } + }); + return; + } + + if !header_closes(active, floating) { + return; + } + + // On the names' line: the middle of the header band + let rect = ui.max_rect(); + let button = egui::Rect::from_center_size( + egui::pos2(rect.right() - HEADER_CLOSE_RIGHT_MARGIN - HEADER_CLOSE_SIZE / 2.0, rect.center().y - self.header_lift(*active)), + vec2(HEADER_CLOSE_SIZE, HEADER_CLOSE_SIZE), + ); + let clicked = ui + .scope_builder(egui::UiBuilder::new().max_rect(button), |ui| { + crate::widgets::icon_button(ui, egui_phosphor::regular::X, tr("Close Panel"), false, HEADER_CLOSE_SIZE).clicked() + }) + .inner; + if clicked { + self.app.ui.dock.close(*active); + } } fn permissions(&self, panel: &Panel) -> Permissions { @@ -559,29 +657,11 @@ impl DockContent for Panels<'_> { } fn limits(&self, panel: &Panel) -> PanelLimits { - let min = if *panel == Panel::Viewport { vec2(200.0, 150.0) } else { vec2(120.0, 60.0) }; - PanelLimits { min, ..PanelLimits::default() } + PanelLimits { min: min_size(*panel), ..PanelLimits::default() } } - fn floating_size(&self, _panel: &Panel) -> Option { - Some(vec2(300.0, 380.0)) - } - - fn group_header_width(&self, panels: &[Panel], active: &Panel, floating: bool, _strip_width: f32) -> f32 { - if redocks(panels, active, floating) { DOCK_BUTTON_SIZE + DOCK_BUTTON_MARGIN } else { 0.0 } - } - - /// A rail panel floating on its own carries the Dock button that sends it back to the rail - fn group_header(&mut self, ui: &mut Ui, panels: &[Panel], active: &Panel, floating: bool) { - if !redocks(panels, active, floating) { - return; - } - - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if crate::widgets::icon_button(ui, egui_phosphor::regular::ARROW_SQUARE_IN, tr("Dock"), false, DOCK_BUTTON_SIZE).clicked() { - self.app.ui.dock.close(*active); - } - }); + fn floating_size(&self, panel: &Panel) -> Option { + Some(FLOATING_SIZE.max(min_size(*panel))) } } @@ -614,6 +694,31 @@ mod tests { assert_eq!(panels_of(&w), [Panel::Assets, Panel::Viewport, Panel::TextureSetList, Panel::Layers, Panel::TextureSetSettings, Panel::Properties]); } + #[test] + fn the_default_right_column_gives_properties_about_two_thirds_under_the_texture_sets() { + let workspace = default_workspace(); + let Some(Node::Split { second: right, .. }) = workspace.layout.root.as_ref() else { panic!("assets | rest") }; + let Node::Split { second: column, .. } = right.as_ref() else { panic!("viewport | right column") }; + let Node::Split { second: below_sets, .. } = column.as_ref() else { panic!("texture sets | rest") }; + let Node::Split { size: SplitSize::Ratio(layers), first, second, .. } = below_sets.as_ref() else { panic!("layers | properties") }; + assert!(matches!(first.as_ref(), Node::Tabs { panels, .. } if panels.first() == Some(&Panel::Layers))); + assert!(matches!(second.as_ref(), Node::Tabs { panels, .. } if panels == &[Panel::Properties])); + let properties = 1.0 - layers; + assert!((2.0 / 3.0..0.7).contains(&properties), "Properties takes about 69% of the column, at least two thirds: {properties}"); + } + + #[test] + fn a_saved_split_keeps_its_own_share() { + let mut workspace = default_workspace(); + let Some(Node::Split { second: right, .. }) = workspace.layout.root.as_mut() else { panic!("assets | rest") }; + let Node::Split { second: column, .. } = right.as_mut() else { panic!("viewport | right column") }; + let Node::Split { second: below_sets, .. } = column.as_mut() else { panic!("texture sets | rest") }; + let Node::Split { size, .. } = below_sets.as_mut() else { panic!("layers | properties") }; + *size = SplitSize::Ratio(0.57); + let back = Dock::from_value(serde_json::to_value(&workspace).unwrap()); + assert_eq!(back.workspace(), &workspace, "a layout saved with the old split opens unchanged"); + } + #[test] fn default_dock_round_trips() { let dock = Dock::default(); diff --git a/crates/ui-egui/src/docking/header_band.rs b/crates/ui-egui/src/docking/header_band.rs new file mode 100644 index 00000000..95dcdeec --- /dev/null +++ b/crates/ui-egui/src/docking/header_band.rs @@ -0,0 +1,60 @@ +//! A docked header's band: the tab strip plus the gutter above it, less a hairline of separation, with the names' capitals centred on it + +use craft_ui::docking::{Layout, Node}; +use craft_ui::layout::SplitAxis; +use egui::text::{LayoutJob, TextFormat}; +use egui::{Align, Color32, FontId, Ui}; + +use super::Panel; + +/// Gutter between two stacked panels left showing between the upper panel and the header band under it, as the reference keeps a dark line there +const PANEL_SEPARATION: f32 = 2.0; + +/// How far a header under another panel reaches above its tab strip: the gutter between them, less the separation +pub(super) const HEADER_RISE: f32 = crate::theme::GUTTER as f32 - PANEL_SEPARATION; + +/// Whether `panel`'s docked group sits under another panel, a gutter above its header; floating groups and the top row have none +pub(super) fn under_a_panel(layout: &Layout, panel: Panel) -> bool { + let Some(root) = &layout.root else { return false }; + let mut nodes: Vec<(&Node, bool)> = vec![(root, false)]; + while let Some((node, below)) = nodes.pop() { + match node { + Node::Split { axis, first, second, .. } => { + nodes.push((first, below)); + nodes.push((second, below || *axis == SplitAxis::Vertical)); + } + Node::Tabs { panels, .. } if panels.contains(&panel) => return below, + Node::Dock { columns, .. } => { + for column in columns { + if let Some(index) = column.groups.iter().position(|group| group.panels.contains(&panel)) { + return below || index > 0; + } + } + } + _ => {} + } + } + + false +} + +/// `name` laid out so that, centred as the dock centres every name, its capitals' middle sits `lift` above the strip's (a galley's height counts descenders) +pub(super) fn header_name(ui: &Ui, name: &str, font: FontId, color: Color32, lift: f32) -> LayoutJob { + let format = TextFormat { font_id: font, color, valign: Align::TOP, ..Default::default() }; + let mut job = LayoutJob::single_section(name.to_owned(), format); + let galley = ui.painter().layout_job(job.clone()); + + // The first capital's ink; a name without one (a script without capitals) keeps the galley's middle + let capital = galley.rows.first().and_then(|row| row.glyphs.iter().find(|glyph| glyph.chr.is_uppercase()).map(|glyph| (row.pos.y, glyph))); + let ink_middle = capital.map_or(galley.size().y / 2.0, |(row_top, glyph)| row_top + glyph.pos.y + glyph.uv_rect.offset.y + glyph.uv_rect.size.y / 2.0); + + // Room below the name raises it when centred, room above lowers it + let shift = ink_middle - galley.size().y / 2.0 + lift; + if shift < 0.0 + && let Some(section) = job.sections.first_mut() + { + section.format.valign = Align::BOTTOM; + } + job.first_row_min_height = galley.size().y + 2.0 * shift.abs(); + job +} diff --git a/crates/ui-egui/src/docking/shown_group_tab.rs b/crates/ui-egui/src/docking/shown_group_tab.rs new file mode 100644 index 00000000..61f5d4e0 --- /dev/null +++ b/crates/ui-egui/src/docking/shown_group_tab.rs @@ -0,0 +1,102 @@ +//! The shown tab of a docked panel group, drawn as the Properties section tabs draw theirs: a raised box joined to the panel's body + +use craft_ui::docking::{DockContent, Layout, Node}; +use egui::text::TextWrapping; +use egui::{Rect, Ui, pos2}; + +use super::header_band::{HEADER_RISE, header_name, under_a_panel}; +use super::{HEADER_TITLE_SIZE, Panel, Panels}; +use crate::property_sheet::{full_height_tab_rect, shown_tab_box}; +use crate::theme::semibold; + +/// Room the dock leaves around a tab's name, half on each side (craft-ui's dock renderer keeps its own copy private) +const DOCK_TAB_PADDING: f32 = 24.0; + +/// From a panel's left edge to its header's name +pub(crate) const HEADER_TITLE_LEFT: f32 = DOCK_TAB_PADDING / 2.0; + +/// Width of the dock's "…" button for the tabs that do not fit (private in craft-ui's dock renderer as well) +const OVERFLOW_WIDTH: f32 = 22.0; + +/// Room between a tab's box and its neighbouring tabs; the first tab's box starts on the panel's left edge +const BOX_INSET: f32 = 4.0; + +/// The panels of the group holding `panel` and whether that group floats; a collapsed stack has no tabs +fn group_of(layout: &Layout, panel: Panel) -> Option<(&[Panel], bool)> { + let docked = layout.root.iter().map(|root| (root, false)); + let floating = layout.floating.iter().map(|window| (&window.root, true)); + let mut nodes: Vec<(&Node, bool)> = docked.chain(floating).collect(); + while let Some((node, floats)) = nodes.pop() { + match node { + Node::Split { first, second, .. } => { + nodes.push((first, floats)); + nodes.push((second, floats)); + } + Node::Tabs { panels, .. } if panels.contains(&panel) => return Some((panels, floats)), + Node::Dock { columns, .. } => { + let group = columns.iter().flat_map(|column| &column.groups).find(|group| group.panels.contains(&panel)); + if let Some(group) = group { + return Some((&group.panels, floats)); + } + } + _ => {} + } + } + None +} + +impl Panels<'_> { + /// How far `panel`'s header band reaches above its tab strip: the gutter above it, under another panel + fn header_rise(&self, panel: Panel) -> f32 { + if under_a_panel(&self.app.ui.dock.workspace.layout, panel) { HEADER_RISE } else { 0.0 } + } + + /// How far `panel`'s header name sits above its tab strip's middle: on its header band's middle + pub(super) fn header_lift(&self, panel: Panel) -> f32 { + self.header_rise(panel) / 2.0 + } + + /// Over the tab the dock drew for `panel`, the panel shown in its group, paints the section tabs' raised box and the name again; a panel alone keeps its plain header. `ui` is the panel's body, right under the strip + pub(super) fn paint_shown_group_tab(&self, ui: &Ui, panel: Panel) { + let Some((panels, floating)) = group_of(&self.app.ui.dock.workspace.layout, panel) else { return }; + if panels.len() < 2 { + return; + } + + let Some(shown) = panels.iter().position(|member| *member == panel) else { return }; + + // The dock's own tab layout: names at their natural width, shrunk or moved to "…" when the strip is short + let body = ui.max_rect(); + let strip = Rect::from_min_max(pos2(body.left(), body.top() - self.style.tab_height), pos2(body.right(), body.top())); + let band = Rect::from_x_y_ranges(strip.x_range(), strip.top() - self.header_rise(panel)..=strip.bottom()); + let font = semibold(HEADER_TITLE_SIZE); + let names: Vec = panels.iter().map(|member| self.logical_label(member).to_uppercase()).collect(); + let natural: Vec = + names.iter().map(|name| ui.painter().layout_no_wrap(name.clone(), font.clone(), self.style.text).size().x + DOCK_TAB_PADDING).collect(); + let header = self.group_header_width(panels, &panel, floating, strip.width()).clamp(0.0, strip.width()); + let available = (strip.width() - header - self.style.drag_bar_width).max(0.0); + let fit = craft_ui::tabs::fit(&natural, shown, available, self.style.min_tab_width, OVERFLOW_WIDTH); + let mut left = strip.left(); + for (index, width) in fit.shown { + if index != shown { + left += width; + continue; + } + + // The body's clip stops at the strip, which the box rises into up to the band's top + let clip = ui.clip_rect(); + let mut painter = ui.painter().clone(); + painter.set_clip_rect(Rect::from_x_y_ranges(clip.x_range(), band.top()..=clip.bottom())); + let box_left = if left > strip.left() { left + BOX_INSET } else { left }; + shown_tab_box(&painter, &self.tokens, full_height_tab_rect(band, box_left, left + width - BOX_INSET)); + + let Some(name) = names.get(index) else { return }; + let mut job = header_name(ui, name, font, self.style.text, self.header_lift(panel)); + job.wrap = TextWrapping::truncate_at_width((width - DOCK_TAB_PADDING).max(0.0)); + let galley = painter.layout_job(job); + let at = pos2(left + HEADER_TITLE_LEFT, strip.center().y - galley.size().y / 2.0); + painter.galley(at, galley, self.style.text); + return; + } + } +} diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs new file mode 100644 index 00000000..53afe419 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -0,0 +1,8 @@ +//! The Properties panel's rows, groups and controls, shared by every panel so they line up + +mod section_tabs; + +pub(crate) use section_tabs::{full_height_tab_rect, shown_tab_box}; + +/// Side padding: every row starts and ends this far inside the panel +pub(crate) const PAD: f32 = 12.0; diff --git a/crates/ui-egui/src/property_sheet/section_tabs.rs b/crates/ui-egui/src/property_sheet/section_tabs.rs new file mode 100644 index 00000000..5b7d6187 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/section_tabs.rs @@ -0,0 +1,19 @@ +use egui::{CornerRadius, Painter, Rect, pos2}; + +use crate::theme::Tokens; + +/// The chosen tab starts this far below the strip's top and reaches this far into the panel +const TAB_BELOW: f32 = 6.0; + +/// Corner rounding of the chosen tab +pub(crate) const TAB_ROUNDING: u8 = 5; + +/// A tab from `left` to `right` filling `strip`'s whole height and reaching as far into the panel as a section tab: a docked group's shown tab +pub(crate) fn full_height_tab_rect(strip: Rect, left: f32, right: f32) -> Rect { + Rect::from_min_max(pos2(left, strip.top()), pos2(right, strip.bottom() + TAB_BELOW)) +} + +/// The shown tab's box over `tab`: the panel's colour, rounded, so it rises from the panel below the strip +pub(crate) fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) { + painter.rect_filled(tab, CornerRadius::same(TAB_ROUNDING), tokens.panel); +} diff --git a/crates/ui-egui/tests/it/panel_header.rs b/crates/ui-egui/tests/it/panel_header.rs new file mode 100644 index 00000000..8a9caed5 --- /dev/null +++ b/crates/ui-egui/tests/it/panel_header.rs @@ -0,0 +1,235 @@ +//! Every docked panel group sits under one header bar: its names at the left, the shown one raised as a box when the group has several, a close × at the right + +use craft_ui::docking::{Action, Placement}; +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::{Dock, Panel, permissions}; + +use crate::{BAKE_RESOLUTION, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION, click_at, panel_close_button}; + +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// A floating window over the viewport, `[x, y, width, height]` +const FLOATING_RECT: [f32; 4] = [600.0, 200.0, 320.0, 400.0]; + +fn app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).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.run_steps(STARTUP_FRAMES); + + harness +} + +/// The rect of the tab whose name starts with `name` +fn tab_rect(harness: &Harness<'_, TextureCraftApp>, name: &str) -> egui::Rect { + harness + .get_all_by_role(Role::Tab) + .find(|tab| tab.accesskit_node().label().is_some_and(|label| label.starts_with(name))) + .map(|tab| tab.rect()) + .unwrap_or_else(|| panic!("a {name} tab")) +} + +#[test] +fn every_docked_panel_header_ends_in_its_own_close_button() { + let harness = app(); + let names = ["Assets", "Texture Sets", "Layers", "Properties - "]; + let tabs: Vec = names.iter().map(|name| tab_rect(&harness, name)).collect(); + for (name, tab) in names.iter().zip(&tabs) { + let close = panel_close_button(&harness, *tab); + + // No other group's tab between a tab and its close button: the button is on its own bar + let between = tabs.iter().any(|other| other.y_range().contains(close.center().y) && other.min.x > tab.max.x && other.max.x < close.min.x); + assert!(!between, "{name} has no close button on its own header"); + } +} + +#[test] +fn the_header_close_button_closes_its_panel() { + let mut harness = app(); + assert!(harness.state().ui.dock.is_visible(Panel::Properties)); + let close = panel_close_button(&harness, tab_rect(&harness, "Properties - ")); + click_at(&mut harness, close.center()); + + assert!(!harness.state().ui.dock.is_open(Panel::Properties)); + assert!(harness.state().ui.dock.is_visible(Panel::Layers), "only the panel under the bar closes"); +} + +/// With an effect selected the Properties header names its type, not the effect's own name (every filter reads "Filter") +#[test] +fn the_properties_header_names_the_selected_effects_type() { + let mut harness = app(); + let session = &mut harness.state_mut().session; + let layer = texturecraft_engine::execute(session, "layer.add.fill", &serde_json::Value::Null).unwrap()["layer"].as_u64().unwrap(); + let blur = texturecraft_engine::execute(session, "effect.add.filter", &serde_json::json!({"layer": layer, "target": "content", "filter": "blur"})).unwrap() + ["effect"] + .as_u64() + .unwrap(); + texturecraft_engine::execute(session, "effect.set", &serde_json::json!({"effect": blur, "name": "Soften edges"})).unwrap(); + texturecraft_engine::execute(session, "layer.select", &serde_json::json!({"layer": layer, "target": blur})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + + tab_rect(&harness, "Properties - Filter"); + + let level = texturecraft_engine::execute(&mut harness.state_mut().session, "effect.add.levels", &serde_json::json!({"layer": layer, "target": "content"})) + .unwrap()["effect"] + .as_u64() + .unwrap(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &serde_json::json!({"layer": layer, "target": level})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + tab_rect(&harness, "Properties - Levels"); +} + +/// How far a header under another panel reaches above its tab strip: the 6 px gutter less a 2 px separation (docking/header_band.rs) +const HEADER_RISE: f32 = 4.0; + +/// Room between a later tab's box and its tab's left edge (docking/shown_group_tab.rs, private to the crate) +const BOX_INSET: f32 = 4.0; + +/// Rounded boxes painted this frame over `tab` whose top is `rise` above it: the raised box of a shown tab +fn tab_boxes(harness: &Harness<'_, TextureCraftApp>, tab: egui::Rect, rise: f32) -> Vec { + harness + .output() + .shapes + .iter() + .filter_map(|shape| match &shape.shape { + egui::Shape::Rect(rect) => { + let rises = (rect.rect.top() - (tab.top() - rise)).abs() < 0.5; + let raised = rises && rect.corner_radius != egui::CornerRadius::ZERO && tab.x_range().contains(rect.rect.center().x); + raised.then_some(rect.rect) + } + _ => None, + }) + .collect() +} + +#[test] +fn a_groups_shown_tab_rises_as_a_box_and_the_others_and_a_lone_panels_do_not() { + let mut harness = app(); + let layers = tab_rect(&harness, "Layers"); + let settings = tab_rect(&harness, "Texture Set Settings"); + + assert_eq!(tab_boxes(&harness, layers, HEADER_RISE).len(), 1, "the shown Layers tab has its box, from the top of its header band"); + assert_eq!(tab_boxes(&harness, settings, HEADER_RISE).len(), 0, "the hidden tab is its name only"); + assert_eq!(tab_boxes(&harness, tab_rect(&harness, "Properties - "), HEADER_RISE).len(), 0, "a panel alone keeps its plain header"); + + click_at(&mut harness, settings.center()); + harness.run_steps(SETTLE_FRAMES); + + assert_eq!(tab_boxes(&harness, tab_rect(&harness, "Texture Set Settings"), HEADER_RISE).len(), 1, "the box goes with the shown tab"); + assert_eq!(tab_boxes(&harness, tab_rect(&harness, "Layers"), HEADER_RISE).len(), 0); +} + +#[test] +fn the_first_tabs_box_starts_on_the_panels_edge_and_a_later_tabs_box_keeps_its_inset() { + let mut harness = app(); + let layers = tab_rect(&harness, "Layers"); + let boxes = tab_boxes(&harness, layers, HEADER_RISE); + assert!(!boxes.is_empty(), "the shown Layers tab has its box"); + assert!(boxes.iter().all(|shown| (shown.left() - layers.left()).abs() < 0.5), "{boxes:?} starts on the panel's left edge {}", layers.left()); + + let settings = tab_rect(&harness, "Texture Set Settings"); + + click_at(&mut harness, settings.center()); + harness.run_steps(SETTLE_FRAMES); + + let boxes = tab_boxes(&harness, settings, HEADER_RISE); + assert!(!boxes.is_empty(), "the shown Texture Set Settings tab has its box"); + assert!(boxes.iter().all(|shown| (shown.left() - (settings.left() + BOX_INSET)).abs() < 0.5), "{boxes:?} keeps its air from the Layers tab"); +} + +/// The middle of the first capital's ink in each painted text reading `name` +fn capital_middles(harness: &Harness<'_, TextureCraftApp>, name: &str) -> Vec { + harness + .output() + .shapes + .iter() + .filter_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text() == name => { + let row = text.galley.rows.first()?; + let glyph = row.glyphs.iter().find(|glyph| glyph.chr.is_uppercase())?; + Some(text.pos.y + row.pos.y + glyph.pos.y + glyph.uv_rect.offset.y + glyph.uv_rect.size.y / 2.0) + } + _ => None, + }) + .collect() +} + +/// Names' capitals and the close × share the header band's middle: the tab strip plus, under another panel, the gutter above it less the separation +#[test] +fn header_names_capitals_and_close_buttons_sit_on_the_header_bands_middle() { + let harness = app(); + let headers = [ + ("Texture Sets", "TEXTURE SETS", 0.0), + ("Layers", "LAYERS", HEADER_RISE), + ("Texture Set Settings", "TEXTURE SET SETTINGS", HEADER_RISE), + ("Properties - ", "PROPERTIES - PAINT", HEADER_RISE), + ]; + for (tab, name, rise) in headers { + let tab = tab_rect(&harness, tab); + let middle = (tab.top() - rise + tab.bottom()) / 2.0; + let capitals = capital_middles(&harness, name); + assert!(!capitals.is_empty(), "{name} is painted"); + assert!(capitals.iter().all(|capital| (capital - middle).abs() < 0.75), "{name}'s capitals at {capitals:?}, its band's middle at {middle}"); + } + + let properties = tab_rect(&harness, "Properties - "); + let close = panel_close_button(&harness, properties); + let middle = (properties.top() - HEADER_RISE + properties.bottom()) / 2.0; + assert!((close.center().y - middle).abs() < 0.5, "the close × at {}, the band's middle at {middle}", close.center().y); +} + +/// A floating group's names sit on one line: the shown name, painted again over its tab, and the dimmed one beside it (the dimmed one kept its galley's middle) +#[test] +fn a_floating_groups_names_share_one_line() { + let mut harness = app(); + let mut workspace = harness.state().ui.dock.workspace().clone(); + let actions = [ + Action::Float { panel: Panel::Properties, rect: FLOATING_RECT }, + Action::Move { panel: Panel::TextureSetSettings, anchor: Panel::Properties, placement: Placement::Tab { before: None } }, + Action::Activate { panel: Panel::Properties }, + ]; + workspace.apply_all(actions, permissions).unwrap(); + harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); + harness.run_steps(SETTLE_FRAMES); + + let shown = capital_middles(&harness, "PROPERTIES - PAINT"); + let dimmed = capital_middles(&harness, "TEXTURE SET SETTINGS"); + assert!(!shown.is_empty() && !dimmed.is_empty(), "both names are painted"); + assert!(shown.iter().chain(&dimmed).all(|capital| (capital - shown[0]).abs() < 0.5), "the shown name's capitals at {shown:?}, the other's at {dimmed:?}"); +} + +/// The tab menu's panel names keep their plain layout: only the header bar pads a name to centre its capitals on the band +#[test] +fn a_tab_menus_panel_names_keep_their_plain_layout() { + let mut harness = app(); + let properties = tab_rect(&harness, "Properties - "); + let button = egui::PointerButton::Secondary; + harness.hover_at(properties.center()); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos: properties.center(), button, pressed, modifiers: egui::Modifiers::NONE }); + harness.run_steps(1); + } + harness.run_steps(SETTLE_FRAMES); + + let move_to = harness.get_by_role_and_label(Role::Button, "Move Panel to Group").rect(); + harness.hover_at(move_to.center()); + harness.run_steps(SETTLE_FRAMES); + + let entry = harness.get_by_role_and_label(Role::Button, "Layers").rect(); + let padded: Vec = harness + .output() + .shapes + .iter() + .filter_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text() == "LAYERS" && entry.contains(text.pos) => Some(text.galley.job.first_row_min_height), + _ => None, + }) + .collect(); + assert!(!padded.is_empty(), "the menu paints the Layers entry"); + assert!(padded.iter().all(|height| *height == 0.0), "the Layers entry is padded to {padded:?}"); +} diff --git a/crates/ui-egui/tests/it/rail.rs b/crates/ui-egui/tests/it/rail.rs index a994bcb3..30f3a153 100644 --- a/crates/ui-egui/tests/it/rail.rs +++ b/crates/ui-egui/tests/it/rail.rs @@ -7,18 +7,13 @@ use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; use texturecraft_ui_egui::state::ViewLayout; +use crate::{BAKE_RESOLUTION, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION, click_at}; + const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); /// The rail is the last 38 points of the window; the popup's own buttons sit left of it const RAIL_LEFT_EDGE: f32 = WINDOW_SIZE.x - 38.0; -// Small texture and bake sizes keep the sample session fast; the rail doesn't depend on them -const TEXTURE_RESOLUTION: u32 = 256; -const BAKE_RESOLUTION: u32 = 64; - -/// Frames for the first layout and fonts to settle -const STARTUP_FRAMES: usize = 4; - /// Where a drag out of the popup ends: in the viewport, clear of every panel const INTO_THE_VIEWPORT: egui::Vec2 = egui::vec2(-500.0, 100.0); @@ -28,9 +23,6 @@ const DRAG_STEPS: usize = 6; /// Frames between a drag's events: the press must land before the moves, and each move be seen const FRAMES_PER_DRAG_EVENT: usize = 2; -/// Frames for a click to reach the rail, the popup and the dock -const SETTLE_FRAMES: usize = 3; - // A setting only Shader Settings shows, and one only Display Settings shows const SHADER_SETTING: &str = "Index of refraction"; const DISPLAY_SETTING: &str = "Environment Opacity"; @@ -60,16 +52,8 @@ fn rail_icon<'h>(harness: &'h Harness<'_, TextureCraftApp>, name: &str) -> Optio } fn click_rail(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { - rail_icon(harness, name).expect("the panel's icon on the rail").click(); - harness.run_steps(SETTLE_FRAMES); -} - -fn click_at(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { - harness.hover_at(position); - harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - harness.run_steps(1); - harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - harness.run_steps(SETTLE_FRAMES); + let at = rail_icon(harness, name).expect("the panel's icon on the rail").rect().center(); + click_at(harness, at); } /// Drag with the primary button from `from` to `to` in a few moves @@ -197,9 +181,12 @@ fn dragging_the_title_onto_a_tab_strip_docks_the_panel_there() { let mut harness = app(); click_rail(&mut harness, "Log"); - let title = popup_title(&harness, "Log").center(); - let properties_tab = harness.get_by_label("Properties - Paint").rect().center(); - drag(&mut harness, title, properties_tab); + let title = popup_title(&harness, "Log"); + + // The popup covers the Properties strip and stays put while dragged: drop on the Texture Sets strip above it + let texture_sets_tab = harness.get_by_label("Texture Sets").rect(); + assert!(texture_sets_tab.bottom() < title.top(), "the Texture Sets strip {texture_sets_tab:?} is under the popup at {title:?}"); + drag(&mut harness, title.center(), texture_sets_tab.center()); let layout = &harness.state().ui.dock.workspace().layout; assert!(layout.contains(&Panel::Log) && !layout.floating.iter().any(|window| window.contains(&Panel::Log)), "the Log is docked"); diff --git a/crates/ui-egui/tests/it/settings_window.rs b/crates/ui-egui/tests/it/settings_window.rs index c2e31b66..477283c9 100644 --- a/crates/ui-egui/tests/it/settings_window.rs +++ b/crates/ui-egui/tests/it/settings_window.rs @@ -9,9 +9,7 @@ use texturecraft_ui_egui::state::{LibraryLocation, UiState}; use texturecraft_ui_egui::unavailable::NOT_AVAILABLE; use texturecraft_ui_egui::{TextureCraftApp, menus}; -#[path = "../../src/ui_state_store/memory_storage.rs"] -mod memory_storage; -use memory_storage::MemoryStorage; +use crate::memory_storage::MemoryStorage; /// The section captions of the General page, top to bottom. const SECTIONS: [&str; 13] = [ diff --git a/crates/ui-egui/tests/it/split_divider.rs b/crates/ui-egui/tests/it/split_divider.rs index 98a6c39c..075d4b80 100644 --- a/crates/ui-egui/tests/it/split_divider.rs +++ b/crates/ui-egui/tests/it/split_divider.rs @@ -1,10 +1,12 @@ //! The divider between the 3D and 2D views in the split layout resizes them and keeps the pointer from the views -use egui::{Event, Modifiers, PointerButton, Pos2, pos2}; +use egui::{Event, Modifiers, PointerButton, Pos2, Role, pos2}; use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::core::Channel; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::UiState; +use texturecraft_ui_egui::theme::GUTTER; use texturecraft_ui_egui::ui_state_store::UiStateStore; /// Narrowest a split view may get, as in `viewport.rs` @@ -37,6 +39,9 @@ impl eframe::Storage for MemoryStorage { fn split_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + + // The Layers tab is found by its English name, whatever the OS language is + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); harness } @@ -57,6 +62,17 @@ fn drag(harness: &mut Harness<'_, TextureCraftApp>, button: PointerButton, from: harness.run_steps(3); } +/// The views' right edge: a gutter left of the right column, whose Layers header starts at the column's left edge +fn views_right(harness: &Harness<'_, TextureCraftApp>) -> f32 { + let column_left = harness + .get_all_by_role(Role::Tab) + .filter(|tab| tab.accesskit_node().label().is_some_and(|label| label.starts_with("Layers"))) + .map(|tab| tab.rect().left()) + .next() + .expect("the right column's Layers header"); + column_left - f32::from(GUTTER) +} + /// The divider's x position: the 3D view ends 1 point left of it fn divider_x(harness: &Harness<'_, TextureCraftApp>) -> f32 { harness.state().viewport_rect.right() + 1.0 @@ -111,8 +127,8 @@ fn dragging_the_divider_resizes_the_views_within_their_minimum_width() { let mut harness = split_app(); let views_left = harness.state().viewport_rect.left(); let start_x = divider_x(&harness); - let views_width = (start_x - views_left) * 2.0; - let views_right = views_left + views_width; + let views_right = views_right(&harness); + let views_width = views_right - views_left; let y = harness.state().viewport_rect.center().y; assert_eq!(harness.state().ui.split_ratio, 0.5); @@ -204,9 +220,8 @@ fn dragging_the_divider_keeps_the_uv_texture_size_and_offset_on_screen() { harness.state_mut().ui.uv_pan = [0.2, 0.1]; harness.run_steps(2); - // The split starts centred, so the views end as far right of the divider as they start left of it let views_left = harness.state().viewport_rect.left(); - let views_right = views_left + (divider_x(&harness) - views_left) * 2.0; + let views_right = views_right(&harness); let y = harness.state().viewport_rect.center().y; let before = uv_texture_on_screen(&harness, views_right); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index b29ce0ed..7462516b 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -858,6 +858,35 @@ fn tile_generator_gradient_map_snapshot() { save(&mut harness, &output_dir, "tile-generator-gradient-map"); } +/// Every docked panel's header bar (names in capitals, a close × at the right), then the Properties × hovered +#[test] +#[ignore] +fn panel_header_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("panel-header-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + let close = harness + .get_all_by_label("Close Panel") + .map(|node| node.rect()) + .filter(|rect| rect.min.x > 1200.0) + .max_by(|a, b| a.min.y.total_cmp(&b.min.y)) + .expect("the Properties header's close button"); + harness.hover_at(close.center()); + save(&mut harness, &output_dir, "panel-header-close-hovered"); +} + /// Edit > Settings: the three pages and a compact window at 150% scale #[test] #[ignore] @@ -898,3 +927,33 @@ fn settings_pages_snapshot() { harness.state_mut().ui.windows.settings_draft.as_mut().unwrap().page = SettingsPage::General; save(&mut harness, &output_dir, "settings-compact"); } + +#[test] +#[ignore] +fn default_layout_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for color in [[0.2, 0.4, 0.7], [0.5, 0.5, 0.5], [0.8, 0.3, 0.1]] { + execute(&mut session, "layer.add.fill", &json!({ "color": color })).unwrap(); + } + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("default-layout-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + let properties_close = harness + .get_all_by_label("Close Panel") + .map(|node| node.rect()) + .filter(|rect| rect.min.x > 1200.0) + .max_by(|a, b| a.min.y.total_cmp(&b.min.y)) + .expect("the Properties header's close button"); + harness.hover_at(egui::pos2(properties_close.center().x - 120.0, properties_close.min.y - 6.0)); + save(&mut harness, &output_dir, "default-layout-split-hovered"); +}