formatting

This commit is contained in:
alexpasmantier 2024-10-27 23:31:40 +01:00
parent 8223e073a0
commit ddedbc11da
18 changed files with 86 additions and 68 deletions

View File

@ -52,7 +52,6 @@
*/ */
use std::sync::Arc; use std::sync::Arc;
use color_eyre::Result; use color_eyre::Result;
use tokio::sync::{mpsc, Mutex}; use tokio::sync::{mpsc, Mutex};
use tracing::{debug, info}; use tracing::{debug, info};
@ -133,7 +132,7 @@ impl App {
frame_rate, frame_rate,
is_output_tty, is_output_tty,
) )
.await .await
}); });
// event handling loop // event handling loop

View File

@ -51,10 +51,7 @@ fn get_raw_aliases(shell: &str) -> Vec<String> {
.output() .output()
.expect("failed to execute process"); .expect("failed to execute process");
let aliases = String::from_utf8(output.stdout).unwrap(); let aliases = String::from_utf8(output.stdout).unwrap();
aliases aliases.lines().map(ToString::to_string).collect()
.lines()
.map(ToString::to_string)
.collect()
} }
"zsh" => { "zsh" => {
let output = std::process::Command::new("zsh") let output = std::process::Command::new("zsh")
@ -64,10 +61,7 @@ fn get_raw_aliases(shell: &str) -> Vec<String> {
.output() .output()
.expect("failed to execute process"); .expect("failed to execute process");
let aliases = String::from_utf8(output.stdout).unwrap(); let aliases = String::from_utf8(output.stdout).unwrap();
aliases aliases.lines().map(ToString::to_string).collect()
.lines()
.map(ToString::to_string)
.collect()
} }
// TODO: add more shells // TODO: add more shells
_ => Vec::new(), _ => Vec::new(),
@ -134,7 +128,7 @@ impl OnAir for Channel {
.matched_items( .matched_items(
offset offset
..(num_entries + offset) ..(num_entries + offset)
.min(snapshot.matched_item_count()), .min(snapshot.matched_item_count()),
) )
.map(move |item| { .map(move |item| {
snapshot.pattern().column_pattern(0).indices( snapshot.pattern().column_pattern(0).indices(

View File

@ -40,9 +40,15 @@ impl Channel {
); );
let injector = matcher.injector(); let injector = matcher.injector();
for (name, value) in std::env::vars() { for (name, value) in std::env::vars() {
let _ = injector.push(EnvVar { name: preprocess_line(&name), value: preprocess_line(&value) }, |e, cols| { let _ = injector.push(
cols[0] = (e.name.clone() + &e.value).into(); EnvVar {
}); name: preprocess_line(&name),
value: preprocess_line(&value),
},
|e, cols| {
cols[0] = (e.name.clone() + &e.value).into();
},
);
} }
Channel { Channel {
matcher, matcher,
@ -93,7 +99,7 @@ impl OnAir for Channel {
.matched_items( .matched_items(
offset offset
..(num_entries + offset) ..(num_entries + offset)
.min(snapshot.matched_item_count()), .min(snapshot.matched_item_count()),
) )
.map(move |item| { .map(move |item| {
snapshot.pattern().column_pattern(0).indices( snapshot.pattern().column_pattern(0).indices(

View File

@ -98,7 +98,7 @@ impl OnAir for Channel {
.matched_items( .matched_items(
offset offset
..(num_entries + offset) ..(num_entries + offset)
.min(snapshot.matched_item_count()), .min(snapshot.matched_item_count()),
) )
.map(move |item| { .map(move |item| {
snapshot.pattern().column_pattern(0).indices( snapshot.pattern().column_pattern(0).indices(
@ -165,7 +165,13 @@ async fn load_files(paths: Vec<PathBuf>, injector: Injector<String>) {
Box::new(move |result| { Box::new(move |result| {
if let Ok(entry) = result { if let Ok(entry) = result {
if entry.file_type().unwrap().is_file() { if entry.file_type().unwrap().is_file() {
let file_path = preprocess_line(&*entry.path().strip_prefix(&current_dir).unwrap().to_string_lossy()); let file_path = preprocess_line(
&*entry
.path()
.strip_prefix(&current_dir)
.unwrap()
.to_string_lossy(),
);
let _ = injector.push(file_path, |e, cols| { let _ = injector.push(file_path, |e, cols| {
cols[0] = e.clone().into(); cols[0] = e.clone().into();
}); });

View File

@ -90,7 +90,7 @@ impl OnAir for Channel {
.matched_items( .matched_items(
offset offset
..(num_entries + offset) ..(num_entries + offset)
.min(snapshot.matched_item_count()), .min(snapshot.matched_item_count()),
) )
.map(move |item| { .map(move |item| {
snapshot.pattern().column_pattern(0).indices( snapshot.pattern().column_pattern(0).indices(
@ -197,7 +197,7 @@ async fn crawl_for_repos(
Some(walker_overrides_builder.build().unwrap()), Some(walker_overrides_builder.build().unwrap()),
Some(get_ignored_paths()), Some(get_ignored_paths()),
) )
.build_parallel(); .build_parallel();
walker.run(|| { walker.run(|| {
let injector = injector.clone(); let injector = injector.clone();
@ -206,11 +206,9 @@ async fn crawl_for_repos(
if entry.file_type().unwrap().is_dir() { if entry.file_type().unwrap().is_dir() {
// if the entry is a .git directory, add its parent to the list of git repos // if the entry is a .git directory, add its parent to the list of git repos
if entry.path().ends_with(".git") { if entry.path().ends_with(".git") {
let parent_path = preprocess_line(&*entry let parent_path = preprocess_line(
.path() &*entry.path().parent().unwrap().to_string_lossy(),
.parent() );
.unwrap()
.to_string_lossy());
debug!("Found git repo: {:?}", parent_path); debug!("Found git repo: {:?}", parent_path);
let _ = injector.push(parent_path, |e, cols| { let _ = injector.push(parent_path, |e, cols| {
cols[0] = e.clone().into(); cols[0] = e.clone().into();

View File

@ -90,7 +90,7 @@ impl OnAir for Channel {
.matched_items( .matched_items(
offset offset
..(num_entries + offset) ..(num_entries + offset)
.min(snapshot.matched_item_count()), .min(snapshot.matched_item_count()),
) )
.map(move |item| { .map(move |item| {
snapshot.pattern().column_pattern(0).indices( snapshot.pattern().column_pattern(0).indices(

View File

@ -153,8 +153,7 @@ impl EventLoop {
pub fn new(tick_rate: f64, init: bool) -> Self { pub fn new(tick_rate: f64, init: bool) -> Self {
let (tx, rx) = mpsc::unbounded_channel(); let (tx, rx) = mpsc::unbounded_channel();
let tx_c = tx.clone(); let tx_c = tx.clone();
let tick_interval = let tick_interval = Duration::from_secs_f64(1.0 / tick_rate);
Duration::from_secs_f64(1.0 / tick_rate);
let (abort, mut abort_recv) = mpsc::unbounded_channel(); let (abort, mut abort_recv) = mpsc::unbounded_channel();

View File

@ -81,7 +81,7 @@ impl FilePreviewer {
entry.name.clone(), entry.name.clone(),
preview.clone(), preview.clone(),
) )
.await; .await;
// compute the highlighted version in the background // compute the highlighted version in the background
let mut reader = let mut reader =
@ -164,10 +164,11 @@ impl FilePreviewer {
"Computing highlights in the background for {:?}", "Computing highlights in the background for {:?}",
entry_c.name entry_c.name
); );
let lines: Vec<String> = let lines: Vec<String> = reader
reader.lines().map_while(Result::ok).map( .lines()
|line| preprocess_line(&line), .map_while(Result::ok)
).collect(); .map(|line| preprocess_line(&line))
.collect();
match syntax::compute_highlights_for_path( match syntax::compute_highlights_for_path(
&PathBuf::from(&entry_c.name), &PathBuf::from(&entry_c.name),
@ -227,8 +228,8 @@ impl FilePreviewer {
if let Ok(bytes_read) = f.read(&mut buffer) { if let Ok(bytes_read) = f.read(&mut buffer) {
if bytes_read > 0 if bytes_read > 0
&& proportion_of_printable_ascii_characters( && proportion_of_printable_ascii_characters(
&buffer[..bytes_read], &buffer[..bytes_read],
) > PRINTABLE_ASCII_THRESHOLD ) > PRINTABLE_ASCII_THRESHOLD
{ {
file_type = FileType::Text; file_type = FileType::Text;
} }

View File

@ -377,8 +377,9 @@ impl Television {
// bottom left block: input // bottom left block: input
self.draw_input_box(f, &layout)?; self.draw_input_box(f, &layout)?;
let selected_entry = let selected_entry = self
self.get_selected_entry(Some(Mode::Channel)).unwrap_or(ENTRY_PLACEHOLDER); .get_selected_entry(Some(Mode::Channel))
.unwrap_or(ENTRY_PLACEHOLDER);
let preview = block_on(self.previewer.preview(&selected_entry)); let preview = block_on(self.previewer.preview(&selected_entry));
// top right block: preview title // top right block: preview title

View File

@ -6,11 +6,11 @@ pub mod keymap;
pub mod layout; pub mod layout;
pub mod logo; pub mod logo;
pub mod metadata; pub mod metadata;
mod mode;
pub mod preview; pub mod preview;
mod remote_control; mod remote_control;
pub mod results; pub mod results;
pub mod spinner; pub mod spinner;
mod mode;
// input // input
//const DEFAULT_INPUT_FG: Color = Color::Rgb(200, 200, 200); //const DEFAULT_INPUT_FG: Color = Color::Rgb(200, 200, 200);
//const DEFAULT_RESULTS_COUNT_FG: Color = Color::Rgb(150, 150, 150); //const DEFAULT_RESULTS_COUNT_FG: Color = Color::Rgb(150, 150, 150);

View File

@ -80,8 +80,11 @@ impl Television {
// MISC line (quit, help, etc.) // MISC line (quit, help, etc.)
// Quit ⏼ // Quit ⏼
let quit_keys = keys_for_action(keymap, &Action::Quit); let quit_keys = keys_for_action(keymap, &Action::Quit);
let quit_row = let quit_row = Row::new(build_cells_for_key_groups(
Row::new(build_cells_for_key_groups("⏼ Quit", vec![quit_keys], key_color)); "⏼ Quit",
vec![quit_keys],
key_color,
));
let widths = vec![Constraint::Fill(1), Constraint::Fill(2)]; let widths = vec![Constraint::Fill(1), Constraint::Fill(2)];
@ -132,8 +135,11 @@ impl Television {
// Quit // Quit
let quit_keys = keys_for_action(keymap, &Action::Quit); let quit_keys = keys_for_action(keymap, &Action::Quit);
let quit_row = let quit_row = Row::new(build_cells_for_key_groups(
Row::new(build_cells_for_key_groups("⏼ Quit", vec![quit_keys], key_color)); "⏼ Quit",
vec![quit_keys],
key_color,
));
Ok(Table::new( Ok(Table::new(
vec![results_row, select_entry_row, switch_channels_row, quit_row], vec![results_row, select_entry_row, switch_channels_row, quit_row],
@ -185,8 +191,7 @@ fn build_cells_for_key_groups(
key_groups: Vec<Vec<String>>, key_groups: Vec<Vec<String>>,
key_color: Color, key_color: Color,
) -> Vec<Cell> { ) -> Vec<Cell> {
if key_groups.is_empty() || key_groups.iter().all(Vec::is_empty) if key_groups.is_empty() || key_groups.iter().all(Vec::is_empty) {
{
return vec![group_name.into(), "No keybindings".into()]; return vec![group_name.into(), "No keybindings".into()];
} }
let non_empty_groups = key_groups.iter().filter(|keys| !keys.is_empty()); let non_empty_groups = key_groups.iter().filter(|keys| !keys.is_empty());

View File

@ -8,7 +8,6 @@ use ratatui::{
use crate::television::Television; use crate::television::Television;
use crate::ui::mode::mode_color; use crate::ui::mode::mode_color;
const METADATA_FIELD_NAME_COLOR: Color = Color::DarkGray; const METADATA_FIELD_NAME_COLOR: Color = Color::DarkGray;
const METADATA_FIELD_VALUE_COLOR: Color = Color::Gray; const METADATA_FIELD_VALUE_COLOR: Color = Color::Gray;

View File

@ -5,11 +5,10 @@ const CHANNEL_COLOR: Color = Color::LightYellow;
const REMOTE_CONTROL_COLOR: Color = Color::LightMagenta; const REMOTE_CONTROL_COLOR: Color = Color::LightMagenta;
const SEND_TO_CHANNEL_COLOR: Color = Color::LightCyan; const SEND_TO_CHANNEL_COLOR: Color = Color::LightCyan;
pub fn mode_color(mode: Mode) -> Color { pub fn mode_color(mode: Mode) -> Color {
match mode { match mode {
Mode::Channel => CHANNEL_COLOR, Mode::Channel => CHANNEL_COLOR,
Mode::RemoteControl => REMOTE_CONTROL_COLOR, Mode::RemoteControl => REMOTE_CONTROL_COLOR,
Mode::SendToChannel => SEND_TO_CHANNEL_COLOR, Mode::SendToChannel => SEND_TO_CHANNEL_COLOR,
} }
} }

View File

@ -174,9 +174,9 @@ impl Television {
self.preview_scroll.unwrap_or(0), self.preview_scroll.unwrap_or(0),
self.preview_pane_height, self.preview_pane_height,
) )
.block(preview_block) .block(preview_block)
.alignment(Alignment::Left) .alignment(Alignment::Left)
.scroll((self.preview_scroll.unwrap_or(0), 0)) .scroll((self.preview_scroll.unwrap_or(0), 0))
} }
// meta // meta
PreviewContent::Loading => self PreviewContent::Loading => self

View File

@ -28,7 +28,7 @@ impl Television {
Constraint::Length(3), Constraint::Length(3),
Constraint::Length(20), Constraint::Length(20),
] ]
.as_ref(), .as_ref(),
) )
.split(*area); .split(*area);
self.draw_rc_channels(f, &layout[0])?; self.draw_rc_channels(f, &layout[0])?;
@ -56,8 +56,15 @@ impl Television {
u32::try_from(self.rc_picker.view_offset)?, u32::try_from(self.rc_picker.view_offset)?,
); );
let channel_list = let channel_list = build_results_list(
build_results_list(rc_block, &entries, ListDirection::TopToBottom, Some(ResultsListColors::default().result_name_fg(mode_color(self.mode)))); rc_block,
&entries,
ListDirection::TopToBottom,
Some(
ResultsListColors::default()
.result_name_fg(mode_color(self.mode)),
),
);
f.render_stateful_widget( f.render_stateful_widget(
channel_list, channel_list,
@ -99,7 +106,7 @@ impl Television {
.fg(crate::television::DEFAULT_INPUT_FG) .fg(crate::television::DEFAULT_INPUT_FG)
.bold(), .bold(),
)) ))
.block(prompt_symbol_block); .block(prompt_symbol_block);
f.render_widget(arrow, inner_input_chunks[0]); f.render_widget(arrow, inner_input_chunks[0]);
let interactive_input_block = Block::default(); let interactive_input_block = Block::default();
@ -124,8 +131,8 @@ impl Television {
// Put cursor past the end of the input text // Put cursor past the end of the input text
inner_input_chunks[1].x inner_input_chunks[1].x
+ u16::try_from( + u16::try_from(
self.rc_picker.input.visual_cursor().max(scroll) - scroll, self.rc_picker.input.visual_cursor().max(scroll) - scroll,
)?, )?,
// Move one line down, from the border to the input line // Move one line down, from the border to the input line
inner_input_chunks[1].y, inner_input_chunks[1].y,
)); ));
@ -134,8 +141,7 @@ impl Television {
} }
fn draw_rc_logo(f: &mut Frame, area: Rect, color: Color) { fn draw_rc_logo(f: &mut Frame, area: Rect, color: Color) {
let logo_block = Block::default() let logo_block = Block::default().style(Style::default().fg(color));
.style(Style::default().fg(color));
let logo_paragraph = build_remote_logo_paragraph() let logo_paragraph = build_remote_logo_paragraph()
.alignment(Alignment::Center) .alignment(Alignment::Center)

View File

@ -134,7 +134,8 @@ where
last_match_end, last_match_end,
start, start,
), ),
Style::default().fg(results_list_colors.result_preview_fg), Style::default()
.fg(results_list_colors.result_preview_fg),
)); ));
spans.push(Span::styled( spans.push(Span::styled(
slice_at_char_boundaries(preview, start, end), slice_at_char_boundaries(preview, start, end),
@ -147,7 +148,8 @@ where
preview, preview,
preview_match_ranges.last().unwrap().1 as usize, preview_match_ranges.last().unwrap().1 as usize,
)..], )..],
Style::default().fg(results_list_colors.result_preview_fg), Style::default()
.fg(results_list_colors.result_preview_fg),
)); ));
} }
} else { } else {
@ -159,10 +161,12 @@ where
} }
Line::from(spans) Line::from(spans)
})) }))
.direction(list_direction) .direction(list_direction)
.highlight_style(Style::default().bg(results_list_colors.result_selected_bg)) .highlight_style(
.highlight_symbol("> ") Style::default().bg(results_list_colors.result_selected_bg),
.block(results_block) )
.highlight_symbol("> ")
.block(results_block)
} }
impl Television { impl Television {

View File

@ -138,8 +138,8 @@ pub fn preprocess_line(line: &str) -> String {
line line
} }
} }
.trim_end_matches(['\r', '\n', '\0']) .trim_end_matches(['\r', '\n', '\0'])
.as_bytes(), .as_bytes(),
TAB_WIDTH, TAB_WIDTH,
) )
} }
@ -175,8 +175,7 @@ mod tests {
test_replace_nonprintable("Hello\tWorld!", "Hello World!"); test_replace_nonprintable("Hello\tWorld!", "Hello World!");
test_replace_nonprintable( test_replace_nonprintable(
" -- AND " -- AND
", ", " -- AND",
" -- AND",
) )
} }

View File

@ -36,7 +36,9 @@ pub fn cli_channel_derive(input: TokenStream) -> TokenStream {
} }
fn has_exclude_attr(attrs: &[syn::Attribute]) -> bool { fn has_exclude_attr(attrs: &[syn::Attribute]) -> bool {
attrs.iter().any(|attr| attr.path().is_ident("exclude_from_cli")) attrs
.iter()
.any(|attr| attr.path().is_ident("exclude_from_cli"))
} }
fn impl_cli_channel(ast: &syn::DeriveInput) -> TokenStream { fn impl_cli_channel(ast: &syn::DeriveInput) -> TokenStream {