Skip to content

Commit

Permalink
some improvements and refactoring on the way
Browse files Browse the repository at this point in the history
  • Loading branch information
alexpasmantier committed Oct 14, 2024
1 parent dbc4b6c commit 725d399
Show file tree
Hide file tree
Showing 20 changed files with 721 additions and 1,364 deletions.
733 changes: 8 additions & 725 deletions Cargo.lock

Large diffs are not rendered by default.

14 changes: 4 additions & 10 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,24 +41,18 @@ color-eyre = "0.6.3"
config = "0.14.0"
crossterm = { version = "0.28.1", features = ["serde"] }
derive_deref = "1.1.1"
devicons = "0.5.4"
devicons = "0.6.8"
directories = "5.0.1"
futures = "0.3.30"
fuzzy-matcher = "0.3.7"
human-panic = "2.0.1"
ignore = "0.4.23"
image = "0.25.2"
impl-enum = "0.3.1"
infer = "0.16.0"
json5 = "0.4.1"
lazy_static = "1.5.0"
libc = "0.2.158"
nucleo = "0.5.0"
nucleo-matcher = "0.3.1"
parking_lot = "0.12.3"
pretty_assertions = "1.4.0"
ratatui = { version = "0.28.1", features = ["serde", "macros"] }
ratatui-image = "1.0.5"
regex = "1.10.6"
serde = { version = "1.0.208", features = ["derive"] }
serde_json = "1.0.125"
Expand All @@ -67,13 +61,13 @@ strip-ansi-escapes = "0.2.0"
strum = { version = "0.26.3", features = ["derive"] }
syntect = "5.2.0"
tokio = { version = "1.39.3", features = ["full"] }
tokio-stream = "0.1.16"
tokio-util = "0.7.11"
toml = "0.8.19"
tracing = "0.1.40"
tracing-error = "0.2.0"
tracing-subscriber = { version = "0.3.18", features = ["env-filter", "serde"] }
unicode-width = "0.2.0"
human-panic = "2.0.2"
pretty_assertions = "1.4.1"


[build-dependencies]
Expand All @@ -88,7 +82,7 @@ debug = "none"
strip = "symbols"
debug-assertions = false
overflow-checks = false
lto = "thin"
lto = "fat"
panic = "abort"

[target.'cfg(target_os = "macos")'.dependencies]
Expand Down
5 changes: 2 additions & 3 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@
- [x] piping output to another command
- [x] piping custom entries from stdin (e.g. `ls | tv`, what bout choosing previewers in that case? Some AUTO mode?)

