tinsel 1.0.1

Clean terminal output with a little sparkle: live step lists, spinners, tables, trees, prompts and full-screen apps.
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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
//! One-line live output for a single task: `spin` around a closure, or a standalone `Progress`.

use std::fmt::Display;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::{Arc, Mutex, Once, Weak};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

use crate::display::{self, lock};
use crate::live::one_row;
use crate::output::{self, Val};
use crate::style::palette::{MUTED, RED, ROSE, SOFT, TEXT};
use crate::style::{Rgb, mix, paint};
use crate::widgets::{BarStyle, Spinner, shimmer};
use crate::{format, term, text};

/// Redraws one line in place from a background thread until finished.
struct Ticker {
    line: Arc<Mutex<LineState>>,
    stop: Arc<AtomicBool>,
    /// Frames a second; 0 for the global rate.
    fps: Arc<AtomicU32>,
    thread: Option<JoinHandle<()>>,
    prev_interrupt: Option<usize>,
}

/// What the drawing thread and everyone else agree on, under one lock so a frame is never
/// drawn halfway through something else.
#[derive(Default)]
struct LineState {
    /// Questions open over the line: nothing is drawn while any is.
    paused: u32,
    /// Lines logged while paused, printed above it once it carries on.
    logs: Vec<String>,
    /// A panic took over the screen: stop drawing.
    abandoned: bool,
}

/// The cursor hidden and no wrapping: an over-long line is cut at the edge instead of
/// breaking the redraw.
const TAKE_OVER: &str = "\x1b[?25l\x1b[?7l";
const GIVE_BACK: &str = "\x1b[?7h\x1b[?25h";

impl Ticker {
    fn start(frame: impl Fn(f64) -> String + Send + 'static) -> Ticker {
        let prev_interrupt = term::guard_interrupt();
        output::write(TAKE_OVER);
        let line = Arc::new(Mutex::new(LineState::default()));
        let stop = Arc::new(AtomicBool::new(false));
        let fps = Arc::new(AtomicU32::new(0));
        let (state, flag, rate) = (line.clone(), stop.clone(), fps.clone());
        let thread = thread::spawn(move || {
            let t0 = Instant::now();
            while !flag.load(Ordering::Relaxed) {
                {
                    let s = lock(&state);
                    if s.paused == 0 && !s.abandoned {
                        // kept to one row: a line break in the label would scroll a line a frame
                        let line = frame(t0.elapsed().as_secs_f64());
                        output::write(&format!("\r{}\x1b[K", one_row(&line)));
                    }
                }
                thread::sleep(crate::fps::frame(rate.load(Ordering::Relaxed)));
            }
        });
        display::add(Arc::downgrade(&line) as Weak<dyn display::Shown>);
        Ticker {
            line,
            stop,
            fps,
            thread: Some(thread),
            prev_interrupt,
        }
    }

    fn finish(&mut self, last: &str) {
        let Some(thread) = self.thread.take() else {
            return;
        };
        self.stop.store(true, Ordering::Relaxed);
        let _ = thread.join();
        display::remove(Arc::as_ptr(&self.line));
        let mut s = lock(&self.line);
        if !s.abandoned {
            let mut out: String = s.logs.drain(..).map(|l| format!("\r{l}\x1b[K\n")).collect();
            out += &format!("\r{}\x1b[K\n{GIVE_BACK}", one_row(last));
            output::write(&out);
        }
        drop(s);
        term::restore_interrupt(self.prev_interrupt.take());
    }
}

impl Drop for Ticker {
    fn drop(&mut self) {
        self.finish("");
    }
}

impl display::Shown for Mutex<LineState> {
    /// Clear the line away, for the question to go where it was.
    fn pause(&self) {
        let mut s = lock(self);
        if s.paused == 0 && !s.abandoned {
            output::write(&format!("\r\x1b[K{GIVE_BACK}"));
        }
        s.paused += 1;
    }

    fn resume(&self) {
        let mut s = lock(self);
        s.paused -= 1;
        if s.paused == 0 && !s.abandoned {
            let logs: String = s.logs.drain(..).map(|l| format!("{l}\n")).collect();
            output::write(&format!("{logs}{TAKE_OVER}"));
        }
    }

