diff --git a/crates/color-ui/src/ui/disc.rs b/crates/color-ui/src/ui/disc.rs index dda1ca904..8d953c248 100644 --- a/crates/color-ui/src/ui/disc.rs +++ b/crates/color-ui/src/ui/disc.rs @@ -226,7 +226,8 @@ impl Component for ColorDisc<'_> { /// A band across the width it is given, as tall as the square that fits it: the picture is centred in it. fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { - Vec2::new(cx.picture_width(cx.style.least, f32::INFINITY), cx.picture_width(cx.style.least, cx.style.most)) + let most = cx.style.most.max(cx.style.least); + cx.picture_size(cx.style.least, f32::INFINITY, |width| width.min(most)) } fn sense(&self) -> Sense { diff --git a/crates/color-ui/src/ui/wheel.rs b/crates/color-ui/src/ui/wheel.rs index a1b3d5d9f..7b0d6ade4 100644 --- a/crates/color-ui/src/ui/wheel.rs +++ b/crates/color-ui/src/ui/wheel.rs @@ -307,7 +307,8 @@ impl Component for ColorWheel<'_> { /// A band across the width it is given, as tall as the square that fits it: the picture is centred in it. fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { - Vec2::new(cx.picture_width(cx.style.least, f32::INFINITY), cx.picture_width(cx.style.least, cx.style.most)) + let most = cx.style.most.max(cx.style.least); + cx.picture_size(cx.style.least, f32::INFINITY, |width| width.min(most)) } fn sense(&self) -> Sense { diff --git a/crates/imaging/src/ui/adjust/levels_editor.rs b/crates/imaging/src/ui/adjust/levels_editor.rs index 5f1bc2ad4..0cdae46d9 100644 --- a/crates/imaging/src/ui/adjust/levels_editor.rs +++ b/crates/imaging/src/ui/adjust/levels_editor.rs @@ -8,7 +8,7 @@ use std::ops::RangeInclusive; use craft_behavior::{Metrics, Mixed, Proposal, Sense, decimals_for_step}; use craft_ui::contract::{ - Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, Outcome, PaintUi, Props as _, Role, WordSetCx as _, + Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, Outcome, PaintUi, Props as _, Role, Sizing, WordSetCx as _, }; use craft_ui::display::{Shade, Text}; use craft_ui::runtime::env::Label; @@ -165,10 +165,6 @@ pub struct LevelsEditorStyle { bar_row: f32, /// The height of a row of fields. fields: f32, - /// The width of a levels field: three digits. - field: f32, - /// The width of the gamma field: a value like 9.99. - gamma_field: f32, /// The width the editor asks for when the parent offers none. width: f32, /// The light end of the output bar: the channel's bar colour. @@ -256,6 +252,8 @@ pub struct LevelsEditor<'a> { #[prop] captions: bool, clip: Option, + /// The width of a levels field and of the gamma field, as the fields measure themselves (`measure`). + field_widths: [f32; 2], } impl<'a> LevelsEditor<'a> { @@ -274,6 +272,7 @@ impl<'a> LevelsEditor<'a> { stale: false, captions: true, clip: None, + field_widths: [0.0; 2], } .label(label) } @@ -327,6 +326,17 @@ impl<'a> LevelsEditor<'a> { if self.stale { plot.stale(StaleMark::Mark(Label::Empty)) } else { plot } } + /// The three input fields (black, gamma, white) showing `base`, with the thumbs at `placed`. + fn input_fields<'c>(&self, words: &LevelsWords, base: &Levels, placed: [f64; 3]) -> [NumberField<'c>; 3] { + let labels = [words.in_black.clone(), words.gamma.clone(), words.in_white.clone()]; + let values = [base.in_black, base.gamma, base.in_white]; + std::array::from_fn(|i| { + let step = if i == 1 { GAMMA_STEP } else { self.step }; + let field = self.field(labels[i].clone(), values[i], input_range(self, i, placed), step); + if i == 1 { field.fixed_decimals(decimals_for_step(GAMMA_STEP)) } else { field } + }) + } + /// A field named `label` showing `value`, within `range`. fn field<'c>(&self, label: Label, value: f64, range: RangeInclusive, step: f64) -> NumberField<'c> { let shown = Some(value).filter(|value| value.is_finite()); @@ -431,8 +441,6 @@ impl Component for LevelsEditor<'_> { row: control.icon, bar_row: control.icon + cx.tokens.size.ramp.bar, fields: row, - field: cx.text_width(TypeRole::Body, "000") + 2.0 * control.pad_x, - gamma_field: cx.text_width(TypeRole::Body, "0.00") + 2.0 * control.pad_x, width: cx.tokens.size.plot.width, bar: key.channel.bar(cx), } @@ -448,6 +456,13 @@ impl Component for LevelsEditor<'_> { let empty = HistogramData::tone(&[0u32; 256], self.channel); let mut plot = self.plot(&words, self.histogram.unwrap_or(&empty)); let plot = cx.child("plot", &mut plot, Proposal::Width(width)).y; + let base = cx.value().copied().unwrap_or_else(|| Levels::identity(self.range.clone())); + let placed = self.input_row(&words, cx.value().copied()).rules().placed(&base.input()); + let mut widths = [0.0f32; 3]; + for (i, field) in self.input_fields(&words, &base, placed).into_iter().enumerate() { + widths[i] = cx.child(("in-field", i), &mut field.sizing(Sizing::Content), Proposal::Ideal).x; + } + self.field_widths = [widths[0].max(widths[2]), widths[1]]; Vec2::new(width, fixed_height(self.captions, cx.style) + plot) } @@ -484,20 +499,16 @@ impl Component for LevelsEditor<'_> { let empty = HistogramData::tone(&[0u32; 256], self.channel); let plot = Rect::from_x_y_ranges(input.travel, at(rows.plot).y_range()); ui.child("plot", plot, self.plot(&words, self.histogram.unwrap_or(&empty))); - let fields = field_rects(rows.fields_in, cx.style.field, cx.style.gamma_field, 3); - let labels = [words.in_black.clone(), words.gamma.clone(), words.in_white.clone()]; - let values = [base.in_black, base.gamma, base.in_white]; - let typed: Vec<_> = (0..3) - .map(|i| { - let step = if i == 1 { GAMMA_STEP } else { self.step }; - let field = self.field(labels[i].clone(), values[i], input_range(self, i, placed), step); - let field = if i == 1 { field.fixed_decimals(decimals_for_step(GAMMA_STEP)) } else { field }; - ui.child(("in-field", i), at(fields[i]), field) - }) + let fields = field_rects(rows.fields_in, self.field_widths[0], self.field_widths[1], 3); + let typed: Vec<_> = self + .input_fields(&words, &base, placed) + .into_iter() + .enumerate() + .map(|(i, field)| ui.child(("in-field", i), at(fields[i]), field)) .collect(); let output = ui.child("output", at(rows.output), self.output_row(&words, shown, &bar)); - let fields = field_rects(rows.fields_out, cx.style.field, 0.0, 2); + let fields = field_rects(rows.fields_out, self.field_widths[0], 0.0, 2); let (low, high) = self.ends(); let out_labels = [words.out_black.clone(), words.out_white.clone()]; let out_values = [base.out_black, base.out_white]; diff --git a/crates/imaging/src/ui/curve/graph.rs b/crates/imaging/src/ui/curve/graph.rs index 71293b838..0bf911331 100644 --- a/crates/imaging/src/ui/curve/graph.rs +++ b/crates/imaging/src/ui/curve/graph.rs @@ -516,7 +516,7 @@ impl Component for CurveGraph<'_> { } fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { - Vec2::splat(cx.picture_width(cx.style.least, cx.style.most)) + cx.picture_size(cx.style.least, cx.style.most, |width| width) } fn sense(&self) -> Sense { diff --git a/crates/imaging/tests/it/adjust_tone.rs b/crates/imaging/tests/it/adjust_tone.rs index c5eecf4b3..263f05df7 100644 --- a/crates/imaging/tests/it/adjust_tone.rs +++ b/crates/imaging/tests/it/adjust_tone.rs @@ -1,10 +1,15 @@ //! The Levels editor and panel, the Curves panel's point helper and the tone pickers, driven through the public //! widgets as a host would show them. -use craft_imaging::ui::adjust::{CurvesPanel, Levels, ToneChannels, ToneCurves, ToneSpace}; +use std::cell::RefCell; +use std::rc::Rc; + +use craft_imaging::ui::adjust::{CurvesPanel, Levels, LevelsEditor, ToneChannels, ToneCurves, ToneSpace}; use craft_imaging::ui::curve::Curve; use craft_theme::Srgba; -use craft_ui::testing::trial; +use craft_ui::contract::{Bind, Show as _}; +use craft_ui::testing::{Fixture, trial}; +use egui::Vec2; fn grey(v: f32) -> Srgba { Srgba { r: v, g: v, b: v, a: 1.0 } @@ -73,3 +78,28 @@ fn a_curves_point_from_a_sample_goes_on_the_shown_channel_or_on_each_colour() { assert_eq!(xs(&curves, 2), [0.0, 153.0, 255.0]); assert_eq!((xs(&curves, 1).len(), xs(&curves, 3).len()), (2, 2), "the other colours stay as they were"); } + +/// Every value field of the editor holds its value whole: the gamma at both ends of its range and the levels at both +/// ends of theirs lie inside the field, not cut by its edge. +#[trial] +fn the_levels_fields_hold_their_values_whole() { + for (levels, shown) in + [(Levels::new(0.0, 1.0, 255.0, 0.0, 255.0), ["0", "1.00", "255"]), (Levels::new(255.0, 9.99, 255.0, 255.0, 255.0), ["255", "9.99", "255"])] + { + let state = Rc::new(RefCell::new(levels)); + let held = Rc::clone(&state); + let mut fixture = Fixture::new(move |ui| { + let _ = LevelsEditor::new("Levels", Bind::bound(&mut *held.borrow_mut())).show(ui); + }); + fixture.room(Vec2::new(800.0, 600.0)); + fixture.settle(); + for value in shown { + let painted: Vec<_> = fixture.texts().iter().filter(|text| text.text == value).collect(); + assert!(!painted.is_empty(), "{value} is painted"); + for text in painted { + assert!(!text.elided, "{value} is not elided"); + assert!(text.clip.contains_rect(text.rect), "{value} {:?} lies inside its field's clip {:?}", text.rect, text.clip); + } + } + } +} diff --git a/crates/imaging/tests/it/hosted_dialogs.rs b/crates/imaging/tests/it/hosted_dialogs.rs index e4d53e6c7..eb88f64e1 100644 --- a/crates/imaging/tests/it/hosted_dialogs.rs +++ b/crates/imaging/tests/it/hosted_dialogs.rs @@ -5,8 +5,10 @@ use std::cell::RefCell; use std::rc::Rc; use craft_imaging::layer_style::{EffectId, EffectInstance, EffectKind, LayerStyle, LayerStyleDraft, LayerStylePage, StyleParams}; -use craft_imaging::ui::adjust::{BrightnessContrast, BrightnessContrastEditor, HostedAdjustDialog}; +use craft_imaging::ui::adjust::{BrightnessContrast, BrightnessContrastEditor, CurvesPanel, HostedAdjustDialog, ToneChannels, ToneCurves, ToneSpace}; +use craft_imaging::ui::curve::Curve; use craft_imaging::ui::layer_style::{HostedLayerStyle, LayerStyleAsk}; +use craft_ui::contract::Role; use craft_ui::dialog::{DialogHost, DialogResult, HeldOk, StackDialog, dialog_id}; use craft_ui::runtime::env::Label; use craft_ui::testing::{Fixture, trial}; @@ -226,3 +228,66 @@ fn a_held_adjustment_ok_refused_stays_open_and_an_accepted_one_closes() { let answered = host.borrow_mut().take_keyed::().and_then(|(result, _)| result.ok()).map(|value| value.brightness); assert_eq!(answered, Some(5.0), "the accepted OK closes the dialog with the held value"); } + +/// The Curves value of the dialog trial: three points on the composite curve. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +struct Curves(ToneCurves); + +impl Default for Curves { + fn default() -> Self { + let mut curves = ToneCurves::identity(&ToneChannels::of(ToneSpace::Rgb, false)); + curves.curves[0] = Curve::smooth(vec![[0.0, 0.0], [128.0, 160.0], [255.0, 255.0]]); + Curves(curves) + } +} + +type CurvesDialog = HostedAdjustDialog; + +// The dialog sizes its content column from what the editor takes, and the graph is a square picture that shows across +// that column: everything under it (its tone bar, the selected point's Input and Output, the hint) lies inside the +// dialog, not pushed past its edge. +#[trial] +fn the_curves_dialog_shows_the_tone_bar_the_point_fields_and_the_hint() { + let host = Rc::new(RefCell::new(DialogHost::new())); + let mut fixture = fixture(&host); + host.borrow_mut().open(CurvesDialog::new("image.adjustments.curves", "Curves", Curves::default(), |ui, value, cx| { + let mut panel = + CurvesPanel::new("Curves", craft_ui::contract::Bind::bound(&mut value.0), ToneChannels::of(ToneSpace::Rgb, false)).context(cx.context); + if let Some(point) = cx.select_point { + panel = panel.select(point); + } + let _ = panel.show(ui); + None + })); + fixture.idle(10); + if let Some(dialog) = host.borrow_mut().get_mut::() { + dialog.select_point(1); + } + fixture.settle(); + let dialog = fixture.by_role(Role::DIALOG).first().map(|dialog| dialog.rect).expect("the Curves dialog shows"); + let point = fixture.by_label("Point 2 of 3").expect("the middle point"); + let tree = fixture.tree(); + let graph = tree.parent_of_key(point.node).and_then(|graph| tree.bounds_of(graph)).expect("the graph holds its points"); + let input = fixture.by_label("Input").expect("the Input field").rect; + let output = fixture.by_label("Output").expect("the Output field").rect; + let hint = fixture.texts().iter().find(|text| text.text.starts_with("Click to add a point")).expect("the hint is painted").rect; + for (part, rect) in [("the graph and its tone bar", graph), ("Input", input), ("Output", output), ("the hint", hint)] { + assert!(dialog.contains_rect(rect), "{part} {rect:?} lies inside the dialog {dialog:?}"); + } + assert!(input.top() >= graph.bottom() && hint.top() >= input.bottom(), "graph, fields, hint top to bottom: {graph:?} {input:?} {hint:?}"); + + // The fields read the selected point, and Input moves it. + let field = |fixture: &Fixture, name: &str| { + let target = fixture.by_label(name).unwrap_or_else(|| panic!("the {name} field")); + fixture.tree().value_of(target.node).map(str::to_owned) + }; + assert_eq!(field(&fixture, "Input").as_deref(), Some("128"), "Input reads the selected point's input"); + assert_eq!(field(&fixture, "Output").as_deref(), Some("160"), "Output reads the selected point's output"); + let input = fixture.by_label("Input").expect("the Input field"); + fixture.click(&input).settle(); + // Tab commits the field; Enter would answer the dialog. + fixture.key(Key::A, Modifiers::COMMAND).type_text("96"); + fixture.key(Key::Tab, Modifiers::NONE).settle(); + let point = host.borrow().get::().and_then(|dialog| dialog.value().0.curves[0].points().map(|points| points[1])); + assert_eq!(point, Some([96.0, 160.0]), "setting Input moves the point"); +} diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 70f69657c..26a4ac93f 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -295,7 +295,7 @@ impl ShapeHooks for BodyHooks<'_> { self.fixed_height = self.fixed_height(props, at); self.passes = self.passes_width(props, &env, at); self.held = self.held(props, &env); - self.across = self.held && matches!(env.column, Some(ColumnSweep::Column(_))); + self.across = self.held && matches!(env.column, Some(ColumnSweep::Column(..))); self.in_column = label::in_column(ui); self.given.1 |= self.over_room(props, &env, at, ui.ctx(), id); let measured = self.measured_body.unwrap_or(Vec2::ZERO); @@ -1827,9 +1827,9 @@ impl BodyHooks<'_> { self.fixed_height = self.fixed_height(&props, at.at); self.passes = self.passes_width(&props, at.env, at.at); self.held = self.held(&props, at.env); - self.across = self.held && matches!(at.env.column, Some(ColumnSweep::Column(_))); + self.across = self.held && matches!(at.env.column, Some(ColumnSweep::Column(..))); // A held container across its column measures at the column's width. - if let Some(ColumnSweep::Column(width)) = at.env.column.filter(|_| self.across && at.width.is_none()) { + if let Some(ColumnSweep::Column(_, width)) = at.env.column.filter(|_| self.across && at.width.is_none()) { self.room.x = width; } self.in_column = label::in_column(at.ui); diff --git a/crates/ui-contract/src/contract/cx/measure.rs b/crates/ui-contract/src/contract/cx/measure.rs index de1112200..7d16484bb 100644 --- a/crates/ui-contract/src/contract/cx/measure.rs +++ b/crates/ui-contract/src/contract/cx/measure.rs @@ -78,11 +78,11 @@ impl MeasureCx<'_, C> { } } - /// The width a picture sizes at (a plot, a wheel, a well): it takes the room it is offered, down to `least` and up - /// to `most`. At its least, where the width is unbounded, and in a measuring run of a column that sizes its width - /// from its content (which offers no room), it is `least`: a picture needs no width of its own, so it never sets - /// that column's width, and the real run shows it across the width the column settles on. A band picture keeps a - /// height of its own; a square one is as tall as this. + /// The width a band picture sizes at (a plot, a strip), one whose height is its own whatever its width: it takes + /// the room it is offered, down to `least` and up to `most`. At its least, where the width is unbounded, and in a + /// measuring run of a column that sizes its width from its content (which offers no room), it is `least`: a + /// picture needs no width of its own, so it never sets that column's width, and the real run shows it across the + /// width the column settles on. pub fn picture_width(&self, least: f32, most: f32) -> f32 { match self.room.filter(|_| self.proposal != Proposal::Min) { Some(room) => room.clamp(least, most.max(least)), @@ -90,6 +90,23 @@ impl MeasureCx<'_, C> { } } + /// The size of a picture whose height follows from its width (a square graph, a wheel, an image at its aspect): + /// [`picture_width`](Self::picture_width)'s width, and `height` of it. Where a content column's measuring run + /// offers it no room, it is a held child of the column (`layout::HeldKind::Picture`): when the column settles + /// wider than the picture, the column sweeps again and offers it that width, so the picture is measured as tall + /// as it shows. + pub fn picture_size(&self, least: f32, most: f32, height: impl FnOnce(f32) -> f32) -> Vec2 { + // The width it reports is its placed width, which the place step gives (`run::place_root`). + if self.room.is_none() + && self.proposal != Proposal::Min + && let Some(column) = self.env.column_first_sweep() + { + crate::layout::report_held(self.ui.ctx(), column, self.id, crate::layout::HeldKind::Picture, f32::INFINITY); + } + let width = self.picture_width(least, most); + Vec2::new(width, height(width)) + } + /// The label as given. pub fn label(&self) -> Label { self.resolved.label_value.clone() @@ -131,7 +148,7 @@ impl MeasureCx<'_, C> { /// editor draws past its last letter, so the caret stays inside the control and the text never scrolls. pub fn field_text(&self, run: &TextRun<'_>) -> Vec2 { let text = self.layout(run).size(); - Vec2::new(text.x + self.ui.visuals().text_cursor.stroke.width, text.y) + Vec2::new(text.x + crate::runtime::egui::style::caret_width(self.ui.ctx()), text.y) } /// Lays document `text` out `text.wrap` wide, as `ContentPainterCx::layout` will paint it: the galley a content diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index f495e805f..1ab5f8ed5 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -820,14 +820,21 @@ fn place_root(p: &Pass<'_, '_, '_>, ui: &mut Ui, at: ShowAt, env: &Env, size: Ve let flowed = steps::place(ui, at, Vec2::new(p.measured.x.min(size.x), size.y), InFlow { fill: false, first: first(size.y), line }); // The column's first sweep learns which of its held children measured narrower than it settles on. if let Some(ColumnSweep::Count(column)) = env.column { - crate::layout::report_held(&ctx, column, flowed.width()); + crate::layout::report_held(&ctx, column, id, crate::layout::HeldKind::Fill, flowed.width()); } let across = Vec2::new(size.x.max(flowed.width()).max(column), flowed.height()); if rtl { Rect::from_min_size(Pos2::new(flowed.max.x - across.x, flowed.min.y), across) } else { Rect::from_min_size(flowed.min, across) } } else { let fill = p.p.fills_width() && !p.p.fills_width_only(); let size = if inert { Vec2::ZERO } else { size }; - steps::place(ui, at, size, InFlow { fill, first: first(size.y), line: p.p.first_is_row_line() }) + let placed = steps::place(ui, at, size, InFlow { fill, first: first(size.y), line: p.p.first_is_row_line() }); + // A picture its measure held (`MeasureCx::picture_size`) reports its placed width, padding included. + if let Some(ColumnSweep::Count(column)) = env.column + && crate::layout::held_kind(&ctx, column, id) == Some(crate::layout::HeldKind::Picture) + { + crate::layout::report_held(&ctx, column, id, crate::layout::HeldKind::Picture, placed.width()); + } + placed }; (rect, held) } @@ -1570,9 +1577,14 @@ fn room_step(t: &mut dyn Erased, ui: &Ui, at: ShowAt, begun: &Begun) -> Room { let room = match at { ShowAt::Rect(rect) => Some(rect.width()), // A measuring run in a content column asks for what the content needs: nothing there fills the room. Once the - // column settled its width, a child that fills its width measures at that width. + // column settled its width, a child that fills its width, or a picture its first sweep held, measures at + // that width. ShowAt::Flow => match env.column { - Some(ColumnSweep::Column(width)) if env.content_column && t.fills_width() => Some(width), + Some(ColumnSweep::Column(column, width)) + if env.content_column && (t.fills_width() || crate::layout::held_kind(ctx, column, id) == Some(crate::layout::HeldKind::Picture)) => + { + Some(width) + } _ => Some(crate::layout::flow_room(ui).x) .filter(|width| width.is_finite() && !(env.content_column && crate::runtime::measure::active(ctx))), }, diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index 39aef7f2b..88b26db0b 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -137,21 +137,40 @@ pub(crate) struct Cursors(IdMap); #[derive(Default)] pub(crate) struct FillCounts(IdMap); -/// The narrowest width a held fill-width child of each content-sized `Stack` column measured at in the first sweep of -/// the column's measuring run (`report_held`), by column id. -#[derive(Default)] -pub(crate) struct HeldWidths(IdMap); +/// What makes a child of a content-sized `Stack` column a held child: it measures at its own width while the column +/// settles its width from the others, and the column's second sweep gives it the settled width. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum HeldKind { + /// A fill-width child: it shows across the width the column settles on. + Fill, + /// A picture whose height follows from its width that took its least for want of room + /// (`MeasureCx::picture_size`): it shows at the width it sizes at in the column's width, which may be narrower than + /// the column. + Picture, +} -/// Reports a held fill-width child of the content-sized column `column` in its first sweep: the `width` it measured -/// at. A column with no first sweep open takes no report. -pub(crate) fn report_held(ctx: &egui::Context, column: Id, width: f32) { +/// The held children of each content-sized `Stack` column in its measuring run, by column id: each child's kind and +/// the narrowest width it measured at in the column's first sweep, by child id. +#[derive(Default)] +pub(crate) struct HeldWidths(IdMap>); + +/// Reports a held child `child` of the content-sized column `column` in its first sweep: its kind and the `width` it +/// measured at. A column with no first sweep open takes no report. +pub(crate) fn report_held(ctx: &egui::Context, column: Id, child: Id, kind: HeldKind, width: f32) { pass_state::with::(ctx, |held| { - if let Some(narrowest) = held.0.get_mut(&column) { - *narrowest = narrowest.min(width); + if let Some(children) = held.0.get_mut(&column) { + let entry = children.entry(child).or_insert((kind, width)); + entry.1 = entry.1.min(width); } }); } +/// The kind of the held child `child` of the column `column`, as the column's first sweep reported it, while the +/// column's measuring run runs. +pub(crate) fn held_kind(ctx: &egui::Context, column: Id, child: Id) -> Option { + pass_state::with::(ctx, |held| held.0.get(&column).and_then(|children| children.get(&child)).map(|(kind, _)| *kind)) +} + /// What the first child a measuring sweep placed in flow in each open target reported (`Scoped::first_line`): the y /// of its first line's centre, or `None` for a child with no line of its own. A container's measuring sweep opens and /// closes its header's and body's targets; a body's sweep starts its own target afresh. @@ -908,13 +927,14 @@ fn measure_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui:: /// is bounded: each sweep is `run_sharing`'s, with the column's sweep (`ColumnSweep`) in its children's env. It adds no /// `Ui` of its own, so the children have the ids `run_sharing` gives them when the column's width is not bounded. /// -/// A held fill-width child measures at its own width while the column settles its width from the others, so it may -/// measure narrower than it shows. A measuring run sweeps the children once, each held child reporting the width it -/// measured at (`report_held`). When one of them measured narrower than the column settled on, it sweeps them again -/// with that width, at which the held children measure across the column and the others reuse their records; else the -/// first sweep stands, and each held child keeps the record it made at its own width, which is the column's. It -/// records which (`sub(id, "column")`): the real run gives the held children the width the column shows at only after -/// a second sweep, so each shows as its records were made. +/// A held child (`HeldKind`: a fill-width child, or a picture that took its least for want of room) measures at its +/// own width while the column settles its width from the others, so it may measure narrower than it shows. A +/// measuring run sweeps the children once, each held child reporting the width it measured at (`report_held`). When +/// one of them measured narrower than the column settled on, it sweeps them again with that width, at which the held +/// children measure in the column's width and the others reuse their records; else the first sweep stands, and each +/// held child keeps the record it made at its own width, which is the column's. It records which +/// (`sub(id, "column")`): the real run gives the held children the width the column shows at only after a second +/// sweep, so each shows as its records were made. // PLAN: the second sweep's need is decided once for the column, not per held container at body/hooks.rs's reuse // rule: a container that reused its content-sized record there would be laid out across in the real run under records // not made across. @@ -931,29 +951,34 @@ fn run_column(ui: &mut Ui, env: &Env, id: Id, layout: egui::Layout, mut body: }; if !measure::active(&ctx) { let across = this_pass(&ctx, false, key).is_some_and(|took| took.x > 0.0); - let column = across.then(|| ColumnSweep::Column(flow_room(ui).x)); + let column = across.then(|| ColumnSweep::Column(id, flow_room(ui).x)); return sweep(ui, column, &mut body); } let (inner, rect, again) = crate::contract::keeping_ids(&ctx, || { - pass_state::with::(&ctx, |held| held.0.insert(id, f32::INFINITY)); + pass_state::with::(&ctx, |held| held.0.insert(id, IdMap::default())); let env = column_env(Some(ColumnSweep::Count(id))); let installed = Env::install_for(ui, env.clone()); let (inner, rect) = measure_sharing(ui, &env, id, Axis::Y, layout, &mut body); Env::restore(&ctx, installed); - let narrowest = pass_state::with::(&ctx, |held| held.0.remove(&id)); + let narrowest = pass_state::with::(&ctx, |held| { + held.0.get(&id).map_or(f32::INFINITY, |children| children.values().fold(f32::INFINITY, |least, (_, width)| least.min(*width))) + }); // Half a point: less than a pixel shows at any scale the box runs. - let again = narrowest.is_some_and(|narrowest| narrowest < rect.width() - 0.5); + let again = narrowest < rect.width() - 0.5; ((inner, rect, again), again) }); let column = rect.width(); // 0 when the first sweep stands, so nothing an earlier run of the pass left is read. found(&ctx, true, key, Vec2::ZERO, Vec2::new(if again { column } else { 0.0 }, 0.0)); - if again { - sweep(ui, Some(ColumnSweep::Column(column)), &mut body) + // The second sweep reads the held children's kinds (`held_kind`); the column's record closes after it. + let inner = if again { + sweep(ui, Some(ColumnSweep::Column(id, column)), &mut body) } else { ui.advance_cursor_after_rect(rect); inner - } + }; + pass_state::with::(&ctx, |held| held.0.remove(&id)); + inner } /// What places the children in flow of a body that places them itself. diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index b5fbb0c2e..1301468c2 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -24,8 +24,8 @@ pub use body::place_in_flow; #[cfg(feature = "testing")] pub(crate) use body::run_body; pub(crate) use body::{ - BracketTook, InFlow, at_flow_start, close_first_line, close_flow_start_in, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, - flow_room, flow_start, grid_cell, in_grid_content_column, leaf_fill_room, members_line, open_first_lines, place_in_cell, report_bracket_control, - report_held, report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, - view_room, + BracketTook, HeldKind, InFlow, at_flow_start, close_first_line, close_flow_start_in, counting_fills, fill_share, fill_size, flow_fill_room, + flow_region, flow_room, flow_start, grid_cell, held_kind, in_grid_content_column, leaf_fill_room, members_line, open_first_lines, place_in_cell, + report_bracket_control, report_held, report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, + take_cell, take_in_flow, view_room, }; diff --git a/crates/ui-contract/src/runtime/egui/style.rs b/crates/ui-contract/src/runtime/egui/style.rs index 4285d9b79..ff7b38fd3 100644 --- a/crates/ui-contract/src/runtime/egui/style.rs +++ b/crates/ui-contract/src/runtime/egui/style.rs @@ -10,6 +10,11 @@ pub(crate) fn set_text_cursor(ui: &mut Ui, visible: bool) { } } +/// The width of the caret an editable text draws past its last letter: the one value measuring and styling both read. +pub(crate) fn caret_width(ctx: &Context) -> f32 { + ctx.global_style().visuals.text_cursor.stroke.width +} + /// Paints the selected text of `ui`'s text edits in `ink` on `fill`. pub(crate) fn set_text_selection(ui: &mut Ui, fill: egui::Color32, ink: egui::Color32) { let selection = &mut ui.visuals_mut().selection; diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 2e0794919..081d101fe 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -284,9 +284,9 @@ pub(crate) enum ColumnSweep { /// The first sweep of the measuring run of the column `Id`: each held fill-width child reports the width it /// measured at (`layout::report_held`). Count(Id), - /// The width the column settled on, in its second sweep and in the real run after one: a held fill-width child - /// measures and shows across it. - Column(f32), + /// The width the content-sized `Stack` column `Id` settled on, in its second sweep and in the real run after one: + /// a held fill-width child measures and shows across it, and a held picture measures in it. + Column(Id, f32), } /// The line of an unwrapped `Row` body, as its direct children placed in flow see it: a child of one line sits with diff --git a/crates/ui-contract/src/runtime/env/view.rs b/crates/ui-contract/src/runtime/env/view.rs index 42d7cb568..b418809b6 100644 --- a/crates/ui-contract/src/runtime/env/view.rs +++ b/crates/ui-contract/src/runtime/env/view.rs @@ -58,6 +58,14 @@ impl<'a> EnvView<'a> { self.scoped.measure } + /// The content-sized `Stack` column whose first sweep runs now, if the scope is a direct child of it in flow. + pub(crate) fn column_first_sweep(&self) -> Option { + match self.scoped.column { + Some(super::ColumnSweep::Count(column)) => Some(column), + _ => None, + } + } + /// The inside label the scope carries ([`inside_label`](EnvView::inside_label) reads it back). pub(crate) fn inside_held(&self) -> Option<&'a Held> { self.scoped.inside_label.as_ref() diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index 3894fd46b..e3bd41318 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -1236,7 +1236,7 @@ pub(crate) mod guard { ("layout::column_group::Open", "column groups: frames the run opens and closes; reports go through contribute"), ("access::scope::Stack", "label and merge scopes: opened and closed by the run; control minimums go through contribute"), ("layout::body::FillCounts", "fill counts: opened and closed by the body's own measuring sweep"), - ("layout::body::HeldWidths", "held widths: opened and closed by the column's own first sweep"), + ("layout::body::HeldWidths", "held children: opened by the column's own first sweep and closed after its last"), ("layout::body::FirstLines", "first lines: opened and closed by the container's own measuring sweep; the line goes through emit_record"), ("layout::body::RowLines", "row lines: opened by each sweep of the row and closed after it; the line goes through emit_record"), ( diff --git a/crates/ui-contract/tests/it/layout/body.rs b/crates/ui-contract/tests/it/layout/body.rs index c5a9edcd7..a8055982a 100644 --- a/crates/ui-contract/tests/it/layout/body.rs +++ b/crates/ui-contract/tests/it/layout/body.rs @@ -1,14 +1,14 @@ //! `BodyLayout` under direction: the physical layouts, measured `Row` placement and the `Grid` cursor; a content-sized //! column's held children, a spread row's room and the end region's line. -use craft_behavior::{ColumnWidth, Proposal, Sense}; +use craft_behavior::{ColumnWidth, Insets, Metrics, Proposal, Sense}; use craft_ui::contract::{ BodyCx, Common, Component, Container, ContainerProps, Cx, EndRegion, MeasureCx, MemoProps, MemoView, Props as _, Role, Show as _, ShowContainer as _, Sizing, }; use craft_ui::layout::{BodyLayout, RowAlign}; use craft_ui::runtime::env::{Direction, with_env}; -use craft_ui::style::StyleCx; +use craft_ui::style::{ComponentStyle, StyleCx}; use craft_ui::testing::layout::{Block, body}; use craft_ui::testing::{Fixture, Frames, is_measuring, trial}; use craft_ui_test_kit::contract::{Panel, PlainStyle, Probe, Seen}; @@ -238,6 +238,145 @@ fn a_held_fill_width_child_measures_again_only_when_a_sibling_widens_the_column( assert!(unbounded >= 1 && bounded == 0, "the narrower sibling: the held child measured again: {unbounded} and {bounded}"); } +/// A picture from `least` up to `MOST_PICTURE` wide: square (`picture_size`), or a band of its own height +/// (`picture_width`), with `PICTURE_PAD` of padding at each side. +#[derive(Component)] +struct Picture<'a> { + #[common] + common: Common, + least: f32, + square: bool, + seen: &'a RefCell, + measures: &'a Measures, +} + +/// The widest a `Picture` takes. +const MOST_PICTURE: f32 = 1000.0; + +/// A `Picture`'s padding at each side. +const PICTURE_PAD: f32 = 20.0; + +/// A style padded `PICTURE_PAD` at each side. +#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)] +struct PaddedStyle { + #[style(metrics)] + metrics: Metrics, +} + +impl Component for Picture<'_> { + const ROLE: Role = Role::GROUP; + type Style = PaddedStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: PictureStyleKey) -> PaddedStyle { + PaddedStyle { metrics: Metrics::new().padding(Insets::new(PICTURE_PAD, PICTURE_PAD, 0.0, 0.0)) } + } + + fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { + if cx.proposal == Proposal::Ideal && is_measuring(cx.ui.ctx()) { + let count = if cx.room.is_some() { &self.measures.bounded } else { &self.measures.unbounded }; + count.set(count.get() + 1); + } + match self.square { + true => cx.picture_size(self.least, MOST_PICTURE, |width| width), + false => Vec2::new(cx.picture_width(self.least, MOST_PICTURE), LINE), + } + } + + fn sense(&self) -> Sense { + Sense::empty() + } + + fn update(&mut self, cx: &mut Cx<'_, Self>) { + self.seen.borrow_mut().rect = cx.rect; + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +/// The picture a column trial shows: its least width and whether it is square. +#[derive(Clone, Copy)] +struct Shown { + least: f32, + square: bool, +} + +impl Shown { + const fn square(least: f32) -> Self { + Shown { least, square: true } + } +} + +/// What a content-sized column shows with a picture (none when `None`), a `Wrap` and a probe under them `sibling` +/// wide: the column's rect, the picture's and the probe's, the picture's ideal measures in measuring runs without a +/// room and in one, and the wrap's. +struct PictureColumn { + rects: [Rect; 3], + picture: (usize, usize), + wrap: (usize, usize), +} + +fn picture_in_column(picture: Option, sibling: f32) -> PictureColumn { + let (seen, under, wrap) = + (Rc::new(RefCell::new(Seen::default())), Rc::new(RefCell::new(Seen::default())), Rc::new(RefCell::new(Seen::default()))); + let (pictures, wraps, column) = (Rc::new(Measures::default()), Rc::new(Measures::default()), Rc::new(Cell::new(Rect::NOTHING))); + let (shown_picture, shown_under, shown_wrap) = (Rc::clone(&seen), Rc::clone(&under), Rc::clone(&wrap)); + let (counted_pictures, counted_wraps, shown_column) = (Rc::clone(&pictures), Rc::clone(&wraps), Rc::clone(&column)); + let mut fixture = Fixture::new(move |ui| { + let shown = Panel::new().id_salt("column").show(ui, |ui, _| { + if let Some(Shown { least, square }) = picture { + let picture = Picture { common: Common::new(), least, square, seen: &shown_picture, measures: &counted_pictures }; + picture.id_salt("picture").show(ui); + } + Wrap::new(&shown_wrap, &counted_wraps).id_salt("wrap").show(ui); + Probe::new(&shown_under).size(Vec2::new(sibling, LINE)).id_salt("under").show(ui); + }); + shown_column.set(shown.output.rect); + }); + fixture.room(Vec2::splat(800.0)).settle(); + let rects = [column.get(), seen.borrow().rect, under.borrow().rect]; + PictureColumn { rects, picture: (pictures.unbounded.get(), pictures.bounded.get()), wrap: (wraps.unbounded.get(), wraps.bounded.get()) } +} + +// A square picture in a content-sized column takes no width of its own there; the column settles on its siblings' +// width and the picture shows across it, as tall as wide, with what follows it laid out below the shown square. +#[trial] +fn a_square_picture_in_a_content_column_pushes_what_follows_below_its_shown_size() { + let PictureColumn { rects: [column, picture, under], .. } = picture_in_column(Some(Shown::square(60.0)), 300.0); + let dump = format!("column {column:?}, picture {picture:?}, under {under:?}"); + assert!(picture.width() > 60.0 + 2.0 * PICTURE_PAD + SLACK, "the picture shows wider than its least, across the column: {dump}"); + assert!((picture.width() - 2.0 * PICTURE_PAD - picture.height()).abs() < SLACK, "a square picture's content is as tall as it shows wide: {dump}"); + assert!(under.top() >= picture.bottom() - SLACK, "what follows lies below the shown picture: {dump}"); + assert!(column.bottom() >= under.bottom() - SLACK, "the column holds everything it shows: {dump}"); +} + +// Count trial: a column whose square picture took its least sweeps again once at its settled width; a column without +// a picture, whose square picture is its widest child (padding included), or whose picture is a band of its own +// height, sweeps once. +#[trial] +fn a_content_column_sweeps_again_only_for_a_square_picture_narrower_than_it() { + let none = picture_in_column(None, 300.0); + let narrow = picture_in_column(Some(Shown::square(60.0)), 300.0); + assert!(none.wrap.0 >= 1 && none.wrap.1 == 0, "no picture: the column sweeps its children: {:?}", none.wrap); + let (unbounded, bounded) = narrow.picture; + assert!( + bounded >= 1 && bounded == unbounded, + "a narrower square picture measures once more per measuring run, at the column: {unbounded} and {bounded}" + ); + let once = [ + ("a square picture wider than the column", Shown::square(400.0)), + ("a square picture as wide as the column with its padding", Shown::square(300.0 - 2.0 * PICTURE_PAD)), + ("a band picture", Shown { least: 60.0, square: false }), + ]; + for (what, shown) in once { + let column = picture_in_column(Some(shown), 300.0); + assert_eq!(column.wrap, none.wrap, "{what} adds no sweep"); + assert!(column.picture.0 >= 1 && column.picture.1 == 0, "{what} keeps its first measure: {:?}", column.picture); + } +} + #[trial] fn a_space_between_child_leaves_room_for_the_siblings_after_it() { let (first, last) = (Rc::new(RefCell::new(Seen::default())), Rc::new(RefCell::new(Seen::default()))); diff --git a/crates/ui-panels/src/dialog/prompt.rs b/crates/ui-panels/src/dialog/prompt.rs index d9e890628..42a3d23a0 100644 --- a/crates/ui-panels/src/dialog/prompt.rs +++ b/crates/ui-panels/src/dialog/prompt.rs @@ -103,10 +103,15 @@ impl Outcome for PromptOutput { } /// The index Escape and the close action answer with: the answer of `chosen` when there is one, else Cancel, else -/// the first Other answer, else the default answer. +/// the first Alternate answer, else the first Other answer, else the default answer. fn escape_answer(answers: &[FooterButton], chosen: Option) -> Option { let find = |wanted: DialogRole| answers.iter().position(|answer| answer.role() == wanted); - chosen.and_then(find).or_else(|| find(DialogRole::Cancel)).or_else(|| find(DialogRole::Other)).or_else(|| default_answer(answers)) + chosen + .and_then(find) + .or_else(|| find(DialogRole::Cancel)) + .or_else(|| find(DialogRole::Alternate)) + .or_else(|| find(DialogRole::Other)) + .or_else(|| default_answer(answers)) } /// The first Accept answer, else the first Destructive one, whether it is enabled or not. diff --git a/crates/ui-panels/src/dialog/prompt/stories.rs b/crates/ui-panels/src/dialog/prompt/stories.rs index 84a5e1f81..2219bcc57 100644 --- a/crates/ui-panels/src/dialog/prompt/stories.rs +++ b/crates/ui-panels/src/dialog/prompt/stories.rs @@ -26,7 +26,7 @@ const AGES: [(&str, Duration); 4] = [ fn answers() -> [FooterButton; 3] { [ FooterButton::new("Save", DialogRole::Accept).letter('S'), - FooterButton::new("Don't Save", DialogRole::Other).letter('D'), + FooterButton::new("Don't Save", DialogRole::Alternate).letter('D'), FooterButton::new("Cancel", DialogRole::Cancel).letter('C'), ] } diff --git a/crates/ui-panels/src/dialog/prompts.rs b/crates/ui-panels/src/dialog/prompts.rs index a62726da4..2349889c1 100644 --- a/crates/ui-panels/src/dialog/prompts.rs +++ b/crates/ui-panels/src/dialog/prompts.rs @@ -79,7 +79,7 @@ impl PromptChoice { fn role(self) -> DialogRole { match self { PromptChoice::Proceed => DialogRole::Accept, - PromptChoice::Alternate => DialogRole::Other, + PromptChoice::Alternate => DialogRole::Alternate, PromptChoice::Cancel => DialogRole::Cancel, } } @@ -347,7 +347,7 @@ impl StandardPrompt { let own = self.buttons.iter().find(|(button, _)| *button == choice).map(|(_, label)| Reply::new(label.clone(), choice.role())); let reply = own.unwrap_or_else(|| match choice { PromptChoice::Proceed => Reply::new(proceed.clone(), role), - PromptChoice::Alternate => Reply::new(words.discard.clone(), DialogRole::Other), + PromptChoice::Alternate => Reply::new(words.discard.clone(), DialogRole::Alternate), PromptChoice::Cancel => Reply::new(common.cancel.clone(), DialogRole::Cancel), }); (choice, reply.enabled(enabled, None)) diff --git a/crates/ui-panels/src/dialog/recovery.rs b/crates/ui-panels/src/dialog/recovery.rs index 06cc70da0..1dfe997c6 100644 --- a/crates/ui-panels/src/dialog/recovery.rs +++ b/crates/ui-panels/src/dialog/recovery.rs @@ -105,7 +105,7 @@ impl RecoveryDialog { let message = words.recovery_message.fill(&[("name", self.document.name.as_str()), ("age", age.as_str())]); let reason = self.document.blocked.clone().map(|reason| Label::from_cow(reason.into())); let replies = vec![ - Reply::plain(words.recovery_discard.clone(), DialogRole::Other), + Reply::plain(words.recovery_discard.clone(), DialogRole::Alternate), Reply::plain(words.recovery_recover.clone(), DialogRole::Accept).enabled(reason.is_none(), reason), ]; let mut prompt = Prompt::new(words.recovery_title.clone(), message).answers(buttons(&env, replies)); diff --git a/crates/ui-panels/src/dialog/unsaved.rs b/crates/ui-panels/src/dialog/unsaved.rs index c716fc53a..e69c9a488 100644 --- a/crates/ui-panels/src/dialog/unsaved.rs +++ b/crates/ui-panels/src/dialog/unsaved.rs @@ -127,9 +127,9 @@ impl UnsavedChangesDialog { CloseAnswer::Save => Reply::new(if mac { &words.unsaved_save } else { &words.unsaved_yes }.clone(), DialogRole::Accept), CloseAnswer::DontSave if self.scope == CloseScope::Revert => Reply::new(words.unsaved_revert.clone(), DialogRole::Accept), CloseAnswer::DontSave if mac => { - Reply::new(words.unsaved_dont_save.clone(), DialogRole::Other).chord(Chord::new(Mods::CMD, Key::D)) + Reply::new(words.unsaved_dont_save.clone(), DialogRole::Alternate).chord(Chord::new(Mods::CMD, Key::D)) } - CloseAnswer::DontSave => Reply::new(words.unsaved_no.clone(), DialogRole::Other), + CloseAnswer::DontSave => Reply::new(words.unsaved_no.clone(), DialogRole::Alternate), CloseAnswer::Cancel => Reply::new(cancel.clone(), DialogRole::Cancel), }; (answer, reply) diff --git a/crates/ui-panels/src/sections/footer.rs b/crates/ui-panels/src/sections/footer.rs index 07c093c1f..1fc926d23 100644 --- a/crates/ui-panels/src/sections/footer.rs +++ b/crates/ui-panels/src/sections/footer.rs @@ -376,25 +376,34 @@ impl FooterDrop { pub enum DialogRole { /// The default outcome: the primary look, last in the row (first on Windows). Accept, - /// An outcome that destroys something: the danger look. + /// An outcome that destroys something (Delete, Replace): the danger look. It proceeds, so Windows puts it with the + /// accepting button, before Cancel. Destructive, /// Leaves without an outcome. Cancel, + /// Another answer that closes the question: No, Don't Save, Discard. It stands with the other outcomes on macOS + /// and Linux and next to the accepting button on Windows. + Alternate, /// Any other outcome. Other, } impl DialogRole { - /// The position in the row: later roles stand nearer the end. Windows puts the accepting button first and the - /// others after it; macOS and Linux put it last. + /// The position in the row: later roles stand nearer the end. Windows puts the committing buttons first (the + /// accepting one, then a destructive proceed) and the answers that close the question after them, before Cancel; + /// macOS and Linux put the accepting button last. fn rank(self, windows: bool) -> u8 { - let rank = match self { - DialogRole::Other => 0, - DialogRole::Destructive => 1, - DialogRole::Cancel => 2, - DialogRole::Accept => 3, - }; - if windows { 3 - rank } else { rank } + match (windows, self) { + (false, DialogRole::Other | DialogRole::Alternate) => 0, + (false, DialogRole::Destructive) => 1, + (false, DialogRole::Cancel) => 2, + (false, DialogRole::Accept) => 3, + (true, DialogRole::Accept) => 0, + (true, DialogRole::Destructive) => 1, + (true, DialogRole::Alternate) => 2, + (true, DialogRole::Cancel) => 3, + (true, DialogRole::Other) => 4, + } } } @@ -515,14 +524,15 @@ enum Content { } /// The indexes of `roles` in display order: by role rank, and in the given order within a rank. A column puts -/// `Accept` on top and `Cancel` under it on every platform, then the others. +/// `Accept` on top, `Alternate` and `Cancel` under it on every platform, then the others. pub(crate) fn display_order(roles: &[DialogRole], windows: bool, column: bool) -> Vec { let mut order: Vec = (0..roles.len()).collect(); if column { order.sort_by_key(|&at| match roles[at] { DialogRole::Accept => 0, - DialogRole::Cancel => 1, - DialogRole::Destructive | DialogRole::Other => 2, + DialogRole::Alternate => 1, + DialogRole::Cancel => 2, + DialogRole::Destructive | DialogRole::Other => 3, }); } else { order.sort_by_key(|&at| roles[at].rank(windows)); @@ -546,7 +556,7 @@ impl FooterBar { } /// The members stand in a column at the top of the bar, each as wide as the widest: the buttons of a dialog whose - /// footer stands beside the body. Buttons go `Accept`, `Cancel`, then the others in the given order. + /// footer stands beside the body. Buttons go `Accept`, `Alternate`, `Cancel`, then the others in the given order. #[must_use] pub fn column(mut self) -> Self { self.props = self.props.layout(BodyLayout::stack()); @@ -633,7 +643,7 @@ impl FooterBar { let variant = match button.role { DialogRole::Accept => Variant::PRIMARY, DialogRole::Destructive => Variant::DANGER, - DialogRole::Cancel | DialogRole::Other => Variant::SECONDARY, + DialogRole::Cancel | DialogRole::Alternate | DialogRole::Other => Variant::SECONDARY, }; let mut widget = Button::new(button.label.clone()).variant(variant).enabled(button.enabled).least_width(least); if column { diff --git a/crates/ui-panels/tests/it/dialogs.rs b/crates/ui-panels/tests/it/dialogs.rs index 5eac75e7e..ef4a79649 100644 --- a/crates/ui-panels/tests/it/dialogs.rs +++ b/crates/ui-panels/tests/it/dialogs.rs @@ -365,6 +365,75 @@ fn cmd_d_answers_dont_save_on_macos() { } } +/// The unsaved-changes buttons run Yes, No, Cancel on Windows and Don't Save, Cancel, Save on macOS; on every OS Escape +/// answers Cancel, and the Yes and No letters answer Save and Don't Save. +#[trial] +fn the_unsaved_question_orders_its_buttons_by_platform_and_answers_by_role() { + let order = |os: Os, names: [&str; 3]| { + let host = Rc::new(RefCell::new(DialogHost::new())); + let shown = Rc::clone(&host); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); + fixture.os(os); + host.borrow_mut().open(UnsavedChangesDialog::new(CloseScope::Close, "poster.psd")); + fixture.idle(6); + let lefts = names.map(|name| fixture.by_label(name).unwrap_or_else(|| panic!("{os:?}: {name} shows")).rect.left()); + assert!(lefts.windows(2).all(|pair| pair[0] < pair[1]), "{os:?}: {names:?} run left to right, at {lefts:?}"); + }; + order(Os::Windows, ["Yes", "No", "Cancel"]); + order(Os::Mac, ["Don't Save", "Cancel", "Save"]); + + for (key, expected) in [(egui::Key::Escape, CloseAnswer::Cancel), (egui::Key::Y, CloseAnswer::Save), (egui::Key::N, CloseAnswer::DontSave)] { + let host = Rc::new(RefCell::new(DialogHost::new())); + let shown = Rc::clone(&host); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); + fixture.os(Os::Windows); + host.borrow_mut().open(UnsavedChangesDialog::new(CloseScope::Close, "poster.psd")); + fixture.idle(6); + fixture.key(key, Modifiers::NONE).idle(4); + let answered = host.borrow_mut().take::().and_then(DialogResult::ok).map(|answer| answer.answer); + assert_eq!(answered, Some(expected), "{key:?} answers {expected:?}"); + } +} + +/// Apply, an auxiliary action, stands after Cancel on Windows; the Alternate role does not move it. +#[trial] +fn windows_puts_an_auxiliary_apply_after_cancel() { + let mut fixture = Fixture::new(|ui| { + let mut open = true; + Dialog::new("Options") + .opened(Bind::bound(&mut open)) + .buttons([ + FooterButton::new("OK", DialogRole::Accept), + FooterButton::new("Apply", DialogRole::Other).stays_open(true), + FooterButton::new("Cancel", DialogRole::Cancel), + ]) + .show(ui, |_, _| {}); + }); + fixture.os(Os::Windows); + fixture.idle(30); + let left = |name: &str| fixture.by_label(name).expect("the button shows").rect.left(); + assert!(left("OK") < left("Cancel") && left("Cancel") < left("Apply"), "OK, Cancel, Apply from the start edge"); +} + +/// A destructive proceed is a committing button: Windows puts it first, before Cancel; macOS keeps Cancel nearer the +/// end edge than Delete. +#[trial] +fn a_delete_prompt_reads_delete_then_cancel_on_windows() { + for os in [Os::Windows, Os::Mac] { + let mut fixture = Fixture::new(|ui| { + let mut open = true; + Dialog::new("Delete Layer") + .opened(Bind::bound(&mut open)) + .buttons([FooterButton::new("Cancel", DialogRole::Cancel), FooterButton::new("Delete", DialogRole::Destructive)]) + .show(ui, |_, _| {}); + }); + fixture.os(os); + fixture.idle(30); + let left = |name: &str| fixture.by_label(name).expect("the button shows").rect.left(); + assert!(left("Delete") < left("Cancel"), "{os:?}: Delete, then Cancel, from the start edge"); + } +} + /// Each open of a dialog has its own serial, kept while it stays open, though its id is the same at every open: a /// reopened dialog is told apart from the one cancelled before it. #[trial] diff --git a/crates/ui-patterns/src/patterns/form_dialogs/new_document/cards.rs b/crates/ui-patterns/src/patterns/form_dialogs/new_document/cards.rs index 6f2417c35..8e23f7791 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/new_document/cards.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/new_document/cards.rs @@ -11,7 +11,7 @@ use crate::primitives::{ContentPainterCx, StrokeWidth}; use crate::runtime::env::{Label, UnitKind}; use crate::style::TypeRole; use crate::tabs::{Tab, TabKind, TabStrip}; -use crate::tile_grid::{Tile, TileGrid}; +use crate::tile_grid::{CardText, Tile, TileGrid}; use craft_behavior::{DisplayOrder, ItemSource, Selection, SelectionChange, keyed}; use egui::{CornerRadius, Rect, Stroke, StrokeKind, Ui, vec2}; use std::borrow::Cow; @@ -175,6 +175,8 @@ pub(super) fn show(ui: &mut Ui, session: &Session, values: &DocumentOptions, rea let shown = TileGrid::::new(words.cards.clone()) .card_columns(CARD_COLUMNS) .card() + .card_text(CardText::Preset) + .fill_row() .aspect(2.0) .select(SelectMode::Single) .detail_line() diff --git a/crates/ui-patterns/src/patterns/form_dialogs/preview.rs b/crates/ui-patterns/src/patterns/form_dialogs/preview.rs index aa9960727..9ace92c87 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/preview.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/preview.rs @@ -441,8 +441,11 @@ impl Component for PreviewPane<'_> { } fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { - let width = cx.picture_width(cx.tokens.size.plot.width, f32::INFINITY); - Vec2::new(width, self.aspect.filter(|aspect| *aspect > 0.0).map_or(0.0, |aspect| width / aspect)) + let least = cx.tokens.size.plot.width; + match self.aspect.filter(|aspect| *aspect > 0.0) { + Some(aspect) => cx.picture_size(least, f32::INFINITY, |width| width / aspect), + None => Vec2::new(cx.picture_width(least, f32::INFINITY), 0.0), + } } fn sense(&self) -> Sense { diff --git a/crates/ui-patterns/tests/it/form_dialogs/new_document.rs b/crates/ui-patterns/tests/it/form_dialogs/new_document.rs index 760b341b0..a1678546b 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/new_document.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/new_document.rs @@ -301,3 +301,39 @@ fn section_captions_paint_in_capitals_and_keep_their_text() { assert!(shows(&fixture, "PRESET DETAILS"), "the caption paints in capitals"); assert!(fixture.by_label("Preset Details").is_some(), "the accessible name keeps the text as written"); } + +/// The preset cards fill the left column's width, and each card's title and size line are painted whole and centred +/// under the page outline. +#[trial] +fn the_preset_cards_fill_the_column_and_show_their_size_lines_whole() { + use craft_ui::contract::Gap; + use craft_ui::runtime::access::Role; + use std::cell::Cell; + + let mut options = DocumentOptions::default(); + let column_gap = Rc::new(Cell::new(0.0f32)); + let shared = Rc::clone(&column_gap); + let mut fixture = Fixture::new(move |ui| { + shared.set(Gap::Row.points(ui)); + let _ = NewDocumentDialog::new(Bind::bound(&mut options)).show(ui); + }); + fixture.room(Vec2::new(1400.0, 1000.0)).idle(30); + let photo = fixture.by_label("Photo").expect("the Photo tab"); + fixture.click(&photo).idle(10); + let cards = fixture.by_role(Role::LIST_ITEM); + assert!(cards.len() >= 3, "the tab lists presets"); + let first_row: Vec<_> = cards.iter().filter(|card| (card.rect.top() - cards[0].rect.top()).abs() < 1.0).collect(); + assert!(first_row.len() >= 2, "a row holds several cards"); + let details = fixture.by_label("Preset Details").expect("the details column").rect; + let column_end = details.left() - column_gap.get(); + let last = first_row.last().expect("a row has cards").rect; + assert!((column_end - last.right()).abs() <= 1.0, "the row's last card ends at the left column's end ({column_end}): {last:?}"); + for card in &first_row { + let lines: Vec<_> = fixture.texts().iter().filter(|text| card.rect.contains_rect(text.rect)).collect(); + assert!(lines.iter().any(|text| text.text.contains('\u{d7}')), "the card shows its size line: {:?}", card.rect); + for line in lines { + assert!(!line.elided, "{:?} is painted whole", line.text); + assert!((line.rect.center().x - card.rect.center().x).abs() <= 1.0, "{:?} is centred in its card", line.text); + } + } +} diff --git a/crates/ui-widgets/src/tile_grid/grid.rs b/crates/ui-widgets/src/tile_grid/grid.rs index d80d1036d..74c847c56 100644 --- a/crates/ui-widgets/src/tile_grid/grid.rs +++ b/crates/ui-widgets/src/tile_grid/grid.rs @@ -11,7 +11,7 @@ pub(crate) mod stories; use super::headers::Outline; use super::layout::{Around, ArrangeSpacing, GridLayout, Recipe, Slot, TailRow, TileGroup, Tiling, arrange, aspects_of, slot_at}; use super::tile::AroundPicture; -use super::{CaptionPlace, Tile, TilePartEvent, ZoomStep}; +use super::{CaptionPlace, CardText, Tile, TilePartEvent, ZoomStep}; use crate::contract::{ Access, Bind, BindMut, Collection, CollectionEvent, CollectionProps, CollectionResponse, ColumnKind, ColumnSpec, Common, Component, ContainerProps, Cx, DropKind, EditResponse, Focus as _, ListDrag, Meta as _, NoValue, Notch, Outcome, PaintUi, PartsCx, Pointer as _, Props as _, @@ -149,13 +149,13 @@ struct GridSizes { } impl GridSizes { - fn of(cx: &StyleCx<'_>, card: bool, rows: RowHeight, regular_card_padding: bool) -> GridSizes { + fn of(cx: &StyleCx<'_>, card: bool, text: CardText, rows: RowHeight, regular_card_padding: bool) -> GridSizes { let spacing = ArrangeSpacing::new(if card { cx.tokens.space.gap.section } else { cx.tokens.space.gap.stack }, cx.tokens.space.gap.inline, rows.of(cx)); GridSizes { card: cx.tokens.size.thumb.card, thumbs: [cx.tokens.size.thumb.sm, cx.tokens.size.thumb.md, cx.tokens.size.thumb.lg], - around: Tile::around(cx, card, regular_card_padding), + around: Tile::around(cx, card, text, regular_card_padding), spacing, // Bare tiles sit with no gap between them: the room around each picture keeps them apart. bare_spacing: if card { spacing } else { ArrangeSpacing { gap: 0.0, ..spacing } }, @@ -236,9 +236,13 @@ pub struct TileGrid<'a, K: Clone + Eq + Hash + Send + Sync + 'static> { /// Cards keep a line under the name for the tile's detail, whether a tile has one or not. #[prop(flag)] detail_line: bool, - /// Tiles are framed cards: the picture inset in a raised surface with the name and detail at the reading start. + /// Tiles are framed cards: the picture inset in a raised surface with the name and detail under it as `card_text` sets them. #[prop(flag)] card: bool, + /// How framed cards set their name and detail: the strong, start-aligned name of a file, or the centred regular + /// name of a preset. + #[prop] + card_text: CardText, /// Framed cards use the theme's regular padding around their picture and caption. #[prop(flag)] regular_card_padding: bool, @@ -314,6 +318,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> { caption: CaptionPlace::Below, detail_line: false, card: false, + card_text: CardText::File, regular_card_padding: false, groups: &[], collapsible: false, @@ -395,7 +400,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> { /// The layout of this pass: `previous` when it was made from the same recipe, else a new arrangement. A card is /// the picture plus what the tile adds around it in every tiling. fn laid_out(&self, previous: Option, source: &dyn ItemSource, width: f32, item: Option, cx: &StyleCx<'_>) -> GridLayout { - let style = GridSizes::of(cx, self.card, self.items.row_height, self.regular_card_padding); + let style = GridSizes::of(cx, self.card, self.card_text, self.items.row_height, self.regular_card_padding); let spacing = style.spacing(self.caption); let around = style.around.get(self.caption, self.detail_line); // A card never outgrows the grid: in a column narrower than a card the card takes the column. @@ -797,7 +802,7 @@ impl Collection for TileGrid<'_, K fn dress_inputs(&self) -> u64 { use std::hash::{Hash as _, Hasher as _}; let mut hasher = std::collections::hash_map::DefaultHasher::new(); - (self.caption, self.detail_line, self.card, self.regular_card_padding).hash(&mut hasher); + (self.caption, self.detail_line, self.card, self.card_text, self.regular_card_padding).hash(&mut hasher); hasher.finish() } @@ -806,7 +811,7 @@ impl Collection for TileGrid<'_, K if self.card_columns == 0 { return 0.0; } - let style = GridSizes::of(cx, self.card, self.items.row_height, self.regular_card_padding); + let style = GridSizes::of(cx, self.card, self.card_text, self.items.row_height, self.regular_card_padding); let aspect = if self.aspect.is_finite() && self.aspect > 0.0 { self.aspect } else { 1.0 }; let around = style.around.get(self.caption, self.detail_line); let card = style.card(self.picture_side(&style, item, around), aspect, around).x; @@ -830,7 +835,7 @@ impl Collection for TileGrid<'_, K /// Every tile gets the grid's caption place and detail line, the card look, and its row's rename state. fn dress<'r>(&self, tile: Self::Item<'r>, row: &RowState) -> Self::Item<'r> { let tile = tile.caption(self.caption).detail_line(self.detail_line).renaming(row.renaming); - if self.card { tile.card().regular_card_padding(self.regular_card_padding) } else { tile } + if self.card { tile.card().card_text(self.card_text).regular_card_padding(self.regular_card_padding) } else { tile } } fn can_rename(&self, key: &K) -> bool { diff --git a/crates/ui-widgets/src/tile_grid/mod.rs b/crates/ui-widgets/src/tile_grid/mod.rs index 8eba110b6..aafd99d82 100644 --- a/crates/ui-widgets/src/tile_grid/mod.rs +++ b/crates/ui-widgets/src/tile_grid/mod.rs @@ -36,6 +36,33 @@ pub enum CaptionPlace { None, } +/// How a framed card (`TileGrid::card`) sets its name and detail. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum CardText { + /// For cards of files (the start screen's recent documents): a strong name and the detail under it, both at the + /// reading start. + #[default] + File, + /// For cards of presets (New Document): a regular name and the detail under it, both centred. + Preset, +} + +impl CardText { + /// The type role of the name. + pub(super) fn name_role(self) -> craft_theme::TypeRole { + match self { + CardText::File => craft_theme::TypeRole::BodyStrong, + CardText::Preset => craft_theme::TypeRole::Body, + } + } + + /// Whether the name and detail are centred in the card. + pub(super) fn centred(self) -> bool { + self == CardText::Preset + } +} + /// A pick or reject flag. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] diff --git a/crates/ui-widgets/src/tile_grid/tile.rs b/crates/ui-widgets/src/tile_grid/tile.rs index 26d7cd831..89680c9c9 100644 --- a/crates/ui-widgets/src/tile_grid/tile.rs +++ b/crates/ui-widgets/src/tile_grid/tile.rs @@ -8,7 +8,7 @@ use super::layout::Around; use super::words::TileWords; -use super::{BadgeKind, BadgeSlot, BadgeVisibility, CaptionPlace, TileBadge, TileFlag, TileMark, TileStatus}; +use super::{BadgeKind, BadgeSlot, BadgeVisibility, CaptionPlace, CardText, TileBadge, TileFlag, TileMark, TileStatus}; use crate::buttons::IconButton; use crate::choice::{Checkbox, ChoiceWords, Rating}; use crate::contract::{ @@ -96,6 +96,7 @@ const RATING_REASON: &str = "In a tile grid with rating keys, the digits rate th #[derive(Clone, Copy, Debug, PartialEq)] struct Sizes { card: bool, + text: CardText, inset: f32, tight: f32, bar: f32, @@ -121,8 +122,8 @@ pub(super) struct AroundPicture { } impl AroundPicture { - fn of(cx: &StyleCx<'_>, card: bool, regular_card_padding: bool) -> AroundPicture { - let around = |place: CaptionPlace, detail: bool| Sizes::of(cx, card, place, regular_card_padding).around(place, detail); + fn of(cx: &StyleCx<'_>, card: bool, text: CardText, regular_card_padding: bool) -> AroundPicture { + let around = |place: CaptionPlace, detail: bool| Sizes::of(cx, card, text, place, regular_card_padding).around(place, detail); AroundPicture { below: around(CaptionPlace::Below, false), below_detail: around(CaptionPlace::Below, true), @@ -145,10 +146,10 @@ impl AroundPicture { impl Sizes { /// The sizes of a tile with its caption in `place`. A bare tile keeps only the room its selection ring draws in, so /// a grid packs bare tiles close. - fn of(cx: &StyleCx<'_>, card: bool, place: CaptionPlace, regular_card_padding: bool) -> Sizes { + fn of(cx: &StyleCx<'_>, card: bool, text: CardText, place: CaptionPlace, regular_card_padding: bool) -> Sizes { let (tokens, control) = (cx.tokens, cx.control()); let line = tokens.typography.get(TypeRole::Caption).line_height; - let name_line = if card { tokens.typography.get(TypeRole::BodyStrong).line_height } else { line }; + let name_line = if card { tokens.typography.get(text.name_role()).line_height } else { line }; let inset = match (card, place) { (true, _) if regular_card_padding => tokens.space.pad.regular, (true, _) => tokens.space.pad.control, @@ -157,6 +158,7 @@ impl Sizes { }; Sizes { card, + text, inset, tight: tokens.space.gap.tight, bar: control.height, @@ -305,11 +307,15 @@ pub struct Tile<'a> { /// The card has a line for the detail, whether this tile has one or not: the grid's, applied to its tiles. #[prop] detail_line: bool, - /// The tile is a framed card: the picture inset in a raised surface, the name strong and the detail under it, both - /// at the reading start. The grid's, applied to its tiles. + /// The tile is a framed card: the picture inset in a raised surface, with the name and detail under it as + /// `card_text` sets them. The grid's, applied to its tiles. #[style_key] #[prop(flag)] card: bool, + /// How a card sets its name and detail; the grid's, applied to its tiles. + #[style_key] + #[prop] + card_text: CardText, /// Draws the preview directly on the tile so a small symbol has no separate background or selection frame. #[style_key] #[prop(flag)] @@ -389,6 +395,7 @@ impl<'a> Tile<'a> { regular_card_padding: false, detail_line: false, card: false, + card_text: CardText::File, flat_thumbnail: false, detail: None, accessible_name: None, @@ -481,12 +488,12 @@ impl<'a> Tile<'a> { /// What a tile adds around its picture: its padding, the caption band under the picture or the column at its /// reading start. A tile grid sizes a tile as the picture plus this. pub fn around_picture(cx: &StyleCx<'_>, place: CaptionPlace, detail: bool) -> Around { - Sizes::of(cx, false, place, false).around(place, detail) + Sizes::of(cx, false, CardText::File, place, false).around(place, detail) } /// What a tile adds around its picture for every caption arrangement. - pub(super) fn around(cx: &StyleCx<'_>, card: bool, regular_card_padding: bool) -> AroundPicture { - AroundPicture::of(cx, card, regular_card_padding) + pub(super) fn around(cx: &StyleCx<'_>, card: bool, text: CardText, regular_card_padding: bool) -> AroundPicture { + AroundPicture::of(cx, card, text, regular_card_padding) } /// Whether the caption band holds a detail line. @@ -654,7 +661,7 @@ impl Component for Tile<'_> { let (state, text) = (&colors.state, &colors.text); let clear = Rgba::TRANSPARENT; let c = |rgba: Rgba| cx.color(rgba); - let sizes = Sizes::of(cx, key.card, key.caption, key.regular_card_padding); + let sizes = Sizes::of(cx, key.card, key.card_text, key.caption, key.regular_card_padding); // Selection and hover are rings around the picture; only a card has a fill of its own. let fill = if key.card { let raised = colors.surface.raised; @@ -693,11 +700,11 @@ impl Component for Tile<'_> { surface, metrics: Metrics::new().padding(Insets::new(sizes.inset, sizes.inset, sizes.inset, sizes.inset)).gap(sizes.tight), name: if key.card { - TextLook::new(TypeRole::BodyStrong, ink(c(text.normal))) + TextLook::new(key.card_text.name_role(), ink(c(text.normal))) } else { TextLook::new(TypeRole::Caption, ink(c(text.muted))) }, - name_failed: TextLook::new(if key.card { TypeRole::BodyStrong } else { TypeRole::Caption }, ink(cx.tone(Tone::Bad))), + name_failed: TextLook::new(if key.card { key.card_text.name_role() } else { TypeRole::Caption }, ink(cx.tone(Tone::Bad))), detail: TextLook::new(TypeRole::Caption, ink(c(if key.card { text.muted } else { text.faint }))), band_text: TextLook::new(TypeRole::Caption, fixed(text.on_status)).on(fixed(colors.status.bad.solid)), band_icon: IconLook::new(sizes.glyph, fixed(text.on_status)).on(fixed(colors.status.bad.solid)), @@ -1029,9 +1036,10 @@ impl Tile<'_> { } } - /// Where a caption line of `width` starts in `rect`: centred, or at the reading start in a card. - fn text_x(&self, rect: Rect, width: f32, cx: &Cx<'_, Self>) -> f32 { - match (cx.style.sizes.card, cx.flow.is_rtl()) { + /// Where a caption line of `width` starts in `rect`: centred, or at the reading start in a card of files. + fn text_x(rect: Rect, width: f32, cx: &Cx<'_, Self>) -> f32 { + let sizes = &cx.style.sizes; + match (sizes.card && !sizes.text.centred(), cx.flow.is_rtl()) { (false, _) => rect.center().x - width / 2.0, (true, false) => rect.left(), (true, true) => rect.right() - width, @@ -1051,7 +1059,7 @@ impl Tile<'_> { if !self.renaming { let run = TextRun::new(cx.resolved.label).role(look.role).color(ink).wrap(Wrap::ElideMiddle); let layout = draw.layout(&run, placed.name.width()); - let at = Pos2::new(self.text_x(placed.name, layout.size().x, cx), placed.name.top()); + let at = Pos2::new(Self::text_x(placed.name, layout.size().x, cx), placed.name.top()); draw.galley(at, &layout); if self.hidden && self.caption == CaptionPlace::Start { let name = Rect::from_min_size(at, layout.size()); @@ -1061,7 +1069,7 @@ impl Tile<'_> { if let (Some(detail), Some(rect)) = (&self.detail, placed.detail) { let run = TextRun::new(detail.as_str()).role(style.detail.role).color(cx.resolve(&style.detail.color)).wrap(Wrap::ElideMiddle); let layout = draw.layout(&run, rect.width()); - draw.galley(Pos2::new(self.text_x(rect, layout.size().x, cx), rect.top()), &layout); + draw.galley(Pos2::new(Self::text_x(rect, layout.size().x, cx), rect.top()), &layout); } for (mark, rect) in self.marks.iter().zip(&placed.marks) { draw.icon(*rect, &IconSpec::svg(mark.icon.clone()).color(cx.resolve(&style.mark.color))); diff --git a/crates/ui-widgets/tests/it/tile_grid/tile.rs b/crates/ui-widgets/tests/it/tile_grid/tile.rs index 057cfab59..74b205b3a 100644 --- a/crates/ui-widgets/tests/it/tile_grid/tile.rs +++ b/crates/ui-widgets/tests/it/tile_grid/tile.rs @@ -5,7 +5,7 @@ use craft_theme::Srgba; use craft_ui::contract::Show as _; use craft_ui::testing::layout::in_region; use craft_ui::testing::{Frames, trial}; -use craft_ui::tile_grid::{BadgeVisibility, Tile, TileFlag}; +use craft_ui::tile_grid::{BadgeVisibility, CardText, Tile, TileFlag}; use egui::{Rect, Shape, pos2, vec2}; /// The tile's rect and the bounds of the glyphs (stars and flag) and colour dots it paints in a region `width` wide. @@ -60,3 +60,24 @@ fn the_badge_bar_leaves_out_what_does_not_fit_and_never_overlaps() { } } } + +/// A card of a preset centres its name; a card of a file sets it at the reading start. +#[trial] +fn card_text_places_the_name_centred_for_presets_and_at_the_start_for_files() { + let name_in = |text: CardText| { + let mut frames = Frames::new(); + let mut tile = Rect::NOTHING; + for _ in 0..3 { + frames.frame(Vec::new(), |ui| { + let region = Rect::from_min_size(pos2(0.0, 0.0), vec2(300.0, 300.0)); + tile = in_region(ui, region, |ui| Tile::new("Poster").card().card_text(text).detail("Just now").show(ui).response.rect); + }); + } + let name = frames.texts().iter().find(|line| line.text == "Poster").expect("the name is painted").rect; + (tile, name) + }; + let (tile, name) = name_in(CardText::Preset); + assert!((name.center().x - tile.center().x).abs() <= 1.0, "a preset's name is centred: {name:?} in {tile:?}"); + let (tile, name) = name_in(CardText::File); + assert!(name.left() - tile.left() < tile.width() / 4.0, "a file's name starts at the tile's start edge: {name:?} in {tile:?}"); +} diff --git a/docs/contract-api.md b/docs/contract-api.md index f5b3b99ef..479a32dd0 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -538,11 +538,11 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn add_document(&mut self, document: &D)`. Adds `document` to the first docked group, or to a new docked group when there is none. A document a group - `pub fn to_actions(&self, layout: &Layout

, panel_of: impl Fn(u64) -> P) -> Vec>`. The dock actions that put `self` into `layout`, for the dock to draw the windows. The - `craft_behavior::dock::Floating`: `pub struct Floating

