Krolyxon
Commit e181181

rmptuisrcapp.rs

362 lines · 13.1 KB · Rust

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