From 9f94611a42d41cf94cdccb00b5d2eec0d5d02970 Mon Sep 17 00:00:00 2001 From: Joris Date: Sun, 14 Nov 2021 23:25:55 +0100 Subject: Add initial working version --- src/util/event.rs | 75 +++++++++++++++++++++++++++++++++++++++++++++++ src/util/mod.rs | 3 ++ src/util/serialization.rs | 7 +++++ 3 files changed, 85 insertions(+) create mode 100644 src/util/event.rs create mode 100644 src/util/mod.rs create mode 100644 src/util/serialization.rs (limited to 'src/util') diff --git a/src/util/event.rs b/src/util/event.rs new file mode 100644 index 0000000..33ee9ec --- /dev/null +++ b/src/util/event.rs @@ -0,0 +1,75 @@ +use std::io; +use std::sync::mpsc; +use std::thread; +use std::time::Duration; + +use termion::event::Key; +use termion::input::TermRead; + +pub enum Event { + Input(I), + Tick, +} + +/// A small event handler that wrap termion input and tick events. Each event +/// type is handled in its own thread and returned to a common `Receiver` +pub struct Events { + rx: mpsc::Receiver>, + input_handle: thread::JoinHandle<()>, + tick_handle: thread::JoinHandle<()>, +} + +#[derive(Debug, Clone, Copy)] +pub struct Config { + pub tick_rate: Duration, +} + +impl Default for Config { + fn default() -> Config { + Config { + tick_rate: Duration::from_millis(250), + } + } +} + +impl Events { + pub fn new() -> Events { + Events::with_config(Config::default()) + } + + pub fn with_config(config: Config) -> Events { + let (tx, rx) = mpsc::channel(); + let input_handle = { + let tx = tx.clone(); + thread::spawn(move || { + let stdin = io::stdin(); + for evt in stdin.keys() { + if let Ok(key) = evt { + if let Err(err) = tx.send(Event::Input(key)) { + eprintln!("{}", err); + return; + } + } + } + }) + }; + let tick_handle = { + thread::spawn(move || loop { + if let Err(err) = tx.send(Event::Tick) { + eprintln!("{}", err); + break; + } + thread::sleep(config.tick_rate); + }) + }; + Events { + rx, + input_handle, + tick_handle, + } + } + + pub fn next(&self) -> Result, mpsc::RecvError> { + self.rx.recv() + } +} diff --git a/src/util/mod.rs b/src/util/mod.rs new file mode 100644 index 0000000..c5504af --- /dev/null +++ b/src/util/mod.rs @@ -0,0 +1,3 @@ +#[allow(dead_code)] +pub mod event; +pub mod serialization; diff --git a/src/util/serialization.rs b/src/util/serialization.rs new file mode 100644 index 0000000..fcb3062 --- /dev/null +++ b/src/util/serialization.rs @@ -0,0 +1,7 @@ +pub fn line_to_words(line: &String) -> Vec { + line.split("|").map(|w| w.trim().to_string()).filter(|w| !w.is_empty()).collect() +} + +pub fn words_to_line(words: &Vec) -> String { + words.join(" | ") +} -- cgit v1.2.3