{ pub id: u64, pub column: Column

, pub rect: Rect, pub native: Option, pub edge: Option }`. A floating window: one column of groups, the same [`Column`] a dock holds. Nothing sits beside the column - - `pub fn new(column: Column

, rect: Rect) -> Self`. A window holding `column`. Each call makes a new window, with a fresh [`Self::id`]: build - - `pub fn single(panels: Vec

, active: usize, rect: Rect) -> Self`. A window with one group. Each call makes a new window, as [`Self::new`] does. - - `pub fn with_id(mut self, id: u64) -> Self`. The window with `id`, for a layout the app builds in code, such as a default layout: + - `pub fn new(id: u64, column: Column

, rect: Rect) -> Self`. The window `id` holding `column`. Ids are unique within a layout; a window added to a live layout takes its id + - `pub fn single(id: u64, panels: Vec

, active: usize, rect: Rect) -> Self`. The window `id` with one group. + - `pub fn with_id(mut self, id: u64) -> Self`. The window with `id` in place of its own. Ids must be unique within a layout. - `pub fn panels(&self) -> impl Iterator`. Every panel in the window, top group first. - - `pub fn stack(groups: Vec>, rect: Rect) -> Option`. A window of `groups`, stacked top to bottom, expanded. `None` without groups. Each call makes a new window, + - `pub fn stack(id: u64, groups: Vec>, rect: Rect) -> Option`. The window `id` of `groups`, stacked top to bottom, expanded. `None` without groups. - `pub fn groups(&self) -> &[Group

]`. The window's groups, top to bottom. - `pub fn contains(&self, panel: &Q) -> bool where P: std::borrow::Borrow,`. True when a group of this window holds `panel`. Takes any borrowed form of `P`, such - `craft_behavior::dock::Group`: `pub struct Group

