revue 2.71.1

A Vue-style TUI framework for Rust with CSS styling
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
//! Gauge widget for displaying metrics and progress
//!
//! Advanced progress indicators with various styles including
//! speedometer, arc, battery, and more.

use crate::render::{Cell, Modifier};
use crate::style::Color;
use crate::utils::color::contrast_color;
use crate::utils::{char_width, display_width};
use crate::widget::theme::SEPARATOR_COLOR;
use crate::widget::traits::{RenderContext, View, WidgetProps};
use crate::{impl_props_builders, impl_styled_view};

/// Gauge style
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum GaugeStyle {
    /// Horizontal bar with segments
    #[default]
    Bar,
    /// Battery indicator
    Battery,
    /// Thermometer style
    Thermometer,
    /// Circular/arc (text-based)
    Arc,
    /// Percentage circle
    Circle,
    /// Vertical bar
    Vertical,
    /// Segmented blocks
    Segments,
    /// Dot indicator
    Dots,
}

/// Gauge label position
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LabelPosition {
    /// No label
    None,
    /// Inside the gauge
    #[default]
    Inside,
    /// Left of gauge
    Left,
    /// Right of gauge
    Right,
    /// Above gauge
    Above,
    /// Below gauge
    Below,
}

/// Gauge widget
pub struct Gauge {
    /// Current value (0.0 - 1.0)
    value: f64,
    /// Minimum value for display
    min: f64,
    /// Maximum value for display
    max: f64,
    /// Visual style
    style: GaugeStyle,
    /// Width (for horizontal styles)
    width: u16,
    /// Height (for vertical styles)
    height: u16,
    /// Label format
    label: Option<String>,
    /// Label position
    label_position: LabelPosition,
    /// Show percentage
    show_percent: bool,
    /// Filled color
    fill_color: Color,
    /// Filled background color
    fill_bg: Option<Color>,
    /// Empty/track color
    empty_color: Color,
    /// Empty background color
    empty_bg: Option<Color>,
    /// Border color
    border_color: Option<Color>,
    /// Warning threshold (0.0-1.0)
    warning_threshold: Option<f64>,
    /// Critical threshold (0.0-1.0)
    critical_threshold: Option<f64>,
    /// Warning color
    warning_color: Color,
    /// Critical color
    critical_color: Color,
    /// Segments count (for segmented style)
    segments: u16,
    /// Title
    title: Option<String>,
    /// Widget properties
    props: WidgetProps,
}

impl Gauge {
    /// Create a new gauge
    pub fn new() -> Self {
        Self {
            value: 0.0,
            min: 0.0,
            max: 100.0,
            style: GaugeStyle::Bar,
            width: 20,
            height: 5,
            label: None,
            label_position: LabelPosition::Inside,
            show_percent: true,
            fill_color: Color::GREEN,
            fill_bg: None,
            empty_color: SEPARATOR_COLOR,
            empty_bg: None,
            border_color: None,
            warning_threshold: None,
            critical_threshold: None,
            warning_color: Color::YELLOW,
            critical_color: Color::RED,
            segments: 10,
            title: None,
            props: WidgetProps::new(),
        }
    }

    /// Set value (0.0 - 1.0)
    pub fn value(mut self, value: f64) -> Self {
        self.value = value.clamp(0.0, 1.0);
        self
    }

    /// Set value with custom range
    ///
    /// If min >= max, they will be swapped to ensure valid range.
    /// If min == max after potential swap, value defaults to 0.0.
    pub fn value_range(mut self, value: f64, min: f64, max: f64) -> Self {
        // Ensure min < max
        let (min, max) = if min < max { (min, max) } else { (max, min) };

        self.min = min;
        self.max = max;

        // Avoid division by zero
        let range = max - min;
        if range.abs() < f64::EPSILON {
            self.value = 0.0;
        } else {
            self.value = ((value - min) / range).clamp(0.0, 1.0);
        }
        self
    }

