ferravex_play/ui/flow.rs
1//! Bounded, content-sized horizontal rows with optional wrapping.
2//!
3//! Supply measured widths in logical screen units; this helper never measures
4//! text or changes its font size. Rectangles retain the parent's coordinate
5//! space. In particular, pass a [`super::HudRegions`] strip directly and use a
6//! zero-inset [`super::Viewport::responsive`] for its absolute screen rectangles.
7//! Use each returned rectangle for both painting and [`super::Widget`] input.
8//!
9//! ```
10//! use ferravex_play::ui::{Rect, UiState, Widget};
11//! use ferravex_play::ui::flow::{layout, FlowItem, FlowOptions};
12//! let items = [
13//! FlowItem::fixed(44.), // Icon/action retains its authored width.
14//! FlowItem { minimum: 100., preferred: 180., maximum: 300., grow: 1. },
15//! FlowItem::fixed(64.),
16//! ];
17//! let area = Rect { min: [8., 24.], size: [320., 96.] };
18//! let mut rects = [area; 3];
19//! let report = layout(area, &items, FlowOptions::default(), &mut rects)?;
20//! assert_eq!((report.written, report.overflow, report.rows), (3, 0, 1));
21//! assert_eq!(rects.map(|r| r.size[0]), [44., 196., 64.]);
22//! let mut ui = UiState::with_capacity(3); // Reuse between frames.
23//! ui.begin_frame();
24//! for (index, &rect) in rects[..report.written].iter().enumerate() {
25//! // Paint this same rect with a fixed-size label in the host.
26//! ui.add(Widget { id: index as u64 + 1, rect, clip: Some(area),
27//! enabled: true, focusable: true }).unwrap();
28//! }
29//! ui.end_frame();
30//! assert_eq!(ui.hit_test([60., 30.]), Some(2));
31//! assert_eq!(ui.focus_next(false), Some(1));
32//! # Ok::<(), ferravex_play::ui::flow::FlowError>(())
33//! ```
34
35use super::Rect;
36
37/// Maximum input length. Layout uses fixed stack scratch and no heap allocation.
38pub const FLOW_ITEM_CAPACITY: usize = 256;
39
40/// Horizontal extent policy. All fields must be finite and nonnegative, with
41/// `minimum <= preferred <= maximum`. Zero-width items are allowed and inert
42/// unless they receive width; they still count as items and separate gaps.
43#[derive(Clone, Copy, Debug, PartialEq)]
44pub struct FlowItem {
45 /// Hard lower bound, typically readable label width plus padding.
46 pub minimum: f32,
47 /// Desired width before weighted growth, often the measured full label.
48 pub preferred: f32,
49 /// Hard upper bound, including growth.
50 pub maximum: f32,
51 /// Relative weight for space beyond preferred. Zero opts out of growth.
52 pub grow: f32,
53}
54
55impl FlowItem {
56 /// An item that neither shrinks nor grows. Validation happens in [`layout`].
57 ///
58 /// ```
59 /// use ferravex_play::ui::flow::FlowItem;
60 /// let icon = FlowItem::fixed(44.);
61 /// assert_eq!((icon.minimum, icon.preferred, icon.maximum, icon.grow),
62 /// (44., 44., 44., 0.));
63 /// ```
64 pub const fn fixed(width: f32) -> Self {
65 Self {
66 minimum: width,
67 preferred: width,
68 maximum: width,
69 grow: 0.,
70 }
71 }
72}
73
74/// Row policy in the parent's units. Defaults: height 44, gaps [8, 8], wrapping.
75/// There is no leading/trailing gap, row stretching, justification or font scale.
76#[derive(Clone, Copy, Debug, PartialEq)]
77pub struct FlowOptions {
78 /// Positive, finite height shared by all rows; partial-height rows are omitted.
79 pub row_height: f32,
80 /// Finite, nonnegative horizontal and vertical gaps, respectively.
81 pub gap: [f32; 2],
82 /// Start another row when the next minimum no longer fits. If false, stop
83 /// after the first row. An item wider than the parent stops either mode.
84 pub wrap: bool,
85}
86
87impl Default for FlowOptions {
88 fn default() -> Self {
89 Self {
90 row_height: 44.,
91 gap: [8.; 2],
92 wrap: true,
93 }
94 }
95}
96
97/// Only `output[..written]` is current geometry. Submit that prefix to input and
98/// painting; rebuild input each frame so omitted widgets lose focus/capture.
99#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
100pub struct FlowReport {
101 /// Number of rectangles copied, matching `items[..written]` in source order.
102 pub written: usize,
103 /// `items.len() - written`: includes space overflow and output truncation.
104 /// No item is skipped in favor of a smaller later item.
105 pub overflow: usize,
106 /// Number of rows containing copied rectangles, zero when `written == 0`.
107 pub rows: usize,
108}
109
110/// Errors leave the entire output unchanged. Ordinary insufficient space or a
111/// short output buffer is instead reported by [`FlowReport::overflow`].
112#[derive(Clone, Copy, Debug, PartialEq, Eq)]
113pub enum FlowError {
114 /// More than [`FLOW_ITEM_CAPACITY`] items; checked before inspecting items.
115 Capacity,
116 /// Invalid parent, row height or gaps.
117 InvalidLayout,
118 /// Non-finite/negative item fields or unordered extents. All input items are
119 /// validated, including the suffix that will not fit. First bad index wins.
120 InvalidItem { index: usize },
121 /// Finite inputs cannot produce representable, disjoint f32 rectangles under
122 /// the rounding policy without violating a minimum or losing a positive edge.
123 Unrepresentable,
124}
125
126impl std::fmt::Display for FlowError {
127 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128 match self {
129 Self::Capacity => f.write_str("flow item capacity exceeded"),
130 Self::InvalidLayout => f.write_str("invalid flow bounds or row policy"),
131 Self::InvalidItem { index } => write!(f, "invalid flow item at index {index}"),
132 Self::Unrepresentable => f.write_str("unrepresentable flow geometry"),
133 }
134 }
135}
136
137impl std::error::Error for FlowError {}
138
139/// Lay out a stable prefix left-to-right, then top-to-bottom, without allocation.
140///
141/// Rows greedily admit consecutive **minimum** widths and intervening gaps, with
142/// equality fitting. Each row shares space toward preferred widths in proportion
143/// to `(preferred - minimum)`, independently of grow weights. After all preferred
144/// widths fit, remaining space is distributed by positive grow weight. Capped
145/// items relinquish their share to uncapped items. Zero weights and capped rows
146/// leave unused space at the right. The last row follows the same policy.
147///
148/// No partial-height row or undersized item is emitted. A minimum wider than the
149/// parent, exhausted height, or disabled wrapping ends the prefix. Empty parents
150/// produce zero rectangles. A short output buffer truncates the computed prefix
151/// **without changing row widths**; its length does not affect layout decisions.
152/// All items are validated and all fitting rows computed even with empty output.
153/// Only the written prefix changes on success; the output tail is untouched.
154/// Empty input succeeds and there is no retained state to reset.
155///
156/// Work is bounded by 256 items and at most one weighted saturation pass per item
157/// per row (O(n²) worst case); scratch is O(256) on the stack. Sums and weighted
158/// shares use f64 to avoid f32 overflow. Final widths round down, respecting the
159/// minimum/maximum; origins round up past the preceding edge plus gap. Space for
160/// later minimum widths is reserved backward, rounding inward. Stored extents
161/// and half-open f32 endpoints stay inside the parent and never overlap. Rounding
162/// may leave small slack or reduce a preferred width; it never relaxes a minimum.
163/// Unrepresentable geometry rejects the entire call, including earlier rows.
164///
165/// ```
166/// use ferravex_play::ui::Rect;
167/// use ferravex_play::ui::flow::{layout, FlowItem, FlowOptions, FlowError};
168/// let area = Rect { min: [0.; 2], size: [96., 96.] };
169/// let items = [FlowItem::fixed(44.); 3];
170/// let mut output = [area; 2];
171/// let report = layout(area, &items, FlowOptions::default(), &mut output)?;
172/// assert_eq!((report.written, report.overflow, report.rows), (2, 1, 1));
173/// assert_eq!(output[1].min, [52., 0.]);
174/// let before = output;
175/// assert_eq!(layout(area, &[FlowItem::fixed(f32::NAN)],
176/// FlowOptions::default(), &mut output),
177/// Err(FlowError::InvalidItem { index: 0 }));
178/// assert_eq!(output, before); // Atomic failure.
179/// let empty = layout(area, &[], FlowOptions::default(), &mut output)?;
180/// assert_eq!(empty.written, 0); // Consume no stale output on the next frame.
181/// # Ok::<(), FlowError>(())
182/// ```
183pub fn layout(
184 parent: Rect,
185 items: &[FlowItem],
186 options: FlowOptions,
187 output: &mut [Rect],
188) -> Result<FlowReport, FlowError> {
189 if items.len() > FLOW_ITEM_CAPACITY {
190 return Err(FlowError::Capacity);
191 }
192 if !parent.valid()
193 || !options.row_height.is_finite()
194 || options.row_height <= 0.
195 || !options.gap.into_iter().all(nonnegative)
196 {
197 return Err(FlowError::InvalidLayout);
198 }
199 for (index, item) in items.iter().enumerate() {
200 if ![item.minimum, item.preferred, item.maximum, item.grow]
201 .into_iter()
202 .all(nonnegative)
203 || item.minimum > item.preferred
204 || item.preferred > item.maximum
205 {
206 return Err(FlowError::InvalidItem { index });
207 }
208 }
209 let mut report = FlowReport {
210 overflow: items.len(),
211 ..FlowReport::default()
212 };
213 if parent.size.contains(&0.) || items.is_empty() {
214 return Ok(report);
215 }
216 let mut scratch = [parent; FLOW_ITEM_CAPACITY];
217 let mut start = 0;
218 let mut y = parent.min[1];
219 let bottom = parent.min[1] + parent.size[1];
220 while start < items.len() {
221 if options.row_height > parent.size[1]
222 || y as f64 + options.row_height as f64 > bottom as f64
223 {
224 break;
225 }
226 let row_bottom = y + options.row_height;
227 if row_bottom <= y {
228 return Err(FlowError::Unrepresentable);
229 }
230 let mut end = start;
231 let mut minimum = 0.;
232 while end < items.len() {
233 let next = minimum
234 + items[end].minimum as f64
235 + if end == start {
236 0.
237 } else {
238 options.gap[0] as f64
239 };
240 if next > parent.size[0] as f64 {
241 break;
242 }
243 minimum = next;
244 end += 1;
245 }
246 if end == start {
247 break;
248 }
249 place_row(
250 parent,
251 &items[start..end],
252 options,
253 y,
254 &mut scratch[start..end],
255 )?;
256 if start < output.len() {
257 report.rows += 1;
258 }
259 start = end;
260 if !options.wrap || start == items.len() {
261 break;
262 }
263 let next_y = row_bottom as f64 + options.gap[1] as f64;
264 if next_y > bottom as f64 {
265 break;
266 }
267 y = round_up(next_y);
268 }
269 report.written = start.min(output.len());
270 report.overflow = items.len() - report.written;
271 output[..report.written].copy_from_slice(&scratch[..report.written]);
272 Ok(report)
273}
274
275fn nonnegative(value: f32) -> bool {
276 value.is_finite() && value >= 0.
277}
278
279fn round_down(value: f64) -> f32 {
280 let rounded = value as f32;
281 if rounded as f64 > value {
282 rounded.next_down()
283 } else {
284 rounded
285 }
286}
287
288fn round_up(value: f64) -> f32 {
289 let rounded = value as f32;
290 if (rounded as f64) < value {
291 rounded.next_up()
292 } else {
293 rounded
294 }
295}
296
297fn place_row(
298 parent: Rect,
299 items: &[FlowItem],
300 options: FlowOptions,
301 y: f32,
302 output: &mut [Rect],
303) -> Result<(), FlowError> {
304 let mut widths = [0.; FLOW_ITEM_CAPACITY];
305 let widths = &mut widths[..items.len()];
306 let budget = parent.size[0] as f64 - options.gap[0] as f64 * (items.len() - 1) as f64;
307 let minimum: f64 = items.iter().map(|item| item.minimum as f64).sum();
308 let desire: f64 = items
309 .iter()
310 .map(|item| item.preferred as f64 - item.minimum as f64)
311 .sum();
312 let fraction = if desire > 0. {
313 ((budget - minimum) / desire).clamp(0., 1.)
314 } else {
315 1.
316 };
317 for (width, item) in widths.iter_mut().zip(items) {
318 *width = item.minimum as f64 + fraction * (item.preferred as f64 - item.minimum as f64);
319 }
320 if fraction == 1. {
321 grow(items, widths, (budget - minimum - desire).max(0.));
322 }
323 // Reserve every later minimum and gap before spending width on this item.
324 let mut limits = [0.; FLOW_ITEM_CAPACITY];
325 let mut right = parent.min[0] + parent.size[0];
326 for index in (0..items.len()).rev() {
327 limits[index] = right;
328 let left = round_down(right as f64 - items[index].minimum as f64);
329 right = round_down(left as f64 - options.gap[0] as f64);
330 }
331 let mut x = parent.min[0];
332 for (index, ((item, width), rect)) in items.iter().zip(widths).zip(output).enumerate() {
333 let room = round_down(limits[index] as f64 - x as f64);
334 let extent = round_down(*width).max(item.minimum).min(room);
335 let edge = x + extent;
336 if !x.is_finite()
337 || extent < item.minimum
338 || extent > item.maximum
339 || edge > limits[index]
340 || (extent > 0. && edge <= x)
341 {
342 return Err(FlowError::Unrepresentable);
343 }
344 *rect = Rect {
345 min: [x, y],
346 size: [extent, options.row_height],
347 };
348 if index + 1 < items.len() {
349 x = round_up(edge as f64 + options.gap[0] as f64);
350 }
351 }
352 Ok(())
353}
354
355fn grow(items: &[FlowItem], widths: &mut [f64], mut remaining: f64) {
356 // Each saturation pass removes at least one participant, or finishes.
357 for _ in 0..items.len() {
358 let weight: f64 = items
359 .iter()
360 .zip(widths.iter())
361 .filter(|(item, width)| item.grow > 0. && **width < item.maximum as f64)
362 .map(|(item, _)| item.grow as f64)
363 .sum();
364 if remaining <= 0. || weight == 0. {
365 break;
366 }
367 let mut capped = false;
368 let share = remaining / weight;
369 for (item, width) in items.iter().zip(widths.iter_mut()) {
370 let room = item.maximum as f64 - *width;
371 if item.grow > 0. && room > 0. && share * item.grow as f64 >= room {
372 *width = item.maximum as f64;
373 remaining = (remaining - room).max(0.);
374 capped = true;
375 }
376 }
377 if !capped {
378 for (item, width) in items.iter().zip(widths.iter_mut()) {
379 if item.grow > 0. && *width < item.maximum as f64 {
380 *width = (*width + share * item.grow as f64).min(item.maximum as f64);
381 }
382 }
383 break;
384 }
385 }
386}