Buffered screen drawing

This commit is contained in:
Jarkko Toivanen 2024-08-01 02:09:20 +03:00
parent 5fc444519d
commit 1528866d65
Signed by: jt
GPG key ID: 9151B109B73ECAD5

View file

@ -12,8 +12,9 @@ use std::{
#[derive(Default)] #[derive(Default)]
struct Nuudel { struct Nuudel {
quitting: bool, quitting: bool,
cursorx: i32, cursorx: u16,
cursory: i32, cursory: u16,
buffer: String,
} }
fn main() -> Result<()> { fn main() -> Result<()> {
@ -36,10 +37,9 @@ fn main() -> Result<()> {
impl Nuudel { impl Nuudel {
pub fn run(&mut self, stdout: &mut Stdout) -> Result<()> { pub fn run(&mut self, stdout: &mut Stdout) -> Result<()> {
print!("Press Q to quit");
while !self.quitting { while !self.quitting {
self.handle_events()?; self.handle_events()?;
stdout.flush()?; self.draw_terminal(stdout)?;
} }
Ok(()) Ok(())
} }
@ -51,6 +51,7 @@ impl Nuudel {
} }
fn restore_terminal() -> Result<()> { fn restore_terminal() -> Result<()> {
stdout().execute(cursor::Show)?;
stdout().execute(terminal::LeaveAlternateScreen)?; stdout().execute(terminal::LeaveAlternateScreen)?;
terminal::disable_raw_mode()?; terminal::disable_raw_mode()?;
Ok(()) Ok(())
@ -70,16 +71,24 @@ impl Nuudel {
print!(""); print!("");
}, },
KeyCode::Left => { KeyCode::Left => {
stdout().execute(cursor::MoveLeft(1))?; if self.cursorx > 0 {
self.cursorx -= 1;
self.cursorx = self.cursorx.clamp(0, terminal::size()?.0-1);
}
}, },
KeyCode::Right => { KeyCode::Right => {
stdout().execute(cursor::MoveRight(1))?; self.cursorx += 1;
self.cursorx = self.cursorx.clamp(0, terminal::size()?.0-1);
}, },
KeyCode::Up => { KeyCode::Up => {
stdout().execute(cursor::MoveUp(1))?; if self.cursory > 0 {
self.cursory -= 1;
}
self.cursory = self.cursory.clamp(0, terminal::size()?.1-1);
}, },
KeyCode::Down => { KeyCode::Down => {
stdout().execute(cursor::MoveDown(1))?; self.cursory += 1;
self.cursory = self.cursory.clamp(0, terminal::size()?.1-1);
}, },
_ => {} _ => {}
}, },
@ -88,4 +97,42 @@ impl Nuudel {
} }
Ok(()) Ok(())
} }
fn draw_terminal(&mut self, stdout: &mut Stdout) -> Result<()> {
//stdout.execute(terminal::BeginSynchronizedUpdate)?;
stdout.execute(cursor::Hide)?;
stdout.execute(cursor::MoveTo(0, 0))?;
let mut y = 0;
self.buffer = "\n".to_string();
let buffer_lines = self.buffer.lines().count() as u16;
while y < terminal::size()?.1 - buffer_lines {
self.buffer.push_str("~\n");
y += 1;
}
// Draw buffer one by one
y = 0;
let mut lines = self.buffer.lines();
while y < terminal::size()?.1-1 {
stdout.execute(terminal::Clear(terminal::ClearType::CurrentLine))?;
let line = lines.next();
if line.is_none() {
break;
}
write!(stdout, "{}", line.unwrap())?;
stdout.execute(cursor::MoveToNextLine(1))?;
y += 1;
}
print!("Press Q to quit");
//stdout.execute(terminal::EndSynchronizedUpdate)?;
stdout.execute(cursor::MoveTo(self.cursorx, self.cursory))?;
stdout.execute(cursor::Show)?;
std::thread::sleep(Duration::from_millis(16));
Ok(())
}
} }