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
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;

use futures::Future;
use indicatif::MultiProgress;

static PROGRESS_TRACKER: OnceLock<Mutex<ProgressTracker>> = OnceLock::new();

tokio::task_local! {
    static CURRENT_GROUP: Vec<usize>;
}

#[derive(Clone, PartialEq, Eq, Debug)]
pub enum LeafStatus {
    Started,
    Finished,
}

#[derive(Debug)]
pub enum BarTree {
    Root(Vec<BarTree>),
    Group(
        String,
        Arc<indicatif::ProgressBar>,
        Vec<BarTree>,
        Option<usize>,
    ),
    Leaf(String, Arc<indicatif::ProgressBar>, LeafStatus),
    Finished,
}

impl BarTree {
    fn get_pb(&self) -> Option<&Arc<indicatif::ProgressBar>> {
        match self {
            BarTree::Root(_) => None,
            BarTree::Group(_, pb, _, _) | BarTree::Leaf(_, pb, _) => Some(pb),
            BarTree::Finished => None,
        }
    }

    fn status(&self) -> LeafStatus {
        match self {
            BarTree::Root(children) | BarTree::Group(_, _, children, _) => {
                if !children.is_empty()
                    && children
                        .iter()
                        .all(|child| child.status() == LeafStatus::Finished)
                {
                    LeafStatus::Finished
                } else {
                    LeafStatus::Started
                }
            }
            BarTree::Leaf(_, _, status) => status.clone(),
            BarTree::Finished => LeafStatus::Finished,
        }
    }

    fn refresh_prefix(&mut self, cur_path: &[String]) {
        match self {
            BarTree::Root(children) => {
                for child in children {
                    child.refresh_prefix(cur_path);
                }
            }
            BarTree::Group(name, pb, children, anticipated_total) => {
                let finished_count = children
                    .iter()
                    .filter(|child| child.status() == LeafStatus::Finished)
                    .count();
                let started_count = children
                    .iter()
                    .filter(|child| child.status() == LeafStatus::Started)
                    .count();
                let queued_count =
                    anticipated_total.map(|total| total - finished_count - started_count);

                let progress_str =
                    if anticipated_total.iter().any(|v| *v == 1) && started_count == 1 {
                        "".to_string()
                    } else {
                        match queued_count {
                            Some(queued_count) => {
                                format!(
                                    " ({}/{}/{})",
                                    finished_count,
                                    started_count,
                                    queued_count + finished_count + started_count
                                )
                            }
                            None => format!(" ({}/{}/?)", finished_count, started_count),
                        }
                    };

                if cur_path.is_empty() {
                    pb.set_prefix(format!("{}{}", name, progress_str));
                } else {
                    pb.set_prefix(format!(
                        "{} / {}{}",
                        cur_path.join(" / "),
                        name,
                        progress_str,
                    ));
                }

                let mut path_with_group = cur_path.to_vec();
                let non_finished_count = children
                    .iter()
                    .filter(|child| child.status() != LeafStatus::Finished)
                    .count();

                if non_finished_count == 1 {
                    path_with_group.push(format!("{}{}", name, progress_str));
                } else {
                    path_with_group.push(name.clone());
                }

                for child in children {
                    child.refresh_prefix(&path_with_group);
                }
            }
            BarTree::Leaf(name, pb, _) => {
                let mut path_with_group = cur_path.to_vec();
                path_with_group.push(name.clone());
                pb.set_prefix(path_with_group.join(" / "));
            }
            BarTree::Finished => {}
        }
    }

    fn find_node(&self, path: &[usize]) -> &BarTree {
        if path.is_empty() {
            return self;
        }

        match self {
            BarTree::Root(children) | BarTree::Group(_, _, children, _) => {
                children[path[0]].find_node(&path[1..])
            }
            _ => panic!(),
        }
    }

    fn find_node_mut(&mut self, path: &[usize]) -> &mut BarTree {
        if path.is_empty() {
            return self;
        }

        match self {
            BarTree::Root(children) | BarTree::Group(_, _, children, _) => {
                children[path[0]].find_node_mut(&path[1..])
            }
            _ => panic!(),
        }
    }
}

pub struct ProgressTracker {
    pub(crate) multi_progress: MultiProgress,
    tree: BarTree,
    pub(crate) current_count: usize,
    progress_list: Vec<(Arc<indicatif::ProgressBar>, bool)>,
}

impl ProgressTracker {
    pub(crate) fn new() -> ProgressTracker {
        ProgressTracker {
            multi_progress: MultiProgress::new(),
            tree: BarTree::Root(vec![]),
            current_count: 0,
            progress_list: vec![],
        }
    }

