Skip to content

Commit

Permalink
fix(repo): various bugs and performance improvements
Browse files Browse the repository at this point in the history
Various fixes
  • Loading branch information
imsnif committed Mar 28, 2024
2 parents 94a4fa4 + fb2daf5 commit 4ac617a
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 122 deletions.
47 changes: 2 additions & 45 deletions src/backend_workers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use ignore::Walk;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::io::{self, BufRead};
use std::path::{Path, PathBuf};
use std::path::Path;
use unicode_width::UnicodeWidthStr;

use crate::search_results::{ResultsOfSearch, SearchResult};
Expand All @@ -30,7 +30,7 @@ impl Search {
..Default::default()
}
}
fn on_message(&mut self, message: String, payload: String) {
fn on_message(&mut self, message: String, _payload: String) {
match serde_json::from_str::<MessageToSearch>(&message) {
Ok(MessageToSearch::ScanFolder) => {
self.scan_hd();
Expand All @@ -44,15 +44,6 @@ impl Search {
self.search(current_search_term);
}
}
Ok(MessageToSearch::FileSystemCreate) => {
self.rescan_files(payload);
}
Ok(MessageToSearch::FileSystemUpdate) => {
self.rescan_files(payload);
}
Ok(MessageToSearch::FileSystemDelete) => {
self.delete_files(payload);
}
Err(e) => eprintln!("Failed to deserialize worker message {:?}", e),
}
}
Expand Down Expand Up @@ -119,28 +110,6 @@ impl Search {
));
}
}
pub fn rescan_files(&mut self, paths: String) {
match serde_json::from_str::<Vec<PathBuf>>(&paths) {
Ok(paths) => {
for path in paths {
self.add_file_entry(&path, path.metadata().ok());
}
self.cached_file_name_results.clear();
self.cached_file_contents_results.clear();
}
Err(e) => eprintln!("Failed to deserialize paths: {:?}", e),
}
}
pub fn delete_files(&mut self, paths: String) {
match serde_json::from_str::<Vec<PathBuf>>(&paths) {
Ok(paths) => {
self.remove_existing_entries(&paths);
self.cached_file_name_results.clear();
self.cached_file_contents_results.clear();
}
Err(e) => eprintln!("Failed to deserialize paths: {:?}", e),
}
}
fn add_file_entry(&mut self, file_name: &Path, file_metadata: Option<std::fs::Metadata>) {
let file_path = file_name.display().to_string();
let file_path_stripped_prefix = self.strip_file_prefix(&file_name);
Expand Down Expand Up @@ -226,24 +195,12 @@ impl Search {
_ => None,
}
}
fn remove_existing_entries(&mut self, paths: &Vec<PathBuf>) {
let file_path_stripped_prefixes: Vec<String> =
paths.iter().map(|p| self.strip_file_prefix(&p)).collect();
self.file_names
.retain(|file_name| !file_path_stripped_prefixes.contains(file_name));
self.file_contents.retain(|(file_name, _line_in_file), _| {
!file_path_stripped_prefixes.contains(file_name)
});
}
}

#[derive(Serialize, Deserialize)]
pub enum MessageToSearch {
ScanFolder,
Search,
FileSystemCreate,
FileSystemUpdate,
FileSystemDelete,
}

