Krolyxon
Commit 32a3c60

rmptuisrcapp.rs

356 lines · 12.5 KB · Rust

1use std::time::Duration;
2
3use crate::browser::FileBrowser;
4use crate::connection::Connection;
5use crate::list::ContentList;
6use crate::ui::InputMode;
7use mpd::Client;
8
9// Application result type
10pub type AppResult<T> = std::result::Result<T, Box<dyn std::error::Error>>;
11
12/// Application
13#[derive(Debug)]
14pub struct App {
15 /// check if app is running
16 pub running: bool,
17 pub conn: Connection,
18 pub browser: FileBrowser, // Directory browser
19 pub queue_list: ContentList<String>, // Stores the current playing queue
20 pub pl_list: ContentList<String>, // Stores list of playlists
21 pub selected_tab: SelectedTab, // Used to switch between tabs
22
23 // Search
24 pub inputmode: InputMode, // Defines input mode, Normal or Search
25 pub search_input: String, // Stores the userinput to be searched
26 pub search_cursor_pos: usize, // Stores the cursor position for searching
27 pub pl_newname_input: String, // Stores the new name of the playlist
28 pub pl_cursor_pos: usize, // Stores the cursor position for renaming playlist
29
30 // playlist variables
31 // used to show playlist popup
32 pub playlist_popup: bool,
33 pub append_list: ContentList<String>,
34}
35
36#[derive(Debug, PartialEq, Clone)]
37pub enum SelectedTab {
38 DirectoryBrowser,
39 Queue,
40 Playlists,
41}
42
43impl App {
44 pub fn builder(addrs: &str) -> AppResult<Self> {
45 let mut conn = Connection::new(addrs).unwrap();
46 let mut queue_list = ContentList::new();
47 let mut pl_list = ContentList::new();
48 pl_list.list = Self::get_playlist(&mut conn.conn)?;
49
50 let append_list = Self::get_append_list(&mut conn.conn)?;
51 Self::get_queue(&mut conn, &mut queue_list.list);
52
53 let browser = FileBrowser::new();
54
55 Ok(Self {
56 running: true,
57 conn,
58 queue_list,
59 pl_list,
60 selected_tab: SelectedTab::Queue,
61 browser,
62 inputmode: InputMode::Normal,
63 search_input: String::new(),
64 pl_newname_input: String::new(),
65 search_cursor_pos: 0,
66 pl_cursor_pos: 0,
67 playlist_popup: false,
68 append_list,
69 })
70 }
71
72 pub fn tick(&mut self) {
73 self.conn.update_status();
74 self.update_queue();
75 }
76
77 pub fn quit(&mut self) {
78 self.running = false;
79 }
80
81 pub fn get_queue(conn: &mut Connection, vec: &mut Vec<String>) {
82 // conn.conn.queue().unwrap().into_iter().for_each(|x| {
83 // if let Some(title) = x.title {
84 // if let Some(artist) = x.artist {
85 // vec.push(format!("{} - {}", artist, title));
86 // } else {
87 // vec.push(title)
88 // }
89 // } else {
90 // vec.push(x.file)
91 // }
92 // });
93 conn.conn.queue().unwrap().into_iter().for_each(|x| {
94 vec.push(x.file);
95 });
96 }
97
98 // Rescan the queue into queue_list
99 pub fn update_queue(&mut self) {
100 self.queue_list.list.clear();
101 Self::get_queue(&mut self.conn, &mut self.queue_list.list);
102 }
103
104 pub fn get_playlist(conn: &mut Client) -> AppResult<Vec<String>> {
105 let list: Vec<String> = conn.playlists()?.iter().map(|p| p.clone().name).collect();
106 Ok(list)
107 }
108
109 pub fn get_append_list(conn: &mut Client) -> AppResult<ContentList<String>> {
110 let mut list = ContentList::new();
111 list.list.push("Current Playlist".to_string());
112 for item in Self::get_playlist(conn)? {
113 list.list.push(item.to_string());
114 }
115
116 Ok(list)
117 }
118
119 /// Handles the <Space> event key
120 pub fn handle_add_or_remove_from_current_playlist(&mut self) -> AppResult<()> {
121 match self.selected_tab {
122 SelectedTab::DirectoryBrowser => {
123 let (_, file) = self.browser.filetree.get(self.browser.selected).unwrap();
124
125 let mut status = false;
126 for (i, song) in self.queue_list.list.clone().iter().enumerate() {
127 if song.contains(file) {
128 self.conn.conn.delete(i as u32).unwrap();
129 status = true;
130 }
131 }
132
133 if !status {
134 if let Some(full_path) = &self.conn.get_full_path(&file) {
135 let song = self.conn.get_song_with_only_filename(full_path);
136 self.conn.conn.push(&song)?;
137 }
138 }
139
140 if self.browser.selected != self.browser.filetree.len() - 1 {
141 self.browser.selected += 1;
142 }
143 }
144
145 SelectedTab::Queue => {
146 if self.queue_list.list.len() == 0 {
147 return Ok(());
148 }
149 let file = self
150 .queue_list
151 .list
152 .get(self.queue_list.index)
153 .unwrap()
154 .to_string();
155
156 for (i, song) in self.queue_list.list.clone().iter().enumerate() {
157 if song.contains(&file) {
158 self.conn.conn.delete(i as u32).unwrap();
159 if self.queue_list.index == self.queue_list.list.len() - 1
160 && self.queue_list.index != 0
161 {
162 self.queue_list.index -= 1;
163 }
164 }
165 }
166 }
167
168 _ => {}
169 }
170
171 self.update_queue();
172 Ok(())
173 }
174
175 /// Cycle through tabs
176 pub fn cycle_tabls(&mut self) {
177 self.selected_tab = match self.selected_tab {
178 SelectedTab::Queue => SelectedTab::DirectoryBrowser,
179 SelectedTab::DirectoryBrowser => SelectedTab::Playlists,
180 SelectedTab::Playlists => SelectedTab::DirectoryBrowser,
181 };
182 }
183
184 /// handles the Enter event on the directory browser
185 pub fn handle_enter(&mut self) -> AppResult<()> {
186 let browser = &mut self.browser;
187 let (t, path) = browser.filetree.get(browser.selected).unwrap();
188 if t == "directory" {
189 if path != "." {
190 browser.prev_path = browser.path.clone();
191 browser.path = browser.prev_path.clone() + "/" + path;
192 browser.update_directory(&mut self.conn)?;
193 browser.prev_selected = browser.selected;
194 browser.selected = 0;
195 }
196 } else {
197 // let list = conn
198 // .songs_filenames
199 // .iter()
200 // .map(|f| f.as_str())
201 // .collect::<Vec<&str>>();
202 // let (filename, _) = rust_fuzzy_search::fuzzy_search_sorted(&path, &list)
203 // .get(0)
204 // .unwrap()
205 // .clone();
206 let index = self.queue_list.list.iter().position(|x| x.contains(path));
207
208 if index.is_some() {
209 self.conn.conn.switch(index.unwrap() as u32)?;
210 } else {
211 for filename in self.conn.songs_filenames.clone().iter() {
212 if filename.contains(path) {
213 let song = self.conn.get_song_with_only_filename(filename);
214 self.conn.push(&song)?;
215 }
216 }
217
218 // updating queue, to avoid multiple pushes of the same songs if we enter multiple times before the queue gets updated
219 self.update_queue();
220 }
221 }
222 Ok(())
223 }
224
225 // Cursor movements
226 pub fn move_cursor_left(&mut self) {
227 match self.inputmode {
228 InputMode::PlaylistRename => {
229 let cursor_moved_left = self.pl_cursor_pos.saturating_sub(1);
230 self.pl_cursor_pos = self.clamp_cursor(cursor_moved_left);
231 }
232 InputMode::Editing => {
233 let cursor_moved_left = self.search_cursor_pos.saturating_sub(1);
234 self.search_cursor_pos = self.clamp_cursor(cursor_moved_left);
235 }
236 _ => {}
237 }
238 }
239
240 pub fn move_cursor_right(&mut self) {
241 match self.inputmode {
242 InputMode::PlaylistRename => {
243 let cursor_moved_right = self.pl_cursor_pos.saturating_add(1);
244 self.pl_cursor_pos = self.clamp_cursor(cursor_moved_right);
245 }
246 InputMode::Editing => {
247 let cursor_moved_right = self.search_cursor_pos.saturating_add(1);
248 self.search_cursor_pos = self.clamp_cursor(cursor_moved_right);
249 }
250 _ => {}
251 }
252 }
253
254 pub fn enter_char(&mut self, new_char: char) {
255 match self.inputmode {
256 InputMode::PlaylistRename => {
257 self.pl_newname_input.insert(self.pl_cursor_pos, new_char);
258 self.move_cursor_right();
259 }
260 InputMode::Editing => {
261 self.search_input.insert(self.search_cursor_pos, new_char);
262 self.move_cursor_right();
263 }
264 _ => {}
265 }
266 }
267
268 pub fn delete_char(&mut self) {
269 let is_not_cursor_leftmost = match self.inputmode {
270 InputMode::PlaylistRename => self.pl_cursor_pos != 0,
271 InputMode::Editing => self.search_cursor_pos != 0,
272 _ => false,
273 };
274
275 if is_not_cursor_leftmost {
276 // Method "remove" is not used on the saved text for deleting the selected char.
277 // Reason: Using remove on String works on bytes instead of the chars.
278 // Using remove would require special care because of char boundaries.
279
280 let current_index = match self.inputmode {
281 InputMode::Editing => self.search_cursor_pos,
282 InputMode::PlaylistRename => self.pl_cursor_pos,
283 _ => 0,
284 };
285
286 let from_left_to_current_index = current_index - 1;
287
288 if self.inputmode == InputMode::PlaylistRename {
289 // Getting all characters before the selected character.
290 let before_char_to_delete = self
291 .pl_newname_input
292 .chars()
293 .take(from_left_to_current_index);
294 // Getting all characters after selected character.
295 let after_char_to_delete = self.pl_newname_input.chars().skip(current_index);
296 // Put all characters together except the selected one.
297 // By leaving the selected one out, it is forgotten and therefore deleted.
298 self.pl_newname_input = before_char_to_delete.chain(after_char_to_delete).collect();
299 self.move_cursor_left();
300 } else if self.inputmode == InputMode::Editing {
301 // Getting all characters before the selected character.
302 let before_char_to_delete =
303 self.search_input.chars().take(from_left_to_current_index);
304 // Getting all characters after selected character.
305 let after_char_to_delete = self.search_input.chars().skip(current_index);
306 // Put all characters together except the selected one.
307 // By leaving the selected one out, it is forgotten and therefore deleted.
308 self.search_input = before_char_to_delete.chain(after_char_to_delete).collect();
309 self.move_cursor_left();
310 }
311 }
312 }
313
314 pub fn clamp_cursor(&self, new_cursor_pos: usize) -> usize {
315 match self.inputmode {
316 InputMode::PlaylistRename => new_cursor_pos.clamp(0, self.pl_newname_input.len()),
317 InputMode::Editing => new_cursor_pos.clamp(0, self.search_input.len()),
318 _ => 0,
319 }
320 }
321
322 pub fn reset_cursor(&mut self) {
323 match self.inputmode {
324 InputMode::Editing => {
325 self.search_cursor_pos = 0;
326 }
327 InputMode::PlaylistRename => {
328 self.pl_cursor_pos = 0;
329 }
330 _ => {}
331 }
332 }
333
334 /// Given time in seconds, convert it to hh:mm:ss
335 pub fn format_time(time: Duration) -> String {
336 let time = time.as_secs();
337 let h = time / 3600;
338 let m = (time % 3600) / 60;
339 let s = (time % 3600) % 60;
340 if h == 0 {
341 format!("{:02}:{:02}", m, s)
342 } else {
343 format!("{:02}:{:02}:{:02}", h, m, s)
344 }
345 }
346
347 pub fn change_playlist_name(&mut self) -> AppResult<()> {
348 match self.selected_tab {
349 SelectedTab::Playlists => {
350 self.inputmode = InputMode::PlaylistRename;
351 }
352 _ => {}
353 }
354 Ok(())
355 }
356}