    /// Set percentage (0-100)
    pub fn percent(mut self, percent: f64) -> Self {
        self.value = (percent / 100.0).clamp(0.0, 1.0);
        self
    }

    /// Set style
    pub fn style(mut self, style: GaugeStyle) -> Self {
        self.style = style;
        self
    }

    /// Set width
    pub fn width(mut self, width: u16) -> Self {
        self.width = width.max(4);
        self
    }

    /// Set height
    pub fn height(mut self, height: u16) -> Self {
        self.height = height.max(1);
        self
    }

    /// Set custom label
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Set label position
    pub fn label_position(mut self, position: LabelPosition) -> Self {
        self.label_position = position;
        self
    }

    /// Show/hide percentage
    pub fn show_percent(mut self, show: bool) -> Self {
        self.show_percent = show;
        self
    }

    /// Set fill color
    pub fn fill_color(mut self, color: Color) -> Self {
        self.fill_color = color;
        self
    }

    /// Set fill background color
    pub fn fill_background(mut self, color: Color) -> Self {
        self.fill_bg = Some(color);
        self
    }

    /// Set empty color
    pub fn empty_color(mut self, color: Color) -> Self {
        self.empty_color = color;
        self
    }

    /// Set empty background color
    pub fn empty_background(mut self, color: Color) -> Self {
        self.empty_bg = Some(color);
        self
    }

    /// Set border color
    pub fn border(mut self, color: Color) -> Self {
        self.border_color = Some(color);
        self
    }

    /// Set thresholds for color changes
    ///
    /// Warning threshold should be less than critical threshold.
    /// If warning >= critical, they will be swapped.
    pub fn thresholds(mut self, warning: f64, critical: f64) -> Self {
        let warning = warning.clamp(0.0, 1.0);
        let critical = critical.clamp(0.0, 1.0);
        // Ensure warning < critical
        let (warning, critical) = if warning < critical {
            (warning, critical)
        } else {
            (critical, warning)
        };
        self.warning_threshold = Some(warning);
        self.critical_threshold = Some(critical);
        self
    }

    /// Set warning color
    pub fn warning_color(mut self, color: Color) -> Self {
        self.warning_color = color;
        self
    }

    /// Set critical color
    pub fn critical_color(mut self, color: Color) -> Self {
        self.critical_color = color;
        self
    }

    /// Set segments count
    pub fn segments(mut self, count: u16) -> Self {
        self.segments = count.max(2);
        self
    }

    /// Set title
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Get current display color based on thresholds
    fn current_color(&self) -> Color {
        if let Some(critical) = self.critical_threshold {
            if self.value >= critical {
                return self.critical_color;
            }
        }
        if let Some(warning) = self.warning_threshold {
            if self.value >= warning {
                return self.warning_color;
            }
        }
        self.fill_color
    }

    /// Get label text
    fn get_label(&self) -> String {
        if let Some(ref label) = self.label {
            label.clone()
        } else if self.show_percent {
            format!("{:.0}%", self.value * 100.0)
        } else {
            let display_value = self.min + self.value * (self.max - self.min);
            format!("{:.0}", display_value)
        }
    }

    /// Update value
    pub fn set_value(&mut self, value: f64) {
        self.value = value.clamp(0.0, 1.0);
    }

    /// Get current value
    pub fn get_value(&self) -> f64 {
        self.value
    }

