2021-03-05 16:36:39 -05:00
|
|
|
use crate::Terminal;
|
2021-01-28 16:47:40 -05:00
|
|
|
use termion::event::Key;
|
2021-03-05 16:36:39 -05:00
|
|
|
|
|
|
|
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
2021-01-28 16:47:40 -05:00
|
|
|
|
|
|
|
pub struct Editor {
|
|
|
|
should_quit: bool,
|
2021-03-05 16:36:39 -05:00
|
|
|
terminal: Terminal,
|
2021-01-28 16:47:40 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Editor {
|
|
|
|
pub fn run(&mut self) {
|
|
|
|
loop {
|
2021-03-05 16:36:39 -05:00
|
|
|
if let Err(error) = self.refresh_screen() {
|
2021-01-28 16:47:40 -05:00
|
|
|
die(error);
|
|
|
|
}
|
|
|
|
if self.should_quit {
|
|
|
|
break;
|
|
|
|
}
|
2021-03-05 16:36:39 -05:00
|
|
|
if let Err(error) = self.process_keypress() {
|
|
|
|
die(error);
|
|
|
|
}
|
2021-01-28 16:47:40 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn default() -> Self {
|
2021-03-05 16:36:39 -05:00
|
|
|
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()
|
2021-01-28 16:47:40 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
fn process_keypress(&mut self) -> Result<(), std::io::Error> {
|
2021-03-05 16:36:39 -05:00
|
|
|
let pressed_key = Terminal::read_key()?;
|
2021-01-28 16:47:40 -05:00
|
|
|
match pressed_key {
|
|
|
|
Key::Ctrl('q') => self.should_quit = true,
|
|
|
|
_ => (),
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2021-03-05 16:36:39 -05:00
|
|
|
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);
|
|
|
|
|
2021-03-05 16:38:35 -05:00
|
|
|
let width = std::cmp::min(self.terminal.size().width as usize, welcome_message.len());
|
2021-03-05 16:36:39 -05:00
|
|
|
println!("{}\r", &welcome_message[..width]);
|
|
|
|
} else {
|
|
|
|
println!("~\r");
|
|
|
|
}
|
2021-01-28 16:47:40 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn die(e: std::io::Error) {
|
2021-03-05 16:36:39 -05:00
|
|
|
Terminal::clear_screen();
|
2021-01-28 16:47:40 -05:00
|
|
|
panic!(e);
|
|
|
|
}
|