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