Krolyxon
Commit 00c5c12

rmptuisrcbrowser.rs

92 lines · 2.5 KB · Rust

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