From 62e3a3dba7fde994020d9d73c35912bb0405e3d4 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Mon, 8 Mar 2021 14:55:14 -0500 Subject: [PATCH] Finish chapter 4: Text viewer --- src/editor.rs | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/editor.rs b/src/editor.rs index 5176f3f..9559085 100644 --- a/src/editor.rs +++ b/src/editor.rs @@ -2,6 +2,8 @@ use crate::Document; use crate::Row; use crate::Terminal; use std::env; +use std::time::Duration; +use std::time::Instant; use termion::color; use termion::event::Key; @@ -15,12 +17,27 @@ pub struct Position { pub y: usize, } +struct StatusMessage { + text: String, + time: Instant, +} + +impl StatusMessage { + fn from(message: String) -> Self { + Self { + time: Instant::now(), + text: message, + } + } +} + pub struct Editor { should_quit: bool, terminal: Terminal, cursor_position: Position, offset: Position, document: Document, + status_message: StatusMessage, } impl Editor { @@ -40,9 +57,16 @@ impl Editor { pub fn default() -> Self { let args: Vec = env::args().collect(); + let mut initial_status = String::from("HELP: Ctrl-Q = quit"); let document = if args.len() > 1 { let file_name = &args[1]; - Document::open(&file_name).unwrap_or_default() + let doc = Document::open(&file_name); + if doc.is_ok() { + doc.unwrap() + } else { + initial_status = format!("ERR: Could not open file: {}", file_name); + Document::default() + } } else { Document::default() }; @@ -53,6 +77,7 @@ impl Editor { document, cursor_position: Position::default(), offset: Position::default(), + status_message: StatusMessage::from(initial_status), } } @@ -108,6 +133,12 @@ impl Editor { fn draw_message_bar(&self) { Terminal::clear_current_line(); + let message = &self.status_message; + if Instant::now() - message.time < Duration::new(5, 0) { + let mut text = message.text.clone(); + text.truncate(self.terminal.size().width as usize); + print!("{}", text); + } } fn process_keypress(&mut self) -> Result<(), std::io::Error> {