diff --git a/crates/draw/src/ui/transform/session_overlay.rs b/crates/draw/src/ui/transform/session_overlay.rs index de65d190e..f5414abac 100644 --- a/crates/draw/src/ui/transform/session_overlay.rs +++ b/crates/draw/src/ui/transform/session_overlay.rs @@ -160,6 +160,7 @@ impl<'a, W: TransformWarp> TransformOverlay<'a, W> { .reference_point(session.reference_point()) .reach(self.reach) .rotate_zone(self.rotate_zone) + .own_context_menu(self.reach == TransformReach::Box) .id_source(self.id); if let Some(mods) = self.mods { tbox = tbox.mods(mods); diff --git a/crates/draw/src/ui/transform/transform_box.rs b/crates/draw/src/ui/transform/transform_box.rs index c5605959c..837fe4dee 100644 --- a/crates/draw/src/ui/transform/transform_box.rs +++ b/crates/draw/src/ui/transform/transform_box.rs @@ -509,6 +509,10 @@ pub struct TransformBox<'a> { /// and an open drag's Escape still cancels the drag. #[prop] session_commit: bool, + /// The caller hangs a context menu of its own on the box (`Menu::context` over its response): every part takes the + /// right click, so it does not reach the tool under the box. + #[prop] + own_context_menu: bool, /// Whether this pass holds a drag of the reference point, so the hidden point is drawn while it moves. pivot_held: bool, /// Whether this pass holds a drag that began, so a live line's box shows as it scales. @@ -538,6 +542,7 @@ impl<'a> TransformBox<'a> { reach: TransformReach::Box, color: None, session_commit: true, + own_context_menu: false, pivot_held: false, dragging: false, report: Report::default(), @@ -1098,11 +1103,11 @@ fn paint_frame(draw: &Draw<'_>, style: &TransformBoxStyle, line: StrokeColor, co /// The move reach outside the box whose corners are `quad` on the screen: every point within `points` of its border, /// as a strip along each side and a round sector outside each corner (PhotoCraft's type move reach measures the /// distance to the nearest side, pc-prod-e76 type_transform.rs:156-196). -fn declare_ring(cx: &mut PartsCx<'_, TransformBox<'_>>, quad: &[Pos2; 4], points: f32) { +fn declare_ring(cx: &mut PartsCx<'_, TransformBox<'_>>, quad: &[Pos2; 4], points: f32, context: Sense) { let outward = outward_normals(quad); let mut declare = |part: usize, shape: Vec| { cx.part(MOVE_RING.at(part as u64), HitShape::Polygon(shape)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Inside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Inside) | context) .priority(HitPriority::new(HitLevel::Body, RING_SUB)) .pointer_only(MOVE_BY_KEY); }; @@ -1250,9 +1255,10 @@ impl Component for TransformBox<'_> { let style = cx.style; let screen = on_screen(&space.view, &state); let quad: [Pos2; 4] = screen.quad.map(pos); + let context = if self.own_context_menu { Sense::CONTEXT_CLICK } else { Sense::empty() }; if self.move_only().is_some() { if let Some(points) = self.ring_reach() { - declare_ring(cx, &quad, points); + declare_ring(cx, &quad, points, context); } return; } @@ -1279,13 +1285,13 @@ impl Component for TransformBox<'_> { ) } }; - cx.part(BOX.at(part.index()), shape).sense(sense | slop_sense(part)).priority(priority).focus_shape(focus).focusable(); + cx.part(BOX.at(part.index()), shape).sense(sense | slop_sense(part) | context).priority(priority).focus_shape(focus).focusable(); any = true; } if let Some(line) = self.line { for (end, at) in line.free_ends() { cx.part(LINE_END.at(end.index()), HitShape::circle(space.view.to_screen(at), style.handle_reach)) - .sense(Sense::DRAG | Sense::CLICK) + .sense(Sense::DRAG | Sense::CLICK | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(LINE_END_BY_KEY); } @@ -1299,7 +1305,7 @@ impl Component for TransformBox<'_> { let band = if self.rules.edge_band > 0.0 { edge_band(&quad, side, self.rules.edge_band) } else { side_band(&quad, side, style.side_band) }; cx.part(EDGE.at(u64::from(k)), band) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Edge(k))) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Edge(k)) | context) .priority(HitPriority::new(HitLevel::Handle, EDGE_SUB)) .pointer_only(EDGE_BY_KEY); } @@ -1309,7 +1315,7 @@ impl Component for TransformBox<'_> { for (end, side) in [(0u64, corner), (1, (corner + 3) % 4)] { let Some(reach) = corner_reach(&quad, side, corner, style.side_band) else { continue }; cx.part(CORNER_REACH.at(2 * u64::from(k) + end), reach) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Corner(k))) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Corner(k)) | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(CORNER_BY_KEY); } @@ -1317,7 +1323,7 @@ impl Component for TransformBox<'_> { if self.declares_centre() { let centre = quad.iter().fold(Vec2::ZERO, |sum, corner| sum + corner.to_vec2()) / 4.0; cx.part(CENTRE.at(0), HitShape::circle(centre.to_pos2(), style.hit)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Inside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Inside) | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(MOVE_BY_KEY); } @@ -1328,7 +1334,7 @@ impl Component for TransformBox<'_> { RotateZone::Outside | RotateZone::Border { .. } if self.rules.allows(BoxPart::Outside) => { for (corner, region) in outside_regions(&quad, rect).into_iter().enumerate() { cx.part(OUTSIDE.at(corner as u64), HitShape::Polygon(region)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside) | context) .priority(HitPriority::new(HitLevel::Background, 0)) .pointer_only(ROTATE_BY_KEY); } @@ -1336,7 +1342,7 @@ impl Component for TransformBox<'_> { RotateZone::Band if self.rules.allows(BoxPart::Outside) => { for (corner, ring) in band_rings(&screen, style).into_iter().enumerate() { cx.part(OUTSIDE.at(corner as u64), HitShape::Polygon(ring)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside) | context) .priority(HitPriority::new(HitLevel::Body, 0)) .pointer_only(ROTATE_BY_KEY); } @@ -1347,7 +1353,7 @@ impl Component for TransformBox<'_> { if self.has_knob() { let (knob, _) = knob_at(&quad, rect, style); cx.part(KNOB.at(0), HitShape::circle(knob, style.handle_reach)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside) | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(ROTATE_BY_KEY); } @@ -1355,7 +1361,7 @@ impl Component for TransformBox<'_> { RotateZone::Handle if self.rules.allows(BoxPart::Outside) => { let (_, knob) = rotate_handle(&quad, style.rotate_stem); cx.part(ROTATE_HANDLE.at(0), HitShape::circle(knob, style.handle_reach)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside) | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(ROTATE_BY_KEY); } diff --git a/crates/draw/tests/it/transform_box.rs b/crates/draw/tests/it/transform_box.rs index 0fbf30cc6..e8b32bb82 100644 --- a/crates/draw/tests/it/transform_box.rs +++ b/crates/draw/tests/it/transform_box.rs @@ -1070,20 +1070,28 @@ fn a_jittery_double_click_inside_applies_with_no_move_committed() { assert_eq!(h.host.borrow().applied, 1, "the double click applies"); } -/// A secondary click on the session's box opens the mode menu (its rows are on the page); with the menu closed again, a -/// secondary click away from the box opens none. +/// A secondary click on the session's box opens the mode menu (its rows are on the page) and is the box's alone: the +/// tool host under it asks for no menu of its own. With the menu closed again, a secondary click away from the box +/// opens none. #[trial] fn a_secondary_click_on_the_box_opens_the_mode_menu() { + use craft_draw::ui::transform::TransformTool; + use craft_ui::canvas::{ToolHost, tool_pass}; let session = TransformSession::<()>::new(RECT); let settings = TransformSettings::default(); let view = Rc::new(RefCell::new(CanvasView::new(egui::Rect::NOTHING, Point::ZERO, 1.0))); - let shown_view = Rc::clone(&view); + let host_asked = Rc::new(Cell::new(false)); + let (shown_view, asked) = (Rc::clone(&view), Rc::clone(&host_asked)); let mut fixture = Fixture::new(move |ui| { let room = ui.available_rect_before_wrap(); let at = CanvasView::new(room, Point::new(f64::from(room.width()) / 2.0, f64::from(room.height()) / 2.0), 1.0); *shown_view.borrow_mut() = at; Canvas::new("Document").view(at).show(ui, |ui, body| { - TransformOverlay::new("Free Transform", &session, &settings).show_at(ui, body.rect); + let shown = TransformOverlay::new("Free Transform", &session, &settings).show_at(ui, body.rect); + if let Some(pass) = tool_pass(&body.env) { + let mut tool = TransformTool::new(&session, shown.snapped.clone()); + asked.set(asked.get() || ToolHost::new().run(ui, &pass, &mut tool).context.is_some()); + } }); }); fixture.settle(); @@ -1098,8 +1106,10 @@ fn a_secondary_click_on_the_box_opens_the_mode_menu() { right_click(&mut fixture, screen(Point::new(1000.0, 1000.0))); assert!(fixture.by_label("Distort").is_none(), "a secondary click away from the box opens no mode menu"); + host_asked.set(false); right_click(&mut fixture, screen(Point::new(200.0, 150.0))); assert!(fixture.by_label("Distort").is_some(), "a secondary click on the box opens the mode menu"); + assert!(!host_asked.get(), "the tool host under the box asks for no menu"); } /// A drag from inside snaps the moved box's edges, not the pointer: the right edge lands on the guide at 310 while the diff --git a/crates/font-manager/src/picker.rs b/crates/font-manager/src/picker.rs index 887faf69c..e25ff1766 100644 --- a/crates/font-manager/src/picker.rs +++ b/crates/font-manager/src/picker.rs @@ -19,7 +19,7 @@ use craft_host::Section; use craft_theme::variant::Tone; use craft_ui::buttons::{ControlPlace, IconButton}; use craft_ui::contract::{ - Access, Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, + Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, Styled as _, WordSetCx as _, step_stop, }; use craft_ui::controls::disclosure::{DisclosureGlyph, DropdownArrow}; @@ -59,8 +59,6 @@ craft_ui::words! { /// The name of the preview banner, with `{family}` for the family it shows. preview_of: template "fontPicker.previewOf" = "Font preview: {family}"; no_match: "fontPicker.noMatch" = "No fonts match"; - /// The family field's label when the selection has several families. - mixed: "fontPicker.mixed" = "Mixed"; /// The name of a row's star, with `{row}` for the row's label. favorite: template "fontPicker.favorite" = "Favorite {row}"; list: "fontPicker.list" = "Fonts"; @@ -934,10 +932,8 @@ impl Component for FontPicker<'_> { } let mut options = TextOptions::new(); options.select_on_focus = true; + // A selection of several families shows an empty field, as the reference applications do. options.mixed = cx.value().is_none(); - if options.mixed { - options.placeholder = Some(cx.words::().mixed.clone()); - } if !self.catalog.is_ready() { // The first scan runs on a background thread; the field asks again until it ends. self.catalog.scan_in_background(); @@ -954,12 +950,6 @@ impl Component for FontPicker<'_> { Some(self.family.reborrow()) } - fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) { - if cx.value().is_none() && cx.text(&text_key()).is_none_or(|text| text.draft.as_deref().is_none_or(str::is_empty)) { - access.value(cx.words::().mixed.as_str()); - } - } - /// A changed draft filters the list: it opens on the matches, and closes when the draft ended (committed, /// cancelled or replaced by a pick). A preview that the list closed on without a pick is cancelled. While the /// list is closed, the arrows and the wheel step through the host rows and the families. diff --git a/crates/font-manager/tests/it/picker.rs b/crates/font-manager/tests/it/picker.rs index 5b1f60c26..bf185a32c 100644 --- a/crates/font-manager/tests/it/picker.rs +++ b/crates/font-manager/tests/it/picker.rs @@ -122,8 +122,10 @@ fn present(fx: &Fixture, text: &str) -> bool { fx.by_label(text).is_some() || fx.texts().iter().any(|painted| painted.text == text) } +/// A selection of several families leaves the family field empty, on screen and to assistive technology, as the +/// reference applications do: no family name and no word stands in for it. #[trial] -fn mixed_family_is_named_until_a_font_is_chosen() { +fn a_mixed_family_shows_an_empty_field() { let catalog = catalog_of(&[INTER_REGULAR]); let mut family = craft_behavior::Mixed::::Mixed; let mut fx = Fixture::new(move |ui| { @@ -132,8 +134,14 @@ fn mixed_family_is_named_until_a_font_is_chosen() { fx.in_room(Room::Window); fx.settle(); let field = fx.by_role(craft_ui::runtime::access::Role::COMBO_BOX).into_iter().next().expect("the family field"); - let label = fx.tree().value_of(field.node).filter(|value| !value.is_empty()).expect("the mixed family has an accessible label"); - assert!(present(&fx, label), "the accessible mixed label is also visible"); + assert!(fx.tree().value_of(field.node).is_none_or(str::is_empty), "the mixed family has no accessible value"); + let words: Vec = fx + .texts() + .iter() + .filter(|painted| field.rect.contains_rect(painted.rect) && painted.text.chars().any(char::is_alphabetic)) + .map(|painted| painted.text.clone()) + .collect(); + assert!(words.is_empty(), "the field paints no text: {words:?}"); } #[trial] diff --git a/crates/ui-canvas/src/canvas/rulers/mod.rs b/crates/ui-canvas/src/canvas/rulers/mod.rs index bed29b8ea..96acf884f 100644 --- a/crates/ui-canvas/src/canvas/rulers/mod.rs +++ b/crates/ui-canvas/src/canvas/rulers/mod.rs @@ -402,7 +402,7 @@ impl Component for Rulers<'_> { for (part, strip) in [(RulerPart::Horizontal, top), (RulerPart::Vertical, left)] { let declared = cx.part(part.part(), strip).priority(handle).pointer_only("the New Guide... command places a guide by number"); if self.interactive { - let declared = declared.sense(Sense::DRAG | Sense::CLICK); + let declared = declared.sense(Sense::DRAG | Sense::CLICK | Sense::CONTEXT_CLICK); if let Some(space) = space { declared.cursor(resize_cursor(&space.view, motion_across(part.guide_along()))); } @@ -410,7 +410,11 @@ impl Component for Rulers<'_> { } let declared = cx.part(CORNER, corner).priority(handle); if self.interactive { - let sense = if self.origin_locked { Sense::CLICK | Sense::CONTEXT_CLICK } else { Sense::DRAG | Sense::CLICK | Sense::TAKE_FOCUS }; + let sense = if self.origin_locked { + Sense::CLICK | Sense::CONTEXT_CLICK + } else { + Sense::DRAG | Sense::CLICK | Sense::CONTEXT_CLICK | Sense::TAKE_FOCUS + }; let declared = declared.sense(sense); if self.origin_locked { declared.pointer_only("the zero point is locked"); diff --git a/crates/ui-canvas/src/canvas_controls/guides/mod.rs b/crates/ui-canvas/src/canvas_controls/guides/mod.rs index c84c921be..f66ebb358 100644 --- a/crates/ui-canvas/src/canvas_controls/guides/mod.rs +++ b/crates/ui-canvas/src/canvas_controls/guides/mod.rs @@ -499,7 +499,7 @@ impl Component for Guides<'_> { let Some([a, b]) = place::segment(&space.view, guide.along, guide.position, guide.span, rect) else { continue }; let part = cx .part(guide.key.part(GUIDE), HitShape::segment(a, b)) - .sense(Sense::DRAG | Sense::CLICK | Sense::TAKE_FOCUS) + .sense(Sense::DRAG | Sense::CLICK | Sense::CONTEXT_CLICK | Sense::TAKE_FOCUS) .priority(HitPriority::new(HitLevel::Edge, 0)) .cursor(resize_cursor(&space.view, motion_across(guide.along))) .focusable(); diff --git a/crates/ui-canvas/tests/it/canvas/rulers.rs b/crates/ui-canvas/tests/it/canvas/rulers.rs index 7176fc6ff..16aa58288 100644 --- a/crates/ui-canvas/tests/it/canvas/rulers.rs +++ b/crates/ui-canvas/tests/it/canvas/rulers.rs @@ -265,3 +265,43 @@ fn a_corner_drag_the_host_cancelled_lands_nothing_at_its_release() { fixture.settle(); assert_eq!(*zero.borrow(), host, "the release after the host's change leaves the zero point where the host put it"); } + +/// A right-click on a ruler strip or on the corner is the rulers': they report the part, for their units menu, and +/// the tool host under them asks for no menu of its own. +#[trial] +fn a_right_click_on_a_ruler_is_the_rulers_not_the_tools() { + use craft_ui::canvas::{RulerPart, ToolHost, tool_pass}; + let zero = Rc::new(RefCell::new(Point::ZERO)); + let asked: Rc, bool)>> = Rc::new(RefCell::new((None, false))); + let (shown_zero, seen) = (Rc::clone(&zero), Rc::clone(&asked)); + let room = Rc::new(Cell::new(Rect::NOTHING)); + let shown_room = Rc::clone(&room); + let tool = RefCell::new(Overpaint); + let mut fixture = Fixture::new(move |ui| { + let at = ui.available_rect_before_wrap(); + shown_room.set(at); + let view = CanvasView::new(at, Point::new(f64::from(at.center().x), f64::from(at.center().y)), 1.0); + let mut zero = shown_zero.borrow_mut(); + let mut host_asked = false; + let canvas = Canvas::new("Document").view(view).with_rulers(Some(Rulers::new("Rulers", Bind::bound(&mut *zero)))).show(ui, |ui, body| { + if let Some(pass) = tool_pass(&body.env) { + host_asked = ToolHost::new().run(ui, &pass, &mut *tool.borrow_mut()).context.is_some(); + } + }); + let mut seen = seen.borrow_mut(); + seen.0 = seen.0.or(canvas.output.rulers.as_ref().and_then(|rulers| rulers.context)); + seen.1 |= host_asked; + }); + fixture.room(Vec2::new(500.0, 400.0)).settle(); + let mut right_click = |at: Pos2| { + *asked.borrow_mut() = (None, false); + fixture.frame(vec![craft_ui::testing::pointer::moved(at)]); + fixture.frame(vec![craft_ui::testing::pointer::secondary(at, true)]); + fixture.frame(vec![craft_ui::testing::pointer::secondary(at, false)]); + fixture.settle(); + *asked.borrow() + }; + let canvas = room.get(); + assert_eq!(right_click(egui::pos2(canvas.center().x, canvas.min.y + 4.0)), (Some(RulerPart::Horizontal), false), "the top strip"); + assert_eq!(right_click(canvas.min + Vec2::splat(4.0)), (Some(RulerPart::Corner), false), "the corner, its zero point unlocked"); +} diff --git a/crates/ui-canvas/tests/it/canvas_controls/guides.rs b/crates/ui-canvas/tests/it/canvas_controls/guides.rs index 3f32ad108..9336a261b 100644 --- a/crates/ui-canvas/tests/it/canvas_controls/guides.rs +++ b/crates/ui-canvas/tests/it/canvas_controls/guides.rs @@ -6,7 +6,7 @@ use craft_behavior::{Axis, CancelReason, CanvasView}; use craft_ui::canvas::{CanvasTool, Guide, GuideKey, Snap, ToolAction, ToolContext, ToolPath, ToolPointer}; use craft_ui::canvas_controls::Guides; use craft_ui::canvas_controls::reading::{GuideReading, running}; -use craft_ui::contract::{Bind, BodyCx, Show as _}; +use craft_ui::contract::{Bind, BodyCx, Props as _, Show as _, ShowContainer as _}; use craft_ui::primitives::Draw; use craft_ui::testing::{ToolFixture, pointer, tool_fixture, trial}; use egui::{Id, Key, Modifiers, Pos2, Rect, Vec2, pos2, vec2}; @@ -284,3 +284,39 @@ fn a_deleted_guide_hands_focus_on_without_selecting_the_next_guide() { assert!(at(&guides, Axis::Y, 200.0).is_none(), "Delete removes it: {:?}", guides.borrow()); assert_eq!(*selected.borrow(), None, "and selects no other guide"); } + +// A right-click on an unlocked guide is the guide's: the guides report its menu request and the tool host under them +// reports none. Off the guide the right-click reaches the host, which asks for its own menu. +#[trial] +fn a_right_click_on_a_guide_asks_for_the_guide_menu_not_the_tools() { + use craft_ui::canvas::{Canvas, ToolHost, tool_pass}; + use craft_ui::testing::Fixture; + use craft_ui::testing::tool_fixture::DOCUMENT; + let guides: Shared> = Rc::new(RefCell::new(vec![guide(1, Axis::Y, 200.0)])); + let asked: Shared<(Option, bool)> = Rc::new(RefCell::new((None, false))); + let (shown, seen) = (Rc::clone(&guides), Rc::clone(&asked)); + let tool = RefCell::new(Recorder::default()); + let mut fixture = Fixture::new(move |ui| { + let room = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").id(tool_fixture::canvas_id("Document")).document(DOCUMENT).view(view_at(1.0)(room)); + let _ = canvas.show(ui, |ui, body| { + let out = Guides::new("Guides", canvas_of(body), Bind::bound(&mut *shown.borrow_mut())).interactive(true).show_at(ui, body.rect); + let mut seen = seen.borrow_mut(); + seen.0 = seen.0.or(out.context.map(|(key, _)| key)); + if let Some(pass) = tool_pass(&body.env) { + seen.1 |= ToolHost::new().run(ui, &pass, &mut *tool.borrow_mut()).context.is_some(); + } + }); + }); + fixture.settle(); + let mut right_click = |at: Pos2| { + *asked.borrow_mut() = (None, false); + fixture.frame(vec![pointer::moved(at)]); + fixture.frame(vec![pointer::secondary(at, true)]); + fixture.frame(vec![pointer::secondary(at, false)]); + fixture.settle(); + *asked.borrow() + }; + assert_eq!(right_click(pos2(200.0, 300.0)), (Some(GuideKey::new(1)), false), "on the guide: its menu, not the tool's"); + assert_eq!(right_click(pos2(400.0, 300.0)), (None, true), "off the guide: the tool's menu"); +} diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index 17dab55ca..328fb8671 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -11,6 +11,7 @@ use crate::runtime::lazy::{self, Call, Decision, Key, Place}; use crate::runtime::measure::{MemoRun, count_memo_run}; use crate::runtime::memory::sub; use crate::runtime::replay; +use craft_behavior::Axis; use egui::{Pos2, Rect, Ui, UiBuilder, Vec2}; use std::hash::Hash; @@ -67,33 +68,48 @@ impl Lazy { } } + /// The id of the child in `ui`: under its scroll area, or under `ui`'s scope outside every scroll area. + pub(super) fn id(&self, ui: &Ui) -> egui::Id { + match Env::of(ui).view().lazy_view() { + Some(view) => sub(view.owner, ("lazy", self.key)), + None => sub(ui.scope_id(), ("lazy", self.key)), + } + } + /// The one runner of a `Lazy` child and a memoized view (`MemoView`), named `name` in the count trials: runs `add`, /// replays the kept run of a memoized view keyed `key`, or takes the extent of a child out of view. pub(super) fn run_keyed(self, ui: &mut Ui, name: &'static str, key: Key, add: impl FnOnce(&mut Ui, &mut Run) -> R) -> Shown { let ctx = ui.ctx().clone(); let env = Env::of(ui); let view = env.view().lazy_view(); - let id = match view { - Some(view) => sub(view.owner, ("lazy", self.key)), - None => sub(ui.scope_id(), ("lazy", self.key)), - }; + let id = self.id(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. A row that narrows it gives it at most the width - // its measuring run settled on, the room its place then holds, so a new width runs it. A view the row does not - // narrow shows as in no room, in the row's flow region: its room does not follow its own content's width, so a - // new content runs it once and the discard pass its new size asks for replays that run. - let shrink = env.shrink.filter(|_| memo); - let cap = match shrink { - Some(Shrink::Apply(row)) => crate::layout::shrink_cap(&ctx, row, id).filter(|cap| cap.narrowed), - _ => None, - }; - let available = cap.map_or_else(|| flow_region(ui), |cap| at_most(flow_region(ui), rtl, cap.width)); - let available = if memo { on_row_line(ui, id, available) } else { available }; 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. let real = !sizing && !crate::runtime::measure::active(&ctx); + // A memoized view whose content filled the axis the body around it shares is one of the children that fill + // that body: a real run shows it in its share, as the body gives a child that fills it directly. + let share = env + .shares() + .filter(|axis| memo && real && lazy::fills(&ctx, id, sizing) == Some(*axis)) + .and_then(|axis| crate::layout::fill_share(ui, axis).map(|share| (axis, share))); + // A memoized view is one unit of the shrinking row around it. A row that narrows it gives it at most the width + // its measuring run settled on, the room its place then holds, so a new width runs it. A view the row does not + // narrow shows as in no room, in the row's flow region: its room does not follow its own content's width, so a + // new content runs it once and the discard pass its new size asks for replays that run. A view that fills the + // row takes no part in its shrink step, as a body that fills it does not. + let shrink = env.shrink.filter(|_| memo); + let cap = match shrink { + Some(Shrink::Apply(row)) if share.is_none() => crate::layout::shrink_cap(&ctx, row, id).filter(|cap| cap.narrowed), + _ => None, + }; + let available = match share { + Some((axis, share)) => share_of(flow_region(ui), rtl, axis, share), + None => cap.map_or_else(|| flow_region(ui), |cap| at_most(flow_region(ui), rtl, cap.width)), + }; + let available = if memo { on_row_line(ui, id, available) } else { available }; let owner = view.map(|view| view.owner); // A run around this one that is replayed later keeps the child's entry. replay::journal(&ctx, || (owner, id), |ctx, &(owner, id)| lazy::keep(ctx, owner, id)); @@ -147,7 +163,8 @@ impl Lazy { { // A real replay is where the run's content went, moved with the room. let rect = if real { ran_at } else { Rect::from_min_size(at_start(available, rtl, size), size) }; - let took = place_view(ui, rect); + let fills = if memo && !real { lazy::fills(&ctx, id, sizing) } else { None }; + let took = place_unit(ui, (shrink, fills), id, rect, rtl); let kept = if real { layout_memory::backstop(&ctx, id, size); let kept = lazy::replay_settled(&ctx, id, &shift); @@ -160,7 +177,6 @@ impl Lazy { // the extent this call takes, never from rects in it. 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); @@ -177,6 +193,9 @@ impl Lazy { if run.recording { open_record(&ctx, audited.is_some()); } + if memo { + crate::layout::open_view_fill(&ctx, id); + } let mut child = alloc::child(ui, UiBuilder::new().max_rect(available).layout(layout).scope_id(id)); // Its extent in the body around it comes from its content's measure, so a change inside reaches that body. The // content runs in the env of `ui`, as the direct children of the body around it: a plain `Lazy` keeps their @@ -185,6 +204,7 @@ impl Lazy { let rect = child.min_rect(); // The child `Ui` writes its widget rect when it drops: the record holds it as written. drop(child); + let fills = if memo { crate::layout::take_view_fill(&ctx, id) } else { None }; let record = run.recording.then(|| replay::close(&ctx, place.layer)); if let Some(shift) = audited { return place_audit_run(ui, Audited { name, id, view, rect, record: record.as_ref(), shift }, out, &run); @@ -199,15 +219,14 @@ impl Lazy { layout_memory::backstop(&ctx, id, rect.size()); } if memo { - place_view(ui, rect); - report_unit(&ctx, shrink, id, rect.size()); + place_unit(ui, (shrink, fills.filter(|_| !real)), id, rect, rtl); } else { crate::layout::close_flow_start_in(ui); alloc::advance_past(ui, rect); } if view.is_some() || memo { let registered = real.then(|| record.as_ref().map_or_else(|| focus::transcript(&ctx, mark), |record| record.focus.clone())); - lazy::shown(&ctx, owner, id, sizing, lazy::Measured { size: rect.size(), key, room: available, flow: place.flow }, registered); + lazy::shown(&ctx, owner, id, sizing, lazy::Measured { size: rect.size(), key, room: available, flow: place.flow, fills }, registered); } if let Some(view) = view && real @@ -296,17 +315,58 @@ fn at_most(region: Rect, rtl: bool, width: f32) -> Rect { 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, id: egui::Id, size: Vec2) { - match shrink { - Some(Shrink::Count(row)) => crate::layout::report_shrink(ctx, row, id, size.x, size.x, None, (false, None)), - Some(Shrink::Least(row)) => crate::layout::report_least(ctx, row, id, size.x), - _ => {} +/// `region` cut to `share` at most along `axis`, from its start edge: the room of a memoized view that fills the body +/// around it. +fn share_of(region: Rect, rtl: bool, axis: Axis, share: f32) -> Rect { + match axis { + Axis::X => at_most(region, rtl, share), + _ => Rect::from_min_size(region.min, Vec2::new(region.width(), share.min(region.height()))), } } +/// Places the extent `rect` of the memoized view `id` in flow in `ui` (`place_view`) as one unit of the body around it, +/// and returns the rect it took. `fills` is the axis the body shares which the view's content filled in a measuring +/// run: the view is then one of the children that fill the body, as a child shown there directly is. It takes its +/// share along the axis once the body knows it; in the first sweep of the body's measuring run it is counted and takes +/// nothing there (`counting_fills`), outside the least measure, where it takes what its content took. In a shrinking +/// row it is a unit that does not narrow below what it takes, as a body that fills the row is. +/// +/// Any other view reports its extent 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 place_unit(ui: &mut Ui, (shrink, fills): (Option, Option), id: egui::Id, rect: Rect, rtl: bool) -> Rect { + let ctx = ui.ctx().clone(); + let env = Env::of(ui); + let Some(axis) = fills.filter(|axis| env.shares() == Some(*axis)) else { + let took = place_view(ui, rect); + match shrink { + Some(Shrink::Count(row)) => crate::layout::report_shrink(&ctx, row, id, rect.width(), rect.width(), None, (false, None)), + Some(Shrink::Least(row)) => crate::layout::report_least(&ctx, row, id, rect.width()), + _ => {} + } + return took; + }; + let content = rect.size(); + let along = match crate::layout::fill_share(ui, axis) { + Some(share) => Some(share), + None if crate::layout::counting_fills(ui, axis) && !env.least => { + crate::layout::count_fill_view(ui); + Some(0.0) + } + None => None, + }; + let size = match (axis, along) { + (Axis::X, Some(along)) => Vec2::new(along, content.y), + (_, Some(along)) => Vec2::new(content.x, along), + (_, None) => content, + }; + let took = place_view(ui, Rect::from_min_size(at_start(rect, rtl, size), size)); + if let (Axis::X, Some(Shrink::Count(row))) = (axis, shrink) { + crate::layout::report_shrink(&ctx, row, id, size.x, size.x, Some((size.x, size.x)), (false, None)); + } + took +} + /// 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`. diff --git a/crates/ui-contract/src/contract/memo_view.rs b/crates/ui-contract/src/contract/memo_view.rs index de103c619..46a1150b0 100644 --- a/crates/ui-contract/src/contract/memo_view.rs +++ b/crates/ui-contract/src/contract/memo_view.rs @@ -3,7 +3,7 @@ use super::lazy::{Lazy, Shown}; use super::memo::{MemoKey, MemoProps}; -use crate::runtime::env::{Env, Scoped, Shrink}; +use crate::runtime::env::{Env, Shrink}; use crate::runtime::shift::Shift; use egui::Ui; use std::fmt; @@ -48,9 +48,9 @@ use std::sync::Arc; /// Its other inputs are the framework's, and each reaches the key or the settled test: /// - its place: the room it is given, the clip, the layer, the layout, the scale, the scope's style inputs (tokens, /// theme, density, direction, language, window active) and the flow of the body around it (whether that body is a -/// content-sized or a given column, the axes it sizes from its content, a least measure, the axes a scroll leaves -/// unbounded, a beside label's cell, whether its leaves fit the room), compared for every view and for each kind of -/// run on its own; +/// content-sized or a given column, the axes it sizes from its content, the axis it shares among the children that +/// fill it, a least measure, the axes a scroll leaves unbounded, a beside label's cell, whether its leaves fit the +/// room), compared for every view and for each kind of run on its own; /// - what the scope around it hands down beyond those (enabled, read-only, size, ink, the command chain, motion, every /// app value, and the rest of `Scoped::scope_key`), in the key; /// - the framework inputs it reads outside its props (`runtime::inputs`: the modifiers, the pointer, the keys held, the @@ -64,8 +64,15 @@ use std::sync::Arc; /// 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. When the row narrows it, the width the row gives it is the room of its place; otherwise it shows as in no -/// room, in the row's flow region. Its content sizes from its content along x, and its leaves fit the view's room, as -/// they fit the room of a `Stack` the view is shown in. +/// room, in the row's flow region. Its leaves fit the view's room, as they fit the room of a `Stack` the view is shown +/// in. +/// +/// In a `Stack` or `Row` body that shares its height or width among the children that fill it, a view whose content +/// fills that axis (a direct child of the content given it to fill, as a fill-width bar in a shell slot) is one of +/// those children, as that child shown without the view would be: the body counts it, and gives it its share as the +/// room of its place, so a new share runs it. Which axis its content filled is kept with its measure. In a shrinking +/// `Row` that does not share its width, its content sizes from its content along x: a child that fills there takes its +/// measured width. /// /// 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 @@ -120,12 +127,14 @@ impl MemoVie 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 id = lazy.id(ui); let key = Self::key(&ctx, &env, &props, show); let shown = lazy.run_keyed(ui, std::any::type_name::

(), 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. It keeps how - // that body sizes from its content and whether its leaves fit their room (`Scoped::start_view_room`), so - // the view takes what its content used there, as the same content shown without the view would. - let installed = Env::install_for(ui, env.derive_local(Scoped::start_view_room)); + // that body sizes from its content, whether its leaves fit their room and which axis it shares among the + // children that fill it (`Scoped::start_view_room`), so the view takes what its content used there, as the + // same content shown without the view would. + let installed = Env::install_for(ui, env.derive_local(|scoped| scoped.start_view_room(id))); let out = show(&mut props, ui); Env::restore(&ctx, installed); run.output = Some(Arc::new(out.clone())); diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index 5ca08306c..5c64e895e 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -141,6 +141,11 @@ pub(crate) struct Cursors(IdMap); #[derive(Default)] pub(crate) struct FillCounts(IdMap); +/// The memoized views running this pass whose content holds a direct child that fills the axis the body around the +/// view shares (`Scoped::fill_view`), by view id, with that axis. +#[derive(Default)] +pub(crate) struct ViewFills(IdMap); + /// What makes a child of a content-sized `Stack` column a held child: it measures at its own width while the column /// settles its width from the others, and the column's second sweep gives it the settled width. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -423,6 +428,9 @@ pub(crate) fn fill_size(ui: &Ui, id: Id, axis: Axis, measured: f32, offered: f32 if !given { return measured; } + if let Some((view, along)) = env.fill_view.filter(|(_, along)| *along == axis) { + pass_state::with::(ui.ctx(), |fills| fills.0.insert(view, along)); + } // In a body that shares the axis and scrolls along it, a share never cuts the child's content: what is past the // view scrolls. if env.fill_body.is_some_and(|(_, along)| along == axis) && view_room(ui, axis).is_some() { @@ -452,12 +460,36 @@ fn main_fill(ui: &Ui, id: Id, axis: Axis) -> MainFill { return MainFill::Share(share, layout_memory::fill_least(ui.ctx(), id, axis)); } if measure::active(ui.ctx()) { - pass_state::with::(ui.ctx(), |counts| *counts.0.entry(body).or_insert(0) += 1); + count_fill(ui.ctx(), body); return MainFill::Measuring; } MainFill::Room(layout_memory::fill_least(ui.ctx(), id, axis)) } +/// Counts one child that fills the main axis of the sharing body `body`, in the first sweep of its measuring run. +fn count_fill(ctx: &egui::Context, body: Id) { + pass_state::with::(ctx, |counts| *counts.0.entry(body).or_insert(0) += 1); +} + +/// Counts the memoized view whose content fills the main axis of `ui`'s sharing body as one child that fills it, in the +/// first sweep of the body's measuring run (`counting_fills`), as a child shown there directly is counted. +pub(crate) fn count_fill_view(ui: &Ui) { + if let Some((body, _)) = Env::of(ui).fill_body { + count_fill(ui.ctx(), body); + } +} + +/// Opens the record of whether the content of the memoized view `view` fills the axis its body shares, before its run. +pub(crate) fn open_view_fill(ctx: &egui::Context, view: Id) { + pass_state::with::(ctx, |fills| fills.0.remove(&view)); +} + +/// The axis the content of the memoized view `view` filled in the run that just ended, as `fill_size` noted it; closes +/// the record. +pub(crate) fn take_view_fill(ctx: &egui::Context, view: Id) -> Option { + pass_state::with::(ctx, |fills| fills.0.remove(&view)) +} + /// The share a child of `ui`'s body that fills along `axis` takes there, once its body knows it: the room the child /// is measured and shown in along that axis, in the measuring run's second sweep and in the real run alike. pub(crate) fn fill_share(ui: &Ui, axis: Axis) -> Option { diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index cc9396d47..2895b9f4d 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -24,8 +24,8 @@ pub use body::place_in_flow; #[cfg(feature = "testing")] pub(crate) use body::run_body; pub(crate) use body::{ - BodyLine, BracketTook, HeldKind, InFlow, ask_shortfall, at_flow_start, close_first_line, close_flow_start_in, counting_fills, fill_share, - fill_size, flow_fill_room, flow_region, flow_room, flow_start, grid_cell, held_kind, in_grid_content_column, leaf_fill_room, members_line, - open_first_lines, place_in_cell, report_bracket_control, report_held, report_least, report_shrink, row_alone_room, run_body_measured, shares_y, - shrink_cap, take_bracket, take_cell, take_in_flow, take_shortfall, view_room, + BodyLine, BracketTook, HeldKind, InFlow, ask_shortfall, at_flow_start, close_first_line, close_flow_start_in, count_fill_view, counting_fills, + fill_share, fill_size, flow_fill_room, flow_region, flow_room, flow_start, grid_cell, held_kind, in_grid_content_column, leaf_fill_room, + members_line, open_first_lines, open_view_fill, place_in_cell, report_bracket_control, report_held, report_least, report_shrink, row_alone_room, + run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, take_shortfall, take_view_fill, view_room, }; diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 9494bc2bb..64494b8af 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -78,7 +78,8 @@ pub(crate) struct FooterSlotOf { } /// The flow facts of the body around a memoized view that its content is laid out by: whether that body is a -/// content-sized or a given column, the axes it sizes from its content, whether the view runs in a least measure, the +/// content-sized or a given column, the axes it sizes from its content, the axis it shares among the children that fill +/// it, whether the view runs in a least measure, the /// axes a scrolling body leaves unbounded, whether it fills a beside label's cell and whether its leaves fit the view's /// room (`Scoped::view_fits`). A measuring run of a container or a row lays the view out under other facts than its /// real run, so they are a fact of the view's place, which each kind of run compares on its own (`lazy::Place`, @@ -88,6 +89,7 @@ pub(crate) struct Flow { content_column: bool, given_column: bool, content: (bool, bool), + shares: Option, least: bool, unbounded: (bool, bool), cell_fills: bool, @@ -187,6 +189,10 @@ pub struct Scoped { /// extents of the other children and the gaps, over the number of children that fill. `None` while the body is /// measured, and without a measuring run of this pass. pub(crate) fill_share: Option, + /// The memoized view whose content the scope's direct children run in, with the axis the body around that view + /// shares (its `fill_body`'s): a child given that axis to fill tells the view (`layout::fill_size`), which then is + /// a child that fills that body (`contract::lazy`). + pub(crate) fill_view: Option<(Id, craft_behavior::Axis)>, /// The shrink step of the unwrapped `Row` or `Stack` body that encloses the scope, as its direct children in flow /// take part in it. pub(crate) shrink: Option, @@ -464,6 +470,7 @@ impl Scoped { self.column_row = false; self.fill_body = None; self.fill_share = None; + self.fill_view = None; self.shrink = None; self.column = None; self.offered = None; @@ -483,6 +490,7 @@ impl Scoped { || self.column_row || self.fill_body.is_some() || self.fill_share.is_some() + || self.fill_view.is_some() || self.shrink.is_some() || self.column.is_some() || self.offered.is_some() @@ -493,12 +501,17 @@ impl Scoped { /// content axes. The view's content then measures and /// fills as it would shown without the view: a child that fills takes its measured size where the body sizes from /// content, never the open room. Where a leaf shown here would fit its room (`view_fits`), the leaves of the view's - /// content fit the room the view is given (`Shrink::Fit`). A view that is a unit of a shrinking `Row` sizes from its - /// content along x, as the row counted it: a child that fills there takes its measured width, not the row's flow - /// region a view the row does not narrow is shown in. - pub(crate) fn start_view_room(&mut self) { + /// content fit the room the view is given (`Shrink::Fit`). + /// + /// In a body that shares an axis among the children that fill it (`fill_body`), a direct child of the content + /// given that axis to fill tells the view `view` (`fill_view`): the view is then one of the children that fill the + /// body, given its share as its room, as the child shown without the view would be. A view that is a unit of a + /// shrinking `Row` that does not share its width sizes from its content along x, as the row counted it: a child + /// that fills there takes its measured width, not the row's flow region a view the row does not narrow is shown in. + pub(crate) fn start_view_room(&mut self, view: Id) { let fits = self.view_fits(); let row_unit = matches!(self.shrink, Some(Shrink::Count(_) | Shrink::Least(_) | Shrink::Apply(_))); + let shares = self.shares(); let (content_column, given_column, egui_cell) = (self.content_column, self.given_column, self.egui_cell); // The view stands on the line of the row around it only to fill it, as a levelled unit does: a fill-width row in // it (a bar in a shell slot) takes the line's height and centres on it, as shown without the view; its children @@ -507,14 +520,23 @@ impl Scoped { self.start_room(); (self.content_column, self.given_column, self.egui_cell) = (content_column, given_column, egui_cell); self.row_line = line; + self.fill_view = shares.map(|axis| (view, axis)); if fits { self.shrink = Some(Shrink::Fit); } - if row_unit { + if row_unit && shares != Some(craft_behavior::Axis::X) { self.content.0 = true; } } + /// The axis the enclosing body shares among its direct children that fill it (`fill_body`). + pub(crate) const fn shares(&self) -> Option { + match self.fill_body { + Some((_, axis)) => Some(axis), + None => None, + } + } + /// Whether a memoized view shown in flow here fits its content to its room, as a leaf here would: in a `Stack` body /// and a wrapping `Row`, whose leaves show at most its room (a whole line), and as one of the units a shrinking /// `Row` narrows. In a `Grid` cell or a `Ui` with no body around it a leaf keeps its measured width, and so does the @@ -568,6 +590,7 @@ impl Scoped { content_column: self.content_column, given_column: self.given_column, content: self.content, + shares: self.shares(), least: self.least, unbounded: self.unbounded, cell_fills: self.cell_fills, @@ -717,6 +740,7 @@ impl Env { footer_slot: None, fill_body: None, fill_share: None, + fill_view: None, shrink: None, column: None, least: false, diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index ab658a888..41cb3f962 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -1244,6 +1244,7 @@ pub(crate) mod guard { ("layout::column_group::Open", "column groups: frames the run opens and closes; reports go through contribute"), ("access::scope::Stack", "label and merge scopes: opened and closed by the run; control minimums go through contribute"), ("layout::body::FillCounts", "fill counts: opened and closed by the body's own measuring sweep"), + ("layout::body::ViewFills", "view fills: opened and closed by the memoized view's own run"), ("layout::body::HeldWidths", "held children: opened by the column's own first sweep and closed after its last"), ("layout::body::FirstLines", "first lines: opened and closed by the container's own measuring sweep; the line goes through emit_record"), ("layout::body::RowLines", "row lines: opened by each sweep of the row and closed after it; the line goes through emit_record"), diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index b30b71829..9c6694bf8 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -160,14 +160,16 @@ struct Entry { } /// What a run that showed a child measured: the extent it took, the key of the content it showed, the room it was -/// offered (`Rect::NOTHING` for a collection row, whose extent its collection reports) and the flow of the body around -/// it (the default for a collection row). +/// offered (`Rect::NOTHING` for a collection row, whose extent its collection reports), the flow of the body around +/// it (the default for a collection row) and the axis that body shares which a memoized view's content filled, which +/// makes the view one of the children that fill the body (`layout::fill_size`). #[derive(Clone, Copy, Debug)] pub(crate) struct Measured { pub(crate) size: Vec2, pub(crate) key: Key, pub(crate) room: Rect, pub(crate) flow: Flow, + pub(crate) fills: Option, } /// Where a memoized view ran: it replays only at a place of the same size, layer, layout, opacity, flow and environment, @@ -457,6 +459,13 @@ pub(crate) fn shown(ctx: &Context, owner: Option, id: Id, sizing: bool, meas }); } +/// The axis the content of the memoized view `id` filled in its last run of this kind (`sizing`), else of the other +/// kind: the run of this pass once one ran, else the kept one. `None` before any run showed it. +pub(crate) fn fills(ctx: &Context, id: Id, sizing: bool) -> Option { + let (own, other) = (usize::from(!sizing), usize::from(sizing)); + with(ctx, |store, _, _| store.entries.get(&id).and_then(|entry| entry.sizes[own].or(entry.sizes[other])).and_then(|measured| measured.fills)) +} + /// The extent the child `id` took in the last measuring or real run that showed it (this pass's measuring run once it /// ran), at whatever room it had; `None` before any run showed it. pub(crate) fn last_extent(ctx: &Context, id: Id) -> Option { @@ -740,7 +749,7 @@ pub(crate) fn note_edit(ctx: &Context, key: BindKey) { pub(crate) fn remember(ctx: &Context, owner: Id, id: Id, size: Vec2) { write(ctx, id, |store, pass_nr, frame| { let entry = store.touch(Some(owner), id, frame); - entry.sizes[1] = Some(Measured { size, key: Key::None, room: Rect::NOTHING, flow: Flow::default() }); + entry.sizes[1] = Some(Measured { size, key: Key::None, room: Rect::NOTHING, flow: Flow::default(), fills: None }); entry.measured_in = Some(pass_nr); }); } diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index ee3b9550d..417b27d85 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -95,6 +95,7 @@ pass_state! { bar_rules: crate::contract::BarRules, surface_frames: crate::primitives::SurfaceFrames, fill_counts: crate::layout::body::FillCounts, + view_fills: crate::layout::body::ViewFills, held_widths: crate::layout::body::HeldWidths, first_lines: crate::layout::body::FirstLines, row_lines: crate::layout::body::RowLines, diff --git a/crates/ui-contract/tests/it/contract/memo_row.rs b/crates/ui-contract/tests/it/contract/memo_row.rs index 7fd587c01..a3660f5e4 100644 --- a/crates/ui-contract/tests/it/contract/memo_row.rs +++ b/crates/ui-contract/tests/it/contract/memo_row.rs @@ -58,3 +58,89 @@ fn a_memoized_row_unit_replays_after_the_rows_counting_call() { let calls = of_view(last_frame_memo_runs(&frames.ctx)); assert!(calls.iter().all(|run| *run == MemoRun::Replayed), "the next frame replays the view in every call: {calls:?}"); } + +thread_local! { + /// The rect the fill panel of a `Filled` view took in its last run. + static FILLED: RefCell = RefCell::default(); +} + +/// A view whose content is one panel that fills the main axis of the body around it (`axis`: 0 the width, 1 the height). +#[derive(MemoProps)] +struct Filled { + axis: u8, +} + +fn filled(props: &mut Filled, ui: &mut Ui) { + fill_panel(ui, props.axis); +} + +/// The panel that fills `axis`, holding one probe. +fn fill_panel(ui: &mut Ui, axis: u8) { + let sizing = if axis == 0 { Sizing::FillWidth } else { Sizing::FillHeight }; + FILLED.with(|seen| { + Panel::new().seen(seen).sizing(sizing).id_salt("fill").show(ui, |ui, _| { + let inner = RefCell::new(Seen::default()); + Probe::new(&inner).id_salt("inner").show(ui); + }); + }); +} + +/// The rects of the fill panel and the probes before and after it in a body along `axis` (0 a row, 1 a stack) given its +/// room, the panel shown through a memoized view when `memo`, after the frames settle; and how the view took part in +/// the calls of one more frame. +fn shared_body(axis: u8, memo: bool) -> ([Rect; 3], Vec) { + let (before, after) = (RefCell::new(Seen::default()), RefCell::new(Seen::default())); + let mut frames = Frames::new(); + let (layout, room) = if axis == 0 { (BodyLayout::row(), Vec2::new(400.0, 40.0)) } else { (BodyLayout::stack(), Vec2::new(200.0, 300.0)) }; + let frame = |frames: &mut Frames| { + frames.frame(vec![], |ui| { + in_region(ui, Rect::from_min_size(Pos2::new(10.0, 10.0), room), |ui| { + Panel::new().layout(layout.clone()).sizing(Sizing::Fill).id_salt("body").show(ui, |ui, _| { + Probe::new(&before).id_salt("before").show(ui); + if memo { + let _ = MemoView::new("view", Filled { axis }, filled).show(ui); + } else { + fill_panel(ui, axis); + } + Probe::new(&after).id_salt("after").show(ui); + }); + }); + }); + }; + for _ in 0..30 { + frame(&mut frames); + } + frame(&mut frames); + let runs = last_frame_memo_runs(&frames.ctx).into_iter().filter(|(name, _, _)| name.contains("Filled")).map(|(_, _, run)| run).collect(); + ([before.borrow().rect, FILLED.with(|seen| seen.borrow().rect), after.borrow().rect], runs) +} + +/// A memoized view whose content fills the width of the row around it is one of the children that fill the row, as the +/// content shown without the view is: it takes the row's free width and the probe after it keeps its place at the row's +/// end. With nothing changed every call of a frame replays the view. +#[trial] +fn a_memoized_view_whose_content_fills_the_row_takes_its_free_width() { + let (direct, _) = shared_body(0, false); + let (memo, runs) = shared_body(0, true); + let [before, fill, after] = memo; + assert!(fill.left() >= before.right() && after.left() >= fill.right(), "the view lies between the probes: {memo:?}"); + for (shown, alone) in memo.iter().zip(direct) { + assert!(shown.min.distance(alone.min) < 0.5 && shown.max.distance(alone.max) < 0.5, "as without the view: {memo:?} and {direct:?}"); + } + assert!(!runs.is_empty() && runs.iter().all(|run| *run == MemoRun::Replayed), "an idle frame replays the view in every call: {runs:?}"); +} + +/// A memoized view whose content fills the height of the stack around it takes its share of the stack's height, as the +/// content shown without the view does: the probe after it stays inside the stack. With nothing changed every call of a +/// frame replays the view. +#[trial] +fn a_memoized_view_whose_content_fills_the_stack_takes_its_share_of_the_height() { + let (direct, _) = shared_body(1, false); + let (memo, runs) = shared_body(1, true); + let [before, fill, after] = memo; + assert!(fill.top() >= before.bottom() && after.top() >= fill.bottom(), "the view lies between the probes: {memo:?}"); + for (shown, alone) in memo.iter().zip(direct) { + assert!(shown.min.distance(alone.min) < 0.5 && shown.max.distance(alone.max) < 0.5, "as without the view: {memo:?} and {direct:?}"); + } + assert!(!runs.is_empty() && runs.iter().all(|run| *run == MemoRun::Replayed), "an idle frame replays the view in every call: {runs:?}"); +} diff --git a/crates/ui-shell/tests/it/shell/title_bar.rs b/crates/ui-shell/tests/it/shell/title_bar.rs index a44a27375..8c39824b3 100644 --- a/crates/ui-shell/tests/it/shell/title_bar.rs +++ b/crates/ui-shell/tests/it/shell/title_bar.rs @@ -354,6 +354,73 @@ fn the_lights_room_follows_the_lights_without_mirroring_the_bar() { assert!(rect("Preferences").right() >= width - 20.0, "Preferences {:?} at the right end", rect("Preferences")); } +/// The props of a whole title bar an app shows through a memoized view. +#[derive(craft_ui::contract::MemoProps)] +struct WholeBar { + version: u64, +} + +/// A Windows title bar with a brand button, a menu bar of an image editor's menus and the document title. +fn whole_bar(_: &mut WholeBar, ui: &mut Ui) { + use craft_ui::buttons::Button; + use craft_ui::contract::Show as _; + use craft_ui::menu::MenuItem; + use craft_ui::menu::bar::{MenuBar, MenuTitle}; + let layout = craft_window::Layout { left: vec![], right: vec![Caption::Minimize, Caption::Maximize, Caption::Close] }; + let frame = Frame::Integrated(Captions { family: CaptionFamily::Windows, layout }); + let _ = TitleBar::new().frame(frame).show_titled( + ui, + Title::new("Untitled-1.psd"), + |ui, _| { + Button::new("Brand").show(ui); + let names = ["&File", "&Edit", "&Image", "&Layer", "&Type", "&Select", "Fil&ter", "&3D", "&View", "&Plugins", "&Window", "&Help"]; + let titles = names + .into_iter() + .map(|name| { + MenuTitle::new(name, |ui| { + MenuItem::new("Row").show(ui); + }) + }) + .collect(); + MenuBar::new("Main menu", titles).show(ui); + }, + |_, _| {}, + ); +} + +/// A whole title bar an app shows through a memoized view in the shell's title slot (1600 × 1000 px at 125 %) fills +/// the slot as the bar shown directly does: the captions end at the slot's end edge and the document title is drawn +/// whole after the last menu. +#[trial] +fn a_memoized_title_bar_fills_the_title_slot() { + use craft_host::target::Os; + use craft_ui::contract::MemoView; + let slot = Rc::new(Cell::new(Rect::NOTHING)); + let seen = Rc::clone(&slot); + let mut fixture = Fixture::new(move |ui| { + let shown = AppShell::new(WindowKey::main()) + .title_bar(|ui, _, _: &mut ()| { + let _ = MemoView::new("title bar", WholeBar { version: 0 }, whole_bar).show(ui); + }) + .body(|_, _, _| {}) + .show(ui, &mut ()); + if let Some(rect) = shown.regions.slots.iter().find(|(key, _)| *key == "title").map(|(_, rect)| *rect) { + seen.set(rect); + } + }); + fixture.os(Os::Windows); + fixture.ctx().set_pixels_per_point(1.25); + fixture.room(vec2(1280.0, 800.0)).settle(); + let slot = slot.get(); + let close = fixture.by_label("Close").expect("the Close caption").rect; + assert!((close.right() - slot.right()).abs() <= 1.0, "the Close caption {close:?} ends at the slot's end {slot:?}"); + let help = fixture.by_label("Help").expect("Help is a title of the menu bar").rect; + let (title, elided) = + fixture.texts().iter().find(|run| run.text == "Untitled-1.psd").map(|run| (run.rect, run.elided)).expect("the document title is painted"); + assert!(title.left() > help.right() && title.right() < close.left(), "the title {title:?} lies between Help {help:?} and the captions"); + assert!(!elided, "the document title is whole"); +} + /// What a bar with Windows captions `width` wide shows in `direction`, with its trailing content fitted after the /// leading content or, without `fitted`, in the end region, by label: the leading button, the trailing buttons ranked 1 /// and 2 when they are there, the unranked trailing button and the Minimize caption. diff --git a/crates/ui-widgets/src/text/number.rs b/crates/ui-widgets/src/text/number.rs index 464009b74..51bdb02b3 100644 --- a/crates/ui-widgets/src/text/number.rs +++ b/crates/ui-widgets/src/text/number.rs @@ -194,7 +194,8 @@ pub struct NumberField<'a, V: NumberValue + 'static = Option> { /// A typed value goes to the nearest multiple of the step when it commits. #[prop] snap_typed: bool, - /// The decimals a committed value is rounded to; the display keeps the codec's. + /// The decimals a committed value is rounded to; the display keeps the codec's, except that a percent field with no + /// decimals of its own shows none when this is 0 ("10%"). #[prop] commit_decimals: Option, /// An empty field means automatic: it shows the "Auto" word as its placeholder. @@ -442,11 +443,21 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { value.and_then(NumberValue::number).map(|stored| self.to_shown(stored)) } - /// Whether the field counts percent: it writes its precision's decimals in full, its sign right after the number. + /// Whether the field counts percent: it shows its sign right after the number. fn is_percent(&self) -> bool { self.codec.is_none() && self.unit_kind == Some(UnitKind::Percent) } + /// The decimals a percent field writes in full when the caller sets none of its own: one at the standard precision + /// ("100.0%"), none at the measured precision ("100%") or for a field whose committed values carry none + /// (`commit_decimals(0)`). + fn percent_decimals(&self) -> Option { + (self.is_percent() && self.fixed_decimals.is_none() && self.max_decimals.is_none()).then(|| match self.precision { + NumberPrecision::Standard => self.commit_decimals.unwrap_or(1).min(1), + NumberPrecision::Measured => 0, + }) + } + /// Whether the field uses the dash for a missing or invalid value. fn shows_blank(&self, shown: Option<&V>) -> bool { shown.is_none() || non_finite(shown) || (self.status_zoom && shown.and_then(NumberValue::number).is_none()) @@ -461,19 +472,18 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { None => units.reader(self.unit_kind), }; let codec = NumberCodec::new(reader, self.decimals()); - if self.fixed_decimals.is_some() || self.is_percent() { codec.fixed() } else { codec } + if self.fixed_decimals.is_some() || self.percent_decimals().is_some() { codec.fixed() } else { codec } }) } - /// The decimals the field shows: its codec's, fixed or maximum precision, else its unit kind's. + /// The decimals the field shows: its codec's, fixed or maximum precision, a percent field's own, else its unit + /// kind's. fn shown_decimals(&self) -> RangeInclusive { + if let Some(percent) = self.percent_decimals() { + return percent..=percent; + } match (&self.codec, self.fixed_decimals, self.max_decimals, self.unit_kind) { (Some(codec), _, _, _) => 0..=codec.decimals(), - // A percentage reads "100.0%": one decimal, written in full; whole at the measured precision. - (None, _, _, Some(UnitKind::Percent)) => match self.precision { - NumberPrecision::Standard => 1..=1, - NumberPrecision::Measured => 0..=0, - }, (None, Some(fixed), _, _) => fixed..=fixed, (None, None, Some(max), _) => 0..=max.min(12), (None, None, None, Some(kind)) => match (self.precision, self.lengths) { diff --git a/crates/ui-widgets/tests/it/text/number.rs b/crates/ui-widgets/tests/it/text/number.rs index d3bce1323..3420c531a 100644 --- a/crates/ui-widgets/tests/it/text/number.rs +++ b/crates/ui-widgets/tests/it/text/number.rs @@ -775,3 +775,25 @@ fn a_percent_field_reads_one_decimal_then_the_sign() { let sign = painted("%").unwrap_or_else(|| panic!("the field shows the sign")); assert!(sign.min.x - number.max.x <= 5.0, "the sign follows the number closely: {number:?} {sign:?}"); } + +/// A percent field whose committed values carry no decimals (`commit_decimals(0)`, a paint bar's Opacity) shows none, +/// "10%"; one that sets no decimals of its own keeps the one-decimal look, "10.0%". +#[trial] +fn a_percent_field_shows_the_decimals_its_caller_commits() { + let shown = |commit: Option| { + let mut value = Some(10.0f64); + let mut fixture = craft_ui::testing::Fixture::new(move |ui| { + let field = NumberField::new("Opacity", Bind::bound(&mut value)).unit_kind(UnitKind::Percent).range(0.0..=100.0); + let _ = match commit { + Some(decimals) => field.commit_decimals(decimals).show(ui), + None => field.show(ui), + }; + }); + fixture.settle(); + fixture.texts().iter().map(|run| run.text.clone()).collect::>() + }; + let whole = shown(Some(0)); + assert!(whole.iter().any(|text| text == "10") && !whole.iter().any(|text| text == "10.0"), "commit_decimals(0) shows 10%: {whole:?}"); + let default = shown(None); + assert!(default.iter().any(|text| text == "10.0"), "with no decimals set the field shows 10.0%: {default:?}"); +}