#[derive(Serialize, Deserialize)]
Expand Down
59 changes: 8 additions & 51 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,14 @@ impl ZellijPlugin for State {
fn load(&mut self, config: BTreeMap<String, String>) {
self.loading = true;
self.kiosk_mode = config.get("kiosk").map(|k| k == "true").unwrap_or(false);
if let Some(search_type) = config.get("search_filter") {
match search_type.as_str() {
"file_names" => self.search_filter = SearchType::Names,
"file_contents" => self.search_filter = SearchType::Contents,
"all" => self.search_filter = SearchType::NamesAndContents,
_ => {}
}
}
request_permission(&[
PermissionType::OpenFiles,
PermissionType::ChangeApplicationState,
Expand All @@ -50,9 +58,6 @@ impl ZellijPlugin for State {
EventType::Mouse,
EventType::CustomMessage,
EventType::Timer,
EventType::FileSystemCreate,
EventType::FileSystemUpdate,
EventType::FileSystemDelete,
]);
post_message_to(PluginMessage::new_to_worker(
"file_name_search",
Expand Down Expand Up @@ -103,54 +108,6 @@ impl ZellijPlugin for State {
self.handle_key(key);
should_render = true;
}
Event::FileSystemCreate(paths) => {
let paths: Vec<String> = paths
.iter()
.map(|p| p.to_string_lossy().to_string())
.collect();
post_message_to(PluginMessage::new_to_worker(
"file_name_search",
&serde_json::to_string(&MessageToSearch::FileSystemCreate).unwrap(),
&serde_json::to_string(&paths).unwrap(),
));
post_message_to(PluginMessage::new_to_worker(
"file_contents_search",
&serde_json::to_string(&MessageToSearch::FileSystemCreate).unwrap(),
&serde_json::to_string(&paths).unwrap(),
));
}
Event::FileSystemUpdate(paths) => {
let paths: Vec<String> = paths
.iter()
.map(|p| p.to_string_lossy().to_string())
.collect();
post_message_to(PluginMessage::new_to_worker(
"file_name_search",
&serde_json::to_string(&MessageToSearch::FileSystemUpdate).unwrap(),
&serde_json::to_string(&paths).unwrap(),
));
post_message_to(PluginMessage::new_to_worker(
"file_contents_search",
&serde_json::to_string(&MessageToSearch::FileSystemUpdate).unwrap(),
&serde_json::to_string(&paths).unwrap(),
));
}
Event::FileSystemDelete(paths) => {
let paths: Vec<String> = paths
.iter()
.map(|p| p.to_string_lossy().to_string())
.collect();
post_message_to(PluginMessage::new_to_worker(
"file_name_search",
&serde_json::to_string(&MessageToSearch::FileSystemDelete).unwrap(),
&serde_json::to_string(&paths).unwrap(),
));
post_message_to(PluginMessage::new_to_worker(
"file_contents_search",
&serde_json::to_string(&MessageToSearch::FileSystemDelete).unwrap(),
&serde_json::to_string(&paths).unwrap(),
));
}
_ => {
eprintln!("Unknown event: {}", event.to_string());
}
Expand Down
38 changes: 23 additions & 15 deletions src/search_results.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use serde::{Deserialize, Serialize};
use unicode_width::UnicodeWidthStr;
use unicode_width::{UnicodeWidthStr, UnicodeWidthChar};

use crate::ui::{
bold, styled_text, styled_text_background, styled_text_foreground, underline, GRAY_LIGHT,
Expand Down Expand Up @@ -233,27 +233,35 @@ impl SearchResult {
let truncate_end_position = truncate_positions
.map(|p| p.1)
.unwrap_or(line_to_render.chars().count());

let left_truncate_sign = if truncate_start_position == 0 {
""
} else {
".."
};
let right_truncate_sign = if truncate_end_position == line_to_render.chars().count() {
""
} else {
".."
};

let max_width_for_visible_portion = max_width.saturating_sub(left_truncate_sign.chars().count()).saturating_sub(right_truncate_sign.chars().count());
let mut visible_portion = String::new();
let mut visible_characters = String::new();
for (i, character) in line_to_render.chars().enumerate() {
if visible_characters.width() + character.width().unwrap_or(0) > max_width_for_visible_portion {
break;
}
if i >= truncate_start_position && i <= truncate_end_position {
if indices.contains(&i) {
visible_portion.push_str(&index_character_style(&character.to_string()));
} else {
visible_portion.push_str(&non_index_character_style(&character.to_string()));
}
visible_characters.push(character);
}
}
if truncate_positions.is_some() {
let left_truncate_sign = if truncate_start_position == 0 {
""
} else {
".."
};
let right_truncate_sign = if truncate_end_position == line_to_render.chars().count() {
""
} else {
".."
};
format!(
"{}{}{}",
non_index_character_style(left_truncate_sign),
Expand Down Expand Up @@ -292,7 +300,7 @@ impl SearchResult {
if i >= width_remaining {
break;
}
if string_start_position > 0 && string_end_position < line_to_render.chars().count()
if string_start_position > 0 && string_end_position < line_to_render.width()
{
let take_from_start = i % 2 == 0;
if take_from_start {
Expand All @@ -302,13 +310,13 @@ impl SearchResult {
}
} else {
string_end_position += 1;
if string_end_position == line_to_render.chars().count() {
if string_end_position == line_to_render.width() {
width_remaining += 2; // no need for truncating dots
}
}
} else if string_end_position < line_to_render.chars().count() {
} else if string_end_position < line_to_render.width() {
string_end_position += 1;
if string_end_position == line_to_render.chars().count() {
if string_end_position == line_to_render.width() {
width_remaining += 2; // no need for truncating dots
}
} else if string_start_position > 0 {
Expand Down
9 changes: 1 addition & 8 deletions src/ui/controls_line.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,7 @@ impl ControlsLine {
self.animation_offset = animation_offset;
self
}
pub fn render(&self, max_width: usize, show_controls: bool) -> String {
if show_controls {
self.render_controls(max_width)
} else {
self.render_empty_line(max_width)
}
}
pub fn render_controls(&self, max_width: usize) -> String {
pub fn render(&self, max_width: usize) -> String {
let loading_animation =
LoadingAnimation::new(&self.scanning_indication, self.animation_offset);
let full_length = loading_animation.full_len()
Expand Down
5 changes: 2 additions & 3 deletions src/ui/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ impl State {
}
}
pub fn render_controls_line(&self) -> String {
let has_results = !self.displayed_search_results.1.is_empty();
let tiled_floating_control =
Control::new_floating_control("Ctrl f", self.should_open_floating);
let names_contents_control = Control::new_filter_control("Ctrl r", &self.search_filter);
Expand All @@ -86,10 +85,10 @@ impl State {
Some(vec!["Scanning folder", "Scanning", "S"]),
)
.with_animation_offset(self.loading_animation_offset)
.render(self.display_columns, has_results)
.render(self.display_columns)
} else {
ControlsLine::new(controls, None)
.render(self.display_columns, has_results)
.render(self.display_columns)
}
}
}
Expand Down

0 comments on commit 4ac617a

Please sign in to comment.