{ pub panels: Vec

, pub active: usize, pub minimized: bool, pub height: Option, pub flyout_width: Option, pub flyout_offset: Option }`. Tabs that move, minimize and size together in a column, docked or floating. @@ -553,7 +553,9 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub const fn with_flyout_width(mut self, width: Option) -> Self`. The location with the group's flyout `width` points wide. - `pub const fn with_flyout_offset(mut self, offset: Option) -> Self`. The location with the group's flyout top `offset` points from its icons' top. - `craft_behavior::dock::Layout`: `pub struct Layout

{ pub root: Option>, pub floating: Vec> }`. The panels of a workspace: a docked tree plus floating windows. Every panel occurs once. - - `pub fn new(root: Option>, floating: Vec>) -> Self`. A layout with the docked tree `root` and the floating windows `floating`. + - `pub fn new(root: Option>, floating: Vec>) -> Self`. A layout with the docked tree `root` and the floating windows `floating`. New windows take ids above every id + - `pub fn fresh_window_id(&mut self) -> u64`. An id for a new floating window: above every window id the layout held when it was built or loaded and every + - `pub fn window_floor(&self) -> u64`. The least id above every id the layout holds or has held. - `pub fn validate(&self) -> Result<(), DockError>`. Check depth, allocation bounds, geometry, selection, globally unique panel ownership and - `pub fn panels(&self) -> Vec<&P>`. Iterate identities without recursion. On excessive input returns no more than the limit. - `pub fn contains(&self, panel: &P) -> bool`. Whether the layout holds `panel`, docked or floating. @@ -600,10 +602,17 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn new_dock(side: DockEdge) -> Self`. Builds [`Target::NewDock`]. - `pub fn float(rect: Rect) -> Self`. Builds [`Target::Float`] with no edge: the area takes the edge nearer `rect`. - `pub fn float_with_edge(rect: Rect, edge: Option) -> Self`. Builds [`Target::Float`] with the edge a collapsed window keeps to. -- `craft_behavior::dock::Workspace`: `pub struct Workspace

{ pub version: u32, pub layout: Layout

, pub hidden: Vec<(P, Location

)>, pub floated: Vec<(P, Location

)> }`. A saved arrangement of panels: the [`Layout`] and the closed panels' former places. +- `craft_behavior::dock::Workspace`: `pub struct Workspace

