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
mod message;
use crate::message::MessageQueue;
pub use crate::message::{Message, ColorString, ColorChar};
mod streak;
use crate::streak::Streak;

pub use pancurses::*;

extern crate rand;
use rand::Rng;

use std::sync::mpsc::{self, TryRecvError};
use std::sync::{Arc, Weak};
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

enum ThreadMsg {
    Kill,
    Start,
    Push(Message),
    PushUpdate(Message),
    Append(Vec<Message>),
    AppendUpdate(Vec<Message>),
    ColorPair(i16, i16, i16)
}

struct ForkedScene { // the version of Scene that lives in another thread
    columns:     Vec<Column>,  // holds all streaks in the scene
    height:      i32,          // height of the scene
    queue:       MessageQueue, // Messages yet to be printed
    max_padding: i32,
    rx:          Option<std::sync::mpsc::Receiver<ThreadMsg>>,
    started:     bool,
    speed:       Duration,
    last_updated:Instant,
    window:      Window,
}
impl ForkedScene {
    pub fn new(max_padding: i32, background: i16, is_closed: bool, rx: std::sync::mpsc::Receiver<ThreadMsg>, speed: Duration) -> Self {
	let window = initscr();
	
	curs_set(0);
	noecho();

	if has_colors() {
            start_color();
	}
	
	window.nodelay(true);
	init_pair(99, COLOR_BLACK, background);
	window.bkgd(COLOR_PAIR(99));

	let (height, width) = window.get_max_yx();
	
	if width == -1 {
	    panic!("Could not get screen size!");
	}
	let mut columns = Vec::with_capacity(width as usize);
	for _ in 0..width {
	    columns.push(Column::new());
	}
	Self{columns, height, queue: MessageQueue::new(width as usize, is_closed), max_padding, rx: Some(rx), started: false, speed, last_updated: Instant::now(), window: window}
    }
    pub fn kill(&self){
	endwin();
    }
    pub fn update(&mut self) -> bool {
	if self.rx.is_none() {
	    return false;
	}
	let rx = self.rx.as_ref().unwrap();
        match rx.try_recv() {
	    Err(TryRecvError::Disconnected) => {
                self.kill();
                return false;
	    }
	    Ok(thread_msg) => {
		match thread_msg {
		    ThreadMsg::Start => {
			if self.started == true {
			    panic!("Tried to start screen twice!");
			} else {
			    self.start();
			}
		    }
		    ThreadMsg::Push(message) => {
			self.queue.push(message);
		    }
		    ThreadMsg::PushUpdate(message) => {
			self.queue.push_update(message);
		    }
		    ThreadMsg::Append(messages) => {
			self.queue.append(messages.into());
		    }
		    ThreadMsg::AppendUpdate(messages) => {
			self.queue.append_update(messages.into());
		    }
		    ThreadMsg::ColorPair(pair, c1, c2) => {
			init_pair(pair, c1, c2);
		    }
		    ThreadMsg::Kill => {
			self.kill();
			return false; // make sure main exits
		    }
		}
	    }
	    Err(TryRecvError::Empty) => {}
	}
	if self.started && self.last_updated.elapsed() >= self.speed {
	    self.last_updated = Instant::now();
	    self.advance();
	}
	true
    }
    fn start(&mut self) {
	self.window.refresh();
	self.last_updated = Instant::now();
	self.started = true;
    }
    pub fn advance(&mut self){ // move all streaks, clean up dead ones, try to spawn new ones
	let mut rng = rand::thread_rng();
	let untouched = self.columns.iter().fold(0, |sum, column| sum + if column.touched  {0} else {1}); // counting untouched to make it progressively more likely to spawn a streak
	for (i, column) in self.columns.iter_mut().enumerate() {
	    for streak in &mut column.streaks { // advance all
		streak.derender(&self.window);
		streak.advance();
	    }
	    let height = self.height; // always fighting with the borrow checker
	    column.streaks.retain(|streak| !streak.finished(height)); // clean up dead streaks

	    // now, try to spawn new streaks
	    if column.streaks.len()==0 || column.streaks.iter().all(|streak| streak.top_space() > 5) { // check if there's need to
		if (!column.touched && rng.gen_range(0, untouched) == 0) || column.touched { // if we started recently, thin things out to look better
		// add new streak, consuming from queue
		column.add_streak(Streak::new_with_queue(&mut self.queue, i as i32, rng.gen_range(self.height/10, self.height*2), self.height, self.max_padding));
		    
		}
	    }

	    
	    for streak in &mut column.streaks { // advance all
		streak.render(&self.window);
	    }
	}
	self.window.refresh();
    }
    pub fn resize(&mut self) {
	// first, update the term
	let height = self.window.get_max_y();
	let width  = self.window.get_max_x();
	if width == -1 {
	    panic!("Could not get screen size!");
	}
	self.height = height;
	resize_term(height, width);
	self.window.erase();
	self.window.refresh();
	// Then, update columns
	let drained = self.queue.drain();
	self.queue.append(drained);
	self.columns = Vec::with_capacity(width as usize);
	for _ in 0..width {
	    self.columns.push(Column::new());
	}
    }
}

