Krolyxon
Commit 5b6a79c

rmptuisrcapp.rs

341 lines · 11.7 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
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 (_, file) = self.browser.filetree.get(self.browser.selected).unwrap();
114
115 let mut status = false;
116 for (i, song) in self.queue_list.list.clone().iter().enumerate() {
117 if song.file.contains(file) {
118 self.conn.conn.delete(i as u32).unwrap();
119 status = true;
120 }
121 }
122
123 if !status {
124 if let Some(full_path) = &self.conn.get_full_path(file) {
125 let song = self.conn.get_song_with_only_filename(full_path);
126 self.conn.conn.push(&song)?;
127 }
128 }
129
130 if self.browser.selected != self.browser.filetree.len() - 1 {
131 self.browser.selected += 1;
132 }
133 }
134
135 SelectedTab::Queue => {
136 if self.queue_list.list.is_empty() {
137 return Ok(());
138 }
139 let file = self
140 .queue_list
141 .list
142 .get(self.queue_list.index)
143 .unwrap()
144 .file
145 .to_string();
146
147 for (i, song) in self.queue_list.list.clone().iter().enumerate() {
148 if song.file.contains(&file) {
149 self.conn.conn.delete(i as u32).unwrap();
150 if self.queue_list.index == self.queue_list.list.len() - 1
151 && self.queue_list.index != 0
152 {
153 self.queue_list.index -= 1;
154 }
155 }
156 }
157 }
158
159 _ => {}
160 }
161
162 self.update_queue();
163 self.conn.update_status();
164 Ok(())
165 }
166
167 /// Cycle through tabs
168 pub fn cycle_tabls(&mut self) {
169 self.selected_tab = match self.selected_tab {
170 SelectedTab::Queue => SelectedTab::DirectoryBrowser,
171 SelectedTab::DirectoryBrowser => SelectedTab::Playlists,
172 SelectedTab::Playlists => SelectedTab::DirectoryBrowser,
173 };
174 }
175
176 /// handles the Enter event on the directory browser
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 index = self
190 .queue_list
191 .list
192 .iter()
193 .position(|x| {
194 let file = x.file.split("/").last().unwrap();
195 file.eq(path)
196 });
197
198 if index.is_some() {
199 self.conn.conn.switch(index.unwrap() as u32)?;
200 } else {
201 let mut filename = format!("{}/{}", browser.path, path);
202
203 // Remove "./" from the beginning of filename
204 filename.remove(0);
205 filename.remove(0);
206
207 let song = self.conn.get_song_with_only_filename(&filename);
208 self.conn.push(&song)?;
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 // Cursor movements
218 pub fn move_cursor_left(&mut self) {
219 match self.inputmode {
220 InputMode::PlaylistRename => {
221 let cursor_moved_left = self.pl_cursor_pos.saturating_sub(1);
222 self.pl_cursor_pos = self.clamp_cursor(cursor_moved_left);
223 }
224 InputMode::Editing => {
225 let cursor_moved_left = self.search_cursor_pos.saturating_sub(1);
226 self.search_cursor_pos = self.clamp_cursor(cursor_moved_left);
227 }
228 _ => {}
229 }
230 }
231
232 pub fn move_cursor_right(&mut self) {
233 match self.inputmode {
234 InputMode::PlaylistRename => {
235 let cursor_moved_right = self.pl_cursor_pos.saturating_add(1);
236 self.pl_cursor_pos = self.clamp_cursor(cursor_moved_right);
237 }
238 InputMode::Editing => {
239 let cursor_moved_right = self.search_cursor_pos.saturating_add(1);
240 self.search_cursor_pos = self.clamp_cursor(cursor_moved_right);
241 }
242 _ => {}
243 }
244 }
245
246 pub fn enter_char(&mut self, new_char: char) {
247 match self.inputmode {
248 InputMode::PlaylistRename => {
249 self.pl_newname_input.insert(self.pl_cursor_pos, new_char);
250 self.move_cursor_right();
251 }
252 InputMode::Editing => {
253 self.search_input.insert(self.search_cursor_pos, new_char);
254 self.move_cursor_right();
255 }
256 _ => {}
257 }
258 }
259
260 pub fn delete_char(&mut self) {
261 let is_not_cursor_leftmost = match self.inputmode {
262 InputMode::PlaylistRename => self.pl_cursor_pos != 0,
263 InputMode::Editing => self.search_cursor_pos != 0,
264 _ => false,
265 };
266
267 if is_not_cursor_leftmost {
268 // Method "remove" is not used on the saved text for deleting the selected char.
269 // Reason: Using remove on String works on bytes instead of the chars.
270 // Using remove would require special care because of char boundaries.
271
272 let current_index = match self.inputmode {
273 InputMode::Editing => self.search_cursor_pos,
274 InputMode::PlaylistRename => self.pl_cursor_pos,
275 _ => 0,
276 };
277
278 let from_left_to_current_index = current_index - 1;
279
280 if self.inputmode == InputMode::PlaylistRename {
281 // Getting all characters before the selected character.
282 let before_char_to_delete = self
283 .pl_newname_input
284 .chars()
285 .take(from_left_to_current_index);
286 // Getting all characters after selected character.
287 let after_char_to_delete = self.pl_newname_input.chars().skip(current_index);
288 // Put all characters together except the selected one.
289 // By leaving the selected one out, it is forgotten and therefore deleted.
290 self.pl_newname_input = before_char_to_delete.chain(after_char_to_delete).collect();
291 self.move_cursor_left();
292 } else if self.inputmode == InputMode::Editing {
293 let before_char_to_delete =
294 self.search_input.chars().take(from_left_to_current_index);
295 let after_char_to_delete = self.search_input.chars().skip(current_index);
296 self.search_input = before_char_to_delete.chain(after_char_to_delete).collect();
297 self.move_cursor_left();
298 }
299 }
300 }
301
302 pub fn clamp_cursor(&self, new_cursor_pos: usize) -> usize {
303 match self.inputmode {
304 InputMode::PlaylistRename => new_cursor_pos.clamp(0, self.pl_newname_input.len()),
305 InputMode::Editing => new_cursor_pos.clamp(0, self.search_input.len()),
306 _ => 0,
307 }
308 }
309
310 pub fn reset_cursor(&mut self) {
311 match self.inputmode {
312 InputMode::Editing => {
313 self.search_cursor_pos = 0;
314 }
315 InputMode::PlaylistRename => {
316 self.pl_cursor_pos = 0;
317 }
318 _ => {}
319 }
320 }
321
322 /// Given time in seconds, convert it to hh:mm:ss
323 pub fn format_time(time: Duration) -> String {
324 let time = time.as_secs();
325 let h = time / 3600;
326 let m = (time % 3600) / 60;
327 let s = (time % 3600) % 60;
328 if h == 0 {
329 format!("{:02}:{:02}", m, s)
330 } else {
331 format!("{:02}:{:02}:{:02}", h, m, s)
332 }
333 }
334
335 pub fn change_playlist_name(&mut self) -> AppResult<()> {
336 if self.selected_tab == SelectedTab::Playlists {
337 self.inputmode = InputMode::PlaylistRename;
338 }
339 Ok(())
340 }
341}