ferravex_render/ui/
stats.rs

1//! Measured, bounded label/value lists in logical UI units.
2//!
3//! Values and units belong to the caller: borrow already formatted strings (a
4//! reusable `String` works), including explicit unavailable copy. No parsing,
5//! rounding, unit conversion, ellipsis or font scaling occurs here. Wrapping
6//! uses [`WrappedText`] and the existing bitmap painter: ASCII is uppercased,
7//! unsupported Unicode glyphs paint as `?`, and wrap-boundary whitespace follows
8//! that API. Inspection retains the supplied UTF-8 copy.
9//!
10//! A runnable result-summary recipe with actual retained UI and inspection.
11//! The same content selects columns at 640 logical pixels and stacks at 320;
12//! the card accepts only a complete list. A caller could instead scroll, expand,
13//! or show an explicit hidden-row message using the returned report.
14//!
15//! ```
16//! use ferravex_render::ui::{ButtonStyle, Ui, UiError, UiLabel, UiRect, Viewport};
17//! use ferravex_render::ui::stats::{StatRow, StatRowsLayout, StatRowsMode, StatRowsStyle};
18//! use std::fmt::Write;
19//! let mut ui = Ui::new(); // Retain across frames.
20//! ui.set_inspection_enabled(true);
21//! let mut time = String::with_capacity(32);
22//! let mut delta = String::with_capacity(32);
23//! let mut count = String::with_capacity(32);
24//! // Caller owns time rollover, signs, precision and units.
25//! let millis = 60_001_u64;
26//! write!(time, "{}:{:02}.{:03}", millis / 60_000, millis / 1_000 % 60, millis % 1_000).unwrap();
27//! write!(delta, "{:+.3} s", -1.25_f64).unwrap();
28//! write!(count, "{}", u64::MAX).unwrap();
29//! let rows = [
30//!     StatRow { label: "TIME", value: &time, description: None },
31//!     StatRow { label: "DELTA", value: &delta, description: None },
32//!     StatRow { label: "DELIVERIES", value: &count, description: Some("Accepted cargo only.") },
33//!     StatRow { label: "BEST", value: "UNAVAILABLE", description: None },
34//! ];
35//! for (width, mode) in [(640., StatRowsMode::Columns), (320., StatRowsMode::Stacked)] {
36//!     ui.begin(Viewport::responsive([width, 440.], [0.; 4])?);
37//!     let bounds = UiRect { min: [16., 16.], size: [width - 32., 340.] };
38//!     let layout = StatRowsLayout::new(bounds, &rows, StatRowsStyle::default())?;
39//!     assert_eq!(layout.report().mode, mode);
40//!     let submitted = ui.compose(|card| {
41//!         card.panel(UiRect { min: [8., 8.], size: [width - 16., 420.] }, ferravex_render::ui::PANEL)?;
42//!         let report = layout.submit(card)?;
43//!         if report.hidden_rows != 0 { return Err(UiError::Capacity); }
44//!         card.button(901, UiRect { min: [16., 374.], size: [width - 32., 44.] },
45//!                     "CONTINUE", true, ButtonStyle::default())?;
46//!         Ok(report)
47//!     })?;
48//!     assert_eq!((submitted.visible_rows, submitted.hidden_rows), (4, 0));
49//!     // These are the actual retained label/value rectangles, shared with paint.
50//!     let mut inspection = ui.inspect().unwrap().skip(1); // Panel.
51//!     for (row, geometry) in rows.iter().zip(layout.rows()) {
52//!         for (copy, rect) in [(row.label, geometry.label), (row.value, geometry.value)] {
53//!             let element = inspection.next().unwrap();
54//!             assert_eq!(element.label, UiLabel::Full(copy));
55//!             assert_eq!(element.painted_label, copy);
56//!             assert_eq!(element.bounds, rect);
57//!             assert_eq!(element.visible_bounds, Some(rect));
58//!         }
59//!         if let Some(copy) = row.description {
60//!             let element = inspection.next().unwrap();
61//!             assert_eq!(element.label, UiLabel::Full(copy));
62//!             assert_eq!(element.bounds, geometry.description.unwrap());
63//!         }
64//!     }
65//!     ui.paint(); // Headless retained paint, not a device readability test.
66//! }
67//! # Ok::<(), UiError>(())
68//! ```
69
70use super::text_layout::{LineLimit, WrappedText};
71use super::{TextStyle, Ui, UiComposition, UiError, UiRect};
72
73/// Hard bound on measured rows. Larger slices return [`UiError::Capacity`]
74/// before scanning any text; callers can paginate their source explicitly.
75pub const MAX_STAT_ROWS: usize = 64;
76
77/// Borrowed caller-authored copy. An empty value stays empty; supply a distinct
78/// string such as `"UNAVAILABLE"` when that is the metric's meaning.
79#[derive(Clone, Copy, Debug)]
80pub struct StatRow<'a> {
81    pub label: &'a str,
82    pub value: &'a str,
83    pub description: Option<&'a str>,
84}
85
86/// Fixed text sizes and nonnegative gaps, all in logical units. Each block
87/// honors color/alignment/shadow; `wrap` is ignored and always enabled. Defaults
88/// use size 18 for every block. No automatic font-size/accessibility policy is
89/// imposed; choose a readable size and responsive viewport in the consumer.
90#[derive(Clone, Copy, Debug)]
91pub struct StatRowsStyle {
92    pub label: TextStyle,
93    pub value: TextStyle,
94    pub description: TextStyle,
95    pub column_gap: f32,
96    pub row_gap: f32,
97    pub stack_gap: f32,
98    pub description_gap: f32,
99}
100
101impl Default for StatRowsStyle {
102    fn default() -> Self {
103        Self {
104            label: TextStyle::default(),
105            value: TextStyle::default(),
106            description: TextStyle::default(),
107            column_gap: 16.,
108            row_gap: 12.,
109            stack_gap: 4.,
110            description_gap: 4.,
111        }
112    }
113}
114
115/// One mode is selected for the whole list using every supplied label/value,
116/// including rows hidden by height. Descriptions do not affect column choice.
117#[derive(Clone, Copy, Debug, PartialEq, Eq)]
118pub enum StatRowsMode {
119    Columns,
120    Stacked,
121}
122
123/// Measurements before viewport projection, ancestor clipping or occlusion.
124/// Visible rows form a complete prefix; no partial row is ever submitted.
125#[derive(Clone, Copy, Debug, PartialEq)]
126pub struct StatRowsReport {
127    pub mode: StatRowsMode,
128    pub visible_rows: usize,
129    pub hidden_rows: usize,
130    /// Full height of every row plus intervening gaps at this width.
131    pub required_height: f32,
132    /// Height of the visible prefix, excluding a trailing row gap.
133    pub used_height: f32,
134    /// Shared column width, or the whole bounds width in stacked mode.
135    pub label_width: f32,
136    /// Bounds are narrower than one cell of a participating style. All rows
137    /// are hidden instead of clipping a scalar horizontally. Empty lists false.
138    pub width_overflow: bool,
139}
140
141/// Exact full-line-slot rectangles used for accepted text commands. The row
142/// includes its description but excludes the gap before the next row.
143#[derive(Clone, Copy, Debug, PartialEq)]
144pub struct StatRowGeometry {
145    pub row: UiRect,
146    pub label: UiRect,
147    pub value: UiRect,
148    pub description: Option<UiRect>,
149}
150
151const EMPTY_RECT: UiRect = UiRect {
152    min: [0.; 2],
153    size: [0.; 2],
154};
155const EMPTY_GEOMETRY: StatRowGeometry = StatRowGeometry {
156    row: EMPTY_RECT,
157    label: EMPTY_RECT,
158    value: EMPTY_RECT,
159    description: None,
160};
161
162/// Immutable borrowed layout with fixed stack storage for at most 64 row
163/// geometries, no heap allocation or retained cache. Rebuild for changed copy,
164/// styles or bounds; construction scans all supplied text, including hidden
165/// rows. Source lengths and scanning work are caller-owned, not capped here.
166/// Submission copies visible source into the existing bounded UI arena.
167#[derive(Debug)]
168pub struct StatRowsLayout<'a> {
169    source: &'a [StatRow<'a>],
170    style: StatRowsStyle,
171    geometry: [StatRowGeometry; MAX_STAT_ROWS],
172    report: StatRowsReport,
173}
174
175impl<'a> StatRowsLayout<'a> {
176    /// Measure with the shared wrapper, keeping every block at its supplied
177    /// size. Columns require the widest natural label and value plus the gap
178    /// to fit. Otherwise each label is above its value at full available width;
179    /// descriptions always follow the pair at full width. Empty blocks reserve
180    /// one line slot. Zero/tiny valid bounds return hidden rows, not cropped text.
181    ///
182    /// Invalid/nonfinite bounds, sizes, colors or gaps return `InvalidLayout`;
183    /// so does unrepresentable geometry/height. Sizes use the existing UI range
184    /// `1..=256`. More than [`MAX_STAT_ROWS`] returns `Capacity`.
185    pub fn new(
186        bounds: UiRect,
187        rows: &'a [StatRow<'a>],
188        style: StatRowsStyle,
189    ) -> Result<Self, UiError> {
190        if !bounds.valid() {
191            return Err(UiError::InvalidLayout);
192        }
193        for text in [style.label, style.value, style.description] {
194            WrappedText::new("", 0., text.size)?;
195            if ![text.color.r, text.color.g, text.color.b, text.color.a]
196                .into_iter()
197                .all(f32::is_finite)
198            {
199                return Err(UiError::InvalidLayout);
200            }
201        }
202        if ![
203            style.column_gap,
204            style.row_gap,
205            style.stack_gap,
206            style.description_gap,
207        ]
208        .into_iter()
209        .all(|v| v.is_finite() && v >= 0.)
210        {
211            return Err(UiError::InvalidLayout);
212        }
213        if rows.len() > MAX_STAT_ROWS {
214            return Err(UiError::Capacity);
215        }
216        let mut label_width = cell(style.label);
217        let mut value_width = cell(style.value);
218        let mut min_width = label_width.max(value_width);
219        for row in rows {
220            label_width = label_width.max(
221                WrappedText::new(row.label, f32::MAX, style.label.size)?
222                    .measure()
223                    .width,
224            );
225            value_width = value_width.max(
226                WrappedText::new(row.value, f32::MAX, style.value.size)?
227                    .measure()
228                    .width,
229            );
230            if row.description.is_some() {
231                min_width = min_width.max(cell(style.description));
232            }
233        }
234        let columns = label_width as f64 + style.column_gap as f64 + value_width as f64
235            <= bounds.size[0] as f64;
236        let mode = if columns {
237            StatRowsMode::Columns
238        } else {
239            StatRowsMode::Stacked
240        };
241        let label_width = if columns { label_width } else { bounds.size[0] };
242        let value_x = if columns {
243            label_width + style.column_gap
244        } else {
245            0.
246        };
247        let value_width = bounds.size[0] - value_x;
248        let width_overflow = !rows.is_empty() && bounds.size[0] < min_width;
249        let mut layout = Self {
250            source: rows,
251            style,
252            geometry: [EMPTY_GEOMETRY; MAX_STAT_ROWS],
253            report: StatRowsReport {
254                mode,
255                visible_rows: 0,
256                hidden_rows: rows.len(),
257                required_height: 0.,
258                used_height: 0.,
259                label_width,
260                width_overflow,
261            },
262        };
263        let mut bottom = bounds.min[1];
264        let mut full_height = 0.;
265        let mut stopped = width_overflow;
266        for (index, row) in rows.iter().enumerate() {
267            let top = advance(bottom, if index == 0 { 0. } else { style.row_gap })?;
268            let label_height = height(row.label, label_width, style.label)?;
269            let value_height = height(row.value, value_width, style.value)?;
270            let label = UiRect {
271                min: [bounds.min[0], top],
272                size: [label_width, label_height],
273            };
274            let value = UiRect {
275                min: [
276                    bounds.min[0] + value_x,
277                    if columns {
278                        top
279                    } else {
280                        advance(advance(top, label_height)?, style.stack_gap)?
281                    },
282                ],
283                size: [value_width, value_height],
284            };
285            let pair_bottom =
286                advance(label.min[1], label_height)?.max(advance(value.min[1], value_height)?);
287            let description = row
288                .description
289                .map(|copy| -> Result<UiRect, UiError> {
290                    Ok(UiRect {
291                        min: [bounds.min[0], advance(pair_bottom, style.description_gap)?],
292                        size: [
293                            bounds.size[0],
294                            height(copy, bounds.size[0], style.description)?,
295                        ],
296                    })
297                })
298                .transpose()?;
299            bottom = if let Some(d) = description {
300                advance(d.min[1], d.size[1])?
301            } else {
302                pair_bottom
303            };
304            // A subtraction can round down; reserve an outward-rounded row
305            // extent so its own f32 endpoint encloses every full text slot.
306            let row_height = covering_extent(top, bottom)?;
307            bottom = advance(top, row_height)?;
308            full_height = covering_extent(bounds.min[1], bottom)?;
309            if stopped || full_height > bounds.size[1] {
310                stopped = true;
311                continue;
312            }
313            let geometry = StatRowGeometry {
314                row: UiRect {
315                    min: [bounds.min[0], top],
316                    size: [bounds.size[0], row_height],
317                },
318                label,
319                value,
320                description,
321            };
322            for block in [Some(geometry.row), Some(label), Some(value), description]
323                .into_iter()
324                .flatten()
325            {
326                validate_rect(bounds, block)?;
327            }
328            if columns && label.min[0] + label.size[0] > value.min[0] {
329                return Err(UiError::InvalidLayout);
330            }
331            layout.geometry[index] = geometry;
332            layout.report.visible_rows += 1;
333            layout.report.used_height = full_height;
334        }
335        layout.report.required_height = full_height;
336        layout.report.hidden_rows -= layout.report.visible_rows;
337        Ok(layout)
338    }
339
340    /// Full and visible-prefix measurements; no geometry is changed by reading.
341    pub fn report(&self) -> StatRowsReport {
342        self.report
343    }
344
345    /// Visible geometry in source order, paired with the same source prefix.
346    /// These rectangles are also the actual retained inspection/paint bounds.
347    pub fn rows(&self) -> &[StatRowGeometry] {
348        &self.geometry[..self.report.visible_rows]
349    }
350
351    /// Submit the measured prefix as a nested atomic group. Capacity/validation
352    /// rejection leaves no list paint or inspection commands. Existing clips
353    /// still apply; a caller must choose bounds inside its visible safe region.
354    /// Handle a rejected optional group locally or propagate `?` to reject its
355    /// enclosing card. Hidden rows are reported on success, never auto-painted.
356    pub fn submit(&self, group: &mut UiComposition<'_>) -> Result<StatRowsReport, UiError> {
357        group.compose(|group| self.submit_commands(group))
358    }
359
360    fn submit_commands(&self, group: &mut UiComposition<'_>) -> Result<StatRowsReport, UiError> {
361        for (row, geometry) in self.source.iter().zip(self.rows()) {
362            group.wrapped_text(
363                geometry.label,
364                row.label,
365                self.style.label,
366                LineLimit::Unlimited,
367            )?;
368            group.wrapped_text(
369                geometry.value,
370                row.value,
371                self.style.value,
372                LineLimit::Unlimited,
373            )?;
374            if let (Some(copy), Some(rect)) = (row.description, geometry.description) {
375                group.wrapped_text(rect, copy, self.style.description, LineLimit::Unlimited)?;
376            }
377        }
378        Ok(self.report)
379    }
380}
381
382impl Ui {
383    /// Measure and atomically submit a stat list. See [`StatRowsLayout`] for
384    /// measurement, overflow policy and the executable result-summary recipe.
385    ///
386    /// ```
387    /// use ferravex_render::ui::{Ui, UiError, UiRect, Viewport};
388    /// use ferravex_render::ui::stats::{StatRow, StatRowsStyle};
389    /// let mut ui = Ui::new();
390    /// ui.begin(Viewport::responsive([320., 240.], [0.; 4])?);
391    /// let rows = [StatRow { label: "TIME", value: "1:00.001", description: None }];
392    /// let bounds = UiRect { min: [16.; 2], size: [288., 18.] };
393    /// assert_eq!(ui.stat_rows(bounds, &rows, StatRowsStyle::default())?.hidden_rows, 0);
394    /// // The restricted facade provides the same helper inside a result card.
395    /// ui.compose(|card| card.stat_rows(bounds, &rows, StatRowsStyle::default()))?;
396    /// # Ok::<(), UiError>(())
397    /// ```
398    pub fn stat_rows(
399        &mut self,
400        bounds: UiRect,
401        rows: &[StatRow<'_>],
402        style: StatRowsStyle,
403    ) -> Result<StatRowsReport, UiError> {
404        self.compose(|group| StatRowsLayout::new(bounds, rows, style)?.submit_commands(group))
405    }
406}
407
408impl UiComposition<'_> {
409    /// Measure and submit one nested atomic list. A handled error allows a local
410    /// fallback; propagate `?` when the enclosing card requires this section.
411    pub fn stat_rows(
412        &mut self,
413        bounds: UiRect,
414        rows: &[StatRow<'_>],
415        style: StatRowsStyle,
416    ) -> Result<StatRowsReport, UiError> {
417        self.compose(|group| StatRowsLayout::new(bounds, rows, style)?.submit_commands(group))
418    }
419}
420
421fn cell(style: TextStyle) -> f32 {
422    // Same metrics/operation order as WrappedText and the retained painter.
423    crate::get_default_font()
424        .try_metrics(8, style.size / 8.)
425        .expect("validated size")
426        .glyph_advance()
427}
428fn height(copy: &str, width: f32, style: TextStyle) -> Result<f32, UiError> {
429    Ok(WrappedText::new(copy, width, style.size)?
430        .measure()
431        .height
432        .max(style.size))
433}
434fn advance(start: f32, extent: f32) -> Result<f32, UiError> {
435    let end = start + extent;
436    if !end.is_finite() || (extent > 0. && end <= start) {
437        return Err(UiError::InvalidLayout);
438    }
439    Ok(end)
440}
441fn covering_extent(start: f32, end: f32) -> Result<f32, UiError> {
442    let mut extent = end - start;
443    if start + extent < end {
444        extent = extent.next_up();
445    }
446    if !extent.is_finite() {
447        return Err(UiError::InvalidLayout);
448    }
449    Ok(extent)
450}
451fn validate_rect(bounds: UiRect, rect: UiRect) -> Result<(), UiError> {
452    if !rect.valid()
453        || (0..2).any(|axis| {
454            rect.min[axis] < bounds.min[axis]
455                || rect.min[axis] + rect.size[axis] > bounds.min[axis] + bounds.size[axis]
456                || (rect.size[axis] > 0. && rect.min[axis] + rect.size[axis] <= rect.min[axis])
457        })
458    {
459        return Err(UiError::InvalidLayout);
460    }
461    Ok(())
462}
463
464#[cfg(test)]
465mod tests {
466    use super::*;
467    use crate::ui::{Align, Viewport};
468
469    #[test]
470    fn fixed_size_stat_paint_matches_complete_shared_wrapped_blocks() {
471        let rows = [
472            StatRow {
473                label: "DELTA",
474                value: "-1.250 s",
475                description: Some("Accepted time.\n\né日"),
476            },
477            StatRow {
478                label: "A LONG RESULT LABEL",
479                value: "18446744073709551615",
480                description: None,
481            },
482        ];
483        for width in [54., 288., 1000.] {
484            for align in [Align::Left, Align::Center, Align::Right] {
485                crate::edit(|s| {
486                    *s = crate::State::default();
487                    s.w = 1200;
488                    s.h = 1200;
489                });
490                let viewport = Viewport::responsive([1200.; 2], [0.; 4]).unwrap();
491                let bounds = UiRect {
492                    min: [16.; 2],
493                    size: [width, 1100.],
494                };
495                let text = TextStyle {
496                    size: 18.5,
497                    align,
498                    shadow: true,
499                    ..Default::default()
500                };
501                let style = StatRowsStyle {
502                    label: text,
503                    value: text,
504                    description: text,
505                    ..Default::default()
506                };
507                let layout = StatRowsLayout::new(bounds, &rows, style).unwrap();
508                assert_eq!(layout.report().hidden_rows, 0);
509                let mut ui = Ui::new();
510                ui.begin(viewport);
511                ui.stat_rows(bounds, &rows, style).unwrap();
512                ui.paint();
513                let actual = crate::read(|s| s.vertices.clone());
514                assert!(!actual.is_empty());
515                crate::edit(|s| {
516                    s.vertices.clear();
517                    s.batches.clear();
518                });
519                ui.begin(viewport);
520                for (row, geometry) in rows.iter().zip(layout.rows()) {
521                    ui.wrapped_text(geometry.label, row.label, text, LineLimit::Unlimited)
522                        .unwrap();
523                    ui.wrapped_text(geometry.value, row.value, text, LineLimit::Unlimited)
524                        .unwrap();
525                    if let (Some(copy), Some(rect)) = (row.description, geometry.description) {
526                        ui.wrapped_text(rect, copy, text, LineLimit::Unlimited)
527                            .unwrap();
528                    }
529                }
530                ui.paint();
531                crate::read(|s| assert_eq!(s.vertices, actual));
532                // Rollback leaves no emitted glyphs beyond the accepted list.
533                let before = crate::read(|s| s.vertices.len());
534                let rejected = "A".repeat(32769);
535                assert_eq!(
536                    ui.stat_rows(
537                        UiRect {
538                            size: [600_000., 1100.],
539                            ..bounds
540                        },
541                        &[StatRow {
542                            label: "REJECTED",
543                            value: &rejected,
544                            description: None
545                        }],
546                        style
547                    ),
548                    Err(UiError::Capacity)
549                );
550                crate::edit(|s| {
551                    s.vertices.clear();
552                    s.batches.clear();
553                });
554                ui.paint();
555                crate::read(|s| {
556                    assert_eq!(s.vertices.len(), before);
557                    assert_eq!(s.vertices, actual);
558                });
559            }
560        }
561    }
562}