From 221512f80cefcbb824e8146baaef11c55018d504 Mon Sep 17 00:00:00 2001 From: "Timothy J. Warren" Date: Thu, 28 Jan 2021 16:47:40 -0500 Subject: [PATCH] Move logic to editor module. --- src/editor.rs | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 29 ++++------------------------- 2 files changed, 52 insertions(+), 25 deletions(-) create mode 100644 src/editor.rs diff --git a/src/editor.rs b/src/editor.rs new file mode 100644 index 0000000..c0b9d8b --- /dev/null +++ b/src/editor.rs @@ -0,0 +1,48 @@ +use std::io::{self, stdout}; +use termion::event::Key; +use termion::input::TermRead; +use termion::raw::IntoRawMode; + +pub struct Editor { + should_quit: bool, +} + +impl Editor { + pub fn run(&mut self) { + let _stdout = stdout().into_raw_mode().unwrap(); + + loop { + if let Err(error) = self.process_keypress() { + die(error); + } + if self.should_quit { + break; + } + } + } + + pub fn default() -> Self { + Self { should_quit: false } + } + + fn process_keypress(&mut self) -> Result<(), std::io::Error> { + let pressed_key = read_key()?; + match pressed_key { + Key::Ctrl('q') => self.should_quit = true, + _ => (), + } + Ok(()) + } +} + +fn read_key() -> Result { + loop { + if let Some(key) = io::stdin().lock().keys().next() { + return key; + } + } +} + +fn die(e: std::io::Error) { + panic!(e); +} diff --git a/src/main.rs b/src/main.rs index 6fe2cb8..8a00098 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,29 +1,8 @@ -use std::io::{self, stdout}; -use termion::event::Key; -use termion::input::TermRead; -use termion::raw::IntoRawMode; +#![warn(clippy::all, clippy::pedantic)] +mod editor; -fn die(e: std::io::Error) { - panic!(e); -} +use editor::Editor; fn main() { - let _stdout = stdout().into_raw_mode().unwrap(); - - for key in io::stdin().keys() { - match key { - Ok(key) => match key { - Key::Char(c) => { - if c.is_control() { - println!("{:?}\r", c as u8); - } else { - println!("{:?} ({})\r", c as u8, c); - } - } - Key::Ctrl('q') => break, - _ => println!("{:?}\r", key), - } - Err(err) => die(err), - } - } + Editor::default().run(); }