Krolyxon
Commit ba002d5

rmptuisrcapp.rs

462 lines · 16.4 KB · Rust

1use std::{path::Path, time::Duration};
2
3use crate::browser::FileBrowser;
4use crate::connection::Connection;
5use crate::list::ContentList;
6use crate::ui::InputMode;
7use crate::utils::FileExtension;
8use mpd::{Client, Song};
9use ratatui::widgets::{ListState, TableState};
10
11// Application result type
12pub type AppResult<T> = std::result::Result<T, Box<dyn std::error::Error>>;
13
14/// Application
15#[derive(Debug)]
16pub struct App {
17 pub running: bool, // Check if app is running
18 pub conn: Connection, // Connection
19 pub browser: FileBrowser, // Directory browser
20 pub queue_list: ContentList<Song>, // Stores the current playing queue
21 pub pl_list: ContentList<String>, // Stores list of playlists
22 pub selected_tab: SelectedTab, // Used to switch between tabs
23
24 // Search
25 pub inputmode: InputMode, // Defines input mode, Normal or Search
26 pub search_input: String, // Stores the userinput to be searched
27 pub search_cursor_pos: usize, // Stores the cursor position for searching
28
29 pub pl_newname_input: String, // Stores the new name of the playlist
30 pub pl_cursor_pos: usize, // Stores the cursor position for renaming playlist
31
32 pub pl_new_pl_input: String, // Stores the name of new playlist to be created
33 pub pl_new_pl_cursor_pos: usize, // Stores the cursor position of new playlist to be created
34 pub pl_new_pl_songs_buffer: Vec<Song>, // Buffer for songs that need to be added to the newly created playlist
35
36 // playlist variables
37 // used to show playlist popup
38 pub playlist_popup: bool,
39 pub append_list: ContentList<String>,
40
41 // Determines if the database should be updated or not
42 pub should_update_song_list: bool,
43
44 // States
45 pub queue_state: TableState,
46 pub browser_state: TableState,
47 pub playlists_state: ListState,
48}
49
50#[derive(Debug, PartialEq, Clone)]
51pub enum SelectedTab {
52 DirectoryBrowser,
53 Queue,
54 Playlists,
55}
56
57impl App {
58 pub fn builder(addrs: &str) -> AppResult<Self> {
59 let mut conn = Connection::builder(addrs)?;
60 let mut queue_list = ContentList::new();
61 let mut pl_list = ContentList::new();
62
63 pl_list.list = Self::get_playlist(&mut conn.conn)?;
64 pl_list.list.sort();
65
66 let append_list = Self::get_append_list(&mut conn.conn)?;
67 Self::get_queue(&mut conn, &mut queue_list.list);
68
69 let browser = FileBrowser::new();
70
71 let queue_state = TableState::new();
72 let browser_state = TableState::new();
73 let playlists_state = ListState::default();
74
75 Ok(Self {
76 running: true,
77 conn,
78 queue_list,
79 pl_list,
80 selected_tab: SelectedTab::Queue,
81 browser,
82 inputmode: InputMode::Normal,
83 search_input: String::new(),
84 pl_newname_input: String::new(),
85 search_cursor_pos: 0,
86 pl_cursor_pos: 0,
87 playlist_popup: false,
88 pl_new_pl_input: String::new(),
89 pl_new_pl_cursor_pos: 0,
90 pl_new_pl_songs_buffer: Vec::new(),
91 append_list,
92 should_update_song_list: false,
93 queue_state,
94 browser_state,
95 playlists_state,
96 })
97 }
98
99 pub fn tick(&mut self) -> AppResult<()> {
100 self.conn.update_status();
101 self.update_queue();
102
103 // Deals with database update
104 if self.should_update_song_list && self.conn.status.updating_db.is_none() {
105 // Update the songs list
106 self.conn.songs_filenames = self
107 .conn
108 .conn
109 .listall()?
110 .into_iter()
111 .map(|x| x.file)
112 .collect();
113
114 self.browser.update_directory(&mut self.conn)?;
115
116 self.should_update_song_list = false;
117 }
118
119 Ok(())
120 }
121
122 pub fn quit(&mut self) {
123 self.running = false;
124 }
125
126 pub fn get_queue(conn: &mut Connection, vec: &mut Vec<Song>) {
127 conn.conn.queue().unwrap().into_iter().for_each(|x| {
128 vec.push(x);
129 });
130 }
131
132 // Rescan the queue into queue_list
133 pub fn update_queue(&mut self) {
134 self.queue_list.list.clear();
135 Self::get_queue(&mut self.conn, &mut self.queue_list.list);
136 }
137
138 pub fn get_playlist(conn: &mut Client) -> AppResult<Vec<String>> {
139 let list: Vec<String> = conn.playlists()?.iter().map(|p| p.clone().name).collect();
140 Ok(list)
141 }
142
143 pub fn get_append_list(conn: &mut Client) -> AppResult<ContentList<String>> {
144 let mut list = ContentList::new();
145 list.list.push("New Playlist".to_string());
146 list.list.push("Current Playlist".to_string());
147 for item in Self::get_playlist(conn)? {
148 list.list.push(item.to_string());
149 }
150
151 Ok(list)
152 }
153
154 /// Handles the <Space> event key
155 pub fn handle_add_or_remove_from_current_playlist(&mut self) -> AppResult<()> {
156 match self.selected_tab {
157 SelectedTab::DirectoryBrowser => {
158 let (content_type, content) =
159 self.browser.filetree.get(self.browser.selected).unwrap();
160 if content_type == "directory" {
161 let file = format!("{}/{}", self.browser.path, content);
162 let songs = self.conn.conn.listfiles(&file).unwrap_or_default();
163 for (t, f) in songs.iter() {
164 if t == "file"
165 && Path::new(&f).has_extension(&[
166 "mp3", "ogg", "flac", "m4a", "wav", "aac", "opus", "ape", "wma",
167 "mpc", "aiff", "dff", "mp2", "mka",
168 ])
169 {
170 let path = file.clone() + "/" + f;
171 let full_path = path.strip_prefix("./").unwrap_or("");
172 let song = self.conn.get_song_with_only_filename(full_path);
173 self.conn.conn.push(&song)?;
174 }
175 }
176 } else if content_type == "file" {
177 let mut status = false;
178 for (i, song) in self.queue_list.list.clone().iter().enumerate() {
179 let song_path = song.file.split('/').last().unwrap_or_default();
180 if song_path.eq(content) {
181 self.conn.conn.delete(i as u32).unwrap();
182 status = true;
183 }
184 }
185
186 if !status {
187 let mut filename = format!("{}/{}", self.browser.path, content);
188
189 // Remove "./" from the beginning of filename
190 filename.remove(0);
191 filename.remove(0);
192
193 let song = self.conn.get_song_with_only_filename(&filename);
194 self.conn.conn.push(&song)?;
195
196 // updating queue, to avoid multiple pushes of the same songs if we enter multiple times before the queue gets updated
197 self.update_queue();
198 }
199 }
200
201 // Highlight next row if possible
202 if self.browser.selected != self.browser.filetree.len() - 1 {
203 self.browser.selected += 1;
204 }
205 }
206
207 SelectedTab::Queue => {
208 if self.queue_list.list.is_empty() {
209 return Ok(());
210 }
211 let file = self
212 .queue_list
213 .list
214 .get(self.queue_list.index)
215 .unwrap()
216 .file
217 .to_string();
218
219 for (i, song) in self.queue_list.list.clone().iter().enumerate() {
220 if song.file.eq(&file) {
221 self.conn.conn.delete(i as u32).unwrap();
222 if self.queue_list.index == self.queue_list.list.len() - 1
223 && self.queue_list.index != 0
224 {
225 self.queue_list.index -= 1;
226 }
227 }
228 }
229 }
230
231 _ => {}
232 }
233
234 self.update_queue();
235 self.conn.update_status();
236 Ok(())
237 }
238
239 /// Cycle through tabs
240 pub fn cycle_tabls(&mut self) {
241 self.selected_tab = match self.selected_tab {
242 SelectedTab::Queue => SelectedTab::DirectoryBrowser,
243 SelectedTab::DirectoryBrowser => SelectedTab::Playlists,
244 SelectedTab::Playlists => SelectedTab::DirectoryBrowser,
245 };
246 }
247
248 /// handles the Enter event on the directory browser
249 pub fn handle_enter(&mut self) -> AppResult<()> {
250 let browser = &mut self.browser;
251 let (t, path) = browser.filetree.get(browser.selected).unwrap();
252 if t == "directory" {
253 if path != "." {
254 browser.prev_path.clone_from(&browser.path);
255 browser.path = browser.prev_path.clone() + "/" + path;
256 browser.update_directory(&mut self.conn)?;
257 browser.prev_selected = browser.selected;
258 browser.selected = 0;
259 }
260 } else {
261 let index = self.queue_list.list.iter().position(|x| {
262 let file = x.file.split('/').last().unwrap_or_default();
263 file.eq(path)
264 });
265
266 if index.is_some() {
267 self.conn.conn.switch(index.unwrap() as u32)?;
268 } else {
269 let mut filename = format!("{}/{}", browser.path, path);
270
271 // Remove "./" from the beginning of filename
272 filename.remove(0);
273 filename.remove(0);
274
275 let song = self.conn.get_song_with_only_filename(&filename);
276 self.conn.push(&song)?;
277
278 // updating queue, to avoid multiple pushes of the same songs if we enter multiple times before the queue gets updated
279 self.update_queue();
280 }
281 }
282 Ok(())
283 }
284
285 // Cursor movements
286 pub fn move_cursor_left(&mut self) {
287 match self.inputmode {
288 InputMode::PlaylistRename => {
289 let cursor_moved_left = self.pl_cursor_pos.saturating_sub(1);
290 self.pl_cursor_pos = self.clamp_cursor(cursor_moved_left);
291 }
292 InputMode::Editing => {
293 let cursor_moved_left = self.search_cursor_pos.saturating_sub(1);
294 self.search_cursor_pos = self.clamp_cursor(cursor_moved_left);
295 }
296 InputMode::NewPlaylist => {
297 let cursor_moved_left = self.pl_new_pl_cursor_pos.saturating_sub(1);
298 self.pl_new_pl_cursor_pos = self.clamp_cursor(cursor_moved_left);
299 }
300 _ => {}
301 }
302 }
303
304 pub fn move_cursor_right(&mut self) {
305 match self.inputmode {
306 InputMode::PlaylistRename => {
307 let cursor_moved_right = self.pl_cursor_pos.saturating_add(1);
308 self.pl_cursor_pos = self.clamp_cursor(cursor_moved_right);
309 }
310 InputMode::Editing => {
311 let cursor_moved_right = self.search_cursor_pos.saturating_add(1);
312 self.search_cursor_pos = self.clamp_cursor(cursor_moved_right);
313 }
314
315 InputMode::NewPlaylist => {
316 let cursor_moved_right = self.pl_new_pl_cursor_pos.saturating_add(1);
317 self.pl_new_pl_cursor_pos = self.clamp_cursor(cursor_moved_right);
318 }
319
320 _ => {}
321 }
322 }
323
324 pub fn enter_char(&mut self, new_char: char) {
325 match self.inputmode {
326 InputMode::PlaylistRename => {
327 self.pl_newname_input.insert(self.pl_cursor_pos, new_char);
328 }
329 InputMode::NewPlaylist => {
330 self.pl_new_pl_input
331 .insert(self.pl_new_pl_cursor_pos, new_char);
332 }
333 InputMode::Editing => {
334 self.search_input.insert(self.search_cursor_pos, new_char);
335 }
336 _ => {}
337 }
338
339 self.move_cursor_right();
340 }
341
342 pub fn delete_char(&mut self) {
343 let is_not_cursor_leftmost = match self.inputmode {
344 InputMode::PlaylistRename => self.pl_cursor_pos != 0,
345 InputMode::NewPlaylist => self.pl_new_pl_cursor_pos != 0,
346 InputMode::Editing => self.search_cursor_pos != 0,
347 _ => false,
348 };
349
350 if is_not_cursor_leftmost {
351 // Method "remove" is not used on the saved text for deleting the selected char.
352 // Reason: Using remove on String works on bytes instead of the chars.
353 // Using remove would require special care because of char boundaries.
354
355 let current_index = match self.inputmode {
356 InputMode::Editing => self.search_cursor_pos,
357 InputMode::PlaylistRename => self.pl_cursor_pos,
358 InputMode::NewPlaylist => self.pl_new_pl_cursor_pos,
359 _ => 0,
360 };
361
362 let from_left_to_current_index = current_index - 1;
363
364 if self.inputmode == InputMode::PlaylistRename {
365 let before_char_to_delete = self
366 .pl_newname_input
367 .chars()
368 .take(from_left_to_current_index);
369 let after_char_to_delete = self.pl_newname_input.chars().skip(current_index);
370
371 self.pl_newname_input = before_char_to_delete.chain(after_char_to_delete).collect();
372 self.move_cursor_left();
373 } else if self.inputmode == InputMode::NewPlaylist {
374 let before_char_to_delete = self
375 .pl_new_pl_input
376 .chars()
377 .take(from_left_to_current_index);
378 let after_char_to_delete = self.pl_new_pl_input.chars().skip(current_index);
379
380 self.pl_new_pl_input = before_char_to_delete.chain(after_char_to_delete).collect();
381 self.move_cursor_left();
382 } else if self.inputmode == InputMode::Editing {
383 let before_char_to_delete =
384 self.search_input.chars().take(from_left_to_current_index);
385 let after_char_to_delete = self.search_input.chars().skip(current_index);
386
387 self.search_input = before_char_to_delete.chain(after_char_to_delete).collect();
388 self.move_cursor_left();
389 }
390 }
391 }
392
393 pub fn clamp_cursor(&self, new_cursor_pos: usize) -> usize {
394 match self.inputmode {
395 InputMode::PlaylistRename => new_cursor_pos.clamp(0, self.pl_newname_input.len()),
396 InputMode::NewPlaylist => new_cursor_pos.clamp(0, self.pl_new_pl_input.len()),
397 InputMode::Editing => new_cursor_pos.clamp(0, self.search_input.len()),
398 _ => 0,
399 }
400 }
401
402 pub fn reset_cursor(&mut self) {
403 match self.inputmode {
404 InputMode::Editing => {
405 self.search_cursor_pos = 0;
406 }
407 InputMode::PlaylistRename => {
408 self.pl_cursor_pos = 0;
409 }
410 InputMode::NewPlaylist => {
411 self.pl_new_pl_cursor_pos = 0;
412 }
413 _ => {}
414 }
415 }
416
417 /// Given time in seconds, convert it to hh:mm:ss
418 pub fn format_time(time: Duration) -> String {
419 let time = time.as_secs();
420 let h = time / 3600;
421 let m = (time % 3600) / 60;
422 let s = (time % 3600) % 60;
423 if h == 0 {
424 format!("{:02}:{:02}", m, s)
425 } else {
426 format!("{:02}:{:02}:{:02}", h, m, s)
427 }
428 }
429
430 // Mouse event handlers
431 pub fn handle_scroll_up(&mut self) {
432 match self.selected_tab {
433 SelectedTab::Queue => {
434 self.queue_list.prev();
435 }
436 SelectedTab::DirectoryBrowser => {
437 self.browser.prev();
438 }
439 SelectedTab::Playlists => {
440 self.pl_list.prev();
441 }
442 }
443 }
444
445 pub fn handle_scroll_down(&mut self) {
446 match self.selected_tab {
447 SelectedTab::Queue => {
448 self.queue_list.next();
449 }
450 SelectedTab::DirectoryBrowser => {
451 self.browser.next();
452 }
453 SelectedTab::Playlists => {
454 self.pl_list.next();
455 }
456 }
457 }
458
459 pub fn handle_mouse_left_click(&mut self, _x: u16, _y: u16) -> AppResult<()> {
460 Ok(())
461 }
462}