A memoized view is a unit of the shrinking row around it; the menu bar takes its titles' width (photocraft#15533)

A memoized view's content started a layout room of its own that cleared the row's shrink step, so a view in a row
took the row's whole remaining room. The in-window menu bar, a memoized view that filled X, then ate the title bar's
gap and the document title was never drawn.

A memoized view in a shrinking Row is now one of its units, as a body unit is: it reports what its content takes in
no room in the counting sweep and what it takes with every leaf at its least in the least probe, and shows at most
the width the row gave it. That width is the room of its place, so a new width runs the view and an unchanged one
replays; whether the view is a row unit is a fact of its place too. Its content's leaves fit that room.
Env::local_mut clears the cached scope key, so a sweep that edits its scope keys again.

MenuBar no longer fills: it measures every title's width, and the "…" title alone as its least, so a short row
narrows it and the last titles fold into "…".
This commit is contained in:
aiongg committed 2026-11-21 09:02:19 +00:00
1 parent 03cf32f21b
commit dfe6c94183
8 files changed
+227 -22

No files matched your search

+1
View File
@@ -12,6 +12,7 @@ pub(crate) mod ribbon;
pub(crate) mod ribbon_gallery;
mod sample;
pub(crate) mod shortcuts;
pub(crate) mod title_bar;
craft_ui::registry!();
+105
View File
@@ -0,0 +1,105 @@
//! The in-window menu bar in an app's title bar: every title shows while the bar has room for them, the document title
//! takes the rest of the bar, and only a bar too narrow for every title folds the last into "…".
use std::rc::Rc;
use craft_host::target::{Os, WindowChrome};
use craft_menu::{CommandRef, MenuBar, MenuBarUi, Row, Target, from_items};
use craft_ui::contract::{Role, Show as _, Tracked};
use craft_ui::display::Picture;
use craft_ui::runtime::env::WindowKey;
use craft_ui::shell::{AppShell, Caption, CaptionFamily, Captions, Frame, Title, TitleBar};
use craft_ui::testing::{Fixture, trial};
use egui::vec2;
const MENUS: [&str; 10] = ["File", "Edit", "Image", "Layer", "Type", "Select", "Filter", "View", "Window", "Help"];
const PREFERRED: [(&str, char); 10] = [
("File", 'F'),
("Edit", 'E'),
("Image", 'I'),
("Layer", 'L'),
("Type", 'Y'),
("Select", 'S'),
("Filter", 'T'),
("View", 'V'),
("Window", 'W'),
("Help", 'H'),
];
const DOCUMENT: &str = "Untitled-1.psd";
fn model() -> Tracked<MenuBar> {
let rows: Vec<Row> = MENUS.iter().map(|menu| Row::new(&[menu], CommandRef::new(format!("{}.first", menu.to_lowercase())), "First")).collect();
Tracked::new(from_items(&MENUS, &rows))
}
fn brand() -> egui::ColorImage {
egui::ColorImage::filled([128, 128], egui::Color32::RED)
}
/// An app window `width` points wide at `pixels_per_point` whose frame the app draws (Windows), with the title bar as
/// PhotoCraft lays it out: a brand picture, the menu bar, then the document title, and the captions at the end.
fn window(width: f32, pixels_per_point: f32) -> Fixture {
let bar = Rc::new(model());
let mut fixture = Fixture::new(move |ui| {
let bar = Rc::clone(&bar);
AppShell::new(WindowKey::main())
.title_bar(move |ui, _, _: &mut ()| {
let bar = Rc::clone(&bar);
let layout = craft_window::Layout { left: vec![], right: vec![Caption::Minimize, Caption::Maximize, Caption::Close] };
TitleBar::new().frame(Frame::Integrated(Captions { family: CaptionFamily::Windows, layout })).show_titled(
ui,
Title::new(DOCUMENT),
move |ui, _| {
Picture::new("", 7, &brand).show(ui);
MenuBarUi::new(&bar).target(Target::Windows).mnemonics(&PREFERRED).help_search(true).show(ui);
},
|_, _| {},
);
})
.body(|ui, _, _| {
ui.label("Document");
})
.show(ui, &mut ());
});
fixture.os(Os::Windows).chrome(WindowChrome::Integrated).pixels_per_point(pixels_per_point).room(vec2(width, 600.0)).settle();
fixture
}
/// The bar's title nodes by name.
fn titles(fixture: &Fixture) -> Vec<String> {
let tree = fixture.tree();
fixture.by_role(Role::MENU_ITEM).iter().filter_map(|title| tree.name_of(title.node).map(str::to_owned)).collect()
}
/// Where `text` was painted, and whether it was cut.
fn painted(fixture: &Fixture, text: &str) -> Option<(egui::Rect, bool)> {
fixture.texts().iter().find(|run| run.text == text).map(|run| (run.rect, run.elided))
}
#[trial]
fn every_menu_title_and_the_document_title_show_in_a_wide_title_bar() {
for pixels_per_point in [1.0, 1.25] {
for width in [960.0, 1280.0, 1520.0] {
let fixture = window(width, pixels_per_point);
let at = format!("{width} pt at {pixels_per_point}x");
assert_eq!(titles(&fixture), MENUS, "{at} shows every title and no \"…\"");
let (help, _) = painted(&fixture, "Help").unwrap_or_else(|| panic!("{at}: Help is painted"));
let (title, cut) = painted(&fixture, DOCUMENT).unwrap_or_else(|| panic!("{at}: the document title is painted"));
assert!(title.left() > help.right(), "{at}: the document title {title:?} lies after Help {help:?}");
assert!(!cut, "{at}: the document title is whole");
}
}
}
#[trial]
fn a_narrow_title_bar_folds_the_last_menus_into_more() {
for pixels_per_point in [1.0, 1.25] {
let mut fixture = window(400.0, pixels_per_point);
let shown = titles(&fixture);
assert_eq!(shown.last().map(String::as_str), Some("…"), "{pixels_per_point}x: {shown:?}");
assert!(!shown.iter().any(|title| title == "Help"), "{pixels_per_point}x: Help is not a title: {shown:?}");
let more = fixture.by_label("…").expect("the \"…\" title");
fixture.click(&more).settle();
assert!(fixture.by_label("Help").is_some(), "{pixels_per_point}x: Help is a row of the \"…\" menu");
}
}
+30 -3
View File
@@ -3,7 +3,7 @@
use crate::layout::{flow_region, take_cell, take_in_flow};
use crate::runtime::egui::alloc;
use crate::runtime::env::Env;
use crate::runtime::env::{Env, Shrink};
use crate::runtime::focus;
use crate::runtime::layout_memory;
use crate::runtime::lazy::{self, Decision, Key, Place};
@@ -76,8 +76,16 @@ impl Lazy {
Some(view) => sub(view.owner, ("lazy", self.key)),
None => sub(ui.scope_id(), ("lazy", self.key)),
};
let available = flow_region(ui);
let rtl = ui.layout().prefer_right_to_left();
let memo = matches!(key, Key::Memo(_));
// A memoized view is one unit of the shrinking row around it: it shows at most the width the row's measuring
// run gave it, the room its place then holds, so a new width runs it.
let shrink = Env::of(ui).shrink.filter(|_| memo);
let cap = match shrink {
Some(Shrink::Apply(row)) => crate::layout::shrink_cap(&ctx, row, id),
_ => None,
};
let available = cap.map_or_else(|| flow_region(ui), |cap| at_most(flow_region(ui), rtl, cap.width));
let sizing = ui.is_sizing_pass();
// The child is not part of its body's transcript: in a real run it counts there by its extent, whether it
// runs or not, so what scrolls into reach does not change the body's content.
@@ -114,8 +122,8 @@ impl Lazy {
pixels_per_point: ctx.pixels_per_point(),
atlas: ctx.fonts(|fonts| fonts.atlas_generation()),
env: Env::of(ui).key,
fits: Env::of(ui).row_unit(),
};
let memo = matches!(key, Key::Memo(_));
if real && memo {
crate::runtime::memory::claim_id(&ctx, id, "two memoized views share an id in one pass");
}
@@ -138,6 +146,7 @@ impl Lazy {
} else {
lazy::kept_output(&ctx, id)
};
report_unit(&ctx, shrink, id, rect.size());
#[cfg(feature = "testing")]
count_memo_run(&ctx, name, id, MemoRun::Replayed, real);
return Shown::Replayed(kept, shift);
@@ -175,6 +184,7 @@ impl Lazy {
}
if memo {
place_view(ui, rect);
report_unit(&ctx, shrink, id, rect.size());
} else {
crate::layout::close_flow_start_in(ui);
alloc::advance_past(ui, rect);
@@ -264,6 +274,23 @@ fn at_start(region: Rect, rtl: bool, size: Vec2) -> Pos2 {
Pos2::new(if rtl { region.max.x - size.x } else { region.min.x }, region.min.y)
}
/// `region` cut to `width` at most, from its start edge.
fn at_most(region: Rect, rtl: bool, width: f32) -> Rect {
let size = Vec2::new(width.min(region.width()), region.height());
Rect::from_min_size(at_start(region, rtl, size), size)
}
/// Reports the extent `size` of the memoized view `id` to the shrinking row around it: what it takes, in the row's
/// counting sweep, and its least, in the sweep that asks the row's body units for theirs. Like a body unit, it narrows
/// from what it takes in no room down to what it takes with every leaf at its least.
fn report_unit(ctx: &egui::Context, shrink: Option<Shrink>, id: egui::Id, size: Vec2) {
match shrink {
Some(Shrink::Count(row)) => crate::layout::report_shrink(ctx, row, id, size.x, size.x, None, false),
Some(Shrink::Least(row)) => crate::layout::report_least(ctx, row, id, size.x),
_ => {}
}
}
/// Places a memoized view's extent `rect` in flow in `ui`, as its run and its replay both do, and returns `rect`: in the
/// `Grid` or spread `Row` body that encloses `ui` directly the view takes the next cell at its extent, as its content
/// starts a layout room of its own and takes none; elsewhere the flow moves past `rect`.
+13 -5
View File
@@ -3,7 +3,7 @@
use super::lazy::{Lazy, Shown};
use super::memo::{MemoKey, MemoProps};
use crate::runtime::env::{Env, Scoped};
use crate::runtime::env::{Env, Scoped, Shrink};
use crate::runtime::shift::Shift;
use egui::Ui;
use std::fmt;
@@ -49,9 +49,11 @@ use std::sync::Arc;
/// - the clock, read through `frame::stepped_clock`: the view runs at the next step;
/// - commands sent to a command scope instance inside it: it runs while one waits.
///
/// Its content is a layout room of its own, as a pane's is: the flow of the body around it (a row's shrink, a column's
/// sweep, a grid's cursor) does not reach in, so the room it is given reaches it only through its place. To the body
/// around it the view is one unit, sized by its content's measure.
/// Its content is a layout room of its own, as a pane's is: the flow of the body around it (a column's sweep, a grid's
/// cursor) does not reach in, so the room it is given reaches it only through its place. To the body
/// around it the view is one unit, sized by its content's measure. In a shrinking `Row` it is a unit the row narrows
/// as it narrows a body unit: from what its content takes in no room down to what it takes with every leaf at its
/// least. The width the row gives it is the room of its place, and the leaves of its content fit that room.
///
/// What `show` returns holds layout facts only (a size, a rect, which part took the room). A replay returns the kept
/// value again, moved with the record when the room moved (`Shift`), so an event returned through it would arrive once
@@ -100,11 +102,14 @@ impl<P: MemoProps, R: Clone + PartialEq + Shift + Send + Sync + 'static> MemoVie
pub fn show(self, ui: &mut Ui) -> Option<R> {
let MemoView { lazy, mut props, show } = self;
let ctx = ui.ctx().clone();
// In the counting sweep of a shrinking row the view reports what it takes in no room, as a leaf there does.
let counting = matches!(Env::of(ui).shrink, Some(Shrink::Count(_)));
let unbounded = counting.then(|| Env::install_for(ui, Env::of(ui).derive_local(|scoped| scoped.unbounded.0 = true)));
let env = Env::of(ui);
let key = Self::key(&ctx, &env, &props, show);
let shown = lazy.run_keyed(ui, std::any::type_name::<P>(), crate::runtime::lazy::Key::Memo(key), |ui, run| {
// The content is a layout room of its own: the flow of the body around it does not reach in.
let installed = Env::install_for(ui, env.derive_local(Scoped::start_room));
let installed = Env::install_for(ui, env.derive_local(Scoped::start_view_room));
let out = show(&mut props, ui);
Env::restore(&ctx, installed);
run.output = Some(Arc::new(out.clone()));
@@ -114,6 +119,9 @@ impl<P: MemoProps, R: Clone + PartialEq + Shift + Send + Sync + 'static> MemoVie
}
out
});
if let Some(installed) = unbounded {
Env::restore(&ctx, installed);
}
match shown {
Shown::Ran(out) => Some(out),
// A replay at another place moves what the run returned with its record.
+20 -2
View File
@@ -409,6 +409,21 @@ impl Scoped {
self.offered = None;
}
/// Starts the layout room of a memoized view's content (`start_room`). A view in a shrinking `Row` is one of the
/// units the row narrows: its content's leaves fit the room the view is given (`Shrink::Fit`).
pub(crate) fn start_view_room(&mut self) {
let fits = self.row_unit();
self.start_room();
if fits {
self.shrink = Some(Shrink::Fit);
}
}
/// Whether a child shown in flow here is a unit of the shrinking `Row` around it.
pub(crate) const fn row_unit(&self) -> bool {
matches!(self.shrink, Some(Shrink::Count(_) | Shrink::Least(_) | Shrink::Apply(_)))
}
/// The key of everything a memoized view shown in this scope inherits beyond `key` (the style inputs, which its
/// place compares): the scope's state (enabled, read-only, size, glyphs, ink, surface, wheel, directions), the
/// containers around it (arena, roving group, transform, collection item and row, inside label, footer slot, line
@@ -678,9 +693,12 @@ impl Env {
Env { scoped: Arc::new(scoped) }
}
/// Reuse a sweep's scope while it is uniquely held. A captured child env keeps its snapshot.
/// Reuse a sweep's scope while it is uniquely held. A captured child env keeps its snapshot. The scope key is
/// computed again by the first view that asks after the edit.
pub(crate) fn local_mut(&mut self) -> &mut Scoped {
Arc::make_mut(&mut self.scoped)
let scoped = Arc::make_mut(&mut self.scoped);
scoped.scope_key = std::sync::OnceLock::new();
scoped
}
/// This env's container scope on top of `root`, the root env of the viewport the scope now runs in: the scale,
+6 -2
View File
@@ -166,7 +166,7 @@ pub(crate) struct Measured {
pub(crate) room: Rect,
}
/// Where a memoized view ran: it replays only at a place of the same size, layer, layout and environment, and its
/// Where a memoized view ran: it replays only at a place of the same size, layer, layout, fit and environment, and its
/// record moves with the room's position (`Place::shift_to`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Place {
@@ -182,6 +182,9 @@ pub(crate) struct Place {
/// The scope's environment (`Env::key`): its tokens (theme, density), scale, direction, language and whether the
/// window is active.
pub(crate) env: EnvKey,
/// Whether the view is a unit of the shrinking `Row` around it, so the leaves of its content fit the view's room
/// (`Scoped::start_view_room`).
pub(crate) fits: bool,
}
/// How a kept run replays at another place: the shift its record moves by, and whether the clip moved with the room.
@@ -211,7 +214,8 @@ impl Place {
&& now.layout == self.layout
&& now.pixels_per_point == self.pixels_per_point
&& now.atlas == self.atlas
&& now.env == self.env;
&& now.env == self.env
&& now.fits == self.fits;
let placeable = offset == Vec2::ZERO || (keeps_placement(rect.union(self.room), offset, now.pixels_per_point) && movable && !transformed);
if !same || !placeable {
return None;
+6 -9
View File
@@ -37,7 +37,7 @@ use crate::runtime::words::common::CommonWords;
use crate::style::{ComponentStyle, FocusLook, IconLook, StyleCx, SurfaceLook, TextLook, TypeRole};
use crate::text::TextField;
use craft_behavior::fit::{FitItem, FitKeep, fit_items};
use craft_behavior::{Arrows, Axis, Flow, Intent, Metrics, NavMove, NavShape, PartKey, PartRef, Roving, Sense};
use craft_behavior::{Arrows, Flow, Intent, Metrics, NavMove, NavShape, PartKey, PartRef, Proposal, Roving, Sense};
use craft_host::target::MenuPlacement;
use craft_keymap::mnemonic;
use craft_theme::Flags;
@@ -436,18 +436,15 @@ impl Component for MenuBar<'_> {
MenuBarStyle { metrics: Metrics::new() }
}
/// Every title's width when the room allows it; the bar fills the row, so what is left over is room for the
/// overflow.
/// Every title's width; at its least (`Proposal::Min`) the width of the "…" title alone. A row that has less room
/// than every title needs narrows the bar, and the titles that no longer fit go into "…".
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
if !Self::in_window(&cx.env) {
return Vec2::ZERO;
}
let (widths, height, _) = self.widths(cx);
Vec2::new(widths.iter().sum(), height)
}
fn fills(&self) -> Option<Axis> {
Some(Axis::X)
let (widths, height, more) = self.widths(cx);
let width = if cx.proposal == Proposal::Min { more } else { widths.iter().sum() };
Vec2::new(width, height)
}
fn sense(&self) -> Sense {
+46 -1
View File
@@ -5,7 +5,7 @@ use crate::values::kit::Scrub;
use craft_ui::buttons::Button;
use craft_ui::choice::Checkbox;
use craft_ui::contract::{Bind, MemoProps, MemoView, Props as _, Show as _, ShowContainer as _, Tracked};
use craft_ui::display::Text;
use craft_ui::display::{Elide, Text};
use craft_ui::layout_components::{Row, Stack};
use craft_ui::runtime::env::{BodyMode, RevealEdge, ShellCx, WindowKey};
use craft_ui::runtime::memory::{SaveKey, set_saved_value};
@@ -1128,3 +1128,48 @@ fn a_view_in_a_content_sized_column_lays_out_its_fill_width_row_as_outside_a_vie
assert!(outside.0.width() < outside.1.width(), "the column outside a view is as narrow as its button: {outside:?}");
assert_eq!(inside, outside, "the view's column and its sibling lie as without the view");
}
#[derive(MemoProps)]
struct Line {
line: String,
}
/// One line of text cut with an ellipsis where its room is short.
fn line(props: &mut Line, ui: &mut Ui) -> Rect {
Text::new(props.line.clone()).elide(Elide::End).show(ui).rect
}
/// A memoized view is one unit of the shrinking row around it: with room it is as wide as its content, and when a
/// sibling after it grows it narrows so the row fits, though the region it is offered stays the same. It replays while
/// the row's width for it is unchanged and runs once when that width changes.
#[trial]
fn a_view_in_a_row_narrows_with_it_and_runs_only_when_its_width_changes() {
const ROOM: Rect = Rect { min: Pos2::new(10.0, 10.0), max: Pos2::new(310.0, 50.0) };
let mut frames = Frames::new();
let frame = |frames: &mut Frames, after: &str| {
let mut rects = (Rect::NOTHING, Rect::NOTHING);
frames.frame(vec![], |ui| {
in_region(ui, ROOM, |ui| {
Row::new().fill_width().show(ui, |ui, _| {
let view = MemoView::new("line", Line { line: "A line of text long enough to be cut".to_owned() }, line).show(ui);
let after = Button::new(after.to_owned()).show(ui).response.rect;
rects = (view.unwrap_or(Rect::NOTHING), after);
});
});
});
rects
};
for _ in 0..WARM {
frame(&mut frames, "B");
}
let (wide, _) = frame(&mut frames, "B");
assert_eq!(runs_of(&frames, "Line"), [MemoRun::Replayed], "an idle frame replays the view");
let (narrow, after) = frame(&mut frames, "A much longer button label");
assert_eq!(runs_of(&frames, "Line"), [MemoRun::Ran], "a new width runs the view");
assert!(narrow.width() < wide.width(), "the view narrows: {narrow:?} from {wide:?}");
assert!(narrow.right() <= after.left() && after.right() <= ROOM.right() + 0.5, "the row fits: {narrow:?}, {after:?} in {ROOM:?}");
for _ in 0..WARM {
frame(&mut frames, "A much longer button label");
}
assert_eq!(runs_of(&frames, "Line"), [MemoRun::Replayed], "at the same width it replays again");
}