Krolyxon
Commit 51a3094

rmptuisrcapp.rs

357 lines · 12.6 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, 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::new(addrs).unwrap();
45 let mut queue_list = ContentList::new();
46 let mut pl_list = ContentList::new();
47 pl_list.list = Self::get_playlist(&mut conn.conn)?;
48
49 let append_list = Self::get_append_list(&mut conn.conn)?;
50 Self::get_queue(&mut conn, &mut queue_list.list);
51
52 let browser = FileBrowser::new();
53
54 Ok(Self {
55 running: true,
56 conn,
57 queue_list,
58 pl_list,
59 selected_tab: SelectedTab::Queue,
60 browser,
61 inputmode: InputMode::Normal,
62 search_input: String::new(),
63 pl_newname_input: String::new(),
64 search_cursor_pos: 0,
65 pl_cursor_pos: 0,
66 playlist_popup: false,
67 append_list,
68 })
69 }
70
71 pub fn tick(&mut self) {
72 self.conn.update_status();
73 self.update_queue();
74 }
75
76 pub fn quit(&mut self) {
77 self.running = false;
78 }
79
80 pub fn get_queue(conn: &mut Connection, vec: &mut Vec<Song>) {
81 // conn.conn.queue().unwrap().into_iter().for_each(|x| {
82 // if let Some(title) = x.title {
83 // if let Some(artist) = x.artist {
84 // vec.push(format!("{} - {}", artist, title));
85 // } else {
86 // vec.push(title)
87 // }
88 // } else {
89 // vec.push(x.file)
90 // }
91 // });
92 conn.conn.queue().unwrap().into_iter().for_each(|x| {
93 vec.push(x);
94 });
95 }
96
97 // Rescan the queue into queue_list
98 pub fn update_queue(&mut self) {
99 self.queue_list.list.clear();
100 Self::get_queue(&mut self.conn, &mut self.queue_list.list);
101 }
102
103 pub fn get_playlist(conn: &mut Client) -> AppResult<Vec<String>> {
104 let list: Vec<String> = conn.playlists()?.iter().map(|p| p.clone().name).collect();
105 Ok(list)
106 }
107
108 pub fn get_append_list(conn: &mut Client) -> AppResult<ContentList<String>> {
109 let mut list = ContentList::new();
110 list.list.push("Current Playlist".to_string());
111 for item in Self::get_playlist(conn)? {
112 list.list.push(item.to_string());
113 }
114
115 Ok(list)
116 }
117
118 /// Handles the <Space> event key
119 pub fn handle_add_or_remove_from_current_playlist(&mut self) -> AppResult<()> {
120 match self.selected_tab {
121 SelectedTab::DirectoryBrowser => {
122 let (_, file) = self.browser.filetree.get(self.browser.selected).unwrap();
123
124 let mut status = false;
125 for (i, song) in self.queue_list.list.clone().iter().enumerate() {
126 if song.file.contains(file) {
127 self.conn.conn.delete(i as u32).unwrap();
128 status = true;
129 }
130 }
131
132 if !status {
133 if let Some(full_path) = &self.conn.get_full_path(file) {
134 let song = self.conn.get_song_with_only_filename(full_path);
135 self.conn.conn.push(&song)?;
136 }
137 }
138
139 if self.browser.selected != self.browser.filetree.len() - 1 {
140 self.browser.selected += 1;
141 }
142 }
143
144 SelectedTab::Queue => {
145 if self.queue_list.list.is_empty() {
146 return Ok(());
147 }
148 let file = self
149 .queue_list
150 .list
151 .get(self.queue_list.index)
152 .unwrap()
153 .file
154 .to_string();
155
156 for (i, song) in self.queue_list.list.clone().iter().enumerate() {
157 if song.file.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
207 .queue_list
208 .list
209 .iter()
210 .position(|x| x.file.contains(path));
211
212 if index.is_some() {
213 self.conn.conn.switch(index.unwrap() as u32)?;
214 } else {
215 for filename in self.conn.songs_filenames.clone().iter() {
216 if filename.contains(path) {
217 let song = self.conn.get_song_with_only_filename(filename);
218 self.conn.push(&song)?;
219 }
220 }
221
222 // updating queue, to avoid multiple pushes of the same songs if we enter multiple times before the queue gets updated
223 self.update_queue();
224 }
225 }
226 Ok(())
227 }
228
229 // Cursor movements
230 pub fn move_cursor_left(&mut self) {
231 match self.inputmode {
232 InputMode::PlaylistRename => {
233 let cursor_moved_left = self.pl_cursor_pos.saturating_sub(1);
234 self.pl_cursor_pos = self.clamp_cursor(cursor_moved_left);
235 }
236 InputMode::Editing => {
237 let cursor_moved_left = self.search_cursor_pos.saturating_sub(1);
238 self.search_cursor_pos = self.clamp_cursor(cursor_moved_left);
239 }
240 _ => {}
241 }
242 }
243
244 pub fn move_cursor_right(&mut self) {
245 match self.inputmode {
246 InputMode::PlaylistRename => {
247 let cursor_moved_right = self.pl_cursor_pos.saturating_add(1);
248 self.pl_cursor_pos = self.clamp_cursor(cursor_moved_right);
249 }
250 InputMode::Editing => {
251 let cursor_moved_right = self.search_cursor_pos.saturating_add(1);
252 self.search_cursor_pos = self.clamp_cursor(cursor_moved_right);
253 }
254 _ => {}
255 }
256 }
257
258 pub fn enter_char(&mut self, new_char: char) {
259 match self.inputmode {
260 InputMode::PlaylistRename => {
261 self.pl_newname_input.insert(self.pl_cursor_pos, new_char);
262 self.move_cursor_right();
263 }
264 InputMode::Editing => {
265 self.search_input.insert(self.search_cursor_pos, new_char);
266 self.move_cursor_right();
267 }
268 _ => {}
269 }
270 }
271
272 pub fn delete_char(&mut self) {
273 let is_not_cursor_leftmost = match self.inputmode {
274 InputMode::PlaylistRename => self.pl_cursor_pos != 0,
275 InputMode::Editing => self.search_cursor_pos != 0,
276 _ => false,
277 };
278
279 if is_not_cursor_leftmost {
280 // Method "remove" is not used on the saved text for deleting the selected char.
281 // Reason: Using remove on String works on bytes instead of the chars.
282 // Using remove would require special care because of char boundaries.
283
284 let current_index = match self.inputmode {
285 InputMode::Editing => self.search_cursor_pos,
286 InputMode::PlaylistRename => self.pl_cursor_pos,
287 _ => 0,
288 };
289
290 let from_left_to_current_index = current_index - 1;
291
292 if self.inputmode == InputMode::PlaylistRename {
293 // Getting all characters before the selected character.
294 let before_char_to_delete = self
295 .pl_newname_input
296 .chars()
297 .take(from_left_to_current_index);
298 // Getting all characters after selected character.
299 let after_char_to_delete = self.pl_newname_input.chars().skip(current_index);
300 // Put all characters together except the selected one.
301 // By leaving the selected one out, it is forgotten and therefore deleted.
302 self.pl_newname_input = before_char_to_delete.chain(after_char_to_delete).collect();
303 self.move_cursor_left();
304 } else if self.inputmode == InputMode::Editing {
305 // Getting all characters before the selected character.
306 let before_char_to_delete =
307 self.search_input.chars().take(from_left_to_current_index);
308 // Getting all characters after selected character.
309 let after_char_to_delete = self.search_input.chars().skip(current_index);
310 // Put all characters together except the selected one.
311 // By leaving the selected one out, it is forgotten and therefore deleted.
312 self.search_input = before_char_to_delete.chain(after_char_to_delete).collect();
313 self.move_cursor_left();
314 }
315 }
316 }
317
318 pub fn clamp_cursor(&self, new_cursor_pos: usize) -> usize {
319 match self.inputmode {
320 InputMode::PlaylistRename => new_cursor_pos.clamp(0, self.pl_newname_input.len()),
321 InputMode::Editing => new_cursor_pos.clamp(0, self.search_input.len()),
322 _ => 0,
323 }
324 }
325
326 pub fn reset_cursor(&mut self) {
327 match self.inputmode {
328 InputMode::Editing => {
329 self.search_cursor_pos = 0;
330 }
331 InputMode::PlaylistRename => {
332 self.pl_cursor_pos = 0;
333 }
334 _ => {}
335 }
336 }
337
338 /// Given time in seconds, convert it to hh:mm:ss
339 pub fn format_time(time: Duration) -> String {
340 let time = time.as_secs();
341 let h = time / 3600;
342 let m = (time % 3600) / 60;
343 let s = (time % 3600) % 60;
344 if h == 0 {
345 format!("{:02}:{:02}", m, s)
346 } else {
347 format!("{:02}:{:02}:{:02}", h, m, s)
348 }
349 }
350
351 pub fn change_playlist_name(&mut self) -> AppResult<()> {
352 if self.selected_tab == SelectedTab::Playlists {
353 self.inputmode = InputMode::PlaylistRename;
354 }
355 Ok(())
356 }
357}