inkling-loader 0.1.5

Reveal arbitrary ASCII art as a progress indicator by choosing the order its glyphs appear.
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
//! `Loader`: the ergonomic, thread-safe front door to Inkling.
//!
//! This is how most programs should use Inkling. Create a [`Loader`] with a total,
//! advance it from anywhere with [`inc`](Loader::inc) or [`set`](Loader::set), and
//! a background thread keeps a living reveal painted at ~30 fps until you
//! [`finish`](Loader::finish). It mirrors the idioms people already expect from a
//! progress bar:
//!
//! * **Drive it by hand** with `inc`/`set`, determinate or [`spinner`](Loader::spinner).
//! * **Wrap an iterator**: `for x in items.inkling() { .. }`.
//! * **Wrap a reader**: `loader.wrap_read(file)` advances by bytes read.
//!
//! The handle is cheap to clone (via [`handle`](Loader::handle)) and `Send + Sync`,
//! so worker threads can report progress while the render thread owns the terminal,
//! which keeps all drawing on one thread and free of races. When stdout is not a
//! TTY the loader does not animate; it prints the finished art once on `finish`, so
//! logs and CI still show the result.

use std::io::{self, IsTerminal, Read, Write};
use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed};
use std::sync::atomic::{AtomicU64, AtomicU8};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

use crossterm::{
    cursor::{Hide, MoveTo, MoveToColumn, MoveToNextLine, MoveToPreviousLine, Show},
    execute, queue,
    style::{Color, Print, ResetColor, SetForegroundColor},
    terminal::{self, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen},
};

use crate::art::Art;
use crate::ordering::{Directional, Ordering};
use crate::render::Style;

/// The built-in art used when you do not supply your own.
const DEFAULT_ART: &str = include_str!("../assets/dragon.txt");
const FPS: u64 = 30;

// Loader lifecycle, stored in `Shared::state`.
const RUNNING: u8 = 0;
const FINISH_KEEP: u8 = 1; // complete the art and leave it on screen
const FINISH_CLEAR: u8 = 2; // complete and erase the art

/// State shared between the public handles and the render thread.
struct Shared {
    pos: AtomicU64,
    total: AtomicU64, // 0 means indeterminate (spinner)
    state: AtomicU8,
    message: Mutex<String>,
    art: Art,
    ranks: crate::rank::RankMap,
    style: Style,
}

impl Shared {
    fn inc(&self, delta: u64) {
        self.pos.fetch_add(delta, Relaxed);
    }
    fn set(&self, pos: u64) {
        self.pos.store(pos, Relaxed);
    }
    fn set_message(&self, msg: String) {
        if let Ok(mut guard) = self.message.lock() {
            *guard = msg;
        }
    }
}

/// A living progress reveal.
///
/// Create one with [`Loader::new`], advance it, and [`finish`](Loader::finish).
/// Dropping the last handle finishes it for you, so the terminal is always
/// restored. Not `Clone`; for cross-thread updates take a [`Handle`].
pub struct Loader {
    shared: Arc<Shared>,
    joiner: Mutex<Option<JoinHandle<()>>>,
    tty: bool,
}

impl Loader {
    /// A determinate loader for `total` units of work, using the built-in dragon.
    pub fn new(total: u64) -> Self {
        Builder::new().total(total).start()
    }

    /// An indeterminate loader (a spinner) for work whose length you do not know.
    pub fn spinner() -> Self {
        Builder::new().start()
    }

    /// Configure a loader with custom art, ordering, style, or message.
    pub fn builder() -> Builder {
        Builder::new()
    }

    /// Advance the position by `delta`.
    pub fn inc(&self, delta: u64) {
        self.shared.inc(delta);
    }

    /// Set the absolute position.
    pub fn set(&self, pos: u64) {
        self.shared.set(pos);
    }

    /// Change the total amount of work.
    pub fn set_length(&self, total: u64) {
        self.shared.total.store(total, Relaxed);
    }

    /// Set a short caption shown beneath the art.
    pub fn set_message<S: Into<String>>(&self, msg: S) {
        self.shared.set_message(msg.into());
    }