    pub fn start_task(
        &mut self,
        under_path: Vec<usize>,
        name: String,
        group: bool,
        anticipated_total: Option<usize>,
        progress: bool,
    ) -> (usize, Arc<indicatif::ProgressBar>) {
        let surrounding = self.tree.find_node(&under_path);
        let (surrounding_children, surrounding_pb) = match surrounding {
            BarTree::Root(children) => (children, None),
            BarTree::Group(_, pb, children, _) => (children, Some(pb)),
            _ => panic!(),
        };

        if let Some(surrounding_pb) = &surrounding_pb {
            let non_finished_count = surrounding_children
                .iter()
                .filter(|child| child.status() != LeafStatus::Finished)
                .count();
            if non_finished_count == 0 {
                self.multi_progress.remove(surrounding_pb.as_ref());
                let surrounding_idx = self
                    .progress_list
                    .iter()
                    .position(|(pb, _)| Arc::ptr_eq(pb, surrounding_pb))
                    .unwrap();
                self.progress_list[surrounding_idx].1 = false;
            } else if non_finished_count == 1 {
                let self_idx = self
                    .progress_list
                    .iter()
                    .position(|(pb, _)| Arc::ptr_eq(pb, surrounding_pb))
                    .unwrap();
                let last_visible_before = self.progress_list[..self_idx]
                    .iter()
                    .rposition(|(_, visible)| *visible);
                if let Some(last_visible_before) = last_visible_before {
                    self.multi_progress.insert_after(
                        &self.progress_list[last_visible_before].0,
                        surrounding_pb.as_ref().clone(),
                    );
                } else {
                    self.multi_progress
                        .insert(0, surrounding_pb.as_ref().clone());
                }

                self.progress_list[self_idx].1 = true;
            }
        }

        let surrounding = self.tree.find_node_mut(&under_path);
        let (surrounding_children, surrounding_pb) = match surrounding {
            BarTree::Root(children) => (children, None),
            BarTree::Group(_, pb, children, _) => (children, Some(pb)),
            _ => panic!(),
        };

        self.current_count += 1;

        let core_bar = indicatif::ProgressBar::new(100);
        let previous_bar = surrounding_children
            .iter()
            .rev()
            .flat_map(|c| c.get_pb())
            .next();

        let index_to_insert = if let Some(previous_bar) = previous_bar {
            let index_of_prev = self
                .progress_list
                .iter()
                .position(|pb| Arc::ptr_eq(&pb.0, previous_bar))
                .unwrap();
            index_of_prev + 1
        } else if let Some(group_pb) = surrounding_pb {
            let index_of_group = self
                .progress_list
                .iter()
                .position(|pb| Arc::ptr_eq(&pb.0, group_pb))
                .unwrap();
            index_of_group + 1
        } else if !self.progress_list.is_empty() {
            self.progress_list.len()
        } else {
            0
        };

        let last_visible = if !self.progress_list.is_empty() {
            self.progress_list[..index_to_insert]
                .iter()
                .rposition(|(_, visible)| *visible)
        } else {
            None
        };

        let created_bar = if let Some(last_visible) = last_visible {
            self.multi_progress
                .insert_after(&self.progress_list[last_visible].0, core_bar)
        } else {
            self.multi_progress.insert(0, core_bar)
        };

        let pb = Arc::new(created_bar);
        self.progress_list
            .insert(index_to_insert, (pb.clone(), true));
        if group {
            surrounding_children.push(BarTree::Group(name, pb.clone(), vec![], anticipated_total));
        } else {
            surrounding_children.push(BarTree::Leaf(name, pb.clone(), LeafStatus::Started));
        }

        let inserted_index = surrounding_children.len() - 1;

        if progress {
            pb.set_style(
                indicatif::ProgressStyle::default_bar()
                    .template("{spinner:.green} {prefix} {wide_msg} {bar} ({elapsed} elapsed)")
                    .unwrap(),
            );
        } else {
            pb.set_style(
                indicatif::ProgressStyle::default_bar()
                    .template("{spinner:.green} {prefix} {wide_msg} ({elapsed} elapsed)")
                    .unwrap(),
            );
        }
        pb.enable_steady_tick(Duration::from_millis(100));

        self.tree.refresh_prefix(&[]);
        (inserted_index, pb)
    }

    pub fn end_task(&mut self, path: Vec<usize>) {
        let parent = self.tree.find_node_mut(&path[0..path.len() - 1]);
        match parent {
            BarTree::Root(children) | BarTree::Group(_, _, children, _) => {
                let removed = children[*path.last().unwrap()].get_pb().unwrap().clone();
                children[*path.last().unwrap()] = BarTree::Finished;
                self.multi_progress.remove(&removed);
                self.progress_list
                    .retain(|(pb, _)| !Arc::ptr_eq(pb, &removed));

                let non_finished_count = children
                    .iter()
                    .filter(|child| child.status() != LeafStatus::Finished)
                    .count();
                if let BarTree::Group(_, pb, _, _) = parent {
                    if non_finished_count == 1 {
                        self.multi_progress.remove(pb.as_ref());
                        self.progress_list
                            .iter_mut()
                            .find(|(pb2, _)| Arc::ptr_eq(pb2, pb))
                            .unwrap()
                            .1 = false;
                    } else if non_finished_count == 0 {
                        let self_idx = self
                            .progress_list
                            .iter()
                            .position(|(pb2, _)| Arc::ptr_eq(pb2, pb))
                            .unwrap();

                        let last_visible_before = self.progress_list[..self_idx]
                            .iter()
                            .rposition(|(_, visible)| *visible);

                        if let Some(last_visible_before) = last_visible_before {
                            self.multi_progress.insert_after(
                                &self.progress_list[last_visible_before].0,
                                pb.as_ref().clone(),
                            );
                        } else {
                            self.multi_progress.insert(0, pb.as_ref().clone());
                        }

                        self.progress_list[self_idx].1 = true;
                    }
                }
            }

            _ => panic!(),
        };

        self.tree.refresh_prefix(&[]);

        self.current_count -= 1;
        if self.current_count == 0 {
            self.multi_progress.clear().unwrap();
        }
    }
}