    /// Render bar style
    fn render_bar(&self, ctx: &mut RenderContext) {
        let area = ctx.area;
        let width = self.width.min(area.width);
        let filled = (self.value * width as f64).round() as u16;
        let color = self.current_color();

        // Draw bar
        for x in 0..width {
            let is_filled = x < filled;
            let ch = if is_filled { '' } else { '' };
            let fg = if is_filled { color } else { self.empty_color };
            let bg = if is_filled {
                self.fill_bg.unwrap_or(color)
            } else {
                self.empty_bg.unwrap_or(self.empty_color)
            };

            let mut cell = Cell::new(ch);
            cell.fg = Some(fg);
            cell.bg = Some(bg);
            ctx.set(x, 0, cell);
        }

        // Draw label inside
        if matches!(self.label_position, LabelPosition::Inside) {
            let label = self.get_label();
            let lw = display_width(&label) as u16;
            let label_x = (width.saturating_sub(lw)) / 2;
            let mut dx: u16 = 0;
            for ch in label.chars() {
                let cw = char_width(ch) as u16;
                let x = label_x + dx;
                if x + cw <= width {
                    let is_filled = x < filled;
                    let bg = if is_filled {
                        self.fill_bg.unwrap_or(color)
                    } else {
                        self.empty_bg.unwrap_or(self.empty_color)
                    };
                    let mut cell = Cell::new(ch);
                    cell.fg = Some(contrast_color(bg));
                    cell.bg = Some(bg);
                    cell.modifier |= Modifier::BOLD;
                    ctx.set(x, 0, cell);
                }
                dx += cw;
            }
        }
    }

    /// Render battery style
    fn render_battery(&self, ctx: &mut RenderContext) {
        let area = ctx.area;
        let width = self.width.min(area.width).max(6);
        let inner_width = width - 3; // Account for borders and cap
        let filled = (self.value * inner_width as f64).round() as u16;
        let color = self.current_color();

        // Battery body
        let mut left = Cell::new('[');
        left.fg = Some(Color::WHITE);
        ctx.set(0, 0, left);

        for x in 0..inner_width {
            let ch = if x < filled { '' } else { ' ' };
            let fg = if x < filled { color } else { self.empty_color };
            let mut cell = Cell::new(ch);
            cell.fg = Some(fg);
            ctx.set(1 + x, 0, cell);
        }

        let mut right = Cell::new(']');
        right.fg = Some(Color::WHITE);
        ctx.set(1 + inner_width, 0, right);

        // Battery cap
        let mut cap = Cell::new('');
        cap.fg = Some(Color::WHITE);
        ctx.set(2 + inner_width, 0, cap);
    }

    /// Render thermometer style
    fn render_thermometer(&self, ctx: &mut RenderContext) {
        let area = ctx.area;
        let height = self.height.min(area.height).max(3);
        let filled = (self.value * (height - 1) as f64).round() as u16;
        let color = self.current_color();

        // Bulb at bottom
        let mut bulb = Cell::new('');
        bulb.fg = Some(color);
        ctx.set(0, height - 1, bulb);

        // Tube
        for y in 0..height - 1 {
            let from_bottom = height - 2 - y;
            let ch = if from_bottom < filled { '' } else { '' };
            let fg = if from_bottom < filled {
                color
            } else {
                self.empty_color
            };
            let mut cell = Cell::new(ch);
            cell.fg = Some(fg);
            ctx.set(0, y, cell);
        }
    }

    /// Render arc style
    fn render_arc(&self, ctx: &mut RenderContext) {
        let area = ctx.area;
        let color = self.current_color();

        // Simple text-based arc: ╭───────╮
        //                        │ 75%   │
        //                        ╰───────╯
        let width = self.width.min(area.width).max(8);

        // Top arc
        let mut tl = Cell::new('');
        tl.fg = Some(color);
        ctx.set(0, 0, tl);

        for x in 1..width - 1 {
            let progress = (x - 1) as f64 / (width - 3) as f64;
            let ch = if progress <= self.value { '' } else { '' };
            let fg = if progress <= self.value {
                color
            } else {
                self.empty_color
            };
            let mut cell = Cell::new(ch);
            cell.fg = Some(fg);
            ctx.set(x, 0, cell);
        }

        let mut tr = Cell::new('');
        tr.fg = Some(color);
        ctx.set(width - 1, 0, tr);

        // Middle with label
        if area.height > 1 {
            let label = self.get_label();
            let lw = display_width(&label) as u16;
            let label_x = (width.saturating_sub(lw)) / 2;

            let mut left = Cell::new('');
            left.fg = Some(color);
            ctx.set(0, 1, left);

            let mut dx: u16 = 0;
            for ch in label.chars() {
                let cw = char_width(ch) as u16;
                let mut cell = Cell::new(ch);
                cell.fg = Some(contrast_color(self.empty_bg.unwrap_or(Color::rgb(0, 0, 0))));
                cell.modifier |= Modifier::BOLD;
                ctx.set(label_x + dx, 1, cell);
                dx += cw;
            }

            let mut right = Cell::new('');
            right.fg = Some(color);
            ctx.set(width - 1, 1, right);
        }

        // Bottom arc
        if area.height > 2 {
            let mut bl = Cell::new('');
            bl.fg = Some(color);
            ctx.set(0, 2, bl);

            for x in 1..width - 1 {
                let mut cell = Cell::new('');
                cell.fg = Some(self.empty_color);
                ctx.set(x, 2, cell);
            }

            let mut br = Cell::new('');
            br.fg = Some(color);
            ctx.set(width - 1, 2, br);
        }
    }