    /// The current position.
    pub fn position(&self) -> u64 {
        self.shared.pos.load(Relaxed)
    }

    /// A cheap, clonable, `Send + Sync` handle for reporting progress from other
    /// threads. Handles can update but not finish the loader.
    pub fn handle(&self) -> Handle {
        Handle {
            shared: Arc::clone(&self.shared),
        }
    }

    /// Wrap a reader so every byte read advances the loader. Ideal for downloads:
    /// set the length to the content length, then read through the wrapper.
    pub fn wrap_read<R: Read>(&self, reader: R) -> ProgressReader<R> {
        ProgressReader {
            inner: reader,
            handle: self.handle(),
        }
    }

    /// Fill the art, leave it on screen, and restore the terminal.
    pub fn finish(&self) {
        self.finalize(FINISH_KEEP);
    }

    /// Finish and erase the art from the screen.
    pub fn finish_and_clear(&self) {
        self.finalize(FINISH_CLEAR);
    }

    fn finalize(&self, how: u8) {
        let won = self
            .shared
            .state
            .compare_exchange(RUNNING, how, AcqRel, Relaxed)
            .is_ok();
        if self.tty {
            if let Ok(mut guard) = self.joiner.lock() {
                if let Some(handle) = guard.take() {
                    let _ = handle.join();
                }
            }
        } else if won && how == FINISH_KEEP {
            // No animation off a TTY; leave the finished art for logs and CI.
            print!(
                "{}",
                crate::frame::to_string(&self.shared.art, &self.shared.ranks, 1.0)
            );
            let _ = io::stdout().flush();
        }
    }
}

impl Drop for Loader {
    fn drop(&mut self) {
        self.finalize(FINISH_KEEP);
    }
}

/// A cheap, clonable updater obtained from [`Loader::handle`]. Safe to send to and
/// share across threads.
#[derive(Clone)]
pub struct Handle {
    shared: Arc<Shared>,
}

impl Handle {
    /// Advance the position by `delta`.
    pub fn inc(&self, delta: u64) {
        self.shared.inc(delta);
    }
    /// Set the absolute position.
    pub fn set(&self, pos: u64) {
        self.shared.set(pos);
    }
    /// Set the caption.
    pub fn set_message<S: Into<String>>(&self, msg: S) {
        self.shared.set_message(msg.into());
    }
    /// The current position.
    pub fn position(&self) -> u64 {
        self.shared.pos.load(Relaxed)
    }
}

/// Builder for a customised [`Loader`].
pub struct Builder {
    total: u64,
    art: Option<Art>,
    ordering: Box<dyn Ordering>,
    style: Style,
    message: String,
}

impl Builder {
    fn new() -> Self {
        Builder {
            total: 0,
            art: None,
            ordering: Box::new(Directional::default()),
            style: Style::default(),
            message: String::new(),
        }
    }

    /// Units of work. Leave it `0` (the default) for an indeterminate spinner.
    pub fn total(mut self, total: u64) -> Self {
        self.total = total;
        self
    }

    /// The art to reveal. Defaults to the built-in dragon.
    pub fn art(mut self, art: Art) -> Self {
        self.art = Some(art);
        self
    }

    /// The ordering that decides the reveal path. Defaults to [`Directional`].
    pub fn ordering(mut self, ordering: impl Ordering + 'static) -> Self {
        self.ordering = Box::new(ordering);
        self
    }

    /// Colours and frontier glow.
    pub fn style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    /// A short caption shown beneath the art.
    pub fn message<S: Into<String>>(mut self, message: S) -> Self {
        self.message = message.into();
        self
    }

    /// Build the loader and start animating (on a TTY).
    pub fn start(self) -> Loader {
        let art = self.art.unwrap_or_else(|| Art::parse(DEFAULT_ART));
        let ranks = self.ordering.rank(&art);
        let shared = Arc::new(Shared {
            pos: AtomicU64::new(0),
            total: AtomicU64::new(self.total),
            state: AtomicU8::new(RUNNING),
            message: Mutex::new(self.message),
            art,
            ranks,
            style: self.style,
        });
        let tty = io::stdout().is_terminal();
        let joiner = if tty {
            let shared = Arc::clone(&shared);
            Mutex::new(Some(thread::spawn(move || run(shared))))
        } else {
            Mutex::new(None)
        };
        Loader {
            shared,
            joiner,
            tty,
        }
    }
}

