1use std::{
4 collections::VecDeque,
5 time::{Duration, Instant},
6};
7
8use gw_parse::Progress;
9use ratatui::{
10 buffer::Buffer,
11 layout::Rect,
12 style::{Color, Modifier, Style},
13 widgets::Widget,
14};
15
16const FILL_BG: Color = Color::Indexed(28);
18const EMPTY_BG: Color = Color::Indexed(237);
20use throbber_widgets_tui::{BRAILLE_SIX, Throbber, ThrobberState};
21
22const RATE: f32 = 400.0;
24const HOLD: Duration = Duration::from_millis(120);
26
27pub struct Animator {
30 shown: Option<Progress>,
31 fill: f32,
32 since: Instant,
33 last: Instant,
34 queue: VecDeque<Progress>,
35}
36
37fn same_stage(a: &Progress, b: &Progress) -> bool {
38 a.label == b.label && a.remote == b.remote
39}
40
41impl Animator {
42 pub fn new(now: Instant) -> Self {
43 Self { shown: None, fill: 0.0, since: now, last: now, queue: VecDeque::new() }
44 }
45
46 pub fn push(&mut self, p: Progress, now: Instant) {
48 if let Some(b) = self.queue.back_mut().filter(|b| same_stage(b, &p)) {
49 *b = p;
50 return;
51 }
52 match &mut self.shown {
53 Some(s) if self.queue.is_empty() && same_stage(s, &p) => *s = p,
54 Some(_) => self.queue.push_back(p),
55 None => {
56 self.shown = Some(p);
57 self.fill = 0.0;
58 self.since = now;
59 }
60 }
61 }
62
63 fn target(&self) -> f32 {
64 self.shown.as_ref().and_then(|s| s.pct).map_or(0.0, f32::from)
65 }
66
67 pub fn tick(&mut self, now: Instant) {
69 let dt = now.saturating_duration_since(self.last).as_secs_f32();
70 self.last = now;
71 self.fill = (self.fill + RATE * dt).min(self.target());
72 if self.fill >= self.target()
73 && now.saturating_duration_since(self.since) >= HOLD
74 && let Some(next) = self.queue.pop_front()
75 {
76 self.shown = Some(next);
77 self.fill = 0.0;
78 self.since = now;
79 }
80 }
81
82 pub fn current(&self) -> Option<(&Progress, u8)> {
84 self.shown.as_ref().map(|s| (s, self.fill as u8))
85 }
86
87 pub fn latest(&self) -> Option<&Progress> {
89 self.queue.back().or(self.shown.as_ref())
90 }
91
92 pub fn settled(&self) -> bool {
94 self.queue.is_empty() && self.fill >= self.target()
95 }
96}
97
98pub struct ProgressLine<'a> {
99 pub progress: &'a Progress,
100 pub fill: Option<u8>,
102 pub throbber: &'a ThrobberState,
103 pub done: Option<bool>,
105 pub color: bool,
106}
107
108impl Widget for ProgressLine<'_> {
109 fn render(self, area: Rect, buf: &mut Buffer) {
110 if area.width < 6 || area.height == 0 {
111 return;
112 }
113 let y = area.y;
114 let st = |c: Color| if self.color { Style::default().fg(c) } else { Style::default() };
115 let (mark, mark_style) = match self.done {
116 Some(true) => ("✔".to_string(), st(Color::Green)),
117 Some(false) => ("✘".to_string(), st(Color::Red)),
118 None => {
119 let span = Throbber::default().throbber_set(BRAILLE_SIX).to_symbol_span(self.throbber);
120 (span.content.trim().to_string(), Style::default())
121 }
122 };
123 buf.set_string(area.x, y, &mark, mark_style);
124 buf.set_string(area.x + 2, y, "[", Style::default());
125 buf.set_string(area.x + area.width - 1, y, "]", Style::default());
126
127 let x0 = area.x + 3;
128 let w = (area.width - 4) as usize;
129 let p = self.progress;
130 let fill = self.fill.or(p.pct).map_or(0, |pct| w * pct.min(100) as usize / 100);
131 let right = match (p.cur, p.total, p.pct) {
132 (Some(c), Some(t), Some(pct)) if area.width >= 40 => format!("{c}/{t} {pct}%"),
133 (_, _, Some(pct)) => format!("{pct}%"),
134 (Some(c), _, None) if area.width >= 40 => c.to_string(),
135 _ => String::new(),
136 };
137 let label = if area.width >= 40 { p.label.as_str() } else { "" };
138
139 let mut text: Vec<Option<char>> = vec![None; w];
141 let right_start = w.saturating_sub(right.chars().count() + 1);
142 for (i, c) in label.chars().enumerate() {
143 if 1 + i + 1 < right_start {
144 text[1 + i] = Some(c);
145 }
146 }
147 for (i, c) in right.chars().enumerate() {
148 if right_start + i < w {
149 text[right_start + i] = Some(c);
150 }
151 }
152 for (i, t) in text.iter().enumerate() {
153 let filled = i < fill;
154 let (sym, style) = match (self.color, t) {
155 (true, _) => {
156 let style = if filled {
158 Style::default().bg(FILL_BG).fg(Color::Indexed(231)).add_modifier(Modifier::BOLD)
159 } else {
160 Style::default().bg(EMPTY_BG).fg(Color::Indexed(252))
161 };
162 (t.unwrap_or(' '), style)
163 }
164 (false, Some(c)) => (*c, Style::default()),
165 (false, None) => (if filled { '#' } else { '.' }, Style::default()),
166 };
167 buf[(x0 + i as u16, y)].set_char(sym).set_style(style);
168 }
169 }
170}
171
172#[cfg(test)]
173mod tests {
174 use super::*;
175 use ratatui::{Terminal, backend::TestBackend};
176
177 fn draw(width: u16, pct: Option<u8>, cur: u64, done: Option<bool>, color: bool) -> Buffer {
178 let p = Progress { label: "Writing objects".into(), cur: Some(cur), total: Some(9), pct, ..Default::default() };
179 let mut t = Terminal::new(TestBackend::new(width, 1)).unwrap();
180 let th = ThrobberState::default();
181 t.draw(|f| f.render_widget(ProgressLine { progress: &p, fill: None, throbber: &th, done, color }, f.area())).unwrap();
182 t.backend().buffer().clone()
183 }
184
185 fn line(b: &Buffer) -> String {
186 b.content.iter().map(|c| c.symbol()).collect()
187 }
188
189 fn bg(b: &Buffer, x: u16) -> Option<Color> {
190 b[(x, 0)].style().bg
191 }
192
193 fn stage(label: &str, pct: u8) -> Progress {
194 Progress { label: label.into(), pct: Some(pct), ..Default::default() }
195 }
196
197 #[test]
198 fn animator_plays_instant_stages_in_order() {
199 let t0 = Instant::now();
200 let ms = |n| t0 + Duration::from_millis(n);
201 let mut a = Animator::new(t0);
202 for (i, p) in [stage("Compressing objects", 50), stage("Compressing objects", 100), stage("Writing objects", 100)].into_iter().enumerate() {
203 a.push(p, ms(i as u64));
204 }
205 a.push(stage("Resolving deltas", 100), ms(3));
206 assert_eq!(a.latest().unwrap().label, "Resolving deltas");
207 a.tick(ms(100));
208 let (p, fill) = a.current().unwrap();
209 assert_eq!((p.label.as_str(), fill), ("Compressing objects", 40), "merged to 100%, eased 400%/s");
210 a.tick(ms(260));
211 assert_eq!(a.current().unwrap().0.label, "Writing objects", "caught up and held -> next stage");
212 assert_eq!(a.current().unwrap().1, 0);
213 a.tick(ms(520));
214 assert_eq!(a.current().unwrap().0.label, "Resolving deltas");
215 assert!(!a.settled());
216 a.tick(ms(800));
217 assert!(a.settled());
218 }
219
220 #[test]
221 fn fill_override() {
222 let p = stage("Writing objects", 100);
223 let mut t = Terminal::new(TestBackend::new(60, 1)).unwrap();
224 let th = ThrobberState::default();
225 t.draw(|f| f.render_widget(ProgressLine { progress: &p, fill: Some(50), throbber: &th, done: None, color: true }, f.area())).unwrap();
226 let b = t.backend().buffer();
227 assert_eq!(bg(b, 30), Some(FILL_BG));
228 assert_eq!(bg(b, 31), Some(EMPTY_BG));
229 assert!(line(b).contains("100%"), "counters show git's real value");
230 }
231
232 #[test]
233 fn zero_percent() {
234 let b = draw(60, Some(0), 0, None, true);
235 assert!(line(&b).contains("[ Writing objects"));
236 assert!(line(&b).ends_with("0/9 0% ]"));
237 assert_eq!(bg(&b, 3), Some(EMPTY_BG));
238 }
239
240 #[test]
241 fn forty_four_percent() {
242 let b = draw(60, Some(44), 4, None, true);
243 assert_eq!(bg(&b, 26), Some(FILL_BG));
245 assert_eq!(bg(&b, 27), Some(EMPTY_BG));
246 assert_eq!(b[(5, 0)].style().fg, Some(Color::Indexed(231)), "label readable on green");
247 assert!(line(&b).contains("4/9 44%"));
248 let plain = line(&draw(60, Some(44), 4, None, false));
249 assert!(plain.contains("[#Writing objects########."), "{plain}");
250 assert!(plain.contains("....4/9 44%.]"), "{plain}");
251 }
252
253 #[test]
254 fn full_success() {
255 let b = draw(60, Some(100), 9, Some(true), true);
256 assert!(line(&b).starts_with("✔ [ Writing objects"));
257 assert!(line(&b).ends_with("9/9 100% ]"));
258 assert_eq!(b[(0, 0)].style().fg, Some(Color::Green));
259 assert_eq!(bg(&b, 58), Some(FILL_BG));
260 }
261
262 #[test]
263 fn failed_keeps_progress() {
264 let b = draw(60, Some(44), 4, Some(false), true);
265 assert!(line(&b).starts_with("✘"));
266 assert_eq!(b[(0, 0)].style().fg, Some(Color::Red));
267 assert_eq!(bg(&b, 26), Some(FILL_BG));
268 assert_eq!(bg(&b, 27), Some(EMPTY_BG));
269 }
270
271 #[test]
272 fn narrow_drops_label() {
273 let s = line(&draw(30, Some(44), 4, None, false));
274 assert_eq!(s.chars().count(), 30);
275 assert!(!s.contains("Writing"));
276 assert!(s.ends_with("44%.]"), "{s}");
277 assert!(s.contains("[###"), "{s}");
278 }
279}