    fn log(&self, lines: &[&str], patient: bool) -> bool {
        let Some(mut s) = display::lock_if(self, patient) else {
            return false;
        };
        if s.paused > 0 || s.abandoned {
            s.logs.extend(lines.iter().map(|l| l.to_string()));
            return true;
        }
        // wrapping is back on for the lines, which may be long; the next frame goes below them
        let text: String = lines.iter().map(|l| format!("\r\x1b[K{l}\n")).collect();
        output::write(&format!("\x1b[?7h{text}\x1b[?7l"));
        true
    }

    fn abandon(&self) {
        if let Some(mut s) = display::lock_patiently(self) {
            s.abandoned = true;
        }
        output::write(&format!("\n{GIVE_BACK}"));
    }
}

/// `  โ—  label` with the time at the right edge, in the same columns as a [`crate::Live`] step:
/// the mark sits in the middle of the spinner's column, so the label stays put.
fn finished_line(mark: &str, color: Rgb, label: &str, label_color: Rgb, time_color: Rgb, took: Duration) -> String {
    let gutter = Spinner::default().width();
    let (before, after) = ((gutter - 1) / 2, gutter - 1 - (gutter - 1) / 2);
    let left = format!(
        "  {}{}{}  {}",
        " ".repeat(before),
        paint(color, mark),
        " ".repeat(after),
        paint(label_color, label)
    );
    let took = format::duration(took);
    let pad = term::content_width().saturating_sub(text::width(&left) + took.chars().count() + 2);
    format!("{left}{}{}", " ".repeat(pad.max(2)), paint(time_color, &took))
}

fn done_line(label: &str, took: Duration) -> String {
    finished_line("โ—", ROSE, label, TEXT, MUTED, took)
}

/// Run `f` with a spinner beside `label`, then leave a `โ—  label` line with the time it took
/// on the right, lined up with [`Live`](crate::Live) steps.
pub fn spin<T>(label: &str, f: impl FnOnce() -> T) -> T {
    match try_spin(label, || Ok::<T, std::convert::Infallible>(f())) {
        Ok(v) => v,
        Err(never) => match never {},
    }
}

/// Like [`spin`], but an `Err` ends on `โœ•` with the error under it.
///
/// # Errors
///
/// Whatever `f` fails with, once the spinner has ended on its โœ• line.
pub fn try_spin<T, E: Display>(label: &str, f: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
    let spinning = Spinning::start(label);
    let result = f();
    spinning.end(result.as_ref().err().map(ToString::to_string));
    result
}

/// One task under way for [`try_spin`]: a spinner on a terminal, nothing until it ends elsewhere.
struct Spinning<'a> {
    label: &'a str,
    start: Instant,
    ticker: Option<Ticker>,
}

