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
use crate::SpannedStrExt;
use std::{
    sync::{Arc, RwLock},
    thread::{self, JoinHandle}
};
use crossbeam_channel::{bounded, Receiver, TryRecvError};
use cursive_core::{
    Printer, Vec2,
    view::View,
    theme::{ColorStyle, PaletteColor},
    utils::markup::StyledString
};

type WorkerThread<T> = Arc<RwLock<Option<JoinHandle<T>>>>;

/// Loading animation view that runs a task in a background thread and shows a loading animation and message while it completes and allows for retrieval of a return value.
/// It is recommended to use `load_resource()` instead of this directly since it has a simpler interface
/// 
/// # Example
/// ```
/// let mut root = cursive::default();
/// let anim = LoadingAnimation::new("Loading Dummy Resource...", || {
///     thread::sleep(Duration::from_secs(10));
/// });
/// 
/// root.add_layer(Dialog::around(anim.with_name("loader")).title("Loading..."));
/// root.set_fps(30);
///
/// root.set_global_callback(Event::Refresh, |root| {
///     let mut loader = root.find_name::<LoadingAnimation<()>>("loader").unwrap();
///     if loader.is_done() {
///         loader.finish().unwrap_or(());
///         root.quit()
///     }
/// });
/// root.run();
/// ```
#[derive(Clone)]
pub struct LoadingAnimation<T: Send + Sync + 'static> {
    worker: WorkerThread<T>,
    recv: Receiver<()>,
    message: StyledString,
    width: usize,
    anim_x: usize,
    reversed: bool
}

impl<T: Send + Sync> LoadingAnimation<T> {
    /// Create a new `LoadingAnimation` with the specified closure or function pointer as the task
    pub fn new<U, M: Into<StyledString>>(message: M, task: U) -> LoadingAnimation<T>
        where U: FnOnce() -> T + Send + Sync + 'static
    {
        let (sender, recv) = bounded(0);
        let worker = Arc::new(RwLock::new(
            Some(
                thread::spawn(move || {
                    let out = task();
                    sender.send(()).unwrap();
                    out
                })
            )
        ));
        let message = message.into();

        LoadingAnimation {
            worker,
            recv,
            width: message.char_len(),
            message,
            anim_x: 0,
            reversed: false
        }
    }

    /// Has the background task finished executing?
    pub fn is_done(&self) -> bool {
        match self.recv.try_recv() {
            Ok(()) => true,
            Err(e) => e == TryRecvError::Disconnected
        }
    }

    /// Join with the task's thread, block until it is finished, and return the resulting value
    /// 
    /// It is best to run this when `LoadingAnimation::is_done()` is true
    /// 
    /// This will return `None` if called more than once
    /// 
    /// # Panics
    /// This method will panic if the underlying task panicked while executing
    #[track_caller]
    pub fn finish(&mut self) -> Option<T> {
        let worker = self.worker.write().unwrap().take()?;
        Some(worker.join().unwrap())
    }
}

impl<T: Send + Sync> View for LoadingAnimation<T> {
    fn draw(&self, printer: &Printer) {
        let style = ColorStyle::new(
            PaletteColor::Highlight,
            PaletteColor::Background,
        );
        printer.with_color(style, |printer| {
            printer.print((self.anim_x, 0), "███");
        });
        printer.print_styled((0, 1), self.message.as_spanned_str());
    }

    fn layout(&mut self, _: Vec2) {
        if self.width > 0 {
            if self.reversed {
                if self.anim_x == 0 {
                    self.reversed = false;
                }
                else {
                    self.anim_x -= 1;
                }
            }
            else if self.anim_x < self.width - 3 {
                self.anim_x += 1;
            }
            else {
                self.reversed = true;
            }
        }
    }

    fn required_size(&mut self, _: Vec2) -> Vec2 { Vec2::new(self.message.char_len(), 2) }
}