diff --git a/crates/ui-canvas/src/canvas_controls/task_bar.rs b/crates/ui-canvas/src/canvas_controls/task_bar.rs index 610125e491..84c360686b 100644 --- a/crates/ui-canvas/src/canvas_controls/task_bar.rs +++ b/crates/ui-canvas/src/canvas_controls/task_bar.rs @@ -76,7 +76,8 @@ impl TaskBarPlace { /// - Area: the bar shows inside `area` (the canvas rect): a move stays inside it, and a stored place outside it comes /// back inside, its left and top edges winning where the bar does not fit. An anchor that leaves no room on either /// side (a crop frame larger than the view) has the bar over it, on its side's edge of the area, with all its -/// members. Its members continue on a new line when the area is too narrow for them. +/// members. In an area too narrow for its members, its selects narrow to fit one line first, and the members +/// continue on a new line only when they do not fit it even at their least. /// - Menu: Hide bar reports `hide`; Reset bar position clears the place, so the bar follows its anchor again; Pin bar /// position keeps it where it shows and, picked again, lets it follow its anchor from where it shows. /// - `place` is the caller's value (`Bind::bound`): the bar reads it before it shows and writes the pass's change diff --git a/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs b/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs index 23a1ca6531..40abee2034 100644 --- a/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs +++ b/crates/ui-canvas/tests/it/canvas_controls/task_bar.rs @@ -605,3 +605,51 @@ fn a_bar_clear_of_the_handles_hangs_farther_below_its_anchor() { assert!(default > 0.0, "the bar hangs below its anchor: {default}"); assert!(clear > default + 2.0 * SLACK, "the bar clear of the handles hangs farther below: {clear} against {default}"); } + +/// What a task bar of three buttons and a select showing its short entry beside a long one shows in an area cut to +/// `width` (the whole canvas when `None`): the bar's rect, then the rects of the first button, the select and the More +/// button. +fn type_bar(width: Option) -> (Rect, [Rect; 3]) { + use craft_ui::contract::{Entry, Props as _}; + use craft_ui::pickers::Select; + let scene = scene(); + let shared = Rc::clone(&scene); + let mut fixture = Fixture::new(move |ui| { + let _ = on_canvas(ui, |ui, area, view| { + let mut held = shared.borrow_mut(); + let scene = &mut *held; + let area = width.map_or(area, |width| Rect::from_min_size(area.min, Vec2::new(width, area.height()))); + scene.bounds = Rect::from_points(&scene.anchor.iter().map(|point| view.to_screen(*point)).collect::>()); + scene.area = area; + let entries = [Entry::new(0u8, "Source Sans 3"), Entry::new(1, "Source Sans 3 Semibold Condensed")]; + let shown = TaskBar::new("Type", &scene.anchor, Bind::bound(&mut scene.place)).show(ui, area, |ui, _| { + let _ = Button::new("Create Outlines").show(ui); + let _ = Button::new("Convert To Area Type").show(ui); + let _ = Button::new("Duplicate").show(ui); + let _ = Select::new("Font family", Bind::given(0u8), &entries).label("Font family").show(ui); + }); + scene.rect = shown.output.rect; + shown.output + }); + }); + fixture.room(Vec2::new(1120.0, 720.0)); + fixture.settle(); + let rect = |label: &str| fixture.by_label(label).unwrap_or_else(|| panic!("the bar shows {label}")).rect; + let members = [rect("Create Outlines"), rect("Font family"), rect("More options")]; + (seen(&scene).rect, members) +} + +/// A task bar a little too wide for its area narrows its select to fit one line before any member goes on a new line: +/// More stays on the members' line, and the bar is no wider than the area. +#[trial] +fn a_task_bar_a_little_too_wide_narrows_its_select_and_keeps_more_on_its_line() { + let (natural, [_, select, _]) = type_bar(None); + let width = natural.width() - select.width() / 4.0; + let (bar, [first, narrowed, more]) = type_bar(Some(width)); + assert!(bar.width() <= width + SLACK, "the bar {bar:?} fits the area {width} wide"); + for (name, member) in [("the select", narrowed), ("More", more)] { + assert!((member.center().y - first.center().y).abs() < SLACK, "{name} {member:?} sits on the first member's line {first:?}"); + } + assert!(narrowed.width() + SLACK < select.width(), "the select narrows: {narrowed:?} against {select:?}"); + assert!(more.max.x <= bar.max.x + SLACK, "More {more:?} lies inside the bar {bar:?}"); +} diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index f090c7586f..a98971add0 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -118,7 +118,9 @@ impl BodyLayout { } } - /// A `Row` that wraps; any other layout is unchanged. + /// A `Row` that wraps; any other layout is unchanged. In a bar, a row placed from its start that is too long for one + /// line first narrows its selects and elidable text to fit it, from the end, as a bar's row that does not wrap does, + /// and continues on a new line only when they do not fit it even at their least. pub fn wrap(self, on: bool) -> Self { match self { BodyLayout::Row { align, .. } => BodyLayout::Row { wrap: on, align }, @@ -980,50 +982,7 @@ fn run_shrinking(ui: &mut Ui, place: &Env, id: Id, mut body: impl FnMut(&mut let room = shrink_room(ui, place); let order = if place.values.get::().0 { ShrinkOrder::FromEnd } else { ShrinkOrder::Even }; let (drops, gap) = (view_room(ui, place, Axis::X).is_none(), ui.spacing().item_spacing.x); - // Records the width each unit gets, and returns whether one took another width in the first sweep. The levelled - // units take their levels first, in the room the continuous units leave at their least; the continuous units then - // narrow by their own rule with the levelled units' widths held. A row without levelled units holds nothing more. - let settle = |leaves: &[Reported], fixed: f32| { - let (levelled, continuous): (Vec<&Reported>, Vec<&Reported>) = leaves.iter().partition(|leaf| !leaf.levels.is_empty()); - let units: Vec = continuous.iter().map(|leaf| leaf.widths).collect(); - let whole: Vec = continuous.iter().map(|leaf| leaf.whole).collect(); - let first: Vec = continuous.iter().map(|leaf| leaf.cut_first).collect(); - let ranks: Vec> = continuous.iter().map(|leaf| leaf.rank).collect(); - let level_widths: Vec> = levelled.iter().map(|leaf| leaf.levels.clone()).collect(); - let levels = if room.is_finite() { - plan_levels(&level_widths, room - fixed - units.iter().map(|unit| unit.least).sum::()) - } else { - vec![0; levelled.len()] - }; - let width_at = |leaf: &Reported, level: usize| leaf.levels.get(level).copied().unwrap_or_default(); - let held: f32 = levelled.iter().zip(&levels).map(|(leaf, level)| width_at(leaf, *level)).sum(); - // The ranked units give up `rank_short` of the row's ideal width; a row offered no bound (a content-sized row's - // measuring run) still drops them for it. - let ideal = fixed + held + units.iter().map(|unit| unit.ideal).sum::(); - let rank_room = rank_short.map_or(f32::INFINITY, |short| ideal - short); - let widths = if room.is_finite() || rank_room.is_finite() { - shrink_or_drop(&units, &whole, (&first, &ranks), (fixed + held, gap), (room, rank_room), order, drops) - } else { - units.iter().map(|unit| ShrinkCap { width: unit.ideal, dropped: false, narrowed: false }).collect() - }; - // A levelled unit took no place of its own content in the first sweep (it measured each level apart), so the - // records its content's run leaves for the real run come from a sweep at the levels given. - let mut again = !levelled.is_empty(); - for (leaf, cap) in continuous.iter().zip(widths) { - let measured = layout_memory::Measured::new(Vec2::new(room, 0.0), Vec2::new(cap.width, 0.0)); - let given = layout_memory::ShrinkGiven { dropped: cap.dropped, narrowed: cap.narrowed }; - layout_memory::emit_shrink(&ctx, shrink_key(id, leaf.leaf), measured, given); - // Half a point: less than a pixel shows at any scale the box runs. - again |= (leaf.took - cap.width).abs() >= 0.5; - } - for (leaf, level) in levelled.iter().zip(levels) { - // The level travels as the record's height (`level_of`). - let measured = layout_memory::Measured::new(Vec2::new(room, 0.0), Vec2::new(width_at(leaf, level), level as f32)); - let given = layout_memory::ShrinkGiven { dropped: false, narrowed: level > 0 }; - layout_memory::emit_shrink(&ctx, shrink_key(id, leaf.leaf), measured, given); - } - again - }; + let settle = |leaves: &[Reported], fixed: f32| settle_shrink(&ctx, id, (leaves, fixed), (room, gap), (rank_short, order, drops)); // A row that is the first control under a label holds every control the label's placement must leave room for. let labelled = scope::label_awaiting_min(&ctx); let (inner, rect, mut leaves, fixed, fills, probe, again) = crate::contract::keeping_ids(&ctx, || { @@ -1078,6 +1037,59 @@ fn run_shrinking(ui: &mut Ui, place: &Env, id: Id, mut body: impl FnMut(&mut } } +/// Records the width each unit of the row `id` gets from the shrink step, for `leaves` with `fixed` (the row's other +/// children and gaps) in `room` with `gap` between units, and returns whether one took another width in the first +/// sweep. The levelled units take their levels first, in the room the continuous units leave at their least; the +/// continuous units then narrow by their own rule with the levelled units' widths held. A row without levelled units +/// holds nothing more. `rank_short`, `order` and `drops` are as `run_shrinking` gives them. +fn settle_shrink( + ctx: &egui::Context, + id: Id, + (leaves, fixed): (&[Reported], f32), + (room, gap): (f32, f32), + (rank_short, order, drops): (Option, ShrinkOrder, bool), +) -> bool { + let (levelled, continuous): (Vec<&Reported>, Vec<&Reported>) = leaves.iter().partition(|leaf| !leaf.levels.is_empty()); + let units: Vec = continuous.iter().map(|leaf| leaf.widths).collect(); + let whole: Vec = continuous.iter().map(|leaf| leaf.whole).collect(); + let first: Vec = continuous.iter().map(|leaf| leaf.cut_first).collect(); + let ranks: Vec> = continuous.iter().map(|leaf| leaf.rank).collect(); + let level_widths: Vec> = levelled.iter().map(|leaf| leaf.levels.clone()).collect(); + let levels = if room.is_finite() { + plan_levels(&level_widths, room - fixed - units.iter().map(|unit| unit.least).sum::()) + } else { + vec![0; levelled.len()] + }; + let width_at = |leaf: &Reported, level: usize| leaf.levels.get(level).copied().unwrap_or_default(); + let held: f32 = levelled.iter().zip(&levels).map(|(leaf, level)| width_at(leaf, *level)).sum(); + // The ranked units give up `rank_short` of the row's ideal width; a row offered no bound (a content-sized row's + // measuring run) still drops them for it. + let ideal = fixed + held + units.iter().map(|unit| unit.ideal).sum::(); + let rank_room = rank_short.map_or(f32::INFINITY, |short| ideal - short); + let widths = if room.is_finite() || rank_room.is_finite() { + shrink_or_drop(&units, &whole, (&first, &ranks), (fixed + held, gap), (room, rank_room), order, drops) + } else { + units.iter().map(|unit| ShrinkCap { width: unit.ideal, dropped: false, narrowed: false }).collect() + }; + // A levelled unit took no place of its own content in the first sweep (it measured each level apart), so the + // records its content's run leaves for the real run come from a sweep at the levels given. + let mut again = !levelled.is_empty(); + for (leaf, cap) in continuous.iter().zip(widths) { + let measured = layout_memory::Measured::new(Vec2::new(room, 0.0), Vec2::new(cap.width, 0.0)); + let given = layout_memory::ShrinkGiven { dropped: cap.dropped, narrowed: cap.narrowed }; + layout_memory::emit_shrink(ctx, shrink_key(id, leaf.leaf), measured, given); + // Half a point: less than a pixel shows at any scale the box runs. + again |= (leaf.took - cap.width).abs() >= 0.5; + } + for (leaf, level) in levelled.iter().zip(levels) { + // The level travels as the record's height (`level_of`). + let measured = layout_memory::Measured::new(Vec2::new(room, 0.0), Vec2::new(width_at(leaf, level), level as f32)); + let given = layout_memory::ShrinkGiven { dropped: false, narrowed: level > 0 }; + layout_memory::emit_shrink(ctx, shrink_key(id, leaf.leaf), measured, given); + } + again +} + /// In a body that scrolls along `axis`, what its view shows along it from the start of the rest of `ui`'s layout: along /// x the width a row there shrinks to fit and a child that fills its width fills, along y the height the children that /// fill a `Stack` there share. `None` outside such a body. @@ -2212,6 +2224,8 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign inner }) .0 + } else if lines && align == RowAlign::Start && row.values.get::().0 { + run_wrap_start(ui, &row, (id, sizing, rtl), &mut body) } else if wrap { body(ui) } else { @@ -2260,6 +2274,70 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign (inner, (align != RowAlign::Start).then(|| took.width())) } +/// Runs `body`, the children of the wrapping `Row` body `id` of a bar placed from its start, in `ui`, the block they +/// wrap in, under `row`. Children too wide for one line first narrow to fit it by the shrink step of an unwrapped bar +/// row (`settle_shrink`, from the end); they go on new lines only when they do not fit it even at their least. A measuring run decides +/// which from a counting sweep it takes back (`narrows_to_line`) and records the widths, and the real run reads its +/// decision. Either way the children run in a child of `ui` with its wrapping layout, so they keep their ids and +/// their lines' alignment. +fn run_wrap_start(ui: &mut Ui, row: &Env, (id, sizing, rtl): (Id, bool, bool), body: &mut impl FnMut(&mut Ui) -> R) -> R { + let ctx = ui.ctx().clone(); + let key = sub(id, "narrows"); + let room = ui.available_rect_before_wrap().width(); + let narrows = if sizing { + let counted = if room.is_finite() { narrows_to_line(ui, row, id, (child::row_layout(rtl, false), room), body) } else { None }; + if let Some((leaves, fixed)) = &counted { + settle_shrink(&ctx, id, (leaves, *fixed), (room, ui.spacing().item_spacing.x), (None, ShrinkOrder::FromEnd, false)); + } + found(&ctx, true, key, Vec2::new(room, 0.0), Vec2::new(if counted.is_some() { 1.0 } else { 0.0 }, 0.0)); + counted.is_some() + } else { + this_pass(&ctx, false, key).is_some_and(|took| took.x > 0.5) + }; + // In a child with the block's layout, as the counting sweep runs in one: the children take the same ids in the + // counting sweep and here, whether they narrow or wrap. + let shown = if narrows { row.derive_local(|scoped| scoped.shrink = Some(Shrink::Apply(id))) } else { row.clone() }; + let layout = *ui.layout(); + child::block(ui, None, layout, |ui| Env::run_in(ui, shown, &mut *body)).0 +} + +/// The units of the row `id`, counted in a sweep of `body` laid out on one `line` and taken back, with the width its +/// other children and gaps take, when they are too wide for `room` at their natural widths and fit it at their least; +/// `None` otherwise. A body among them counts at its natural width, and no unit carries a rank. +fn narrows_to_line( + ui: &mut Ui, + row: &Env, + id: Id, + (line, room): (egui::Layout, f32), + body: &mut impl FnMut(&mut Ui) -> R, +) -> Option<(Vec, f32)> { + let ctx = ui.ctx().clone(); + let count = row.derive_local(|scoped| { + scoped.rank_short = None; + scoped.shrink = Some(Shrink::Count(id)); + }); + let (counted, _) = crate::contract::draft( + &ctx, + || { + pass_state::with::(&ctx, |reports| reports.0.insert(id, Vec::new())); + let mut sweep = laid_out_child(ui, line); + let _ = Env::run_in(&mut sweep, count.clone(), &mut *body); + let mut leaves = pass_state::with::(&ctx, |reports| reports.0.remove(&id)).unwrap_or_default(); + // A wrapping row keeps every member: none leaves by rank, which would bring it back on a new line once + // the row is too narrow to narrow. + for leaf in &mut leaves { + leaf.rank = None; + } + let fixed = sweep.min_rect().width() - leaves.iter().map(|leaf| leaf.took).sum::(); + let short = |width: fn(&Reported) -> f32| fixed + leaves.iter().map(width).sum::() - room; + // Half a point: less than a pixel shows at any scale the box runs. + (short(|leaf| leaf.widths.ideal) >= 0.5 && short(|leaf| leaf.widths.least) < 0.5).then_some((leaves, fixed)) + }, + |_| false, + ); + counted +} + /// The line the children of the wrapping `SpaceBetween` row `id` sit on when they `took` one line, with the line /// `shared` it shares with its container's inline header or end region: how far below the row's top the line's centre /// lies, and the row's height once every child sits on it, as `record_line` finds an unwrapped row's. `None` when the diff --git a/crates/ui-widgets/src/bars/bar.rs b/crates/ui-widgets/src/bars/bar.rs index 0762decc6c..735a6341ac 100644 --- a/crates/ui-widgets/src/bars/bar.rs +++ b/crates/ui-widgets/src/bars/bar.rs @@ -153,7 +153,9 @@ impl<'a> Bar<'a> { } /// Lays out the members as a row that wraps instead of scrolling under an overlay bar: no horizontal scroll, no row - /// cap; a member wider than the bar narrows and elides by the shared rules. + /// cap. A row too long for the bar first narrows its selects and elidable text to fit one line, the last first, and + /// continues on a new line only when they do not fit it even at their least; a member wider than the bar narrows + /// and elides by the shared rules. #[must_use] pub fn wrap(mut self) -> Self { self.props.layout = self.props.layout.clone().wrap(true); diff --git a/crates/ui-widgets/tests/it/bars/bar.rs b/crates/ui-widgets/tests/it/bars/bar.rs index 30fdec56e7..7f58862a02 100644 --- a/crates/ui-widgets/tests/it/bars/bar.rs +++ b/crates/ui-widgets/tests/it/bars/bar.rs @@ -343,6 +343,69 @@ fn a_wrapping_bar_continues_on_a_new_line() { assert!(select.max.x <= 120.0 + SLACK, "a member wider than the bar kept its width: {select:?}"); } +/// The rects of two buttons, a select showing its short entry beside a long one and a last button in a tool bar +/// `width` wide that wraps. +fn select_among_tools(width: f32) -> [Rect; 4] { + let seen = Rc::new(Cell::new([Rect::NOTHING; 4])); + let out = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let entries = [Entry::new(0u8, "Current and Below, No Adjustments"), Entry::new(1, "All Layers")]; + Bar::new("Tools", BarKind::Tool).wrap().show(ui, |ui, _| { + let first = Button::new("Create Outlines").show(ui).rect; + let second = Button::new("Duplicate").show(ui).rect; + let select = Select::new("Sample", Bind::given(1u8), &entries).show(ui).response.rect; + let last = IconButton::new(IconId::new("more")).label("More").show(ui).rect; + out.set([first, second, select, last]); + }); + }); + fixture.room(Vec2::new(width, 300.0)).settle(); + seen.get() +} + +#[trial] +fn a_wrapping_bar_narrows_its_select_to_one_line_before_it_wraps() { + let natural = select_among_tools(2000.0); + let line = natural[0].center().y; + assert!(natural.iter().all(|rect| (rect.center().y - line).abs() < SLACK), "a wide bar holds its members on one line: {natural:?}"); + let width = natural[3].max.x - natural[2].width() / 4.0; + let narrowed = select_among_tools(width); + for rect in narrowed { + assert!((rect.center().y - narrowed[0].center().y).abs() < SLACK, "{rect:?} went on a new line in a bar {width} wide: {narrowed:?}"); + assert!(rect.max.x <= width + SLACK, "{rect:?} lies past the bar's edge at {width}"); + } + assert!(narrowed[2].width() + SLACK < natural[2].width(), "the select narrows: {:?} against {:?}", narrowed[2], natural[2]); + let wrapped = select_among_tools(natural[1].max.x); + assert!(wrapped[3].center().y > wrapped[0].center().y + SLACK, "a bar too narrow for its members at their least wraps: {wrapped:?}"); +} + +/// Whether a ranked row's button shows in a tool bar `width` wide that wraps, beside a select it can narrow, with the +/// select's rect. +fn ranked_beside_select(width: f32) -> (bool, Rect) { + let seen = Rc::new(Cell::new(Rect::NOTHING)); + let out = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let entries = [Entry::new(0u8, "Current and Below, No Adjustments"), Entry::new(1, "All Layers")]; + Bar::new("Tools", BarKind::Tool).wrap().show(ui, |ui, _| { + Row::new().fit_rank(1).show(ui, |ui, _| { + Button::new("Low").show(ui); + }); + out.set(Select::new("Sample", Bind::given(1u8), &entries).show(ui).response.rect); + }); + }); + fixture.room(Vec2::new(width, 300.0)).settle(); + (fixture.by_label("Low").is_some(), seen.get()) +} + +#[trial] +fn a_wrapping_bar_keeps_a_ranked_member_while_its_select_narrows() { + let (shown, select) = ranked_beside_select(2000.0); + assert!(shown, "a wide bar shows the ranked button"); + let width = select.max.x - select.width() / 4.0; + let (shown, narrowed) = ranked_beside_select(width); + assert!(narrowed.width() + SLACK < select.width(), "the select narrows: {narrowed:?} against {select:?}"); + assert!(shown, "the ranked button left a wrapping bar {width} wide"); +} + /// What a bar of three rows, ranked 1 and 2 and unranked, `width` wide shows: whether each of their buttons is there. fn ranked(width: f32) -> [bool; 3] { let mut fixture = Fixture::new(|ui| {