// ---------------------------------------------------------------------------
// Iterator wrapping: `for x in items.inkling() { .. }`
// ---------------------------------------------------------------------------

/// Extension trait that wraps any iterator in a progress reveal.
pub trait ProgressIteratorExt: Iterator + Sized {
    /// Reveal a loader while iterating, inferring the total from `size_hint`.
    fn inkling(self) -> InklingIter<Self> {
        let total = self.size_hint().1.unwrap_or(0) as u64;
        let loader = if total > 0 {
            Loader::new(total)
        } else {
            Loader::spinner()
        };
        InklingIter {
            inner: self,
            loader: Some(loader),
        }
    }

    /// Reveal a specific, pre-configured loader while iterating.
    fn inkling_with(self, loader: Loader) -> InklingIter<Self> {
        InklingIter {
            inner: self,
            loader: Some(loader),
        }
    }
}

impl<I: Iterator> ProgressIteratorExt for I {}

/// Iterator adaptor returned by [`ProgressIteratorExt::inkling`].
pub struct InklingIter<I> {
    inner: I,
    loader: Option<Loader>,
}

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

    fn next(&mut self) -> Option<Self::Item> {
        let next = self.inner.next();
        match next {
            Some(_) => {
                if let Some(loader) = &self.loader {
                    loader.inc(1);
                }
            }
            None => {
                if let Some(loader) = self.loader.take() {
                    loader.finish();
                }
            }
        }
        next
    }

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

impl<I> Drop for InklingIter<I> {
    fn drop(&mut self) {
        if let Some(loader) = self.loader.take() {
            loader.finish();
        }
    }
}

// ---------------------------------------------------------------------------
// Reader wrapping: bytes read advance the loader.
// ---------------------------------------------------------------------------

/// A `Read` wrapper that advances a loader by the number of bytes read.
pub struct ProgressReader<R> {
    inner: R,
    handle: Handle,
}

impl<R: Read> Read for ProgressReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let n = self.inner.read(buf)?;
        self.handle.inc(n as u64);
        Ok(n)
    }
}

// ---------------------------------------------------------------------------
// The render thread: a reveal at ~30 fps in the alternate screen.
// ---------------------------------------------------------------------------

fn run(shared: Arc<Shared>) {
    let mut out = io::stdout();
    let (w, h) = (shared.art.width(), shared.art.height());
    let rows = terminal::size().map(|(_, r)| r).unwrap_or(0);
    // Animate inline while the picture and its caption fit the viewport, which keeps
    // the reveal in the flow of the terminal and lets the next output follow below it.
    // Only when the art is taller than the screen do we fall back to the alternate
    // screen, where it cannot scroll and duplicate itself.
    let fullscreen = rows < h + 2;

    let (ox, oy) = if fullscreen {
        let (cols, vr) = terminal::size().unwrap_or((w, h + 2));
        let _ = execute!(out, EnterAlternateScreen, Hide, Clear(ClearType::All));
        (
            cols.saturating_sub(crate::render::art_cols(&shared.art)) / 2,
            vr.saturating_sub(h + 1) / 2,
        )
    } else {
        let _ = execute!(out, Hide);
        (0, 0)
    };

    let frame = Duration::from_millis(1000 / FPS);
    let start = Instant::now();
    let mut displayed = 0.0f32;
    let mut first = true;

    loop {
        let finishing = shared.state.load(Acquire) != RUNNING;
        let total = shared.total.load(Relaxed);
        let pos = shared.pos.load(Relaxed);
        let t = start.elapsed().as_secs_f32();
        let target = if total == 0 {
            0.1 + 0.9 * (0.5 - 0.5 * (t * 1.5).cos()) // spinner: a breathing reveal
        } else {
            (pos as f32 / total as f32).clamp(0.0, 1.0)
        };
        displayed += (target - displayed) * 0.3; // glide toward the true value
        let progress = if finishing { 1.0 } else { displayed };

        let _ = if fullscreen {
            draw_frame(&mut out, &shared, ox, oy, progress, t)
        } else {
            draw_inline(&mut out, &shared, progress, t, first)
        };
        first = false;

        if finishing {
            let cleared = shared.state.load(Relaxed) == FINISH_CLEAR;
            if fullscreen {
                let _ = execute!(out, ResetColor, Show, LeaveAlternateScreen);
                if !cleared {
                    let _ = persist_final(&mut out, &shared);
                }
            } else if cleared {
                let _ = clear_inline(&mut out, h + 1);
                let _ = execute!(out, Show);
            } else {
                // Leave the finished art in place and park the cursor below it.
                let _ = queue!(out, Print("\r\n"));
                let _ = execute!(out, Show);
            }
            let _ = out.flush();
            break;
        }
        thread::sleep(frame);
    }
}