impl<'a> Spinning<'a> {
    fn start(label: &'a str) -> Spinning<'a> {
        let drawn = !output::json() && !output::quiet() && crate::display::animated();
        let ticker = drawn.then(|| {
            let owned = label.to_string();
            Ticker::start(move |t| format!("  {}  {}", Spinner::default().frame(t), shimmer(&owned, t)))
        });
        Spinning {
            label,
            start: Instant::now(),
            ticker,
        }
    }

    /// Say how it went: done, or the error it failed with.
    fn end(self, error: Option<String>) {
        let (label, took) = (self.label, self.start.elapsed());
        if output::json() {
            let mut fields = vec![
                ("label", Val::Str(label)),
                ("outcome", Val::Str(if error.is_none() { "ok" } else { "fail" })),
                ("secs", Val::Num(took.as_secs_f64())),
            ];
            if let Some(e) = &error {
                fields.push(("error", Val::Str(e)));
            }
            return output::emit("task", &fields);
        }
        let Some(mut ticker) = self.ticker else {
            let took = format::duration(took);
            match error {
                Some(e) => crate::output::err_line(&format!("  [FAIL] {label} ({took}) - {e}")),
                None if !output::quiet() => output::line(&format!("  [ok] {label} ({took})")),
                None => {}
            }
            return;
        };
        match error {
            None => ticker.finish(&done_line(label, took)),
            Some(e) => {
                ticker.finish(&finished_line("โœ•", RED, label, RED, RED, took));
                let indent = " ".repeat(2 + Spinner::default().width() + 2);
                output::line(&format!("{indent}{}", paint(mix(RED, SOFT, 0.3), &e)));
            }
        }
    }
}

struct Counts {
    done: u64,
    /// `None` when there's no telling how much work there is.
    total: Option<u64>,
    bytes: bool,
    bar: BarStyle,
}

/// A single progress line with rate and time left, for work that isn't part of a [`crate::Live`] list.
///
/// ```no_run
/// let p = tinsel::Progress::new("Downloading", 34_200_000).bytes();
/// p.inc(1_000_000);
/// p.finish();
/// ```
///
/// When the amount of work isn't known up front, use [`Progress::unknown`] (a count and a
/// rate, no bar), or grow the total as you find more with [`add_total`](Progress::add_total).
/// To track a loop, see [`ProgressIterator`]. Dropping a `Progress` finishes it.
#[must_use = "a progress line finishes as soon as it's dropped"]
pub struct Progress {
    counts: Arc<Mutex<Counts>>,
    label: String,
    start: Instant,
    /// Whether it's drawn and redrawn, rather than reported once at the end.
    drawn: bool,
    /// Set once drawing has begun, at the first update.
    shown: Once,
    ticker: Mutex<Option<Ticker>>,
    fps: u32,
    finished: bool,
}

impl std::fmt::Debug for Progress {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let c = lock(&self.counts);
        f.debug_struct("Progress")
            .field("label", &self.label)
            .field("done", &c.done)
            .field("total", &c.total)
            .finish_non_exhaustive()
    }
}

impl Progress {
    /// A progress line for `total` units of work. It's drawn from the first update
    /// ([`inc`](Progress::inc), [`set`](Progress::set) or a change of total), so everything
    /// chosen with [`bytes`](Progress::bytes), [`bar`](Progress::bar) and [`fps`](Progress::fps)
    /// holds from its first frame; `set(0)` shows it before any work is done.
    pub fn new(label: impl Into<String>, total: u64) -> Self {
        Progress::start(label.into(), Some(total))
    }

    /// Start a progress line for an unknown amount of work: it counts and shows a rate, but
    /// has no bar or time left until [`set_total`](Progress::set_total) is called.
    pub fn unknown(label: impl Into<String>) -> Self {
        Progress::start(label.into(), None)
    }

    fn start(label: String, total: Option<u64>) -> Self {
        let counts = Arc::new(Mutex::new(Counts {
            done: 0,
            total,
            bytes: false,
            bar: BarStyle::default(),
        }));
        Progress {
            counts,
            label,
            start: Instant::now(),
            drawn: output::output() == output::Output::Pretty && crate::display::animated(),
            shown: Once::new(),
            ticker: Mutex::new(None),
            fps: 0,
            finished: false,
        }
    }

    /// Start drawing, once, if it's drawn at all.
    fn show(&self) {
        if !self.drawn {
            return;
        }
        self.shown.call_once(|| {
            let (counts, label, start) = (self.counts.clone(), self.label.clone(), self.start);
            let ticker = Ticker::start(move |t| progress_line(&label, &lock(&counts), start.elapsed(), t));
            ticker.fps.store(self.fps, Ordering::Relaxed);
            *lock(&self.ticker) = Some(ticker);
        });
    }

    /// Draw this many frames a second, rather than [`fps`](crate::fps) for every display.
    pub fn fps(mut self, fps: u32) -> Self {
        self.fps = fps.clamp(1, 240);
        if let Some(ticker) = lock(&self.ticker).as_ref() {
            ticker.fps.store(self.fps, Ordering::Relaxed);
        }
        self
    }

    /// Show amounts as bytes (`12 MB / 34 MB ยท 4.1 MB/s`) rather than plain counts.
    pub fn bytes(self) -> Self {
        lock(&self.counts).bytes = true;
        self
    }

    /// Choose how the bar is drawn (default: [`BarStyle::Line`]).
    ///
    /// ```no_run
    /// use tinsel::{BarStyle, Progress};
    ///
    /// let p = Progress::new("Encoding", 1_800).bar(BarStyle::Waveform);
    /// ```
    pub fn bar(self, bar: BarStyle) -> Self {
        lock(&self.counts).bar = bar;
        self
    }

