Krolyxon
Commit 59e8e8c

rmptuisrcbrowser.rs

90 lines · 2.5 KB · Rust

1use crate::{app::AppResult, connection::Connection};
2
3#[derive(Debug)]
4pub struct FileBrowser {
5 pub filetree: Vec<(String, String)>,
6 pub selected: usize,
7 pub prev_selected: usize,
8 pub path: String,
9 pub prev_path: String,
10}
11
12impl FileBrowser {
13 pub fn new() -> FileBrowser {
14 FileBrowser {
15 filetree: Vec::new(),
16 selected: 0,
17 prev_selected: 0,
18 path: ".".to_string(),
19 prev_path: ".".to_string(),
20 }
21 }
22
23 pub fn update_directory(&mut self, conn: &mut Connection) -> AppResult<()> {
24 self.filetree.clear();
25 self.filetree = conn
26 .conn
27 .listfiles(self.path.as_str())?
28 .into_iter()
29 .filter(|(f, _)| f == "directory" || f == "file")
30 .collect::<Vec<(String, String)>>();
31
32 Ok(())
33 }
34
35 // Go to next item in filetree
36 pub fn next(&mut self) {
37 // if self.selected < self.filetree.len() - 1 {
38 // self.selected += 1;
39 // }
40
41 if self.selected == self.filetree.len() - 1 {
42 self.selected = 0;
43 } else {
44 self.selected += 1;
45 }
46 }
47
48 /// Go to previous item in filetree
49 pub fn prev(&mut self) {
50 if self.selected == 0 {
51 self.selected = self.filetree.len() - 1;
52 } else {
53 self.selected -= 1;
54 }
55 }
56
57 pub fn handle_enter(&mut self, conn: &mut Connection) -> AppResult<()> {
58 let (t, path) = self.filetree.get(self.selected).unwrap();
59 if t == "directory" {
60 if path != "." {
61 self.prev_path = self.path.clone();
62 self.path = path.to_string();
63 self.update_directory(conn)?;
64 self.prev_selected = self.selected;
65 self.selected = 0;
66 }
67 } else {
68 let list = conn
69 .songs_filenames
70 .iter()
71 .map(|f| f.as_str())
72 .collect::<Vec<&str>>();
73 let (filename, _) = rust_fuzzy_search::fuzzy_search_sorted(&path, &list)
74 .get(0)
75 .unwrap()
76 .clone();
77
78 let song = conn.get_song_with_only_filename(filename);
79 conn.push(&song)?;
80 }
81 Ok(())
82 }
83
84 pub fn handle_go_back(&mut self, conn: &mut Connection) -> AppResult<()> {
85 self.path = self.prev_path.clone();
86 self.selected = self.prev_selected;
87 self.update_directory(conn)?;
88 Ok(())
89 }
90}