fn draw_frame(
    out: &mut io::Stdout,
    shared: &Shared,
    ox: u16,
    oy: u16,
    progress: f32,
    t: f32,
) -> io::Result<()> {
    let art = &shared.art;
    let (w, h) = (art.width(), art.height());
    let style = &shared.style;

    queue!(out, Print(crate::render::SYNC_BEGIN))?;
    for y in 0..h {
        queue!(out, MoveTo(ox, oy + y))?;
        let mut last: Option<(u8, u8, u8)> = None;
        for x in 0..w {
            match shared.ranks.rank_at(x, y) {
                Some(r) if r <= progress => {
                    if style.color {
                        let c = crate::render::cell_rgb(style, progress, r, x, y, t);
                        if last != Some(c) {
                            queue!(
                                out,
                                SetForegroundColor(Color::Rgb {
                                    r: c.0,
                                    g: c.1,
                                    b: c.2
                                })
                            )?;
                            last = Some(c);
                        }
                    }
                    queue!(out, Print(art.glyph(x, y)))?;
                }
                _ => {
                    if last.take().is_some() {
                        queue!(out, ResetColor)?;
                    }
                    queue!(out, Print(' '))?;
                }
            }
        }
        if last.is_some() {
            queue!(out, ResetColor)?;
        }
    }

    // Caption row beneath the art.
    queue!(out, MoveTo(ox, oy + h), Clear(ClearType::CurrentLine))?;
    let msg = shared
        .message
        .lock()
        .ok()
        .map(|m| m.clone())
        .unwrap_or_default();
    if !msg.is_empty() {
        let cols = terminal::size().map(|(c, _)| c).unwrap_or(80);
        let shown = crate::render::truncate_to_cols(&msg, cols.saturating_sub(1));
        if style.color {
            queue!(
                out,
                SetForegroundColor(Color::Rgb {
                    r: 120,
                    g: 134,
                    b: 168
                })
            )?;
        }
        queue!(out, Print(shown), ResetColor)?;
    }
    queue!(out, Print(crate::render::SYNC_END))?;
    out.flush()
}

