Merge pull request #2796 from aiongg/rework-d1

Dialogs and prompts: Curves fields, Levels midtone, Windows prompt order, preset cards
This commit is contained in:
aiongg authored and GitHub committed 2026-11-21 12:42:10 -05:00
commit 0f8a553365
31 files changed
+670 -138

No files matched your search

+2 -1
View File
@@ -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 {
+2 -1
View File
@@ -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 {
+29 -18
View File
@@ -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<LevelsClip>,
/// 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<f64>, 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];
+1 -1
View File
@@ -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 {
+32 -2
View File
@@ -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);
}
}
}
}
+66 -1
View File
@@ -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::<Adjust>().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<Curves, &'static str>;
// 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::<CurvesDialog>() {
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::<CurvesDialog>().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");
}
@@ -295,7 +295,7 @@ impl<C: Container> ShapeHooks<C> 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);
+23 -6
View File
@@ -78,11 +78,11 @@ impl<C: Component> 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<C: Component> 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<C: Component> 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
+16 -4
View File
@@ -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))),
},
+48 -23
View File
@@ -137,21 +137,40 @@ pub(crate) struct Cursors(IdMap<Cursor>);
#[derive(Default)]
pub(crate) struct FillCounts(IdMap<u32>);
/// 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<f32>);
/// 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<IdMap<(HeldKind, f32)>>);
/// 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::<HeldWidths, _>(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<HeldKind> {
pass_state::with::<HeldWidths, _>(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<R>(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<R>(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::<HeldWidths, _>(&ctx, |held| held.0.insert(id, f32::INFINITY));
pass_state::with::<HeldWidths, _>(&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::<HeldWidths, _>(&ctx, |held| held.0.remove(&id));
let narrowest = pass_state::with::<HeldWidths, _>(&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::<HeldWidths, _>(&ctx, |held| held.0.remove(&id));
inner
}
/// What places the children in flow of a body that places them itself.
+4 -4
View File
@@ -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,
};
@@ -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;
+3 -3
View File
@@ -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
+8
View File
@@ -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<Id> {
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()
@@ -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"),
(
+141 -2
View File
@@ -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<Seen>,
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<Shown>, 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())));
+7 -2
View File
@@ -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<DialogRole>) -> Option<usize> {
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.
@@ -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'),
]
}
+2 -2
View File
@@ -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))
+1 -1
View File
@@ -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));
+2 -2
View File
@@ -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)
+25 -15
View File
@@ -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<usize> {
let mut order: Vec<usize> = (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 {
+69
View File
@@ -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::<UnsavedChangesDialog>().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]
@@ -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::<usize>::new(words.cards.clone())
.card_columns(CARD_COLUMNS)
.card()
.card_text(CardText::Preset)
.fill_row()
.aspect(2.0)
.select(SelectMode::Single)
.detail_line()
@@ -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 {
@@ -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);
}
}
}
+13 -8
View File
@@ -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<GridLayout>, source: &dyn ItemSource<K>, width: f32, item: Option<Vec2>, 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<K: Clone + Eq + Hash + Send + Sync + 'static> 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<K: Clone + Eq + Hash + Send + Sync + 'static> 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<K: Clone + Eq + Hash + Send + Sync + 'static> 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 {
+27
View File
@@ -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]
+26 -18
View File
@@ -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)));
+22 -1
View File
@@ -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:?}");
}
+47 -15
View File
@@ -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<P: Clone + Eq + Hash>(&self, layout: &Layout<P>, panel_of: impl Fn(u64) -> P) -> Vec<Action<P>>`. The dock actions that put `self` into `layout`, for the dock to draw the windows. The
- `craft_behavior::dock::Floating`: `pub struct Floating<P> { pub id: u64, pub column: Column<P>, pub rect: Rect, pub native: Option<Placement>, pub edge: Option<DockEdge> }`. A floating window: one column of groups, the same [`Column`] a dock holds. Nothing sits beside the column
- `pub fn new(column: Column<P>, rect: Rect) -> Self`. A window holding `column`. Each call makes a new window, with a fresh [`Self::id`]: build
- `pub fn single(panels: Vec<P>, 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<P>, 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<P>, 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<Item = &P>`. Every panel in the window, top group first.
- `pub fn stack(groups: Vec<Group<P>>, rect: Rect) -> Option<Self>`. 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<Group<P>>, rect: Rect) -> Option<Self>`. The window `id` of `groups`, stacked top to bottom, expanded. `None` without groups.
- `pub fn groups(&self) -> &[Group<P>]`. The window's groups, top to bottom.
- `pub fn contains<Q: ?Sized + PartialEq>(&self, panel: &Q) -> bool where P: std::borrow::Borrow<Q>,`. True when a group of this window holds `panel`. Takes any borrowed form of `P`, such
- `craft_behavior::dock::Group`: `pub struct Group<P> { pub panels: Vec<P>, pub active: usize, pub minimized: bool, pub height: Option<f32>, pub flyout_width: Option<f32>, pub flyout_offset: Option<f32> }`. 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<f32>) -> Self`. The location with the group's flyout `width` points wide.
- `pub const fn with_flyout_offset(mut self, offset: Option<f32>) -> Self`. The location with the group's flyout top `offset` points from its icons' top.
- `craft_behavior::dock::Layout`: `pub struct Layout<P> { pub root: Option<Node<P>>, pub floating: Vec<Floating<P>> }`. The panels of a workspace: a docked tree plus floating windows. Every panel occurs once.
- `pub fn new(root: Option<Node<P>>, floating: Vec<Floating<P>>) -> Self`. A layout with the docked tree `root` and the floating windows `floating`.
- `pub fn new(root: Option<Node<P>>, floating: Vec<Floating<P>>) -> 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<DockEdge>) -> Self`. Builds [`Target::Float`] with the edge a collapsed window keeps to.
- `craft_behavior::dock::Workspace`: `pub struct Workspace<P> { pub version: u32, pub layout: Layout<P>, pub hidden: Vec<(P, Location<P>)>, pub floated: Vec<(P, Location<P>)> }`. A saved arrangement of panels: the [`Layout`] and the closed panels' former places.
- `craft_behavior::dock::Workspace`: `pub struct Workspace<P>`. 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<P>)`. 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<P>`. The current arrangement.
- `pub fn hidden(&self) -> &[(P, Location<P>)]`. The closed panels, and panels the application does not register now, with where each one goes back.
- `pub fn floated(&self) -> &[(P, Location<P>)]`. 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<P>)`. 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<P>, locked: bool, permissions: impl Fn(&P) -> Permissions) -> Result<Vec<P>, 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<Item = Action<P>>, locked: bool, permissions: impl Fn(&P) -> Permissions,) -> Result<Vec<P>, 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<C: Show, D: Show>(&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<C: Container>(&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<f32>`. The gap the body's layout puts between its children (`ContainerProps::body_gap`), for a body that places
- `pub fn derived<K: crate::contract::MemoProps, V: Send + Sync + 'static>(&self, key: &K, build: impl FnOnce() -> V) -> std::sync::Arc<V>`. 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<K, E> { Selection(SelectionChange<K>), LeadMoved { key: K, by: LeadSource }, Activate(K), Rested(K), EmptyActivated, EmptyContextMenu { at: Pos2 }, Preview(K), ContextMenu(ContextMenuRequest<K>), EdgePressed { above: K, below: K, mods: craft_keymap::Mods }, CommandClick { key: K, mods: craft_keymap::Mods }, Delete(Vec<K>), Open(OpenChange<K>), Reorder(EditEvent<ReorderMove<K>>), Move(EditEvent<Vec2>), Dropped { at: DropAt<K>, op: DropOperation, payload: DropPayload }, Zoom { factor: f32, about: Pos2 }, Rename(EditEvent<Rename<K>>), Toggle(EditEvent<ToggleEdit<K>>), 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<ReorderRule>, pub rename: bool, pub rename_column: Option<ColumnKey>, pub slow_click_rename: bool, pub columns: Vec<ColumnSpec>, pub sort: Option<ColumnSort>, pub empty: Option<Label>, pub activate: ActivateOn, pub striped: bool, pub allow_empty: bool, pub lead_on_open: LeadOnOpen, pub lead_follows_hover: bool, pub arrows_select: bool, pub focus_on_press: bool, pub rows_stamp: Option<u64>, pub space: SpaceAction, pub type_ahead: bool, pub arrows_wrap: bool, pub header: bool, pub digit_keys: bool, pub menu_on_click: bool, pub item_keys: ItemKeys, pub marquee: bool, pub deletable: bool, pub drag_payload: Option<DragPayload>, pub drag_count: Option<Counted>, pub natural_height: bool, pub min_rows: u16, pub max_rows: Option<u16>, pub row_height: RowHeight, pub command_click: bool, pub notch: Option<Notch>, pub overflow: Axis, pub pages: bool, pub current: Option<Arc<dyn Any + Send + Sync>>, pub select_under_drag: bool }`. What a collection reads from the app: plain data. A new builder's name is added to the forwarder list in
- `craft_ui::contract::CollectionProps`: `pub struct CollectionProps { pub select: SelectMode, pub reorder: Option<ReorderRule>, pub rename: bool, pub rename_column: Option<ColumnKey>, pub slow_click_rename: bool, pub columns: Vec<ColumnSpec>, pub sort: Option<ColumnSort>, pub empty: Option<Label>, pub activate: ActivateOn, pub striped: bool, pub allow_empty: bool, pub lead_on_open: LeadOnOpen, pub hover_lead: HoverLead, pub arrows_select: bool, pub focus_on_press: bool, pub rows_stamp: Option<u64>, pub space: SpaceAction, pub type_ahead: bool, pub arrows_wrap: bool, pub header: bool, pub digit_keys: bool, pub menu_on_click: bool, pub item_keys: ItemKeys, pub marquee: bool, pub deletable: bool, pub drag_payload: Option<DragPayload>, pub drag_count: Option<Counted>, pub natural_height: bool, pub min_rows: u16, pub max_rows: Option<u16>, pub row_height: RowHeight, pub command_click: bool, pub notch: Option<Notch>, pub overflow: Axis, pub pages: bool, pub current: Option<Arc<dyn Any + Send + Sync>>, pub select_under_drag: bool }`. What a collection reads from the app: plain data. A new builder's name is added to the forwarder list in
- `pub const fn new() -> Self`. Collection props with every setting at its default.
- `pub const fn select_under_drag(mut self, on: bool) -> Self`. Whether a foreign drag resting over an unselected item selects it (`select_under_drag`).
- `pub fn select(mut self, mode: SelectMode) -> Self`. What can be selected.
@@ -1988,7 +1999,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st
- `pub const fn striped(mut self, on: bool) -> Self`. Odd rows carry `RowState.striped`.
- `pub const fn allow_empty(mut self, on: bool) -> Self`. A press on the empty space below the rows empties the selection.
- `pub const fn lead_on_open(mut self, at: LeadOnOpen) -> Self`. Where the lead starts.
- `pub const fn lead_follows_hover(mut self, on: bool) -> Self`. The lead follows the pointer over the rows.
- `pub const fn hover_lead(mut self, hover: HoverLead) -> Self`. What the pointer moving over the rows changes.
- `pub const fn arrows_select(mut self, on: bool) -> Self`. Whether the arrow keys select the row they move the lead to.
- `pub const fn type_ahead(mut self, on: bool) -> Self`. Typed letters move the lead (`CollectionProps::type_ahead`).
- `pub const fn arrows_wrap(mut self, on: bool) -> Self`. The arrow keys wrap at the ends (`CollectionProps::arrows_wrap`).
@@ -2046,7 +2057,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st
- `craft_ui::contract::Common`: `pub struct Common { pub label: Label, pub tooltip: Option<Tooltip>, pub description: Option<String>, pub selected: Option<bool> }`. What every component carries: the props the pipeline reads at step 1.
- `pub const fn new() -> Common`. A `Common` with every prop unset, which the derive's constructors start from.
- `craft_ui::contract::Component`: re-export of `craft_ui_macros::Component` (outside these crates).
- `craft_ui::contract::ContainerProps`: `pub struct ContainerProps { pub mount: Mount, pub surface: Option<SurfaceKind>, pub pad: Pad, pub pad_edges: PadEdges, pub sizing: Sizing, pub content_in_bar: bool, pub room_height: Option<f32>, pub layout: BodyLayout, pub header: Option<HeaderRegion>, pub scroll: Option<Scroll>, pub footer: Option<FooterRegion>, pub end: Option<EndRegion>, pub help: Option<Label>, pub position: Option<SetPosition>, pub focus: FocusPolicy, pub collapse: Option<Collapse>, pub body_gap: Gap, pub least_width: Option<LeastWidth>, pub wrap_width: Option<WrapWidth>, pub edge_rule: bool, pub child_size: Option<ControlSize>, pub child_glyphs: Option<GlyphRole>, pub arena: bool, pub scroll_owner: bool, pub gates: bool, pub transform: Option<CanvasTransform>, pub theme: Option<ThemeScope>, pub command_scope: Option<CommandScope>, pub live: Option<Politeness>, pub label: Option<SideLabel>, pub roving: Option<Roving>, pub save: Option<SaveKey>, pub outer_edit: bool, pub collection_body: bool, pub label_column: bool, pub labels: Option<LabelScheme> }`. What a container or collection adds to `Common`. A builder added here is added to the forwarder list in
- `craft_ui::contract::ContainerProps`: `pub struct ContainerProps { pub mount: Mount, pub surface: Option<SurfaceKind>, pub pad: Pad, pub pad_edges: PadEdges, pub sizing: Sizing, pub content_in_bar: bool, pub room_height: Option<f32>, pub layout: BodyLayout, pub header: Option<HeaderRegion>, pub scroll: Option<Scroll>, pub footer: Option<FooterRegion>, pub end: Option<EndRegion>, pub help: Option<Label>, pub position: Option<SetPosition>, pub focus: FocusPolicy, pub collapse: Option<Collapse>, pub body_gap: Gap, pub least_width: Option<LeastWidth>, pub wrap_width: Option<WrapWidth>, pub edge_rule: bool, pub child_size: Option<ControlSize>, pub child_glyphs: Option<GlyphRole>, pub arena: bool, pub scroll_owner: bool, pub gates: bool, pub transform: Option<CanvasTransform>, pub theme: Option<ThemeScope>, pub command_scope: Option<CommandScope>, pub live: Option<Politeness>, pub label: Option<SideLabel>, pub roving: Option<Roving>, pub save: Option<SaveKey>, pub outer_edit: bool, pub collection_body: bool, pub label_column: bool, pub labels: Option<LabelScheme>, pub bracket: Option<Bracket> }`. What a container or collection adds to `Common`. A builder added here is added to the forwarder list in
- `pub const fn new() -> Self`. Props with every field at its default.
- `pub fn mount(mut self, mount: Mount) -> Self`. Where the container lives.
- `pub const fn surface(mut self, surface: SurfaceKind) -> Self`. The surface the container paints.
@@ -2082,6 +2093,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st
- `pub fn save(mut self, key: SaveKey) -> Self`. Saves placement, size and open state under `key`.
- `pub const fn outer_edit(mut self, on: bool) -> Self`. One outer gesture over the body's fields, from open to close.
- `pub const fn label_column(mut self, on: bool) -> Self`. The labelled rows of the body share the widest label as one column. A nested container with its own
- `pub const fn bracket(mut self, bracket: Bracket) -> Self`. The bracket of a `Row` from its first child's labelled rows to the child after them ([`bracket`](Self::bracket)).
- `pub const fn labels(mut self, scheme: LabelScheme) -> Self`. The labelled rows under the container show their labels in `scheme`: its regions, its body and every container
- `craft_ui::contract::ContextMenuRequest`: `pub struct ContextMenuRequest<K> { pub key: K, pub at: Pos2, pub column: Option<ColumnKey>, pub part: Option<PartRef> }`. A request for the context menu of an item. Collections never open menus: the app does.
- `pub fn new(key: K, at: Pos2) -> Self`. A request for the menu of `key` that opens at `at`, from the item itself: no column and no part. A component
@@ -2244,6 +2256,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st
- `fn show(self: Box<Self>, ui: &mut PaintUi<'_>, key: HostedKey, rect: Rect)`. Shows the leaf at `rect` under `key` and hands its output on.
- `craft_ui::contract::HostedKey`: `pub type HostedKey = (&'static str, usize)`. The key a hosted leaf is measured and shown under: the slot's name and its index among the host's slots.
- `craft_ui::contract::Hover`: `pub struct Hover { pub over: bool, pub entered: bool, pub left: bool, pub clicked: bool }`. A command-bound control's report of the pointer's stay over it.
- `craft_ui::contract::HoverLead`: `pub enum HoverLead { Off, Lead, LeadAndSelection }`. What the pointer moving over the rows changes.
- `craft_ui::contract::Input`: re-export of `craft_behavior::input::Input`.
- `craft_ui::contract::InsideLabel`: `pub struct InsideLabel`. What a control shows in its slot for a side label with `FieldLayout::Inside` (`EnvView::inside_label`): the
- `pub const PART: PartKey`. The part a control declares its slot as (`PartsCx::label_part`).
@@ -2287,7 +2300,8 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st
- `pub fn command(&self) -> Option<&ResolvedCommand>`. The bound command as step 1 resolved it, with the scoped bindings of the scopes above the component.
- `pub fn resolve_command(&self, command: impl Into<CommandRef>) -> Option<std::sync::Arc<ResolvedCommand>>`. `command` as this component shows it: the label, icon and chord with the scoped bindings of the scopes above
- `pub fn column_room(&self) -> Option<f32>`. The width a component whose height follows its width (wrapped text, a square plot) sizes at: the room the
- `pub fn picture_width(&self, least: f32, most: f32) -> f32`. The width a picture sizes at (a plot, a wheel, a well): it takes the room it is offered, down to `least` and up
- `pub fn picture_width(&self, least: f32, most: f32) -> f32`. The width a band picture sizes at (a plot, a strip), one whose height is its own whatever its width: it takes
- `pub fn picture_size(&self, least: f32, most: f32, height: impl FnOnce(f32) -> f32) -> Vec2`. The size of a picture whose height follows from its width (a square graph, a wheel, an image at its aspect):
- `pub fn label(&self) -> Label`. The label as given.
- `pub fn cell_width(&self, column: &craft_behavior::ColumnKey, width: f32)`. Reports, from the `Ideal` measure of a collection's item, the width its content in `column` takes unclipped,
- `pub fn layout(&self, run: &TextRun<'_>) -> TextLayout`. Lays `run` out in the content's room, as `Draw::text` will paint it.
@@ -2748,6 +2762,7 @@ Chapter 15: the `Overlay` data, its presets, popup handles, `OverlayUi` and the
- `craft_ui::contract::overlay::close_popups`: re-export of `craft_ui::runtime::overlay::close_popups`.
- `craft_ui::contract::overlay::family`: re-export of `craft_ui::runtime::overlay::family`.
- `craft_ui::contract::overlay::is_open`: re-export of `craft_ui::runtime::overlay::is_open`.
- `craft_ui::contract::overlay::layer_room`: `pub fn layer_room(ctx: &Context) -> Rect`. The room a layer opened in the running viewport may take, in its points: the work area around a palette window,
- `craft_ui::contract::overlay::paint_frame_layers`: `pub fn paint_frame_layers(ctx: &Context)`. Paints the ghost egui layer from runtime data: the drag preview and drop mark, and the painted cursor the cursor
- `craft_ui::contract::overlay::request_close`: re-export of `craft_ui::runtime::overlay::request_close`.
- `craft_ui::contract::overlay::top`: re-export of `craft_ui::runtime::overlay::top`.
@@ -3042,6 +3057,8 @@ Painters, `Draw`, the sensing core, the text adapter and `ImeSurface`.
- `pub fn strip_arrow(strip: Rect, back: bool, color: Color32) -> Shape`. The filled arrow of a scroll strip, centred in `strip`: pointing up for the strip before the view (`back`),
- `pub fn thumb(min_thumb: f32, track: Rect, axis: Axis, rtl: bool, span: &ScrollSpan) -> Rect`. The thumb inside `track`, a bar along `axis`, for `span`: its length is the shown share of the track, at least
- `pub fn shapes(look: &ScrollBarLook, track: Rect, axis: Axis, rtl: bool, span: &ScrollSpan, state: &StateSet) -> Vec<Shape>`. The shapes of the bar in `track` along `axis` for `span`, in `state` (the bar's: hovered while the pointer is
- `craft_ui::primitives::Serials`: `pub struct Serials`. The numbers that keep apart the textures one owner makes: a mask or preview made anew gets a number no earlier one
- `pub fn mint(&mut self) -> u64`. A new number: never one this `Serials` gave before.
- `craft_ui::primitives::Span`: `pub struct Span<'a> { pub text: Cow<'a, str>, pub italic: bool, pub tabular: bool, pub mono: bool, pub muted: bool, pub shortcut: bool, pub highlight: bool, pub underline: bool, pub strong: bool, pub flag: Option<Tone> }`. One styled stretch of a run.
- `pub fn new(text: impl Into<Cow<'a, str>>) -> Self`. A plain span.
- `pub fn flag(mut self, tone: Tone) -> Self`. Underlines the span in the ink of `tone` (spelling `Bad`, grammar `Info`).
@@ -3242,6 +3259,8 @@ Frosted backdrops: a bounded blurred composition of the layers under a surface,
- `pub const fn new(value: u64) -> Revision`. The revision `value` (a document's own change counter).
- `pub const fn get(self) -> u64`. The number.
- `pub fn of(value: &impl Hash) -> Revision`. The revision of anything hashable: `Revision::of(&(fingerprint, doc_width))`. Stable within one run of the
- `craft_ui::primitives::textures::Serials`: `pub struct Serials`. The numbers that keep apart the textures one owner makes: a mask or preview made anew gets a number no earlier one
- `pub fn mint(&mut self) -> u64`. A new number: never one this `Serials` gave before.
- `craft_ui::primitives::textures::TextureBudget`: `pub struct TextureBudget { pub max_bytes: usize, pub max_entries: usize, pub uploads_per_pass: usize, pub upload_bytes_per_pass: usize }`. How much a store may hold and upload. Entries past `max_bytes` or `max_entries` are evicted; `uploads_per_pass`
- `pub const fn new(max_bytes: usize, max_entries: usize) -> Self`. Holds `max_bytes` and `max_entries`; a loader uploads 16 pictures and 16 MiB per frame.
- `pub const fn uploads(mut self, count: usize, bytes: usize) -> Self`. Other upload limits per frame.
@@ -3515,6 +3534,12 @@ The cursor service (8.5): requests of a pass collect here, the end hook picks th
- `pub fn new(layer: LayerKey, clip: Rect) -> Self`. The region of `clip` on `layer`.
- `craft_ui::runtime::cursor::current`: `pub fn current(ctx: &Context) -> Option<Cursor>`. The cursor the last pass of the running viewport settled on; `None` is the default arrow.
## `craft_ui::runtime::derived`
Derived values: data a component computes from its inputs and keeps across passes. [`derived`] keeps one value per
- `craft_ui::runtime::derived::derived`: `pub fn derived<K: MemoProps, V: Send + Sync + 'static>(ctx: &Context, id: Id, key: &K, build: impl FnOnce() -> V) -> Arc<V>`. The value of the component `id` derived from `key`: the kept one while `key` is the one it was built from, else
## `craft_ui::runtime::drag`
The drag session (8.4): one per context. It holds the payload, the preview, the held modifiers, the operation and the
@@ -4222,7 +4247,7 @@ The toast queues: one per window (`WindowKey`), filled from any code with a `Con
- `craft_ui::runtime::windows::ScreenshotError`: re-export of `craft_ui::runtime::egui::screenshot::ScreenshotError`.
- `craft_ui::runtime::windows::ScreenshotFacts`: re-export of `craft_ui::runtime::egui::screenshot::ScreenshotFacts`.
- `craft_ui::runtime::windows::ScreenshotSlot`: re-export of `craft_ui::runtime::egui::screenshot::ScreenshotSlot`.
- `craft_ui::runtime::windows::WindowAction`: `pub enum WindowAction { Close, Minimize, ToggleMaximize, ToggleFullscreen, SetFullscreen(bool), SetMaximized(bool), Focus, StartMove, StartResize(ResizeEdge), SetOuterPosition(Pos2), SetInnerSize(Vec2), Restore, SetMinInnerSize(Vec2), SetLevel(WindowLevel), SetTitle(String), SetOpacity(f32) }`. A window command `act` sends.
- `craft_ui::runtime::windows::WindowAction`: `pub enum WindowAction { Close, Minimize, ToggleMaximize, ToggleFullscreen, SetFullscreen(bool), SetMaximized(bool), Focus, Raise, StartMove, StartResize(ResizeEdge), SetOuterPosition(Pos2), SetInnerSize(Vec2), Restore, SetMinInnerSize(Vec2), SetLevel(WindowLevel), SetTitle(String), SetOpacity(f32) }`. A window command `act` sends.
- `craft_ui::runtime::windows::WindowFacts`: `pub struct WindowFacts { pub inner: Rect, pub outer: Option<Rect>, pub scale: Option<f32>, pub state: WindowState, pub focused: bool }`. What the OS tells about a window, in desktop points.
- `craft_ui::runtime::windows::WindowHit`: `pub enum WindowHit { Move, Resize(ResizeEdge), Caption(Button) }`. What a part of the window does for the operating system: a press on it moves the window, resizes it from an edge,
- `craft_ui::runtime::windows::WindowHost`: `pub struct WindowHost`. The multi-window driver of one context.
@@ -4278,8 +4303,9 @@ The toast queues: one per window (`WindowKey`), filled from any code with a `Con
- `pub fn install_hit_sink(&self, viewport: ViewportId) -> HitSink`. The hit-test sink of `viewport`'s window, made on the first call. The platform layer calls it once it has put
- `pub fn pointer_in(&self, viewport: ViewportId) -> Option<Pos2>`. The desktop pointer in the coordinates of `viewport`, when it lies inside that window.
- `craft_ui::runtime::windows::WindowLevel`: `pub enum WindowLevel { Normal, Palette, AlwaysOnTop }`. Where a window stands in the stack of windows.
- `craft_ui::runtime::windows::WindowSpec`: `pub struct WindowSpec { pub kind: WindowKind, pub chrome: Option<WindowChrome>, pub captions: Option<Captions>, pub level: WindowLevel, pub taskbar: bool, pub shown_after_first_paint: bool }`. How an OS window opens (21.2): what it is for, who draws its frame, where it stands and whether it has a taskbar
- `craft_ui::runtime::windows::WindowSpec`: `pub struct WindowSpec { pub kind: WindowKind, pub chrome: Option<WindowChrome>, pub captions: Option<Captions>, pub level: WindowLevel, pub taskbar: bool, pub shown_after_first_paint: bool, pub takes_focus: bool, pub passes_pointer: bool }`. How an OS window opens (21.2): what it is for, who draws its frame, where it stands and whether it has a taskbar
- `pub fn tool() -> Self`. A tool window (a native dock window): its own title row in place of the OS title bar
- `pub fn popup() -> Self`. A popup window: a layer opened from a palette window (a flyout, menu or tooltip) in an OS window of its own. It
- `pub fn document() -> Self`. A document window with the installed decision's frame.
- `pub fn dialog() -> Self`. A dialog window with the installed decision's frame.
- `pub fn kind(mut self, kind: WindowKind) -> Self`. Sets what the window is for.
@@ -4288,6 +4314,8 @@ The toast queues: one per window (`WindowKey`), filled from any code with a `Con
- `pub fn frame(mut self, frame: &Frame) -> Self`. Takes the chrome and the captions from a decided `frame`; a frame without buttons has no captions.
- `pub fn level(mut self, level: WindowLevel) -> Self`. Sets the level.
- `pub fn taskbar(mut self, taskbar: bool) -> Self`. Sets whether the window has a taskbar or Dock entry.
- `pub fn takes_focus(mut self, takes_focus: bool) -> Self`. Sets whether the window takes OS focus when it opens.
- `pub fn passes_pointer(mut self, passes_pointer: bool) -> Self`. Sets whether pointer input passes through the window to the window below it (a tooltip's).
- `craft_ui::runtime::windows::act`: `pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool`. Sends `action` to `viewport`. It is the only sender of window commands: it checks the capabilities and the
- `craft_ui::runtime::windows::double_click_action`: `pub fn double_click_action(frame: &Frame, setting: DoubleClick, maximized: bool) -> Option<WindowAction>`. What a double click on a window's free move band (its title bar, or the strip a modal leaves over it) asks of the
@@ -4324,6 +4352,7 @@ The style layer: the state set and its resolver, style parts and `ComponentStyle
- `pub fn on(mut self, ground: Stateful<StyleColor>) -> Self`. Declares the fill the icon is painted on, for an icon that sits on a part's own fill.
- `craft_ui::style::Ink`: `pub enum Ink { OnPanel, OnDark, Accent }`. The text and icon colour that reads on a surface, resolved at step 12.
- `craft_ui::style::Insets`: re-export of `craft_behavior::flow::Insets`.
- `craft_ui::style::LetterCase`: re-export of `craft_theme::LetterCase` (outside these crates).
- `craft_ui::style::MarkerLook`: `pub struct MarkerLook { pub radius: f32, pub large: f32, pub ring: StyleColor, pub selected: StyleColor, pub ring_width: f32, pub halo: StyleColor, pub halo_width: f32, pub backing: StyleColor }`. A colour marker: the mark on a colour field, wheel, disc or gradient line that shows where a colour sits. Its ring
- `craft_ui::style::Metrics`: re-export of `craft_behavior::sizing::Metrics`.
- `craft_ui::style::Mix`: re-export of `craft_theme::Mix` (outside these crates).
@@ -4336,7 +4365,7 @@ The style layer: the state set and its resolver, style parts and `ComponentStyle
- `pub fn pixels(self, pixels_per_point: f32) -> f32`. The width in whole physical pixels on a display of `pixels_per_point`.
- `pub fn points(self, pixels_per_point: f32) -> f32`. The width in points on a display of `pixels_per_point`.
- `craft_ui::style::ScrollBarKind`: `pub enum ScrollBarKind { Floating, Docked }`. Which of the two scroll bar looks a bar has.
- `craft_ui::style::ScrollBarLook`: `pub struct ScrollBarLook { pub track: Stateful<StyleColor>, pub thumb: Stateful<StyleColor>, pub thickness: f32, pub thumb_width: Stateful<f32>, pub min_thumb: f32, pub fade: f32 }`. A scroll bar's track and thumb, of a [`ScrollBarKind`].
- `craft_ui::style::ScrollBarLook`: `pub struct ScrollBarLook { pub track: Stateful<StyleColor>, pub thumb: Stateful<StyleColor>, pub thickness: f32, pub thumb_width: Stateful<f32>, pub min_thumb: f32 }`. A scroll bar's track and thumb, of a [`ScrollBarKind`].
- `craft_ui::style::Span`: `pub struct Span<'a> { pub text: Cow<'a, str>, pub italic: bool, pub tabular: bool, pub mono: bool, pub muted: bool, pub shortcut: bool, pub highlight: bool, pub underline: bool, pub strong: bool, pub flag: Option<Tone> }`. One styled stretch of a run.
- `pub fn new(text: impl Into<Cow<'a, str>>) -> Self`. A plain span.
- `pub fn flag(mut self, tone: Tone) -> Self`. Underlines the span in the ink of `tone` (spelling `Bad`, grammar `Info`).
@@ -4473,7 +4502,9 @@ The fixture, the suite runner and the story helpers.
- `craft_ui::testing::install_spec`: re-export of `craft_ui::testing::windows::install_spec`.
- `craft_ui::testing::is_measuring`: re-export of `craft_ui::runtime::measure::active` (defined outside these crates).
- `craft_ui::testing::kept_measurement_leaves`: re-export of `craft_ui::runtime::layout_memory::kept_leaves`.
- `craft_ui::testing::last_frame_derived_builds`: re-export of `craft_ui::runtime::measure::last_frame_derived_builds` (defined outside these crates).
- `craft_ui::testing::last_frame_memo_runs`: re-export of `craft_ui::runtime::measure::last_frame_memo_runs` (defined outside these crates).
- `craft_ui::testing::last_pass_derived_builds`: re-export of `craft_ui::runtime::measure::last_pass_derived_builds` (defined outside these crates).
- `craft_ui::testing::last_pass_measure_asks`: re-export of `craft_ui::runtime::measure::last_pass_measure_asks` (defined outside these crates).
- `craft_ui::testing::last_pass_measuring_runs`: re-export of `craft_ui::runtime::measure::last_pass_body_runs` (defined outside these crates).
- `craft_ui::testing::last_pass_memo_key_bytes`: re-export of `craft_ui::runtime::measure::last_pass_memo_key_bytes` (defined outside these crates).
@@ -4636,6 +4667,7 @@ Text dumps for tests: ordered `key = value` lines compared exactly with a file,
- `pub fn take_paint(&mut self) -> Option<fixture::FullOutput>`. What the frames painted since the last call, as a renderer takes it: the latest frame's shapes and every texture
- `pub fn command_state(&mut self, command: impl Into<CommandRef>, state: CommandState) -> &mut Self`. Gives app-scope `command` this state in every following pass, as an app's `FrameInput.commands` does; a later
- `pub fn gate(&mut self, gate: CommandGate) -> &mut Self`. Sets the app's one gate over commands for every following pass, as an app's `FrameInput.commands` does.
- `pub fn overrides(&mut self, overrides: std::sync::Arc<craft_keymap::Overrides>) -> &mut Self`. Sets the user's binding overrides for every following pass, as an app's `FrameInput.commands` does: the keymap is
- `pub fn room(&mut self, room: Vec2) -> &mut Self`. The room the story is shown in.
- `pub fn in_room(&mut self, room: Room) -> &mut Self`. The room of a host kind: the same as [`Fixture::room`] with that kind's size.
- `pub fn direction(&mut self, direction: Direction) -> &mut Self`. The layout direction.