ferravex_render/ui/
meters.rs

1//! Passive, atomic meter compositions over a single caller telemetry snapshot.
2//!
3//! Label, display and status are mandatory complete caller-authored copy. Display
4//! is never parsed or replaced with a computed percentage: it may deliberately
5//! show a countdown while the fraction shows energy. The caller owns this
6//! relationship, localization, precision and meaningful known/empty/unknown
7//! wording. No gameplay availability, input registration, animation or smoothing
8//! is added. Rebuild after accepted ticks; reuse the same snapshot during pause.
9//!
10//! Text wraps at fixed theme sizes (no shadows, shrink or ellipsis). Every block
11//! and mark must fit the supplied logical bounds or construction fails. The
12//! caller must reserve these bounds within its viewport/safe area and any outer
13//! clips; an outer clip can still hide an otherwise valid composition. Static
14//! patterns supplement hue: known fills have canvas dots, Empty a dash, Unknown
15//! three separated vertical bars. All three retain explicit caller status text.
16//!
17//! ```
18//! use ferravex_play::ui::{meters::*, theme::*};
19//! use ferravex_render::ui::{Ui, UiRect, Viewport, meters::*};
20//! let viewport = Viewport::responsive([352., 400.], [8., 12., 8., 12.])?;
21//! let layout = MeterLayout::meter(viewport.bounds().inset([16.; 4])?,
22//!     MeterCopy { label: "BOOST", display: "ENERGY 050%", status: "COOLING 1.2s" },
23//!     MeterValue::Known { current: 0.5, capacity: 1. },
24//!     &[Threshold { fraction: 0.25, label: "REARM >25%" }],
25//!     UiTheme::preset(ThemeMode::Normal))?;
26//! let mut ui = Ui::new();
27//! ui.set_inspection_enabled(true);
28//! ui.begin(viewport);
29//! layout.draw(&mut ui)?; // Also: layout.submit(group) inside a larger compose.
30//! ui.finish(true);
31//! assert!(ui.inspect().unwrap().all(|e| !e.interaction_registered));
32//! ui.paint();
33//! # Ok::<(), ferravex_render::ui::UiError>(())
34//! ```
35use super::{
36    Align, TextStyle, Ui, UiComposition, UiError, UiRect,
37    text_layout::{LineLimit, WrappedText},
38};
39use ferravex_play::ui::{
40    meters::{
41        MAX_METER_MARKERS, MAX_METER_SEGMENTS, MeterError, MeterGeometry, MeterValue,
42        SegmentGeometry, SegmentRect, SegmentValue,
43    },
44    theme::{ColorRole, UiTheme},
45};
46
47/// A bounded total source budget including threshold labels (UTF-8 bytes).
48pub const MAX_METER_BYTES: usize = 4096;
49const ZERO: UiRect = UiRect {
50    min: [0.; 2],
51    size: [0.; 2],
52};
53const CELL: SegmentRect = SegmentRect {
54    bounds: ZERO,
55    filled: false,
56};
57
58/// Mandatory nonblank text, borrowed unchanged. Unsupported bitmap glyphs retain
59/// complete inspection copy but use the existing font's `?` painting fallback.
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub struct MeterCopy<'a> {
62    pub label: &'a str,
63    pub display: &'a str,
64    pub status: &'a str,
65}
66/// Explicit normalized threshold and complete description. Its text is placed
67/// in a separate row below the track, in caller order, never over a tiny fill.
68/// Duplicate/unsorted thresholds are allowed; the caller owns their meaning.
69#[derive(Clone, Copy, Debug, PartialEq)]
70pub struct Threshold<'a> {
71    pub fraction: f64,
72    pub label: &'a str,
73}
74
75/// Shared logical rectangles used for retained paint/inspection. A future input
76/// adapter can consume them explicitly; these passive meters register no hits.
77#[derive(Clone, Copy, Debug, PartialEq)]
78pub struct MeterRegions {
79    pub label: UiRect,
80    pub display: UiRect,
81    pub status: UiRect,
82    pub track: UiRect,
83}
84#[derive(Clone, Copy, Debug)]
85enum Geometry {
86    Continuous(MeterGeometry),
87    Segments(SegmentGeometry),
88}
89
90/// Checked borrowed composition with fixed arrays, no retained clock or cache.
91/// Reset is replacement from a new caller snapshot; no prior state can reappear.
92#[derive(Clone, Debug)]
93pub struct MeterLayout<'a> {
94    bounds: UiRect,
95    copy: MeterCopy<'a>,
96    theme: UiTheme,
97    regions: MeterRegions,
98    well: UiRect,
99    geometry: Geometry,
100    cells: [SegmentRect; MAX_METER_SEGMENTS],
101    count: usize,
102    thresholds: &'a [Threshold<'a>],
103    marks: [UiRect; MAX_METER_MARKERS],
104    mark_labels: [UiRect; MAX_METER_MARKERS],
105}
106impl<'a> MeterLayout<'a> {
107    /// Continuous composition. Known zero capacity rejects; choose explicit
108    /// Empty/Unknown instead. Markers, borders and patterns stay inside the
109    /// track; threshold endpoint strokes move inward to fit, as in pure geometry.
110    pub fn meter(
111        bounds: UiRect,
112        copy: MeterCopy<'a>,
113        value: MeterValue,
114        thresholds: &'a [Threshold<'a>],
115        theme: UiTheme,
116    ) -> Result<Self, UiError> {
117        Self::build(bounds, copy, Some(value), None, thresholds, theme)
118    }
119    /// Integer-count composition, with gaps from the fixed theme compact-gap
120    /// token. Insufficient width for all cells/gaps rejects, never drops cells.
121    ///
122    /// ```
123    /// use ferravex_play::ui::{meters::SegmentValue, theme::*};
124    /// use ferravex_render::ui::{UiRect, meters::*};
125    /// let route = MeterLayout::segments(UiRect { min: [0.; 2], size: [320., 240.] },
126    ///     MeterCopy { label: "ROUTE", display: "2 / 6", status: "IN FLIGHT" },
127    ///     SegmentValue::Known { filled: 2, capacity: 6 },
128    ///     UiTheme::preset(ThemeMode::HighContrast))?;
129    /// assert_eq!(route.cells().iter().filter(|c| c.filled).count(), 2);
130    /// # Ok::<(), ferravex_render::ui::UiError>(())
131    /// ```
132    pub fn segments(
133        bounds: UiRect,
134        copy: MeterCopy<'a>,
135        value: SegmentValue,
136        theme: UiTheme,
137    ) -> Result<Self, UiError> {
138        Self::build(bounds, copy, None, Some(value), &[], theme)
139    }
140    fn build(
141        bounds: UiRect,
142        copy: MeterCopy<'a>,
143        continuous: Option<MeterValue>,
144        segments: Option<SegmentValue>,
145        thresholds: &'a [Threshold<'a>],
146        theme: UiTheme,
147    ) -> Result<Self, UiError> {
148        if thresholds.len() > MAX_METER_MARKERS {
149            return Err(UiError::Capacity);
150        }
151        let mut bytes = 0usize;
152        for text in [copy.label, copy.display, copy.status]
153            .into_iter()
154            .chain(thresholds.iter().map(|m| m.label))
155        {
156            bytes = bytes.checked_add(text.len()).ok_or(UiError::Capacity)?;
157            if bytes > MAX_METER_BYTES {
158                return Err(UiError::Capacity);
159            }
160            if text.trim().is_empty() {
161                return Err(UiError::InvalidLayout);
162            }
163        }
164        check(bounds)?;
165        let spacing = theme.spacing();
166        let mut y = bounds.min[1];
167        let label = text_rect(
168            bounds,
169            &mut y,
170            copy.label,
171            theme.types().label,
172            spacing.compact_gap,
173        )?;
174        let display = text_rect(
175            bounds,
176            &mut y,
177            copy.display,
178            theme.types().body,
179            spacing.compact_gap,
180        )?;
181        let status = text_rect(
182            bounds,
183            &mut y,
184            copy.status,
185            theme.types().body,
186            spacing.compact_gap,
187        )?;
188        let track = UiRect {
189            min: [bounds.min[0], y],
190            size: [bounds.size[0], spacing.control_height],
191        };
192        contain(bounds, track)?;
193        // Reject cramped tracks rather than allowing inset() to collapse them.
194        if track.size.iter().any(|v| *v <= spacing.stroke * 2.) {
195            return Err(UiError::InvalidLayout);
196        }
197        let well = track.inset([spacing.stroke; 4])?;
198        check(well)?;
199        let geometry = if let Some(value) = continuous {
200            Geometry::Continuous(MeterGeometry::new(well, value).map_err(map_error)?)
201        } else {
202            Geometry::Segments(
203                SegmentGeometry::new(
204                    well,
205                    segments.expect("one constructor kind"),
206                    spacing.compact_gap,
207                )
208                .map_err(map_error)?,
209            )
210        };
211        let mut result = Self {
212            bounds,
213            copy,
214            theme,
215            regions: MeterRegions {
216                label,
217                display,
218                status,
219                track,
220            },
221            well,
222            geometry,
223            cells: [CELL; MAX_METER_SEGMENTS],
224            count: 0,
225            thresholds,
226            marks: [ZERO; MAX_METER_MARKERS],
227            mark_labels: [ZERO; MAX_METER_MARKERS],
228        };
229        if let Geometry::Segments(g) = geometry {
230            result.count = g.write_into(&mut result.cells).map_err(map_error)?;
231            // Each cell must fit the fixed stroke used by its static cues.
232            if result
233                .cells()
234                .iter()
235                .any(|c| c.bounds.size[0] < spacing.stroke * 3.)
236            {
237                return Err(UiError::InvalidLayout);
238            }
239        }
240        let mut fractions = [0.; MAX_METER_MARKERS];
241        for (i, m) in thresholds.iter().enumerate() {
242            fractions[i] = m.fraction;
243        }
244        if let Geometry::Continuous(g) = geometry {
245            g.markers_into(
246                &fractions[..thresholds.len()],
247                spacing.stroke,
248                &mut result.marks,
249            )
250            .map_err(map_error)?;
251        }
252        y = track.min[1] + track.size[1] + spacing.compact_gap;
253        for (i, m) in thresholds.iter().enumerate() {
254            result.mark_labels[i] = text_rect(
255                bounds,
256                &mut y,
257                m.label,
258                theme.types().label,
259                spacing.compact_gap,
260            )?;
261        }
262        result.validate_paint()?;
263        Ok(result)
264    }
265    pub fn bounds(&self) -> UiRect {
266        self.bounds
267    }
268    pub fn copy(&self) -> MeterCopy<'a> {
269        self.copy
270    }
271    pub fn regions(&self) -> MeterRegions {
272        self.regions
273    }
274    pub fn continuous(&self) -> Option<MeterGeometry> {
275        if let Geometry::Continuous(g) = self.geometry {
276            Some(g)
277        } else {
278            None
279        }
280    }
281    pub fn segment_geometry(&self) -> Option<SegmentGeometry> {
282        if let Geometry::Segments(g) = self.geometry {
283            Some(g)
284        } else {
285            None
286        }
287    }
288    pub fn cells(&self) -> &[SegmentRect] {
289        &self.cells[..self.count]
290    }
291    pub fn marker_rect(&self, index: usize) -> Option<UiRect> {
292        self.marks
293            .get(index)
294            .copied()
295            .filter(|_| index < self.thresholds.len())
296    }
297    pub fn marker_label_rect(&self, index: usize) -> Option<UiRect> {
298        self.mark_labels
299            .get(index)
300            .copied()
301            .filter(|_| index < self.thresholds.len())
302    }
303    /// Atomic standalone submission using the existing Ui transaction/inspection
304    /// rollback. Lifecycle, input and paint remain explicit caller operations.
305    pub fn draw(&self, ui: &mut Ui) -> Result<(), UiError> {
306        ui.compose(|g| self.paint(g))
307    }
308    /// Atomic nested submission. Even if a later text/vertex/command/clip budget
309    /// fails, every command/inspection entry in this meter disappears. Propagate
310    /// errors with `?` to reject an enclosing card, or handle for a local fallback.
311    pub fn submit(&self, group: &mut UiComposition<'_>) -> Result<(), UiError> {
312        group.compose(|g| self.paint(g))
313    }
314    fn paint(&self, g: &mut UiComposition<'_>) -> Result<(), UiError> {
315        g.push_clip(self.bounds)?;
316        let t = self.theme;
317        for (rect, text, size, color) in [
318            (
319                self.regions.label,
320                self.copy.label,
321                t.types().label,
322                ColorRole::MutedText,
323            ),
324            (
325                self.regions.display,
326                self.copy.display,
327                t.types().body,
328                ColorRole::Text,
329            ),
330            (
331                self.regions.status,
332                self.copy.status,
333                t.types().body,
334                ColorRole::Text,
335            ),
336        ] {
337            g.wrapped_text(
338                rect,
339                text,
340                text_style(size, t.color(color)),
341                LineLimit::Unlimited,
342            )?;
343        }
344        g.panel(self.regions.track, t.color(ColorRole::Border))?;
345        g.panel(self.well, t.color(ColorRole::Canvas))?;
346        match self.geometry {
347            Geometry::Continuous(geometry) => match geometry.value() {
348                MeterValue::Known { .. } => {
349                    let fill = geometry.fill().expect("known validated value");
350                    if fill.size[0] > 0. {
351                        self.paint_fill(g, fill)?;
352                    }
353                }
354                MeterValue::Empty => self.paint_empty(g, self.well)?,
355                MeterValue::Unknown => self.paint_unknown(g, self.well)?,
356            },
357            Geometry::Segments(geometry) => match geometry.value() {
358                SegmentValue::Known { .. } => {
359                    for cell in self.cells() {
360                        g.panel(cell.bounds, t.color(ColorRole::Border))?;
361                        let inner = cell.bounds.inset([t.spacing().stroke; 4])?;
362                        g.panel(inner, t.color(ColorRole::Canvas))?;
363                        if cell.filled {
364                            self.paint_fill(g, inner)?;
365                        }
366                    }
367                }
368                SegmentValue::Empty => self.paint_empty(g, self.well)?,
369                SegmentValue::Unknown { .. } => {
370                    if self.cells().is_empty() {
371                        self.paint_unknown(g, self.well)?;
372                    }
373                    for cell in self.cells() {
374                        self.paint_unknown(g, cell.bounds)?;
375                    }
376                }
377            },
378        }
379        for (i, marker) in self.thresholds.iter().enumerate() {
380            g.panel(self.marks[i], t.color(ColorRole::Text))?;
381            g.wrapped_text(
382                self.mark_labels[i],
383                marker.label,
384                text_style(t.types().label, t.color(ColorRole::MutedText)),
385                LineLimit::Unlimited,
386            )?;
387        }
388        g.pop_clip()?;
389        Ok(())
390    }
391
392    fn validate_paint(&self) -> Result<(), UiError> {
393        match self.geometry {
394            Geometry::Continuous(g) => match g.value() {
395                MeterValue::Known { .. } => {
396                    let r = g.fill().expect("known validated value");
397                    if r.size[0] > 0. {
398                        self.fill_dots(r)?;
399                    }
400                }
401                MeterValue::Empty => {
402                    self.empty_mark(self.well)?;
403                }
404                MeterValue::Unknown => {
405                    self.unknown_marks(self.well)?;
406                }
407            },
408            Geometry::Segments(g) => match g.value() {
409                SegmentValue::Known { .. } => {
410                    for c in self.cells() {
411                        let inner = c.bounds.inset([self.theme.spacing().stroke; 4])?;
412                        check(inner)?;
413                        if c.filled {
414                            self.fill_dots(inner)?;
415                        }
416                    }
417                }
418                SegmentValue::Empty => {
419                    self.empty_mark(self.well)?;
420                }
421                SegmentValue::Unknown { .. } => {
422                    self.unknown_marks(self.well)?;
423                    for c in self.cells() {
424                        self.unknown_marks(c.bounds)?;
425                    }
426                }
427            },
428        }
429        Ok(())
430    }
431    fn fill_dots(&self, r: UiRect) -> Result<[UiRect; 3], UiError> {
432        let size = self
433            .theme
434            .spacing()
435            .stroke
436            .min(r.size[0] / 6.)
437            .min(r.size[1] / 3.);
438        let dots = [0.2, 0.5, 0.8].map(|fraction| UiRect {
439            min: [
440                r.min[0] + (r.size[0] - size) * fraction,
441                r.min[1] + (r.size[1] - size) * 0.5,
442            ],
443            size: [size; 2],
444        });
445        for dot in dots {
446            contain(r, dot)?;
447        }
448        Ok(dots)
449    }
450    fn empty_mark(&self, r: UiRect) -> Result<UiRect, UiError> {
451        let mark = UiRect {
452            min: [
453                r.min[0] + r.size[0] * 0.25,
454                r.min[1] + (r.size[1] - self.theme.spacing().stroke) * 0.5,
455            ],
456            size: [r.size[0] * 0.5, self.theme.spacing().stroke],
457        };
458        contain(r, mark)?;
459        Ok(mark)
460    }
461    fn unknown_marks(&self, r: UiRect) -> Result<[UiRect; 3], UiError> {
462        let width = self.theme.spacing().stroke.min(r.size[0] / 6.);
463        let marks = [0.2, 0.5, 0.8].map(|fraction| UiRect {
464            min: [r.min[0] + (r.size[0] - width) * fraction, r.min[1]],
465            size: [width, r.size[1]],
466        });
467        for mark in marks {
468            contain(r, mark)?;
469        }
470        Ok(marks)
471    }
472    fn paint_fill(&self, g: &mut UiComposition<'_>, r: UiRect) -> Result<(), UiError> {
473        g.panel(r, self.theme.color(ColorRole::Accent))?;
474        for dot in self.fill_dots(r)? {
475            g.panel(dot, self.theme.color(ColorRole::Canvas))?;
476        }
477        Ok(())
478    }
479    fn paint_empty(&self, g: &mut UiComposition<'_>, r: UiRect) -> Result<(), UiError> {
480        g.panel(self.empty_mark(r)?, self.theme.color(ColorRole::Border))
481    }
482    fn paint_unknown(&self, g: &mut UiComposition<'_>, r: UiRect) -> Result<(), UiError> {
483        for mark in self.unknown_marks(r)? {
484            g.panel(mark, self.theme.color(ColorRole::Border))?;
485        }
486        Ok(())
487    }
488}
489fn text_style(size: f32, color: crate::Color) -> TextStyle {
490    TextStyle {
491        size,
492        color,
493        align: Align::Left,
494        wrap: true,
495        shadow: false,
496    }
497}
498fn text_rect(
499    bounds: UiRect,
500    y: &mut f32,
501    text: &str,
502    size: f32,
503    gap: f32,
504) -> Result<UiRect, UiError> {
505    let m = WrappedText::new(text, bounds.size[0], size)?.measure();
506    if m.width > bounds.size[0] || m.line_count == 0 {
507        return Err(UiError::InvalidLayout);
508    }
509    let r = UiRect {
510        min: [bounds.min[0], *y],
511        size: [bounds.size[0], m.required_height],
512    };
513    contain(bounds, r)?;
514    *y = r.min[1] + r.size[1] + gap;
515    if !y.is_finite() {
516        return Err(UiError::InvalidLayout);
517    }
518    Ok(r)
519}
520fn check(r: UiRect) -> Result<(), UiError> {
521    if !r.valid() || (0..2).any(|i| r.size[i] <= 0. || r.min[i] + r.size[i] <= r.min[i]) {
522        Err(UiError::InvalidLayout)
523    } else {
524        Ok(())
525    }
526}
527fn contain(parent: UiRect, r: UiRect) -> Result<(), UiError> {
528    check(r)?;
529    if (0..2)
530        .any(|i| r.min[i] < parent.min[i] || r.min[i] + r.size[i] > parent.min[i] + parent.size[i])
531    {
532        Err(UiError::InvalidLayout)
533    } else {
534        Ok(())
535    }
536}
537fn map_error(e: MeterError) -> UiError {
538    match e {
539        MeterError::Capacity => UiError::Capacity,
540        _ => UiError::InvalidLayout,
541    }
542}
543
544#[cfg(test)]
545mod tests {
546    use super::*;
547    use crate::input::host_frame;
548    use ferravex_play::ui::theme::ThemeMode;
549
550    const BOUNDS: UiRect = UiRect {
551        min: [16., 12.],
552        size: [320., 500.],
553    };
554    const COPY: MeterCopy<'static> = MeterCopy {
555        label: "BOOST",
556        display: "ENERGY 050%",
557        status: "COOLING",
558    };
559    fn theme() -> UiTheme {
560        UiTheme::preset(ThemeMode::Normal)
561    }
562    fn viewport() -> super::super::Viewport {
563        super::super::Viewport::responsive([352., 600.], [0.; 4]).unwrap()
564    }
565    fn color(v: &[f32; 8]) -> crate::Color {
566        crate::Color::new(v[4], v[5], v[6], v[7])
567    }
568    fn point(v: &[f32; 8]) -> [f32; 2] {
569        [(v[0] + 1.) * 176., (1. - v[1]) * 300.]
570    }
571    fn close(a: f32, b: f32) {
572        assert!((a - b).abs() < 0.0001, "{a} != {b}");
573    }
574
575    #[test]
576    fn continuous_emitted_fill_and_unknown_empty_patterns_match_reserved_geometry() {
577        let mut ui = Ui::new();
578        ui.set_inspection_enabled(true);
579        for value in [
580            MeterValue::Known {
581                current: 0.,
582                capacity: 6.,
583            },
584            MeterValue::Known {
585                current: 3.,
586                capacity: 6.,
587            },
588            MeterValue::Known {
589                current: 6.,
590                capacity: 6.,
591            },
592            MeterValue::Empty,
593            MeterValue::Unknown,
594        ] {
595            let layout = MeterLayout::meter(BOUNDS, COPY, value, &[], theme()).unwrap();
596            host_frame(0., 352, 600, || {
597                ui.begin(viewport());
598                layout.draw(&mut ui).unwrap();
599                ui.finish(true);
600                ui.paint();
601                crate::read(|s| {
602                    assert!(!s.vertices.is_empty());
603                    for v in &s.vertices {
604                        let p = point(v);
605                        assert!(
606                            p[0] >= BOUNDS.min[0] - 0.0001
607                                && p[0] <= BOUNDS.min[0] + BOUNDS.size[0] + 0.0001
608                        );
609                        assert!(
610                            p[1] >= BOUNDS.min[1] - 0.0001
611                                && p[1] <= BOUNDS.min[1] + BOUNDS.size[1] + 0.0001
612                        );
613                    }
614                    let fill_vertices: Vec<_> = s
615                        .vertices
616                        .iter()
617                        .filter(|v| color(v) == theme().color(ColorRole::Accent))
618                        .collect();
619                    if let MeterValue::Known { current, .. } = value {
620                        if current == 0. {
621                            assert!(fill_vertices.is_empty());
622                        } else {
623                            assert_eq!(fill_vertices.len(), 6);
624                            let fill = layout.continuous().unwrap().fill().unwrap();
625                            for axis in 0..2 {
626                                let lo = fill_vertices
627                                    .iter()
628                                    .map(|v| point(v)[axis])
629                                    .fold(f32::INFINITY, f32::min);
630                                let hi = fill_vertices
631                                    .iter()
632                                    .map(|v| point(v)[axis])
633                                    .fold(f32::NEG_INFINITY, f32::max);
634                                close(lo, fill.min[axis]);
635                                close(hi, fill.min[axis] + fill.size[axis]);
636                            }
637                        }
638                    } else {
639                        assert!(fill_vertices.is_empty());
640                    }
641                    // The retained actual border-color geometry distinguishes no
642                    // capacity (one dash), unknown (three bars) and known zero.
643                    let marks = s
644                        .vertices
645                        .iter()
646                        .filter(|v| color(v) == theme().color(ColorRole::Border))
647                        .count();
648                    assert_eq!(
649                        marks,
650                        match value {
651                            MeterValue::Empty => 12,
652                            MeterValue::Unknown => 24,
653                            _ => 6,
654                        }
655                    );
656                });
657                for e in ui.inspect().unwrap() {
658                    assert!(!e.interaction_registered);
659                    if let Some(r) = e.visible_bounds {
660                        contain(BOUNDS, r).unwrap();
661                    }
662                }
663            });
664        }
665    }
666
667    #[test]
668    fn emitted_segment_fills_thresholds_and_text_use_inspected_rectangles() {
669        let mut ui = Ui::new();
670        ui.set_inspection_enabled(true);
671        for filled in [0, 2, 6] {
672            let layout = MeterLayout::segments(
673                BOUNDS,
674                COPY,
675                SegmentValue::Known {
676                    filled,
677                    capacity: 6,
678                },
679                theme(),
680            )
681            .unwrap();
682            host_frame(0., 352, 600, || {
683                ui.begin(viewport());
684                layout.draw(&mut ui).unwrap();
685                ui.paint();
686                crate::read(|s| {
687                    let fills: Vec<_> = s
688                        .vertices
689                        .iter()
690                        .filter(|v| color(v) == theme().color(ColorRole::Accent))
691                        .collect();
692                    assert_eq!(fills.len(), filled * 6);
693                    for (cell, vertices) in layout.cells()[..filled]
694                        .iter()
695                        .zip(fills.as_chunks::<6>().0)
696                    {
697                        let r = cell.bounds.inset([theme().spacing().stroke; 4]).unwrap();
698                        let lo = vertices
699                            .iter()
700                            .map(|v| point(v)[0])
701                            .fold(f32::INFINITY, f32::min);
702                        let hi = vertices
703                            .iter()
704                            .map(|v| point(v)[0])
705                            .fold(f32::NEG_INFINITY, f32::max);
706                        close(lo, r.min[0]);
707                        close(hi, r.min[0] + r.size[0]);
708                    }
709                });
710            });
711        }
712        let thresholds = [
713            Threshold {
714                fraction: 0.,
715                label: "ZERO",
716            },
717            Threshold {
718                fraction: 0.25,
719                label: "REARM >25%",
720            },
721            Threshold {
722                fraction: 1.,
723                label: "FULL",
724            },
725        ];
726        let layout = MeterLayout::meter(
727            BOUNDS,
728            COPY,
729            MeterValue::Known {
730                current: 0.5,
731                capacity: 1.,
732            },
733            &thresholds,
734            theme(),
735        )
736        .unwrap();
737        host_frame(0., 352, 600, || {
738            ui.begin(viewport());
739            layout.draw(&mut ui).unwrap();
740            ui.paint();
741            let inspected: Vec<_> = ui.inspect().unwrap().collect();
742            for (i, threshold) in thresholds.iter().enumerate() {
743                let text = inspected
744                    .iter()
745                    .find(|e| e.painted_label == threshold.label)
746                    .unwrap();
747                assert_eq!(text.bounds, layout.marker_label_rect(i).unwrap());
748                let mark = layout.marker_rect(i).unwrap();
749                contain(layout.regions().track, mark).unwrap();
750                assert!(inspected.iter().any(|e| e.bounds == mark));
751                assert!(
752                    text.bounds.min[1]
753                        >= layout.regions().track.min[1] + layout.regions().track.size[1]
754                );
755            }
756            assert_eq!(layout.marker_rect(3), None);
757            assert_eq!(layout.marker_label_rect(usize::MAX), None);
758        });
759    }
760
761    #[test]
762    fn rejected_meter_keeps_prior_emitted_paint_identical() {
763        let mut ui = Ui::new();
764        ui.set_inspection_enabled(true);
765        let layout = MeterLayout::meter(BOUNDS, COPY, MeterValue::Empty, &[], theme()).unwrap();
766        let text = "A".repeat(1540); // 194040 estimated vertices, below 196608.
767        host_frame(0., 352, 600, || {
768            ui.begin(viewport());
769            ui.wrapped_text(BOUNDS, &text, TextStyle::default(), LineLimit::Unlimited)
770                .unwrap();
771            ui.paint();
772            let before = crate::read(|s| s.vertices.clone());
773            crate::edit(|s| {
774                s.vertices.clear();
775                s.batches.clear();
776            });
777            assert_eq!(layout.draw(&mut ui), Err(UiError::Capacity));
778            assert_eq!(ui.inspect().unwrap().len(), 1);
779            ui.paint();
780            crate::read(|s| assert_eq!(s.vertices, before));
781        });
782    }
783}
784
785#[cfg(test)]
786mod segment_state_tests {
787    use super::*;
788    use crate::input::host_frame;
789    use ferravex_play::ui::theme::ThemeMode;
790
791    #[test]
792    fn maximum_and_unknown_segment_paint_retains_all_cells_and_no_hit_regions() {
793        let theme = UiTheme::preset(ThemeMode::HighContrast);
794        let bounds = UiRect {
795            min: [16., 12.],
796            size: [4096., 600.],
797        };
798        let mut ui = Ui::new();
799        ui.set_inspection_enabled(true);
800        for value in [
801            SegmentValue::Known {
802                filled: 64,
803                capacity: 64,
804            },
805            SegmentValue::Empty,
806            SegmentValue::Unknown { capacity: 0 },
807            SegmentValue::Unknown { capacity: 6 },
808        ] {
809            let layout = MeterLayout::segments(
810                bounds,
811                MeterCopy {
812                    label: "ROUTE",
813                    display: "EXACT AUTHORED COPY",
814                    status: "CALLER STATUS",
815                },
816                value,
817                theme,
818            )
819            .unwrap();
820            host_frame(0., 4200, 700, || {
821                ui.begin(super::super::Viewport::responsive([4200., 700.], [0.; 4]).unwrap());
822                layout.draw(&mut ui).unwrap();
823                ui.finish(true);
824                assert!(ui.inspect().unwrap().all(|e| !e.interaction_registered));
825                ui.paint();
826                crate::read(|s| {
827                    let count = s
828                        .vertices
829                        .iter()
830                        .filter(|v| {
831                            crate::Color::new(v[4], v[5], v[6], v[7])
832                                == theme.color(ColorRole::Accent)
833                        })
834                        .count();
835                    assert_eq!(
836                        count,
837                        if matches!(value, SegmentValue::Known { .. }) {
838                            64 * 6
839                        } else {
840                            0
841                        }
842                    );
843                    assert!(!s.vertices.is_empty());
844                });
845                assert_eq!(layout.cells().len(), value.count().unwrap());
846            });
847        }
848    }
849}