// Inline reveal: draw the block in place and keep the cursor on its last line so the
// next frame can step back up to it. The next program output then flows in below.
fn draw_inline(
    out: &mut io::Stdout,
    shared: &Shared,
    progress: f32,
    t: f32,
    first: bool,
) -> io::Result<()> {
    let art = &shared.art;
    let (w, h) = (art.width(), art.height());
    let style = &shared.style;

    queue!(out, Print(crate::render::SYNC_BEGIN))?;
    if !first {
        queue!(out, MoveToPreviousLine(h))?;
    }
    for y in 0..h {
        queue!(out, MoveToColumn(0), Clear(ClearType::CurrentLine))?;
        let mut last: Option<(u8, u8, u8)> = None;
        for x in 0..w {
            match shared.ranks.rank_at(x, y) {
                Some(r) if r <= progress => {
                    if style.color {
                        let c = crate::render::cell_rgb(style, progress, r, x, y, t);
                        if last != Some(c) {
                            queue!(
                                out,
                                SetForegroundColor(Color::Rgb {
                                    r: c.0,
                                    g: c.1,
                                    b: c.2
                                })
                            )?;
                            last = Some(c);
                        }
                    }
                    queue!(out, Print(art.glyph(x, y)))?;
                }
                _ => {
                    if last.take().is_some() {
                        queue!(out, ResetColor)?;
                    }
                    queue!(out, Print(' '))?;
                }
            }
        }
        if last.is_some() {
            queue!(out, ResetColor)?;
        }
        queue!(out, MoveToNextLine(1))?;
    }

    // Caption line; leave the cursor here for the next frame to step back up to.
    queue!(out, MoveToColumn(0), Clear(ClearType::CurrentLine))?;
    let msg = shared
        .message
        .lock()
        .ok()
        .map(|m| m.clone())
        .unwrap_or_default();
    if !msg.is_empty() {
        let cols = terminal::size().map(|(c, _)| c).unwrap_or(80);
        let shown = crate::render::truncate_to_cols(&msg, cols.saturating_sub(1));
        if style.color {
            queue!(
                out,
                SetForegroundColor(Color::Rgb {
                    r: 120,
                    g: 134,
                    b: 168
                })
            )?;
        }
        queue!(out, Print(shown), ResetColor)?;
    }
    queue!(out, Print(crate::render::SYNC_END))?;
    out.flush()
}

// Erase an inline block (the cursor is on its last line) and park it at the top.
fn clear_inline(out: &mut io::Stdout, lines: u16) -> io::Result<()> {
    queue!(out, MoveToPreviousLine(lines - 1))?;
    for _ in 0..lines {
        queue!(
            out,
            MoveToColumn(0),
            Clear(ClearType::CurrentLine),
            MoveToNextLine(1)
        )?;
    }
    queue!(out, MoveToPreviousLine(lines))?;
    out.flush()
}

// Print the finished art, coloured and trimmed, into the normal buffer so it stays.
fn persist_final(out: &mut io::Stdout, shared: &Shared) -> io::Result<()> {
    let art = &shared.art;
    let (w, h) = (art.width(), art.height());
    let style = &shared.style;
    for y in 0..h {
        let mut last_ink = 0u16;
        let mut any = false;
        for x in 0..w {
            if art.is_ink(x, y) {
                last_ink = x;
                any = true;
            }
        }
        if any {
            let mut last: Option<(u8, u8, u8)> = None;
            for x in 0..=last_ink {
                if art.is_ink(x, y) {
                    if style.color {
                        let c = crate::render::cell_rgb(style, 1.0, 0.0, x, y, 0.0);
                        if last != Some(c) {
                            queue!(
                                out,
                                SetForegroundColor(Color::Rgb {
                                    r: c.0,
                                    g: c.1,
                                    b: c.2
                                })
                            )?;
                            last = Some(c);
                        }
                    }
                    queue!(out, Print(art.glyph(x, y)))?;
                } else {
                    if last.take().is_some() {
                        queue!(out, ResetColor)?;
                    }
                    queue!(out, Print(' '))?;
                }
            }
            if last.is_some() {
                queue!(out, ResetColor)?;
            }
        }
        queue!(out, Print("\r\n"))?;
    }
    out.flush()
}

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

    #[test]
    fn loader_and_handle_are_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<Loader>();
        assert_send_sync::<Handle>();
    }

    #[test]
    fn position_tracks_updates() {
        let loader = Loader::builder().total(10).message("x").start();
        loader.inc(3);
        loader.set(7);
        assert_eq!(loader.position(), 7);
        loader.finish_and_clear();
    }

    #[test]
    fn iterator_yields_every_item() {
        let loader = Loader::builder().total(5).art(Art::parse("##")).start();
        let collected: Vec<i32> = (0..5).inkling_with(loader).collect();
        assert_eq!(collected, vec![0, 1, 2, 3, 4]);
    }
}