    /// Record `n` more units done.
    pub fn inc(&self, n: u64) {
        {
            let mut c = lock(&self.counts);
            c.done += n;
            if let Some(total) = c.total {
                c.done = c.done.min(total);
            }
        }
        self.show();
    }

    /// Set how many units are done in total.
    pub fn set(&self, n: u64) {
        {
            let mut c = lock(&self.counts);
            c.done = c.total.map_or(n, |total| n.min(total));
        }
        self.show();
    }

    /// Say how much work there is after all, or that there's a different amount than first thought.
    pub fn set_total(&self, total: u64) {
        {
            let mut c = lock(&self.counts);
            c.total = Some(total);
            c.done = c.done.min(total);
        }
        self.show();
    }

    /// Add to the total, for work that's discovered as it goes (pages of results, nested
    /// folders). On an unknown total, this makes it known.
    pub fn add_total(&self, n: u64) {
        {
            let mut c = lock(&self.counts);
            c.total = Some(c.total.unwrap_or(0) + n);
        }
        self.show();
    }

    /// Stop drawing and leave a `โ—  label` line, with the time it took on the right.
    pub fn finish(mut self) {
        self.end(Ended::Done);
    }

    fn end(&mut self, ended: Ended) {
        if std::mem::replace(&mut self.finished, true) {
            return;
        }
        let took = self.start.elapsed();
        // finished without an update still ends on its line
        self.show();
        let label = one_row(&self.label);
        if let Some(t) = lock(&self.ticker).as_mut() {
            return t.finish(&match ended {
                Ended::Done => done_line(&label, took),
                Ended::Stopped => finished_line("โŠ˜", SOFT, &label, SOFT, MUTED, took),
                Ended::Panicked => finished_line("โœ•", RED, &label, RED, RED, took),
            });
        }
        if output::json() {
            let c = lock(&self.counts);
            let mut fields = vec![
                ("label", Val::Str(&self.label)),
                ("done", Val::Num(c.done as f64)),
                ("secs", Val::Num(took.as_secs_f64())),
            ];
            if ended != Ended::Done {
                fields.push(("outcome", Val::Str(ended.name())));
            }
            if let Some(total) = c.total {
                fields.push(("total", Val::Num(total as f64)));
            }
            output::emit("progress", &fields);
        } else if ended == Ended::Panicked {
            output::err_line(&format!("  [FAIL] {label} ({})", format::duration(took)));
        } else if !output::quiet() {
            output::line(&format!("  [{}] {label} ({})", ended.name(), format::duration(took)));
        }
    }
}

/// How a progress line ended.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Ended {
    /// Finished, or dropped with all its work done.
    Done,
    /// Dropped with work left, by an early return or a `break`.
    Stopped,
    /// Dropped while a panic unwinds.
    Panicked,
}

impl Ended {
    fn name(self) -> &'static str {
        match self {
            Ended::Done => "ok",
            Ended::Stopped => "stopped",
            Ended::Panicked => "fail",
        }
    }
}

impl Drop for Progress {
    fn drop(&mut self) {
        // dropped short of its total (an early return), or by a panic, it doesn't claim success
        let short = {
            let c = lock(&self.counts);
            c.total.is_some_and(|total| c.done < total)
        };
        let ended = if thread::panicking() {
            Ended::Panicked
        } else if short {
            Ended::Stopped
        } else {
            Ended::Done
        };
        self.end(ended);
    }
}

/// `.progress("label")` on any iterator: a [`Progress`] line that counts items as they go by
/// and finishes when the iterator runs out. Iterators that know their length get a bar.
///
/// ```no_run
/// use tinsel::ProgressIterator;
///
/// # fn index(_: &str) {}
/// let files = vec!["a.rs", "b.rs", "c.rs"];
/// for file in files.iter().progress("Indexing") {
///     index(file);
/// }
/// ```
pub trait ProgressIterator: Iterator + Sized {
    /// Wrap the iterator in a progress line labelled `label`.
    fn progress(self, label: impl Into<String>) -> WithProgress<Self>;
}

