Skip to content

Commit

Permalink
improvements on temp plain text previews
Browse files Browse the repository at this point in the history
  • Loading branch information
alexpasmantier committed Oct 10, 2024
1 parent af79937 commit 7454102
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 41 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,6 @@ debug = "none"
strip = "symbols"
debug-assertions = false
overflow-checks = false
lto = "fat"
lto = "thin"
panic = "abort"

10 changes: 8 additions & 2 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
- [x] use nucleo for env
- [ ] better keymaps
- [ ] mutualize placeholder previews in cache (really not a priority)
- [ ] better abstractions for channels / separation / isolation so that others can contribute new ones easily
- [ ] channel selection in the UI (separate menu or top panel or something)
- [ ] only render highlighted lines that are visible
- [ ] only ever read a portion of the file for the temp preview

## feature ideas
- [ ] some sort of iterative fuzzy file explorer (preview contents of folders on the right, enter to go in etc.) maybe
Expand All @@ -25,6 +29,8 @@
- [ ] text in documents (pdfs, archives, ...) (rga, adapters) https://github.com/jrmuizel/pdf-extract
- [x] fd
- [ ] recent directories
- [ ] git
- [ ] git (commits, branches, status, diff, ...)
- [ ] makefile commands
-
- [ ] remote files (s3, ...)
- [ ] custom actions as part of a channel (mappable)

1 change: 0 additions & 1 deletion src/components/channels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ impl TvChannel {
}
}

