hecto/src/editor.rs
2021-03-05 16:36:39 -05:00

78 lines
1.9 KiB
Rust

use crate::Terminal;
use termion::event::Key;
const VERSION: &str = env!("CARGO_PKG_VERSION");
pub struct Editor {
should_quit: bool,
terminal: Terminal,
}
impl Editor {
pub fn run(&mut self) {
loop {
if let Err(error) = self.refresh_screen() {
die(error);
}
if self.should_quit {
break;
}
if let Err(error) = self.process_keypress() {
die(error);
}
}
}
pub fn default() -> Self {
Self {
should_quit: false,
terminal: Terminal::default().expect("Failed to initialize terminal"),
}
}
fn refresh_screen(&self) -> Result<(), std::io::Error> {
Terminal::cursor_hide();
Terminal::cursor_position(0, 0);
if self.should_quit {
Terminal::clear_screen();
println!("Goodbye.\r");
} else {
self.draw_rows();
Terminal::cursor_position(0, 0);
}
Terminal::cursor_show();
Terminal::flush()
}
fn process_keypress(&mut self) -> Result<(), std::io::Error> {
let pressed_key = Terminal::read_key()?;
match pressed_key {
Key::Ctrl('q') => self.should_quit = true,
_ => (),
}
Ok(())
}
fn draw_rows(&self) {
let height = self.terminal.size().height;
for row in 0..height - 1 {
Terminal::clear_current_line();
if row == height / 3 {
let welcome_message = format!("Hecto editor -- version {}", VERSION);
let width = std::cmp::min(self.terminal.size() as usize, welcome_message.len());
println!("{}\r", &welcome_message[..width]);
} else {
println!("~\r");
}
}
}
}
fn die(e: std::io::Error) {
Terminal::clear_screen();
panic!(e);
}