impl<I: Iterator> ProgressIterator for I {
    fn progress(self, label: impl Into<String>) -> WithProgress<Self> {
        let total = match self.size_hint() {
            (lo, Some(hi)) if lo == hi => Some(lo as u64),
            _ => None,
        };
        WithProgress {
            inner: self,
            bar: Some(Progress::start(label.into(), total)),
        }
    }
}

/// An iterator with a progress line: see [`ProgressIterator`].
#[must_use = "iterators do nothing until they're used, and the progress line finishes when dropped"]
pub struct WithProgress<I> {
    inner: I,
    bar: Option<Progress>,
}

impl<I: std::fmt::Debug> std::fmt::Debug for WithProgress<I> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WithProgress")
            .field("inner", &self.inner)
            .field("progress", &self.bar)
            .finish()
    }
}

impl<I> WithProgress<I> {
    /// Choose how the bar is drawn: `iter.progress("Encoding").bar(BarStyle::Waveform)`.
    pub fn bar(self, bar: BarStyle) -> Self {
        if let Some(p) = &self.bar {
            lock(&p.counts).bar = bar;
        }
        self
    }

    /// The progress line behind this iterator, to change its total as more turns up.
    pub fn as_progress(&self) -> Option<&Progress> {
        self.bar.as_ref()
    }
}

impl<I: Iterator> Iterator for WithProgress<I> {
    type Item = I::Item;