`. A saved arrangement of panels: the [`Layout`] and the closed panels' former places. - `pub const VERSION: u32`. The format version written to files. Version 4 saves a floating window as one column; older floating - - `pub fn revision(&self) -> u64`. The revision of this live workspace: it changes with every [`replace`](Self::replace) and nothing else. - - `pub fn replace(&mut self, with: Workspace

)`. Replaces the arrangement with `with` and moves to the next revision. + - `pub fn version(&self) -> u32`. The format version the workspace was read with. + - `pub fn layout(&self) -> &Layout

`. The current arrangement. + - `pub fn hidden(&self) -> &[(P, Location

)]`. The closed panels, and panels the application does not register now, with where each one goes back. + - `pub fn floated(&self) -> &[(P, Location

)]`. The floating panels with the docked location each one left. + - `pub fn revision(&self) -> Revision`. The revision of this workspace value: it moves with every write, and no other value has it. + - `pub fn generation(&self) -> u64`. The generation of this live workspace: it moves with every [`replace`](Self::replace) and nothing else. + - `pub fn raise_window_floor(&mut self, floor: u64)`. Keeps the ids of new floating windows at or above `floor`. A dock that showed windows below `floor` raises a + - `pub fn forget_hidden(&mut self, forget: impl Fn(&P) -> bool)`. Drops the closed-panel records of the panels `forget` names, so reopening them does not restore their place. + - `pub fn replace(&mut self, with: Workspace

)`. Replaces the arrangement with `with` and moves to the next generation. The windows of `with` take ids this - `pub fn apply(&mut self, action: Action

, locked: bool, permissions: impl Fn(&P) -> Permissions) -> Result, DockError>`. Apply one action. Closed panels record where they go back, so each one can be reopened - `pub fn apply_all(&mut self, actions: impl IntoIterator>, locked: bool, permissions: impl Fn(&P) -> Permissions,) -> Result, DockError>`. Apply every action in order, or none, as [`Self::apply`] does. Returns the panels the - `craft_behavior::dock::WorkspaceChrome`: `pub struct WorkspaceChrome { pub menu_bar: bool, pub tool_rail: bool, pub options_bar: bool, pub status_bar: bool }`. Chrome a workspace remembers beside the dock layout: which bars show. The default shows every bar. @@ -1955,6 +1964,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn labelled_with(&mut self, ui: &mut Ui, key: impl Hash + Debug, label: Label, side: SideLabel, child: C, content: D,) -> C::Output`. `labelled`, with `content` shown inside the label after its text (a sample of what the option picks). The - `pub fn style(&self) -> Option<&'a C::Style>`. The style of the container `C` whose body this is, as step 2 resolved it for this pass: the one way a body - `pub fn gap(&self) -> Option`. The gap the body's layout puts between its children (`ContainerProps::body_gap`), for a body that places + - `pub fn derived(&self, key: &K, build: impl FnOnce() -> V) -> std::sync::Arc`. The value this body derives from `key`: kept while `key` is unchanged, else built by `build` - `pub fn take_cancel(&mut self) -> bool`. Takes the Escape of this pass that no component took: a field that clears on Escape passes it on once it - `craft_ui::contract::BodyLayout`: `pub enum BodyLayout { Stack, Row { wrap: bool, align: RowAlign }, Grid { columns: Cow<'static, [ColumnWidth]>, fit: GridFit, cells: CellAlign } }`. How a body lays out its children, in reading order: mirrored under a right-to-left direction. - `pub const fn stack() -> Self`. Children one under another. @@ -1964,6 +1974,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn cells(self, cells: CellAlign) -> Self`. A `Grid` with `cells`; any other layout is unchanged. - `pub fn wrap(self, on: bool) -> Self`. A `Row` that wraps; any other layout is unchanged. - `pub fn align(self, align: RowAlign) -> Self`. A `Row` with `align`; any other layout is unchanged. +- `craft_ui::contract::Bracket`: `pub enum Bracket { Linked, Unlinked }`. The bracket a `Row` draws from the labelled rows of its first child to the child after them (Image Size's width and - `craft_ui::contract::CanvasGesture`: re-export of `craft_ui::runtime::sampler::CanvasGesture`. - `craft_ui::contract::CellWidth`: `pub type CellWidth = ColumnWidth`. The width of a caption's cell. - `craft_ui::contract::Collapse`: `pub struct Collapse { pub initially_open: bool, pub animated: bool }`. Collapse configuration. @@ -1971,7 +1982,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub const fn initially_open(mut self, on: bool) -> Self`. Whether the body starts open. - `pub const fn animated(mut self, on: bool) -> Self`. Whether opening and closing animate. - `craft_ui::contract::CollectionEvent`: `pub enum CollectionEvent { Selection(SelectionChange), LeadMoved { key: K, by: LeadSource }, Activate(K), Rested(K), EmptyActivated, EmptyContextMenu { at: Pos2 }, Preview(K), ContextMenu(ContextMenuRequest), EdgePressed { above: K, below: K, mods: craft_keymap::Mods }, CommandClick { key: K, mods: craft_keymap::Mods }, Delete(Vec), Open(OpenChange), Reorder(EditEvent>), Move(EditEvent), Dropped { at: DropAt, op: DropOperation, payload: DropPayload }, Zoom { factor: f32, about: Pos2 }, Rename(EditEvent>), Toggle(EditEvent>), Column(ColumnEvent), Item(K, E) }`. What a collection reports, in drawing order. -- `craft_ui::contract::CollectionProps`: `pub struct CollectionProps { pub select: SelectMode, pub reorder: Option, pub rename: bool, pub rename_column: Option, pub slow_click_rename: bool, pub columns: Vec, pub sort: Option, pub empty: Option