Move logic to editor module.

This commit is contained in:
Timothy Warren 2021-01-28 16:47:40 -05:00
parent a7fe16b007
commit 221512f80c
2 changed files with 52 additions and 25 deletions

48
src/editor.rs Normal file
View File

@ -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<Key, std::io::Error> {
loop {
if let Some(key) = io::stdin().lock().keys().next() {
return key;
}
}
}
fn die(e: std::io::Error) {
panic!(e);
}

View File

@ -1,29 +1,8 @@
use std::io::{self, stdout}; #![warn(clippy::all, clippy::pedantic)]
use termion::event::Key; mod editor;
use termion::input::TermRead;
use termion::raw::IntoRawMode;
fn die(e: std::io::Error) { use editor::Editor;
panic!(e);
}
fn main() { fn main() {
let _stdout = stdout().into_raw_mode().unwrap(); Editor::default().run();
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),
}
}
} }