Skip to main content

ftui_widgets/
progress.rs

1#![forbid(unsafe_code)]
2
3//! Progress bar widget.
4
5use crate::block::Block;
6use crate::{
7    MeasurableWidget, SizeConstraints, Widget, apply_style, clear_text_area, clear_text_row,
8};
9use ftui_core::geometry::{Rect, Size};
10use ftui_render::cell::{Cell, PackedRgba};
11use ftui_render::frame::Frame;
12use ftui_style::Style;
13use ftui_text::display_width;
14
15/// How a [`ProgressBar`] fills: a known fraction, or an animated marquee for
16/// work of unknown duration.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum ProgressMode {
19    /// Fill proportional to the bar's `ratio` (the default).
20    #[default]
21    Determinate,
22    /// A fixed-width segment sweeps across the bar; `ratio` is ignored. The
23    /// caller supplies the animation `phase` (a tick or frame counter), so the
24    /// widget stays a stateless [`Widget`] and its output is deterministic.
25    Indeterminate {
26        /// Animation phase, typically a monotonically increasing tick count.
27        phase: u64,
28    },
29}
30
31/// A widget to display a progress bar.
32#[derive(Debug, Clone, Default)]
33pub struct ProgressBar<'a> {
34    block: Option<Block<'a>>,
35    ratio: f64,
36    label: Option<&'a str>,
37    style: Style,
38    gauge_style: Style,
39    mode: ProgressMode,
40}
41
42impl<'a> ProgressBar<'a> {
43    /// Create a new progress bar with default settings.
44    #[must_use]
45    pub fn new() -> Self {
46        Self::default()
47    }
48
49    /// Set the surrounding block.
50    #[must_use]
51    pub fn block(mut self, block: Block<'a>) -> Self {
52        self.block = Some(block);
53        self
54    }
55
56    /// Set the progress ratio (clamped to 0.0..=1.0).
57    #[must_use]
58    pub fn ratio(mut self, ratio: f64) -> Self {
59        self.ratio = if ratio.is_nan() {
60            0.0
61        } else {
62            ratio.clamp(0.0, 1.0)
63        };
64        self
65    }
66
67    /// Set the centered label text.
68    #[must_use]
69    pub fn label(mut self, label: &'a str) -> Self {
70        self.label = Some(label);
71        self
72    }
73
74    /// Set the base style.
75    #[must_use]
76    pub fn style(mut self, style: Style) -> Self {
77        self.style = style;
78        self
79    }
80
81    /// Set the filled portion style.
82    #[must_use]
83    pub fn gauge_style(mut self, style: Style) -> Self {
84        self.gauge_style = style;
85        self
86    }
87
88    /// Switch to indeterminate mode with the given animation `phase`.
89    ///
90    /// In this mode a fixed-width segment sweeps across the bar and `ratio` is
91    /// ignored; the label (if any) is still drawn. The caller supplies `phase`
92    /// — usually a tick or frame counter driven from `Cmd::Tick`/`Every` — so
93    /// the widget remains a stateless [`Widget`] (like [`Sparkline`], unlike the
94    /// stateful `Spinner`) and renders deterministically for a given phase.
95    ///
96    /// [`Sparkline`]: crate::sparkline::Sparkline
97    #[must_use]
98    pub fn indeterminate(mut self, phase: u64) -> Self {
99        self.mode = ProgressMode::Indeterminate { phase };
100        self
101    }
102
103    /// Set the fill mode explicitly.
104    #[must_use]
105    pub fn mode(mut self, mode: ProgressMode) -> Self {
106        self.mode = mode;
107        self
108    }
109
110    /// Whether the bar is in indeterminate (marquee) mode.
111    #[must_use]
112    pub fn is_indeterminate(&self) -> bool {
113        matches!(self.mode, ProgressMode::Indeterminate { .. })
114    }
115
116    /// The visible `[start, end)` columns of the marquee segment for a bar of
117    /// `inner_width` cells at animation `phase`, or `None` when the width is 0.
118    ///
119    /// The segment is `max(3, inner_width / 5)` cells wide and its period is
120    /// `inner_width + seg`, so it enters from the left, crosses, and leaves at
121    /// the right before wrapping. The returned range is always clamped inside
122    /// `[0, inner_width)` (it may be empty while the segment is off-screen).
123    #[must_use]
124    pub fn marquee_span(inner_width: u16, phase: u64) -> Option<(u16, u16)> {
125        if inner_width == 0 {
126            return None;
127        }
128        let width = u64::from(inner_width);
129        let seg = (width / 5).max(3);
130        let period = width + seg;
131        let pos = (phase % period) as i64 - seg as i64;
132        let start = pos.max(0);
133        let end = (pos + seg as i64).clamp(0, width as i64);
134        Some((start as u16, end as u16))
135    }
136
137    /// A short label of the current mode, for the render span.
138    #[cfg(feature = "tracing")]
139    fn mode_label(&self) -> &'static str {
140        match self.mode {
141            ProgressMode::Determinate => "determinate",
142            ProgressMode::Indeterminate { .. } => "indeterminate",
143        }
144    }
145}
146
147impl<'a> Widget for ProgressBar<'a> {
148    fn render(&self, area: Rect, frame: &mut Frame) {
149        // Not for an empty area: nothing lands on screen for one, so a node
150        // would describe a widget that was never drawn, and every such node
151        // collides on the id of the same empty rect
152        // (bd-a11y-sibling-id-collision-6zqd2).
153        if frame.a11y_enabled() && !area.is_empty() {
154            frame.push_a11y_nodes(ftui_a11y::Accessible::accessibility_nodes(self, area));
155        }
156        #[cfg(feature = "tracing")]
157        let _span = tracing::debug_span!(
158            "widget_render",
159            widget = "ProgressBar",
160            x = area.x,
161            y = area.y,
162            w = area.width,
163            h = area.height,
164            mode = self.mode_label()
165        )
166        .entered();
167
168        let deg = frame.buffer.degradation;
169
170        // Skeleton+: skip entirely
171        if !deg.render_content() {
172            return;
173        }
174
175        // EssentialOnly: just show text, no bar. Determinate shows a
176        // percentage; indeterminate has none, so it shows the label or "...".
177        if !deg.render_decorative() {
178            clear_text_area(frame, area, Style::default());
179            let text = match self.mode {
180                ProgressMode::Determinate => format!("{}%", (self.ratio * 100.0) as u8),
181                ProgressMode::Indeterminate { .. } => {
182                    self.label.map_or_else(|| "...".to_string(), String::from)
183                }
184            };
185            crate::draw_text_span(frame, area.x, area.y, &text, Style::default(), area.right());
186            return;
187        }
188
189        let base_style = if deg.apply_styling() {
190            self.style
191        } else {
192            Style::default()
193        };
194
195        clear_text_area(frame, area, base_style);
196
197        let bar_area = match &self.block {
198            Some(b) => {
199                crate::render_block_without_a11y(b, area, frame);
200                b.inner(area)
201            }
202            None => area,
203        };
204
205        if bar_area.is_empty() {
206            return;
207        }
208
209        // The gauge-styled columns: a left-anchored fill in determinate mode,
210        // or the swept marquee segment in indeterminate mode. The determinate
211        // range is byte-for-byte what it was before this branch existed.
212        let (fill_start, fill_end) = match self.mode {
213            ProgressMode::Determinate => {
214                let max_width = bar_area.width as f64;
215                let filled_width = if self.ratio >= 1.0 {
216                    bar_area.width
217                } else {
218                    (max_width * self.ratio).floor() as u16
219                };
220                (0, filled_width)
221            }
222            ProgressMode::Indeterminate { phase } => {
223                Self::marquee_span(bar_area.width, phase).unwrap_or((0, 0))
224            }
225        };
226
227        // Draw filled part
228        let gauge_style = if deg.apply_styling() {
229            self.gauge_style
230        } else {
231            // At NoStyling, use '#' as fill char instead of background color
232            Style::default()
233        };
234        let fill_char = if deg.apply_styling() { ' ' } else { '#' };
235
236        for y in bar_area.top()..bar_area.bottom() {
237            for x in fill_start..fill_end {
238                let cell_x = bar_area.left().saturating_add(x);
239                if cell_x < bar_area.right() {
240                    let mut cell = Cell::from_char(fill_char);
241                    crate::apply_style(&mut cell, gauge_style);
242                    frame.buffer.set_fast(cell_x, y, cell);
243                }
244            }
245        }
246
247        // Draw label (centered)
248        let label_style = if deg.apply_styling() {
249            self.style
250        } else {
251            Style::default()
252        };
253        if let Some(label) = self.label {
254            let label_width = display_width(label);
255            let label_x = bar_area
256                .left()
257                .saturating_add(((bar_area.width as usize).saturating_sub(label_width) / 2) as u16);
258            let label_y = bar_area.top().saturating_add(bar_area.height / 2);
259
260            crate::draw_text_span(
261                frame,
262                label_x,
263                label_y,
264                label,
265                label_style,
266                bar_area.right(),
267            );
268        }
269    }
270}
271
272impl MeasurableWidget for ProgressBar<'_> {
273    fn measure(&self, _available: Size) -> SizeConstraints {
274        // ProgressBar fills available width, has fixed height of 1 (or block inner height)
275        let (block_width, block_height) = self
276            .block
277            .as_ref()
278            .map(|b| {
279                let inner = b.inner(Rect::new(0, 0, 100, 100));
280                let w_overhead = 100u16.saturating_sub(inner.width);
281                let h_overhead = 100u16.saturating_sub(inner.height);
282                (w_overhead, h_overhead)
283            })
284            .unwrap_or((0, 0));
285
286        // Minimum: 1 cell for bar + block overhead
287        // Preferred: fills available width, 1 row + block overhead
288        let min_width = 1u16.saturating_add(block_width);
289        let min_height = 1u16.saturating_add(block_height);
290
291        SizeConstraints {
292            min: Size::new(min_width, min_height),
293            preferred: Size::new(min_width, min_height), // Fills width, so preferred = min
294            max: None,                                   // Can grow to fill available space
295        }
296    }
297
298    fn has_intrinsic_size(&self) -> bool {
299        // ProgressBar fills width, so it doesn't have true intrinsic width
300        // but it does have intrinsic height
301        true
302    }
303}
304
305// ---------------------------------------------------------------------------
306// Accessibility
307// ---------------------------------------------------------------------------
308
309impl ftui_a11y::Accessible for ProgressBar<'_> {
310    fn accessibility_nodes(&self, area: Rect) -> Vec<ftui_a11y::node::A11yNodeInfo> {
311        use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState};
312
313        let id = crate::a11y_node_id(area);
314        // Indeterminate bars have no meaningful value: omit value_now (like an
315        // ARIA indeterminate progressbar) and describe them as "in progress".
316        let state = if self.is_indeterminate() {
317            A11yState {
318                value_text: Some("in progress".to_string()),
319                ..A11yState::default()
320            }
321        } else {
322            let pct = (self.ratio * 100.0).round() as u32;
323            A11yState {
324                value_now: Some(self.ratio),
325                value_min: Some(0.0),
326                value_max: Some(1.0),
327                value_text: Some(format!("{pct}%")),
328                ..A11yState::default()
329            }
330        };
331        let name = self.label.map_or_else(
332            || {
333                state
334                    .value_text
335                    .clone()
336                    .unwrap_or_else(|| "progress".to_string())
337            },
338            String::from,
339        );
340
341        vec![
342            A11yNodeInfo::new(id, A11yRole::ProgressBar, area)
343                .with_name(name)
344                .with_state(state),
345        ]
346    }
347}
348
349// ---------------------------------------------------------------------------
350// MiniBar
351// ---------------------------------------------------------------------------
352
353/// Color thresholds for [`MiniBar`].
354#[derive(Debug, Clone, Copy)]
355pub struct MiniBarColors {
356    pub high: PackedRgba,
357    pub mid: PackedRgba,
358    pub low: PackedRgba,
359    pub critical: PackedRgba,
360}
361
362impl MiniBarColors {
363    pub fn new(high: PackedRgba, mid: PackedRgba, low: PackedRgba, critical: PackedRgba) -> Self {
364        Self {
365            high,
366            mid,
367            low,
368            critical,
369        }
370    }
371}
372
373impl Default for MiniBarColors {
374    fn default() -> Self {
375        Self {
376            high: PackedRgba::rgb(64, 200, 120),
377            mid: PackedRgba::rgb(255, 180, 64),
378            low: PackedRgba::rgb(80, 200, 240),
379            critical: PackedRgba::rgb(160, 160, 160),
380        }
381    }
382}
383
384/// Thresholds for mapping values to colors.
385#[derive(Debug, Clone, Copy)]
386pub struct MiniBarThresholds {
387    pub high: f64,
388    pub mid: f64,
389    pub low: f64,
390}
391
392impl Default for MiniBarThresholds {
393    fn default() -> Self {
394        Self {
395            high: 0.75,
396            mid: 0.50,
397            low: 0.25,
398        }
399    }
400}
401
402/// Compact progress indicator for dashboard-style metrics.
403#[derive(Debug, Clone)]
404pub struct MiniBar {
405    value: f64,
406    width: u16,
407    show_percent: bool,
408    style: Style,
409    filled_char: char,
410    empty_char: char,
411    colors: MiniBarColors,
412    thresholds: MiniBarThresholds,
413}
414
415impl MiniBar {
416    /// Create a new MiniBar with value in the 0.0..=1.0 range.
417    pub fn new(value: f64, width: u16) -> Self {
418        Self {
419            value,
420            width,
421            show_percent: false,
422            style: Style::new(),
423            filled_char: '█',
424            empty_char: '░',
425            colors: MiniBarColors::default(),
426            thresholds: MiniBarThresholds::default(),
427        }
428    }
429
430    /// Override the value (clamped to 0.0..=1.0).
431    #[must_use]
432    pub fn value(mut self, value: f64) -> Self {
433        self.value = value;
434        self
435    }
436
437    /// Override the displayed width.
438    #[must_use]
439    pub fn width(mut self, width: u16) -> Self {
440        self.width = width;
441        self
442    }
443
444    /// Enable or disable percentage text.
445    #[must_use]
446    pub fn show_percent(mut self, show: bool) -> Self {
447        self.show_percent = show;
448        self
449    }
450
451    /// Set the base style for the bar.
452    #[must_use]
453    pub fn style(mut self, style: Style) -> Self {
454        self.style = style;
455        self
456    }
457
458    /// Override the filled block character.
459    #[must_use]
460    pub fn filled_char(mut self, ch: char) -> Self {
461        self.filled_char = ch;
462        self
463    }
464
465    /// Override the empty block character.
466    #[must_use]
467    pub fn empty_char(mut self, ch: char) -> Self {
468        self.empty_char = ch;
469        self
470    }
471
472    /// Override the color thresholds.
473    #[must_use]
474    pub fn thresholds(mut self, thresholds: MiniBarThresholds) -> Self {
475        self.thresholds = thresholds;
476        self
477    }
478
479    /// Override the color palette.
480    #[must_use]
481    pub fn colors(mut self, colors: MiniBarColors) -> Self {
482        self.colors = colors;
483        self
484    }
485
486    /// Map a value to a color using default thresholds.
487    pub fn color_for_value(value: f64) -> PackedRgba {
488        let v = if value.is_finite() { value } else { 0.0 };
489        let v = v.clamp(0.0, 1.0);
490        let thresholds = MiniBarThresholds::default();
491        let colors = MiniBarColors::default();
492        if v > thresholds.high {
493            colors.high
494        } else if v > thresholds.mid {
495            colors.mid
496        } else if v > thresholds.low {
497            colors.low
498        } else {
499            colors.critical
500        }
501    }
502
503    /// Render the bar as a string (for testing/debugging).
504    pub fn render_string(&self) -> String {
505        let width = self.width as usize;
506        if width == 0 {
507            return String::new();
508        }
509        let filled = self.filled_cells(width);
510        let empty = width.saturating_sub(filled);
511        let mut out = String::with_capacity(width);
512        out.extend(std::iter::repeat_n(self.filled_char, filled));
513        out.extend(std::iter::repeat_n(self.empty_char, empty));
514        out
515    }
516
517    fn normalized_value(&self) -> f64 {
518        if self.value.is_finite() {
519            self.value.clamp(0.0, 1.0)
520        } else {
521            0.0
522        }
523    }
524
525    fn filled_cells(&self, width: usize) -> usize {
526        if width == 0 {
527            return 0;
528        }
529        let v = self.normalized_value();
530        let filled = (v * width as f64).round() as usize;
531        filled.min(width)
532    }
533
534    fn color_for_value_with_palette(&self, value: f64) -> PackedRgba {
535        let v = if value.is_finite() { value } else { 0.0 };
536        let v = v.clamp(0.0, 1.0);
537        if v > self.thresholds.high {
538            self.colors.high
539        } else if v > self.thresholds.mid {
540            self.colors.mid
541        } else if v > self.thresholds.low {
542            self.colors.low
543        } else {
544            self.colors.critical
545        }
546    }
547}
548
549impl Widget for MiniBar {
550    fn render(&self, area: Rect, frame: &mut Frame) {
551        #[cfg(feature = "tracing")]
552        let _span = tracing::debug_span!(
553            "widget_render",
554            widget = "MiniBar",
555            x = area.x,
556            y = area.y,
557            w = area.width,
558            h = area.height
559        )
560        .entered();
561
562        if area.is_empty() {
563            return;
564        }
565
566        let deg = frame.buffer.degradation;
567        if !deg.render_content() {
568            return;
569        }
570
571        let base_style = if deg.apply_styling() {
572            self.style
573        } else {
574            Style::default()
575        };
576        clear_text_row(frame, area, base_style);
577
578        let value = self.normalized_value();
579
580        if !deg.render_decorative() {
581            if self.show_percent {
582                let pct = format!("{:3.0}%", value * 100.0);
583                let pct_width = display_width(&pct) as u16;
584                if area.width >= pct_width {
585                    let text_x = area.right().saturating_sub(pct_width);
586                    crate::draw_text_span(
587                        frame,
588                        text_x,
589                        area.y,
590                        &pct,
591                        Style::default(),
592                        area.right(),
593                    );
594                } else {
595                    crate::draw_text_span(
596                        frame,
597                        area.x,
598                        area.y,
599                        pct.trim_start(),
600                        Style::default(),
601                        area.right(),
602                    );
603                }
604            }
605            return;
606        }
607
608        let mut bar_width = self.width.min(area.width) as usize;
609        let mut render_percent = false;
610        let mut percent_text = String::new();
611        let mut percent_only_text = String::new();
612        let percent_width = if self.show_percent {
613            percent_text = format!(" {:3.0}%", value * 100.0);
614            percent_only_text = percent_text.trim_start().to_owned();
615            render_percent = true;
616            display_width(&percent_text) as u16
617        } else {
618            0
619        };
620
621        if render_percent {
622            if area.width <= percent_width {
623                bar_width = 0;
624            } else {
625                let available = area.width - percent_width;
626                bar_width = bar_width.min(available as usize);
627            }
628        }
629
630        if bar_width == 0 {
631            if render_percent {
632                crate::draw_text_span(
633                    frame,
634                    area.x,
635                    area.y,
636                    &percent_only_text,
637                    Style::default(),
638                    area.right(),
639                );
640            }
641            return;
642        }
643
644        let color = self.color_for_value_with_palette(value);
645        let filled = self.filled_cells(bar_width);
646
647        for i in 0..bar_width {
648            let x = area.x + i as u16;
649            if x >= area.right() {
650                break;
651            }
652            let ch = if i < filled {
653                self.filled_char
654            } else {
655                self.empty_char
656            };
657            let mut cell = Cell::from_char(ch);
658            if deg.apply_styling() {
659                apply_style(&mut cell, self.style);
660                if i < filled {
661                    cell.fg = color;
662                }
663            }
664            frame.buffer.set_fast(x, area.y, cell);
665        }
666
667        if render_percent {
668            let text_x = area.x + bar_width as u16;
669            crate::draw_text_span(
670                frame,
671                text_x,
672                area.y,
673                &percent_text,
674                Style::default(),
675                area.right(),
676            );
677        }
678    }
679}
680
681impl MeasurableWidget for MiniBar {
682    fn measure(&self, _available: Size) -> SizeConstraints {
683        // MiniBar has fixed dimensions
684        let percent_width = if self.show_percent { 5 } else { 0 }; // " XXX%"
685        let total_width = self.width.saturating_add(percent_width);
686
687        SizeConstraints {
688            // At least show something - unless the bar was sized to nothing,
689            // where a 1-cell minimum would exceed its own 0-cell preferred
690            // and maximum and break `min <= preferred <= max`.
691            min: Size::new(total_width.min(1), 1),
692            preferred: Size::new(total_width, 1),
693            max: Some(Size::new(total_width, 1)), // Fixed size
694        }
695    }
696
697    fn has_intrinsic_size(&self) -> bool {
698        self.width > 0
699    }
700}
701
702#[cfg(test)]
703mod tests {
704    use super::*;
705    use ftui_render::cell::PackedRgba;
706    use ftui_render::grapheme_pool::GraphemePool;
707
708    fn cell_at(frame: &Frame, x: u16, y: u16) -> Cell {
709        let cell = frame.buffer.get(x, y).copied();
710        assert!(cell.is_some(), "test cell should exist at ({x},{y})");
711        cell.unwrap()
712    }
713
714    fn raw_row_text(frame: &Frame, y: u16, width: u16) -> String {
715        (0..width)
716            .map(|x| {
717                frame
718                    .buffer
719                    .get(x, y)
720                    .and_then(|cell| cell.content.as_char())
721                    .unwrap_or(' ')
722            })
723            .collect()
724    }
725
726    // --- Builder tests ---
727
728    #[test]
729    fn default_progress_bar() {
730        let pb = ProgressBar::new();
731        assert_eq!(pb.ratio, 0.0);
732        assert!(pb.label.is_none());
733        assert!(pb.block.is_none());
734    }
735
736    #[test]
737    fn ratio_clamped_above_one() {
738        let pb = ProgressBar::new().ratio(1.5);
739        assert_eq!(pb.ratio, 1.0);
740    }
741
742    #[test]
743    fn ratio_clamped_below_zero() {
744        let pb = ProgressBar::new().ratio(-0.5);
745        assert_eq!(pb.ratio, 0.0);
746    }
747
748    #[test]
749    fn ratio_normal_range() {
750        let pb = ProgressBar::new().ratio(0.5);
751        assert!((pb.ratio - 0.5).abs() < f64::EPSILON);
752    }
753
754    #[test]
755    fn builder_label() {
756        let pb = ProgressBar::new().label("50%");
757        assert_eq!(pb.label, Some("50%"));
758    }
759
760    // --- Rendering tests ---
761
762    #[test]
763    fn render_zero_area() {
764        let pb = ProgressBar::new().ratio(0.5);
765        let area = Rect::new(0, 0, 0, 0);
766        let mut pool = GraphemePool::new();
767        let mut frame = Frame::new(1, 1, &mut pool);
768        Widget::render(&pb, area, &mut frame);
769        // Should not panic
770    }
771
772    #[test]
773    fn render_zero_ratio_no_fill() {
774        let gauge_style = Style::new().bg(PackedRgba::RED);
775        let pb = ProgressBar::new().ratio(0.0).gauge_style(gauge_style);
776        let area = Rect::new(0, 0, 10, 1);
777        let mut pool = GraphemePool::new();
778        let mut frame = Frame::new(10, 1, &mut pool);
779        Widget::render(&pb, area, &mut frame);
780
781        // No cells should have the gauge style bg
782        for x in 0..10 {
783            let cell = cell_at(&frame, x, 0);
784            assert_ne!(
785                cell.bg,
786                PackedRgba::RED,
787                "cell at x={x} should not have gauge bg"
788            );
789        }
790    }
791
792    #[test]
793    fn render_full_ratio_fills_all() {
794        let gauge_style = Style::new().bg(PackedRgba::GREEN);
795        let pb = ProgressBar::new().ratio(1.0).gauge_style(gauge_style);
796        let area = Rect::new(0, 0, 10, 1);
797        let mut pool = GraphemePool::new();
798        let mut frame = Frame::new(10, 1, &mut pool);
799        Widget::render(&pb, area, &mut frame);
800
801        // All cells should have gauge bg
802        for x in 0..10 {
803            let cell = cell_at(&frame, x, 0);
804            assert_eq!(
805                cell.bg,
806                PackedRgba::GREEN,
807                "cell at x={x} should have gauge bg"
808            );
809        }
810    }
811
812    #[test]
813    fn render_half_ratio() {
814        let gauge_style = Style::new().bg(PackedRgba::BLUE);
815        let pb = ProgressBar::new().ratio(0.5).gauge_style(gauge_style);
816        let area = Rect::new(0, 0, 10, 1);
817        let mut pool = GraphemePool::new();
818        let mut frame = Frame::new(10, 1, &mut pool);
819        Widget::render(&pb, area, &mut frame);
820
821        // About 5 cells should be filled (10 * 0.5 = 5)
822        let filled_count = (0..10)
823            .filter(|&x| cell_at(&frame, x, 0).bg == PackedRgba::BLUE)
824            .count();
825        assert_eq!(filled_count, 5);
826    }
827
828    #[test]
829    fn render_multi_row_bar() {
830        let gauge_style = Style::new().bg(PackedRgba::RED);
831        let pb = ProgressBar::new().ratio(1.0).gauge_style(gauge_style);
832        let area = Rect::new(0, 0, 5, 3);
833        let mut pool = GraphemePool::new();
834        let mut frame = Frame::new(5, 3, &mut pool);
835        Widget::render(&pb, area, &mut frame);
836
837        // All 3 rows should be filled
838        for y in 0..3 {
839            for x in 0..5 {
840                let cell = cell_at(&frame, x, y);
841                assert_eq!(
842                    cell.bg,
843                    PackedRgba::RED,
844                    "cell at ({x},{y}) should have gauge bg"
845                );
846            }
847        }
848    }
849
850    #[test]
851    fn render_with_label_centered() {
852        let pb = ProgressBar::new().ratio(0.5).label("50%");
853        let area = Rect::new(0, 0, 10, 1);
854        let mut pool = GraphemePool::new();
855        let mut frame = Frame::new(10, 1, &mut pool);
856        Widget::render(&pb, area, &mut frame);
857
858        // Label "50%" is 3 chars wide, centered in 10 = starts at x=3
859        // (10 - 3) / 2 = 3
860        let c = frame.buffer.get(3, 0).and_then(|c| c.content.as_char());
861        assert_eq!(c, Some('5'));
862        let c = frame.buffer.get(4, 0).and_then(|c| c.content.as_char());
863        assert_eq!(c, Some('0'));
864        let c = frame.buffer.get(5, 0).and_then(|c| c.content.as_char());
865        assert_eq!(c, Some('%'));
866    }
867
868    #[test]
869    fn render_with_block() {
870        let pb = ProgressBar::new()
871            .ratio(1.0)
872            .gauge_style(Style::new().bg(PackedRgba::GREEN))
873            .block(Block::bordered());
874        // Block::bordered() includes 1 cell padding on each side, so we need
875        // at least 5 rows to have a 1-row inner content area.
876        let area = Rect::new(0, 0, 10, 5);
877        let mut pool = GraphemePool::new();
878        let mut frame = Frame::new(10, 5, &mut pool);
879        Widget::render(&pb, area, &mut frame);
880
881        // Inner area is 6x1 (borders + padding take 2 on each side)
882        // All inner cells should have gauge bg
883        for x in 2..8 {
884            let cell = cell_at(&frame, x, 2);
885            assert_eq!(
886                cell.bg,
887                PackedRgba::GREEN,
888                "inner cell at x={x} should have gauge bg"
889            );
890        }
891    }
892
893    // --- Degradation tests ---
894
895    #[test]
896    fn degradation_skeleton_skips_entirely() {
897        use ftui_render::budget::DegradationLevel;
898
899        let pb = ProgressBar::new()
900            .ratio(0.5)
901            .gauge_style(Style::new().bg(PackedRgba::GREEN));
902        let area = Rect::new(0, 0, 10, 1);
903        let mut pool = GraphemePool::new();
904        let mut frame = Frame::new(10, 1, &mut pool);
905        frame.buffer.degradation = DegradationLevel::Skeleton;
906        Widget::render(&pb, area, &mut frame);
907
908        // Nothing should be rendered
909        for x in 0..10 {
910            assert!(
911                cell_at(&frame, x, 0).is_empty(),
912                "cell at x={x} should be empty at Skeleton"
913            );
914        }
915    }
916
917    #[test]
918    fn degradation_essential_only_shows_percentage() {
919        use ftui_render::budget::DegradationLevel;
920
921        let pb = ProgressBar::new()
922            .ratio(0.5)
923            .gauge_style(Style::new().bg(PackedRgba::GREEN));
924        let area = Rect::new(0, 0, 10, 1);
925        let mut pool = GraphemePool::new();
926        let mut frame = Frame::new(10, 1, &mut pool);
927        frame.buffer.degradation = DegradationLevel::EssentialOnly;
928        Widget::render(&pb, area, &mut frame);
929
930        // Should show "50%" text, no gauge bar
931        assert_eq!(cell_at(&frame, 0, 0).content.as_char(), Some('5'));
932        assert_eq!(cell_at(&frame, 1, 0).content.as_char(), Some('0'));
933        assert_eq!(cell_at(&frame, 2, 0).content.as_char(), Some('%'));
934        // No gauge background color
935        assert_ne!(cell_at(&frame, 0, 0).bg, PackedRgba::GREEN);
936    }
937
938    #[test]
939    fn degradation_full_renders_bar() {
940        use ftui_render::budget::DegradationLevel;
941
942        let pb = ProgressBar::new()
943            .ratio(1.0)
944            .gauge_style(Style::new().bg(PackedRgba::BLUE));
945        let area = Rect::new(0, 0, 10, 1);
946        let mut pool = GraphemePool::new();
947        let mut frame = Frame::new(10, 1, &mut pool);
948        frame.buffer.degradation = DegradationLevel::Full;
949        Widget::render(&pb, area, &mut frame);
950
951        // All cells should have gauge bg
952        for x in 0..10 {
953            assert_eq!(
954                cell_at(&frame, x, 0).bg,
955                PackedRgba::BLUE,
956                "cell at x={x} should have gauge bg at Full"
957            );
958        }
959    }
960
961    #[test]
962    fn render_no_styling_ratio_shrink_clears_stale_fill() {
963        use ftui_render::budget::DegradationLevel;
964
965        let area = Rect::new(0, 0, 10, 1);
966        let mut pool = GraphemePool::new();
967        let mut frame = Frame::new(10, 1, &mut pool);
968        frame.buffer.degradation = DegradationLevel::NoStyling;
969
970        Widget::render(&ProgressBar::new().ratio(0.8), area, &mut frame);
971        Widget::render(&ProgressBar::new().ratio(0.2), area, &mut frame);
972
973        assert_eq!(raw_row_text(&frame, 0, 10), "##        ");
974    }
975
976    #[test]
977    fn degradation_essential_only_clears_previous_bar_content() {
978        use ftui_render::budget::DegradationLevel;
979
980        let pb = ProgressBar::new().ratio(0.5);
981        let area = Rect::new(0, 0, 10, 1);
982        let mut pool = GraphemePool::new();
983        let mut frame = Frame::new(10, 1, &mut pool);
984
985        Widget::render(&pb, area, &mut frame);
986        frame.buffer.degradation = DegradationLevel::EssentialOnly;
987        Widget::render(&pb, area, &mut frame);
988
989        assert_eq!(raw_row_text(&frame, 0, 10), "50%       ");
990    }
991
992    // --- MiniBar tests ---
993
994    #[test]
995    fn minibar_zero_is_empty() {
996        let bar = MiniBar::new(0.0, 10);
997        let filled = bar.render_string().chars().filter(|c| *c == '█').count();
998        assert_eq!(filled, 0);
999    }
1000
1001    #[test]
1002    fn minibar_full_is_complete() {
1003        let bar = MiniBar::new(1.0, 10);
1004        let filled = bar.render_string().chars().filter(|c| *c == '█').count();
1005        assert_eq!(filled, 10);
1006    }
1007
1008    #[test]
1009    fn minibar_half_is_half() {
1010        let bar = MiniBar::new(0.5, 10);
1011        let filled = bar.render_string().chars().filter(|c| *c == '█').count();
1012        assert!((4..=6).contains(&filled));
1013    }
1014
1015    #[test]
1016    fn minibar_color_thresholds() {
1017        let high = MiniBar::color_for_value(0.80);
1018        let mid = MiniBar::color_for_value(0.60);
1019        let low = MiniBar::color_for_value(0.30);
1020        let crit = MiniBar::color_for_value(0.10);
1021        assert_ne!(high, mid);
1022        assert_ne!(mid, low);
1023        assert_ne!(low, crit);
1024    }
1025
1026    #[test]
1027    fn minibar_respects_width() {
1028        for width in [5, 10, 20] {
1029            let bar = MiniBar::new(0.5, width);
1030            assert_eq!(bar.render_string().chars().count(), width as usize);
1031        }
1032    }
1033
1034    // --- MeasurableWidget tests ---
1035
1036    #[test]
1037    fn progress_bar_measure_has_intrinsic_size() {
1038        let pb = ProgressBar::new();
1039        assert!(pb.has_intrinsic_size());
1040    }
1041
1042    #[test]
1043    fn progress_bar_measure_min_size() {
1044        let pb = ProgressBar::new();
1045        let c = pb.measure(Size::MAX);
1046
1047        assert_eq!(c.min.width, 1);
1048        assert_eq!(c.min.height, 1);
1049        assert!(c.max.is_none()); // Fills available width
1050    }
1051
1052    #[test]
1053    fn progress_bar_measure_with_block() {
1054        let pb = ProgressBar::new().block(Block::bordered());
1055        let c = pb.measure(Size::MAX);
1056
1057        // Block adds chrome (borders + padding) = 4 on each axis.
1058        assert_eq!(c.min.width, 5);
1059        assert_eq!(c.min.height, 5);
1060    }
1061
1062    #[test]
1063    fn minibar_measure_fixed_width() {
1064        let bar = MiniBar::new(0.5, 10);
1065        let c = bar.measure(Size::MAX);
1066
1067        assert_eq!(c.preferred.width, 10);
1068        assert_eq!(c.preferred.height, 1);
1069        assert_eq!(c.max, Some(Size::new(10, 1)));
1070    }
1071
1072    #[test]
1073    fn minibar_measure_with_percent() {
1074        let bar = MiniBar::new(0.5, 10).show_percent(true);
1075        let c = bar.measure(Size::MAX);
1076
1077        // Width = 10 + 5 (" XXX%") = 15
1078        assert_eq!(c.preferred.width, 15);
1079        assert_eq!(c.preferred.height, 1);
1080    }
1081
1082    #[test]
1083    fn minibar_measure_has_intrinsic_size() {
1084        let bar = MiniBar::new(0.5, 10);
1085        assert!(bar.has_intrinsic_size());
1086
1087        let zero_width = MiniBar::new(0.5, 0);
1088        assert!(!zero_width.has_intrinsic_size());
1089    }
1090
1091    // ── Edge-case tests (bd-3b82x) ──────────────────────────
1092
1093    #[test]
1094    fn ratio_nan_clamped_to_zero() {
1095        let pb = ProgressBar::new().ratio(f64::NAN);
1096        // We now safely handle NaN in the ratio setter to avoid clamping panic.
1097        // The render path uses floor() which handles NaN → 0
1098        let mut pool = GraphemePool::new();
1099        let mut frame = Frame::new(10, 1, &mut pool);
1100        let area = Rect::new(0, 0, 10, 1);
1101        Widget::render(&pb, area, &mut frame);
1102    }
1103
1104    #[test]
1105    fn ratio_infinity_clamped() {
1106        let pb = ProgressBar::new().ratio(f64::INFINITY);
1107        assert_eq!(pb.ratio, 1.0);
1108
1109        let pb_neg = ProgressBar::new().ratio(f64::NEG_INFINITY);
1110        assert_eq!(pb_neg.ratio, 0.0);
1111    }
1112
1113    #[test]
1114    fn label_wider_than_area() {
1115        let pb = ProgressBar::new()
1116            .ratio(0.5)
1117            .label("This is a very long label text");
1118        let mut pool = GraphemePool::new();
1119        let mut frame = Frame::new(10, 1, &mut pool);
1120        let area = Rect::new(0, 0, 5, 1);
1121        Widget::render(&pb, area, &mut frame); // Should not panic, truncated
1122    }
1123
1124    #[test]
1125    fn label_on_multi_row_bar_vertically_centered() {
1126        let pb = ProgressBar::new().ratio(0.5).label("X");
1127        let mut pool = GraphemePool::new();
1128        let mut frame = Frame::new(10, 5, &mut pool);
1129        let area = Rect::new(0, 0, 10, 5);
1130        Widget::render(&pb, area, &mut frame);
1131        // label_y = top + height/2 = 0 + 2 = 2
1132        let c = frame.buffer.get(4, 2).and_then(|c| c.content.as_char());
1133        assert_eq!(c, Some('X'));
1134    }
1135
1136    #[test]
1137    fn empty_label_renders_no_text() {
1138        let pb = ProgressBar::new().ratio(0.5).label("");
1139        let mut pool = GraphemePool::new();
1140        let mut frame = Frame::new(10, 1, &mut pool);
1141        let area = Rect::new(0, 0, 10, 1);
1142        Widget::render(&pb, area, &mut frame); // Should not panic
1143    }
1144
1145    #[test]
1146    fn progress_bar_clone_and_debug() {
1147        let pb = ProgressBar::new().ratio(0.5).label("test");
1148        let cloned = pb.clone();
1149        assert!((cloned.ratio - 0.5).abs() < f64::EPSILON);
1150        assert_eq!(cloned.label, Some("test"));
1151        let dbg = format!("{:?}", pb);
1152        assert!(dbg.contains("ProgressBar"));
1153    }
1154
1155    #[test]
1156    fn progress_bar_default_trait() {
1157        let pb = ProgressBar::default();
1158        assert_eq!(pb.ratio, 0.0);
1159        assert!(pb.label.is_none());
1160    }
1161
1162    #[test]
1163    fn render_width_one() {
1164        let pb = ProgressBar::new()
1165            .ratio(1.0)
1166            .gauge_style(Style::new().bg(PackedRgba::RED));
1167        let mut pool = GraphemePool::new();
1168        let mut frame = Frame::new(1, 1, &mut pool);
1169        let area = Rect::new(0, 0, 1, 1);
1170        Widget::render(&pb, area, &mut frame);
1171        assert_eq!(cell_at(&frame, 0, 0).bg, PackedRgba::RED);
1172    }
1173
1174    #[test]
1175    fn render_ratio_just_above_zero() {
1176        let pb = ProgressBar::new()
1177            .ratio(0.01)
1178            .gauge_style(Style::new().bg(PackedRgba::GREEN));
1179        let mut pool = GraphemePool::new();
1180        let mut frame = Frame::new(100, 1, &mut pool);
1181        let area = Rect::new(0, 0, 100, 1);
1182        Widget::render(&pb, area, &mut frame);
1183        // floor(100 * 0.01) = 1 cell filled
1184        assert_eq!(cell_at(&frame, 0, 0).bg, PackedRgba::GREEN);
1185        assert_ne!(cell_at(&frame, 1, 0).bg, PackedRgba::GREEN);
1186    }
1187
1188    // --- MiniBar edge cases ---
1189
1190    #[test]
1191    fn minibar_nan_value_treated_as_zero() {
1192        let bar = MiniBar::new(f64::NAN, 10);
1193        let filled = bar.render_string().chars().filter(|c| *c == '█').count();
1194        assert_eq!(filled, 0);
1195    }
1196
1197    #[test]
1198    fn minibar_infinity_clamped_to_full() {
1199        let bar = MiniBar::new(f64::INFINITY, 10);
1200        let filled = bar.render_string().chars().filter(|c| *c == '█').count();
1201        assert_eq!(filled, 0); // NaN/Inf → normalized_value returns 0.0
1202    }
1203
1204    #[test]
1205    fn minibar_negative_value() {
1206        let bar = MiniBar::new(-0.5, 10);
1207        let filled = bar.render_string().chars().filter(|c| *c == '█').count();
1208        assert_eq!(filled, 0);
1209    }
1210
1211    #[test]
1212    fn minibar_value_above_one() {
1213        let bar = MiniBar::new(1.5, 10);
1214        let filled = bar.render_string().chars().filter(|c| *c == '█').count();
1215        assert_eq!(filled, 10); // clamped to 1.0
1216    }
1217
1218    #[test]
1219    fn minibar_width_zero() {
1220        let bar = MiniBar::new(0.5, 0);
1221        assert_eq!(bar.render_string(), "");
1222    }
1223
1224    #[test]
1225    fn minibar_width_one() {
1226        let bar = MiniBar::new(1.0, 1);
1227        let s = bar.render_string();
1228        assert_eq!(s.chars().count(), 1);
1229        assert_eq!(s.chars().next(), Some('█'));
1230    }
1231
1232    #[test]
1233    fn minibar_custom_chars() {
1234        let bar = MiniBar::new(0.5, 4).filled_char('#').empty_char('-');
1235        let s = bar.render_string();
1236        assert!(s.contains('#'));
1237        assert!(s.contains('-'));
1238        assert_eq!(s.chars().count(), 4);
1239    }
1240
1241    #[test]
1242    fn minibar_value_and_width_setters() {
1243        let bar = MiniBar::new(0.0, 5).value(1.0).width(3);
1244        assert_eq!(bar.render_string().chars().count(), 3);
1245        let filled = bar.render_string().chars().filter(|c| *c == '█').count();
1246        assert_eq!(filled, 3);
1247    }
1248
1249    #[test]
1250    fn minibar_color_boundary_exactly_at_high() {
1251        // Default high threshold is 0.75; at exactly 0.75, value is NOT > 0.75
1252        let at_thresh = MiniBar::color_for_value(0.75);
1253        let above = MiniBar::color_for_value(0.76);
1254        let defaults = MiniBarColors::default();
1255        assert_eq!(above, defaults.high);
1256        assert_eq!(at_thresh, defaults.mid); // not above high threshold
1257    }
1258
1259    #[test]
1260    fn minibar_color_boundary_exactly_at_mid() {
1261        let at_thresh = MiniBar::color_for_value(0.50);
1262        let defaults = MiniBarColors::default();
1263        assert_eq!(at_thresh, defaults.low); // not above mid threshold
1264    }
1265
1266    #[test]
1267    fn minibar_color_boundary_exactly_at_low() {
1268        let at_thresh = MiniBar::color_for_value(0.25);
1269        let defaults = MiniBarColors::default();
1270        assert_eq!(at_thresh, defaults.critical); // not above low threshold
1271    }
1272
1273    #[test]
1274    fn minibar_color_for_value_nan() {
1275        let c = MiniBar::color_for_value(f64::NAN);
1276        let defaults = MiniBarColors::default();
1277        assert_eq!(c, defaults.critical); // NaN → 0.0 → critical
1278    }
1279
1280    #[test]
1281    fn minibar_colors_new() {
1282        let r = PackedRgba::rgb(255, 0, 0);
1283        let g = PackedRgba::rgb(0, 255, 0);
1284        let b = PackedRgba::rgb(0, 0, 255);
1285        let w = PackedRgba::rgb(255, 255, 255);
1286        let colors = MiniBarColors::new(r, g, b, w);
1287        assert_eq!(colors.high, r);
1288        assert_eq!(colors.mid, g);
1289        assert_eq!(colors.low, b);
1290        assert_eq!(colors.critical, w);
1291    }
1292
1293    #[test]
1294    fn minibar_custom_thresholds_and_colors() {
1295        let colors = MiniBarColors::new(
1296            PackedRgba::rgb(1, 1, 1),
1297            PackedRgba::rgb(2, 2, 2),
1298            PackedRgba::rgb(3, 3, 3),
1299            PackedRgba::rgb(4, 4, 4),
1300        );
1301        let thresholds = MiniBarThresholds {
1302            high: 0.9,
1303            mid: 0.5,
1304            low: 0.1,
1305        };
1306        let bar = MiniBar::new(0.95, 10).colors(colors).thresholds(thresholds);
1307        let c = bar.color_for_value_with_palette(0.95);
1308        assert_eq!(c, PackedRgba::rgb(1, 1, 1));
1309    }
1310
1311    #[test]
1312    fn minibar_clone_and_debug() {
1313        let bar = MiniBar::new(0.5, 10).show_percent(true);
1314        let cloned = bar.clone();
1315        assert_eq!(cloned.render_string(), bar.render_string());
1316        let dbg = format!("{:?}", bar);
1317        assert!(dbg.contains("MiniBar"));
1318    }
1319
1320    #[test]
1321    fn minibar_render_zero_area() {
1322        let bar = MiniBar::new(0.5, 10);
1323        let mut pool = GraphemePool::new();
1324        let mut frame = Frame::new(10, 1, &mut pool);
1325        let area = Rect::new(0, 0, 0, 0);
1326        Widget::render(&bar, area, &mut frame); // Should not panic
1327    }
1328
1329    #[test]
1330    fn minibar_render_with_percent_narrow() {
1331        let bar = MiniBar::new(0.5, 10).show_percent(true);
1332        let mut pool = GraphemePool::new();
1333        let mut frame = Frame::new(5, 1, &mut pool);
1334        // Area smaller than bar_width + percent_width
1335        let area = Rect::new(0, 0, 5, 1);
1336        Widget::render(&bar, area, &mut frame); // Should adapt or truncate
1337    }
1338
1339    #[test]
1340    fn minibar_render_percent_only_no_bar_room() {
1341        let bar = MiniBar::new(0.5, 10).show_percent(true);
1342        let mut pool = GraphemePool::new();
1343        let mut frame = Frame::new(5, 1, &mut pool);
1344        // Area of width 5, percent takes 5 (" XXX%"), bar_width gets 0
1345        let area = Rect::new(0, 0, 5, 1);
1346        Widget::render(&bar, area, &mut frame);
1347        assert_eq!(cell_at(&frame, 0, 0).content.as_char(), Some('5'));
1348    }
1349
1350    #[test]
1351    fn minibar_render_percent_only_starts_with_digits_in_tight_widths() {
1352        let bar = MiniBar::new(0.5, 10).show_percent(true);
1353        let mut pool = GraphemePool::new();
1354        let mut frame = Frame::new(2, 1, &mut pool);
1355        Widget::render(&bar, Rect::new(0, 0, 2, 1), &mut frame);
1356
1357        assert_eq!(cell_at(&frame, 0, 0).content.as_char(), Some('5'));
1358        assert_eq!(cell_at(&frame, 1, 0).content.as_char(), Some('0'));
1359    }
1360
1361    #[test]
1362    fn minibar_essential_only_percent_starts_with_digits_in_tight_widths() {
1363        use ftui_render::budget::DegradationLevel;
1364
1365        let bar = MiniBar::new(0.5, 10).show_percent(true);
1366        let mut pool = GraphemePool::new();
1367        let mut frame = Frame::new(2, 1, &mut pool);
1368        frame.buffer.degradation = DegradationLevel::EssentialOnly;
1369        Widget::render(&bar, Rect::new(0, 0, 2, 1), &mut frame);
1370
1371        assert_eq!(cell_at(&frame, 0, 0).content.as_char(), Some('5'));
1372        assert_eq!(cell_at(&frame, 1, 0).content.as_char(), Some('0'));
1373    }
1374
1375    #[test]
1376    fn minibar_essential_only_right_aligns_percent_when_width_allows() {
1377        use ftui_render::budget::DegradationLevel;
1378
1379        let bar = MiniBar::new(0.5, 10).show_percent(true);
1380        let mut pool = GraphemePool::new();
1381        let mut frame = Frame::new(7, 1, &mut pool);
1382        frame.buffer.degradation = DegradationLevel::EssentialOnly;
1383        Widget::render(&bar, Rect::new(0, 0, 7, 1), &mut frame);
1384
1385        assert_eq!(cell_at(&frame, 0, 0).content.as_char(), Some(' '));
1386        assert_eq!(cell_at(&frame, 1, 0).content.as_char(), Some(' '));
1387        assert_eq!(cell_at(&frame, 2, 0).content.as_char(), Some(' '));
1388        assert_eq!(cell_at(&frame, 3, 0).content.as_char(), Some(' '));
1389        assert_eq!(cell_at(&frame, 4, 0).content.as_char(), Some('5'));
1390        assert_eq!(cell_at(&frame, 5, 0).content.as_char(), Some('0'));
1391        assert_eq!(cell_at(&frame, 6, 0).content.as_char(), Some('%'));
1392    }
1393
1394    #[test]
1395    fn minibar_essential_only_clears_previous_bar_content() {
1396        use ftui_render::budget::DegradationLevel;
1397
1398        let bar = MiniBar::new(0.5, 10).show_percent(true);
1399        let area = Rect::new(0, 0, 7, 1);
1400        let mut pool = GraphemePool::new();
1401        let mut frame = Frame::new(7, 1, &mut pool);
1402
1403        Widget::render(&bar, area, &mut frame);
1404        frame.buffer.degradation = DegradationLevel::EssentialOnly;
1405        Widget::render(&bar, area, &mut frame);
1406
1407        assert_eq!(raw_row_text(&frame, 0, 7), "    50%");
1408    }
1409
1410    #[test]
1411    fn minibar_thresholds_default_values() {
1412        let t = MiniBarThresholds::default();
1413        assert!((t.high - 0.75).abs() < f64::EPSILON);
1414        assert!((t.mid - 0.50).abs() < f64::EPSILON);
1415        assert!((t.low - 0.25).abs() < f64::EPSILON);
1416    }
1417
1418    #[test]
1419    fn minibar_colors_default_not_all_same() {
1420        let c = MiniBarColors::default();
1421        assert_ne!(c.high, c.mid);
1422        assert_ne!(c.mid, c.low);
1423        assert_ne!(c.low, c.critical);
1424    }
1425
1426    #[test]
1427    fn minibar_colors_copy() {
1428        let c = MiniBarColors::default();
1429        let c2 = c; // Copy
1430        assert_eq!(c.high, c2.high);
1431    }
1432
1433    #[test]
1434    fn minibar_thresholds_copy() {
1435        let t = MiniBarThresholds::default();
1436        let t2 = t; // Copy
1437        assert!((t.high - t2.high).abs() < f64::EPSILON);
1438    }
1439
1440    #[test]
1441    fn minibar_style_setter() {
1442        let bar = MiniBar::new(0.5, 10).style(Style::new().bold());
1443        let dbg = format!("{:?}", bar);
1444        assert!(dbg.contains("MiniBar"));
1445    }
1446
1447    mod indeterminate_tests {
1448        use super::*;
1449        use proptest::prelude::*;
1450
1451        /// Render `pb` to a `width`x1 frame and return, for each column, whether
1452        /// its background is `bg` (i.e. it is a gauge-filled cell).
1453        fn gauge_cols(pb: &ProgressBar, width: u16, bg: PackedRgba) -> Vec<bool> {
1454            let mut pool = GraphemePool::new();
1455            let mut frame = Frame::new(width, 1, &mut pool);
1456            Widget::render(pb, Rect::new(0, 0, width, 1), &mut frame);
1457            (0..width).map(|x| cell_at(&frame, x, 0).bg == bg).collect()
1458        }
1459
1460        /// Render a 40x1 indeterminate bar at `phase` and describe the row as
1461        /// `#` for gauge-filled columns and `.` for the rest.
1462        ///
1463        /// The fill is a space carrying a background colour, not a glyph, so
1464        /// there is nothing to pin as text: the row's identity is which
1465        /// columns are filled, and that is what these render as.
1466        fn marquee_row(phase: u64) -> String {
1467            let bg = PackedRgba::BLUE;
1468            let pb = ProgressBar::new()
1469                .indeterminate(phase)
1470                .gauge_style(Style::new().bg(bg));
1471            gauge_cols(&pb, 40, bg)
1472                .into_iter()
1473                .map(|filled| if filled { '#' } else { '.' })
1474                .collect()
1475        }
1476
1477        // The three phase snapshots required by bd-g00-root-epic-ewths.23.1.
1478        // Width 40 gives seg = 8 and period = 48, so the segment enters from
1479        // the left over phases 0..8 before it starts to travel; these three
1480        // pin the entry, which is where an off-by-one in the span maths shows
1481        // up first and where a clamp bug would let the segment start wider
1482        // than it should.
1483
1484        #[test]
1485        fn progress_indeterminate_phase0_40x1() {
1486            // Phase 0 is the boundary: the segment has not entered, so no
1487            // column is filled. A regression that fails to clamp would paint
1488            // the whole row here.
1489            assert_eq!(marquee_row(0), ".".repeat(40));
1490        }
1491
1492        #[test]
1493        fn progress_indeterminate_phase3_40x1() {
1494            assert_eq!(
1495                marquee_row(3),
1496                format!("{}{}", "#".repeat(3), ".".repeat(37))
1497            );
1498        }
1499
1500        #[test]
1501        fn progress_indeterminate_phase7_40x1() {
1502            assert_eq!(
1503                marquee_row(7),
1504                format!("{}{}", "#".repeat(7), ".".repeat(33))
1505            );
1506        }
1507
1508        #[test]
1509        fn progress_indeterminate_phases_are_distinct_positions() {
1510            // The three snapshots above all sit at the left edge because the
1511            // segment is still entering. This pins a phase from each later
1512            // part of the sweep, so "the segment moves" is actually asserted
1513            // rather than implied.
1514            assert_eq!(
1515                marquee_row(20),
1516                format!("{}{}{}", ".".repeat(12), "#".repeat(8), ".".repeat(20))
1517            );
1518            assert_eq!(marquee_row(47), format!("{}#", ".".repeat(39)));
1519            // One period later the row repeats exactly.
1520            assert_eq!(marquee_row(48 + 20), marquee_row(20));
1521        }
1522
1523        #[test]
1524        fn indeterminate_marquee_wraps() {
1525            // width 40, seg = 40/5 = 8, period = 48.
1526            assert_eq!(ProgressBar::marquee_span(40, 0), Some((0, 0)));
1527            assert_eq!(ProgressBar::marquee_span(40, 3), Some((0, 3)));
1528            assert_eq!(ProgressBar::marquee_span(40, 7), Some((0, 7)));
1529            assert_eq!(ProgressBar::marquee_span(40, 8), Some((0, 8)));
1530            assert_eq!(ProgressBar::marquee_span(40, 20), Some((12, 20)));
1531            assert_eq!(ProgressBar::marquee_span(40, 47), Some((39, 40)));
1532            // Wraps at inner_width + seg = 48.
1533            assert_eq!(ProgressBar::marquee_span(40, 48), Some((0, 0)));
1534            assert_eq!(
1535                ProgressBar::marquee_span(40, 48 + 8),
1536                ProgressBar::marquee_span(40, 8)
1537            );
1538        }
1539
1540        #[test]
1541        fn indeterminate_width_one_and_zero() {
1542            // Zero width has no span.
1543            assert_eq!(ProgressBar::marquee_span(0, 5), None);
1544            // Width 1 (seg clamps to 3) stays inside [0, 1] for every phase.
1545            for phase in 0..10u64 {
1546                let (start, end) = ProgressBar::marquee_span(1, phase).expect("width 1");
1547                assert!(start <= end && end <= 1, "phase {phase}: {start}..{end}");
1548            }
1549            // Rendering width 1 must not panic.
1550            let pb = ProgressBar::new()
1551                .indeterminate(3)
1552                .gauge_style(Style::new().bg(PackedRgba::BLUE));
1553            let _ = gauge_cols(&pb, 1, PackedRgba::BLUE);
1554        }
1555
1556        #[test]
1557        fn determinate_unchanged_by_mode_default() {
1558            let pb = ProgressBar::new()
1559                .ratio(0.5)
1560                .gauge_style(Style::new().bg(PackedRgba::BLUE));
1561            assert!(!pb.is_indeterminate());
1562            let cols = gauge_cols(&pb, 40, PackedRgba::BLUE);
1563            // 0.5 * 40 = 20 cells filled from the left, exactly as before.
1564            assert!(cols[..20].iter().all(|&f| f), "left half filled");
1565            assert!(cols[20..].iter().all(|&f| !f), "right half empty");
1566        }
1567
1568        #[test]
1569        fn indeterminate_render_highlights_marquee() {
1570            let pb = ProgressBar::new()
1571                .indeterminate(8)
1572                .gauge_style(Style::new().bg(PackedRgba::BLUE));
1573            assert!(pb.is_indeterminate());
1574            // phase 8 -> span (0, 8): cols 0..8 highlighted, the rest not.
1575            let cols = gauge_cols(&pb, 40, PackedRgba::BLUE);
1576            assert!(cols[..8].iter().all(|&f| f), "marquee segment filled");
1577            assert!(cols[8..].iter().all(|&f| !f), "rest of bar empty");
1578        }
1579
1580        #[test]
1581        fn indeterminate_ignores_ratio() {
1582            // The marquee is identical whatever the ratio is set to.
1583            let high = ProgressBar::new()
1584                .indeterminate(8)
1585                .ratio(0.9)
1586                .gauge_style(Style::new().bg(PackedRgba::BLUE));
1587            let low = ProgressBar::new()
1588                .indeterminate(8)
1589                .ratio(0.1)
1590                .gauge_style(Style::new().bg(PackedRgba::BLUE));
1591            assert_eq!(
1592                gauge_cols(&high, 40, PackedRgba::BLUE),
1593                gauge_cols(&low, 40, PackedRgba::BLUE)
1594            );
1595        }
1596
1597        proptest! {
1598            #![proptest_config(ProptestConfig::with_cases(1000))]
1599
1600            /// The marquee span is `None` iff the width is 0; otherwise it is a
1601            /// non-empty-to-empty range clamped inside the bar and no wider than
1602            /// the segment.
1603            #[test]
1604            fn marquee_span_always_inside_area(width in 0u16..=200, phase in any::<u64>()) {
1605                match ProgressBar::marquee_span(width, phase) {
1606                    None => prop_assert_eq!(width, 0),
1607                    Some((start, end)) => {
1608                        prop_assert_ne!(width, 0);
1609                        prop_assert!(start <= end);
1610                        prop_assert!(end <= width);
1611                        let seg = (u64::from(width) / 5).max(3);
1612                        prop_assert!(u64::from(end - start) <= seg);
1613                    }
1614                }
1615            }
1616        }
1617    }
1618}