Advanced buffering, read and display file

This commit is contained in:
Jarkko Toivanen 2024-08-12 22:55:24 +03:00
parent b3f7321b90
commit cb2511adf2
Signed by: jt
GPG key ID: 9151B109B73ECAD5

View file

@ -4,6 +4,7 @@ use crossterm::{
};
use std::panic;
use std::io::{stdout, Result, Write, Stdout};
use std::fs::read_to_string;
#[derive(Default)]
@ -11,7 +12,7 @@ struct Nuudel {
quitting: bool,
cursorx: u16,
cursory: u16,
buffer: String,
buffer: Buffer,
}
#[derive(Default)]
@ -30,6 +31,7 @@ fn main() -> Result<()> {
// Basic stuff
let mut nuudel = Nuudel::default();
Nuudel::init_terminal()?;
nuudel.open_file("Cargo.toml")?;
nuudel.run(&mut stdout())?;
Nuudel::restore_terminal()?;
@ -105,24 +107,17 @@ impl Nuudel {
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();
let mut lines = self.buffer.lines.iter();
while y < terminal::size()?.1-1 {
stdout.execute(terminal::Clear(terminal::ClearType::CurrentLine))?;
if let Some(line) = lines.next() {
write!(stdout, "{}", line)?;
} else {
break;
} stdout.execute(cursor::MoveToNextLine(1))?;
write!(stdout, "~")?;
}
stdout.execute(cursor::MoveToNextLine(1))?;
y += 1;
}
print!("Press Q to quit");
@ -133,4 +128,14 @@ impl Nuudel {
Ok(())
}
fn open_file(&mut self, filename: &str) -> Result<()> {
self.buffer.lines.clear();
self.buffer.lines = read_to_string(filename)
.unwrap()
.lines()
.map(String::from)
.collect();
Ok(())
}
}