diff --git a/Cargo.lock b/Cargo.lock index 4a7ff7f07..bf4b460c7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5451,7 +5451,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "bytemuck", "emath", @@ -5507,7 +5507,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "ahash", "bytemuck", @@ -5542,7 +5542,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "accesskit", "ahash", @@ -5561,7 +5561,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "ahash", "bytemuck", @@ -5580,7 +5580,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "block2 0.6.2", "bytemuck", @@ -5600,7 +5600,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "bytemuck", "egui", @@ -5613,7 +5613,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "eframe", "egui", @@ -5690,7 +5690,7 @@ dependencies = [ [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "bytemuck", ] @@ -5763,7 +5763,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "ahash", "bytemuck", @@ -5789,7 +5789,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[package]] name = "equator" @@ -15120,19 +15120,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[patch.unused]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" diff --git a/Cargo.toml b/Cargo.toml index 8afdc685c..44b4079a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -310,20 +310,20 @@ hayro-postscript = { path = "vendor/hayro-postscript" } linesweeper = { path = "vendor/linesweeper" } vello_common = { path = "vendor/vello_common" } vello_cpu = { path = "vendor/vello_cpu" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -emath = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +emath = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid diff --git a/crates/craft/src/egui_fork.rs b/crates/craft/src/egui_fork.rs index acd621c1e..3890d7981 100644 --- a/crates/craft/src/egui_fork.rs +++ b/crates/craft/src/egui_fork.rs @@ -3,7 +3,7 @@ /// The egui fork the library is built and tested with. Apps patch egui to exactly this. pub const GIT: &str = "https://github.com/storytold/egui.git"; /// The commit of [`GIT`]. -pub const REV: &str = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"; +pub const REV: &str = "f5025284445ea19c35f746d96fc0b75468b3f560"; /// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]). pub const PACKAGES: &[&str] = &[ diff --git a/crates/font-manager/src/picker.rs b/crates/font-manager/src/picker.rs index 1521d943b..1fcd06282 100644 --- a/crates/font-manager/src/picker.rs +++ b/crates/font-manager/src/picker.rs @@ -14,16 +14,18 @@ use craft_behavior::{Codec, EditEvent, IconId, Mixed, NotAValue, PartKey, Sense, use craft_behavior::{HitLevel, HitPriority, NavMove, Preview}; use craft_font_catalog::Catalog; use craft_host::Section; +use craft_theme::variant::Tone; use craft_ui::buttons::{ControlPlace, IconButton}; use craft_ui::contract::{ Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, - Pointer as _, Props as _, Remember as _, Role, WordSetCx as _, + Pointer as _, Props as _, Remember as _, Role, Styled as _, WordSetCx as _, }; use craft_ui::list::{ThumbSize, TrailingPart}; use craft_ui::primitives::{IconSpec, TextKey, TextOptions, TextRun}; use craft_ui::runtime::env::{EnvView, Label}; use craft_ui::runtime::memory::StageAccess; -use craft_ui::text::{Adornment, place, reserve}; +use craft_ui::style::{ComponentStyle, Metrics, Stateful, States, StyleColor, StyleCx, SurfaceLook}; +use craft_ui::text::{Adornment, FieldStyle, place, reserve}; use egui::{Rect, Response, Vec2}; use serde::{Deserialize, Serialize}; @@ -589,18 +591,35 @@ impl<'a> FontPicker<'a> { } } +/// The style of [`FontPicker`]: the field look and the colour of the missing-font warning icon. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +#[non_exhaustive] +pub struct FontPickerStyle { + #[style(surface)] + surface: SurfaceLook, + #[style(metrics)] + metrics: Metrics, + /// The field look the adornments are placed by; `surface` and `metrics` are its own. + field: FieldStyle, + /// The ink of the missing-font warning icon (`status.warn.fg`), dimmed to `text.disabled` while disabled. + warning: Stateful, +} + impl Component for FontPicker<'_> { const ROLE: Role = Role::COMBO_BOX; const INPUT: Input = Input::Text; const KEYS: craft_ui::runtime::focus::KeyUse = craft_ui::runtime::focus::KeyUse::of(Input::Text).with_moves(); - type Style = craft_ui::text::FieldStyle; + type Style = FontPickerStyle; type Output = FontPickerOutput; /// A field; in a ribbon (`ControlPlace::Ribbon`) held at the small field length (`size.length.field.sm`), as a /// ribbon's font box is: wide enough for a family name and its menu arrow, the same width whichever it shows. - fn style(cx: &craft_ui::style::StyleCx<'_>, _: FontPickerStyleKey) -> craft_ui::text::FieldStyle { - let field = craft_ui::text::FieldStyle::at(cx); - if cx.env::() == ControlPlace::Ribbon { field.held_at(cx.tokens.size.length.field.sm) } else { field } + fn style(cx: &StyleCx<'_>, _: FontPickerStyleKey) -> FontPickerStyle { + let field = FieldStyle::at(cx); + let field = if cx.env::() == ControlPlace::Ribbon { field.held_at(cx.tokens.size.length.field.sm) } else { field }; + let warn = cx.tone(Tone::Warn); + let off = cx.color(cx.tokens.color.text.disabled); + FontPickerStyle { surface: cx.field(), metrics: field.metrics(), field, warning: Stateful::new(warn).off(States::new(warn, warn, warn, off)) } } /// The wheel steps the family through the list. @@ -620,7 +639,7 @@ impl Component for FontPicker<'_> { let widest = if ribbon { Vec2::new(cx.tokens.size.length.short, widest.y) } else { widest }; let name = cx.words::().list.clone(); let note = self.missing_note(current, &cx.words::()); - Vec2::new(widest.x + reserve(cx.style, &[], &Self::trailing(name, note.is_some())), widest.y) + Vec2::new(widest.x + reserve(&cx.style.field, &[], &Self::trailing(name, note.is_some())), widest.y) } fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) { @@ -628,7 +647,7 @@ impl Component for FontPicker<'_> { let family = cx.value().cloned().unwrap_or_default(); let note = self.missing_note(&family, &cx.words::()); let trailing = Self::trailing(name, note.is_some()); - let placed = place(cx.content_rect, cx.style, &[], &trailing, cx.flow.is_rtl()); + let placed = place(cx.content_rect, &cx.style.field, &[], &trailing, cx.flow.is_rtl()); if let (Some(note), Some(at)) = (note, placed.trailing.first()) { cx.part(WARNING, *at).tooltip(note); } @@ -708,9 +727,10 @@ impl Component for FontPicker<'_> { let family = cx.value().cloned().unwrap_or_default(); let missing = self.missing_note(&family, &cx.words::()).is_some(); let trailing = Self::trailing(name.clone(), missing); - let placed = place(cx.content_rect, cx.style, &[], &trailing, cx.env.direction().is_rtl()); + let placed = place(cx.content_rect, &cx.style.field, &[], &trailing, cx.env.direction().is_rtl()); if let (true, Some(at)) = (missing, placed.trailing.first()) { - ui.draw().icon(*at, &IconSpec::svg(IconId::new(WARNING_ICON))); + let color = cx.resolve(&cx.style.warning); + ui.draw().icon(*at, &IconSpec::svg(IconId::new(WARNING_ICON)).color(color)); } ui.face(CHEVRON, IconButton::new(IconId::new(CHEVRON_ICON)).label(name)); } diff --git a/crates/font-manager/tests/it/picker.rs b/crates/font-manager/tests/it/picker.rs index 8ef2bc258..195bf3a1b 100644 --- a/crates/font-manager/tests/it/picker.rs +++ b/crates/font-manager/tests/it/picker.rs @@ -400,3 +400,78 @@ fn a_picker_handed_another_catalog_at_the_same_generation_builds_its_family_data fx.frame(vec![]); assert_eq!(family_builds(&fx), 1, "the second catalog builds the data once"); } + +/// Every non-transparent vertex colour of textured meshes whose centre falls inside `rect`. +fn mesh_tints(shapes: &[egui::Shape], rect: egui::Rect, out: &mut Vec) { + for shape in shapes { + match shape { + egui::Shape::Vec(inner) => mesh_tints(inner, rect, out), + egui::Shape::Mesh(mesh) if rect.contains(mesh.calc_bounds().center()) => { + out.extend(mesh.vertices.iter().map(|vertex| vertex.color).filter(|color| color.a() > 0)); + } + _ => {} + } + } +} + +/// The painted tint colours of the missing-font warning icon in `mode`/`contrast`, enabled or disabled, together with +/// the theme's `status.warn.fg`, `text.normal` and `text.disabled` colours. +fn missing_warning_colors( + mode: craft_theme::Mode, + contrast: craft_theme::Contrast, + enabled: bool, +) -> (Vec, egui::Color32, egui::Color32, egui::Color32) { + use craft_ui::contract::Props as _; + use craft_ui::runtime::env::Env; + use egui::Color32; + use std::cell::Cell; + + let catalog = catalog_of(&[INTER_REGULAR]); + let seen = Rc::new(Cell::new((None, Color32::TRANSPARENT, Color32::TRANSPARENT, Color32::TRANSPARENT))); + let held = Rc::clone(&seen); + let mut family = "Gotham".to_owned(); + let mut fx = Fixture::new(move |ui| { + let color = |[r, g, b, a]: [u8; 4]| Color32::from_rgba_unmultiplied(r, g, b, a); + let env = Env::of(ui); + let tokens = &env.tokens.tokens().color; + let out = FontPicker::new("Font family", Bind::bound(&mut family), &catalog) + .kind(FontPickerKind::Plain) + .shown_as("Inter") + .enabled(enabled) + .show(ui); + held.set((Some(out.edit.response.id), color(tokens.status.warn.fg.0), color(tokens.text.normal.0), color(tokens.text.disabled.0))); + }); + fx.theme(mode, contrast); + fx.in_room(Room::Window); + fx.settle(); + let (id, warn_fg, text_normal, text_disabled) = seen.get(); + let picker = id.expect("the picker"); + let mark = fx.part_rect(picker, PartKey::new("missing")).expect("the field carries a mark while the family is not installed"); + let mut tints = Vec::new(); + mesh_tints(&fx.frame_shapes(), mark, &mut tints); + tints.dedup(); + (tints, warn_fg, text_normal, text_disabled) +} + +#[trial] +fn the_missing_font_warning_icon_paints_in_status_warn_fg_and_dims_when_disabled() { + use craft_theme::{Contrast, Mode}; + + for (mode, contrast) in [(Mode::Light, Contrast::Standard), (Mode::Dark, Contrast::Standard), (Mode::Dark, Contrast::High)] { + let (tints, warn_fg, text_normal, _) = missing_warning_colors(mode, contrast, true); + assert_ne!(warn_fg, text_normal, "{mode:?} {contrast:?}: warning ink differs from neutral text ink"); + assert!(!tints.is_empty(), "{mode:?} {contrast:?}: the missing-font warning icon paints"); + assert!( + tints.iter().all(|tint| *tint == warn_fg), + "{mode:?} {contrast:?}: the warning icon paints in status.warn.fg {warn_fg:?}, not {tints:?}" + ); + } + + let (tints, warn_fg, _, text_disabled) = missing_warning_colors(Mode::Dark, Contrast::Standard, false); + assert_ne!(text_disabled, warn_fg, "disabled ink differs from warning ink"); + assert!(!tints.is_empty(), "a disabled picker still paints its warning icon"); + assert!( + tints.iter().all(|tint| *tint == text_disabled), + "a disabled picker paints its warning icon in text.disabled {text_disabled:?}, not {tints:?}" + ); +} diff --git a/crates/imaging/src/ui/liquify/mod.rs b/crates/imaging/src/ui/liquify/mod.rs index 61e2304eb..708bee7dc 100644 --- a/crates/imaging/src/ui/liquify/mod.rs +++ b/crates/imaging/src/ui/liquify/mod.rs @@ -77,6 +77,7 @@ use craft_ui::dialog::{ FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowTitle, FullWindowView, FullWindowWorkspace, RasterOverlay, WorkspaceCx, WorkspacePass, serde_fields, set_serde_field, }; +use craft_ui::layout::RowAlign; use craft_ui::layout_components::Row; use craft_ui::primitives::Checker; use craft_ui::rails::{LastUsed, ToolRail, ToolSlot}; @@ -462,7 +463,7 @@ impl LiquifyWorkspace { .opened(open) .buttons([FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)]) .footer(|ui, _| { - ui.vertical_centered(|ui| { + let _ = Row::new().fill_width().align(RowAlign::Center).show(ui, |ui, _| { let mut guard = this.borrow_mut(); let work: &mut LiquifyWorkspace = &mut guard; let events = Checkbox::new(Bind::given(work.preview)).label(preview_label.clone()).show(ui).events; diff --git a/crates/menu/src/ribbon/gallery.rs b/crates/menu/src/ribbon/gallery.rs index f26bb2528..d6b93a768 100644 --- a/crates/menu/src/ribbon/gallery.rs +++ b/crates/menu/src/ribbon/gallery.rs @@ -85,6 +85,8 @@ pub struct Gallery<'a, K: Clone + Eq + Hash + Send + Sync + 'static> { caption: CaptionPlace, /// Each shown tile's rect. laid: Vec, + /// The column of stepper buttons, if shown. + column: Rect, picked: Option, menu: Option>, } @@ -118,6 +120,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Gallery<'a, K> { thumb_size: ThumbSize::Medium, caption: CaptionPlace::None, laid: Vec::new(), + column: Rect::NOTHING, picked: None, menu: None, } @@ -131,7 +134,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Gallery<'a, K> { self } - /// One rounded frame on the raised surface around the tiles and the buttons, as the old Word-style ribbon drew + /// One rounded frame on the sunken well surface around the tiles and the buttons, as the old Word-style ribbon drew /// its Styles gallery. pub fn framed(mut self) -> Self { self.framed = true; @@ -509,6 +512,9 @@ pub struct GalleryStyle { frame: (StyleColor, StyleColor, f32), /// The room inside a frame. inset: f32, + /// The stepper buttons column's track fill and divider. + track: StyleColor, + divider: StyleColor, } /// The sizes the gallery's faces measure. @@ -527,8 +533,10 @@ impl Component for Gallery<'_, K> let colors = &cx.tokens.color; GalleryStyle { metrics: Metrics::new().gap(cx.tokens.space.gap.inline), - frame: (cx.color(colors.surface.raised), cx.color(colors.line.control_edge), cx.tokens.shape.radius.control), + frame: (cx.color(colors.surface.sunken), cx.color(colors.line.control_edge), cx.tokens.shape.radius.control), inset: cx.tokens.space.gap.inline, + track: cx.color(colors.surface.panel), + divider: cx.color(colors.line.divider), } } @@ -566,6 +574,7 @@ impl Component for Gallery<'_, K> let buttons = self.buttons(level); let rect = rect.shrink2(Vec2::new(self.inset(cx.style), 0.0)); let (column, rest) = Flow::new(rect, cx.flow.is_rtl()).take_end(if buttons { sizes.button.x } else { 0.0 }); + self.column = if buttons { column } else { Rect::NOTHING }; self.laid.clear(); for at in 0..shown { let cell = rest.span(at as f32 * (sizes.tile.x + sizes.gap), sizes.tile.x); @@ -702,6 +711,18 @@ impl Component for Gallery<'_, K> if !self.buttons(level) { return; } + if self.framed && self.column.is_positive() { + let draw = ui.draw(); + let radius = cx.style.frame.2.round().clamp(0.0, 255.0) as u8; + let track_shape = PaintShape::Rect(self.column, CornerRadius::same(radius)); + draw.fill(&track_shape, cx.style.track); + draw.stroke(&track_shape, craft_ui::primitives::StrokeWidth::Thin, cx.style.divider); + let height = self.column.height() / 3.0; + let y1 = self.column.min.y + height; + let y2 = self.column.min.y + 2.0 * height; + draw.rule(craft_ui::style::RuleKind::Divider, egui::pos2(self.column.left(), y1), egui::pos2(self.column.right(), y1)); + draw.rule(craft_ui::style::RuleKind::Divider, egui::pos2(self.column.left(), y2), egui::pos2(self.column.right(), y2)); + } ui.face(UP, IconButton::new(IconId::new("chevron_up")).label(words.up.clone()).enabled(start > 0)); ui.face(DOWN, IconButton::new(IconId::new("chevron_down")).label(words.down.clone()).enabled(start < last)); ui.face(MORE, IconButton::new(IconId::new("more")).label(words.more.clone())); diff --git a/crates/menu/tests/it/ribbon_gallery.rs b/crates/menu/tests/it/ribbon_gallery.rs index 41061fe14..8314365eb 100644 --- a/crates/menu/tests/it/ribbon_gallery.rs +++ b/crates/menu/tests/it/ribbon_gallery.rs @@ -138,3 +138,56 @@ fn a_wide_captioned_gallery_names_its_tiles_under_wide_pictures() { assert!(name.min.y >= wide.min.y + square.width() / 2.0, "the name {name:?} is under the picture in {wide:?}"); assert!(!plain.iter().any(|(text, _)| text == "Tile 0"), "a plain tile paints no name: {plain:?}"); } + +/// A framed gallery paints a sunken well fill over its bounds, and a panel fill over its stepper button track. +#[trial] +fn a_framed_gallery_paints_sunken_well_and_stepper_track() { + use craft_ui::runtime::env::Env; + use egui::Color32; + + fn fills(shapes: &[egui::Shape], out: &mut Vec<(egui::Rect, egui::Color32)>) { + for shape in shapes { + match shape { + egui::Shape::Vec(inner) => fills(inner, out), + egui::Shape::Rect(rect) => out.push((rect.rect, rect.fill)), + _ => {} + } + } + } + + let colors_and_rect = Rc::new(Cell::new((Rect::NOTHING, Color32::TRANSPARENT, Color32::TRANSPARENT))); + let held = colors_and_rect.clone(); + let mut fixture = Fixture::new(move |ui| { + let [sr, sg, sb, sa] = Env::of(ui).tokens.tokens().color.surface.sunken.0; + let [pr, pg, pb, pa] = Env::of(ui).tokens.tokens().color.surface.panel.0; + let sunken = Color32::from_rgba_unmultiplied(sr, sg, sb, sa); + let panel = Color32::from_rgba_unmultiplied(pr, pg, pb, pa); + + let paint = |_: &ContentPainterCx, _: Rect| {}; + let items: Vec> = + (0..10).map(|at| GalleryItem { key: at, label: Label::from(format!("Tile {at}")), face: GalleryFace::Paint(&paint) }).collect(); + let out = Gallery::new("Styles", &items, None).tiles(6, 3).framed().show(ui); + held.set((out.response.rect, sunken, panel)); + }); + fixture.settle(); + + let (gallery_rect, sunken, panel) = colors_and_rect.get(); + assert!(gallery_rect.is_positive(), "the gallery paints a positive rect"); + + let mut seen = Vec::new(); + fills(&fixture.frame_shapes(), &mut seen); + + assert!( + seen.iter() + .any(|(rect, fill)| *fill == sunken && rect.contains_rect(gallery_rect.shrink(1.0)) && gallery_rect.expand(1.0).contains_rect(*rect)), + "a sunken fill covers the gallery {gallery_rect:?}: {seen:?}" + ); + + let up = fixture.by_label("Previous row").expect("the up button shows"); + let down = fixture.by_label("Next row").expect("the down button shows"); + let more = fixture.by_label("More").expect("the more button shows"); + let column = up.rect.union(down.rect).union(more.rect); + let stepper_track = + seen.iter().find(|(rect, fill)| *fill == panel && rect.contains_rect(column.shrink(1.0)) && gallery_rect.contains_rect(*rect)); + assert!(stepper_track.is_some(), "a panel fill covers the stepper track column {column:?}: {seen:?}"); +} diff --git a/crates/pages/src/layout.rs b/crates/pages/src/layout.rs index ed571bfa7..1189ba99f 100644 --- a/crates/pages/src/layout.rs +++ b/crates/pages/src/layout.rs @@ -7,13 +7,12 @@ //! out), with a markup column beside each page and Hide White Space. [`PageDisplay`] holds both, //! and [`LayoutOptions`] carries each app's switches ([`LayoutOptions::ACROBAT`], //! [`LayoutOptions::WORD`]). The screen spacing ([`PageSpacing`]: gap, margin, side gutter, Hide -//! White Space's pad and seam) is not a constant here: the page view reads it from the `pages.*` -//! size tokens (`PageView::style`), which an app overrides in its `sizes.json` (WordCraft's wider -//! gap and no side gutter). +//! White Space's pad and seam) is not a constant here: the page view derives it from the scope's +//! semantic tokens and `ComponentSet` (`Creative` keeps the tool-rail side gutter; `Productivity` +//! uses a wider gap and matching margin/side without the rail gutter). //! //! ```ignore //! let sizes: Vec = doc.pages.iter().map(|p| p.size()).collect(); -//! let spacing = PageView::style(&tokens).spacing; //! let scale = fit_scale(&sizes, viewport, view.fit, &options, &spacing, view.current).unwrap_or(view.zoom * SCREEN_POINTS_PER_POINT); //! let laid = place_pages(&sizes, scale, viewport, &options, &spacing); //! let shown = if options.continuous { 0..sizes.len() } else { shown_row(sizes.len(), view.current, &options) }; @@ -118,9 +117,9 @@ impl LayoutOptions { } /// The spacing of a page layout: screen points, except [`white_space_pad`](Self::white_space_pad), -/// which is in points at 100 % zoom and is multiplied by the zoom. The page view takes it from the `pages.*` size tokens -/// (`craft_pages::ui::PageView::style`); this crate's core has no tokens, so the layout functions -/// take it as a value. +/// which is in points at 100 % zoom and is multiplied by the zoom. The page view derives it from the +/// scope's semantic tokens and `ComponentSet`; this crate's core has no tokens, so the layout +/// functions take it as a value. #[derive(Clone, Copy, Debug, PartialEq)] pub struct PageSpacing { /// Between pages, and between rows (the page view's gap); unused with diff --git a/crates/pages/src/ui/view.rs b/crates/pages/src/ui/view.rs index 3d4244cb5..59bb08827 100644 --- a/crates/pages/src/ui/view.rs +++ b/crates/pages/src/ui/view.rs @@ -38,6 +38,7 @@ use craft_ui::contract::{Bind, BodyCx, Held, Props as _, Show as _, ShowContaine use craft_ui::primitives::EditorPurpose; use craft_ui::primitives::textures::ThumbSource; use craft_ui::runtime::env::{Env, Label}; +use craft_ui::runtime::focus::EditSet; use craft_ui::runtime::memory::Remember as _; use craft_ui::style::DataColor; use egui::{Rect, Ui, Vec2, pos2}; @@ -338,6 +339,7 @@ pub struct PageView<'a> { describer: Option<&'a dyn AccessDescriber>, paper: DataColor, editor: Option, + inactive_edits: EditSet, snap: Option, tool_regions: Vec, rulers: bool, @@ -362,6 +364,7 @@ impl<'a> PageView<'a> { describer: None, paper, editor: None, + inactive_edits: EditSet::NONE, snap: None, tool_regions: Vec::new(), rulers: false, @@ -404,6 +407,13 @@ impl<'a> PageView<'a> { self } + /// Edit commands the view's editor part cannot act on right now, forwarded to [`Canvas::inactive_edits`]. + #[must_use] + pub fn inactive_edits(mut self, inactive: EditSet) -> Self { + self.inactive_edits = inactive; + self + } + /// The snapping of the coordinates the pointer sets on the view, with its targets in page points. The view places /// them on the pages that show this pass, drops those of pages outside the shown row and passes the result to the /// inner canvas. @@ -455,7 +465,22 @@ impl<'a> PageView<'a> { } fn run(self, ui: &mut Ui, rect: Rect, take_room: bool, mut body: impl FnMut(&mut Ui, &PageBody<'_>)) -> PageViewOutput { - let PageView { label, source, state, options, navigation, bodies, describer, paper, editor, snap, tool_regions, rulers, reach } = self; + let PageView { + label, + source, + state, + options, + navigation, + bodies, + describer, + paper, + editor, + inactive_edits, + snap, + tool_regions, + rulers, + reach, + } = self; let spacing = PageMetrics::new().show_at(ui, Rect::from_min_size(rect.min, Vec2::ZERO)).spacing; let count = source.page_count(); @@ -485,7 +510,7 @@ impl<'a> PageView<'a> { let regions: Vec = tool_regions.iter().filter_map(|region| placed_region(region, &geo, &frame)).collect(); let mut canvas = Canvas::new(label.clone()).view(given).navigation(navigation).keys_to_body(true).tool_regions(regions); if let Some(purpose) = editor { - canvas = canvas.editor(purpose); + canvas = canvas.editor(purpose).inactive_edits(inactive_edits); } if let Some(snap) = &snap { canvas = canvas.snap(placed_snap(snap, &geo, &frame)); diff --git a/crates/pages/src/ui/view/pictures.rs b/crates/pages/src/ui/view/pictures.rs index 3a6d0c0f8..ad9cd40c5 100644 --- a/crates/pages/src/ui/view/pictures.rs +++ b/crates/pages/src/ui/view/pictures.rs @@ -5,6 +5,7 @@ use super::{PageSource, PlacedPage}; use crate::layout::PageSpacing; use crate::ui::access::{AccessDescriber, describe}; use craft_behavior::{Input, Metrics, PixelSize, Sense}; +use craft_theme::ComponentSet; use craft_ui::canvas::DetailPlan; use craft_ui::canvas::PixelRect; use craft_ui::contract::{Access, Common, Component, Cx, DisabledLook, MeasureCx, NoValue, Outcome, PaintUi, Role}; @@ -15,8 +16,12 @@ use craft_ui::runtime::memory::Remember as _; use craft_ui::style::{ComponentStyle, DataColor, StyleCx}; use egui::{Rect, Response, Vec2, pos2}; +/// Productivity inter-page gap as a multiple of `space.gap.section`: 18 pt in Compact (Word's gap) and 24 pt in +/// Comfortable. +const PRODUCTIVITY_GAP_RATIO: f32 = 1.5; + /// The style of the page view's spacing: the gap between pages, the margin, the side column, Hide White Space's pad -/// and its seam, all from the tokens. +/// and its seam, from the tokens and the scope's [`ComponentSet`]. #[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] pub struct PageMetricsStyle { @@ -74,14 +79,26 @@ impl Component for PageMetrics { fn style(cx: &StyleCx<'_>, _: PageMetricsStyleKey) -> PageMetricsStyle { let tokens = cx.tokens; - let pad = tokens.space.pad; - PageMetricsStyle { - metrics: Metrics::new(), - gap: tokens.space.gap.section, - margin: pad.roomy, - side: tokens.size.rail.width, - white_space_pad: tokens.space.gap.inline, - seam: tokens.stroke.thin, + match cx.set() { + ComponentSet::Creative => PageMetricsStyle { + metrics: Metrics::new(), + gap: tokens.space.gap.section, + margin: tokens.space.pad.roomy, + side: tokens.size.rail.width, + white_space_pad: tokens.space.gap.inline, + seam: tokens.stroke.thin, + }, + ComponentSet::Productivity => { + let gap = tokens.space.gap.section * PRODUCTIVITY_GAP_RATIO; + PageMetricsStyle { + metrics: Metrics::new(), + gap, + margin: gap, + side: gap, + white_space_pad: tokens.space.gap.stack, + seam: tokens.stroke.thin, + } + } } } diff --git a/crates/pages/tests/it/views.rs b/crates/pages/tests/it/views.rs index 425a56ccf..8a8f04cd6 100644 --- a/crates/pages/tests/it/views.rs +++ b/crates/pages/tests/it/views.rs @@ -3,18 +3,21 @@ use craft_behavior::geometry::{CropBox, SnapKind, SnapOptions, SnapTarget}; use craft_behavior::kurbo; -use craft_behavior::{Axis, CancelReason, CanvasView}; -use craft_pages::layout::{Fit, LayoutOptions, PageDisplay}; +use craft_behavior::{Axis, CancelReason, CanvasView, EditCommand}; +use craft_pages::layout::{Fit, LayoutOptions, PageDisplay, PagedLayout}; use craft_pages::ui::fixtures::{DemoPages, PAPER}; use craft_pages::ui::{ PagePreview, PageRegion, PageSnap, PageSource, PageView, PageViewState, PageViewWords, PlacedPage, ReadingNav, ReadingState, ReadingView, }; +use craft_theme::ComponentSet; use craft_ui::canvas::{CanvasTool, CropOverlay, ToolAction, ToolContext, ToolHost, ToolPath, ToolPointer}; use craft_ui::contract::{Bind, Role, Show as _}; use craft_ui::primitives::textures::TextureStoreOptions; use craft_ui::primitives::{Draw, EditorPurpose}; +use craft_ui::runtime::commands::{CommandState, EditCommands, resolve}; use craft_ui::runtime::env::Env; +use craft_ui::runtime::focus::EditSet; use craft_ui::testing::{Fixture, pointer, trial}; use egui::{Key, Modifiers, pos2, vec2}; use std::cell::{Cell, RefCell}; @@ -955,3 +958,160 @@ fn go_to_a_point_inside_a_page_puts_it_at_the_top() { assert_eq!(first, Some(5), "the first page in view is the one gone to"); assert!((offset - at).abs() < 0.01, "the view's top {offset} is the point gone to, {at}"); } + +/// Lays out three pages under `set` with `start`, returning the layout and the scope's `space.gap.section` token. +fn layout_in_set(set: ComponentSet, options: LayoutOptions, start: PageViewState, bodies: Option<&'static [(f64, f64)]>) -> (PagedLayout, f32) { + let state = Rc::new(RefCell::new(start)); + let seen: Rc> = Rc::default(); + let (kept, recorded) = (Rc::clone(&state), Rc::clone(&seen)); + let pages = DemoPages::new(3); + let mut fixture = Fixture::new(move |ui| { + let section_gap = Env::of(ui).tokens.space.gap.section; + let mut now = kept.borrow().clone(); + let mut view = PageView::new("Pages", &pages, &mut now, PAPER).options(options); + if let Some(bodies) = bodies { + view = view.bodies(bodies); + } + let out = view.show(ui, |_, _| ()); + *recorded.borrow_mut() = (out.layout, section_gap); + *kept.borrow_mut() = now; + }); + fixture.set(set); + fixture.room(vec2(900.0, 600.0)); + fixture.settle(); + seen.borrow().clone() +} + +/// The productivity component set gives pages a wider inter-page gap, no tool-rail side gutter under Fit Width (without +/// overflowing the viewport), and wider Hide White Space padding than the creative set, while leaving `space.gap.section` +/// untouched for other components. +#[trial] +fn the_component_set_picks_the_page_spacing_without_changing_section_gap() { + let fixed = state_with(|s| { + s.fit = Fit::None; + s.zoom = 1.0; + s.display = PageDisplay::Columns; + }); + let (creative, creative_section) = layout_in_set(ComponentSet::Creative, LayoutOptions::WORD, fixed.clone(), None); + let (productivity, productivity_section) = layout_in_set(ComponentSet::Productivity, LayoutOptions::WORD, fixed, None); + let creative_gap = creative.rects[1].y0 - creative.rects[0].y1; + let productivity_gap = productivity.rects[1].y0 - productivity.rects[0].y1; + assert_eq!(productivity_section, creative_section, "space.gap.section is unchanged by the component set"); + assert!(productivity_gap > creative_gap, "productivity inter-page gap ({productivity_gap}) is wider than creative ({creative_gap})"); + assert!( + productivity.rects[0].y0 > creative.rects[0].y0, + "productivity top margin ({}) is wider than creative ({})", + productivity.rects[0].y0, + creative.rects[0].y0 + ); + + let fit_width = state_with(|s| { + s.fit = Fit::Width; + s.display = PageDisplay::Columns; + }); + let (creative_fit, _) = layout_in_set(ComponentSet::Creative, LayoutOptions::WORD, fit_width.clone(), None); + let (productivity_fit, _) = layout_in_set(ComponentSet::Productivity, LayoutOptions::WORD, fit_width, None); + assert!( + productivity_fit.rects[0].width() > creative_fit.rects[0].width(), + "productivity Fit Width fills more of the viewport ({}) than creative with its rail gutter ({})", + productivity_fit.rects[0].width(), + creative_fit.rects[0].width() + ); + assert!( + productivity_fit.size.width <= 900.0 + 0.5, + "productivity Fit Width stays within the viewport width without horizontal overflow: {}", + productivity_fit.size.width + ); + + const BODIES: [(f64, f64); 3] = [(72.0, 720.0); 3]; + let hidden = state_with(|s| { + s.fit = Fit::None; + s.zoom = 1.0; + s.display = PageDisplay::Single; + s.hide_white_space = true; + }); + let (creative_hidden, _) = layout_in_set(ComponentSet::Creative, LayoutOptions::ACROBAT, hidden.clone(), Some(&BODIES)); + let (productivity_hidden, _) = layout_in_set(ComponentSet::Productivity, LayoutOptions::ACROBAT, hidden, Some(&BODIES)); + assert!( + productivity_hidden.bands[1].0 < creative_hidden.bands[1].0 && productivity_hidden.bands[1].1 > creative_hidden.bands[1].1, + "productivity Hide White Space keeps more pad around the text body: {:?} vs {:?}", + productivity_hidden.bands[1], + creative_hidden.bands[1] + ); +} + +/// Switching the component set updates the page view's inter-page spacing on the frame of the change and settles. +#[trial] +fn a_component_set_change_updates_the_page_view_spacing() { + let state = Rc::new(RefCell::new(state_with(|s| { + s.fit = Fit::None; + s.zoom = 1.0; + s.display = PageDisplay::Columns; + }))); + let gap = Rc::new(Cell::new(0.0_f64)); + let (kept, seen) = (Rc::clone(&state), Rc::clone(&gap)); + let pages = DemoPages::new(3); + let mut fixture = Fixture::new(move |ui| { + let mut now = kept.borrow().clone(); + let out = PageView::new("Pages", &pages, &mut now, PAPER).options(LayoutOptions::WORD).show(ui, |_, _| ()); + seen.set(out.layout.rects[1].y0 - out.layout.rects[0].y1); + *kept.borrow_mut() = now; + }); + fixture.set(ComponentSet::Creative); + fixture.room(vec2(900.0, 600.0)); + fixture.settle(); + let creative_gap = gap.get(); + + fixture.set(ComponentSet::Productivity); + fixture.frame(Vec::new()); + let productivity_gap = gap.get(); + assert!( + productivity_gap > creative_gap, + "switching to productivity widens the page gap on the frame of the change: {productivity_gap} vs {creative_gap}" + ); + fixture.idle(1); + assert_eq!(gap.get(), productivity_gap, "an idle frame after the switch keeps the new gap"); +} + +/// `PageView::inactive_edits` forwards to its inner canvas editor: Cut resolves disabled while inactive and enabled +/// once active, and Undo/Redo fall through to app command states while inactive. +#[trial] +fn page_view_forwards_inactive_edits_to_its_editor_canvas() { + let state = Rc::new(RefCell::new(PageViewState::default())); + let inactive = Rc::new(Cell::new(EditSet::NONE.with(EditCommand::Cut).with(EditCommand::Undo).with(EditCommand::Redo))); + let (kept_state, kept_inactive) = (Rc::clone(&state), Rc::clone(&inactive)); + let pages = DemoPages::new(2); + let mut fixture = Fixture::new(move |ui| { + let mut now = kept_state.borrow().clone(); + PageView::new("Pages", &pages, &mut now, PAPER) + .options(LayoutOptions::ACROBAT) + .editor(EditorPurpose::Text) + .inactive_edits(kept_inactive.get()) + .show(ui, |_, _| ()); + *kept_state.borrow_mut() = now; + }); + fixture.command_state(EditCommands::Cut, CommandState::new().enabled(true)); + fixture.command_state(EditCommands::Undo, CommandState::new().enabled(false)); + fixture.command_state(EditCommands::Redo, CommandState::new().enabled(false)); + fixture.room(vec2(900.0, 600.0)); + fixture.settle(); + + let canvas_rect = fixture.by_role(Role::CANVAS).into_iter().next().expect("a canvas").rect; + fixture.click_at(canvas_rect.center()); + fixture.settle(); + assert!(fixture.focused().is_some(), "clicking the page view focuses its editor canvas"); + + assert!(!resolve(fixture.ctx(), EditCommands::Cut).enabled, "inactive Cut resolves disabled on focused PageView"); + assert!(!resolve(fixture.ctx(), EditCommands::Undo).enabled, "inactive Undo falls through to disabled app state"); + assert!(!resolve(fixture.ctx(), EditCommands::Redo).enabled, "inactive Redo falls through to disabled app state"); + + fixture.command_state(EditCommands::Undo, CommandState::new().enabled(true)); + fixture.command_state(EditCommands::Redo, CommandState::new().enabled(true)); + fixture.settle(); + assert!(resolve(fixture.ctx(), EditCommands::Undo).enabled, "inactive Undo follows enabled app state"); + assert!(resolve(fixture.ctx(), EditCommands::Redo).enabled, "inactive Redo follows enabled app state"); + + inactive.set(EditSet::NONE.with(EditCommand::Undo).with(EditCommand::Redo)); + fixture.settle(); + assert!(resolve(fixture.ctx(), EditCommands::Cut).enabled, "active Cut resolves enabled on focused PageView"); +} diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index 1e4895efe..dea38e038 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -107,7 +107,7 @@ use crate::contract::{ use crate::primitives::{EditorPurpose, ImeStamp}; use crate::runtime::commands::{CommandSet as _, CommandState, Commands as _}; use crate::runtime::env::Label; -use crate::runtime::focus::KeyUse; +use crate::runtime::focus::{EditSet, KeyUse}; use crate::runtime::lock_keys; use crate::runtime::measure; use crate::runtime::motion::{Animate as _, spec}; @@ -217,6 +217,12 @@ pub struct Canvas<'a> { /// does not apply. The body reports its editor state through [`ToolPass::editor`]. #[prop] editor: Option, + /// Edit commands the canvas's editor part cannot act on right now (for instance Cut and Copy with nothing + /// selected, or Undo and Redo with no editor-local history). Applied to [`KeyUse::inactive`] while + /// [`editor`](Self::editor) is set: Cut, Copy, Paste and Select All stay the editor's and resolve disabled; Undo + /// and Redo fall through to the app command's state. Ignored without [`editor`](Self::editor). + #[prop] + inactive_edits: EditSet, /// The editor part's inputs of this pass, taken once in `update`: `tool_pass` is built from a shared `Cx`. editor_input: Arc<[EditorInput]>, /// The rulers' units and zero point, published to the body in its [`CanvasSpace`]. @@ -308,6 +314,7 @@ impl<'a> Canvas<'a> { ruler_output: None, keys_to_body: false, editor: None, + inactive_edits: EditSet::NONE, editor_input: Arc::from([]), pasteboard: PasteboardColor::Default, precise_cursors: false, @@ -825,7 +832,7 @@ impl Component for Canvas<'_> { /// nudges. It still marks its window as showing a document. fn keys(&self) -> KeyUse { match self.editor { - Some(_) => KeyUse::of(Input::Editor).with_chrome_key(true).with_moves(), + Some(_) => KeyUse::of(Input::Editor).with_chrome_key(true).with_moves().with_inactive(self.inactive_edits), None => Self::KEYS, } } diff --git a/crates/ui-canvas/tests/it/canvas/editor.rs b/crates/ui-canvas/tests/it/canvas/editor.rs index 48153ff5f..688d7438a 100644 --- a/crates/ui-canvas/tests/it/canvas/editor.rs +++ b/crates/ui-canvas/tests/it/canvas/editor.rs @@ -2,12 +2,15 @@ //! body through its `ToolPass`. use craft_behavior::kurbo::{Point, Size}; -use craft_behavior::{CanvasView, EditorInput, Proposal, TextPos}; +use craft_behavior::{CanvasView, EditCommand, EditorInput, Proposal, TextPos}; +use craft_ui::buttons::Button; use craft_ui::canvas::{Canvas, tool_pass}; use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; use craft_ui::primitives::{EditorPurpose, EditorState}; use craft_ui::runtime::access::Role; -use craft_ui::runtime::focus; +use craft_ui::runtime::commands::{CommandRef, CommandState, EditCommands, resolve}; +use craft_ui::runtime::focus::{self, EditSet}; +use craft_ui::runtime::frame; use craft_ui::testing::focus::egui_focused; use craft_ui::testing::{Fixture, trial}; use craft_ui::text::TextField; @@ -144,3 +147,69 @@ fn focus_has_answers_for_a_canvas_whose_editor_part_holds_focus() { assert!(focus::has(fixture.ctx(), field_id), "a click on the field moves focus there"); assert!(!focus::has(fixture.ctx(), canvas_id), "and the canvas has it no more"); } + +/// Guards `Canvas::inactive_edits` with an editor part: inactive Cut stays owned by the editor and resolves disabled +/// (even when the app's Cut is enabled), inactive Undo and Redo fall through to app command states and fire the app +/// command while keeping canvas focus, and a separate text field resolves Cut from its own selection independently. +#[trial] +fn inactive_edits_disable_cut_and_let_undo_and_redo_fall_through_to_app_state() { + let inactive = Rc::new(Cell::new(EditSet::NONE.with(EditCommand::Cut).with(EditCommand::Undo).with(EditCommand::Redo))); + let text = Rc::new(RefCell::new("hello".to_owned())); + let ids: Rc>> = Rc::default(); + let (held_inactive, held_text, shown_ids) = (Rc::clone(&inactive), Rc::clone(&text), Rc::clone(&ids)); + let mut fixture = Fixture::new(move |ui| { + let cut = Button::command(EditCommands::Cut).show(ui).id; + let undo = Button::command(EditCommands::Undo).show(ui).id; + let _ = TextField::new("Notes", Bind::bound(&mut *held_text.borrow_mut())).show(ui); + let room = ui.available_rect_before_wrap(); + let view = CanvasView::new(room, Point::new(PAGE.width / 2.0, PAGE.height / 2.0), 1.0); + let output = canvas(view).inactive_edits(held_inactive.get()).show_at(ui, room, |_, _| {}); + shown_ids.set(Some((output.output.response.id, cut, undo))); + }); + fixture.command_state(EditCommands::Cut, CommandState::new().enabled(true)); + fixture.command_state(EditCommands::Undo, CommandState::new().enabled(false)); + fixture.command_state(EditCommands::Redo, CommandState::new().enabled(false)); + fixture.room(ROOM); + fixture.settle(); + + let (canvas_id, cut_id, undo_id) = ids.get().expect("the canvas and buttons showed"); + let canvas_rect = fixture.by_role(Role::CANVAS).into_iter().next().expect("a canvas").rect; + fixture.click_at(canvas_rect.center()); + fixture.settle(); + assert!(focus::has(fixture.ctx(), canvas_id), "the canvas has focus"); + + assert!(!resolve(fixture.ctx(), EditCommands::Cut).enabled, "inactive Cut resolves disabled despite app Cut state"); + assert!(fixture.tree().is_disabled(cut_id), "the Cut button reflects the inactive editor command"); + assert!(!resolve(fixture.ctx(), EditCommands::Undo).enabled, "inactive Undo falls through to disabled app state"); + assert!(!resolve(fixture.ctx(), EditCommands::Redo).enabled, "inactive Redo falls through to disabled app state"); + assert!(fixture.tree().is_disabled(undo_id), "the Undo button is disabled while app Undo is disabled"); + + fixture.command_state(EditCommands::Undo, CommandState::new().enabled(true)); + fixture.command_state(EditCommands::Redo, CommandState::new().enabled(true)); + fixture.settle(); + assert!(resolve(fixture.ctx(), EditCommands::Undo).enabled, "inactive Undo follows enabled app state"); + assert!(resolve(fixture.ctx(), EditCommands::Redo).enabled, "inactive Redo follows enabled app state"); + assert!(!fixture.tree().is_disabled(undo_id), "the Undo button enables with app Undo"); + + frame::take_output(fixture.ctx()); + let undo_node = fixture.by_label("Undo").expect("the Undo button shows"); + fixture.click(&undo_node); + fixture.settle(); + let undo_ref = CommandRef::from(EditCommands::Undo).id; + let fired: Vec = frame::take_output(fixture.ctx()).fired.into_iter().map(|entry| entry.command.id).collect(); + assert!(fired.contains(&undo_ref), "clicking Undo while inactive on the editor fires the app command: {fired:?}"); + assert!(focus::has(fixture.ctx(), canvas_id), "the Undo button press keeps focus on the canvas"); + + inactive.set(EditSet::NONE.with(EditCommand::Undo).with(EditCommand::Redo)); + fixture.settle(); + assert!(resolve(fixture.ctx(), EditCommands::Cut).enabled, "removing Cut from inactive_edits enables Cut"); + assert!(!fixture.tree().is_disabled(cut_id), "the Cut button enables once Cut is active on the editor"); + + let field_rect = fixture.by_role(Role::TEXT_INPUT).into_iter().next().expect("the field").rect; + fixture.click_at(field_rect.center()); + fixture.settle(); + assert!(!resolve(fixture.ctx(), EditCommands::Cut).enabled, "a focused TextField with no selection disables Cut independently"); + fixture.key(Key::A, Modifiers::COMMAND); + fixture.settle(); + assert!(resolve(fixture.ctx(), EditCommands::Cut).enabled, "selecting text in the TextField enables Cut independently"); +} diff --git a/crates/ui-contract/src/contract/body.rs b/crates/ui-contract/src/contract/body.rs index e03be55cb..82d220de4 100644 --- a/crates/ui-contract/src/contract/body.rs +++ b/crates/ui-contract/src/contract/body.rs @@ -166,6 +166,9 @@ pub(super) struct BodyHooks<'b> { /// The container is a row of a vertical flow, not a member of a row's line (`label::in_column`), as its parent /// flow showed it this run: its own measuring run shows its content in a flow of its own. in_column: bool, + /// The container is shown in a cell of an `egui::Grid` (`LabelIn::egui_cell`), as its parent flow showed it this + /// run: its label is decided at its own width. + egui_cell: bool, /// The line just before the container in its flow is a rule (`layout::flow_start`), as its parent flow showed it /// this run: a rule above its header is not drawn, so two rules never follow each other. after_rule: bool, @@ -245,6 +248,7 @@ impl<'b> BodyHooks<'b> { held: false, across: false, in_column: true, + egui_cell: false, after_rule: false, follows_end: false, } diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index bc7dddbaf..93d4f933a 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -297,6 +297,7 @@ impl ShapeHooks for BodyHooks<'_> { self.held = self.held(props, &env); self.across = self.held && matches!(env.column, Some(ColumnSweep::Column(..))); self.in_column = label::in_column(ui); + self.egui_cell = env.egui_cell; self.given.1 |= self.given_room(props, &env, at, ui.ctx(), id); let measured = self.measured_body.unwrap_or(Vec2::ZERO); let body = if self.presence.visible { Vec2::new(measured.x, measured.y * self.presence.t) } else { Vec2::ZERO }; @@ -1289,6 +1290,7 @@ impl BodyHooks<'_> { plan.regions.body.width() }, content_row: false, + egui_cell: self.egui_cell, text: resolved.label_value, side, help: props.help.as_ref(), @@ -1840,6 +1842,7 @@ impl BodyHooks<'_> { self.room.x = width; } self.in_column = label::in_column(at.ui); + self.egui_cell = at.env.egui_cell; // A body that fills the main axis of the body it sits in is measured and shown at its share of it. The first // sweep of that body's measuring run only counts it: its contents run in the second sweep, at the share. let (x, y) = (craft_behavior::Axis::X, craft_behavior::Axis::Y); diff --git a/crates/ui-contract/src/contract/body/size.rs b/crates/ui-contract/src/contract/body/size.rs index 6111db511..fdf9b5084 100644 --- a/crates/ui-contract/src/contract/body/size.rs +++ b/crates/ui-contract/src/contract/body/size.rs @@ -61,6 +61,7 @@ pub(crate) struct EnvFacts { offered: Option, measure: Option, grid: Option, + egui_cell: bool, } impl EnvFacts { @@ -80,6 +81,7 @@ impl EnvFacts { offered: env.offered, measure: env.measure, grid: env.grid, + egui_cell: env.egui_cell, } } } diff --git a/crates/ui-contract/src/contract/cx/context.rs b/crates/ui-contract/src/contract/cx/context.rs index 4d1fc6b8b..efb5f8c60 100644 --- a/crates/ui-contract/src/contract/cx/context.rs +++ b/crates/ui-contract/src/contract/cx/context.rs @@ -419,12 +419,13 @@ impl Under { } /// An env derived for children `PaintUi` builds: the composite's resolved `enabled` and `size`, and only the inside -/// label `under` gives. +/// label `under` gives. The composite places its children itself, so they are in no egui grid's cell. pub(crate) fn child_env(env: &Env, under: &Under) -> Env { env.derive_local(|scoped| { scoped.enabled &= under.enabled; scoped.size = under.size; scoped.inside_label = under.inside.clone().map(|inside| inside as crate::runtime::env::Held); scoped.cell_fills = false; + scoped.egui_cell = false; }) } diff --git a/crates/ui-contract/src/contract/label/place.rs b/crates/ui-contract/src/contract/label/place.rs index f86ab6e67..81aaf4a0f 100644 --- a/crates/ui-contract/src/contract/label/place.rs +++ b/crates/ui-contract/src/contract/label/place.rs @@ -87,7 +87,7 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: let gap = label_gap(env); let indent = after_indent(ctx, env, input, gap); let mut natural = leaf.measure_in(kids, craft_behavior::Proposal::Ideal); - if input.side.layout == FieldLayout::After { + if input.side.layout == FieldLayout::After && !input.egui_cell { // The label takes the room the control and the gap leave, and its detail wraps there. let room = (input.row.width() - indent - input.control_min - gap).max(0.0); if natural.x > room { @@ -95,8 +95,13 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: } } let baseline = leaf.baseline.get(); + // An egui grid's cell is decided at what it needs from its left edge in any direction (`LabelIn::egui_cell`); a + // row grows at its end edge. + let grows = if input.egui_cell { Grows::Cell } else { Grows::End }; if input.side.layout == FieldLayout::Line { - let (cell, rest) = flow.take_end(env.control(input.size).number); + let number = env.control(input.size).number; + let flow = if input.egui_cell { widened(flow, natural.x + gap + number, grows) } else { flow }; + let (cell, rest) = flow.take_end(number); let width = natural.x.min((rest.rect().width() - gap).max(0.0)); let drop = (cell.height() - natural.y).max(0.0) / 2.0; let label = Flow::new(rest.rect(), rtl).align(Vec2::new(width, natural.y), Align::Min, Align::Min).translate(Vec2::new(0.0, drop)); @@ -124,20 +129,19 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: let caption = if matches!(input.side.layout, FieldLayout::Above | FieldLayout::Caption(_)) { column } else { 0.0 }; // The room decides; a beside label gets the width it needs even where last frame's content was narrower. A label // that never sits beside stacks in an unbounded room as well. - let stacks = (input.room < stack_below || stack_below == f32::INFINITY) && !(input.content_row && input.side.layout == FieldLayout::Beside); - // A stacked label has the row's width at most; its name elides there. - let column = if stacks { column.min(input.row.width()) } else { column }; - let flow = if stacks || input.row.width() >= stack_below { - flow - } else { - let mut wide = input.row; - if rtl { - wide.min.x = wide.max.x - stack_below; - } else { - wide.max.x = wide.min.x + stack_below; - } - Flow::new(wide, rtl) + let stacks = (input.room < stack_below || stack_below == f32::INFINITY) + && !((input.content_row || input.egui_cell) && input.side.layout == FieldLayout::Beside); + // A stacked label has the row's width at most, where its name elides; in an egui grid's cell it keeps its own. + let column = if stacks && !input.egui_cell { column.min(input.row.width()) } else { column }; + // A beside label that does not stack takes its column, the gap and the control's least, past the row's end where + // the row is narrower. An egui grid's cell is as wide as its label and control need, whatever the layout. + let need = match input.side.layout { + FieldLayout::After if input.egui_cell => indent + input.control_min + gap + natural.x, + _ if input.egui_cell && stacks => column.max(input.control_min), + _ if stacks => 0.0, + _ => stack_below, }; + let flow = widened(flow, need, grows); if input.side.layout == FieldLayout::After { let flow = if indent > 0.0 { flow.take_start(indent).1 } else { flow }; @@ -162,6 +166,29 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: } } +/// How a flow takes the width its label and control need (`widened`). +#[derive(Clone, Copy)] +enum Grows { + /// A flow that is too narrow grows at its end edge: the left one under RTL. + End, + /// An egui grid's cell: exactly as wide as they need from its left edge, in either direction, narrowed as well as + /// widened. egui offers a grid's last column the rest of the room, where the control would sit at its far edge + /// under RTL. + Cell, +} + +/// `flow` widened to `need` as `grows` says. +fn widened(flow: Flow, need: f32, grows: Grows) -> Flow { + let mut wide = flow.rect(); + match grows { + Grows::Cell => wide.max.x = wide.min.x + need, + Grows::End if wide.width() >= need => return flow, + Grows::End if flow.is_rtl() => wide.min.x = wide.max.x - need, + Grows::End => wide.max.x = wide.min.x + need, + } + Flow::new(wide, flow.is_rtl()) +} + /// The gap between a label and its control: `space.gap.inline`, `space.gap.item` inside a bar. pub(crate) fn label_gap(env: &Env) -> f32 { let gaps = &env.tokens.space.gap; diff --git a/crates/ui-contract/src/contract/label/step.rs b/crates/ui-contract/src/contract/label/step.rs index e9126f28b..41ca65e0c 100644 --- a/crates/ui-contract/src/contract/label/step.rs +++ b/crates/ui-contract/src/contract/label/step.rs @@ -32,6 +32,10 @@ pub(crate) struct LabelIn<'a> { /// The row sits in a column that takes its width from its content: a beside label never stacks for want of room, /// since the column is as wide as the label, the gap and the control need. pub content_row: bool, + /// The row is a cell of an `egui::Grid` (`LeafLabel::egui_cell`): the row is as wide as its label and control need, + /// so the label neither wraps nor stacks for want of room, and the row is that wide from its left edge in any + /// direction. + pub egui_cell: bool, pub text: &'a Label, pub side: &'a SideLabel, /// The help line the container's footer shows; it joins the control's description with the label's detail. @@ -39,6 +43,7 @@ pub(crate) struct LabelIn<'a> { pub enabled: bool, pub size: craft_theme::ControlSize, /// The narrowest the control can be; a row too narrow for the label column, the gap and this stacks the label above. + /// In an egui grid's cell (`egui_cell`), the width the control takes there: a leaf's ideal width. pub control_min: f32, /// The control is a leaf child shown in the flow with its label after it, not a field's body. pub leaf: bool, @@ -82,6 +87,10 @@ pub(crate) struct LeafLabel<'a> { pub parent: Option, /// The row the label and the child share. pub row: Rect, + /// The row is a cell of an `egui::Grid` (`Scoped::egui_cell`): egui places it from the cell's left edge in any + /// direction, and gives the column the width it takes from the next frame. `row` then gives only the cell's left + /// edge, top and height. + pub egui_cell: bool, pub text: &'a Label, pub side: &'a SideLabel, /// What the child inherits (`leaf_under`). @@ -117,7 +126,9 @@ impl LeafPlaced { pub(crate) fn decide_leaf(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &mut C, trailing: Vec2) -> Decided { // Read before the child measures: nothing it does there may count as a child placed in flow. let in_column = in_column(ui); - let control_min = crate::contract::run::measure_under(child, &*ui, Some(at.id), craft_behavior::Proposal::Min, Some(at.under)).x; + // An egui grid's cell is as wide as the row takes, and the control shows at its ideal width there. + let proposal = if at.egui_cell { craft_behavior::Proposal::Ideal } else { craft_behavior::Proposal::Min }; + let control_min = crate::contract::run::measure_under(child, &*ui, Some(at.id), proposal, Some(at.under)).x; let facts = LeafFacts { control_min, in_column, claims: C::LABELLED_AFTER }; decide_step(ui, env, &leaf_input(env, at, at.row, facts, trailing)) } @@ -148,6 +159,7 @@ fn leaf_input<'a>(env: &Env, at: &LeafLabel<'a>, row: Rect, facts: LeafFacts, tr row, room: row.width(), content_row: env.content.0, + egui_cell: at.egui_cell, text: at.text, side: at.side, help: None, @@ -392,20 +404,25 @@ fn flow_leaf_row( // grid's cell or a horizontal layout. The row spans the room's own edges: a room that scrolls along x is unbounded // at its start edge, the left one under RTL. let row = Rect::from_min_max(avail.min, egui::pos2(avail.max.x, avail.min.y + ideal.y)); - let at = LeafLabel { id, owner, parent: None, row, text: &label, side: &side, under: &under }; + // An `egui::Grid` offers a column with no width from the last frame its least cell width, where the label would + // wrap and keep the column that narrow: in its cell the label is decided at its own width. + let egui_cell = env.egui_cell; + let at = LeafLabel { id, owner, parent: None, row, egui_cell, text: &label, side: &side, under: &under }; let decided = decide_leaf(ui, &env, &at, &mut child, trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size)); // In a column that sizes from its content the row is the label plus the control, never the room around them. // A row of a horizontal flow is as wide as its label and control: the room it has there is unbounded. // So is a grid's cell: the room before it is the whole grid's, and a row spanning it measures its column as wide - // as the grid, so the grid could never set two such cells beside each other (two columns of check boxes). - let content = env.content.0 || ui.layout().is_horizontal() || in_cell; + // as the grid, so the grid could never set two such cells beside each other (two columns of check boxes). An egui + // grid's cell is too, also inside a scope of its own there. + let content = env.content.0 || ui.layout().is_horizontal() || in_cell || egui_cell; let control_width = if content { decided.control().width().min(ideal.x) } else { decided.control().width() }; let rtl = env.direction.is_rtl(); let span = |cell: Rect| Flow::new(Rect::from_min_size(cell.min, Vec2::new(cell.width(), ideal.y)), rtl).span(0.0, control_width); let (decided_control, decided_label) = (span(decided.control()), decided.label()); + // An egui grid's cell takes its extent from its left edge in any direction. let extent = if !content { avail.width() - } else if rtl { + } else if rtl && !egui_cell { avail.max.x - decided_control.min.x.min(decided_label.min.x) } else { decided_control.max.x.max(decided_label.max.x) - avail.min.x diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index bb622ea9f..f5d4ab15d 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -172,8 +172,10 @@ impl Lazy { open_record(&ctx, audited.is_some()); } 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. - let out = layout_memory::boundary(&ctx, false, || add(&mut child, &mut run)); + // 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 + // line, cells and shrink step, and a memoized view starts its own room on top of it. + let out = layout_memory::boundary(&ctx, false, || Env::run_in(&mut child, env, |child| add(child, &mut run))); let rect = child.min_rect(); // The child `Ui` writes its widget rect when it drops: the record holds it as written. drop(child); diff --git a/crates/ui-contract/src/contract/mount.rs b/crates/ui-contract/src/contract/mount.rs index fc2e44b89..8f90ce438 100644 --- a/crates/ui-contract/src/contract/mount.rs +++ b/crates/ui-contract/src/contract/mount.rs @@ -158,7 +158,9 @@ impl Host for PaneHost { _ => builder, }; let mut ui = crate::runtime::egui::alloc::child(parent, builder); - pass(&mut ui, Some(ShowAt::Flow), None); + // A layout room of its own, as a docked pane's. + let room = env.new_room(); + Env::run_in(&mut ui, room.clone(), |ui| pass(ui, Some(ShowAt::Flow), Some(&room))); crate::runtime::egui::alloc::advance_past(parent, ui.min_rect()); } else { pass(parent, Some(ShowAt::Rect(rect)), None); diff --git a/crates/ui-contract/src/contract/pages.rs b/crates/ui-contract/src/contract/pages.rs index 28c7b0916..02d0fb37f 100644 --- a/crates/ui-contract/src/contract/pages.rs +++ b/crates/ui-contract/src/contract/pages.rs @@ -3,6 +3,7 @@ use crate::layout::flow_region; use crate::runtime::egui::alloc; +use crate::runtime::env::Env; use crate::runtime::layout_memory; use crate::runtime::lazy; use crate::runtime::memory::sub; @@ -42,6 +43,8 @@ impl<'a, K: Hash + PartialEq> Pages<'a, K> { let base = sub(ui.scope_id(), ("pages", self.salt)); let region = flow_region(ui); let layout = *ui.layout(); + // Each page runs in the env of `ui`, as the direct children of the body around it. + let env = Env::of(ui); let hidden = self.pages.iter().filter(|key| *key != self.current).fold(Vec2::ZERO, |largest, key| { let id = sub(base, hash(key)); let kept = lazy::measured(&ctx, id).map(|(size, reads)| { @@ -59,7 +62,7 @@ impl<'a, K: Hash + PartialEq> Pages<'a, K> { layout_memory::boundary(&ctx, true, || { let room = Rect::from_min_size(region.min, Vec2::new(region.width(), f32::INFINITY)); let mut child = alloc::child(ui, UiBuilder::new().max_rect(room).layout(layout).scope_id(id).sizing_pass().invisible()); - page(&mut child, key); + Env::run_in(&mut child, env.clone(), |child| page(child, key)); child.min_rect().size() }) }); @@ -72,7 +75,7 @@ impl<'a, K: Hash + PartialEq> Pages<'a, K> { let id = sub(base, hash(self.current)); let mut child = alloc::child(ui, UiBuilder::new().max_rect(region).layout(layout).scope_id(id)); child.set_min_size(hidden.min(region.size())); - let out = page(&mut child, self.current); + let out = Env::run_in(&mut child, env, |child| page(child, self.current)); let rect = child.min_rect(); drop(child); // What the place took comes from the hidden pages' measures as well as from the shown page's components. diff --git a/crates/ui-contract/src/contract/paint_ui.rs b/crates/ui-contract/src/contract/paint_ui.rs index f60372b59..5ad18430c 100644 --- a/crates/ui-contract/src/contract/paint_ui.rs +++ b/crates/ui-contract/src/contract/paint_ui.rs @@ -163,7 +163,7 @@ impl PaintUi<'_> { let env = Env::of(self.ui); let mut child = child; let under = label::leaf_under(&env, &side, &child, (self.enabled, self.size)); - let at = LeafLabel { id, owner: self.id, parent: Some(self.id), row: rect, text: &label, side: &side, under: &under }; + let at = LeafLabel { id, owner: self.id, parent: Some(self.id), row: rect, egui_cell: false, text: &label, side: &side, under: &under }; let ctx = self.ui.ctx().clone(); layout_memory::boundary(&ctx, true, || { let placed = crate::layout::ColumnGroup::field(&mut *self.ui, |ui| label::leaf(ui, &env, &at, &mut child, None)); @@ -183,12 +183,14 @@ impl PaintUi<'_> { fn child_with(&mut self, id: Id, rect: Rect, child: C, tip: Option>, inside: Option>) -> C::Output { let scope = sub(self.id, "children"); let parent = &mut *self.ui; + // The kids' `Ui` holds no entry of its own: they inherit the env of the composite's `Ui`. + let outer = Env::of(parent); let kids = self.kids.get_or_insert_with(|| { let builder = egui::UiBuilder::new().layout(child::pinned_layout()).scope_id(scope).max_rect(self.rect); alloc::child(parent, access::with_parent(builder, self.id)) }); let ctx = kids.ctx().clone(); - let env = super::cx::child_env(&Env::of(kids), &super::cx::Under { enabled: self.enabled, size: self.size, inside }); + let env = super::cx::child_env(&outer, &super::cx::Under { enabled: self.enabled, size: self.size, inside }); // A child shown while the owner's fade runs lies under the owner's veil, so a faded child adds none of its own. let env = match self.fade { Some(_) => { diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index f65e44ecc..419419b6c 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -92,7 +92,10 @@ impl BodyLayout { BodyLayout::Row { wrap: false, align: RowAlign::Start } } - /// Children row-major over `columns`: a `'static` slice, or columns built in the pass. + /// Children row-major over `columns`: a `'static` slice, or columns built in the pass. The cells are the body's + /// craft children: an egui container shown in the body is no cell, and egui places it below the cells placed so + /// far. The rows after it are placed over it: show it as the last child, or put it in a craft body (`Row`), which + /// takes a cell. pub fn grid(columns: impl Into>) -> Self { BodyLayout::Grid { columns: columns.into(), fit: GridFit::Stack, cells: CellAlign::Center } } @@ -521,13 +524,13 @@ pub fn levelled_unit(ui: &mut Ui, key: Id, levels: usize, mut show: impl FnMut(& }); let width = ui.max_rect().width(); for level in 0..levels.max(1) { - let installed = Env::install_for(ui, no_room.clone()); // Every level shows the same bodies under the same ids: each measures as a probe, so no level reuses a // record another level left, and none serves the sweep at the levels given, which records its own. let (_, took) = layout_memory::probing(&ctx, || { - crate::runtime::egui::sizing::run_sized(ui, width, child::column_layout(rtl), |ui| show(ui, level)) + crate::runtime::egui::sizing::run_sized(ui, width, child::column_layout(rtl), |ui| { + Env::run_in(ui, no_room.clone(), |ui| show(ui, level)) + }) }); - Env::restore(&ctx, installed); if level == 0 { widest = took; } @@ -889,7 +892,7 @@ fn run_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::Layo return inner; } if !shares_along(env, axis) { - return child::block(ui, None, layout, body).0; + return child::block(ui, None, layout, |ui| Env::run_in(ui, env.clone(), body)).0; } let key = sub(id, "share"); child::block(ui, None, layout, |ui| { @@ -943,7 +946,7 @@ fn measure_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui:: let ctx = ui.ctx().clone(); let in_child = |ui: &mut Ui, body: &mut dyn FnMut(&mut Ui) -> R| { let mut child = laid_out_child(ui, layout); - let inner = body(&mut child); + let inner = Env::run_in(&mut child, env.clone(), body); (inner, child.min_rect()) }; if !shares_along(env, axis) { @@ -1158,10 +1161,12 @@ impl Spread { fn run_spread(ui: &mut Ui, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut(&mut Ui) -> R) -> (R, Option) { let ctx = ui.ctx().clone(); let layout = child::row_layout(rtl, false); - let sweep = |ui: &mut Ui, last: Option, leasts: Vec, probe: bool, body: &mut dyn FnMut(&mut Ui) -> R| { + let env = Env::of(ui); + let sweep = |ui: &mut Ui, env: &Env, last: Option, leasts: Vec, probe: bool, body: &mut dyn FnMut(&mut Ui) -> R| { let flow = Flow::new(ui.available_rect_before_wrap(), rtl); pass_state::with::(&ctx, |cursors| cursors.0.insert(id, Cursor::Spread(Spread::new(flow, gap, last, leasts, probe)))); - let inner = body(ui); + // The children run in the sweep's own `Ui`: the row's env is installed for it, so they are its direct children. + let inner = Env::run_in(ui, env.clone(), body); let spread = match pass_state::with::(&ctx, |cursors| cursors.0.remove(&id)) { Some(Cursor::Spread(spread)) => Some(spread), _ => None, @@ -1174,13 +1179,13 @@ fn run_spread(ui: &mut Ui, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut( let count = this_pass(&ctx, false, leasts_id).map_or(0, |count| count.x as usize); let leasts = (0..count).map(|i| this_pass(&ctx, false, sub(id, ("least", i))).map_or(0.0, |least| least.x)).collect(); let last = this_pass(&ctx, false, id); - let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, last, leasts, false, body)).0; + let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, &env, last, leasts, false, body)).0; return (inner, natural(&spread)); } let room = ui.available_rect_before_wrap().size(); let ((inner, spread), rect, short) = crate::contract::keeping_ids(&ctx, || { let mut first = ui.new_child(egui::UiBuilder::new().layout(layout)); - let (inner, spread) = sweep(&mut first, None, Vec::new(), false, body); + let (inner, spread) = sweep(&mut first, &env, None, Vec::new(), false, body); // Half a point: less than a pixel shows at any scale the box runs. let short = spread.as_ref().is_some_and(|spread| spread.count >= 2 && room.x.is_finite() && spread.natural > room.x + 0.5); (((inner, spread), first.min_rect(), short), short) @@ -1188,21 +1193,19 @@ fn run_spread(ui: &mut Ui, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut( let (inner, spread, leasts) = if short { #[cfg(feature = "testing")] measure::count_least(&ctx, id); - let probe = Env::of(ui).derive_local(|scoped| { + let probe = env.derive_local(|scoped| { scoped.unbounded.0 = true; scoped.least = true; }); let leasts = crate::contract::keeping_ids(&ctx, || { let leasts = layout_memory::probing(&ctx, || { let mut least = ui.new_child(egui::UiBuilder::new().layout(layout)); - let installed = Env::install_for(&least, probe.clone()); - let (_, spread) = sweep(&mut least, None, Vec::new(), true, body); - Env::restore(&ctx, installed); + let (_, spread) = sweep(&mut least, &probe, None, Vec::new(), true, body); spread.map_or_else(Vec::new, |spread| spread.widths) }); (leasts, true) }); - let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, None, leasts.clone(), false, body)).0; + let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, &env, None, leasts.clone(), false, body)).0; (inner, spread, leasts) } else { ui.advance_cursor_after_rect(rect); diff --git a/crates/ui-contract/src/layout/slot.rs b/crates/ui-contract/src/layout/slot.rs index 79e573ffb..e4f26734b 100644 --- a/crates/ui-contract/src/layout/slot.rs +++ b/crates/ui-contract/src/layout/slot.rs @@ -7,6 +7,7 @@ use egui::{Ui, Vec2}; /// Runs `body` in an invisible sizing pass `width` wide and returns the size it took. Nothing is allocated in /// `ui` and nothing is painted; the closure sees the env of `ui`. pub fn measure_slot(ui: &mut Ui, width: f32, body: impl FnOnce(&mut Ui)) -> Vec2 { - let rtl = Env::of(ui).direction.is_rtl(); - sizing::run_sized(ui, width, child::column_layout(rtl), body).1 + let env = Env::of(ui); + let rtl = env.direction.is_rtl(); + sizing::run_sized(ui, width, child::column_layout(rtl), |ui| Env::run_in(ui, env, body)).1 } diff --git a/crates/ui-contract/src/primitives/text_adapter.rs b/crates/ui-contract/src/primitives/text_adapter.rs index e9c7866fb..66e1cbf41 100644 --- a/crates/ui-contract/src/primitives/text_adapter.rs +++ b/crates/ui-contract/src/primitives/text_adapter.rs @@ -518,13 +518,13 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut _ => {} } } + let env = crate::runtime::env::Env::of(input.ui); let multiline = input.options.multiline(); let scroll = if multiline { scroll_before(ctx, widget) } else { 0.0 }; let filter = egui_focus::event_filter(input.keys.keep, false); // A single line sits on the baseline of its control's line, whatever its face: a number field's mono digits on // the body text's. let baseline = (!input.options.multiline()).then(|| { - let env = crate::runtime::env::Env::of(input.ui); let text_env = super::text::TextEnv { tokens: &env.tokens, direction: env.direction, ink: input.ink, fonts: crate::fonts::stack_facts(ctx) }; super::text::line_baseline(ctx, &text_env, input.options.role, input.rect.center().y) }); @@ -557,7 +557,7 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut // egui's widget moves the caret to any press, so the selection from before the press is put back. let secondary = crate::runtime::pointer::frame_raw(ctx).press.is_some_and(|press| press.button == craft_behavior::PointerButton::Secondary); let kept = selection(ctx, widget).filter(|(caret, anchor)| secondary && caret != anchor); - let shown = text_edit::show(input.ui, edit); + let shown = text_edit::show(input.ui, &env, edit); crate::runtime::pointer::record_text_widget(ctx, widget, input.id); if let Some((caret, anchor)) = kept && selection(ctx, widget).is_some_and(|(at, _)| (caret.min(anchor)..=caret.max(anchor)).contains(&at)) @@ -644,6 +644,7 @@ pub(crate) fn show_selectable(ui: &mut Ui, text: Selectable<'_>) { let multiline = run.wrap == crate::primitives::Wrap::Wrap; let keep = if multiline { KeepKeys::BlockArrows } else { KeepKeys::InlineArrows }; let mut shown = layout.full().to_owned(); + let env = crate::runtime::env::Env::of(ui); // A line longer than its room is cut at the room's edge, as a field's is. let mut cut = (layout.size().x > rect.width()).then(|| { let mut cut = crate::runtime::egui::alloc::child(ui, egui::UiBuilder::new().max_rect(rect)); @@ -652,6 +653,7 @@ pub(crate) fn show_selectable(ui: &mut Ui, text: Selectable<'_>) { }); text_edit::show( cut.as_mut().unwrap_or(&mut *ui), + &env, text_edit::Edit { id: widget, rect: layout.galley.rect.translate(at.to_vec2()), diff --git a/crates/ui-contract/src/runtime/egui/child.rs b/crates/ui-contract/src/runtime/egui/child.rs index 9831d7b7e..19aef6e35 100644 --- a/crates/ui-contract/src/runtime/egui/child.rs +++ b/crates/ui-contract/src/runtime/egui/child.rs @@ -43,10 +43,14 @@ pub(crate) fn column_layout(right_to_left: bool) -> Layout { stack_layout(right_to_left) } -/// Runs `body` in a child `Ui`. `disabled` disables the child and everything below it. `direction` gives the -/// child a cloned style carrying that direction and an explicit layout, never the parent's. -pub(crate) fn scope(ui: &mut Ui, disabled: bool, direction: Option, body: impl FnOnce(&mut Ui) -> R) -> R { +/// Runs `body` in a child `Ui`, with the id salt `id_salt` when given. `disabled` disables the child and everything +/// below it. `direction` gives the child a cloned style carrying that direction and an explicit layout, never the +/// parent's. +pub(crate) fn scope(ui: &mut Ui, id_salt: Option, disabled: bool, direction: Option, body: impl FnOnce(&mut Ui) -> R) -> R { let mut builder = UiBuilder::new(); + if let Some(salt) = id_salt { + builder = builder.id_salt(salt); + } if let Some(right_to_left) = direction { let mut style = (**ui.style()).clone(); style.right_to_left = right_to_left; diff --git a/crates/ui-contract/src/runtime/egui/stack.rs b/crates/ui-contract/src/runtime/egui/stack.rs index 71d3bea9a..e5cff8766 100644 --- a/crates/ui-contract/src/runtime/egui/stack.rs +++ b/crates/ui-contract/src/runtime/egui/stack.rs @@ -1,13 +1,29 @@ //! `UiStack` walks for `Env::of`. -use egui::{Id, Ui}; +use egui::{Id, Ui, UiKind}; /// The unique id of `ui`'s stack node: the key env entries are installed under. pub(crate) fn node_id(ui: &Ui) -> Id { ui.stack().unique_id } +/// What `nearest` found walking from a `Ui` outwards. +pub(crate) struct Found { + /// The first value found, and whether it was found for the `Ui`'s own node. + pub value: Option<(T, bool)>, + /// The walk passed the `Ui` of an `egui::Grid` (`UiKind::Grid`) before the node the value was found for, or + /// anywhere on the stack when none was found. + pub grid: bool, +} + /// The first value `lookup` finds walking from `ui` outwards, by the stack nodes' unique ids. -pub(crate) fn nearest(ui: &Ui, lookup: impl Fn(Id) -> Option) -> Option { - ui.stack().iter().find_map(|node| lookup(node.unique_id)) +pub(crate) fn nearest(ui: &Ui, lookup: impl Fn(Id) -> Option) -> Found { + let mut grid = false; + for (depth, node) in ui.stack().iter().enumerate() { + if let Some(value) = lookup(node.unique_id) { + return Found { value: Some((value, depth == 0)), grid }; + } + grid |= node.kind() == Some(UiKind::Grid); + } + Found { value: None, grid } } diff --git a/crates/ui-contract/src/runtime/egui/text_edit.rs b/crates/ui-contract/src/runtime/egui/text_edit.rs index 7a432c2b6..300e08ea4 100644 --- a/crates/ui-contract/src/runtime/egui/text_edit.rs +++ b/crates/ui-contract/src/runtime/egui/text_edit.rs @@ -65,8 +65,8 @@ pub(crate) struct Shown { pub content: f32, } -/// Runs the widget at `edit.rect`. -pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown { +/// Runs the widget at `edit.rect`, under `env`, the env of the `Ui` the caller shows the field in. +pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>) -> Shown { let Edit { id, rect, @@ -93,7 +93,6 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown { scroll, } = edit; // The same font and optical size as a label of the same role: one text path. - let env = crate::runtime::env::Env::of(ui); let tokens = &env.tokens; // Behind selected text and the selected text itself: the field's roles. let selection = (tokens.color.accent.soft, tokens.color.text.normal); @@ -177,7 +176,7 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown { super::style::disable_without_fade(ui); } // The placeholder is the faint text colour, the disabled one when the field is off. - let text_colors = &crate::runtime::env::Env::of(ui).tokens.color.text; + let text_colors = &tokens.color.text; super::style::set_hint_color(ui, crate::style::rgba_color(if enabled { text_colors.faint } else { text_colors.disabled })); super::style::set_text_cursor(ui, caret_visible); super::style::set_text_selection(ui, crate::style::rgba_color(selection.0), crate::style::rgba_color(selection.1)); diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 9708a392e..9c1cd92ef 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -90,6 +90,7 @@ pub(crate) struct Flow { unbounded: (bool, bool), cell_fills: bool, fits: bool, + egui_cell: bool, } /// The values of an env. @@ -216,6 +217,12 @@ pub struct Scoped { /// The scope is the body of a beside label in an inspector (`LabelScheme::Inspector`): the control shown there /// fills the width the label leaves. Only that control sees it, as with `inside_label`. pub(crate) cell_fills: bool, + /// The scope lays out in a cell of an `egui::Grid` that egui code made below the body around it: the grid places + /// each child from its cell's left edge in any direction, and gives the column the width the child takes from the + /// next frame. `Env::of` sets it where the stack between a `Ui` and its entry holds a grid's `Ui`; a scope that + /// passes `Env::of` on (`with_env`, `Lazy`, a memoized view) keeps it, and a body (`start_room`) or a component's + /// children (`child_env`) end it. + pub(crate) egui_cell: bool, } /// The values of an env that a scope rarely changes: the resolved tokens, the platform, the language and the app's @@ -416,7 +423,8 @@ impl Scoped { /// Ends the layout room of the enclosing body: its flow grid and content column. The axes the body sizes from its /// content stay (`content`): like `cell_fills` and `least`, they say what a child that fills takes there, its - /// measured size or the room, and the place of a memoized view holds them (`flow`). + /// measured size or the room, and the place of a memoized view holds them (`flow`). `has_room` checks the same set, + /// and `Env::of` ends it for a `Ui` below the one an entry was installed for. pub(crate) fn start_room(&mut self) { self.grid = None; self.grid_top = false; @@ -432,10 +440,30 @@ impl Scoped { self.shrink = None; self.column = None; self.offered = None; + self.egui_cell = false; + } + + /// Whether any of the facts `start_room` ends is set, besides `egui_cell`, which `Env::of` sets. + fn has_room(&self) -> bool { + self.grid.is_some() + || self.grid_top + || self.content_column + || self.given_column + || self.row_room.is_some() + || self.row_line.is_some() + || self.first_line.is_some() + || self.flow_body.is_some() + || self.column_row + || self.fill_body.is_some() + || self.fill_share.is_some() + || self.shrink.is_some() + || self.column.is_some() + || self.offered.is_some() } /// Starts the layout room of a memoized view's content (`start_room`), keeping whether the enclosing body is a - /// content-sized or a given column, as `start_room` keeps the content axes. The view's content then measures and + /// content-sized or a given column and whether the view lies in an egui grid's cell, as `start_room` keeps the + /// 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 @@ -444,9 +472,9 @@ impl Scoped { pub(crate) fn start_view_room(&mut self) { let fits = self.view_fits(); let row_unit = matches!(self.shrink, Some(Shrink::Count(_) | Shrink::Least(_) | Shrink::Apply(_))); - let (content_column, given_column) = (self.content_column, self.given_column); + let (content_column, given_column, egui_cell) = (self.content_column, self.given_column, self.egui_cell); self.start_room(); - (self.content_column, self.given_column) = (content_column, given_column); + (self.content_column, self.given_column, self.egui_cell) = (content_column, given_column, egui_cell); if fits { self.shrink = Some(Shrink::Fit); } @@ -505,6 +533,7 @@ impl Scoped { unbounded: self.unbounded, cell_fills: self.cell_fills, fits: self.view_fits(), + egui_cell: self.egui_cell, } } @@ -656,6 +685,7 @@ impl Env { item_facts: None, inside_label: None, cell_fills: false, + egui_cell: false, }), } } @@ -663,14 +693,33 @@ impl Env { /// The env of `ui`: the nearest entry up the `Ui` stack, else the running viewport's root env, so the `Ui` /// of an egui `Area` or `Window` reads the app's root values. For app panels (layer 8) and caller closures only. /// + /// What a body sets up for the children it places in flow (`Scoped::start_room`: its `Grid` or spread row's cells, + /// its unwrapped row's line and shrink step, its flow start, its content column) is for its direct children, which + /// it shows in the `Ui` it installed its env for. A `Ui` egui code makes below that one (an `egui::Grid`, + /// `ui.horizontal`, `ui.push_id` in a caller's closure) lays out its own children: an entry found for an ancestor + /// of `ui` comes without those facts, so a component there takes no cell, line or shrink step of the body around it. + /// Where that stack holds an `egui::Grid`'s `Ui`, the env says the component lays out in the grid's cell + /// (`Scoped::egui_cell`). + /// /// While apps still use `add_enabled_ui`, it also ANDs `ui.is_enabled()`, outside sizing passes. pub fn of(ui: &Ui) -> Env { let ctx = ui.ctx(); let viewport = pass::current_viewport(ctx); - let found = PerViewport::::with(ctx, viewport, |envs| { - stack::nearest(ui, |node| envs.entries.get(&node).cloned()).or_else(|| envs.root.clone()) + // The root env stands for an entry above the whole stack. + let (found, grid) = PerViewport::::with(ctx, viewport, |envs| { + let stack::Found { value, grid } = stack::nearest(ui, |node| envs.entries.get(&node).cloned()); + (value.or_else(|| envs.root.clone().map(|env| (env, false))), grid) }); - let env = found.unwrap_or_else(|| Env::from_root(ctx, &RootEnv::fallback(ctx), None, scale::pixels_per_point(ctx))); + let (env, own) = found.unwrap_or_else(|| (Env::from_root(ctx, &RootEnv::fallback(ctx), None, scale::pixels_per_point(ctx)), false)); + let egui_cell = env.egui_cell || grid; + let env = if own || !(env.scoped.has_room() || egui_cell != env.egui_cell) { + env + } else { + env.derive_local(|scoped| { + scoped.start_room(); + scoped.egui_cell = egui_cell; + }) + }; // egui's `invisible()` also disables the `Ui`, and a sizing `Ui` is invisible, not disabled: in a sizing pass // the env keeps the enabled state the real run has, so a memoized view keys alike in both. if style::is_enabled(ui) || ui.is_sizing_pass() { env } else { env.derive_local(|s| s.enabled = false) } @@ -772,6 +821,14 @@ impl Env { Installed { viewport, node, previous } } + /// Runs `body` in `ui` with `env` installed for it, and puts back what the install replaced, also when `body` + /// panics. A body runs its direct children this way in a `Ui` it makes for them. + pub(crate) fn run_in(ui: &mut Ui, env: Env, body: impl FnOnce(&mut Ui) -> R) -> R { + let ctx = ui.ctx().clone(); + let _restore = Restore { ctx: &ctx, installed: Some(Env::install_for(ui, env)) }; + body(ui) + } + /// Puts back the entry `install_for` replaced. pub(crate) fn restore(ctx: &Context, installed: Installed) { PerViewport::::with(ctx, installed.viewport, |envs| match installed.previous { diff --git a/crates/ui-contract/src/runtime/env/overrides.rs b/crates/ui-contract/src/runtime/env/overrides.rs index cb9e7d2c4..ab64df1e3 100644 --- a/crates/ui-contract/src/runtime/env/overrides.rs +++ b/crates/ui-contract/src/runtime/env/overrides.rs @@ -128,6 +128,8 @@ pub struct Overrides { pub words: Option, /// App values set for the scope. pub values: AppValues, + /// The child `Ui`'s id salt, as `ui.push_id` gives it: the ids of what it shows derive from it. + pub id_salt: Option, } /// How a scope changes the built-in text: the only override path for words. @@ -179,15 +181,22 @@ impl Overrides { /// Runs `body` in a child `Ui` with `set`'s changes applied to the inherited values. A scope that disables /// disables its child `Ui`; one that changes direction builds the child with an explicit layout and never /// inherits the parent's. +/// +/// The components the child `Ui` shows are children of the body around `ui` as those shown in `ui` itself are, on its +/// line and in its cells. It is the craft form of `ui.scope` and +/// `ui.push_id` (`Overrides::id_salt`) around craft content: what a body sets up for its children in flow does not +/// reach a `Ui` egui code makes below the body's own (`Env::of`). Content laid out along the other axis goes in a +/// craft `Row` or `Stack`, a body of its own. pub fn with_env(ui: &mut Ui, set: impl FnOnce(&mut Overrides), body: impl FnOnce(&mut Ui) -> R) -> R { let mut overrides = Overrides::default(); set(&mut overrides); + let id_salt = overrides.id_salt.take(); let outer = Env::of(ui); let ctx = ui.ctx().clone(); let inner = outer.derive(|scoped| overrides.apply(&ctx, scoped)); let direction = (inner.direction != outer.direction).then(|| inner.direction.is_rtl()); let disabled = !inner.enabled; - child::scope(ui, disabled, direction, |child| { + child::scope(ui, id_salt, disabled, direction, |child| { let _restore = Restore { ctx: &ctx, installed: Some(Env::install_for(child, inner)) }; body(child) }) diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index be2673f53..28e21886d 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -560,6 +560,9 @@ impl Container for let (line, gap) = (env.tokens.size.panel_header, env.tokens.space.gap.item); ui.set_min_height(line); let surface_pressed = cx.surface_pressed(); + // A raw egui layout: the host's items and the tab row sit side by side, and the header column's flow facts are + // not theirs. The tab row takes the rest of the line, so the strip's empty room is its own, and nothing but the + // memoized tab row runs in it, so a settled header replays. let layout = if rtl { egui::Layout::right_to_left(egui::Align::Min) } else { egui::Layout::left_to_right(egui::Align::Min) }; let mut sent = Vec::new(); let strip = ui diff --git a/crates/ui-widgets/src/layout_components/mod.rs b/crates/ui-widgets/src/layout_components/mod.rs index a658ea805..01f7e6eac 100644 --- a/crates/ui-widgets/src/layout_components/mod.rs +++ b/crates/ui-widgets/src/layout_components/mod.rs @@ -212,6 +212,11 @@ layout_component!( ); layout_component!( /// Children row-major over a column list: a child in flow takes the next cell. + /// + /// The cells are the grid's craft children. An egui container shown in the body (`ui.horizontal`, an + /// `egui::Grid`) is no cell: egui places it below the cells placed so far, and its children are not cells. The + /// rows after it are placed over it, since the grid's rows do not count it: show it as the last child, or put it + /// in a craft body (`Row`), which takes a cell. Grid, GridStyleKey, [] diff --git a/crates/ui-widgets/src/list/toggle.rs b/crates/ui-widgets/src/list/toggle.rs index 82f8f8149..afe5733a2 100644 --- a/crates/ui-widgets/src/list/toggle.rs +++ b/crates/ui-widgets/src/list/toggle.rs @@ -185,18 +185,3 @@ impl ToggleCell { !self.empty_off && (self.always_visible || hovered) } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn an_empty_off_cell_never_draws_its_off_icon() { - let eye = ToggleCell::eye(ColumnKey::new("eye"), false); - assert!(!eye.shows_off(false) && eye.shows_off(true), "a plain off cell shows its off icon only under the pointer"); - assert!(eye.clone().always_visible().shows_off(false), "always_visible shows it in every row"); - let empty = eye.empty_off(); - assert!(!empty.shows_off(true), "an empty_off cell stays empty under the pointer"); - assert!(!empty.always_visible().shows_off(true), "empty_off wins over always_visible"); - } -} diff --git a/crates/ui-widgets/src/pickers/date.rs b/crates/ui-widgets/src/pickers/date.rs index d8819c941..0ebb83cd1 100644 --- a/crates/ui-widgets/src/pickers/date.rs +++ b/crates/ui-widgets/src/pickers/date.rs @@ -18,8 +18,9 @@ use crate::buttons::{IconButton, Link}; use crate::choice::Segmented; use crate::contract::{ Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Entry, Input, MeasureCx, Overlay, OverlayUi, Overlays as _, PaintUi, - PartsCx, Props as _, Remember as _, Role, Show as _, WordSetCx as _, clicked, + PartsCx, Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _, clicked, }; +use crate::layout_components::Row; use crate::primitives::{IconSpec, TextKey, TextOptions, TextRun}; use crate::runtime::env::Label; use crate::text::{Adornment, FieldStyle, place, reserve}; @@ -338,7 +339,7 @@ impl Component for DatePicker<'_> { view = next; } let mut pick = page.picked.map(Some); - ui.horizontal(|ui| { + let _ = Row::new().show(ui, |ui, _| { let at_precision = today.map(|today| match view.precision { DatePrecision::Day => today, DatePrecision::Month => PickedDate::month(today.year, today.month.unwrap_or(1)), diff --git a/crates/ui-widgets/src/pickers/select.rs b/crates/ui-widgets/src/pickers/select.rs index 8aec2a378..f23620475 100644 --- a/crates/ui-widgets/src/pickers/select.rs +++ b/crates/ui-widgets/src/pickers/select.rs @@ -16,6 +16,7 @@ use crate::contract::{ MeasureCx, Numeric, Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, PopupHandle, PopupKind, Props as _, Role, Show as _, ShowCollection as _, ShowContainer as _, Sizing, WordSetCx as _, step_stop, step_stops, }; +use crate::layout_components::Row; use crate::list::{List, ListRow, ThumbAspect}; use crate::menu::Menu; use crate::primitives::ContentPainterCx; @@ -318,7 +319,7 @@ impl Component for Select<'_, T> { let list = ui.scope_id().with("options"); let mut query = String::new(); if searchable || header_menu.is_some() { - ui.horizontal(|ui| { + let _ = Row::new().show(ui, |ui, _| { if searchable { query = search::show(ui, body, popup, cx, &name, list); } diff --git a/crates/ui-widgets/src/pickers/select/stories.rs b/crates/ui-widgets/src/pickers/select/stories.rs index 3c9e689c8..d87e26971 100644 --- a/crates/ui-widgets/src/pickers/select/stories.rs +++ b/crates/ui-widgets/src/pickers/select/stories.rs @@ -115,6 +115,12 @@ fn select_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { Select::new("Blend mode", data.bind("open", 1u8), &entries).show(ui).into() } +#[story(Select<'static, u8>, covers = [Open], drive = Drive::Custom(open_listbox))] +fn select_searchable_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let entries = resampling(); + Select::new("Resampling", data.bind("searchable_open", 2u8), &entries).searchable().show(ui).into() +} + #[story(Select<'static, u8>, covers = [], disabled_text = "Pick a layer first")] fn select_with_reason(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let entries = modes(); diff --git a/crates/ui-widgets/tests/it/layout/row_line.rs b/crates/ui-widgets/tests/it/layout/row_line.rs index 92a3cd6b8..e210f3331 100644 --- a/crates/ui-widgets/tests/it/layout/row_line.rs +++ b/crates/ui-widgets/tests/it/layout/row_line.rs @@ -1,17 +1,19 @@ //! The row line: a child of an unwrapped row that is one line sits with its centre on the row's line; a child of more //! than one line (a column, a field with a help line below) sits at the row's top. A control with its label after it //! or above it, and a field labelled above, sit on the line by their control, as a bare control does, in a row and in -//! a grid's cell. +//! a grid's cell. Components an app shows in an egui container inside a row or grid are laid out by that container: +//! they take neither the row's line nor the grid's cells. In an `egui::Grid`'s cell a labelled control decides its +//! label at its own width. use craft_behavior::ColumnWidth; use craft_theme::ControlSize; use craft_ui::buttons::Button; use craft_ui::choice::Checkbox; -use craft_ui::contract::{Bind, FieldLayout, Props as _, Show as _, ShowContainer as _, Sizing}; +use craft_ui::contract::{Bind, FieldLayout, LabelScheme, Props as _, Show as _, ShowContainer as _, Sizing}; use craft_ui::display::Text; -use craft_ui::form::{Field, Help}; +use craft_ui::form::{Field, FieldGroup, Help}; use craft_ui::layout_components::{Grid, Row, Stack}; -use craft_ui::runtime::env::Label; +use craft_ui::runtime::env::{Label, with_env}; use craft_ui::testing::{Fixture, last_pass_measuring_runs, trial}; use egui::Rect; use std::cell::Cell; @@ -165,3 +167,326 @@ fn a_labelled_check_box_sits_with_its_box_on_a_buttons_line_in_a_row_and_a_grid_ assert!((button.center().y - check.center().y).abs() <= ROUNDING, "{at}: the box {check:?} sits on the button's line {button:?}"); } } + +const GRID_ROWS: usize = 3; +type GridBoxes = [(Rect, Rect); GRID_ROWS]; + +/// Two columns of labelled check boxes in an `egui::Grid`, each box run through `wrap` (`ui.show` or a scope around +/// it) with its index: the box rects of each row. +fn boxes_grid(ui: &mut egui::Ui, wrap: Wrap) -> GridBoxes { + let mut boxes = [(Rect::NOTHING, Rect::NOTHING); GRID_ROWS]; + egui::Grid::new("boxes").num_columns(2).spacing([24.0, 6.0]).show(ui, |ui| { + for (row, rect) in boxes.iter_mut().enumerate() { + rect.0 = wrap(ui, 2 * row, Checkbox::new(Bind::given(true)).label(format!("Left {row}"))); + rect.1 = wrap(ui, 2 * row + 1, Checkbox::new(Bind::given(false)).label(format!("Right {row}"))); + ui.end_row(); + } + }); + boxes +} + +/// How `boxes_grid` shows each check box in its cell. +type Wrap = fn(&mut egui::Ui, usize, Checkbox<'_>) -> Rect; + +fn plain(ui: &mut egui::Ui, _: usize, check: Checkbox<'_>) -> Rect { + check.show(ui).response.rect +} + +fn read_only(ui: &mut egui::Ui, _: usize, check: Checkbox<'_>) -> Rect { + with_env(ui, |set| set.read_only = Some(true), |ui| check.show(ui).response.rect) +} + +fn pushed(ui: &mut egui::Ui, index: usize, check: Checkbox<'_>) -> Rect { + ui.push_id(index, |ui| check.show(ui).response.rect).inner +} + +/// The grid of `boxes_grid` in a 300 pt column, inside an unwrapped `Row` or a `Stack`, with a button after it. +fn grid_in(in_row: bool, wrap: Wrap) -> (GridBoxes, Rect) { + let (boxes, after, _) = grid_shown(in_row, wrap); + (boxes, after) +} + +/// `grid_in`, with the fixture it ran in. +fn grid_shown(in_row: bool, wrap: Wrap) -> (GridBoxes, Rect, Fixture) { + let seen = Rc::new(Cell::new(([(Rect::NOTHING, Rect::NOTHING); GRID_ROWS], Rect::NOTHING))); + let out = Rc::clone(&seen); + let fixture = settled(move |ui| { + let room = Rect::from_min_size(ui.available_rect_before_wrap().min, egui::vec2(300.0, 600.0)); + let out = Rc::clone(&out); + Stack::new().fill().show_at(ui, room, move |ui, _| { + let mut boxes = [(Rect::NOTHING, Rect::NOTHING); GRID_ROWS]; + if in_row { + Row::new().fill().show(ui, |ui, _| boxes = boxes_grid(ui, wrap)); + } else { + Stack::new().fill().show(ui, |ui, _| boxes = boxes_grid(ui, wrap)); + } + let after = Button::new("After").show(ui).rect; + out.set((boxes, after)); + }); + }); + let (boxes, after) = seen.get(); + (boxes, after, fixture) +} + +fn pitch(boxes: &GridBoxes) -> f32 { + boxes[1].0.top() - boxes[0].0.top() +} + +/// Check boxes an app lays out in an `egui::Grid` inside a row (a dialog's custom row of two columns of check boxes) +/// are no children of the row: the grid's rows are as high as the same grid's outside a row, not as high as the row's +/// line, and what follows the row starts under the grid. +#[trial] +fn check_boxes_in_an_egui_grid_in_a_row_keep_their_own_rows() { + let (alone, _) = grid_in(false, plain); + let (boxes, after) = grid_in(true, plain); + assert!((pitch(&boxes) - pitch(&alone)).abs() <= ROUNDING, "the grid rows in a row {boxes:?} are as high as outside one {alone:?}"); + assert!(after.top() >= boxes[GRID_ROWS - 1].0.bottom() - ROUNDING, "the button {after:?} is under the grid {boxes:?}"); +} + +/// The same check boxes, each in a scope of its own in its cell (an env scope, `with_env`, or `ui.push_id`): the scope +/// holds none of the row's facts, so the grid's rows stay as high as the same grid's outside a row, and the boxes are +/// still in the grid's cells: the labels stay on one line and the two columns share each row. +#[trial] +fn check_boxes_in_scopes_in_an_egui_grid_in_a_row_keep_their_own_rows_and_lines() { + for (scope, wrap) in [("with_env", read_only as Wrap), ("push_id", pushed)] { + let (alone, _) = grid_in(false, wrap); + let (boxes, after, fixture) = grid_shown(true, wrap); + assert!((pitch(&boxes) - pitch(&alone)).abs() <= ROUNDING, "{scope}: the grid rows in a row {boxes:?} are as high as outside one {alone:?}"); + let line = text(&fixture, "After").height(); + for (row, (left, right)) in boxes.iter().enumerate() { + for name in [format!("Left {row}"), format!("Right {row}")] { + let label = text(&fixture, &name); + assert!(label.height() < line * 1.5, "{scope}: the label {name} {label:?} stays on one line"); + } + assert!((left.center().y - right.center().y).abs() <= ROUNDING, "{scope}: the two columns share each row: {left:?} {right:?}"); + assert!(right.left() >= left.right() - ROUNDING, "{scope}: the right column {right:?} follows the left {left:?}"); + } + assert!(after.top() >= boxes[GRID_ROWS - 1].0.bottom() - ROUNDING, "{scope}: the button {after:?} is under the grid {boxes:?}"); + } +} + +/// Two columns of labelled check boxes in an `egui::Grid` share each row: the first column's labels are decided at +/// their own width, not wrapped in the narrow column egui offers a column it has no width for yet. +#[trial] +fn two_columns_of_labelled_check_boxes_in_an_egui_grid_share_each_row() { + let (boxes, _) = grid_in(false, plain); + for (left, right) in boxes { + assert!((left.center().y - right.center().y).abs() <= ROUNDING, "the two columns share each row: {left:?} {right:?}"); + assert!(right.left() >= left.right() - ROUNDING, "the right column {right:?} follows the left {left:?}"); + } +} + +/// In a form whose labelled rows share a label column, check boxes in an `egui::Grid` in a full-width row (a dialog's +/// custom row) each sit at their cell's start: none takes the form's label-column indent. +#[trial] +fn check_boxes_in_an_egui_grid_in_a_forms_row_sit_at_their_cells_start() { + let seen = Rc::new(Cell::new([(Rect::NOTHING, Rect::NOTHING); GRID_ROWS])); + let out = Rc::clone(&seen); + let _fixture = settled(move |ui| { + let room = Rect::from_min_size(ui.available_rect_before_wrap().min, egui::vec2(400.0, 600.0)); + let out = Rc::clone(&out); + Stack::new().fill().show_at(ui, room, move |ui, _| { + FieldGroup::new("Mode").labels(LabelScheme::Form).show(ui, |ui, _| { + Field::new("Name").show(ui, |ui, _| { + Button::new("Pick").show(ui); + }); + Row::new().fill().show(ui, |ui, _| out.set(boxes_grid(ui, plain))); + }); + }); + }); + let boxes = seen.get(); + for (row, (left, _)) in boxes.iter().enumerate() { + assert!((left.left() - boxes[0].0.left()).abs() <= ROUNDING, "row {row}'s box {left:?} starts where the first {:?} does", boxes[0].0); + } +} + +/// A craft `Grid`'s cells are its craft children. A `ui.horizontal` an app shows in one is no cell: egui lays out its +/// check boxes side by side on one line and places it below the cells placed so far, at the grid's start edge, and the +/// next craft child takes the next cell, beside "Name". +#[trial] +fn check_boxes_in_an_egui_container_in_a_grid_take_no_cells() { + let seen = Rc::new(Cell::new([Rect::NOTHING; 5])); + let out = Rc::clone(&seen); + let fixture = settled(move |ui| { + let room = Rect::from_min_size(ui.available_rect_before_wrap().min, egui::vec2(400.0, 400.0)); + let out = Rc::clone(&out); + Stack::new().fill().show_at(ui, room, move |ui, _| { + let mut pair = (Rect::NOTHING, Rect::NOTHING); + Grid::new(&[ColumnWidth::Content, ColumnWidth::Content]).show(ui, |ui, _| { + Text::new("Name").show(ui); + Text::new("Size").show(ui); + pair = ui + .horizontal(|ui| { + let one = Checkbox::new(Bind::given(true)).label("One").show(ui).response.rect; + let two = Checkbox::new(Bind::given(true)).label("Two").show(ui).response.rect; + (one, two) + }) + .inner; + }); + let after = Button::new("After").show(ui).rect; + out.set([pair.0, pair.1, after, Rect::NOTHING, Rect::NOTHING]); + }); + }); + let [one, two, after, ..] = seen.get(); + let (name, size) = (text(&fixture, "Name"), text(&fixture, "Size")); + assert!((one.center().y - two.center().y).abs() <= ROUNDING && two.left() >= one.right() - ROUNDING, "One {one:?}, then Two {two:?} on its line"); + assert!( + (size.center().y - name.center().y).abs() <= ROUNDING && size.left() >= name.right() - ROUNDING, + "Size {size:?} takes the cell beside Name {name:?}" + ); + assert!(one.top() >= name.bottom() - ROUNDING, "the pair {one:?} lies under Name's row {name:?}"); + assert!(one.left() <= name.left() + ROUNDING, "the pair {one:?} starts at the grid's start edge, as Name {name:?} does"); + assert!(after.top() >= one.bottom().max(two.bottom()) - ROUNDING, "the grid {after:?} reaches past the pair {one:?} {two:?}"); +} + +/// A check box in a `ui.horizontal` too narrow for its label wraps the label at the room's end: egui gives the +/// horizontal the room it has, and nothing runs past it. +#[trial] +fn a_check_box_in_a_narrow_horizontal_wraps_its_label_at_the_rooms_end() { + const LONG: &str = "Second option with a long name"; + const WIDTH: f32 = 160.0; + let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING))); + let out = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let out = Rc::clone(&out); + Stack::new().fill().show(ui, move |ui, _| { + let pair = ui.horizontal(|ui| { + let one = Checkbox::new(Bind::given(true)).label("One").show(ui).response.rect; + let two = Checkbox::new(Bind::given(false)).label(LONG).show(ui).response.rect; + (one, two) + }); + out.set(pair.inner); + }); + }); + fixture.room(egui::vec2(WIDTH, 200.0)).settle(); + fixture.idle(3); + let (_, two) = seen.get(); + let (label, one_line) = (text(&fixture, LONG), text(&fixture, "One")); + assert!(label.right() <= WIDTH + ROUNDING, "the label {label:?} ends inside the room"); + assert!(label.height() > one_line.height() * 1.5, "the label {label:?} wraps to a second line beside its box {two:?}"); +} + +/// One row of two labelled check boxes in an `egui::Grid` shown directly in a `Stack`, or in a `Row` in it (a dialog's +/// custom row), in a 400 pt room under `direction`; `long` lengthens the labels. Records the two boxes and the grid's +/// rect. +fn one_row_grid(in_row: bool, direction: craft_i18n::Direction, long: &Rc>) -> (Fixture, Rc>) { + let seen = Rc::new(Cell::new([Rect::NOTHING; 3])); + let (out, lengthen) = (Rc::clone(&seen), Rc::clone(long)); + let mut fixture = Fixture::new(move |ui| { + let (out, long) = (Rc::clone(&out), lengthen.get()); + let grid = move |ui: &mut egui::Ui| { + let mut boxes = [Rect::NOTHING; 3]; + boxes[2] = egui::Grid::new("boxes") + .num_columns(2) + .spacing([24.0, 6.0]) + .show(ui, |ui| { + for (column, rect) in boxes.iter_mut().take(2).enumerate() { + *rect = Checkbox::new(Bind::given(true)).label(column_name(column, long)).show(ui).response.rect; + } + ui.end_row(); + }) + .response + .rect; + out.set(boxes); + }; + Stack::new().fill().show(ui, move |ui, _| { + if in_row { + Row::new().fill().show(ui, |ui, _| grid(ui)); + } else { + grid(ui); + } + }); + }); + fixture.direction(direction).room(egui::vec2(400.0, 200.0)).settle(); + (fixture, seen) +} + +fn column_name(column: usize, long: bool) -> String { + if long { format!("Column {column} with a longer name") } else { format!("C{column}") } +} + +/// What the cells of `one_row_grid` show: each column's box and label. +fn cells(fixture: &Fixture, boxes: [Rect; 3]) -> [Rect; 2] { + [0, 1].map(|column| boxes[column].union(text(fixture, &column_name(column, true)))) +} + +/// Under right-to-left, labelled check boxes in an `egui::Grid` shown directly in a right-to-left body, or in a row +/// there, stay in their cells: egui lays a grid out from its left edge in any direction, so the grid's rect is finite, +/// on the frame the labels lengthen the first column's box and label stay right of the grid's left edge, once settled +/// the second column stays clear of the first, and the cells take as much width as under left-to-right: the last +/// column is as wide as its box and label, not the rest of the room. +#[trial] +fn check_boxes_in_an_egui_grid_stay_in_their_cells_under_rtl() { + for in_row in [false, true] { + let ltr = { + let long = Rc::new(Cell::new(true)); + let (mut fixture, seen) = one_row_grid(in_row, craft_i18n::Direction::Ltr, &long); + fixture.settle(); + cells(&fixture, seen.get()) + }; + let long = Rc::new(Cell::new(false)); + let (mut fixture, seen) = one_row_grid(in_row, craft_i18n::Direction::Rtl, &long); + let grid = seen.get()[2]; + assert!(grid.is_finite(), "in a row {in_row}: the grid's rect {grid:?} is finite"); + long.set(true); + fixture.frame(vec![]); + for (part, rect) in [("box", seen.get()[0]), ("label", text(&fixture, &column_name(0, true)))] { + assert!( + rect.left() >= grid.left() - ROUNDING, + "in a row {in_row}: the first column's {part} {rect:?} stays right of the grid's left edge {grid:?}" + ); + } + fixture.settle(); + let [first, second] = cells(&fixture, seen.get()); + assert!(second.left() >= first.right() - ROUNDING, "in a row {in_row}: the second column {second:?} is clear of the first {first:?}"); + let (width, ltr_width) = (first.union(second).width(), ltr[0].union(ltr[1]).width()); + assert!((width - ltr_width).abs() <= ROUNDING, "in a row {in_row}: the cells take {width} under RTL, as under LTR ({ltr_width})"); + } +} + +/// A labelled container in an `egui::Grid`'s first column decides its label at its own width: the label stays on one +/// line, and the two columns share the row. +#[trial] +fn a_labelled_row_in_an_egui_grid_keeps_its_label_on_one_line() { + const LONG: &str = "Spacing between the rows"; + let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING))); + let out = Rc::clone(&seen); + let fixture = settled(move |ui| { + let room = Rect::from_min_size(ui.available_rect_before_wrap().min, egui::vec2(400.0, 300.0)); + let out = Rc::clone(&out); + Stack::new().fill().show_at(ui, room, move |ui, _| { + egui::Grid::new("rows").num_columns(2).show(ui, |ui| { + let mut first = Rect::NOTHING; + Field::new(LONG).show(ui, |ui, _| first = Button::new("Go").show(ui).rect); + let second = Button::new("Next").show(ui).rect; + ui.end_row(); + out.set((first, second)); + }); + }); + }); + let (first, second) = seen.get(); + let (label, go) = (text(&fixture, LONG), text(&fixture, "Go")); + assert!(label.height() < go.height() * 1.5, "the label {label:?} stays on one line"); + assert!((first.center().y - second.center().y).abs() <= ROUNDING, "the two columns share the row: {first:?} {second:?}"); +} + +/// A small labelled check box in a plain `Lazy` in a row beside a button sits with its box on the button's line: a +/// `Lazy` runs its content as the row's direct children. +#[trial] +fn a_labelled_check_box_in_a_lazy_in_a_row_sits_on_the_rows_line() { + let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING))); + let out = Rc::clone(&seen); + let _fixture = settled(move |ui| { + let out = Rc::clone(&out); + Row::new().show(ui, |ui, _| { + let button = Button::new("Go").show(ui).rect; + let mut check = Rect::NOTHING; + craft_ui::contract::Lazy::new("check", 0.0).show(ui, |ui| { + check = Checkbox::new(Bind::given(true)).label("Snap").size(ControlSize::Sm).show(ui).response.rect; + }); + out.set((button, check)); + }); + }); + let (button, check) = seen.get(); + assert!((button.center().y - check.center().y).abs() <= ROUNDING, "the box {check:?} sits on the button's line {button:?}"); +}