## bugs
- [x] sanitize input (tabs, \0, etc) (see https://github.com/autobib/nucleo-picker/blob/d51dec9efd523e88842c6eda87a19c0a492f4f36/src/lib.rs#L212-L227)

## improvements
- [x] async finder initialization
- [x] async finder search
Expand All @@ -21,6 +18,8 @@
- [x] only ever read a portion of the file for the temp preview
- [ ] make layout an attribute of the channel?
- [x] I feel like the finder abstraction is a superfluous layer, maybe just use the channel directly?
- [ ] support for images is implemented but do we really want that in the core? it's quite heavy
- [ ] use an icon for the prompt

## feature ideas
- [ ] some sort of iterative fuzzy file explorer (preview contents of folders on the right, enter to go in etc.) maybe
Expand Down
6 changes: 3 additions & 3 deletions crates/television/channels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ use television_derive::CliChannel;
mod alias;
mod env;
mod files;
mod grep;
mod text;
mod stdin;

/// The interface that all television channels must implement.
///
/// # Important
/// The `TelevisionChannel` requires the `Send` trait to be implemented as
/// well. This is necessary to allow the channels to be used in a
/// multi-threaded environment.
/// multithreaded environment.
///
/// # Methods
/// - `find`: Find entries that match the given pattern. This method does not
Expand Down Expand Up @@ -87,7 +87,7 @@ pub trait TelevisionChannel: Send {
pub enum AvailableChannels {
Env(env::Channel),
Files(files::Channel),
Grep(grep::Channel),
Text(text::Channel),
Stdin(stdin::Channel),
Alias(alias::Channel),
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use std::{
sync::Arc,
};

use tracing::info;
use tracing::{debug, info};

use super::TelevisionChannel;
use crate::entry::Entry;
Expand Down Expand Up @@ -182,13 +182,18 @@ async fn load_candidates(path: PathBuf, injector: Injector<CandidateLine>) {
match maybe_line {
Ok(l) => {
line_number += 1;
let line = preprocess_line(&l);
if line.is_empty() {
debug!("Empty line");
continue;
}
let candidate = CandidateLine::new(
entry
.path()
.strip_prefix(&current_dir)
.unwrap()
.to_path_buf(),
preprocess_line(&l),
line,
line_number,
);
// Send the line via the async channel
Expand Down
1 change: 0 additions & 1 deletion crates/television/components.rs

This file was deleted.

1 change: 0 additions & 1 deletion crates/television/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ mod action;
mod app;
mod channels;
mod cli;
mod components;
mod config;
mod entry;
mod errors;
Expand Down
4 changes: 2 additions & 2 deletions crates/television/previewers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ mod files;
pub use basic::BasicPreviewer;
pub use env::EnvVarPreviewer;
pub use files::FilePreviewer;
use ratatui_image::protocol::StatefulProtocol;
//use ratatui_image::protocol::StatefulProtocol;
use syntect::highlighting::Style;

#[derive(Debug, Clone, Eq, PartialEq, Hash, Default)]
Expand All @@ -27,7 +27,7 @@ pub enum PreviewContent {
Empty,
FileTooLarge,
HighlightedText(Vec<Vec<(Style, String)>>),
Image(Box<dyn StatefulProtocol>),
//Image(Box<dyn StatefulProtocol>),
Loading,
NotSupported,
PlainText(Vec<String>),
Expand Down
2 changes: 1 addition & 1 deletion crates/television/previewers/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ where
const DEFAULT_PREVIEW_CACHE_SIZE: usize = 100;

/// A cache for previews.
/// The cache is implemented as a LRU cache with a fixed size.
/// The cache is implemented as an LRU cache with a fixed size.
pub struct PreviewCache {
entries: HashMap<String, Arc<Preview>>,
ring_set: RingSet<String>,
Expand Down
81 changes: 41 additions & 40 deletions crates/television/previewers/files.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use color_eyre::Result;
use image::{ImageReader, Rgb};
use ratatui_image::picker::Picker;
//use image::{ImageReader, Rgb};
//use ratatui_image::picker::Picker;
use std::fs::File;
use std::io::{BufRead, BufReader, Read, Seek};
use std::path::{Path, PathBuf};
Expand All @@ -12,7 +12,8 @@ use syntect::{
highlighting::{Style, Theme, ThemeSet},
parsing::SyntaxSet,
};
use tracing::{debug, info, warn};
//use tracing::{debug, info, warn};
use tracing::{debug, warn};

use crate::entry;
use crate::previewers::{Preview, PreviewContent};
Expand All @@ -27,48 +28,48 @@ 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();
info!("got image picker");
//info!("getting 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: &entry::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: &entry::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,
Expand Down Expand Up @@ -213,8 +214,8 @@ impl FilePreviewer {
let preview = loading(&entry.name);
self.cache_preview(entry.name.clone(), preview.clone())
.await;
// compute the image preview in the background
self.compute_image_preview(entry).await;
//// compute the image preview in the background
//self.compute_image_preview(entry).await;
preview
}
FileType::Other => {
Expand All @@ -235,15 +236,15 @@ impl FilePreviewer {
}
}

fn get_image_picker() -> Picker {
let mut picker = match Picker::from_termios() {
Ok(p) => p,
Err(_) => Picker::new((7, 14)),
};
picker.guess_protocol();
picker.background_color = Some(Rgb::<u8>([255, 0, 255]));
picker
}
//fn get_image_picker() -> Picker {
// let mut picker = match Picker::from_termios() {
// Ok(p) => p,
// Err(_) => Picker::new((7, 14)),
// };
// picker.guess_protocol();
// picker.background_color = Some(Rgb::<u8>([255, 0, 255]));
// picker
//}

/// This should be enough to most standard terminal sizes
const TEMP_PLAIN_TEXT_PREVIEW_HEIGHT: usize = 200;
Expand Down
Loading

0 comments on commit 725d399

Please sign in to comment.