Krolyxon
Commit bf531fa

rmptuisrcapp.rs

271 lines · 9.0 KB · Rust

1use crate::browser::FileBrowser;
2use crate::connection::Connection;
3use crate::list::ContentList;
4use crate::ui::InputMode;
5use mpd::Client;
6
7// Application result type
8pub type AppResult<T> = std::result::Result<T, Box<dyn std::error::Error>>;
9
10/// Application
11#[derive(Debug)]
12pub struct App {
13 /// check if app is running
14 pub running: bool,
15 pub conn: Connection,
16 pub queue_list: ContentList<String>,
17 pub pl_list: ContentList<String>,
18 pub selected_tab: SelectedTab,
19 pub browser: FileBrowser,
20
21 // Search
22 pub inputmode: InputMode,
23 pub search_input: String,
24 pub cursor_position: usize,
25
26 // add to playlists
27 pub playlist_popup: bool,
28 pub append_list: ContentList<String>,
29}
30
31#[derive(Debug, PartialEq, Clone)]
32pub enum SelectedTab {
33 DirectoryBrowser,
34 Queue,
35 Playlists,
36}
37
38impl App {
39 pub fn builder(addrs: &str) -> AppResult<Self> {
40 let mut conn = Connection::new(addrs).unwrap();
41 let mut queue_list = ContentList::new();
42 let mut pl_list = ContentList::new();
43 pl_list.list = Self::get_playlist(&mut conn.conn)?;
44
45 let append_list = Self::get_append_list(&mut conn.conn)?;
46 Self::get_queue(&mut conn, &mut queue_list.list);
47
48 let browser = FileBrowser::new();
49
50 Ok(Self {
51 running: true,
52 conn,
53 queue_list,
54 pl_list,
55 selected_tab: SelectedTab::Queue,
56 browser,
57 inputmode: InputMode::Normal,
58 search_input: String::new(),
59 cursor_position: 0,
60 playlist_popup: false,
61 append_list,
62 })
63 }
64
65 pub fn tick(&mut self) {
66 self.conn.update_status();
67 self.update_queue();
68 }
69
70 pub fn quit(&mut self) {
71 self.running = false;
72 }
73
74 pub fn get_queue(conn: &mut Connection, vec: &mut Vec<String>) {
75 // conn.conn.queue().unwrap().into_iter().for_each(|x| {
76 // if let Some(title) = x.title {
77 // if let Some(artist) = x.artist {
78 // vec.push(format!("{} - {}", artist, title));
79 // } else {
80 // vec.push(title)
81 // }
82 // } else {
83 // vec.push(x.file)
84 // }
85 // });
86 conn.conn.queue().unwrap().into_iter().for_each(|x| {
87 vec.push(x.file);
88 });
89 }
90
91 pub fn update_queue(&mut self) {
92 self.queue_list.list.clear();
93 Self::get_queue(&mut self.conn, &mut self.queue_list.list);
94 }
95
96 pub fn get_playlist(conn: &mut Client) -> AppResult<Vec<String>> {
97 let list: Vec<String> = conn.playlists()?.iter().map(|p| p.clone().name).collect();
98 Ok(list)
99 }
100
101 pub fn get_append_list(conn: &mut Client) -> AppResult<ContentList<String>> {
102 let mut list = ContentList::new();
103 list.list.push("Current Playlist".to_string());
104 for item in Self::get_playlist(conn)? {
105 list.list.push(item.to_string());
106 }
107
108 Ok(list)
109 }
110
111 pub fn update_playlist(&mut self) -> AppResult<()> {
112 Self::get_playlist(&mut self.conn.conn)?;
113 Ok(())
114 }
115
116 pub fn handle_add_or_remove_from_current_playlist(&mut self) -> AppResult<()> {
117 match self.selected_tab {
118 SelectedTab::DirectoryBrowser => {
119 let (_, file) = self.browser.filetree.get(self.browser.selected).unwrap();
120
121 let mut status = false;
122 for (i, song) in self.queue_list.list.clone().iter().enumerate() {
123 if song.contains(file) {
124 self.conn.conn.delete(i as u32).unwrap();
125 status = true;
126 }
127 }
128
129 if !status {
130 if let Some(full_path) = &self.conn.get_full_path(&file) {
131 let song = self.conn.get_song_with_only_filename(full_path);
132 self.conn.conn.push(&song)?;
133 }
134 }
135
136 if self.browser.selected != self.browser.filetree.len() - 1 {
137 self.browser.selected += 1;
138 }
139 }
140
141 SelectedTab::Queue => {
142 if self.queue_list.list.len() == 0 {
143 return Ok(());
144 }
145 let file = self
146 .queue_list
147 .list
148 .get(self.queue_list.index)
149 .unwrap()
150 .to_string();
151
152 for (i, song) in self.queue_list.list.clone().iter().enumerate() {
153 if song.contains(&file) {
154 self.conn.conn.delete(i as u32).unwrap();
155 if self.queue_list.index == self.queue_list.list.len() - 1 && self.queue_list.index != 0 {
156 self.queue_list.index -= 1;
157 }
158 }
159 }
160 }
161
162 _ => {}
163 }
164
165 self.update_queue();
166 Ok(())
167 }
168
169 pub fn cycle_tabls(&mut self) {
170 self.selected_tab = match self.selected_tab {
171 SelectedTab::Queue => SelectedTab::DirectoryBrowser,
172 SelectedTab::DirectoryBrowser => SelectedTab::Playlists,
173 SelectedTab::Playlists => SelectedTab::DirectoryBrowser,
174 };
175 }
176
177 pub fn handle_enter(&mut self) -> AppResult<()> {
178 let browser = &mut self.browser;
179 let (t, path) = browser.filetree.get(browser.selected).unwrap();
180 if t == "directory" {
181 if path != "." {
182 browser.prev_path = browser.path.clone();
183 browser.path = browser.prev_path.clone() + "/" + path;
184 browser.update_directory(&mut self.conn)?;
185 browser.prev_selected = browser.selected;
186 browser.selected = 0;
187 }
188 } else {
189 // let list = conn
190 // .songs_filenames
191 // .iter()
192 // .map(|f| f.as_str())
193 // .collect::<Vec<&str>>();
194 // let (filename, _) = rust_fuzzy_search::fuzzy_search_sorted(&path, &list)
195 // .get(0)
196 // .unwrap()
197 // .clone();
198 let index = self.queue_list.list.iter().position(|x| x.contains(path));
199
200 if index.is_some() {
201 self.conn.conn.switch(index.unwrap() as u32)?;
202 } else {
203 for filename in self.conn.songs_filenames.clone().iter() {
204 if filename.contains(path) {
205 let song = self.conn.get_song_with_only_filename(filename);
206 self.conn.push(&song)?;
207 }
208 }
209
210 // updating queue, to avoid multiple pushes of the same songs if we enter multiple times before the queue gets updated
211 self.update_queue();
212 }
213 }
214 Ok(())
215 }
216
217 pub fn search_song(&mut self) -> AppResult<()> {
218 if let Some(filename) = self.conn.get_full_path(&self.search_input) {
219 let song = self.conn.get_song_with_only_filename(&filename);
220 self.conn.push(&song)?;
221 }
222 Ok(())
223 }
224
225 // Cursor movements
226 pub fn move_cursor_left(&mut self) {
227 let cursor_moved_left = self.cursor_position.saturating_sub(1);
228 self.cursor_position = self.clamp_cursor(cursor_moved_left);
229 }
230
231 pub fn move_cursor_right(&mut self) {
232 let cursor_moved_right = self.cursor_position.saturating_add(1);
233 self.cursor_position = self.clamp_cursor(cursor_moved_right);
234 }
235
236 pub fn enter_char(&mut self, new_char: char) {
237 self.search_input.insert(self.cursor_position, new_char);
238
239 self.move_cursor_right();
240 }
241
242 pub fn delete_char(&mut self) {
243 let is_not_cursor_leftmost = self.cursor_position != 0;
244 if is_not_cursor_leftmost {
245 // Method "remove" is not used on the saved text for deleting the selected char.
246 // Reason: Using remove on String works on bytes instead of the chars.
247 // Using remove would require special care because of char boundaries.
248
249 let current_index = self.cursor_position;
250 let from_left_to_current_index = current_index - 1;
251
252 // Getting all characters before the selected character.
253 let before_char_to_delete = self.search_input.chars().take(from_left_to_current_index);
254 // Getting all characters after selected character.
255 let after_char_to_delete = self.search_input.chars().skip(current_index);
256
257 // Put all characters together except the selected one.
258 // By leaving the selected one out, it is forgotten and therefore deleted.
259 self.search_input = before_char_to_delete.chain(after_char_to_delete).collect();
260 self.move_cursor_left();
261 }
262 }
263
264 pub fn clamp_cursor(&self, new_cursor_pos: usize) -> usize {
265 new_cursor_pos.clamp(0, self.search_input.len())
266 }
267
268 pub fn reset_cursor(&mut self) {
269 self.cursor_position = 0;
270 }
271}