diff --git a/crates/behavior/src/item_layout.rs b/crates/behavior/src/item_layout.rs index 0332d57e8..03af94bc8 100644 --- a/crates/behavior/src/item_layout.rs +++ b/crates/behavior/src/item_layout.rs @@ -99,7 +99,8 @@ pub trait ItemLayout { /// Whether the items are as wide as they measure themselves. A layout that asks for widths places the items /// from their measured ideal and minimum widths (`set_width`), so every item must be built and measured: its - /// `visible` lists all items, and the collection does not virtualise it. + /// `visible` lists all items, and the collection does not virtualise it. Its items sit side by side, so where the + /// collection's width comes from its rows (a room that does not bound it) it is their ideal widths' sum. fn auto_widths(&self) -> bool { false } diff --git a/crates/menu/src/bar/stories.rs b/crates/menu/src/bar/stories.rs index a48970a67..b5fd9d8eb 100644 --- a/crates/menu/src/bar/stories.rs +++ b/crates/menu/src/bar/stories.rs @@ -14,6 +14,7 @@ fn model() -> MenuBar { vec![ item("file.new", "New").into(), Node::submenu("Open Recent", vec![item("file.recent.a", "notes.txt").into()]), + Node::submenu("Export", vec![item("file.export.pdf", "PDF").into()]).enabled(false), Node::Separator, item("file.revert", "Revert").enabled(false).into(), ], diff --git a/crates/menu/src/context.rs b/crates/menu/src/context.rs index cc30e4d0b..d851943c1 100644 --- a/crates/menu/src/context.rs +++ b/crates/menu/src/context.rs @@ -129,8 +129,8 @@ impl<'a> Rows<'a> { Node::Separator => { Divider::horizontal().show(ui); } - Node::Submenu { children, .. } => { - if is_dead(children) { + Node::Submenu { children, enabled, .. } => { + if !enabled || is_dead(children) { MenuItem::submenu(label).enabled(false).show(ui); } else { Menu::submenu_row(ui, label, |ui, _| self.show(ui, children)); @@ -212,7 +212,7 @@ fn checked(ui: &Ui, command: &CommandRef) -> Option { fn is_dead(nodes: &[Node]) -> bool { !nodes.iter().any(|node| match node { Node::Item(item) => item.enabled, - Node::Submenu { children, .. } => !is_dead(children), + Node::Submenu { children, enabled, .. } => *enabled && !is_dead(children), Node::Separator | Node::Standard { .. } => false, }) } diff --git a/crates/menu/src/layout.rs b/crates/menu/src/layout.rs index b4e3fe3d6..230197a2c 100644 --- a/crates/menu/src/layout.rs +++ b/crates/menu/src/layout.rs @@ -347,7 +347,9 @@ fn desktop_bar(bar: &MenuBar, target: Target, quit: Option<&'static str>, option it.label = options.text("Preferences…"); Node::Item(it) } - Node::Submenu { children, role, platforms, .. } => Node::Submenu { label: options.text("Preferences"), children, role, platforms }, + Node::Submenu { children, role, platforms, enabled, .. } => { + Node::Submenu { label: options.text("Preferences"), children, role, platforms, enabled } + } other => other, }; ensure_menu(&mut bar, MenuRole::Edit, "Edit", options).children.extend([Node::Separator, s]); @@ -373,9 +375,13 @@ fn shown_on(bar: &MenuBar, target: Target) -> MenuBar { let shown = nodes.iter().filter_map(|n| match n { Node::Item(it) if !it.platforms.contains(on) => None, Node::Submenu { platforms, .. } if !platforms.contains(on) => None, - Node::Submenu { label, children, role, platforms } => { - Some(Node::Submenu { label: label.clone(), children: keep(children, on, appkit), role: *role, platforms: *platforms }) - } + Node::Submenu { label, children, role, platforms, enabled } => Some(Node::Submenu { + label: label.clone(), + children: keep(children, on, appkit), + role: *role, + platforms: *platforms, + enabled: *enabled, + }), Node::Standard { .. } if !appkit => None, other => Some(other.clone()), }); @@ -441,11 +447,11 @@ fn settings_node(node: Node, comma_taken: Option, options: &LayoutOp give(&mut it); Node::Item(it) } - Node::Submenu { mut children, role, platforms, .. } => { + Node::Submenu { mut children, role, platforms, enabled, .. } => { if let Some(Node::Item(first)) = children.iter_mut().find(|n| matches!(n, Node::Item(i) if i.enabled)) { give(first); } - Node::Submenu { label: options.text("Settings"), children, role, platforms } + Node::Submenu { label: options.text("Settings"), children, role, platforms, enabled } } other => other, } @@ -461,12 +467,12 @@ fn appearance_node(bar: &mut MenuBar, options: &LayoutOptions) -> Vec { items.push(it); } match submenu { - Some(Node::Submenu { mut children, role, platforms, .. }) => { + Some(Node::Submenu { mut children, role, platforms, enabled, .. }) => { if !items.is_empty() { children.push(Node::Separator); children.extend(items); } - vec![Node::Submenu { label: options.text("Appearance"), children, role, platforms }] + vec![Node::Submenu { label: options.text("Appearance"), children, role, platforms, enabled }] } _ => items, } diff --git a/crates/menu/src/mac.rs b/crates/menu/src/mac.rs index 5223bfa78..8193ff2c8 100644 --- a/crates/menu/src/mac.rs +++ b/crates/menu/src/mac.rs @@ -173,7 +173,11 @@ fn lower_nodes(nodes: &[Node], targets: &mut HashMap) -> Vec native::Node::Separator, - Node::Submenu { label, children, .. } => native::Node::Submenu { label: label.clone(), children: lower_nodes(children, targets) }, + // A native submenu is disabled while it has no children: a disabled one goes over empty. + Node::Submenu { label, children, enabled, .. } => native::Node::Submenu { + label: label.clone(), + children: if *enabled { lower_nodes(children, targets) } else { Vec::new() }, + }, Node::Standard { kind, label } => native::Node::Platform { kind: match kind { Standard::Services => native::Platform::Services, diff --git a/crates/menu/src/model.rs b/crates/menu/src/model.rs index d0955032b..be9993575 100644 --- a/crates/menu/src/model.rs +++ b/crates/menu/src/model.rs @@ -150,6 +150,9 @@ pub enum Node { role: Option, /// The platforms it is shown on. platforms: Platforms, + /// Whether it can be opened. A disabled submenu shows its row greyed and never opens + /// (Open Recent with nothing to list); one whose rows are all disabled is greyed too. + enabled: bool, }, /// An item AppKit provides and runs itself (Services, Zoom, …), with the label to show. #[non_exhaustive] @@ -432,9 +435,20 @@ impl Node { Node::Standard { kind, label: label.into() } } - /// A submenu shown on every platform. + /// An enabled submenu shown on every platform. pub fn submenu(label: impl Into, children: Vec) -> Node { - Node::Submenu { label: label.into(), children, role: None, platforms: Platforms::ALL } + Node::Submenu { label: label.into(), children, role: None, platforms: Platforms::ALL, enabled: true } + } + + /// Set whether an item can be chosen or a submenu opened: + /// `Node::submenu("Open Recent", rows).enabled(!recent.is_empty())`. + pub fn enabled(mut self, on: bool) -> Node { + match &mut self { + Node::Item(it) => it.enabled = on, + Node::Submenu { enabled, .. } => *enabled = on, + Node::Separator | Node::Standard { .. } => {} + } + self } /// Give an item or a submenu a role: `Node::submenu("Theme", pages).role(ItemRole::Appearance)`. @@ -702,12 +716,12 @@ pub fn tidy(nodes: Vec) -> Vec { let mut out: Vec = Vec::with_capacity(nodes.len()); for n in nodes { let n = match n { - Node::Submenu { label, children, role, platforms } => { + Node::Submenu { label, children, role, platforms, enabled } => { let children = tidy(children); if children.is_empty() { continue; } - Node::Submenu { label, children, role, platforms } + Node::Submenu { label, children, role, platforms, enabled } } other => other, }; @@ -764,8 +778,10 @@ fn hash_nodes(nodes: &[Node], h: &mut DefaultHasher) { it.alternate.as_ref().map(|a| (a.command.key(), a.mods)).hash(h); } Node::Separator => '-'.hash(h), - Node::Submenu { label, children, role, .. } => { - ('[', label, role).hash(h); + // A native submenu is enabled only through its children (see `mac::lower_nodes`), so its + // enabled state is structure. + Node::Submenu { label, children, role, enabled, .. } => { + ('[', label, role, enabled).hash(h); hash_nodes(children, h); ']'.hash(h); } diff --git a/crates/menu/tests/it/bar.rs b/crates/menu/tests/it/bar.rs new file mode 100644 index 000000000..ae1fd26e8 --- /dev/null +++ b/crates/menu/tests/it/bar.rs @@ -0,0 +1,31 @@ +//! The in-window bar's own rules over the model. + +use craft_menu::{Item, Menu, MenuBar, MenuBarUi, Node}; +use craft_ui::testing::{Fixture, trial}; + +/// A submenu the app disables stays greyed and never opens, though its rows could be chosen +/// (Open Recent with a placeholder row while the app keeps no recent files). +#[trial] +fn a_disabled_submenu_is_greyed_and_does_not_open() { + let bar = MenuBar::new(vec![Menu::new( + "File", + vec![ + Node::submenu("Open Recent", vec![Item::new("file.recent.a", "notes.txt").into()]).enabled(false), + Node::submenu("Export", vec![Item::new("file.export.pdf", "PDF").into()]), + ], + )]); + let mut fixture = Fixture::new(move |ui| { + MenuBarUi::new(&bar).show(ui); + }); + fixture.settle(); + let Some(file) = fixture.by_label("File") else { panic!("the bar shows File") }; + fixture.click(&file).settle(); + let Some(recent) = fixture.by_label("Open Recent") else { panic!("File shows Open Recent") }; + let Some(export) = fixture.by_label("Export") else { panic!("File shows Export") }; + assert!(fixture.tree().is_disabled_key(recent.node), "the disabled submenu is greyed"); + assert!(!fixture.tree().is_disabled_key(export.node), "its enabled sibling is not"); + fixture.click(&recent).settle(); + assert!(fixture.by_label("notes.txt").is_none(), "a click does not open it"); + fixture.click(&export).settle(); + assert!(fixture.by_label("PDF").is_some(), "the enabled one opens"); +} diff --git a/crates/menu/tests/it/main.rs b/crates/menu/tests/it/main.rs index dccdaddd3..04aa3ab28 100644 --- a/crates/menu/tests/it/main.rs +++ b/crates/menu/tests/it/main.rs @@ -1,5 +1,6 @@ //! The integration binary of craft-menu: every test is a registered trial. +mod bar; mod layout; mod mnemonic; mod native; diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index b9db8f73e..144f901ba 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -225,6 +225,18 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { }; let previous = self.layout.take().or_else(|| self.previous.take()).map(|held| Arc::try_unwrap(held).unwrap_or_else(|held| (*held).clone())); let mut layout = comp.item_layout_from(previous, &*self.source, width, item, scx); + // An auto-width layout sets its items side by side: where its width comes from its rows, it takes their run at + // their ideal widths, not the widest one (a tab strip in a bar's unbounded row). + let run = (layout.auto_widths() && (asked.is_some() || !bounded) && !self.source.is_empty()) + .then(|| self.run_in(ui, id, room).min(room.x)) + .filter(|run| *run > width); + let (width, asked) = match run { + Some(run) => { + layout = comp.item_layout_from(Some(layout), &*self.source, run, item, scx); + (run, asked.map(|asked| asked.max(run))) + } + None => (width, asked), + }; if self.header.has_columns() { layout.set_columns(&self.header.columns(width)); } diff --git a/crates/ui-contract/src/contract/items/measure.rs b/crates/ui-contract/src/contract/items/measure.rs index 3fefcf765..3b2bb04ce 100644 --- a/crates/ui-contract/src/contract/items/measure.rs +++ b/crates/ui-contract/src/contract/items/measure.rs @@ -43,10 +43,10 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { rows.max(comp.ideal_width(item, scx)).min(room.x) } - /// The largest ideal size of the rows in this pass, and the widest cell each column's items reported: each row is - /// built as `content` builds it, with its column cells at the widths the header resolves with no room to share (a - /// fixed or toggle column at its own width), and measured without allocating. - fn largest_row(&mut self, comp: &C, ui: &Ui, id: Id) -> (Vec2, Vec<(craft_behavior::ColumnKey, f32)>) { + /// The largest ideal size of the rows in this pass, the sum of their ideal widths, and the widest cell each column's + /// items reported: each row is built as `content` builds it, with its column cells at the widths the header + /// resolves with no room to share (a fixed or toggle column at its own width), and measured without allocating. + fn largest_row(&mut self, comp: &C, ui: &Ui, id: Id) -> (Vec2, f32, Vec<(craft_behavior::ColumnKey, f32)>) { let ctx = ui.ctx().clone(); crate::contract::steps::measuring(&ctx, || self.largest_row_in(comp, ui, id)) } @@ -96,8 +96,9 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { if inputs.is_some() { layout_memory::begin_measure(&ctx, key); } - let (largest, cells) = self.largest_row(comp, ui, id); + let (largest, run, cells) = self.largest_row(comp, ui, id); layout_memory::emit_record(&ctx, key, layout_memory::Measured::new(room, largest)); + layout_memory::emit_record(&ctx, run_id(id), layout_memory::Measured::new(room, Vec2::new(run, 0.0))); let env = Env::of(ui); let content: Vec<(usize, craft_behavior::ColumnKey)> = self.header.content_columns().map(|(at, key)| (at, key.clone())).collect(); for (at, column) in content { @@ -126,13 +127,23 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { }) } - fn largest_row_in(&mut self, comp: &C, ui: &Ui, id: Id) -> (Vec2, Vec<(craft_behavior::ColumnKey, f32)>) { + /// The length of the rows side by side at their ideal widths, as the last measure of the largest row in the room + /// `room` found them (`largest_in`); 0 before one. + pub(super) fn run_in(&self, ui: &Ui, id: Id, room: Vec2) -> f32 { + let tolerance = measure_tolerance(crate::runtime::egui::scale::pixels_per_point(ui.ctx())); + layout_memory::measured(ui.ctx(), run_id(id)) + .filter(|found| layout_memory::Measured::serves(room.x, found.room.x, false, found.took.x, tolerance)) + .map_or(0.0, |found| found.took.x) + } + + fn largest_row_in(&mut self, comp: &C, ui: &Ui, id: Id) -> (Vec2, f32, Vec<(craft_behavior::ColumnKey, f32)>) { let ctx = ui.ctx().clone(); let env = Env::of(ui); let mut memory = MemoryStage::open_peek(&ctx, id); let cells: Vec<(craft_behavior::ColumnKey, Rect)> = self.header.columns(0.0).into_iter().map(|(key, width)| (key, Rect::from_min_size(Pos2::ZERO, Vec2::new(width, 0.0)))).collect(); let mut largest = Vec2::ZERO; + let mut run = 0.0; let mut widest: Vec<(craft_behavior::ColumnKey, f32)> = Vec::new(); for at in 0..self.source.len() { if self.source.section_stop(at) { @@ -141,6 +152,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { let row = RowMeasure { at, rect: Rect::ZERO, cells: cells.clone(), proposal: Proposal::Ideal }; let (size, cells) = self.measure_row(comp, ui, (id, env.view(), &env), &mut memory, row); largest = largest.max(size); + run += size.x; for (column, width) in cells { match widest.iter_mut().find(|(held, _)| *held == column) { Some((_, held)) => *held = held.max(width), @@ -148,7 +160,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { } } } - (largest, widest) + (largest, run, widest) } /// Builds the item of `row.at` as the collection `id` builds it, with the default row state, under `installed` @@ -217,6 +229,11 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { } } +/// Where the measure of the largest row of the collection `id` records the length of its rows side by side. +fn run_id(id: Id) -> Id { + sub(id, "run") +} + /// A row to build and measure (`measure_row`): its position, rect and column cells, and the proposal it is measured at. pub(super) struct RowMeasure { pub(super) at: usize, diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index e3c462e80..76aeaa5d5 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -10,14 +10,15 @@ use crate::buttons::IconButton; use crate::contract::{ Access, Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, ContextMenuRequest, Cx, FooterRegion, HeaderEdge, HeaderParts, HeaderRegion, ListDrag, MeasureCx, Name, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Role, - ShowCollection as _, ShowContainer as _, Sizing, WordSetCx as _, + Show as _, ShowCollection as _, ShowContainer as _, Sizing, WordSetCx as _, }; +use crate::display::{Shade, Text}; use crate::menu::{GroupItem, Menu, PanelMenu, PanelRow}; use crate::runtime::commands::{self, CommandSet as _, CommandState, Commands as _}; use crate::runtime::env::Label; use crate::runtime::focus::{self, FocusTarget}; use crate::sections::FooterBar; -use crate::style::{ComponentStyle, Corners, StyleCx, SurfaceKind}; +use crate::style::{ComponentStyle, Corners, StyleCx, SurfaceKind, TypeRole}; use crate::tabs::{Tab, TabKind, TabStrip, TornOff}; use craft_behavior::{DockSide, IconId, Metrics, PartKey, PressPhase, Sense, keyed}; use craft_theme::{ControlSize, Tokens}; @@ -465,7 +466,7 @@ impl Container for DockGroup<'_, P> { } } - /// The host's items and the tab strip, on one line. + /// The host's items and the tab strip, on one line, a tab with its panel's count; then the shown panel's caption. fn header(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>) { for (command, state) in self.command_states.drain(..) { cx.publish(command, state); @@ -515,7 +516,10 @@ impl Container for DockGroup<'_, P> { // The panel's toggle command marks its tab as it marks the panel's rail button, with the hint to say why. let resolved = panel.and_then(|panel| panel.command.clone()).map(|command| commands::resolve(&ctx, command)); let marked = resolved.as_ref().is_some_and(|resolved| IconButton::shows_marker(resolved)); - let tab = Tab::new(title).closable(panel.is_some_and(closes)).marked(marked); + let mut tab = Tab::new(title).closable(panel.is_some_and(closes)).marked(marked); + if let Some(count) = panel.and_then(|panel| panel.count) { + tab = tab.detail(env.format().integer(u64::try_from(count).unwrap_or(u64::MAX))); + } match resolved.and_then(|resolved| resolved.hint).filter(|_| marked) { Some(hint) => tab.tooltip(hint), None => tab, @@ -550,6 +554,9 @@ impl Container for DockGroup<'_, P> { reported.item = shown.inner.flatten().or(reported.item); } }); + if let Some(caption) = panels.iter().find(|panel| panel.key == active).and_then(|panel| panel.caption.clone()) { + Text::new(caption).role(TypeRole::Caption).shade(Shade::Faint).show(ui); + } self.extra = extra; } } diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index e67f94a75..485e55c32 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -113,12 +113,30 @@ pub struct PanelTitle { pub closable: bool, /// The panel's toggle command: the tab resolves it for its marker and its hint. pub command: Option, + /// The number the tab shows after the title ([`PanelSpec::count`]). + pub count: Option, + /// The line under the header row while the panel is shown ([`PanelSpec::caption`]). + pub caption: Option