diff --git a/src/main.rs b/src/main.rs index 8c475ee..b1db43d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,14 +5,14 @@ mod editor; fn main() { let lambda = editor::Editor::new(); - let _term = terminal::Terminal::new(); + let mut term = terminal::Terminal::new().unwrap(); loop { - print!("{esc}[2J{esc}[1;1H", esc = 27 as char); for line in lambda.buffer.data { terminal::Terminal::write(format!("{line}")); + mut term.cursor.move_to(0, 1); }; - std::thread::sleep(Duration::from_millis(3000)); + std::thread::sleep(Duration::from_secs(3)); break; }; - terminal::Terminal::exit() + terminal::Terminal::exit(); } diff --git a/src/terminal.rs b/src/terminal.rs index a4a4f9b..81e5045 100644 --- a/src/terminal.rs +++ b/src/terminal.rs @@ -1,28 +1,65 @@ use crossterm::terminal; use crossterm::{execute, ErrorKind}; use crossterm::style::Print; +use crossterm::cursor::{CursorShape, MoveTo}; use std::io::{stdout, Write}; -#[derive(Debug)] pub struct Size { pub width: usize, pub height: usize, } -#[derive(Debug)] +pub struct Coords { + pub x: usize, + pub y: usize, +} + +impl Coords { + pub fn from(x: usize, y: usize) -> Self { + Self { + x: 0, + y: 0, + } + } +} + +pub struct Cursor { + pub position: Coords, + pub shape: CursorShape, +} + +impl Cursor { + pub fn new() -> Result { + let cursor = Self { + position: Coords::from(0, 0), + shape: CursorShape::Block, + }; + Cursor::move_to(&mut cursor, 0, 0); + Ok(cursor) + } + + pub fn move_to(&mut self, x: u16, y: u16) { + self.position = Coords::from(x as usize, y as usize); + execute!(stdout(), MoveTo(x, y)).unwrap() + } +} + pub struct Terminal { pub size: Size, + pub cursor: Cursor, } impl Terminal { pub fn new() -> Result { let size = terminal::size()?; + Terminal::clear(); Terminal::enter(); Ok(Self { size: Size { width: size.0 as usize, height: size.1 as usize, }, + cursor: Cursor::new().unwrap(), }) } @@ -39,6 +76,12 @@ impl Terminal { } pub fn write(text: String) { + // Writes a line to a current cursor position execute!(stdout(), Print(text)).unwrap(); } + + pub fn clear() { + // Clears the terminal screen + execute!(stdout(), terminal::Clear(terminal::ClearType::All)).unwrap(); + } }