// Scene struct
// Holds all data for the scene, including:
//   Streaks (light things up and hold messages)
//   Dimensions
//   MessageQueue (messages yet to be printed)
// Handles updating, can render

pub struct Scene {
    tx:              Option<std::sync::mpsc::Sender<ThreadMsg>>, // used to communicate with other threads
    join_handle:     Option<JoinHandle<()>>, // needed for rejoining
    thread_control:  Option<Weak<AtomicBool>>, // needed for seeing if the thread is still alive
}

impl Scene {
    pub fn new(max_padding: i32, background: i16, is_closed: bool, speed: Duration) -> Self {
	let (tx, rx) = mpsc::channel();

	let working = Arc::new(AtomicBool::new(true));
	let control = Arc::downgrade(&working);

	let join_handle = thread::spawn(move || {
	    
	    let mut background = ForkedScene::new(max_padding, background, is_closed, rx, speed);
	    while (*working).load(Ordering::Relaxed) {
		if !background.update() {
		    break;
		}
		match background.window.getch() {
		    Some(Input::Character(c)) => { if c == 'q' {
			background.kill();
			break;
		    } },
		    Some(Input::KeyDC) => break,
		    Some(Input::KeyResize) => background.resize(),
		    Some(_) => { panic!("I don't know what to do with this!"); },
		    None => ()
		}
	    }});
	
	Self{tx: Some(tx), join_handle: Some(join_handle), thread_control: Some(control)}
    }
    pub fn push(&mut self, message: Message){
	if !self.alive() {
	    return;
	}
	let _ = self.tx.as_ref().unwrap().send(ThreadMsg::Push(message));
    }
    pub fn push_update(&mut self, message: Message){
	if !self.alive() {
	    return;
	}
	let _ = self.tx.as_ref().unwrap().send(ThreadMsg::PushUpdate(message));
    }
    pub fn append(&mut self, messages: Vec<Message>){
	if !self.alive() {
	    return;
	}
	let _ = self.tx.as_ref().unwrap().send(ThreadMsg::Append(messages));
    }
    pub fn append_update(&mut self, messages: Vec<Message>){
	if !self.alive() {
	    return;
	}
	let _ = self.tx.as_ref().unwrap().send(ThreadMsg::AppendUpdate(messages));
    }
    pub fn start(&mut self){ // start and fork to background
	let _ = self.tx.as_ref().unwrap().send(ThreadMsg::Start);
    }
    pub fn init_pair(&self, pair: i16, c1: i16, c2: i16){
	let _ = self.tx.as_ref().unwrap().send(ThreadMsg::ColorPair(pair.into(), c1, c2));	
    }
    pub fn alive(&self) -> bool { // ping the background thread to see if it's alive
	self.thread_control.is_some() && self.thread_control.as_ref().unwrap().upgrade().is_some()
    }
    pub fn kill(&mut self){
	if !self.alive() {
	    return;
	}
	let _ = self.tx.as_ref().unwrap().send(ThreadMsg::Kill);
	let _ = self.join_handle.take().unwrap().join(); // give curses time to clean up
	self.join_handle = None;
	self.tx = None;
    }
    pub fn join(&self) {
	while self.alive() {} // wait till screen is dead
    }
}

// Column struct
struct Column {
    streaks: Vec<Streak>,
    touched: bool,          // have we ever put a streak into this column?
}

impl Column {
    fn new() -> Self {
	Self{streaks: Vec::new(), touched: false}
    }
    fn add_streak(&mut self, streak: Streak){
	self.streaks.push(streak);
	self.touched = true;
    }
}

#[cfg(test)]
mod tests;