diff --git a/crates/formats/src/mesh_export.rs b/crates/formats/src/mesh_export.rs index 2e0f2c53..d35156a9 100644 --- a/crates/formats/src/mesh_export.rs +++ b/crates/formats/src/mesh_export.rs @@ -7,6 +7,7 @@ pub(crate) mod usd; use std::collections::BTreeSet; use std::fmt::Write as _; +use craft_image_codecs::{DecodeOptions, Format, Limits, SampleType, decode_as_with, png_probe}; use texturecraft_core::{Channel, NormalFormat}; use texturecraft_geom::{Mesh, SubMesh}; @@ -182,12 +183,25 @@ fn png8_options(preset: ExportPreset, normal: NormalFormat) -> ExportOptions { } fn is_black(png: &[u8]) -> bool { - image::load_from_memory_with_format(png, image::ImageFormat::Png).map_or(true, |img| img.to_rgb8().iter().all(|v| *v == 0)) + // Keep the previous PNG decoder's 512 MiB allocation ceiling. + let options = DecodeOptions { limits: Limits { max_alloc: 512 << 20, ..Limits::none() }, keep_orientation: true }; + let Ok(image) = decode_as_with(Format::Png, png, &options) else { return true }; + let sample = image.sample_type(); + let layout = image.layout(); + let pixel_bytes = layout.channels() * sample.bytes(); + let color_bytes = layout.color_channels() * sample.bytes(); + let mut colors = image.data().chunks_exact(pixel_bytes).map(|pixel| &pixel[..color_bytes]); + match sample { + SampleType::U8 => colors.all(|color| color.iter().all(|&value| value == 0)), + // The prior RGB8 conversion rounds 16-bit values through 128 to zero. + SampleType::U16 => colors.all(|color| color.as_chunks::<2>().0.iter().all(|&value| u16::from_ne_bytes(value) <= 128)), + _ => true, + } } /// PNG color type 4 (gray + alpha) or 6 (RGBA), from the IHDR chunk. fn png_has_alpha(png: &[u8]) -> bool { - matches!(png.get(25), Some(4 | 6)) + png_probe::pixel_model(png).is_ok_and(|model| matches!(model.color_type, 4 | 6)) } /// The mesh as binary glTF (GLB) named `name`, with `textures[i]` on material `i` (materials @@ -426,6 +440,73 @@ mod tests { assert_eq!((sampler.mag_filter(), sampler.min_filter()), expected); } + #[test] + fn mesh_png_maps_keep_only_nonblack_color() { + let png = |color, samples: &[u8]| { + let mut out = std::io::Cursor::new(Vec::new()); + image::write_buffer_with_format(&mut out, samples, 1, 1, color, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mesh = texturecraft_geom::primitives::cube(1.0); + for (bytes, keep) in [ + (png(image::ColorType::Rgba8, &[0, 0, 0, 255]), false), + (png(image::ColorType::Rgba8, &[0, 1, 0, 0]), true), + (png(image::ColorType::L16, &128u16.to_ne_bytes()), false), + (png(image::ColorType::L16, &129u16.to_ne_bytes()), true), + (b"PNG without image data".to_vec(), false), + ] { + let file = |name: &str, bytes: &[u8]| ExportedFile { name: name.into(), bytes: bytes.to_vec(), width: 1, height: 1, warnings: Vec::new() }; + let emissive = file("Emissive.png", &bytes); + let textures = GlbTextures::from_files(vec![emissive.clone()]); + assert_eq!(textures.emissive.as_deref(), keep.then_some(bytes.as_slice())); + let glb = glb_bytes(&mesh, "PNG maps", &[textures]).unwrap(); + let glb = gltf::Gltf::from_slice(&glb).unwrap(); + assert_eq!(glb.materials().next().unwrap().emissive_texture().is_some(), keep); + + let roughness = png(image::ColorType::L8, &[64]); + let usd_maps = vec![emissive, file("Clearcoat.png", &bytes), file("ClearcoatRoughness.png", &roughness)]; + let usd = usd_bytes(&mesh, "PNG maps", &[usd_maps], UsdFormat::Usda).unwrap(); + if keep { + assert_eq!(usd.textures.len(), 3); + for (suffix, expected) in [("_Emissive.png", &bytes), ("_Clearcoat.png", &bytes), ("_ClearcoatRoughness.png", &roughness)] { + let (_, written) = usd.textures.iter().find(|(name, _)| name.ends_with(suffix)).unwrap(); + assert_eq!(written, expected); + } + } else { + assert!(usd.textures.is_empty()); + } + } + } + + #[test] + fn mesh_png_alpha_requires_a_png_with_stored_alpha() { + let encode = |color: png::ColorType, samples: &[u8], color_key: bool| { + let mut output = Vec::new(); + let mut encoder = png::Encoder::new(&mut output, 1, 1); + encoder.set_color(color); + if color_key { + encoder.set_trns(vec![0; 6]); + } + let mut writer = encoder.write_header().unwrap(); + writer.write_image_data(samples).unwrap(); + writer.finish().unwrap(); + output + }; + let mut impostor = vec![0; 26]; + impostor[25] = 6; + let mesh = texturecraft_geom::primitives::cube(1.0); + for (bytes, expected) in [ + (encode(png::ColorType::Rgba, &[0, 1, 2, 120], false), gltf::material::AlphaMode::Blend), + (encode(png::ColorType::Rgb, &[0, 0, 0], true), gltf::material::AlphaMode::Opaque), + (impostor, gltf::material::AlphaMode::Opaque), + ] { + let textures = GlbTextures { base_color: Some(bytes), ..GlbTextures::default() }; + let glb = glb_bytes(&mesh, "PNG alpha", &[textures]).unwrap(); + let glb = gltf::Gltf::from_slice(&glb).unwrap(); + assert_eq!(glb.materials().next().unwrap().alpha_mode(), expected); + } + } + #[test] fn glb_writes_clearcoat_and_sheen_extensions() { use serde_json::{Value, json}; diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 6256973b..7f8cebfe 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1798,7 +1798,8 @@ pub(crate) fn properties_title(app: &TextureCraftApp) -> String { let what = match (app.session.selected_layer().and_then(|id| project.layers.get(&id)), app.session.target) { // Polygon fill keeps its own properties wherever it can fill _ if tool == Tool::PolygonFill && tool_usable => tr(tool.label()).to_string(), - // The effect's type, not its own name (every filter reads "Filter") + + // Filters share a title even when the effect is renamed (Some(_), StackTarget::Effect(effect)) => project.effect(effect).map(|(_, found)| tr(effect_type_label(&found.kind)).to_string()).unwrap_or_default(), (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => tr("Fill").to_string(), (Some(layer), StackTarget::Content) if layer.is_group() => tr("Folder").to_string(), @@ -1821,12 +1822,17 @@ fn effect_type_label(kind: &EffectKind) -> &'static str { 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", properties_place(app))).auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui)); + + let selection = properties_selection(app); + let area = egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]); + let area = app.properties_scroll.prepare(area, ui.scope_id(), selection); + let output = area.show(ui, |ui| properties_contents(app, ui)); + app.properties_scroll.remember(selection, output.state.clamped_offset().y); } -/// What the docked Properties list keeps its own scroll place for: the selected layer and the part of it edited, none for the tool -fn properties_place(app: &TextureCraftApp) -> Option<(LayerId, StackTarget)> { - // A short panel in between would clamp a shared place back to the top; a greyed tool shows the layer's own sheet +/// The layer and target whose scroll offset is shown, or the polygon fill tool's own offset +fn properties_selection(app: &TextureCraftApp) -> crate::property_sheet::PropertiesSelection { + // Disabled polygon fill shows the selected layer's settings if app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) { return None; } @@ -1835,7 +1841,7 @@ fn properties_place(app: &TextureCraftApp) -> Option<(LayerId, StackTarget)> { } /// Room around the Properties rows not yet laid out by the property sheet: the sheet's side padding, so both start under the panel's name -const LEGACY_BODY_MARGIN: egui::Margin = egui::Margin::symmetric(crate::property_sheet::PAD as i8, 4); +const LEGACY_BODY_MARGIN: egui::Margin = egui::Margin::symmetric(crate::property_sheet::SIDE_PADDING_POINTS as i8, 4); /// Lays out `body` with the other panels' margin fn legacy_body(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { @@ -1849,41 +1855,51 @@ pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { return; } - let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id).cloned()); + let selected = app.session.selected_layer(); let tool = app.session.tool.tool; let tool_usable = app.session.tool_usable(tool); let tokens = Tokens::get(ui.ctx()); - match (&selected, app.session.target) { + legacy_body(ui, |ui| match (selected.and_then(|id| app.session.project().layers.get(&id)), app.session.target) { // Polygon fill shows its own settings and says what it fills into, wherever it can fill - _ if tool == Tool::PolygonFill && tool_usable => legacy_body(ui, |ui| polygon_fill_properties(app, ui)), - (Some(layer), StackTarget::Effect(effect)) => legacy_body(ui, |ui| effect_properties(app, ui, layer, effect)), - (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => legacy_body(ui, |ui| fill_properties(app, ui, layer)), - (Some(layer), StackTarget::Content) if layer.is_group() => legacy_body(ui, |ui| { + _ if tool == Tool::PolygonFill && tool_usable => polygon_fill_properties(app, ui), + (Some(layer), StackTarget::Effect(effect)) => { + let snapshot = layer.clone(); + effect_properties(app, ui, &snapshot, effect); + } + (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => { + let snapshot = layer.clone(); + fill_properties(app, ui, &snapshot); + } + (Some(layer), StackTarget::Content) if layer.is_group() => { ui.label(RichText::new(tr("A folder blends its children (pass-through). Set per-channel opacity in the layer rows.")).color(tokens.text_dim)); - }), - (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => legacy_body(ui, |ui| instance_properties(app, ui, layer)), - (Some(layer), StackTarget::Mask) => legacy_body(ui, |ui| { - height_mask_section(app, ui, layer); + } + (Some(Layer { kind: LayerKind::Instance { source }, .. }), StackTarget::Content) => { + let source = *source; + instance_properties(app, ui, source); + } + (Some(layer), StackTarget::Mask) => { + let layer_id = layer.id; + height_mask_section(app, ui, layer_id); if tool_usable { ui.separator(); tool_properties(app, ui); } - }), - (None, _) if !tool_usable => legacy_body(ui, |ui| { + } + (None, _) if !tool_usable => { ui.label(RichText::new(tr("Select a layer to paint on")).color(tokens.text_dim)); - }), - _ => legacy_body(ui, |ui| tool_properties(app, ui)), - } + } + _ => tool_properties(app, ui), + }); } /// An instance draws its source: point there for edits. -fn instance_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { - let tk = Tokens::get(ui.ctx()); - let Some(src) = layer.instance_source() else { return }; - let p = &app.session.doc.project; - let name = p.layers.get(&src).map_or_else(|| tr("a missing layer").to_string(), |l| format!("\"{}\"", l.name)); - let set = p.locate(src).and_then(|(ts, _, _)| p.texture_sets.get(ts)).map(|t| t.name.clone()).unwrap_or_default(); +fn instance_properties(app: &mut TextureCraftApp, ui: &mut Ui, source: LayerId) { + let tokens = Tokens::get(ui.ctx()); + let project = app.session.project(); + let name = project.layers.get(&source).map_or_else(|| tr("a missing layer").to_string(), |layer| format!("\"{}\"", layer.name)); + let set = project.locate(source).and_then(|(index, _, _)| project.texture_sets.get(index)).map(|set| set.name.as_str()).unwrap_or_default(); + ui.label(caption(tr("Instance"))); ui.label( RichText::new(format!( @@ -1891,33 +1907,35 @@ fn instance_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { ic::LINK, trf("Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", &[("name", &name), ("set", &set)]) )) - .color(tk.text_dim), + .color(tokens.text_dim), ); + if ui.button(tr("Select source")).clicked() { - app.run("layer.select", json!({"layer": src.0})); + app.run("layer.select", json!({"layer": source.0})); } } /// Mask with height: the layer's height shapes its mask transitions. -fn height_mask_section(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { - let id = layer.id.0; - let hm = app.session.doc.project.content_layer(layer.id).map(|l| l.height_mask).unwrap_or_default(); +fn height_mask_section(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId) { + let height_mask = app.session.project().content_layer(layer).map(|source| source.height_mask).unwrap_or_default(); + section(ui, "sec_height_mask", tr("Mask with height"), true, |ui| { - let mut on = hm.enabled; + let mut on = height_mask.enabled; if ui .checkbox(&mut on, tr("Combine with the layer's height")) .on_hover_text(tr("Partial mask values follow the layer's height: high parts show first")) .changed() { - app.run("layer.set", json!({"layer": id, "heightMask": {"enabled": on}})); + app.run("layer.set", json!({"layer": layer.0, "heightMask": {"enabled": on}})); } - ui.add_enabled_ui(hm.enabled, |ui| { - let (mut contrast, mut offset) = (hm.contrast, hm.offset); + + ui.add_enabled_ui(height_mask.enabled, |ui| { + let (mut contrast, mut offset) = (height_mask.contrast, height_mask.offset); if let Some(merge) = slider_edit(ui, tr("Contrast"), &mut contrast, 0.0..=16.0, 2) { - app.run("layer.set", json!({"layer": id, "heightMask": {"contrast": contrast}, "merge": merge})); + app.run("layer.set", json!({"layer": layer.0, "heightMask": {"contrast": contrast}, "merge": merge})); } if let Some(merge) = slider_edit(ui, tr("Height offset"), &mut offset, -1.0..=1.0, 2) { - app.run("layer.set", json!({"layer": id, "heightMask": {"offset": offset}, "merge": merge})); + app.run("layer.set", json!({"layer": layer.0, "heightMask": {"offset": offset}, "merge": merge})); } }); }); diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 16164aa4..05eb9ae9 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -166,7 +166,7 @@ pub fn default_workspace() -> Workspace { const VIEWPORT_SPLIT_RATIO: f32 = 0.80; const TEXTURE_SET_SPLIT_RATIO: f32 = 0.125; - // Layers' share under the texture sets: Properties' 69% shows a fill down to its channels, Layers keeps three rows + // Leave room for three layer rows and the fill's channel controls const LAYERS_SPLIT_RATIO: f32 = 0.31; let column = split( @@ -419,6 +419,9 @@ const TAB_TEXT_SIZE: f32 = 12.5; /// Narrowest panel tab, in points const MIN_TAB_WIDTH: f32 = 54.0; +/// Mixing in title ink keeps the light dock's focus outline above 3:1 on both header surfaces +const LIGHT_DOCK_ACCENT_TEXT_MIX: f32 = 0.2; + /// 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); @@ -428,12 +431,12 @@ fn style(ui: &Ui, tokens: &Tokens) -> DockStyle { dock_style.background = tokens.panel; dock_style.tab_background = tokens.chrome; - // The shown and the hovered tab keep the bar's colour; their names brighten instead + // The selected title is brighter while the strip keeps its colour 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; - dock_style.accent = tokens.accent; + dock_style.accent = if tokens.dark { tokens.accent } else { tokens.accent.lerp_to_gamma(tokens.text_strong, LIGHT_DOCK_ACCENT_TEXT_MIX) }; dock_style.floating_background = tokens.panel; dock_style.floating_stroke = egui::Stroke::new(FLOATING_BORDER_WIDTH, tokens.button_border); @@ -477,10 +480,11 @@ 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, style: style.clone() }); + + let output = area.show_content(ui, &layout, &style, &mut Panels { app, tokens, layout: &layout, style: &style }); 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 + // The popup needs the viewport the dock recorded this frame crate::rail_popup::show(app, &context); #[cfg(not(target_arch = "wasm32"))] @@ -518,7 +522,8 @@ fn header_closes(active: &Panel, floating: bool) -> bool { struct Panels<'a> { app: &'a mut TextureCraftApp, tokens: Tokens, - style: DockStyle, + layout: &'a Layout, + style: &'a DockStyle, } /// Room between a panel's edges and its contents @@ -603,7 +608,7 @@ impl DockContent for Panels<'_> { 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 + // Popup menu rows use their unpadded text metrics if matches!(ui.layer_id().order, egui::Order::Foreground | egui::Order::Tooltip) { return RichText::new(name).font(font).color(color).into(); } @@ -636,7 +641,7 @@ impl DockContent for Panels<'_> { return; } - // On the names' line: the middle of the header band + // Centre the close control on the header title line 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)), @@ -686,14 +691,15 @@ mod tests { #[test] fn default_workspace_has_every_panel_and_is_valid() { - let w = default_workspace(); - assert!(validate(&w).is_ok()); + let workspace = default_workspace(); + + assert!(validate(&workspace).is_ok()); for panel in Panel::ALL { - assert!(w.layout.contains(&panel) || w.hidden.iter().any(|(p, _)| *p == panel), "{panel:?} is neither shown nor hidden"); + assert!(workspace.layout.contains(&panel) || workspace.hidden.iter().any(|(hidden, _)| *hidden == panel), "{panel:?} is neither shown nor hidden"); } - assert_eq!(panels_of(&w), [Panel::Assets, Panel::Viewport, Panel::TextureSetList, Panel::Layers, Panel::TextureSetSettings, Panel::Properties]); + assert_eq!(panels_of(&workspace), [Panel::Assets, Panel::Viewport, Panel::TextureSetList, Panel::Layers, Panel::TextureSetSettings, Panel::Properties]); } #[test] diff --git a/crates/ui-egui/src/docking/header_band.rs b/crates/ui-egui/src/docking/header_band.rs index 3c00cd31..3cbd77d9 100644 --- a/crates/ui-egui/src/docking/header_band.rs +++ b/crates/ui-egui/src/docking/header_band.rs @@ -1,4 +1,4 @@ -//! 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 +//! Positions dock tab titles within the tab strip and the gutter above it. use craft_ui::docking::{Layout, Node}; use craft_ui::layout::SplitAxis; @@ -7,50 +7,42 @@ 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; +/// Gap left between a header band and the panel above it, in points. +const HEADER_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; +pub(super) const HEADER_RISE: f32 = crate::theme::GUTTER as f32 - HEADER_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 }; + layout.root.as_ref().and_then(|node| group_is_below_panel(node, panel, false)).unwrap_or(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; - } - } - } - _ => {} +fn group_is_below_panel(node: &Node, panel: Panel, below_panel: bool) -> Option { + match node { + Node::Split { axis, first, second, .. } => { + group_is_below_panel(second, panel, below_panel || *axis == SplitAxis::Vertical).or_else(|| group_is_below_panel(first, panel, below_panel)) } + Node::Tabs { panels, .. } if panels.contains(&panel) => Some(below_panel), + Node::Dock { columns, .. } => { + columns.iter().find_map(|column| column.groups.iter().position(|group| group.panels.contains(&panel))).map(|index| below_panel || index > 0) + } + _ => None, } - - 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 { +pub(super) fn header_name(ui: &Ui, name: &str, font: FontId, color: Color32, lift_points: 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 + // Scripts without capitals use the whole galley as their ink bounds 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; + let shift = ink_middle - galley.size().y / 2.0 + lift_points; if shift < 0.0 && let Some(section) = job.sections.first_mut() { diff --git a/crates/ui-egui/src/docking/shown_group_tab.rs b/crates/ui-egui/src/docking/shown_group_tab.rs index c9c500cb..2080d530 100644 --- a/crates/ui-egui/src/docking/shown_group_tab.rs +++ b/crates/ui-egui/src/docking/shown_group_tab.rs @@ -1,106 +1,101 @@ -//! 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 +//! The active tab in a panel group, drawn as a raised box joined to the panel body -use craft_ui::docking::{DockContent, Layout, Node}; +use craft_ui::docking::{DockContent, Node}; use egui::text::TextWrapping; -use egui::{Rect, Ui, pos2}; +use egui::{Rect, Stroke, StrokeKind, Ui, pos2}; use super::header_band::{HEADER_RISE, header_name, under_a_panel}; -use super::{HEADER_TITLE_SIZE, Panel, Panels}; +use super::{HEADER_TITLE_SIZE, Panel, Panels, area_id}; 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) +/// Horizontal padding of craft-ui's dock tab, in points 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; +/// Gap between the active tab's box and its neighbours, in points +const TAB_BOX_INSET: f32 = 4.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; +/// Insets the focus outline inside the tab's actual hit rect +const TAB_FOCUS_INSET: f32 = 2.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(); +/// Width of the focus outline in points +const TAB_FOCUS_STROKE_WIDTH: f32 = 1.0; - 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)); - } - } - _ => {} +/// The tab group containing `panel`; a collapsed stack has no tabs +fn group_of(node: &Node, panel: Panel) -> Option<&[Panel]> { + match node { + Node::Split { first, second, .. } => group_of(first, panel).or_else(|| group_of(second, panel)), + Node::Tabs { panels, .. } if panels.contains(&panel) => Some(panels), + Node::Dock { columns, .. } => { + columns.iter().flat_map(|column| &column.groups).find(|group| group.panels.contains(&panel)).map(|group| group.panels.as_slice()) } + _ => None, } - - None } impl Panels<'_> { - /// How far `panel`'s header band reaches above its tab strip: the gutter above it, under another panel + /// How far a header band reaches above its tab strip fn header_rise(&self, panel: Panel) -> f32 { - if under_a_panel(&self.app.ui.dock.workspace.layout, panel) { HEADER_RISE } else { 0.0 } + if under_a_panel(self.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 + /// How far a header name sits above the tab strip's centre 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 + /// Paints the active tab and its focus outline above the renderer's fallback paint 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 { + let layout = self.layout; + let in_group = layout + .root + .iter() + .chain(layout.floating.iter().map(|window| &window.root)) + .find_map(|root| group_of(root, panel)) + .is_some_and(|group| group.len() > 1); + if !in_group { 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 + // The shared renderer submits the active tab before it calls the panel body + let tab_id = area_id().with(("tab", &panel)); + let Some(tab) = ui.ctx().read_response(tab_id) else { return }; 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); + let tab_rect = tab.rect; + if tab.layer_id != ui.layer_id() || tab_rect.bottom() != body.top() || tab_rect.left() < body.left() || tab_rect.right() > body.right() { return; } + + let band_top = tab_rect.top() - self.header_rise(panel); + let box_left = if tab_rect.left() > body.left() { tab_rect.left() + TAB_BOX_INSET } else { tab_rect.left() }; + let box_right = tab_rect.right() - TAB_BOX_INSET; + if box_left >= box_right { + return; + } + + // Extend the body's clip over the header without widening it + 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 band = Rect::from_x_y_ranges(body.x_range(), band_top..=tab_rect.bottom()); + shown_tab_box(&painter, &self.tokens, full_height_tab_rect(band, box_left, box_right)); + + let name = self.logical_label(&panel).to_uppercase(); + let font = semibold(HEADER_TITLE_SIZE); + let mut job = header_name(ui, &name, font, self.style.text, (tab_rect.top() - band_top) / 2.0); + job.wrap = TextWrapping::truncate_at_width((tab_rect.width() - DOCK_TAB_PADDING).max(0.0)); + let galley = painter.layout_job(job); + let at = pos2(tab_rect.left() + HEADER_TITLE_LEFT, tab_rect.center().y - galley.size().y / 2.0); + painter.galley(at, galley, self.style.text); + + // Preserve the shared dock's keyboard focus ring above the opaque selected tab + let pointer_focus = ui.data(|data| data.get_temp::(tab_id.with("pointer-focus"))).unwrap_or(false); + let focus_rect = tab_rect.shrink(TAB_FOCUS_INSET); + if tab.has_focus() && !pointer_focus && focus_rect.is_positive() { + painter.rect_stroke(focus_rect, 0.0, Stroke::new(TAB_FOCUS_STROKE_WIDTH, self.style.accent), StrokeKind::Inside); + } } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 90519b44..1a8508eb 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -240,6 +240,7 @@ pub struct TextureCraftApp { pub placing_decal: Option, /// The Properties popup a right click in a view opens. pub properties_popup: Option, + properties_scroll: property_sheet::PropertiesScroll, /// The color selection the next click in the 3D or 2D view picks an ID color for pub picking_id_color: Option, /// Whether the next click on the model places the symmetry planes (Pick point in the symmetry settings) @@ -297,6 +298,7 @@ impl TextureCraftApp { /// The app around `session`, with the saved UI state (or defaults in the OS language) and the GPU viewport. pub fn new(cc: &eframe::CreationContext<'_>, mut session: Session) -> TextureCraftApp { theme::install(&cc.egui_ctx); + popup_drag::install(&cc.egui_ctx); // Bakes cast their rays on a GPU device of their own (created on the first bake) #[cfg(not(target_arch = "wasm32"))] @@ -346,6 +348,7 @@ impl TextureCraftApp { last_paint_uv: None, placing_decal: None, properties_popup: None, + properties_scroll: property_sheet::PropertiesScroll::default(), picking_id_color: None, picking_symmetry_plane: false, render_state: cc.wgpu_render_state.clone(), @@ -1007,6 +1010,7 @@ impl eframe::App for TextureCraftApp { #[cfg(not(target_arch = "wasm32"))] self.poll_link_imports(ctx); self.thumbs.sync_images(&self.session.images, self.session.revision); + self.properties_scroll.sync(&self.session); // The library shelf rescans when the window comes back (MaterialCraft may have sent a material) let focused = ctx.input(|i| i.viewport().focused).unwrap_or(true); @@ -1055,9 +1059,6 @@ impl eframe::App for TextureCraftApp { self.ui.mode = state::Mode::Painting; } - // Before any popup draws, so one a drag closes is gone from this frame - popup_drag::close_on_drag_outside(&ctx); - if !self.ui.hide_ui { titlebar::show(self, ui); banner(self, ui); diff --git a/crates/ui-egui/src/popup_drag.rs b/crates/ui-egui/src/popup_drag.rs index b1bb14a2..55cb91cc 100644 --- a/crates/ui-egui/src/popup_drag.rs +++ b/crates/ui-egui/src/popup_drag.rs @@ -1,22 +1,62 @@ -//! A press outside the popups that turns into a drag closes them: egui closes a popup only on a click, so a paint stroke or slider drag left it open +//! Dismisses popups when a primary press outside them becomes a drag -use egui::{Order, PointerButton}; +use std::sync::Arc; -/// Whether a primary press outside every popup has just been held or moved past a click: it starts a stroke, a slider drag or a panel move -pub(crate) fn drag_outside_popups(ctx: &egui::Context) -> bool { - let (dragging, origin, orbiting) = ctx.input(|input| { - let dragging = input.pointer.button_down(PointerButton::Primary) && input.pointer.is_decidedly_dragging(); - (dragging, input.pointer.press_origin(), input.modifiers.alt) - }); +use egui::{Event, Id, Order, PointerButton, ViewportId}; - // Alt+drag orbits the camera, which keeps popups open like the colour picker; a drag in a popup or a dropdown it opened stays in it - let over_popup = |at| ctx.layer_id_at(at).is_some_and(|layer| matches!(layer.order, Order::Foreground | Order::Tooltip | Order::Debug)); - dragging && !orbiting && origin.is_some_and(|at| !over_popup(at)) +/// Installs dismissal before drawing popups in the main and native floating windows +pub(crate) fn install(ctx: &egui::Context) { + ctx.on_begin_pass("dismiss popups on outside drag", Arc::new(|ui| update(ui.ctx()))); } -/// Closes egui's open popup, menu or dropdown when [`drag_outside_popups`]; a plain click outside is egui's own close -pub(crate) fn close_on_drag_outside(ctx: &egui::Context) { - if egui::Popup::is_any_open(ctx) && drag_outside_popups(ctx) { +/// Tracks the primary press across frames, including the frame that releases it +fn update(ctx: &egui::Context) { + let viewport = ctx.viewport_id(); + let press_id = Id::unique("popup-drag-press"); + let result_id = Id::unique("popup-drag-result"); + let (press, down, drag) = ctx.input(|input| { + let pointer = &input.pointer; + let press = pointer + .button_pressed(PointerButton::Primary) + .then(|| { + input.events.iter().rev().find_map(|event| match event { + Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, .. } => Some(*pos), + _ => None, + }) + }) + .flatten(); + let down = input.focused && pointer.button_down(PointerButton::Primary); + let released_without_click = pointer.button_released(PointerButton::Primary) && !pointer.button_clicked(PointerButton::Primary); + let drag = input.focused && !input.modifiers.alt && (released_without_click || (down && pointer.is_decidedly_dragging())); + (press, down, drag) + }); + + let started_outside = + press.map(|position| ctx.layer_id_at(position).is_none_or(|layer| !matches!(layer.order, Order::Foreground | Order::Tooltip | Order::Debug))); + let dismiss = ctx.data_mut(|data| { + let previous = data.get_temp::<(ViewportId, bool)>(press_id).filter(|(owner, _)| *owner == viewport); + let outside = started_outside.or(previous.map(|(_, outside)| outside)).unwrap_or(false); + if let Some(started_outside) = started_outside.filter(|_| down) { + data.insert_temp(press_id, (viewport, started_outside)); + } else if !down && previous.is_some() { + data.remove::<(ViewportId, bool)>(press_id); + } + + let dismiss = outside && drag; + if viewport == ViewportId::ROOT { + data.insert_temp(result_id, dismiss); + } + + dismiss + }); + + if dismiss && egui::Popup::is_any_open(ctx) { egui::Popup::close_all(ctx); } } + +/// Whether the main window's current pass has an outside drag for its app-owned popups +pub(crate) fn drag_outside_popups(ctx: &egui::Context) -> bool { + let id = Id::unique("popup-drag-result"); + ctx.data(|data| data.get_temp::(id).unwrap_or(false)) +} diff --git a/crates/ui-egui/src/properties_popup.rs b/crates/ui-egui/src/properties_popup.rs index 305c8bb6..00b08d04 100644 --- a/crates/ui-egui/src/properties_popup.rs +++ b/crates/ui-egui/src/properties_popup.rs @@ -56,6 +56,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { Some(PropertiesPopup::Open { .. }) => { let shown = ctx.memory(|memory| memory.area_rect(area_id())); let outside = pressed_at.is_some_and(|at| shown.is_some_and(|rect| !rect.contains(at))); + // A press in one of the popup's own dropdowns lands outside its area if outside && !egui::Popup::is_any_open(ctx) { app.properties_popup = Some(PropertiesPopup::Closing); @@ -65,12 +66,15 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } let Some(PropertiesPopup::Open { at, bounds }) = app.properties_popup else { return }; + let tokens = Tokens::get(ctx); egui::Area::new(area_id()).order(egui::Order::Foreground).fixed_pos(at).constrain_to(bounds.shrink(PROPERTIES_POPUP_VIEW_MARGIN)).show(ctx, |ui| { egui::Frame::popup(ui.style()).fill(tokens.panel).inner_margin(egui::Margin::ZERO).show(ui, |ui| { ui.set_width(PROPERTIES_POPUP_WIDTH); + // The area's remembered size would otherwise cap the scroll height ui.set_max_height(bounds.height() * PROPERTIES_POPUP_MAX_HEIGHT_SHARE); + // A floating bar would cover the sliders' right-aligned values ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); egui::ScrollArea::vertical().id_salt("properties_popup_scroll").show(ui, |ui| crate::dock::properties_contents(app, ui)); diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 53afe419..05a106f9 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -1,8 +1,10 @@ //! The Properties panel's rows, groups and controls, shared by every panel so they line up +mod properties_scroll; mod section_tabs; +pub(crate) use properties_scroll::{PropertiesScroll, PropertiesSelection}; 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; +pub(crate) const SIDE_PADDING_POINTS: f32 = 12.0; diff --git a/crates/ui-egui/src/property_sheet/properties_scroll.rs b/crates/ui-egui/src/property_sheet/properties_scroll.rs new file mode 100644 index 00000000..294d52f5 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/properties_scroll.rs @@ -0,0 +1,138 @@ +use std::collections::HashMap; + +use egui::{Id, ScrollArea}; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::{Session, StackTarget}; + +pub(crate) type PropertiesSelection = Option<(LayerId, StackTarget)>; + +/// Docked Properties offsets belong to the active document and its live selections +#[derive(Default)] +pub(crate) struct PropertiesScroll { + project_id: u64, + revision: u64, + drawn: Option<(Id, PropertiesSelection)>, + offsets: HashMap, +} + +impl PropertiesScroll { + pub(crate) fn sync(&mut self, session: &Session) { + if self.project_id != session.project_id { + *self = Self { project_id: session.project_id, revision: session.revision, ..Self::default() }; + } + + if self.revision == session.revision { + return; + } + + self.revision = session.revision; + let project = session.project(); + self.offsets.retain(|selection, _| { + let Some((layer_id, target)) = selection else { return true }; + let Some(layer) = project.layers.get(layer_id) else { return false }; + + match target { + StackTarget::Content => true, + StackTarget::Mask => project.layers.get(&project.mask_owner(*layer_id)).is_some_and(|owner| owner.mask.is_some()), + StackTarget::Effect(effect_id) => { + // Instances can edit a source effect while remaining selected + let source = layer.instance_source().and_then(|id| project.content_layer(id)).unwrap_or(layer); + let mask = layer.mask.as_ref().or(source.mask.as_ref()); + mask.into_iter().flat_map(|mask| &mask.effects).chain(&source.content_effects).any(|effect| effect.id == *effect_id) + || project.effect(*effect_id).is_some() + } + } + }); + + if self.offsets.capacity() / 2 > self.offsets.len() { + self.offsets.shrink_to_fit(); + } + } + + pub(crate) fn prepare(&mut self, area: ScrollArea, ui_id: Id, selection: PropertiesSelection) -> ScrollArea { + let current = (ui_id, selection); + if self.drawn == Some(current) { + return area; + } + + self.drawn = Some(current); + area.vertical_scroll_offset(self.offsets.get(&selection).copied().unwrap_or_default()) + } + + pub(crate) fn remember(&mut self, selection: PropertiesSelection, offset_points: f32) { + if offset_points > 0.0 { + self.offsets.insert(selection, offset_points); + } else { + self.offsets.remove(&selection); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + use texturecraft_engine::{execute, sample_session}; + + #[test] + fn instance_offsets_survive_selection_changes_until_the_source_targets_are_removed() { + let mut session = sample_session(128, 16).unwrap(); + execute(&mut session, "mask.add.white", &json!({})).unwrap(); + execute(&mut session, "layer.instance", &json!({})).unwrap(); + let instance = session.selected_layer().unwrap(); + execute(&mut session, "layer.select", &json!({"layer": instance.0, "target": "mask"})).unwrap(); + let mask = Some((instance, session.target)); + execute(&mut session, "effect.add.levels", &json!({"target": "mask"})).unwrap(); + let effect = Some((instance, session.target)); + let mut scroll = PropertiesScroll::default(); + scroll.sync(&session); + scroll.remember(mask, 24.0); + scroll.remember(effect, 52.0); + + execute(&mut session, "layer.select", &json!({"layer": instance.0})).unwrap(); + scroll.sync(&session); + + assert_eq!(scroll.offsets.get(&mask), Some(&24.0)); + assert_eq!(scroll.offsets.get(&effect), Some(&52.0)); + + execute(&mut session, "mask.remove", &json!({})).unwrap(); + scroll.sync(&session); + + assert!(scroll.offsets.is_empty()); + } + + #[test] + fn offsets_follow_live_selections_and_clear_on_project_replacement() { + let mut session = sample_session(128, 16).unwrap(); + let layer_id = LayerId(execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].as_u64().unwrap()); + let effect_id = + LayerId(execute(&mut session, "effect.add.levels", &json!({"layer": layer_id.0, "target": "content"})).unwrap()["effect"].as_u64().unwrap()); + let mut scroll = PropertiesScroll::default(); + let content = Some((layer_id, StackTarget::Content)); + let effect = Some((layer_id, StackTarget::Effect(effect_id))); + scroll.sync(&session); + scroll.remember(content, 42.0); + scroll.remember(effect, 68.0); + + let context = egui::Context::default(); + for (selection, expected_offset) in [(content, 42.0), (effect, 68.0), (content, 42.0)] { + let _ = context.run_ui(egui::RawInput::default(), |ui| { + let area = scroll.prepare(ScrollArea::vertical().max_height(80.0), ui.scope_id(), selection); + let output = area.show(ui, |ui| ui.add_space(256.0)); + + assert_eq!(output.state.clamped_offset().y, expected_offset); + }); + } + + execute(&mut session, "effect.remove", &json!({"effect": effect_id.0})).unwrap(); + scroll.sync(&session); + + assert_eq!(scroll.offsets.get(&content), Some(&42.0)); + assert!(!scroll.offsets.contains_key(&effect)); + + execute(&mut session, "file.close", &json!({})).unwrap(); + scroll.sync(&session); + + assert!(scroll.offsets.is_empty() && scroll.drawn.is_none()); + } +} diff --git a/crates/ui-egui/src/symmetry/mod.rs b/crates/ui-egui/src/symmetry/mod.rs index 081387c3..a8403a30 100644 --- a/crates/ui-egui/src/symmetry/mod.rs +++ b/crates/ui-egui/src/symmetry/mod.rs @@ -109,6 +109,7 @@ pub(crate) fn toolbar_controls(app: &mut TextureCraftApp, ui: &mut Ui) { let clicked_at = ui.input(|input| input.pointer.interact_pos().filter(|_| input.pointer.any_click())); let click_outside = clicked_at .is_some_and(|at| ui.ctx().layer_id_at(at).is_none_or(|layer| layer != shown.response.layer_id && layer.order != egui::Order::Foreground)); + if click_outside || crate::popup_drag::drag_outside_popups(ui.ctx()) { open = false; } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index ef2455a1..87e44604 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -495,19 +495,17 @@ fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) -> painter.add(mesh); } -/// From a panel body's top to its empty note's lettering: the reference's gap under the header's name -const EMPTY_NOTE_TOP: f32 = 9.0; +/// Gap above empty panel text, in points +const EMPTY_NOTE_TOP_GAP: f32 = 9.0; -/// The line an empty panel shows instead of its contents ("No properties found"): under the header at its name's left edge, greyed as the disabled toolbar icons are +/// Aligns an empty panel's note with its header pub(crate) fn empty_note(ui: &mut Ui, text: &str) { let tokens = Tokens::get(ui.ctx()); - ui.add_enabled_ui(false, |ui| { - let font = egui::TextStyle::Body.resolve(ui.style()); - let galley = ui.painter().layout_no_wrap(text.to_owned(), font, tokens.text); - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), EMPTY_NOTE_TOP + galley.size().y), Sense::hover()); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, false, text)); - let at = egui::pos2(rect.left() + crate::docking::HEADER_TITLE_LEFT, rect.top() + EMPTY_NOTE_TOP); - ui.painter().galley(at, galley, tokens.text); + let side_margin = crate::docking::HEADER_TITLE_LEFT as i8; + + ui.add_space(EMPTY_NOTE_TOP_GAP); + egui::Frame::new().inner_margin(egui::Margin::symmetric(side_margin, 0)).show(ui, |ui| { + ui.label(RichText::new(text).color(tokens.text_dim)); }); } diff --git a/crates/ui-egui/tests/it/empty_start.rs b/crates/ui-egui/tests/it/empty_start.rs index eedbb9c2..83170c99 100644 --- a/crates/ui-egui/tests/it/empty_start.rs +++ b/crates/ui-egui/tests/it/empty_start.rs @@ -105,10 +105,11 @@ fn the_empty_views_keep_the_view_picker_and_drop_the_camera_picker() { assert!(!has_camera_picker(&empty), "no camera picker"); - // The picker shows "Material" right of the tool shelf and the Assets panel and left of the right column: one per view in the split layout + // Only count the Material pickers between the side panels let pickers = painted(&empty).iter().filter(|(text, x)| text == "Material" && (300.0..1200.0).contains(x)).count(); assert_eq!(pickers, 2, "each of the two views keeps its view picker"); + drop(empty); let open = open_project(); diff --git a/crates/ui-egui/tests/it/layer_multi_select.rs b/crates/ui-egui/tests/it/layer_multi_select.rs index 5dab5e1d..c0d0054c 100644 --- a/crates/ui-egui/tests/it/layer_multi_select.rs +++ b/crates/ui-egui/tests/it/layer_multi_select.rs @@ -24,24 +24,25 @@ fn harness() -> (Harness<'static, TextureCraftApp>, [LayerId; 4]) { const SCROLL_FRAMES: usize = 25; /// Scrolls the row `name` into view: six rows overflow the Layers panel -fn show_row(h: &mut Harness<'_, TextureCraftApp>, name: &str) { - h.get_by_label(name).scroll_to_me(); - h.run_steps(SCROLL_FRAMES); +fn show_row(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { + harness.get_by_label(name).scroll_to_me(); + harness.run_steps(SCROLL_FRAMES); } /// Click the row `name` while `modifiers` are held (pressed before and released after the click). -fn click(h: &mut Harness<'_, TextureCraftApp>, name: &str, modifiers: Modifiers) { - show_row(h, name); - let at: Pos2 = h.get_by_label(name).rect().center(); - h.event(Event::PointerMoved(at)); - h.event(Event::ModifiersChanged(modifiers)); - h.run_steps(1); - h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers }); - h.run_steps(1); - h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers }); - h.run_steps(2); - h.event(Event::ModifiersChanged(Modifiers::NONE)); - h.run_steps(2); +fn click(harness: &mut Harness<'_, TextureCraftApp>, name: &str, modifiers: Modifiers) { + show_row(harness, name); + let at: Pos2 = harness.get_by_label(name).rect().center(); + + harness.event(Event::PointerMoved(at)); + harness.event(Event::ModifiersChanged(modifiers)); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(2); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(2); } fn highlighted(h: &Harness<'_, TextureCraftApp>, name: &str) -> bool { @@ -170,12 +171,13 @@ fn ctrl_a_leaves_text_fields_and_other_panels_alone() { } /// Right-click the row `name` and choose the menu item whose label starts with `item`. -fn row_menu(h: &mut Harness<'_, TextureCraftApp>, name: &str, item: &str) { - show_row(h, name); - h.get_by_label(name).click_secondary(); - h.run_steps(3); - h.get_by(|node| node.label().is_some_and(|label| label.starts_with(item))).click(); - h.run_steps(3); +fn row_menu(harness: &mut Harness<'_, TextureCraftApp>, name: &str, item: &str) { + show_row(harness, name); + + harness.get_by_label(name).click_secondary(); + harness.run_steps(3); + harness.get_by(|node| node.label().is_some_and(|label| label.starts_with(item))).click(); + harness.run_steps(3); } #[test] diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index e346617a..0a88c260 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -101,32 +101,33 @@ fn deeply_nested_effect_visibility_is_reachable_in_a_narrow_panel() { use craft_ui::layout::SplitSize; use texturecraft_ui_egui::docking::Dock; - let (mut h, layer) = harness(); + let (mut harness, layer) = harness(); for _ in 0..6 { - execute(&mut h.state_mut().session, "layer.group", &Value::Null).unwrap(); + execute(&mut harness.state_mut().session, "layer.group", &Value::Null).unwrap(); } - let mut workspace = h.state().ui.dock.workspace().clone(); + + let mut workspace = harness.state().ui.dock.workspace().clone(); let Some(Node::Split { second, .. }) = workspace.layout.root.as_mut() else { panic!("default columns") }; let Node::Split { size, second: column, .. } = second.as_mut() else { panic!("viewport and right column") }; *size = SplitSize::Ratio(0.99); - // Layers tall enough for the whole nested stack: the default gives most of the column to Properties + // Give Layers enough height to show the nested stack let Node::Split { second: below_sets, .. } = column.as_mut() else { panic!("texture sets and the rest") }; let Node::Split { size: layers_share, .. } = below_sets.as_mut() else { panic!("layers and properties") }; *layers_share = SplitSize::Ratio(0.9); - h.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); + harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); - // Properties holds its column at its minimum width: without it the column narrows as far as Layers allows - h.state_mut().ui.dock.close(texturecraft_ui_egui::docking::Panel::Properties); - h.run_steps(4); + // Closing Properties lets the column shrink to the Layers minimum + harness.state_mut().ui.dock.close(texturecraft_ui_egui::docking::Panel::Properties); + harness.run_steps(4); - let row = h.get_by_label("Effect A").rect(); + let row = harness.get_by_label("Effect A").rect(); assert!(row.width() < 180.0, "the test must use a compact panel: {row:?}"); let indent = (row.width() - 7.0 - 22.0 - 21.6 - 8.0 - 20.0 - 6.0).max(0.0); - click(&mut h, egui::pos2(row.left() + 15.0 + indent, row.center().y)); + click(&mut harness, egui::pos2(row.left() + 15.0 + indent, row.center().y)); - let content = &h.state().session.doc.project.layers[&layer].content_effects; + let content = &harness.state().session.doc.project.layers[&layer].content_effects; assert!(!content.iter().find(|effect| effect.name == "Effect A").unwrap().visible, "the compact eye toggles the effect instead of missing the panel"); } diff --git a/crates/ui-egui/tests/it/panel_header.rs b/crates/ui-egui/tests/it/panel_header.rs index 6485f50a..9e32fd57 100644 --- a/crates/ui-egui/tests/it/panel_header.rs +++ b/crates/ui-egui/tests/it/panel_header.rs @@ -125,6 +125,27 @@ fn a_groups_shown_tab_rises_as_a_box_and_the_others_and_a_lone_panels_do_not() { assert_eq!(tab_boxes(&harness, tab_rect(&harness, "Layers"), HEADER_RISE).len(), 0); } +#[test] +fn the_selected_dock_tab_keeps_its_keyboard_focus_outline_visible() { + let mut harness = app(); + let layers = tab_rect(&harness, "Layers"); + let tab_id = egui::Id::unique("texturecraft-docking").with(("tab", Panel::Layers)); + harness.ctx.memory_mut(|memory| memory.request_focus(tab_id)); + harness.run_steps(SETTLE_FRAMES); + + assert_eq!(harness.ctx.memory(|memory| memory.focused()), Some(tab_id)); + let raised_box = tab_boxes(&harness, layers, HEADER_RISE)[0]; + let shapes = &harness.output().shapes; + let box_index = shapes.iter().position(|shape| matches!(&shape.shape, egui::Shape::Rect(rect) if rect.rect == raised_box)).unwrap(); + assert!( + shapes[box_index + 1..].iter().any(|shape| { + matches!(&shape.shape, egui::Shape::Rect(rect) + if rect.stroke.width > 0.0 && layers.contains_rect(rect.rect) && rect.rect.contains(layers.center())) + }), + "the focus outline is painted above the selected tab" + ); +} + #[test] fn the_first_tabs_box_starts_on_the_panels_edge_and_a_later_tabs_box_keeps_its_inset() { let mut harness = app(); diff --git a/crates/ui-egui/tests/it/popup_press_close.rs b/crates/ui-egui/tests/it/popup_press_close.rs index b56d3c91..c6b0030f 100644 --- a/crates/ui-egui/tests/it/popup_press_close.rs +++ b/crates/ui-egui/tests/it/popup_press_close.rs @@ -47,9 +47,11 @@ fn restarted_rearranged() -> Harness<'static, TextureCraftApp> { first.state_mut().ui.dock = Dock::from_value(serde_json::from_str(&swapped).unwrap()); first.run_steps(STARTUP_FRAMES); first.state_mut().save(&mut storage); + let expected_layout = first.state().ui.dock.clone(); + drop(first); let restarted = app(&storage); - assert_eq!(restarted.state().ui.dock, first.state().ui.dock, "the rearranged layout comes back"); + assert_eq!(restarted.state().ui.dock, expected_layout, "the rearranged layout comes back"); restarted } @@ -103,7 +105,7 @@ fn open_tool_color(harness: &mut Harness<'_, TextureCraftApp>) { #[test] fn a_stroke_on_the_model_closes_the_tool_colour_popup_in_the_default_and_a_restored_rearranged_layout() { - for (mut harness, layout) in [(app(&MemoryStorage::default()), "default"), (restarted_rearranged(), "restored rearranged")] { + let check_stroke = |mut harness: Harness<'_, TextureCraftApp>, layout: &str| { open_tool_color(&mut harness); let history = harness.state().session.history_labels().len(); @@ -111,7 +113,10 @@ fn a_stroke_on_the_model_closes_the_tool_colour_popup_in_the_default_and_a_resto assert!(!egui::Popup::is_any_open(&harness.ctx), "{layout}: the stroke closes the popup"); assert!(harness.state().session.history_labels().len() > history, "{layout}: the stroke still paints"); - } + }; + + check_stroke(app(&MemoryStorage::default()), "default"); + check_stroke(restarted_rearranged(), "restored rearranged"); } #[test] @@ -124,6 +129,29 @@ fn an_alt_orbit_keeps_the_tool_colour_popup_open() { assert!(egui::Popup::is_any_open(&harness.ctx), "an Alt+drag orbits the camera and keeps the popup, like the colour picker"); } +#[test] +fn outside_drag_dismissal_handles_motion_batched_with_release() { + for (modifiers, stays_open) in [(Modifiers::ALT, true), (Modifiers::NONE, false)] { + let mut harness = app(&MemoryStorage::default()); + open_tool_color(&mut harness); + let origin = harness.state().viewport_rect.center(); + harness.event(Event::ModifiersChanged(modifiers)); + harness.hover_at(origin); + press(&mut harness, origin, true, modifiers); + assert!(egui::Popup::is_any_open(&harness.ctx), "the press is still a potential click"); + + let end = origin + STROKE; + harness + .input_mut() + .events + .extend([Event::PointerMoved(end), Event::PointerButton { pos: end, button: PointerButton::Primary, pressed: false, modifiers }]); + harness.run_steps(1); + + assert!(harness.ctx.input(|input| input.pointer.button_released(PointerButton::Primary) && !input.pointer.any_click())); + assert_eq!(egui::Popup::is_any_open(&harness.ctx), stays_open); + } +} + #[test] fn a_stroke_on_the_model_closes_the_symmetry_settings() { let mut harness = app(&MemoryStorage::default()); diff --git a/crates/ui-egui/tests/it/properties_min_width.rs b/crates/ui-egui/tests/it/properties_min_width.rs index f9d5fd68..93e232d2 100644 --- a/crates/ui-egui/tests/it/properties_min_width.rs +++ b/crates/ui-egui/tests/it/properties_min_width.rs @@ -110,3 +110,33 @@ fn a_layout_saved_narrower_draws_properties_at_its_minimum_width() { assert!((width - at_minimum).abs() < 0.5, "a narrow saved column opens at the minimum: header {width}, {at_minimum} at the minimum"); } + +#[test] +fn visiting_and_deleting_layers_does_not_accumulate_scroll_areas() { + let mut harness = app(); + let count = |harness: &Harness<'_, TextureCraftApp>| harness.ctx.data(|data| data.count::()); + let initial = count(&harness); + + let mut layers = Vec::new(); + for index in 0..12 { + let session = &mut harness.state_mut().session; + let layer = texturecraft_engine::execute(session, "layer.add.group", &serde_json::json!({"name": format!("Folder {index}")})).unwrap()["layer"] + .as_u64() + .unwrap(); + texturecraft_engine::execute(session, "layer.select", &serde_json::json!({"layer": layer})).unwrap(); + harness.run_steps(1); + layers.push(layer); + } + let after_visiting = count(&harness); + + let session = &mut harness.state_mut().session; + texturecraft_engine::execute(session, "layer.remove", &serde_json::json!({"layers": layers})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + + let after_removal = count(&harness); + eprintln!("scroll states after visiting {after_visiting}, after removal {after_removal}, initially {initial}"); + assert!( + after_visiting <= initial && after_removal <= initial, + "scroll areas after visiting {after_visiting}, after removal {after_removal}, initially {initial}" + ); +}