impl ProgressTracker {
    pub fn println(msg: impl AsRef<str>) {
        let progress_bar = PROGRESS_TRACKER
            .get_or_init(|| Mutex::new(ProgressTracker::new()))
            .lock()
            .unwrap();

        if progress_bar.current_count == 0
            || progress_bar.multi_progress.println(msg.as_ref()).is_err()
        {
            println!("{}", msg.as_ref());
        }
    }

    pub fn with_group<'a, T, F: Future<Output = T>>(
        name: impl Into<String>,
        anticipated_total: Option<usize>,
        f: impl FnOnce() -> F + 'a,
    ) -> impl Future<Output = T> + 'a {
        let mut group = CURRENT_GROUP
            .try_with(|cur| cur.clone())
            .unwrap_or_default();

        let (group_i, _) = {
            let mut progress_bar = PROGRESS_TRACKER
                .get_or_init(|| Mutex::new(ProgressTracker::new()))
                .lock()
                .unwrap();
            progress_bar.start_task(group.clone(), name.into(), true, anticipated_total, false)
        };

        group.push(group_i);

        CURRENT_GROUP.scope(group.clone(), async {
            let out = f().await;
            let mut progress_bar = PROGRESS_TRACKER
                .get_or_init(|| Mutex::new(ProgressTracker::new()))
                .lock()
                .unwrap();
            progress_bar.end_task(group);
            out
        })
    }

    pub fn leaf<T, F: Future<Output = T>>(
        name: impl Into<String>,
        f: F,
    ) -> impl Future<Output = T> {
        let mut group = CURRENT_GROUP
            .try_with(|cur| cur.clone())
            .unwrap_or_default();

        let (leaf_i, _) = {
            let mut progress_bar = PROGRESS_TRACKER
                .get_or_init(|| Mutex::new(ProgressTracker::new()))
                .lock()
                .unwrap();
            progress_bar.start_task(group.clone(), name.into(), false, None, false)
        };

        group.push(leaf_i);

        async move {
            let out = f.await;
            let mut progress_bar = PROGRESS_TRACKER
                .get_or_init(|| Mutex::new(ProgressTracker::new()))
                .lock()
                .unwrap();
            progress_bar.end_task(group);
            out
        }
    }

    pub fn rich_leaf<'a, T, F: Future<Output = T>>(
        name: impl Into<String>,
        f: impl FnOnce(Box<dyn Fn(String) + Send + Sync>) -> F + 'a,
    ) -> impl Future<Output = T> + 'a {
        let mut group = CURRENT_GROUP
            .try_with(|cur| cur.clone())
            .unwrap_or_default();

        let (leaf_i, bar) = {
            let mut progress_bar = PROGRESS_TRACKER
                .get_or_init(|| Mutex::new(ProgressTracker::new()))
                .lock()
                .unwrap();
            progress_bar.start_task(group.clone(), name.into(), false, None, false)
        };

        group.push(leaf_i);

        async move {
            let my_bar = bar.clone();
            let out = f(Box::new(move |msg| {
                my_bar.set_message(msg);
            }))
            .await;
            let mut progress_bar = PROGRESS_TRACKER
                .get_or_init(|| Mutex::new(ProgressTracker::new()))
                .lock()
                .unwrap();
            progress_bar.end_task(group);
            out
        }
    }

    pub fn progress_leaf<'a, T, F: Future<Output = T>>(
        name: impl Into<String>,
        f: impl FnOnce(Box<dyn Fn(u64) + Send + Sync>, Box<dyn Fn(String) + Send + Sync>) -> F + 'a,
    ) -> impl Future<Output = T> + 'a {
        let mut group = CURRENT_GROUP
            .try_with(|cur| cur.clone())
            .unwrap_or_default();

        let (leaf_i, bar) = {
            let mut progress_bar = PROGRESS_TRACKER
                .get_or_init(|| Mutex::new(ProgressTracker::new()))
                .lock()
                .unwrap();
            progress_bar.start_task(group.clone(), name.into(), false, None, true)
        };

        group.push(leaf_i);

        async move {
            let my_bar = bar.clone();
            let my_bar_2 = bar.clone();
            let out = f(
                Box::new(move |progress| {
                    my_bar.set_position(progress);
                }),
                Box::new(move |msg| {
                    my_bar_2.set_message(msg);
                }),
            )
            .await;
            let mut progress_bar = PROGRESS_TRACKER
                .get_or_init(|| Mutex::new(ProgressTracker::new()))
                .lock()
                .unwrap();
            progress_bar.end_task(group);
            out
        }
    }
}