// FIXME: could we avoid collecting here?
pub fn results(&mut self, num_entries: u32, offset: u32) -> Vec<Entry> {
match self {
TvChannel::Env(channel) => channel.finder.results(num_entries, offset).collect(),
Expand Down
83 changes: 46 additions & 37 deletions src/components/previewers/files.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use color_eyre::Result;
use image::Rgb;
use image::{ImageReader, Rgb};
use ratatui_image::picker::Picker;
use std::fs::File;
use std::io::{BufRead, BufReader, Read};
use std::io::{BufRead, BufReader, Read, Seek};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use syntect::easy::HighlightLines;
Expand All @@ -27,46 +27,50 @@ pub struct FilePreviewer {
cache: Arc<Mutex<PreviewCache>>,
syntax_set: Arc<SyntaxSet>,
syntax_theme: Arc<Theme>,
//image_picker: Arc<Mutex<Picker>>,
image_picker: Arc<Mutex<Picker>>,
}

impl FilePreviewer {
pub fn new() -> Self {
let syntax_set = SyntaxSet::load_defaults_nonewlines();
let theme_set = ThemeSet::load_defaults();
info!("getting image picker");
//let image_picker = get_image_picker();
let image_picker = get_image_picker();
info!("got image picker");

FilePreviewer {
cache: Arc::new(Mutex::new(PreviewCache::default())),
syntax_set: Arc::new(syntax_set),
syntax_theme: Arc::new(theme_set.themes["base16-ocean.dark"].clone()),
//image_picker: Arc::new(Mutex::new(image_picker)),
image_picker: Arc::new(Mutex::new(image_picker)),
}
}

//async fn compute_image_preview(&self, entry: &finders::Entry) {
// let cache = self.cache.clone();
// let picker = self.image_picker.clone();
// let entry_c = entry.clone();
// tokio::spawn(async move {
// info!("Loading image: {:?}", entry_c.name);
// if let Ok(dyn_image) = ImageReader::open(entry_c.name.clone()).unwrap().decode() {
// let image = picker.lock().await.new_resize_protocol(dyn_image);
// let preview = Arc::new(Preview::new(
// entry_c.name.clone(),
// PreviewContent::Image(image),
// ));
// cache
// .lock()
// .await
// .insert(entry_c.name.clone(), preview.clone());
// }
// });
//}
async fn compute_image_preview(&self, entry: &finders::Entry) {
let cache = self.cache.clone();
let picker = self.image_picker.clone();
let entry_c = entry.clone();
tokio::spawn(async move {
info!("Loading image: {:?}", entry_c.name);
if let Ok(dyn_image) = ImageReader::open(entry_c.name.clone()).unwrap().decode() {
let image = picker.lock().await.new_resize_protocol(dyn_image);
let preview = Arc::new(Preview::new(
entry_c.name.clone(),
PreviewContent::Image(image),
));
cache
.lock()
.await
.insert(entry_c.name.clone(), preview.clone());
}
});
}

async fn compute_highlighted_text_preview(&self, entry: &finders::Entry, lines: Vec<String>) {
async fn compute_highlighted_text_preview(
&self,
entry: &finders::Entry,
reader: BufReader<File>,
) {
let cache = self.cache.clone();
let syntax_set = self.syntax_set.clone();
let syntax_theme = self.syntax_theme.clone();
Expand All @@ -76,10 +80,11 @@ impl FilePreviewer {
"Computing highlights in the background for {:?}",
entry_c.name
);
let lines: Vec<String> = reader.lines().map_while(Result::ok).collect();

match compute_highlights(
&PathBuf::from(&entry_c.name),
lines.clone(),
lines,
&syntax_set,
&syntax_theme,
) {
Expand All @@ -88,7 +93,7 @@ impl FilePreviewer {
cache.lock().await.insert(
entry_c.name.clone(),
Arc::new(Preview::new(
entry_c.name.clone(),
entry_c.name,
PreviewContent::HighlightedText(highlighted_lines),
)),
);
Expand Down Expand Up @@ -165,20 +170,18 @@ impl FilePreviewer {
debug!("Computing preview for {:?}", entry.name);
match self.get_file_type(&path_buf) {
FileType::Text => {

match File::open(&path_buf) {
Ok(file) => {
// insert a non-highlighted version of the preview into the cache
let reader = BufReader::new(file);
let reader = BufReader::new(&file);
let preview = plain_text_preview(&entry.name, reader);
self.cache_preview(entry.name.clone(), preview.clone())
.await;

if let PreviewContent::PlainText(ref lines) = preview.content {
// compute the highlighted version in the background
self.compute_highlighted_text_preview(entry, lines.to_vec())
.await;
}
// compute the highlighted version in the background
let mut reader = BufReader::new(file.try_clone().unwrap());
reader.seek(std::io::SeekFrom::Start(0)).unwrap();
self.compute_highlighted_text_preview(entry, reader).await;
preview
}
Err(e) => {
Expand All @@ -196,7 +199,7 @@ impl FilePreviewer {
self.cache_preview(entry.name.clone(), preview.clone())
.await;
// compute the image preview in the background
//self.compute_image_preview(entry).await;
self.compute_image_preview(entry).await;
preview
}
FileType::Other => {
Expand Down Expand Up @@ -227,9 +230,12 @@ fn get_image_picker() -> Picker {
picker
}

fn plain_text_preview(title: &str, reader: BufReader<File>) -> Arc<Preview> {
/// This should be enough to most standard terminal sizes
const TEMP_PLAIN_TEXT_PREVIEW_HEIGHT: usize = 200;

fn plain_text_preview(title: &str, reader: BufReader<&File>) -> Arc<Preview> {
debug!("Creating plain text preview for {:?}", title);
let mut lines = Vec::new();
let mut lines = Vec::with_capacity(TEMP_PLAIN_TEXT_PREVIEW_HEIGHT);
for maybe_line in reader.lines() {
match maybe_line {
Ok(line) => lines.push(preprocess_line(&line)),
Expand All @@ -238,6 +244,9 @@ fn plain_text_preview(title: &str, reader: BufReader<File>) -> Arc<Preview> {
return not_supported(title);
}
}
if lines.len() >= TEMP_PLAIN_TEXT_PREVIEW_HEIGHT {
break;
}
}
Arc::new(Preview::new(
title.to_string(),
Expand Down

0 comments on commit 7454102

Please sign in to comment.