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
use std::{
cell::RefCell,
rc::Rc,
thread::{self, JoinHandle}
};
use crossbeam_channel::{bounded, Receiver};
use cursive_core::{
Printer, Vec2,
event::{Event, EventResult},
view::View,
theme::ColorStyle
};
type WorkerThread<T> = Rc<RefCell<Option<JoinHandle<T>>>>;
#[derive(Clone)]
pub struct LoadingAnimation<T: Send + Sync + 'static> {
worker: WorkerThread<T>,
recv: Receiver<bool>,
completed: bool,
message: String,
width: usize,
anim_x: usize,
reversed: bool
}
impl<T: Send + Sync> LoadingAnimation<T> {
pub fn new<U>(message: &str, task: U) -> LoadingAnimation<T>
where U: FnOnce() -> T + Send + Sync + 'static
{
let (sender, recv) = bounded::<bool>(0);
let worker = Rc::new(RefCell::from(
Some(
thread::spawn(move || {
let out = task();
sender.send(true).expect("Did the other side disconnect?");
out
})
)
));
LoadingAnimation {
worker,
recv,
completed: false,
width: message.chars().count(),
message: message.to_string(),
anim_x: 0,
reversed: false
}
}
pub fn is_done(&mut self) -> bool {
if let Ok(b) = self.recv.try_recv() {
self.completed = b;
return b;
}
else if self.completed {
return true;
}
if let None = *self.worker.borrow() {
self.completed = true;
true
}
else {
false
}
}
pub fn finish(&mut self) -> Option<T> {
if self.worker.borrow().is_none() {
None
}
else {
let worker = self.worker.borrow_mut().take().unwrap();
Some(worker.join().unwrap())
}
}
}
impl<T: Send + Sync> View for LoadingAnimation<T> {
fn draw(&self, printer: &Printer) {
let style = ColorStyle::secondary();
printer.print((0, 0), &" ".repeat(self.width));
printer.with_color(style, |printer| {
printer.print((0, 0), &format!("{}███", " ".repeat(self.anim_x)));
});
printer.print((0, 1), &self.message);
}
fn on_event(&mut self, event: Event) -> EventResult {
if let Event::Refresh = event {
if self.width == 0 {
return EventResult::Ignored;
}
else 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;
}
}
}
EventResult::Ignored
}
fn required_size(&mut self, _: Vec2) -> Vec2 {
Vec2::new(self.message.chars().count(), 2)
}
}