diff options
| author | Aram Drevekenin <aram@poor.dev> | 2024-03-18 09:19:58 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-03-18 09:19:58 +0100 |
| commit | ee16a4b8c347a81878389fd4f90144c2c6357f41 (patch) | |
| tree | bf8675d57499b6278e8c89b84c8141969cc2ce3f /default-plugins/strider/src | |
| parent | docs(changelog): switch session cwd (diff) | |
| download | sl0ppij-ee16a4b8c347a81878389fd4f90144c2c6357f41.tar.gz sl0ppij-ee16a4b8c347a81878389fd4f90144c2c6357f41.tar.xz sl0ppij-ee16a4b8c347a81878389fd4f90144c2c6357f41.zip | |
feat(plugins): session manager cwd and new filepicker (#3200)
* prototype
* folder selection ui in session manager
* overhaul strider
* scan folder host command
* get strider to work from the cli and some cli pipe fixes
* some ux improvements to strider
* improve strider's ui
* make strider ui responsive
* make session-manager new ui parts responsive
* fix tests
* style(fmt): rustfmt
Diffstat (limited to 'default-plugins/strider/src')
| -rw-r--r-- | default-plugins/strider/src/file_list_view.rs | 191 | ||||
| -rw-r--r-- | default-plugins/strider/src/main.rs | 224 | ||||
| -rw-r--r-- | default-plugins/strider/src/search_view.rs | 134 | ||||
| -rw-r--r-- | default-plugins/strider/src/shared.rs | 156 | ||||
| -rw-r--r-- | default-plugins/strider/src/state.rs | 243 |
5 files changed, 754 insertions, 194 deletions
diff --git a/default-plugins/strider/src/file_list_view.rs b/default-plugins/strider/src/file_list_view.rs new file mode 100644 index 00000000..e16c66b3 --- /dev/null +++ b/default-plugins/strider/src/file_list_view.rs @@ -0,0 +1,191 @@ +use crate::shared::{calculate_list_bounds, render_list_tip}; +use crate::state::{refresh_directory, ROOT}; +use pretty_bytes::converter::convert as pretty_bytes; +use std::collections::HashMap; +use std::path::PathBuf; +use unicode_width::UnicodeWidthStr; +use zellij_tile::prelude::*; + +#[derive(Debug, Clone)] +pub struct FileListView { + pub path: PathBuf, + pub path_is_dir: bool, + pub files: Vec<FsEntry>, + pub cursor_hist: HashMap<PathBuf, usize>, +} + +impl Default for FileListView { + fn default() -> Self { + FileListView { + path_is_dir: true, + path: Default::default(), + files: Default::default(), + cursor_hist: Default::default(), + } + } +} + +impl FileListView { + pub fn descend_to_previous_path(&mut self) { + self.path.pop(); + self.path_is_dir = true; + self.files.clear(); + self.reset_selected(); + refresh_directory(&self.path); + } + pub fn descend_to_root_path(&mut self) { + self.path.clear(); + self.path_is_dir = true; + self.files.clear(); + self.reset_selected(); + refresh_directory(&self.path); + } + pub fn enter_dir(&mut self, entry: &FsEntry) { + let is_dir = entry.is_folder(); + let path = entry.get_pathbuf_without_root_prefix(); + self.path = path; + self.path_is_dir = is_dir; + self.files.clear(); + self.reset_selected(); + } + pub fn reset_selected(&mut self) { + *self.selected_mut() = self.selected().unwrap_or(0); + } + pub fn update_files( + &mut self, + paths: Vec<(PathBuf, Option<FileMetadata>)>, + hide_hidden_files: bool, + ) { + let mut files = vec![]; + for (entry, entry_metadata) in paths { + if entry_metadata.map(|e| e.is_symlink).unwrap_or(false) { + continue; // ignore symlinks + } + let entry = if entry_metadata.map(|e| e.is_dir).unwrap_or(false) { + FsEntry::Dir(entry) + } else { + let size = entry_metadata.map(|e| e.len).unwrap_or(0); + FsEntry::File(entry, size) + }; + if !entry.is_hidden_file() || !hide_hidden_files { + files.push(entry); + } + } + self.files = files; + self.files.sort_unstable(); + } + pub fn get_selected_entry(&self) -> Option<FsEntry> { + self.selected().and_then(|f| self.files.get(f).cloned()) + } + pub fn selected_mut(&mut self) -> &mut usize { + self.cursor_hist.entry(self.path.clone()).or_default() + } + pub fn selected(&self) -> Option<usize> { + self.cursor_hist.get(&self.path).copied() + } + pub fn move_selection_up(&mut self) { + if let Some(selected) = self.selected() { + *self.selected_mut() = selected.saturating_sub(1); + } + } + pub fn move_selection_down(&mut self) { + if let Some(selected) = self.selected() { + let next = selected.saturating_add(1); + *self.selected_mut() = std::cmp::min(self.files.len().saturating_sub(1), next); + } else { + *self.selected_mut() = 0; + } + } + pub fn render(&mut self, rows: usize, cols: usize) { + let (start_index, selected_index_in_range, end_index) = + calculate_list_bounds(self.files.len(), rows.saturating_sub(1), self.selected()); + + render_list_tip(3, cols); + for i in start_index..end_index { + if let Some(entry) = self.files.get(i) { + let is_selected = Some(i) == selected_index_in_range; + let mut file_or_folder_name = entry.name(); + let size = entry + .size() + .map(|s| pretty_bytes(s as f64)) + .unwrap_or("".to_owned()); + if entry.is_folder() { + file_or_folder_name.push('/'); + } + let file_or_folder_name_width = file_or_folder_name.width(); + let size_width = size.width(); + let text = if file_or_folder_name_width + size_width < cols { + let padding = " ".repeat( + cols.saturating_sub(file_or_folder_name_width) + .saturating_sub(size_width), + ); + format!("{}{}{}", file_or_folder_name, padding, size) + } else { + // drop the size, no room for it + let padding = " ".repeat(cols.saturating_sub(file_or_folder_name_width)); + format!("{}{}", file_or_folder_name, padding) + }; + let mut text_element = if is_selected { + Text::new(text).selected() + } else { + Text::new(text) + }; + if entry.is_folder() { + text_element = text_element.color_range(0, ..); + } + print_text_with_coordinates( + text_element, + 0, + 4 + i.saturating_sub(start_index), + Some(cols), + None, + ); + } + } + } +} + +#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)] +pub enum FsEntry { + Dir(PathBuf), + File(PathBuf, u64), +} + +impl FsEntry { + pub fn name(&self) -> String { + let path = match self { + FsEntry::Dir(p) => p, + FsEntry::File(p, _) => p, + }; + path.file_name().unwrap().to_string_lossy().into_owned() + } + pub fn size(&self) -> Option<u64> { + match self { + FsEntry::Dir(p) => None, + FsEntry::File(_, size) => Some(*size), + } + } + pub fn get_pathbuf_without_root_prefix(&self) -> PathBuf { + match self { + FsEntry::Dir(p) => p + .strip_prefix(ROOT) + .map(|p| p.to_path_buf()) + .unwrap_or_else(|_| p.clone()), + FsEntry::File(p, _) => p + .strip_prefix(ROOT) + .map(|p| p.to_path_buf()) + .unwrap_or_else(|_| p.clone()), + } + } + + pub fn is_hidden_file(&self) -> bool { + self.name().starts_with('.') + } + + pub fn is_folder(&self) -> bool { + match self { + FsEntry::Dir(_) => true, + _ => false, + } + } +} diff --git a/default-plugins/strider/src/main.rs b/default-plugins/strider/src/main.rs index 1ad2e70c..ce9a5273 100644 --- a/default-plugins/strider/src/main.rs +++ b/default-plugins/strider/src/main.rs @@ -1,121 +1,122 @@ +mod file_list_view; +mod search_view; +mod shared; mod state; -use colored::*; -use state::{refresh_directory, FsEntry, State}; +use crate::file_list_view::FsEntry; +use shared::{render_current_path, render_instruction_line, render_search_term}; +use state::{refresh_directory, State}; use std::collections::BTreeMap; -use std::{cmp::min, time::Instant}; +use std::path::PathBuf; use zellij_tile::prelude::*; register_plugin!(State); impl ZellijPlugin for State { - fn load(&mut self, _configuration: BTreeMap<String, String>) { - refresh_directory(self); + fn load(&mut self, configuration: BTreeMap<String, String>) { + let plugin_ids = get_plugin_ids(); + self.initial_cwd = plugin_ids.initial_cwd; + let show_hidden_files = configuration + .get("show_hidden_files") + .map(|v| v == "true") + .unwrap_or(false); + self.hide_hidden_files = !show_hidden_files; + self.close_on_selection = configuration + .get("close_on_selection") + .map(|v| v == "true") + .unwrap_or(false); subscribe(&[ EventType::Key, EventType::Mouse, EventType::CustomMessage, EventType::Timer, + EventType::FileSystemUpdate, ]); + self.file_list_view.reset_selected(); + // the caller_cwd might be different from the initial_cwd if this plugin was defined as an + // alias, with access to a certain part of the file system (often broader) and was called + // from an individual pane somewhere inside this broad scope - in this case, we want to + // start in the same cwd as the caller, giving them the full access we were granted + match configuration + .get("caller_cwd") + .map(|c| PathBuf::from(c)) + .and_then(|c| { + c.strip_prefix(&self.initial_cwd) + .ok() + .map(|c| PathBuf::from(c)) + }) { + Some(relative_caller_path) => { + let relative_caller_path = FsEntry::Dir(relative_caller_path.to_path_buf()); + self.file_list_view.enter_dir(&relative_caller_path); + refresh_directory(&self.file_list_view.path); + }, + None => { + refresh_directory(&std::path::Path::new("/")); + }, + } } fn update(&mut self, event: Event) -> bool { let mut should_render = false; - let prev_event = if self.ev_history.len() == 2 { - self.ev_history.pop_front() - } else { - None - }; - self.ev_history.push_back((event.clone(), Instant::now())); match event { + Event::FileSystemUpdate(paths) => { + self.update_files(paths); + should_render = true; + }, Event::Key(key) => match key { - Key::Esc => { - hide_self(); + Key::Char(character) if character != '\n' => { + self.update_search_term(character); should_render = true; }, - Key::Up | Key::Char('k') => { - let currently_selected = self.selected(); - *self.selected_mut() = self.selected().saturating_sub(1); - if currently_selected != self.selected() { - should_render = true; - } + Key::Backspace => { + self.handle_backspace(); + should_render = true; }, - Key::Down | Key::Char('j') => { - let currently_selected = self.selected(); - let next = self.selected().saturating_add(1); - if next >= self.files.len() { - refresh_directory(self); - } - *self.selected_mut() = min(self.files.len().saturating_sub(1), next); - if currently_selected != self.selected() { - should_render = true; - } + Key::Esc | Key::Ctrl('c') => { + self.clear_search_term_or_descend(); + should_render = true; }, - Key::Right | Key::Char('\n') | Key::Char('l') if !self.files.is_empty() => { - self.traverse_dir_or_open_file(); - self.ev_history.clear(); + Key::Up => { + self.move_selection_up(); should_render = true; }, - Key::Left | Key::Char('h') => { - if self.path.components().count() > 2 { - // don't descend into /host - // the reason this is a hard-coded number (2) and not "== ROOT" - // or some such is that there are certain cases in which self.path - // is empty and this will work then too - should_render = true; - self.path.pop(); - refresh_directory(self); - } + Key::Down => { + self.move_selection_down(); + should_render = true; + }, + Key::Char('\n') if self.handling_filepick_request_from.is_some() => { + self.send_filepick_response(); + }, + Key::Char('\n') => { + self.open_selected_path(); + }, + Key::Right | Key::BackTab => { + self.traverse_dir(); + should_render = true; + }, + Key::Left => { + self.descend_to_previous_path(); + should_render = true; }, - Key::Char('.') => { + Key::Ctrl('e') => { should_render = true; self.toggle_hidden_files(); - refresh_directory(self); + refresh_directory(&self.file_list_view.path); }, - _ => (), }, Event::Mouse(mouse_event) => match mouse_event { Mouse::ScrollDown(_) => { - let currently_selected = self.selected(); - let next = self.selected().saturating_add(1); - if next >= self.files.len() { - refresh_directory(self); - } - *self.selected_mut() = min(self.files.len().saturating_sub(1), next); - if currently_selected != self.selected() { - should_render = true; - } + self.move_selection_down(); + should_render = true; }, Mouse::ScrollUp(_) => { - let currently_selected = self.selected(); - *self.selected_mut() = self.selected().saturating_sub(1); - if currently_selected != self.selected() { - should_render = true; - } + self.move_selection_up(); + should_render = true; }, - Mouse::Release(line, _) => { - if line < 0 { - return should_render; - } - let mut should_select = true; - if let Some((Event::Mouse(Mouse::Release(prev_line, _)), t)) = prev_event { - if prev_line == line - && Instant::now().saturating_duration_since(t).as_millis() < 400 - { - self.traverse_dir_or_open_file(); - self.ev_history.clear(); - should_select = false; - should_render = true; - } - } - if should_select && self.scroll() + (line as usize) < self.files.len() { - let currently_selected = self.selected(); - *self.selected_mut() = self.scroll() + (line as usize); - if currently_selected != self.selected() { - should_render = true; - } - } + Mouse::LeftClick(line, _) => { + self.handle_left_click(line); + should_render = true; }, _ => {}, }, @@ -125,42 +126,37 @@ impl ZellijPlugin for State { }; should_render } + fn pipe(&mut self, pipe_message: PipeMessage) -> bool { + if pipe_message.is_private && pipe_message.name == "filepicker" { + if let PipeSource::Cli(pipe_id) = &pipe_message.source { + // here we block the cli pipe input because we want it to wait until the user chose + // a file + #[cfg(target_family = "wasm")] + block_cli_pipe_input(pipe_id); + } + self.handling_filepick_request_from = Some((pipe_message.source, pipe_message.args)); + true + } else { + false + } + } fn render(&mut self, rows: usize, cols: usize) { self.current_rows = Some(rows); - for i in 0..rows { - if self.selected() < self.scroll() { - *self.scroll_mut() = self.selected(); - } - if self.selected() - self.scroll() + 2 > rows { - *self.scroll_mut() = self.selected() + 2 - rows; - } - - let is_last_row = i == rows.saturating_sub(1); - let i = self.scroll() + i; - if let Some(entry) = self.files.get(i) { - let mut path = entry.as_line(cols).normal(); - - if let FsEntry::Dir(..) = entry { - path = path.dimmed().bold(); - } - - if i == self.selected() { - if is_last_row { - print!("{}", path.clone().reversed()); - } else { - println!("{}", path.clone().reversed()); - } - } else { - if is_last_row { - print!("{}", path); - } else { - println!("{}", path); - } - } - } else if !is_last_row { - println!(); - } + let rows_for_list = rows.saturating_sub(6); + render_search_term(&self.search_term); + render_current_path( + &self.initial_cwd, + &self.file_list_view.path, + self.file_list_view.path_is_dir, + self.handling_filepick_request_from.is_some(), + cols, + ); + if self.is_searching { + self.search_view.render(rows_for_list, cols); + } else { + self.file_list_view.render(rows_for_list, cols); } + render_instruction_line(rows, cols); } } diff --git a/default-plugins/strider/src/search_view.rs b/default-plugins/strider/src/search_view.rs new file mode 100644 index 00000000..bcc38bc8 --- /dev/null +++ b/default-plugins/strider/src/search_view.rs @@ -0,0 +1,134 @@ +use crate::shared::{calculate_list_bounds, render_list_tip}; +use fuzzy_matcher::skim::SkimMatcherV2; +use fuzzy_matcher::FuzzyMatcher; +use pretty_bytes::converter::convert as pretty_bytes; +use unicode_width::UnicodeWidthStr; +use zellij_tile::prelude::*; + +use crate::file_list_view::FsEntry; + +#[derive(Default, Debug)] +pub struct SearchView { + pub search_results: Vec<SearchResult>, + pub selected_search_result: usize, +} + +impl SearchView { + pub fn search_result_count(&self) -> usize { + self.search_results.len() + } + pub fn update_search_results(&mut self, search_term: &str, files: &Vec<FsEntry>) { + self.selected_search_result = 0; + if search_term.is_empty() { + self.search_results.clear(); + } else { + let mut matches = vec![]; + let matcher = SkimMatcherV2::default().use_cache(true); + for file in files { + let name = file.name(); + if let Some((score, indices)) = matcher.fuzzy_indices(&name, search_term) { + matches.push(SearchResult::new(file.clone(), score, indices)); + } + } + matches.sort_by(|a, b| b.score.cmp(&a.score)); + self.search_results = matches; + } + } + pub fn clear_and_reset_selection(&mut self) { + self.search_results.clear(); + self.selected_search_result = 0; + } + pub fn move_selection_up(&mut self) { + self.selected_search_result = self.selected_search_result.saturating_sub(1); + } + pub fn move_selection_down(&mut self) { + if self.selected_search_result + 1 < self.search_results.len() { + self.selected_search_result += 1; + } + } + pub fn get_selected_entry(&self) -> Option<FsEntry> { + self.search_results + .get(self.selected_search_result) + .map(|s| s.entry.clone()) + } + pub fn render(&mut self, rows: usize, cols: usize) { + let (start_index, selected_index_in_range, end_index) = calculate_list_bounds( + self.search_results.len(), + rows.saturating_sub(1), + Some(self.selected_search_result), + ); + render_list_tip(3, cols); + for i in start_index..end_index { + if let Some(search_result) = self.search_results.get(i) { + let is_selected = Some(i) == selected_index_in_range; + let mut search_result_text = search_result.name(); + let size = search_result + .size() + .map(|s| pretty_bytes(s as f64)) + .unwrap_or("".to_owned()); + if search_result.is_folder() { + search_result_text.push('/'); + } + + let search_result_text_width = search_result_text.width(); + let size_width = size.width(); + let text = if search_result_text_width + size_width < cols { + let padding = " ".repeat( + cols.saturating_sub(search_result_text_width) + .saturating_sub(size_width), + ); + format!("{}{}{}", search_result_text, padding, size) + } else { + // drop the size, no room for it + let padding = " ".repeat(cols.saturating_sub(search_result_text_width)); + format!("{}{}", search_result_text, padding) + }; + let mut text_element = if is_selected { + Text::new(text).selected() + } else { + Text::new(text) + }; + if search_result.is_folder() { + text_element = text_element.color_range(0, ..); + } + text_element = text_element.color_indices(3, search_result.indices()); + print_text_with_coordinates( + text_element, + 0, + i.saturating_sub(start_index) + 4, + Some(cols), + None, + ); + } + } + } +} + +#[derive(Debug)] +pub struct SearchResult { + pub entry: FsEntry, + pub score: i64, + pub indices: Vec<usize>, +} + +impl SearchResult { + pub fn new(entry: FsEntry, score: i64, indices: Vec<usize>) -> Self { + SearchResult { + entry, + score, + indices, + } + } + pub fn name(&self) -> String { + self.entry.name() + } + pub fn size(&self) -> Option<u64> { + self.entry.size() + } + pub fn indices(&self) -> Vec<usize> { + self.indices.clone() + } + pub fn is_folder(&self) -> bool { + self.entry.is_folder() + } +} diff --git a/default-plugins/strider/src/shared.rs b/default-plugins/strider/src/shared.rs new file mode 100644 index 00000000..c51cb312 --- /dev/null +++ b/default-plugins/strider/src/shared.rs @@ -0,0 +1,156 @@ +use std::path::PathBuf; +use unicode_width::UnicodeWidthStr; +use zellij_tile::prelude::*; + +pub fn render_instruction_line(y: usize, max_cols: usize) { + if max_cols > 78 { + let text = "Help: go back with <Ctrl c>, go to root with /, <Ctrl e> - toggle hidden files"; + let text = Text::new(text) + .color_range(3, 19..27) + .color_range(3, 45..46) + .color_range(3, 48..56); + print_text_with_coordinates(text, 0, y, Some(max_cols), None); + } else if max_cols > 56 { + let text = "Help: <Ctrl c> - back, / - root, <Ctrl e> - hidden files"; + let text = Text::new(text) + .color_range(3, 6..14) + .color_range(3, 23..24) + .color_range(3, 33..41); + print_text_with_coordinates(text, 0, y, Some(max_cols), None); + } else if max_cols > 25 { + let text = "<Ctrl c> - back, / - root"; + let text = Text::new(text).color_range(3, ..8).color_range(3, 17..18); + print_text_with_coordinates(text, 0, y, Some(max_cols), None); + } +} + +pub fn render_list_tip(y: usize, max_cols: usize) { + let tip = Text::new(format!("(<↓↑> - Navigate, <TAB> - Select)")) + .color_range(3, 1..5) + .color_range(3, 18..23); + print_text_with_coordinates(tip, 0, y, Some(max_cols), None); +} + +// returns the list (start_index, selected_index_in_range, end_index) +pub fn calculate_list_bounds( + result_count: usize, + max_result_count: usize, + selected_index_in_all_results: Option<usize>, +) -> (usize, Option<usize>, usize) { + match selected_index_in_all_results { + Some(selected_index_in_all_results) => { + let mut room_in_list = max_result_count; + let mut start_index = selected_index_in_all_results; + let mut end_index = selected_index_in_all_results + 1; + let mut alternate = false; + loop { + if room_in_list == 0 { + break; + } + if !alternate && start_index > 0 { + start_index -= 1; + room_in_list -= 1; + } else if alternate && end_index < result_count { + end_index += 1; + room_in_list -= 1; + } else if start_index > 0 { + start_index -= 1; + room_in_list -= 1; + } else if end_index < result_count { + end_index += 1; + room_in_list -= 1; + } else { + break; + } + alternate = !alternate; + } + (start_index, Some(selected_index_in_all_results), end_index) + }, + None => (0, None, max_result_count + 1), + } +} + +pub fn render_search_term(search_term: &str) { + let prompt = "FIND: "; + let text = Text::new(format!("{}{}_", prompt, search_term)) + .color_range(2, 0..prompt.len()) + .color_range(3, prompt.len()..); + print_text(text); + println!("") +} + +pub fn render_current_path( + initial_cwd: &PathBuf, + path: &PathBuf, + path_is_dir: bool, + handling_filepick: bool, + max_cols: usize, +) { + let prompt = "PATH: "; + let current_path = initial_cwd.join(path); + let current_path = current_path.display().to_string(); + let prompt_len = prompt.width(); + let current_path_len = current_path.width(); + + let enter_tip = if handling_filepick { + "Select" + } else if path_is_dir { + "Open terminal here" + } else { + "Open in editor" + }; + if max_cols > prompt_len + current_path_len + enter_tip.width() + 13 { + let path_end = prompt_len + current_path_len; + let current_path = Text::new(format!( + "{}{} (<ENTER> - {})", + prompt, current_path, enter_tip + )) + .color_range(2, 0..prompt_len) + .color_range(0, prompt_len..path_end) + .color_range(3, path_end + 2..path_end + 9); + print_text(current_path); + } else { + let max_path_len = max_cols + .saturating_sub(prompt_len) + .saturating_sub(8) + .saturating_sub(prompt_len); + let current_path = if current_path_len <= max_path_len { + current_path + } else { + truncate_path( + initial_cwd.join(path), + current_path_len.saturating_sub(max_path_len), + ) + }; + let current_path_len = current_path.width(); + let path_end = prompt_len + current_path_len; + let current_path = Text::new(format!("{}{} <ENTER>", prompt, current_path)) + .color_range(2, 0..prompt_len) + .color_range(0, prompt_len..path_end) + .color_range(3, path_end + 1..path_end + 9); + print_text(current_path); + } + println!(); + println!(); +} + +fn truncate_path(path: PathBuf, mut char_count_to_remove: usize) -> String { + let mut truncated = String::new(); + let component_count = path.iter().count(); + for (i, component) in path.iter().enumerate() { + let mut component_str = component.to_string_lossy().to_string(); + if char_count_to_remove > 0 { + truncated.push(component_str.remove(0)); + if i != 0 && i + 1 != component_count { + truncated.push('/'); + } + char_count_to_remove = char_count_to_remove.saturating_sub(component_str.width() + 1); + } else { + truncated.push_str(&component_str); + if i != 0 && i + 1 != component_count { + truncated.push('/'); + } + } + } + truncated +} diff --git a/default-plugins/strider/src/state.rs b/default-plugins/strider/src/state.rs index 230e92ea..1ff58386 100644 --- a/default-plugins/strider/src/state.rs +++ b/default-plugins/strider/src/state.rs @@ -1,9 +1,9 @@ -use pretty_bytes::converter as pb; +use crate::file_list_view::{FileListView, FsEntry}; +use crate::search_view::SearchView; +use crate::shared::calculate_list_bounds; use std::{ - collections::{HashMap, VecDeque}, - fs::read_dir, + collections::BTreeMap, path::{Path, PathBuf}, - time::Instant, }; use zellij_tile::prelude::*; @@ -11,106 +11,189 @@ pub const ROOT: &str = "/host"; #[derive(Default)] pub struct State { - pub path: PathBuf, - pub files: Vec<FsEntry>, - pub cursor_hist: HashMap<PathBuf, (usize, usize)>, + pub file_list_view: FileListView, + pub search_view: SearchView, pub hide_hidden_files: bool, - pub ev_history: VecDeque<(Event, Instant)>, // stores last event, can be expanded in future pub loading: bool, pub loading_animation_offset: u8, pub should_open_floating: bool, pub current_rows: Option<usize>, + pub handling_filepick_request_from: Option<(PipeSource, BTreeMap<String, String>)>, + pub initial_cwd: PathBuf, // TODO: get this from zellij + pub is_searching: bool, + pub search_term: String, + pub close_on_selection: bool, } impl State { - pub fn selected_mut(&mut self) -> &mut usize { - &mut self.cursor_hist.entry(self.path.clone()).or_default().0 + pub fn update_search_term(&mut self, character: char) { + self.search_term.push(character); + if &self.search_term == ".." { + self.descend_to_previous_path(); + } else if &self.search_term == "/" { + self.descend_to_root_path(); + } else { + self.is_searching = true; + self.search_view + .update_search_results(&self.search_term, &self.file_list_view.files); + } } - pub fn selected(&self) -> usize { - self.cursor_hist.get(&self.path).unwrap_or(&(0, 0)).0 + pub fn handle_backspace(&mut self) { + if self.search_term.is_empty() { + self.descend_to_previous_path(); + } else { + self.search_term.pop(); + if self.search_term.is_empty() { + self.is_searching = false; + } + self.search_view + .update_search_results(&self.search_term, &self.file_list_view.files); + } } - pub fn scroll_mut(&mut self) -> &mut usize { - &mut self.cursor_hist.entry(self.path.clone()).or_default().1 + pub fn clear_search_term_or_descend(&mut self) { + if self.search_term.is_empty() { + self.descend_to_previous_path(); + } else { + self.search_term.clear(); + self.search_view + .update_search_results(&self.search_term, &self.file_list_view.files); + self.is_searching = false; + } } - pub fn scroll(&self) -> usize { - self.cursor_hist.get(&self.path).unwrap_or(&(0, 0)).1 + pub fn move_selection_up(&mut self) { + if self.is_searching { + self.search_view.move_selection_up(); + } else { + self.file_list_view.move_selection_up(); + } + } + pub fn move_selection_down(&mut self) { + if self.is_searching { + self.search_view.move_selection_down(); + } else { + self.file_list_view.move_selection_down(); + } + } + pub fn handle_left_click(&mut self, line: isize) { + if let Some(current_rows) = self.current_rows { + let rows_for_list = current_rows.saturating_sub(5); + if self.is_searching { + let (start_index, _selected_index_in_range, _end_index) = calculate_list_bounds( + self.search_view.search_result_count(), + rows_for_list, + Some(self.search_view.selected_search_result), + ); + let prev_selected = self.search_view.selected_search_result; + self.search_view.selected_search_result = + (line as usize).saturating_sub(2) + start_index; + if prev_selected == self.search_view.selected_search_result { + self.traverse_dir(); + } + } else { + let (start_index, _selected_index_in_range, _end_index) = calculate_list_bounds( + self.file_list_view.files.len(), + rows_for_list, + self.file_list_view.selected(), + ); + let prev_selected = self.file_list_view.selected(); + *self.file_list_view.selected_mut() = + (line as usize).saturating_sub(2) + start_index; + if prev_selected == self.file_list_view.selected() { + self.traverse_dir(); + } + } + } + } + pub fn descend_to_previous_path(&mut self) { + self.search_term.clear(); + self.search_view.clear_and_reset_selection(); + self.file_list_view.descend_to_previous_path(); + } + pub fn descend_to_root_path(&mut self) { + self.search_term.clear(); + self.search_view.clear_and_reset_selection(); + self.file_list_view.descend_to_root_path(); + refresh_directory(&self.file_list_view.path); } pub fn toggle_hidden_files(&mut self) { self.hide_hidden_files = !self.hide_hidden_files; } - pub fn traverse_dir_or_open_file(&mut self) { - if let Some(f) = self.files.get(self.selected()) { - match f.clone() { - FsEntry::Dir(p) => { - self.path = p; - refresh_directory(self); + pub fn traverse_dir(&mut self) { + let entry = if self.is_searching { + self.search_view.get_selected_entry() + } else { + self.file_list_view.get_selected_entry() + }; + if let Some(entry) = entry { + match &entry { + FsEntry::Dir(_p) => { + self.file_list_view.enter_dir(&entry); + self.search_view.clear_and_reset_selection(); + refresh_directory(&self.file_list_view.path); + }, + FsEntry::File(_p, _) => { + self.file_list_view.enter_dir(&entry); + self.search_view.clear_and_reset_selection(); }, - FsEntry::File(p, _) => open_file(FileToOpen { - path: p.strip_prefix(ROOT).unwrap().into(), - ..Default::default() - }), } } + self.is_searching = false; + self.search_term.clear(); + self.search_view.clear_and_reset_selection(); } -} - -#[derive(PartialEq, Eq, PartialOrd, Ord, Clone)] -pub enum FsEntry { - Dir(PathBuf), - File(PathBuf, u64), -} - -impl FsEntry { - pub fn name(&self) -> String { - let path = match self { - FsEntry::Dir(p) => p, - FsEntry::File(p, _) => p, - }; - path.file_name().unwrap().to_string_lossy().into_owned() + pub fn update_files(&mut self, paths: Vec<(PathBuf, Option<FileMetadata>)>) { + self.file_list_view + .update_files(paths, self.hide_hidden_files); } - - pub fn as_line(&self, width: usize) -> String { - let info = match self { - FsEntry::Dir(_s) => "".to_owned(), - FsEntry::File(_, s) => pb::convert(*s as f64), - }; - let space = width.saturating_sub(info.len()); - let name = self.name(); - if space.saturating_sub(1) < name.len() { - [&name[..space.saturating_sub(2)], &info].join("~ ") + pub fn open_selected_path(&mut self) { + if self.file_list_view.path_is_dir { + open_terminal(&self.file_list_view.path); } else { - let padding = " ".repeat(space - name.len()); - [name, padding, info].concat() + if let Some(parent_folder) = self.file_list_view.path.parent() { + open_file( + FileToOpen::new(&self.file_list_view.path).with_cwd(parent_folder.into()), + ); + } else { + open_file(FileToOpen::new(&self.file_list_view.path)); + } + } + if self.close_on_selection { + close_focus(); } } - - pub fn is_hidden_file(&self) -> bool { - self.name().starts_with('.') + pub fn send_filepick_response(&mut self) { + let selected_path = self.initial_cwd.join( + self.file_list_view + .path + .strip_prefix(ROOT) + .map(|p| p.to_path_buf()) + .unwrap_or_else(|_| self.file_list_view.path.clone()), + ); + match &self.handling_filepick_request_from { + Some((PipeSource::Plugin(plugin_id), args)) => { + pipe_message_to_plugin( + MessageToPlugin::new("filepicker_result") + .with_destination_plugin_id(*plugin_id) + .with_args(args.clone()) + .with_payload(selected_path.display().to_string()), + ); + #[cfg(target_family = "wasm")] + close_focus(); + }, + Some((PipeSource::Cli(pipe_id), _args)) => { + #[cfg(target_family = "wasm")] + cli_pipe_output(pipe_id, &selected_path.display().to_string()); + #[cfg(target_family = "wasm")] + unblock_cli_pipe_input(pipe_id); + #[cfg(target_family = "wasm")] + close_focus(); + }, + _ => {}, + } } } -pub(crate) fn refresh_directory(state: &mut State) { - // TODO: might be good to do this asynchronously with a worker - let mut max_lines = (state.current_rows.unwrap_or(50) + state.scroll()) * 2; // 100 is arbitrary for performance reasons - let mut files = vec![]; - for entry in read_dir(Path::new(ROOT).join(&state.path)).unwrap() { - if let Ok(entry) = entry { - if max_lines == 0 { - break; - } - let entry_metadata = entry.metadata().unwrap(); - let entry = if entry_metadata.is_dir() { - FsEntry::Dir(entry.path()) - } else { - let size = entry_metadata.len(); - FsEntry::File(entry.path(), size) - }; - if !entry.is_hidden_file() || !state.hide_hidden_files { - max_lines = max_lines.saturating_sub(1); - files.push(entry); - } - } - } - state.files = files; - state.files.sort_unstable(); +pub(crate) fn refresh_directory(path: &Path) { + let path_on_host = Path::new(ROOT).join(path.strip_prefix("/").unwrap_or(path)); + scan_host_folder(&path_on_host); } |