    fn next(&mut self) -> Option<I::Item> {
        // shown from the first look for an item, at 0, rather than once one has been through
        if let Some(bar) = &self.bar {
            bar.show();
        }
        let item = self.inner.next();
        match &item {
            Some(_) => {
                if let Some(bar) = &self.bar {
                    bar.inc(1);
                }
            }
            // finished as soon as it runs out, not whenever the loop's iterator is dropped, and
            // done, even if the iterator gave fewer items than it said it would
            None => {
                if let Some(bar) = self.bar.take() {
                    bar.finish();
                }
            }
        }
        item
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

fn progress_line(label: &str, c: &Counts, elapsed: Duration, t: f64) -> String {
    let amount = |n: u64| {
        if c.bytes { format::bytes(n) } else { format::count(n) }
    };
    let rate = c.done as f64 / elapsed.as_secs_f64().max(0.001);
    let spinner = Spinner::default().frame(t);
    let Some(total) = c.total else {
        let mut stats = amount(c.done);
        if c.done > 0 {
            stats += &format!("  ยท  {}/s", amount(rate as u64));
        }
        return format!("  {spinner}  {}  {}", shimmer(label, t), paint(SOFT, &stats));
    };
    let f = if total == 0 { 1.0 } else { c.done as f32 / total as f32 };
    let mut stats = format!("{:>3.0}%  {} / {}", f * 100.0, amount(c.done), amount(total));
    if c.done > 0 && rate > 0.0 {
        let left = Duration::from_secs_f64(total.saturating_sub(c.done) as f64 / rate);
        stats += &format!("  ยท  {}/s  ยท  {} left", amount(rate as u64), format::duration(left));
    }
    format!(
        "  {spinner}  {}  {}  {}",
        paint(TEXT, label),
        c.bar.draw(f, 24, t),
        paint(SOFT, &stats)
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::output::{Output, capture, with_output, with_terminal};

    fn plain() {
        crate::set_color_mode(crate::ColorMode::None);
    }

    #[test]
    fn spinning_on_a_terminal_ends_on_a_mark() {
        plain();
        let out = capture(|| {
            with_terminal(true, || {
                let slept = spin("s-ok", || {
                    std::thread::sleep(Duration::from_millis(30));
                    "slept"
                });
                assert_eq!(slept, "slept");
                let failed: Result<(), &str> = try_spin("s-fail", || Err("it broke"));
                assert!(failed.is_err());
            })
        });
        assert!(out.contains("\x1b[?25l") && out.contains("โ—   s-ok"), "{out:?}");
        assert!(out.contains("โœ•   s-fail") && out.contains("it broke\n"), "{out:?}");
    }

    #[test]
    fn spinning_elsewhere_prints_a_line_an_event_or_nothing() {
        plain();
        let out = capture(|| {
            with_terminal(false, || {
                spin("p-ok", || ());
                let _ = try_spin("p-fail", || Err::<(), _>("nope"));
            })
        });
        assert!(
            out.contains("  [ok] p-ok (") && out.contains("  [FAIL] p-fail (") && out.contains("nope"),
            "{out:?}"
        );
        let quiet = capture(|| with_output(Output::Quiet, || spin("q-ok", || ())));
        assert!(!quiet.contains("q-ok"));
        let json = capture(|| {
            with_output(Output::Json, || {
                spin("j-ok", || ());
                let _ = try_spin("j-fail", || Err::<(), _>("nope"));
            })
        });
        assert!(json.contains(r#""label":"j-ok","outcome":"ok""#), "{json}");
        assert!(
            json.contains(r#""label":"j-fail","outcome":"fail""#) && json.contains(r#""error":"nope""#),
            "{json}"
        );
    }

    #[test]
    fn progress_draws_on_a_terminal_and_finishes_on_a_mark() {
        plain();
        let out = capture(|| {
            with_terminal(true, || {
                let p = Progress::new("p-draw", 100).fps(240).bytes().bar(BarStyle::Waveform);
                p.inc(30);
                p.set(50);
                std::thread::sleep(Duration::from_millis(30));
                p.finish();
            })
        });
        assert!(out.contains("p-draw") && out.contains("โ—   p-draw"), "{out:?}");
    }

    #[test]
    fn progress_dropped_short_of_its_total_doesnt_claim_success() {
        plain();
        let out = capture(|| {
            with_terminal(true, || {
                let p = Progress::new("p-short", 10).fps(240);
                p.inc(3);
                std::thread::sleep(Duration::from_millis(20));
                drop(p);
                let mut it = [1, 2, 3].iter().progress("p-break");
                it.next();
                drop(it);
                let p = Progress::new("p-whole", 10).fps(240);
                p.inc(10);
                drop(p);
                let p = Progress::new("p-told", 10).fps(240);
                p.inc(1);
                p.finish();
            })
        });
        assert!(out.contains("โŠ˜   p-short") && !out.contains("โ—   p-short"), "{out:?}");
        assert!(out.contains("โŠ˜   p-break"), "{out:?}");
        assert!(out.contains("โ—   p-whole") && out.contains("โ—   p-told"), "{out:?}");

        let plain_out = capture(|| {
            with_terminal(false, || {
                let p = Progress::new("p-plain", 4);
                p.inc(1);
                drop(p);
                let _ = std::panic::catch_unwind(|| {
                    let p = Progress::new("p-panic", 4);
                    p.inc(4);
                    panic!("mid-loop");
                });
            })
        });
        assert!(plain_out.contains("[stopped] p-plain ("), "{plain_out:?}");
        assert!(plain_out.contains("[FAIL] p-panic ("), "{plain_out:?}");
        let json = capture(|| with_output(Output::Json, || drop(Progress::new("pj-short", 4))));
        assert!(json.contains(r#""outcome":"stopped","total":4}"#), "{json}");
    }

    #[test]
    fn a_label_with_a_line_break_stays_on_one_row() {
        plain();
        let out = capture(|| {
            with_terminal(true, || {
                let p = Progress::new("two\nrows", 1).fps(240);
                p.set(0);
                std::thread::sleep(Duration::from_millis(20));
                p.finish();
                spin("s-two\nrows", || std::thread::sleep(Duration::from_millis(20)));
            })
        });
        assert!(!out.contains("two\n") && out.contains("two rows"), "{out:?}");
        assert!(out.contains("s-two rows"), "{out:?}");
    }

    #[test]
    fn progress_draws_from_its_first_update_so_its_settings_hold_from_the_start() {
        plain();
        let out = capture(|| {
            with_terminal(true, || {
                let p = Progress::new("p-lazy", 100).fps(240).bytes();
                std::thread::sleep(Duration::from_millis(30));
                assert!(lock(&p.ticker).is_none(), "nothing drawn before an update");
                p.inc(1_000);
                assert!(lock(&p.ticker).is_some());
                std::thread::sleep(Duration::from_millis(30));
                p.finish();
            })
        });
        // every frame in bytes, the first included
        let frames = out.split('\r').filter(|f| f.contains("p-lazy") && f.contains('%'));
        assert!(frames.clone().count() > 0, "{out:?}");
        assert!(frames.clone().all(|f| f.contains("100 B / 100 B")), "{out:?}");
    }

    #[test]
    fn progress_counts_within_its_total() {
        let p = with_terminal(false, || Progress::new("count", 10).fps(30));
        p.inc(25);
        assert_eq!(lock(&p.counts).done, 10);
        p.set(40);
        assert_eq!(lock(&p.counts).done, 10);
        p.set_total(5);
        assert_eq!(lock(&p.counts).done, 5);
        p.add_total(5);
        assert_eq!(lock(&p.counts).total, Some(10));
        capture(|| p.finish());

        let u = with_terminal(false, || Progress::unknown("unknown"));
        u.inc(7);
        u.set(9);
        assert_eq!(lock(&u.counts).done, 9);
        u.add_total(3);
        assert_eq!(lock(&u.counts).total, Some(3));
        assert!(capture(|| drop(u)).contains("[ok] unknown"));
    }

    #[test]
    fn progress_off_a_terminal_reports_once() {
        let json = capture(|| {
            with_output(Output::Json, || {
                let p = Progress::new("pj", 4);
                p.inc(2);
                p.finish();
                Progress::unknown("pu").finish();
            })
        });
        assert!(
            json.contains(r#"{"event":"progress","label":"pj","done":2,"#) && json.contains(r#""total":4}"#),
            "{json}"
        );
        assert!(json.contains(r#""label":"pu","done":0,"#), "{json}");
        let quiet = capture(|| with_output(Output::Quiet, || Progress::new("pq", 1).finish()));
        assert!(!quiet.contains("pq"));
    }

    #[test]
    fn iterators_count_as_they_go() {
        let out = capture(|| {
            with_terminal(false, || {
                let mut it = [1, 2, 3].iter().progress("known").bar(BarStyle::Line);
                assert_eq!(it.size_hint(), (3, Some(3)));
                assert_eq!(lock(&it.as_progress().unwrap().counts).total, Some(3));
                assert_eq!(it.by_ref().count(), 3);
                assert!(it.as_progress().is_none());
                assert!(it.bar(BarStyle::Line).next().is_none());
                let unknown = (0..10).filter(|n| n % 2 == 0).progress("filtered");
                assert_eq!(lock(&unknown.as_progress().unwrap().counts).total, None);
                assert_eq!(unknown.sum::<i32>(), 20);
            })
        });
        assert!(out.contains("[ok] known") && out.contains("[ok] filtered"), "{out:?}");
    }

    #[test]
    fn the_progress_line_shows_rate_and_time_left() {
        plain();
        let counts = |done, total| Counts {
            done,
            total,
            bytes: false,
            bar: BarStyle::Line,
        };
        let line = progress_line("work", &counts(50, Some(100)), Duration::from_secs(5), 0.0);
        assert!(
            line.contains(" 50%  50 / 100") && line.contains("10/s") && line.contains("5.0s left"),
            "{line}"
        );
        let line = progress_line("work", &counts(0, Some(0)), Duration::from_secs(1), 0.0);
        assert!(line.contains("100%  0 / 0") && !line.contains("/s"), "{line}");
        let line = progress_line("work", &counts(0, None), Duration::from_secs(1), 0.0);
        assert!(line.ends_with("  0"), "{line}");
        let bytes = Counts {
            bytes: true,
            ..counts(2048, None)
        };
        let line = progress_line("work", &bytes, Duration::from_secs(1), 0.0);
        assert!(line.contains("2.0 KB  ยท  2.0 KB/s"), "{line}");
    }

    #[test]
    fn an_iterator_that_carries_on_after_running_out_isnt_counted_twice() {
        let mut calls = 0;
        let resumes = std::iter::from_fn(move || {
            calls += 1;
            (calls != 2).then_some(calls)
        });
        let out = capture(|| {
            with_terminal(false, || {
                let mut it = resumes.progress("resumes");
                assert_eq!((it.next(), it.next(), it.next()), (Some(1), None, Some(3)));
            })
        });
        assert_eq!(out.matches("[ok] resumes").count(), 1, "{out:?}");
    }
}