    /// Render circle style (text-based)
    fn render_circle(&self, ctx: &mut RenderContext) {
        let color = self.current_color();

        // Braille-based circle approximation
        // ⠀⢀⣴⣾⣿⣷⣦⡀⠀
        // ⠀⣿⣿⣿⣿⣿⣿⣿⠀
        // ⠀⠻⣿⣿⣿⣿⣿⠟⠀

        let label = self.get_label();

        // Simple representation: (●●●○○) 60%
        let segments = 5u16;
        let filled = (self.value * segments as f64).round() as u16;

        let mut open = Cell::new('(');
        open.fg = Some(Color::WHITE);
        ctx.set(0, 0, open);

        for i in 0..segments {
            let ch = if i < filled { '' } else { '' };
            let fg = if i < filled { color } else { self.empty_color };
            let mut cell = Cell::new(ch);
            cell.fg = Some(fg);
            ctx.set(1 + i, 0, cell);
        }

        let mut close = Cell::new(')');
        close.fg = Some(Color::WHITE);
        ctx.set(1 + segments, 0, close);

        // Label
        let label_x = 3 + segments;
        let mut dx: u16 = 0;
        for ch in label.chars() {
            let cw = char_width(ch) as u16;
            let mut cell = Cell::new(ch);
            cell.fg = Some(contrast_color(self.empty_bg.unwrap_or(Color::rgb(0, 0, 0))));
            ctx.set(label_x + dx, 0, cell);
            dx += cw;
        }
    }

    /// Render vertical style
    fn render_vertical(&self, ctx: &mut RenderContext) {
        let area = ctx.area;
        let height = self.height.min(area.height);
        let filled = (self.value * height as f64).round() as u16;
        let color = self.current_color();

        for y in 0..height {
            let from_bottom = height - 1 - y;
            let ch = if from_bottom < filled { '' } else { '' };
            let fg = if from_bottom < filled {
                color
            } else {
                self.empty_color
            };
            let mut cell = Cell::new(ch);
            cell.fg = Some(fg);
            ctx.set(0, y, cell);
        }
    }

    /// Render segments style
    fn render_segments(&self, ctx: &mut RenderContext) {
        let area = ctx.area;
        let segments = self.segments.min(area.width / 2);
        let filled = (self.value * segments as f64).round() as u16;
        let color = self.current_color();

        for i in 0..segments {
            let ch = if i < filled { '' } else { '' };
            let fg = if i < filled { color } else { self.empty_color };
            let mut cell = Cell::new(ch);
            cell.fg = Some(fg);
            ctx.set(i * 2, 0, cell);
        }
    }

    /// Render dots style
    fn render_dots(&self, ctx: &mut RenderContext) {
        let area = ctx.area;
        let dots = self.segments.min(area.width);
        let filled = (self.value * dots as f64).round() as u16;
        let color = self.current_color();

        for i in 0..dots {
            let ch = if i < filled { '' } else { '' };
            let fg = if i < filled { color } else { self.empty_color };
            let mut cell = Cell::new(ch);
            cell.fg = Some(fg);
            ctx.set(i, 0, cell);
        }
    }
}

