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
use std::sync::mpsc;
use std::{sync::mpsc::Sender, time::Duration};

#[cfg(test)]
use std::thread::JoinHandle;

use cursive_core::theme::Style;
use cursive_core::views::TextView;
use cursive_core::CbSink;
use cursive_core::{views::TextContent, Printer, Vec2, View};

use crate::{
    spinner::Spinner, Frames, ACCCEL_FACTOR, DEFAULT_FRAMES, DEFAULT_IDLING_FRAME, MAX_FPS, MIN_FPS,
};

pub(crate) enum ThreadControl {
    Go,
    Drop,
}

pub(crate) enum SpinnerControl {
    Frames(Frames),
    Duration(Duration),
    Stop,
}

/// Spinner view
#[allow(missing_debug_implementations)]
pub struct SpinnerView {
    spin_ups: usize,
    speeds: bool,
    text_view: TextView,
    tx_spinner: Sender<SpinnerControl>,
    tx_thread: Sender<ThreadControl>,

    #[cfg(test)]
    // Used in tests to prove that the spinner
    // thread terminates after dropping the view
    join_handle: Option<JoinHandle<()>>,
}

//todo? create a builder struct for SpinnerView
impl SpinnerView {
    /// New spinner view
    ///
    /// A CbSink is needed for new spinner.
    ///
    /// # Examples
    ///
    /// ```
    /// use cursive_spinner_view::SpinnerView;
    ///
    /// let siv = cursive::default();
    /// #[allow(unused)]
    /// let spinner = SpinnerView::new(siv.cb_sink().clone());
    /// ```
    pub fn new(cb_sink: CbSink) -> Self {
        let content = TextContent::new("");
        let text_view = TextView::new_with_content(content.clone()).no_wrap();

        let (tx_spinner, rx_spinner) = mpsc::channel();
        let (tx_thread, rx_thread) = mpsc::channel();

        let spinner = Spinner::new(
            DEFAULT_FRAMES,
            DEFAULT_IDLING_FRAME,
            cb_sink.clone(),
            content,
            rx_spinner,
            rx_thread,
        );

        let _join_handle = spinner.spin_loop();

        SpinnerView {
            spin_ups: 0,
            speeds: true, //todo? create kinda GearBox instead speeds
            text_view,
            tx_spinner,
            tx_thread,

            #[cfg(test)]
            join_handle: Some(_join_handle),
        }
    }

    /// Spin up the spinner
    ///
    /// You can do it as many times as you need.
    pub fn spin_up(&mut self) {
        if self.spin_ups == 0 {
            // Wake up spinner thread
            self.tx_thread.send(ThreadControl::Go).unwrap();
        }

        self.spin_ups = self.spin_ups.saturating_add(1);

        self.recalc_duration();
    }

    /// Spin down the spinner
    ///
    /// To stop the spinner the numbers of spin-downs
    /// have to be equal the numbers of spin-ups.
    pub fn spin_down(&mut self) {
        if self.spin_ups == 1 {
            self.tx_spinner.send(SpinnerControl::Stop).unwrap();
        }

        self.spin_ups = self.spin_ups.saturating_sub(1);

        self.recalc_duration();
    }

    /// Stop the spinner immediately
    pub fn stop(&mut self) {
        if self.spin_ups != 0 {
            self.tx_spinner.send(SpinnerControl::Stop).unwrap();
        }

        self.spin_ups = 0;
    }

    /// The number of spin-ups
    pub fn spin_ups(&self) -> usize {
        self.spin_ups
    }

    /// Is the spinner spinning
    pub fn is_spinning(&self) -> bool {
        self.spin_ups() != 0
    }

    /// Set spinner's frames
    pub fn frames(&mut self, frames: Frames) -> &mut Self {
        self.tx_spinner
            .send(SpinnerControl::Frames(frames))
            .unwrap();

        self
    }

    /// Set spinner's style
    pub fn style<S: Into<Style>>(&mut self, style: S) -> &mut Self {
        self.text_view.set_style(style);
        self
    }

    fn recalc_duration(&self) {
        self.tx_spinner
            .send(SpinnerControl::Duration(Duration::from_secs_f32(
                1.0 / Self::fps(self.spin_ups(), self.speeds) as f32,
            )))
            .unwrap();
    }

    fn fps(spin_ups: usize, speeds: bool) -> usize {
        if !speeds || spin_ups == 0 {
            return MIN_FPS;
        }

        let fps = MIN_FPS.saturating_add(ACCCEL_FACTOR.saturating_mul(spin_ups - 1));

        match fps {
            fps if fps < MIN_FPS as usize => MIN_FPS,
            fps if fps > MAX_FPS as usize => MAX_FPS,
            _ => fps,
        }
    }

    #[cfg(test)]
    #[must_use]
    fn join_handle(&mut self) -> JoinHandle<()> {
        self.join_handle.take().unwrap()
    }
}

impl Drop for SpinnerView {
    fn drop(&mut self) {
        let _ = self.tx_spinner.send(SpinnerControl::Stop);
        let _ = self.tx_thread.send(ThreadControl::Drop);
    }
}

impl View for SpinnerView {
    fn draw(&self, printer: &Printer) {
        self.text_view.draw(printer)
    }

    fn needs_relayout(&self) -> bool {
        self.text_view.needs_relayout()
    }

    fn required_size(&mut self, constraint: Vec2) -> Vec2 {
        self.text_view.required_size(constraint)
    }

    fn layout(&mut self, size: Vec2) {
        self.text_view.layout(size)
    }
}

#[cfg(test)]
mod tests {
    use std::thread;
    use std::time::Duration;

    use cursive;
    use ntest::timeout;

    use super::*;

    #[test]
    #[timeout(1000)]
    fn drop_running_thread() {
        let siv = cursive::default();
        let mut spinner = SpinnerView::new(siv.cb_sink().clone());

        spinner.spin_up();

        thread::sleep(Duration::from_millis(10));

        let handle = spinner.join_handle();

        drop(spinner);

        assert!(matches!(handle.join(), Ok(())));
    }

    #[test]
    #[timeout(1000)]
    fn drop_sleeping_thread() {
        let siv = cursive::default();

        let mut spinner = SpinnerView::new(siv.cb_sink().clone());

        thread::sleep(Duration::from_millis(10));

        let handle = spinner.join_handle();

        drop(spinner);

        assert!(matches!(handle.join(), Ok(())));
    }
}