@ -1,9 +1,5 @@
use std ::io ;
use std ::io ;
use std ::sync ::mpsc ;
use std ::sync ::mpsc ;
use std ::sync ::{
atomic ::{ AtomicBool , Ordering } ,
Arc ,
} ;
use std ::thread ;
use std ::thread ;
use std ::time ::Duration ;
use std ::time ::Duration ;
@ -20,20 +16,17 @@ pub enum Event<I> {
pub struct Events {
pub struct Events {
rx : mpsc ::Receiver < Event < Key > > ,
rx : mpsc ::Receiver < Event < Key > > ,
input_handle : thread ::JoinHandle < ( ) > ,
input_handle : thread ::JoinHandle < ( ) > ,
ignore_exit_key : Arc < AtomicBool > ,
tick_handle : thread ::JoinHandle < ( ) > ,
tick_handle : thread ::JoinHandle < ( ) > ,
}
}
#[ derive(Debug, Clone, Copy) ]
#[ derive(Debug, Clone, Copy) ]
pub struct Config {
pub struct Config {
pub exit_key : Key ,
pub tick_rate : Duration ,
pub tick_rate : Duration ,
}
}
impl Default for Config {
impl Default for Config {
fn default ( ) -> Config {
fn default ( ) -> Config {
Config {
Config {
exit_key : Key ::Char ( 'q' ) ,
tick_rate : Duration ::from_millis ( 250 ) ,
tick_rate : Duration ::from_millis ( 250 ) ,
}
}
}
}
@ -46,10 +39,8 @@ impl Events {
pub fn with_config ( config : Config ) -> Events {
pub fn with_config ( config : Config ) -> Events {
let ( tx , rx ) = mpsc ::channel ( ) ;
let ( tx , rx ) = mpsc ::channel ( ) ;
let ignore_exit_key = Arc ::new ( AtomicBool ::new ( false ) ) ;
let input_handle = {
let input_handle = {
let tx = tx . clone ( ) ;
let tx = tx . clone ( ) ;
let ignore_exit_key = ignore_exit_key . clone ( ) ;
thread ::spawn ( move | | {
thread ::spawn ( move | | {
let stdin = io ::stdin ( ) ;
let stdin = io ::stdin ( ) ;
for evt in stdin . keys ( ) {
for evt in stdin . keys ( ) {
@ -58,16 +49,14 @@ impl Events {
eprintln! ( "{}" , err ) ;
eprintln! ( "{}" , err ) ;
return ;
return ;
}
}
if ! ignore_exit_key . load ( Ordering ::Relaxed ) & & key = = config . exit_key {
return ;
}
}
}
}
}
} )
} )
} ;
} ;
let tick_handle = {
let tick_handle = {
thread ::spawn ( move | | loop {
thread ::spawn ( move | | loop {
if tx . send ( Event ::Tick ) . is_err ( ) {
if let Err ( err ) = tx . send ( Event ::Tick ) {
eprintln! ( "{}" , err ) ;
break ;
break ;
}
}
thread ::sleep ( config . tick_rate ) ;
thread ::sleep ( config . tick_rate ) ;
@ -75,7 +64,6 @@ impl Events {
} ;
} ;
Events {
Events {
rx ,
rx ,
ignore_exit_key ,
input_handle ,
input_handle ,
tick_handle ,
tick_handle ,
}
}
@ -84,12 +72,4 @@ impl Events {
pub fn next ( & self ) -> Result < Event < Key > , mpsc ::RecvError > {
pub fn next ( & self ) -> Result < Event < Key > , mpsc ::RecvError > {
self . rx . recv ( )
self . rx . recv ( )
}
}
pub fn disable_exit_key ( & mut self ) {
self . ignore_exit_key . store ( true , Ordering ::Relaxed ) ;
}
pub fn enable_exit_key ( & mut self ) {
self . ignore_exit_key . store ( false , Ordering ::Relaxed ) ;
}
}
}