impl Default for Gauge {
    fn default() -> Self {
        Self::new()
    }
}

impl View for Gauge {
    crate::impl_view_meta!("Gauge");

    fn render(&self, ctx: &mut RenderContext) {
        let area = ctx.area;
        if area.width == 0 || area.height == 0 {
            return;
        }

        // Draw title if present
        let mut y_offset = 0u16;
        if let Some(ref title) = self.title {
            for (i, ch) in title.chars().enumerate() {
                if i as u16 >= area.width {
                    break;
                }
                let mut cell = Cell::new(ch);
                cell.fg = Some(Color::WHITE);
                cell.modifier |= Modifier::BOLD;
                ctx.set(i as u16, 0, cell);
            }
            y_offset = 1;
        }

        let adjusted_area = ctx.sub_area(
            0,
            y_offset,
            area.width,
            area.height.saturating_sub(y_offset),
        );

        let mut adjusted_ctx = RenderContext::new(ctx.buffer, adjusted_area);

        match self.style {
            GaugeStyle::Bar => self.render_bar(&mut adjusted_ctx),
            GaugeStyle::Battery => self.render_battery(&mut adjusted_ctx),
            GaugeStyle::Thermometer => self.render_thermometer(&mut adjusted_ctx),
            GaugeStyle::Arc => self.render_arc(&mut adjusted_ctx),
            GaugeStyle::Circle => self.render_circle(&mut adjusted_ctx),
            GaugeStyle::Vertical => self.render_vertical(&mut adjusted_ctx),
            GaugeStyle::Segments => self.render_segments(&mut adjusted_ctx),
            GaugeStyle::Dots => self.render_dots(&mut adjusted_ctx),
        }
    }
}

impl_styled_view!(Gauge);
impl_props_builders!(Gauge);

/// Helper to create a gauge
pub fn gauge() -> Gauge {
    Gauge::new()
}

/// Helper to create a percentage gauge
pub fn percentage(value: f64) -> Gauge {
    Gauge::new().percent(value)
}

/// Helper to create a battery gauge
pub fn battery(level: f64) -> Gauge {
    Gauge::new()
        .percent(level)
        .style(GaugeStyle::Battery)
        .thresholds(0.5, 0.2)
}

// Most tests moved to tests/widget_tests.rs

#[cfg(test)]
mod tests {
    use super::*;
    use crate::layout::Rect;
    use crate::render::Buffer;

    #[test]
    fn test_gauge_new() {
        let g = Gauge::new();
        assert_eq!(g.value, 0.0);
    }

    #[test]
    fn test_gauge_value() {
        let g = Gauge::new().value(0.75);
        assert_eq!(g.value, 0.75);
    }

    #[test]
    fn test_gauge_value_clamped() {
        let g = Gauge::new().value(1.5);
        assert_eq!(g.value, 1.0);
        let g = Gauge::new().value(-0.5);
        assert_eq!(g.value, 0.0);
    }

    #[test]
    fn test_gauge_percent() {
        let g = Gauge::new().percent(50.0);
        assert!((g.value - 0.5).abs() < 0.01);
    }

    #[test]
    fn test_gauge_styles() {
        let _ = Gauge::new().style(GaugeStyle::Bar);
        let _ = Gauge::new().style(GaugeStyle::Battery);
        let _ = Gauge::new().style(GaugeStyle::Arc);
        let _ = Gauge::new().style(GaugeStyle::Vertical);
    }

    #[test]
    fn test_gauge_render_no_panic() {
        let mut buf = Buffer::new(20, 3);
        let area = Rect::new(0, 0, 20, 3);
        let mut ctx = RenderContext::new(&mut buf, area);
        let g = Gauge::new().value(0.5).style(GaugeStyle::Bar);
        g.render(&mut ctx);
    }

    #[test]
    fn test_gauge_helpers() {
        let g = gauge().value(0.7);
        assert_eq!(g.value, 0.7);
        let b = battery(80.0);
        assert!((b.value - 0.8).abs() < 0.01);
    }
}