Skip to content

Commit

Permalink
add binary file preview
Browse files Browse the repository at this point in the history
  • Loading branch information
Kl4rry committed Jul 15, 2024
1 parent 718c3df commit dc993d6
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
28 changes: 23 additions & 5 deletions crates/ferrite-core/src/picker/file_previewer.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use std::{
collections::{hash_map::Entry, HashMap},
fs, io,
fs::{self, File},
io::{self, Read},
path::Path,
};

use crate::{
Expand All @@ -10,9 +12,19 @@ use crate::{
promise::Promise,
};

fn is_text_file(path: impl AsRef<Path>) -> Result<bool, io::Error> {
let mut file = File::open(&path)?;

let mut buf = [0; 1024];
let read = file.read(&mut buf)?;

let content_type = content_inspector::inspect(&buf[..read]);
Ok(content_type.is_text())
}

pub struct FilePreviewer {
files: HashMap<String, Result<Buffer, io::Error>>,
loading: HashMap<String, Promise<Result<Buffer, io::Error>>>,
files: HashMap<String, Result<Option<Buffer>, io::Error>>,
loading: HashMap<String, Promise<Result<Option<Buffer>, io::Error>>>,
proxy: Box<dyn EventLoopProxy>,
}

Expand All @@ -36,7 +48,8 @@ impl Previewer<String> for FilePreviewer {
}

match self.files.get_mut(m) {
Some(Ok(buffer)) => return Preview::Buffer(buffer),
Some(Ok(Some(buffer))) => return Preview::Buffer(buffer),
Some(Ok(None)) => return Preview::Binary,
Some(Err(_)) => return Preview::Err,
None => (),
}
Expand All @@ -51,7 +64,12 @@ impl Previewer<String> for FilePreviewer {

self.loading.insert(
m.clone(),
Promise::spawn(self.proxy.dup(), move || Buffer::from_file(path)),
Promise::spawn(self.proxy.dup(), move || {
if !is_text_file(&path)? {
return Ok(None);
}
Ok(Some(Buffer::from_file(&path)?))
}),
);
Preview::Loading
}
Expand Down
1 change: 1 addition & 0 deletions crates/ferrite-tui/src/widgets/background_widget.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ impl Widget for BackgroundWidget<'_> {
fn render(self, _: tui::layout::Rect, buf: &mut tui::buffer::Buffer) {
for cell in &mut buf.content {
cell.set_style(convert_style(&self.theme.background));
cell.set_symbol(" ");
}
}
}

0 comments on commit dc993d6

Please sign in to comment.