mirror of
https://github.com/alexpasmantier/television.git
synced 2025-06-06 03:25:23 +00:00
some improvements and refactoring on the way
This commit is contained in:
parent
dbc4b6c06a
commit
725d399d82
733
Cargo.lock
generated
733
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
14
Cargo.toml
14
Cargo.toml
@ -41,14 +41,10 @@ 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"
|
||||
@ -56,9 +52,7 @@ 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"
|
||||
@ -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]
|
||||
@ -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]
|
||||
|
5
TODO.md
5
TODO.md
@ -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
|
||||
@ -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
|
||||
|
@ -4,7 +4,7 @@ use television_derive::CliChannel;
|
||||
mod alias;
|
||||
mod env;
|
||||
mod files;
|
||||
mod grep;
|
||||
mod text;
|
||||
mod stdin;
|
||||
|
||||
/// The interface that all television channels must implement.
|
||||
@ -12,7 +12,7 @@ mod stdin;
|
||||
/// # 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
|
||||
@ -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),
|
||||
}
|
||||
|
@ -10,7 +10,7 @@ use std::{
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use tracing::info;
|
||||
use tracing::{debug, info};
|
||||
|
||||
use super::TelevisionChannel;
|
||||
use crate::entry::Entry;
|
||||
@ -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(¤t_dir)
|
||||
.unwrap()
|
||||
.to_path_buf(),
|
||||
preprocess_line(&l),
|
||||
line,
|
||||
line_number,
|
||||
);
|
||||
// Send the line via the async channel
|
@ -1 +0,0 @@
|
||||
|
@ -12,7 +12,6 @@ mod action;
|
||||
mod app;
|
||||
mod channels;
|
||||
mod cli;
|
||||
mod components;
|
||||
mod config;
|
||||
mod entry;
|
||||
mod errors;
|
||||
|
@ -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)]
|
||||
@ -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>),
|
||||
|
@ -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>,
|
||||
|
@ -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};
|
||||
@ -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};
|
||||
@ -27,16 +28,16 @@ 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())),
|
||||
@ -44,31 +45,31 @@ impl FilePreviewer {
|
||||
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,
|
||||
@ -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 => {
|
||||
@ -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;
|
||||
|
@ -1,30 +1,30 @@
|
||||
use color_eyre::Result;
|
||||
use futures::executor::block_on;
|
||||
use ratatui::{
|
||||
layout::{Alignment, Constraint, Direction, Layout, Rect},
|
||||
style::{Color, Modifier, Style, Stylize},
|
||||
text::{Line, Span, Text},
|
||||
layout::{
|
||||
Alignment, Constraint, Direction, Layout as RatatuiLayout, Rect,
|
||||
},
|
||||
style::{Color, Style},
|
||||
text::{Line, Span},
|
||||
widgets::{
|
||||
block::{Position, Title},
|
||||
Block, BorderType, Borders, ListState, Padding, Paragraph, Wrap,
|
||||
Block, BorderType, Borders, ListState, Padding, Paragraph,
|
||||
},
|
||||
Frame,
|
||||
};
|
||||
use ratatui_image::StatefulImage;
|
||||
use std::{collections::HashMap, str::FromStr, sync::Arc};
|
||||
use syntect;
|
||||
use syntect::highlighting::Color as SyntectColor;
|
||||
|
||||
use std::{collections::HashMap, str::FromStr};
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
|
||||
use crate::channels::{CliTvChannel, TelevisionChannel};
|
||||
use crate::entry::{Entry, ENTRY_PLACEHOLDER};
|
||||
use crate::previewers::{
|
||||
Preview, PreviewContent, Previewer, FILE_TOO_LARGE_MSG,
|
||||
PREVIEW_NOT_SUPPORTED_MSG,
|
||||
};
|
||||
use crate::ui::input::{Input, InputRequest, StateChanged};
|
||||
use crate::ui::{build_results_list, create_layout, get_border_style};
|
||||
use crate::previewers::Previewer;
|
||||
use crate::ui::get_border_style;
|
||||
use crate::ui::input::actions::InputActionHandler;
|
||||
use crate::ui::input::Input;
|
||||
use crate::ui::layout::{Dimensions, Layout};
|
||||
use crate::ui::preview::DEFAULT_PREVIEW_TITLE_FG;
|
||||
use crate::ui::results::build_results_list;
|
||||
use crate::utils::strings::EMPTY_STRING;
|
||||
use crate::{action::Action, config::Config};
|
||||
|
||||
#[derive(PartialEq, Copy, Clone)]
|
||||
@ -48,14 +48,12 @@ pub struct Television {
|
||||
picker_view_offset: usize,
|
||||
results_area_height: u32,
|
||||
previewer: Previewer,
|
||||
preview_scroll: Option<u16>,
|
||||
preview_pane_height: u16,
|
||||
pub preview_scroll: Option<u16>,
|
||||
pub(crate) preview_pane_height: u16,
|
||||
current_preview_total_lines: u16,
|
||||
meta_paragraph_cache: HashMap<String, Paragraph<'static>>,
|
||||
pub(crate) meta_paragraph_cache: HashMap<String, Paragraph<'static>>,
|
||||
}
|
||||
|
||||
const EMPTY_STRING: &str = "";
|
||||
|
||||
impl Television {
|
||||
#[must_use]
|
||||
pub fn new(cli_channel: CliTvChannel) -> Self {
|
||||
@ -87,7 +85,7 @@ impl Television {
|
||||
|
||||
#[must_use]
|
||||
/// # Panics
|
||||
/// This method will panic if the index doesn't fit into a u32.
|
||||
/// This method will panic if the index doesn't fit into an u32.
|
||||
pub fn get_selected_entry(&self) -> Option<Entry> {
|
||||
self.picker_state
|
||||
.selected()
|
||||
@ -140,10 +138,10 @@ impl Television {
|
||||
self.picker_view_offset.saturating_sub(1);
|
||||
}
|
||||
} else {
|
||||
self.picker_view_offset = (self
|
||||
self.picker_view_offset = self
|
||||
.channel
|
||||
.result_count()
|
||||
.saturating_sub(self.results_area_height - 2))
|
||||
.saturating_sub(self.results_area_height - 2)
|
||||
as usize;
|
||||
self.picker_state.select(Some(
|
||||
(self.channel.result_count() as usize).saturating_sub(1),
|
||||
@ -269,19 +267,10 @@ impl Television {
|
||||
}
|
||||
}
|
||||
|
||||
// Misc
|
||||
const FOUR_SPACES: &str = " ";
|
||||
|
||||
// Styles
|
||||
// input
|
||||
const DEFAULT_INPUT_FG: Color = Color::Rgb(200, 200, 200);
|
||||
const DEFAULT_RESULTS_COUNT_FG: Color = Color::Rgb(150, 150, 150);
|
||||
// preview
|
||||
const DEFAULT_PREVIEW_TITLE_FG: Color = Color::Blue;
|
||||
const DEFAULT_SELECTED_PREVIEW_BG: Color = Color::Rgb(50, 50, 50);
|
||||
const DEFAULT_PREVIEW_CONTENT_FG: Color = Color::Rgb(150, 150, 180);
|
||||
const DEFAULT_PREVIEW_GUTTER_FG: Color = Color::Rgb(70, 70, 70);
|
||||
const DEFAULT_PREVIEW_GUTTER_SELECTED_FG: Color = Color::Rgb(255, 150, 150);
|
||||
|
||||
impl Television {
|
||||
/// Register an action handler that can send actions for processing if necessary.
|
||||
@ -400,11 +389,14 @@ impl Television {
|
||||
///
|
||||
/// * `Result<()>` - An Ok result or an error.
|
||||
pub fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> {
|
||||
let (results_area, input_area, preview_title_area, preview_area) =
|
||||
create_layout(area);
|
||||
//let layout = Layout::all_panes_centered(Dimensions::default(), area);
|
||||
let layout =
|
||||
Layout::results_only_centered(Dimensions::new(40, 60), area);
|
||||
|
||||
self.results_area_height = u32::from(results_area.height);
|
||||
self.preview_pane_height = preview_area.height;
|
||||
self.results_area_height = u32::from(layout.results.height);
|
||||
if let Some(preview_window) = layout.preview_window {
|
||||
self.preview_pane_height = preview_window.height;
|
||||
}
|
||||
|
||||
// top left block: results
|
||||
let results_block = Block::default()
|
||||
@ -427,14 +419,14 @@ impl Television {
|
||||
}
|
||||
|
||||
let entries = self.channel.results(
|
||||
(results_area.height - 2).into(),
|
||||
u32::try_from(self.picker_view_offset).unwrap(),
|
||||
(layout.results.height - 2).into(),
|
||||
u32::try_from(self.picker_view_offset)?,
|
||||
);
|
||||
let results_list = build_results_list(results_block, &entries);
|
||||
|
||||
frame.render_stateful_widget(
|
||||
results_list,
|
||||
results_area,
|
||||
layout.results,
|
||||
&mut self.relative_picker_state,
|
||||
);
|
||||
|
||||
@ -450,11 +442,11 @@ impl Television {
|
||||
.border_style(get_border_style(Pane::Input == self.current_pane))
|
||||
.style(Style::default());
|
||||
|
||||
let input_block_inner = input_block.inner(input_area);
|
||||
let input_block_inner = input_block.inner(layout.input);
|
||||
|
||||
frame.render_widget(input_block, input_area);
|
||||
frame.render_widget(input_block, layout.input);
|
||||
|
||||
let inner_input_chunks = Layout::default()
|
||||
let inner_input_chunks = RatatuiLayout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([
|
||||
Constraint::Length(2),
|
||||
@ -478,7 +470,7 @@ impl Television {
|
||||
let width = inner_input_chunks[1].width.max(3) - 3;
|
||||
let scroll = self.input.visual_scroll(width as usize);
|
||||
let input = Paragraph::new(self.input.value())
|
||||
.scroll((0, u16::try_from(scroll).unwrap()))
|
||||
.scroll((0, u16::try_from(scroll)?))
|
||||
.block(interactive_input_block)
|
||||
.style(Style::default().fg(DEFAULT_INPUT_FG))
|
||||
.alignment(Alignment::Left);
|
||||
@ -508,373 +500,94 @@ impl Television {
|
||||
// Put cursor past the end of the input text
|
||||
inner_input_chunks[1].x
|
||||
+ u16::try_from(
|
||||
(self.input.visual_cursor()).max(scroll) - scroll,
|
||||
)
|
||||
.unwrap(),
|
||||
self.input.visual_cursor().max(scroll) - scroll,
|
||||
)?,
|
||||
// Move one line down, from the border to the input line
|
||||
inner_input_chunks[1].y,
|
||||
));
|
||||
}
|
||||
|
||||
// top right block: preview title
|
||||
let selected_entry =
|
||||
self.get_selected_entry().unwrap_or(ENTRY_PLACEHOLDER);
|
||||
if layout.preview_title.is_some() || layout.preview_window.is_some() {
|
||||
let selected_entry =
|
||||
self.get_selected_entry().unwrap_or(ENTRY_PLACEHOLDER);
|
||||
let preview = block_on(self.previewer.preview(&selected_entry));
|
||||
|
||||
let preview = block_on(self.previewer.preview(&selected_entry));
|
||||
self.current_preview_total_lines = preview.total_lines();
|
||||
if let Some(preview_title_area) = layout.preview_title {
|
||||
// top right block: preview title
|
||||
self.current_preview_total_lines = preview.total_lines();
|
||||
|
||||
let mut preview_title_spans = Vec::new();
|
||||
if let Some(icon) = &selected_entry.icon {
|
||||
preview_title_spans.push(Span::styled(
|
||||
icon.to_string(),
|
||||
Style::default().fg(Color::from_str(icon.color).unwrap()),
|
||||
));
|
||||
preview_title_spans.push(Span::raw(" "));
|
||||
}
|
||||
preview_title_spans.push(Span::styled(
|
||||
preview.title.clone(),
|
||||
Style::default().fg(DEFAULT_PREVIEW_TITLE_FG),
|
||||
));
|
||||
let preview_title = Paragraph::new(Line::from(preview_title_spans))
|
||||
.block(
|
||||
Block::default()
|
||||
let mut preview_title_spans = Vec::new();
|
||||
if let Some(icon) = &selected_entry.icon {
|
||||
preview_title_spans.push(Span::styled(
|
||||
icon.to_string(),
|
||||
Style::default().fg(Color::from_str(icon.color)?),
|
||||
));
|
||||
preview_title_spans.push(Span::raw(" "));
|
||||
}
|
||||
preview_title_spans.push(Span::styled(
|
||||
preview.title.clone(),
|
||||
Style::default().fg(DEFAULT_PREVIEW_TITLE_FG),
|
||||
));
|
||||
let preview_title =
|
||||
Paragraph::new(Line::from(preview_title_spans))
|
||||
.block(
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.border_type(BorderType::Rounded)
|
||||
.border_style(get_border_style(false)),
|
||||
)
|
||||
.alignment(Alignment::Left);
|
||||
frame.render_widget(preview_title, preview_title_area);
|
||||
}
|
||||
|
||||
if let Some(preview_area) = layout.preview_window {
|
||||
// file preview
|
||||
let preview_outer_block = Block::default()
|
||||
.title(
|
||||
Title::from(" Preview ")
|
||||
.position(Position::Top)
|
||||
.alignment(Alignment::Center),
|
||||
)
|
||||
.borders(Borders::ALL)
|
||||
.border_type(BorderType::Rounded)
|
||||
.border_style(get_border_style(false)),
|
||||
)
|
||||
.alignment(Alignment::Left);
|
||||
frame.render_widget(preview_title, preview_title_area);
|
||||
.border_style(get_border_style(
|
||||
Pane::Preview == self.current_pane,
|
||||
))
|
||||
.style(Style::default())
|
||||
.padding(Padding::right(1));
|
||||
|
||||
// file preview
|
||||
let preview_outer_block = Block::default()
|
||||
.title(
|
||||
Title::from(" Preview ")
|
||||
.position(Position::Top)
|
||||
.alignment(Alignment::Center),
|
||||
)
|
||||
.borders(Borders::ALL)
|
||||
.border_type(BorderType::Rounded)
|
||||
.border_style(get_border_style(Pane::Preview == self.current_pane))
|
||||
.style(Style::default())
|
||||
.padding(Padding::right(1));
|
||||
let preview_inner_block = Block::default()
|
||||
.style(Style::default())
|
||||
.padding(Padding {
|
||||
top: 0,
|
||||
right: 1,
|
||||
bottom: 0,
|
||||
left: 1,
|
||||
});
|
||||
let inner = preview_outer_block.inner(preview_area);
|
||||
frame.render_widget(preview_outer_block, preview_area);
|
||||
|
||||
let preview_inner_block =
|
||||
Block::default().style(Style::default()).padding(Padding {
|
||||
top: 0,
|
||||
right: 1,
|
||||
bottom: 0,
|
||||
left: 1,
|
||||
});
|
||||
let inner = preview_outer_block.inner(preview_area);
|
||||
frame.render_widget(preview_outer_block, preview_area);
|
||||
|
||||
if let PreviewContent::Image(img) = &preview.content {
|
||||
let image_component = StatefulImage::new(None);
|
||||
frame.render_stateful_widget(
|
||||
image_component,
|
||||
inner,
|
||||
&mut img.clone(),
|
||||
);
|
||||
} else {
|
||||
let preview_block = self.build_preview_paragraph(
|
||||
preview_inner_block,
|
||||
inner,
|
||||
&preview,
|
||||
selected_entry
|
||||
.line_number
|
||||
// FIXME: this actually might panic in some edge cases
|
||||
.map(|l| u16::try_from(l).unwrap()),
|
||||
);
|
||||
frame.render_widget(preview_block, inner);
|
||||
//if let PreviewContent::Image(img) = &preview.content {
|
||||
// let image_component = StatefulImage::new(None);
|
||||
// frame.render_stateful_widget(
|
||||
// image_component,
|
||||
// inner,
|
||||
// &mut img.clone(),
|
||||
// );
|
||||
//} else {
|
||||
let preview_block = self.build_preview_paragraph(
|
||||
preview_inner_block,
|
||||
inner,
|
||||
&preview,
|
||||
selected_entry
|
||||
.line_number
|
||||
// FIXME: this actually might panic in some edge cases
|
||||
.map(|l| u16::try_from(l).unwrap()),
|
||||
);
|
||||
frame.render_widget(preview_block, inner);
|
||||
//}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Television {
|
||||
const FILL_CHAR_SLANTED: char = '╱';
|
||||
const FILL_CHAR_EMPTY: char = ' ';
|
||||
|
||||
fn build_preview_paragraph<'b>(
|
||||
&'b mut self,
|
||||
preview_block: Block<'b>,
|
||||
inner: Rect,
|
||||
preview: &Arc<Preview>,
|
||||
target_line: Option<u16>,
|
||||
) -> Paragraph<'b> {
|
||||
self.maybe_init_preview_scroll(target_line, inner.height);
|
||||
match &preview.content {
|
||||
PreviewContent::PlainText(content) => {
|
||||
let mut lines = Vec::new();
|
||||
for (i, line) in content.iter().enumerate() {
|
||||
lines.push(Line::from(vec![
|
||||
build_line_number_span(i + 1).style(Style::default().fg(
|
||||
// FIXME: this actually might panic in some edge cases
|
||||
if matches!(
|
||||
target_line,
|
||||
Some(l) if l == u16::try_from(i).unwrap() + 1
|
||||
)
|
||||
{
|
||||
DEFAULT_PREVIEW_GUTTER_SELECTED_FG
|
||||
} else {
|
||||
DEFAULT_PREVIEW_GUTTER_FG
|
||||
},
|
||||
)),
|
||||
Span::styled(" │ ",
|
||||
Style::default().fg(DEFAULT_PREVIEW_GUTTER_FG).dim()),
|
||||
Span::styled(
|
||||
line.to_string(),
|
||||
Style::default().fg(DEFAULT_PREVIEW_CONTENT_FG).bg(
|
||||
if matches!(target_line, Some(l) if l == u16::try_from(i).unwrap() + 1) {
|
||||
DEFAULT_SELECTED_PREVIEW_BG
|
||||
} else {
|
||||
Color::Reset
|
||||
},
|
||||
),
|
||||
),
|
||||
]));
|
||||
}
|
||||
let text = Text::from(lines);
|
||||
Paragraph::new(text)
|
||||
.block(preview_block)
|
||||
.scroll((self.preview_scroll.unwrap_or(0), 0))
|
||||
}
|
||||
PreviewContent::PlainTextWrapped(content) => {
|
||||
let mut lines = Vec::new();
|
||||
for line in content.lines() {
|
||||
lines.push(Line::styled(
|
||||
line.to_string(),
|
||||
Style::default().fg(DEFAULT_PREVIEW_CONTENT_FG),
|
||||
));
|
||||
}
|
||||
let text = Text::from(lines);
|
||||
Paragraph::new(text)
|
||||
.block(preview_block)
|
||||
.wrap(Wrap { trim: true })
|
||||
}
|
||||
PreviewContent::HighlightedText(highlighted_lines) => {
|
||||
compute_paragraph_from_highlighted_lines(
|
||||
highlighted_lines,
|
||||
target_line.map(|l| l as usize),
|
||||
self.preview_scroll.unwrap_or(0),
|
||||
self.preview_pane_height,
|
||||
)
|
||||
.block(preview_block)
|
||||
.alignment(Alignment::Left)
|
||||
.scroll((self.preview_scroll.unwrap_or(0), 0))
|
||||
}
|
||||
// meta
|
||||
PreviewContent::Loading => self
|
||||
.build_meta_preview_paragraph(
|
||||
inner,
|
||||
"Loading...",
|
||||
Self::FILL_CHAR_EMPTY,
|
||||
)
|
||||
.block(preview_block)
|
||||
.alignment(Alignment::Left)
|
||||
.style(Style::default().add_modifier(Modifier::ITALIC)),
|
||||
PreviewContent::NotSupported => self
|
||||
.build_meta_preview_paragraph(
|
||||
inner,
|
||||
PREVIEW_NOT_SUPPORTED_MSG,
|
||||
Self::FILL_CHAR_SLANTED,
|
||||
)
|
||||
.block(preview_block)
|
||||
.alignment(Alignment::Left)
|
||||
.style(Style::default().add_modifier(Modifier::ITALIC)),
|
||||
PreviewContent::FileTooLarge => self
|
||||
.build_meta_preview_paragraph(
|
||||
inner,
|
||||
FILE_TOO_LARGE_MSG,
|
||||
Self::FILL_CHAR_SLANTED,
|
||||
)
|
||||
.block(preview_block)
|
||||
.alignment(Alignment::Left)
|
||||
.style(Style::default().add_modifier(Modifier::ITALIC)),
|
||||
_ => Paragraph::new(Text::raw(EMPTY_STRING)),
|
||||
}
|
||||
}
|
||||
|
||||
fn maybe_init_preview_scroll(
|
||||
&mut self,
|
||||
target_line: Option<u16>,
|
||||
height: u16,
|
||||
) {
|
||||
if self.preview_scroll.is_none() {
|
||||
self.preview_scroll =
|
||||
Some(target_line.unwrap_or(0).saturating_sub(height / 3));
|
||||
}
|
||||
}
|
||||
|
||||
fn build_meta_preview_paragraph<'a>(
|
||||
&mut self,
|
||||
inner: Rect,
|
||||
message: &str,
|
||||
fill_char: char,
|
||||
) -> Paragraph<'a> {
|
||||
if let Some(paragraph) = self.meta_paragraph_cache.get(message) {
|
||||
return paragraph.clone();
|
||||
}
|
||||
let message_len = message.len();
|
||||
let fill_char_str = fill_char.to_string();
|
||||
let fill_line = fill_char_str.repeat(inner.width as usize);
|
||||
|
||||
// Build the paragraph content with slanted lines and center the custom message
|
||||
let mut lines = Vec::new();
|
||||
|
||||
// Calculate the vertical center
|
||||
let vertical_center = inner.height as usize / 2;
|
||||
let horizontal_padding = (inner.width as usize - message_len) / 2 - 4;
|
||||
|
||||
// Fill the paragraph with slanted lines and insert the centered custom message
|
||||
for i in 0..inner.height {
|
||||
if i as usize == vertical_center {
|
||||
// Center the message horizontally in the middle line
|
||||
let line = format!(
|
||||
"{} {} {}",
|
||||
fill_char_str.repeat(horizontal_padding),
|
||||
message,
|
||||
fill_char_str.repeat(
|
||||
inner.width as usize
|
||||
- horizontal_padding
|
||||
- message_len
|
||||
)
|
||||
);
|
||||
lines.push(Line::from(line));
|
||||
} else if i as usize + 1 == vertical_center
|
||||
|| (i as usize).saturating_sub(1) == vertical_center
|
||||
{
|
||||
let line = format!(
|
||||
"{} {} {}",
|
||||
fill_char_str.repeat(horizontal_padding),
|
||||
" ".repeat(message_len),
|
||||
fill_char_str.repeat(
|
||||
inner.width as usize
|
||||
- horizontal_padding
|
||||
- message_len
|
||||
)
|
||||
);
|
||||
lines.push(Line::from(line));
|
||||
} else {
|
||||
lines.push(Line::from(fill_line.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
// Create a paragraph with the generated content
|
||||
let p = Paragraph::new(Text::from(lines));
|
||||
self.meta_paragraph_cache
|
||||
.insert(message.to_string(), p.clone());
|
||||
p
|
||||
}
|
||||
}
|
||||
|
||||
/// This makes the `Action` type compatible with the `Input` logic.
|
||||
pub trait InputActionHandler {
|
||||
// Handle Key event.
|
||||
fn handle_action(&mut self, action: &Action) -> Option<StateChanged>;
|
||||
}
|
||||
|
||||
impl InputActionHandler for Input {
|
||||
/// Handle Key event.
|
||||
fn handle_action(&mut self, action: &Action) -> Option<StateChanged> {
|
||||
match action {
|
||||
Action::AddInputChar(c) => {
|
||||
self.handle(InputRequest::InsertChar(*c))
|
||||
}
|
||||
Action::DeletePrevChar => {
|
||||
self.handle(InputRequest::DeletePrevChar)
|
||||
}
|
||||
Action::DeleteNextChar => {
|
||||
self.handle(InputRequest::DeleteNextChar)
|
||||
}
|
||||
Action::GoToPrevChar => self.handle(InputRequest::GoToPrevChar),
|
||||
Action::GoToNextChar => self.handle(InputRequest::GoToNextChar),
|
||||
Action::GoToInputStart => self.handle(InputRequest::GoToStart),
|
||||
Action::GoToInputEnd => self.handle(InputRequest::GoToEnd),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn build_line_number_span<'a>(line_number: usize) -> Span<'a> {
|
||||
Span::from(format!("{line_number:5} "))
|
||||
}
|
||||
|
||||
fn compute_paragraph_from_highlighted_lines(
|
||||
highlighted_lines: &[Vec<(syntect::highlighting::Style, String)>],
|
||||
line_specifier: Option<usize>,
|
||||
scroll: u16,
|
||||
preview_pane_height: u16,
|
||||
) -> Paragraph<'static> {
|
||||
let preview_lines: Vec<Line> = highlighted_lines
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, l)| {
|
||||
if i < scroll as usize
|
||||
|| i >= (scroll + preview_pane_height) as usize
|
||||
{
|
||||
return Line::from(Span::raw(EMPTY_STRING));
|
||||
}
|
||||
let line_number =
|
||||
build_line_number_span(i + 1).style(Style::default().fg(
|
||||
if line_specifier.is_some()
|
||||
&& i == line_specifier.unwrap() - 1
|
||||
{
|
||||
DEFAULT_PREVIEW_GUTTER_SELECTED_FG
|
||||
} else {
|
||||
DEFAULT_PREVIEW_GUTTER_FG
|
||||
},
|
||||
));
|
||||
Line::from_iter(
|
||||
std::iter::once(line_number)
|
||||
.chain(std::iter::once(Span::styled(
|
||||
" │ ",
|
||||
Style::default().fg(DEFAULT_PREVIEW_GUTTER_FG).dim(),
|
||||
)))
|
||||
.chain(l.iter().cloned().map(|sr| {
|
||||
convert_syn_region_to_span(
|
||||
&(sr.0, sr.1.replace('\t', FOUR_SPACES)),
|
||||
if line_specifier.is_some()
|
||||
&& i == line_specifier.unwrap() - 1
|
||||
{
|
||||
Some(SyntectColor {
|
||||
r: 50,
|
||||
g: 50,
|
||||
b: 50,
|
||||
a: 255,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
},
|
||||
)
|
||||
})),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
Paragraph::new(preview_lines)
|
||||
}
|
||||
|
||||
fn convert_syn_region_to_span<'a>(
|
||||
syn_region: &(syntect::highlighting::Style, String),
|
||||
background: Option<syntect::highlighting::Color>,
|
||||
) -> Span<'a> {
|
||||
let mut style = Style::default()
|
||||
.fg(convert_syn_color_to_ratatui_color(syn_region.0.foreground));
|
||||
if let Some(background) = background {
|
||||
style = style.bg(convert_syn_color_to_ratatui_color(background));
|
||||
}
|
||||
style = match syn_region.0.font_style {
|
||||
syntect::highlighting::FontStyle::BOLD => style.bold(),
|
||||
syntect::highlighting::FontStyle::ITALIC => style.italic(),
|
||||
syntect::highlighting::FontStyle::UNDERLINE => style.underlined(),
|
||||
_ => style,
|
||||
};
|
||||
Span::styled(syn_region.1.clone(), style)
|
||||
}
|
||||
|
||||
fn convert_syn_color_to_ratatui_color(
|
||||
color: syntect::highlighting::Color,
|
||||
) -> ratatui::style::Color {
|
||||
ratatui::style::Color::Rgb(color.r, color.g, color.b)
|
||||
}
|
||||
|
@ -1,26 +1,10 @@
|
||||
use ratatui::{
|
||||
layout::{Constraint, Direction, Layout, Rect},
|
||||
style::{Color, Style, Stylize},
|
||||
text::{Line, Span},
|
||||
widgets::{Block, List, ListDirection},
|
||||
};
|
||||
use std::str::FromStr;
|
||||
|
||||
use crate::entry::Entry;
|
||||
use crate::utils::strings::{next_char_boundary, slice_at_char_boundaries};
|
||||
use crate::utils::ui::centered_rect;
|
||||
use ratatui::style::{Color, Style, Stylize};
|
||||
|
||||
pub mod input;
|
||||
pub mod results;
|
||||
pub mod preview;
|
||||
pub mod layout;
|
||||
|
||||
// UI size
|
||||
const UI_WIDTH_PERCENT: u16 = 90;
|
||||
const UI_HEIGHT_PERCENT: u16 = 90;
|
||||
|
||||
// Styles
|
||||
// results
|
||||
const DEFAULT_RESULT_NAME_FG: Color = Color::Blue;
|
||||
const DEFAULT_RESULT_PREVIEW_FG: Color = Color::Rgb(150, 150, 150);
|
||||
const DEFAULT_RESULT_LINE_NUMBER_FG: Color = Color::Yellow;
|
||||
// input
|
||||
//const DEFAULT_INPUT_FG: Color = Color::Rgb(200, 200, 200);
|
||||
//const DEFAULT_RESULTS_COUNT_FG: Color = Color::Rgb(150, 150, 150);
|
||||
@ -40,137 +24,3 @@ pub fn get_border_style(focused: bool) -> Style {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_layout(area: Rect) -> (Rect, Rect, Rect, Rect) {
|
||||
let main_block = centered_rect(UI_WIDTH_PERCENT, UI_HEIGHT_PERCENT, area);
|
||||
|
||||
// split the main block into two vertical chunks
|
||||
let chunks = Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
|
||||
.split(main_block);
|
||||
|
||||
// left block: results + input field
|
||||
let left_chunks = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([Constraint::Min(10), Constraint::Length(3)])
|
||||
.split(chunks[0]);
|
||||
|
||||
// right block: preview title + preview
|
||||
let right_chunks = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([Constraint::Length(3), Constraint::Min(10)])
|
||||
.split(chunks[1]);
|
||||
|
||||
(
|
||||
left_chunks[0],
|
||||
left_chunks[1],
|
||||
right_chunks[0],
|
||||
right_chunks[1],
|
||||
)
|
||||
}
|
||||
|
||||
pub fn build_results_list<'a, 'b>(
|
||||
results_block: Block<'b>,
|
||||
entries: &'a [Entry],
|
||||
) -> List<'a>
|
||||
where
|
||||
'b: 'a,
|
||||
{
|
||||
List::new(entries.iter().map(|entry| {
|
||||
let mut spans = Vec::new();
|
||||
// optional icon
|
||||
if let Some(icon) = &entry.icon {
|
||||
spans.push(Span::styled(
|
||||
icon.to_string(),
|
||||
Style::default().fg(Color::from_str(icon.color).unwrap()),
|
||||
));
|
||||
spans.push(Span::raw(" "));
|
||||
}
|
||||
// entry name
|
||||
if let Some(name_match_ranges) = &entry.name_match_ranges {
|
||||
let mut last_match_end = 0;
|
||||
for (start, end) in name_match_ranges
|
||||
.iter()
|
||||
.map(|(s, e)| (*s as usize, *e as usize))
|
||||
{
|
||||
spans.push(Span::styled(
|
||||
slice_at_char_boundaries(
|
||||
&entry.name,
|
||||
last_match_end,
|
||||
start,
|
||||
),
|
||||
Style::default()
|
||||
.fg(DEFAULT_RESULT_NAME_FG)
|
||||
.bold()
|
||||
.italic(),
|
||||
));
|
||||
spans.push(Span::styled(
|
||||
slice_at_char_boundaries(&entry.name, start, end),
|
||||
Style::default().fg(Color::Red).bold().italic(),
|
||||
));
|
||||
last_match_end = end;
|
||||
}
|
||||
spans.push(Span::styled(
|
||||
&entry.name[next_char_boundary(&entry.name, last_match_end)..],
|
||||
Style::default().fg(DEFAULT_RESULT_NAME_FG).bold().italic(),
|
||||
));
|
||||
} else {
|
||||
spans.push(Span::styled(
|
||||
entry.display_name(),
|
||||
Style::default().fg(DEFAULT_RESULT_NAME_FG).bold().italic(),
|
||||
));
|
||||
}
|
||||
// optional line number
|
||||
if let Some(line_number) = entry.line_number {
|
||||
spans.push(Span::styled(
|
||||
format!(":{line_number}"),
|
||||
Style::default().fg(DEFAULT_RESULT_LINE_NUMBER_FG),
|
||||
));
|
||||
}
|
||||
// optional preview
|
||||
if let Some(preview) = &entry.value {
|
||||
spans.push(Span::raw(": "));
|
||||
|
||||
if let Some(preview_match_ranges) = &entry.value_match_ranges {
|
||||
if !preview_match_ranges.is_empty() {
|
||||
let mut last_match_end = 0;
|
||||
for (start, end) in preview_match_ranges
|
||||
.iter()
|
||||
.map(|(s, e)| (*s as usize, *e as usize))
|
||||
{
|
||||
spans.push(Span::styled(
|
||||
slice_at_char_boundaries(
|
||||
preview,
|
||||
last_match_end,
|
||||
start,
|
||||
),
|
||||
Style::default().fg(DEFAULT_RESULT_PREVIEW_FG),
|
||||
));
|
||||
spans.push(Span::styled(
|
||||
slice_at_char_boundaries(preview, start, end),
|
||||
Style::default().fg(Color::Red),
|
||||
));
|
||||
last_match_end = end;
|
||||
}
|
||||
spans.push(Span::styled(
|
||||
&preview[next_char_boundary(
|
||||
preview,
|
||||
preview_match_ranges.last().unwrap().1 as usize,
|
||||
)..],
|
||||
Style::default().fg(DEFAULT_RESULT_PREVIEW_FG),
|
||||
));
|
||||
}
|
||||
} else {
|
||||
spans.push(Span::styled(
|
||||
preview,
|
||||
Style::default().fg(DEFAULT_RESULT_PREVIEW_FG),
|
||||
));
|
||||
}
|
||||
}
|
||||
Line::from(spans)
|
||||
}))
|
||||
.direction(ListDirection::BottomToTop)
|
||||
.highlight_style(Style::default().bg(Color::Rgb(50, 50, 50)))
|
||||
.highlight_symbol("> ")
|
||||
.block(results_block)
|
||||
}
|
||||
|
@ -1,4 +1,5 @@
|
||||
pub mod backend;
|
||||
pub mod actions;
|
||||
|
||||
/// Input requests are used to change the input state.
|
||||
///
|
||||
@ -356,7 +357,7 @@ impl Input {
|
||||
|
||||
/// Get the scroll position with account for multispace characters.
|
||||
pub fn visual_scroll(&self, width: usize) -> usize {
|
||||
let scroll = (self.visual_cursor()).max(width) - width;
|
||||
let scroll = self.visual_cursor().max(width) - width;
|
||||
let mut uscroll = 0;
|
||||
let mut chars = self.value().chars();
|
||||
|
||||
|
30
crates/television/ui/input/actions.rs
Normal file
30
crates/television/ui/input/actions.rs
Normal file
@ -0,0 +1,30 @@
|
||||
use crate::action::Action;
|
||||
use crate::ui::input::{Input, InputRequest, StateChanged};
|
||||
|
||||
/// This makes the `Action` type compatible with the `Input` logic.
|
||||
pub trait InputActionHandler {
|
||||
// Handle Key event.
|
||||
fn handle_action(&mut self, action: &Action) -> Option<StateChanged>;
|
||||
}
|
||||
|
||||
impl InputActionHandler for Input {
|
||||
/// Handle Key event.
|
||||
fn handle_action(&mut self, action: &Action) -> Option<StateChanged> {
|
||||
match action {
|
||||
Action::AddInputChar(c) => {
|
||||
self.handle(InputRequest::InsertChar(*c))
|
||||
}
|
||||
Action::DeletePrevChar => {
|
||||
self.handle(InputRequest::DeletePrevChar)
|
||||
}
|
||||
Action::DeleteNextChar => {
|
||||
self.handle(InputRequest::DeleteNextChar)
|
||||
}
|
||||
Action::GoToPrevChar => self.handle(InputRequest::GoToPrevChar),
|
||||
Action::GoToNextChar => self.handle(InputRequest::GoToNextChar),
|
||||
Action::GoToInputStart => self.handle(InputRequest::GoToStart),
|
||||
Action::GoToInputEnd => self.handle(InputRequest::GoToEnd),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
114
crates/television/ui/layout.rs
Normal file
114
crates/television/ui/layout.rs
Normal file
@ -0,0 +1,114 @@
|
||||
use ratatui::layout;
|
||||
use ratatui::layout::{Constraint, Direction, Rect};
|
||||
|
||||
pub struct Dimensions {
|
||||
pub x: u16,
|
||||
pub y: u16,
|
||||
}
|
||||
|
||||
impl Dimensions {
|
||||
pub fn new(x: u16, y: u16) -> Self {
|
||||
Self { x, y }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Dimensions {
|
||||
fn default() -> Self {
|
||||
Self::new(UI_WIDTH_PERCENT, UI_HEIGHT_PERCENT)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Layout {
|
||||
pub results: Rect,
|
||||
pub input: Rect,
|
||||
pub preview_title: Option<Rect>,
|
||||
pub preview_window: Option<Rect>,
|
||||
}
|
||||
|
||||
impl Layout {
|
||||
pub fn new(
|
||||
results: Rect,
|
||||
input: Rect,
|
||||
preview_title: Option<Rect>,
|
||||
preview_window: Option<Rect>,
|
||||
) -> Self {
|
||||
Self {
|
||||
results,
|
||||
input,
|
||||
preview_title,
|
||||
preview_window,
|
||||
}
|
||||
}
|
||||
|
||||
/// TODO: add diagram
|
||||
pub fn all_panes_centered(dimensions: Dimensions, area: Rect) -> Self {
|
||||
let main_block = centered_rect(dimensions.x, dimensions.y, area);
|
||||
// split the main block into two vertical chunks
|
||||
let chunks = layout::Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([
|
||||
Constraint::Percentage(50),
|
||||
Constraint::Percentage(50),
|
||||
])
|
||||
.split(main_block);
|
||||
|
||||
// left block: results + input field
|
||||
let left_chunks = layout::Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([Constraint::Min(10), Constraint::Length(3)])
|
||||
.split(chunks[0]);
|
||||
|
||||
// right block: preview title + preview
|
||||
let right_chunks = layout::Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([Constraint::Length(3), Constraint::Min(10)])
|
||||
.split(chunks[1]);
|
||||
|
||||
Self::new(
|
||||
left_chunks[0],
|
||||
left_chunks[1],
|
||||
Some(right_chunks[0]),
|
||||
Some(right_chunks[1]),
|
||||
)
|
||||
}
|
||||
|
||||
/// TODO: add diagram
|
||||
pub fn results_only_centered(dimensions: Dimensions, area: Rect) -> Self {
|
||||
let main_block = centered_rect(dimensions.x, dimensions.y, area);
|
||||
// split the main block into two vertical chunks
|
||||
let chunks = layout::Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([Constraint::Min(10), Constraint::Length(3)])
|
||||
.split(main_block);
|
||||
|
||||
Self::new(chunks[0], chunks[1], None, None)
|
||||
}
|
||||
}
|
||||
|
||||
/// helper function to create a centered rect using up certain percentage of the available rect `r`
|
||||
fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
|
||||
// Cut the given rectangle into three vertical pieces
|
||||
let popup_layout = layout::Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Percentage((100 - percent_y) / 2),
|
||||
Constraint::Percentage(percent_y),
|
||||
Constraint::Percentage((100 - percent_y) / 2),
|
||||
])
|
||||
.split(r);
|
||||
|
||||
// Then cut the middle vertical piece into three width-wise pieces
|
||||
layout::Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([
|
||||
Constraint::Percentage((100 - percent_x) / 2),
|
||||
Constraint::Percentage(percent_x),
|
||||
Constraint::Percentage((100 - percent_x) / 2),
|
||||
])
|
||||
.split(popup_layout[1])[1] // Return the middle chunk
|
||||
}
|
||||
|
||||
// UI size
|
||||
const UI_WIDTH_PERCENT: u16 = 90;
|
||||
const UI_HEIGHT_PERCENT: u16 = 90;
|
||||
|
275
crates/television/ui/preview.rs
Normal file
275
crates/television/ui/preview.rs
Normal file
@ -0,0 +1,275 @@
|
||||
use ratatui::prelude::{Color, Line, Modifier, Span, Style, Stylize, Text};
|
||||
use ratatui::widgets::{Block, Paragraph, Wrap};
|
||||
use ratatui::layout::{Alignment, Rect};
|
||||
use std::sync::Arc;
|
||||
use syntect::highlighting::Color as SyntectColor;
|
||||
use crate::previewers::{Preview, PreviewContent, FILE_TOO_LARGE_MSG, PREVIEW_NOT_SUPPORTED_MSG};
|
||||
use crate::television::Television;
|
||||
use crate::utils::strings::{EMPTY_STRING, FOUR_SPACES};
|
||||
|
||||
// preview
|
||||
pub const DEFAULT_PREVIEW_TITLE_FG: Color = Color::Blue;
|
||||
const DEFAULT_SELECTED_PREVIEW_BG: Color = Color::Rgb(50, 50, 50);
|
||||
const DEFAULT_PREVIEW_CONTENT_FG: Color = Color::Rgb(150, 150, 180);
|
||||
const DEFAULT_PREVIEW_GUTTER_FG: Color = Color::Rgb(70, 70, 70);
|
||||
const DEFAULT_PREVIEW_GUTTER_SELECTED_FG: Color = Color::Rgb(255, 150, 150);
|
||||
|
||||
impl Television {
|
||||
const FILL_CHAR_SLANTED: char = '╱';
|
||||
const FILL_CHAR_EMPTY: char = ' ';
|
||||
|
||||
pub fn build_preview_paragraph<'b>(
|
||||
&'b mut self,
|
||||
preview_block: Block<'b>,
|
||||
inner: Rect,
|
||||
preview: &Arc<Preview>,
|
||||
target_line: Option<u16>,
|
||||
) -> Paragraph<'b> {
|
||||
self.maybe_init_preview_scroll(target_line, inner.height);
|
||||
match &preview.content {
|
||||
PreviewContent::PlainText(content) => {
|
||||
let mut lines = Vec::new();
|
||||
for (i, line) in content.iter().enumerate() {
|
||||
lines.push(Line::from(vec![
|
||||
build_line_number_span(i + 1).style(Style::default().fg(
|
||||
// FIXME: this actually might panic in some edge cases
|
||||
if matches!(
|
||||
target_line,
|
||||
Some(l) if l == u16::try_from(i).unwrap() + 1
|
||||
)
|
||||
{
|
||||
DEFAULT_PREVIEW_GUTTER_SELECTED_FG
|
||||
} else {
|
||||
DEFAULT_PREVIEW_GUTTER_FG
|
||||
},
|
||||
)),
|
||||
Span::styled(" │ ",
|
||||
Style::default().fg(DEFAULT_PREVIEW_GUTTER_FG).dim()),
|
||||
Span::styled(
|
||||
line.to_string(),
|
||||
Style::default().fg(DEFAULT_PREVIEW_CONTENT_FG).bg(
|
||||
if matches!(target_line, Some(l) if l == u16::try_from(i).unwrap() + 1) {
|
||||
DEFAULT_SELECTED_PREVIEW_BG
|
||||
} else {
|
||||
Color::Reset
|
||||
},
|
||||
),
|
||||
),
|
||||
]));
|
||||
}
|
||||
let text = Text::from(lines);
|
||||
Paragraph::new(text)
|
||||
.block(preview_block)
|
||||
.scroll((self.preview_scroll.unwrap_or(0), 0))
|
||||
}
|
||||
PreviewContent::PlainTextWrapped(content) => {
|
||||
let mut lines = Vec::new();
|
||||
for line in content.lines() {
|
||||
lines.push(Line::styled(
|
||||
line.to_string(),
|
||||
Style::default().fg(DEFAULT_PREVIEW_CONTENT_FG),
|
||||
));
|
||||
}
|
||||
let text = Text::from(lines);
|
||||
Paragraph::new(text)
|
||||
.block(preview_block)
|
||||
.wrap(Wrap { trim: true })
|
||||
}
|
||||
PreviewContent::HighlightedText(highlighted_lines) => {
|
||||
compute_paragraph_from_highlighted_lines(
|
||||
highlighted_lines,
|
||||
target_line.map(|l| l as usize),
|
||||
self.preview_scroll.unwrap_or(0),
|
||||
self.preview_pane_height,
|
||||
)
|
||||
.block(preview_block)
|
||||
.alignment(Alignment::Left)
|
||||
.scroll((self.preview_scroll.unwrap_or(0), 0))
|
||||
}
|
||||
// meta
|
||||
PreviewContent::Loading => self
|
||||
.build_meta_preview_paragraph(
|
||||
inner,
|
||||
"Loading...",
|
||||
Self::FILL_CHAR_EMPTY,
|
||||
)
|
||||
.block(preview_block)
|
||||
.alignment(Alignment::Left)
|
||||
.style(Style::default().add_modifier(Modifier::ITALIC)),
|
||||
PreviewContent::NotSupported => self
|
||||
.build_meta_preview_paragraph(
|
||||
inner,
|
||||
PREVIEW_NOT_SUPPORTED_MSG,
|
||||
Self::FILL_CHAR_SLANTED,
|
||||
)
|
||||
.block(preview_block)
|
||||
.alignment(Alignment::Left)
|
||||
.style(Style::default().add_modifier(Modifier::ITALIC)),
|
||||
PreviewContent::FileTooLarge => self
|
||||
.build_meta_preview_paragraph(
|
||||
inner,
|
||||
FILE_TOO_LARGE_MSG,
|
||||
Self::FILL_CHAR_SLANTED,
|
||||
)
|
||||
.block(preview_block)
|
||||
.alignment(Alignment::Left)
|
||||
.style(Style::default().add_modifier(Modifier::ITALIC)),
|
||||
_ => Paragraph::new(Text::raw(EMPTY_STRING)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn maybe_init_preview_scroll(
|
||||
&mut self,
|
||||
target_line: Option<u16>,
|
||||
height: u16,
|
||||
) {
|
||||
if self.preview_scroll.is_none() {
|
||||
self.preview_scroll =
|
||||
Some(target_line.unwrap_or(0).saturating_sub(height / 3));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_meta_preview_paragraph<'a>(
|
||||
&mut self,
|
||||
inner: Rect,
|
||||
message: &str,
|
||||
fill_char: char,
|
||||
) -> Paragraph<'a> {
|
||||
if let Some(paragraph) = self.meta_paragraph_cache.get(message) {
|
||||
return paragraph.clone();
|
||||
}
|
||||
let message_len = message.len();
|
||||
let fill_char_str = fill_char.to_string();
|
||||
let fill_line = fill_char_str.repeat(inner.width as usize);
|
||||
|
||||
// Build the paragraph content with slanted lines and center the custom message
|
||||
let mut lines = Vec::new();
|
||||
|
||||
// Calculate the vertical center
|
||||
let vertical_center = inner.height as usize / 2;
|
||||
let horizontal_padding = (inner.width as usize - message_len) / 2 - 4;
|
||||
|
||||
// Fill the paragraph with slanted lines and insert the centered custom message
|
||||
for i in 0..inner.height {
|
||||
if i as usize == vertical_center {
|
||||
// Center the message horizontally in the middle line
|
||||
let line = format!(
|
||||
"{} {} {}",
|
||||
fill_char_str.repeat(horizontal_padding),
|
||||
message,
|
||||
fill_char_str.repeat(
|
||||
inner.width as usize
|
||||
- horizontal_padding
|
||||
- message_len
|
||||
)
|
||||
);
|
||||
lines.push(Line::from(line));
|
||||
} else if i as usize + 1 == vertical_center
|
||||
|| (i as usize).saturating_sub(1) == vertical_center
|
||||
{
|
||||
let line = format!(
|
||||
"{} {} {}",
|
||||
fill_char_str.repeat(horizontal_padding),
|
||||
" ".repeat(message_len),
|
||||
fill_char_str.repeat(
|
||||
inner.width as usize
|
||||
- horizontal_padding
|
||||
- message_len
|
||||
)
|
||||
);
|
||||
lines.push(Line::from(line));
|
||||
} else {
|
||||
lines.push(Line::from(fill_line.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
// Create a paragraph with the generated content
|
||||
let p = Paragraph::new(Text::from(lines));
|
||||
self.meta_paragraph_cache
|
||||
.insert(message.to_string(), p.clone());
|
||||
p
|
||||
}
|
||||
}
|
||||
|
||||
fn build_line_number_span<'a>(line_number: usize) -> Span<'a> {
|
||||
Span::from(format!("{line_number:5} "))
|
||||
}
|
||||
|
||||
fn compute_paragraph_from_highlighted_lines(
|
||||
highlighted_lines: &[Vec<(syntect::highlighting::Style, String)>],
|
||||
line_specifier: Option<usize>,
|
||||
scroll: u16,
|
||||
preview_pane_height: u16,
|
||||
) -> Paragraph<'static> {
|
||||
let preview_lines: Vec<Line> = highlighted_lines
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, l)| {
|
||||
if i < scroll as usize
|
||||
|| i >= (scroll + preview_pane_height) as usize
|
||||
{
|
||||
return Line::from(Span::raw(EMPTY_STRING));
|
||||
}
|
||||
let line_number =
|
||||
build_line_number_span(i + 1).style(Style::default().fg(
|
||||
if line_specifier.is_some()
|
||||
&& i == line_specifier.unwrap() - 1
|
||||
{
|
||||
DEFAULT_PREVIEW_GUTTER_SELECTED_FG
|
||||
} else {
|
||||
DEFAULT_PREVIEW_GUTTER_FG
|
||||
},
|
||||
));
|
||||
Line::from_iter(
|
||||
std::iter::once(line_number)
|
||||
.chain(std::iter::once(Span::styled(
|
||||
" │ ",
|
||||
Style::default().fg(DEFAULT_PREVIEW_GUTTER_FG).dim(),
|
||||
)))
|
||||
.chain(l.iter().cloned().map(|sr| {
|
||||
convert_syn_region_to_span(
|
||||
&(sr.0, sr.1.replace('\t', FOUR_SPACES)),
|
||||
if line_specifier.is_some()
|
||||
&& i == line_specifier.unwrap() - 1
|
||||
{
|
||||
Some(SyntectColor {
|
||||
r: 50,
|
||||
g: 50,
|
||||
b: 50,
|
||||
a: 255,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
},
|
||||
)
|
||||
})),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
Paragraph::new(preview_lines)
|
||||
}
|
||||
|
||||
fn convert_syn_region_to_span<'a>(
|
||||
syn_region: &(syntect::highlighting::Style, String),
|
||||
background: Option<syntect::highlighting::Color>,
|
||||
) -> Span<'a> {
|
||||
let mut style = Style::default()
|
||||
.fg(convert_syn_color_to_ratatui_color(syn_region.0.foreground));
|
||||
if let Some(background) = background {
|
||||
style = style.bg(convert_syn_color_to_ratatui_color(background));
|
||||
}
|
||||
style = match syn_region.0.font_style {
|
||||
syntect::highlighting::FontStyle::BOLD => style.bold(),
|
||||
syntect::highlighting::FontStyle::ITALIC => style.italic(),
|
||||
syntect::highlighting::FontStyle::UNDERLINE => style.underlined(),
|
||||
_ => style,
|
||||
};
|
||||
Span::styled(syn_region.1.clone(), style)
|
||||
}
|
||||
|
||||
fn convert_syn_color_to_ratatui_color(
|
||||
color: syntect::highlighting::Color,
|
||||
) -> ratatui::style::Color {
|
||||
ratatui::style::Color::Rgb(color.r, color.g, color.b)
|
||||
}
|
116
crates/television/ui/results.rs
Normal file
116
crates/television/ui/results.rs
Normal file
@ -0,0 +1,116 @@
|
||||
use ratatui::prelude::{Color, Line, Span, Style, Stylize};
|
||||
use ratatui::widgets::{Block, List, ListDirection};
|
||||
use std::str::FromStr;
|
||||
use crate::entry::Entry;
|
||||
use crate::utils::strings::{next_char_boundary, slice_at_char_boundaries};
|
||||
|
||||
// Styles
|
||||
const DEFAULT_RESULT_NAME_FG: Color = Color::Blue;
|
||||
const DEFAULT_RESULT_PREVIEW_FG: Color = Color::Rgb(150, 150, 150);
|
||||
const DEFAULT_RESULT_LINE_NUMBER_FG: Color = Color::Yellow;
|
||||
|
||||
pub fn build_results_list<'a, 'b>(
|
||||
results_block: Block<'b>,
|
||||
entries: &'a [Entry],
|
||||
) -> List<'a>
|
||||
where
|
||||
'b: 'a,
|
||||
{
|
||||
List::new(entries.iter().map(|entry| {
|
||||
let mut spans = Vec::new();
|
||||
// optional icon
|
||||
if let Some(icon) = &entry.icon {
|
||||
spans.push(Span::styled(
|
||||
icon.to_string(),
|
||||
Style::default().fg(Color::from_str(icon.color).unwrap()),
|
||||
));
|
||||
spans.push(Span::raw(" "));
|
||||
}
|
||||
// entry name
|
||||
if let Some(name_match_ranges) = &entry.name_match_ranges {
|
||||
let mut last_match_end = 0;
|
||||
for (start, end) in name_match_ranges
|
||||
.iter()
|
||||
.map(|(s, e)| (*s as usize, *e as usize))
|
||||
{
|
||||
spans.push(Span::styled(
|
||||
slice_at_char_boundaries(
|
||||
&entry.name,
|
||||
last_match_end,
|
||||
start,
|
||||
),
|
||||
Style::default()
|
||||
.fg(DEFAULT_RESULT_NAME_FG)
|
||||
.bold()
|
||||
.italic(),
|
||||
));
|
||||
spans.push(Span::styled(
|
||||
slice_at_char_boundaries(&entry.name, start, end),
|
||||
Style::default().fg(Color::Red).bold().italic(),
|
||||
));
|
||||
last_match_end = end;
|
||||
}
|
||||
spans.push(Span::styled(
|
||||
&entry.name[next_char_boundary(&entry.name, last_match_end)..],
|
||||
Style::default().fg(DEFAULT_RESULT_NAME_FG).bold().italic(),
|
||||
));
|
||||
} else {
|
||||
spans.push(Span::styled(
|
||||
entry.display_name(),
|
||||
Style::default().fg(DEFAULT_RESULT_NAME_FG).bold().italic(),
|
||||
));
|
||||
}
|
||||
// optional line number
|
||||
if let Some(line_number) = entry.line_number {
|
||||
spans.push(Span::styled(
|
||||
format!(":{line_number}"),
|
||||
Style::default().fg(DEFAULT_RESULT_LINE_NUMBER_FG),
|
||||
));
|
||||
}
|
||||
// optional preview
|
||||
if let Some(preview) = &entry.value {
|
||||
spans.push(Span::raw(": "));
|
||||
|
||||
if let Some(preview_match_ranges) = &entry.value_match_ranges {
|
||||
if !preview_match_ranges.is_empty() {
|
||||
let mut last_match_end = 0;
|
||||
for (start, end) in preview_match_ranges
|
||||
.iter()
|
||||
.map(|(s, e)| (*s as usize, *e as usize))
|
||||
{
|
||||
spans.push(Span::styled(
|
||||
slice_at_char_boundaries(
|
||||
preview,
|
||||
last_match_end,
|
||||
start,
|
||||
),
|
||||
Style::default().fg(DEFAULT_RESULT_PREVIEW_FG),
|
||||
));
|
||||
spans.push(Span::styled(
|
||||
slice_at_char_boundaries(preview, start, end),
|
||||
Style::default().fg(Color::Red),
|
||||
));
|
||||
last_match_end = end;
|
||||
}
|
||||
spans.push(Span::styled(
|
||||
&preview[next_char_boundary(
|
||||
preview,
|
||||
preview_match_ranges.last().unwrap().1 as usize,
|
||||
)..],
|
||||
Style::default().fg(DEFAULT_RESULT_PREVIEW_FG),
|
||||
));
|
||||
}
|
||||
} else {
|
||||
spans.push(Span::styled(
|
||||
preview,
|
||||
Style::default().fg(DEFAULT_RESULT_PREVIEW_FG),
|
||||
));
|
||||
}
|
||||
}
|
||||
Line::from(spans)
|
||||
}))
|
||||
.direction(ListDirection::BottomToTop)
|
||||
.highlight_style(Style::default().bg(Color::Rgb(50, 50, 50)))
|
||||
.highlight_symbol("> ")
|
||||
.block(results_block)
|
||||
}
|
@ -1,4 +1,3 @@
|
||||
pub mod files;
|
||||
pub mod indices;
|
||||
pub mod strings;
|
||||
pub mod ui;
|
||||
|
@ -52,6 +52,9 @@ lazy_static! {
|
||||
static ref NULL_SYMBOL: char = char::from_u32(0x2400).unwrap();
|
||||
}
|
||||
|
||||
pub const EMPTY_STRING: &str = "";
|
||||
pub const FOUR_SPACES: &str = " ";
|
||||
|
||||
const SPACE_CHARACTER: char = ' ';
|
||||
const TAB_CHARACTER: char = '\t';
|
||||
const LINE_FEED_CHARACTER: char = '\x0A';
|
||||
|
@ -1,24 +0,0 @@
|
||||
use ratatui::layout::{Constraint, Direction, Layout, Rect};
|
||||
|
||||
/// helper function to create a centered rect using up certain percentage of the available rect `r`
|
||||
pub fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
|
||||
// Cut the given rectangle into three vertical pieces
|
||||
let popup_layout = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Percentage((100 - percent_y) / 2),
|
||||
Constraint::Percentage(percent_y),
|
||||
Constraint::Percentage((100 - percent_y) / 2),
|
||||
])
|
||||
.split(r);
|
||||
|
||||
// Then cut the middle vertical piece into three width-wise pieces
|
||||
Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([
|
||||
Constraint::Percentage((100 - percent_x) / 2),
|
||||
Constraint::Percentage(percent_x),
|
||||
Constraint::Percentage((100 - percent_x) / 2),
|
||||
])
|
||||
.split(popup_layout[1])[1] // Return the middle chunk
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user