Krolyxon
Commit bc7ab75

rmptuisrcapp.rs

335 lines · 11.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 vec.push(x);
83 });
84 }
85
86 // Rescan the queue into queue_list
87 pub fn update_queue(&mut self) {
88 self.queue_list.list.clear();
89 Self::get_queue(&mut self.conn, &mut self.queue_list.list);
90 }
91
92 pub fn get_playlist(conn: &mut Client) -> AppResult<Vec<String>> {
93 let list: Vec<String> = conn.playlists()?.iter().map(|p| p.clone().name).collect();
94 Ok(list)
95 }
96
97 pub fn get_append_list(conn: &mut Client) -> AppResult<ContentList<String>> {
98 let mut list = ContentList::new();
99 list.list.push("Current Playlist".to_string());
100 for item in Self::get_playlist(conn)? {
101 list.list.push(item.to_string());
102 }
103
104 Ok(list)
105 }
106
107 /// Handles the <Space> event key
108 pub fn handle_add_or_remove_from_current_playlist(&mut self) -> AppResult<()> {
109 match self.selected_tab {
110 SelectedTab::DirectoryBrowser => {
111 let (_, file) = self.browser.filetree.get(self.browser.selected).unwrap();
112
113 let mut status = false;
114 for (i, song) in self.queue_list.list.clone().iter().enumerate() {
115 if song.file.contains(file) {
116 self.conn.conn.delete(i as u32).unwrap();
117 status = true;
118 }
119 }
120
121 if !status {
122 if let Some(full_path) = &self.conn.get_full_path(file) {
123 let song = self.conn.get_song_with_only_filename(full_path);
124 self.conn.conn.push(&song)?;
125 }
126 }
127
128 if self.browser.selected != self.browser.filetree.len() - 1 {
129 self.browser.selected += 1;
130 }
131 }
132
133 SelectedTab::Queue => {
134 if self.queue_list.list.is_empty() {
135 return Ok(());
136 }
137 let file = self
138 .queue_list
139 .list
140 .get(self.queue_list.index)
141 .unwrap()
142 .file
143 .to_string();
144
145 for (i, song) in self.queue_list.list.clone().iter().enumerate() {
146 if song.file.contains(&file) {
147 self.conn.conn.delete(i as u32).unwrap();
148 if self.queue_list.index == self.queue_list.list.len() - 1
149 && self.queue_list.index != 0
150 {
151 self.queue_list.index -= 1;
152 }
153 }
154 }
155 }
156
157 _ => {}
158 }
159
160 self.update_queue();
161 Ok(())
162 }
163
164 /// Cycle through tabs
165 pub fn cycle_tabls(&mut self) {
166 self.selected_tab = match self.selected_tab {
167 SelectedTab::Queue => SelectedTab::DirectoryBrowser,
168 SelectedTab::DirectoryBrowser => SelectedTab::Playlists,
169 SelectedTab::Playlists => SelectedTab::DirectoryBrowser,
170 };
171 }
172
173 /// handles the Enter event on the directory browser
174 pub fn handle_enter(&mut self) -> AppResult<()> {
175 let browser = &mut self.browser;
176 let (t, path) = browser.filetree.get(browser.selected).unwrap();
177 if t == "directory" {
178 if path != "." {
179 browser.prev_path = browser.path.clone();
180 browser.path = browser.prev_path.clone() + "/" + path;
181 browser.update_directory(&mut self.conn)?;
182 browser.prev_selected = browser.selected;
183 browser.selected = 0;
184 }
185 } else {
186 let index = self
187 .queue_list
188 .list
189 .iter()
190 .position(|x| x.file.contains(path));
191
192 if index.is_some() {
193 self.conn.conn.switch(index.unwrap() as u32)?;
194 } else {
195 let mut filename = format!("{}/{}", browser.path, path);
196
197 // Remove "./" from the beginning of filename
198 filename.remove(0);
199 filename.remove(0);
200
201 let song = self.conn.get_song_with_only_filename(&filename);
202 self.conn.push(&song)?;
203
204 // updating queue, to avoid multiple pushes of the same songs if we enter multiple times before the queue gets updated
205 self.update_queue();
206 }
207 }
208 Ok(())
209 }
210
211 // Cursor movements
212 pub fn move_cursor_left(&mut self) {
213 match self.inputmode {
214 InputMode::PlaylistRename => {
215 let cursor_moved_left = self.pl_cursor_pos.saturating_sub(1);
216 self.pl_cursor_pos = self.clamp_cursor(cursor_moved_left);
217 }
218 InputMode::Editing => {
219 let cursor_moved_left = self.search_cursor_pos.saturating_sub(1);
220 self.search_cursor_pos = self.clamp_cursor(cursor_moved_left);
221 }
222 _ => {}
223 }
224 }
225
226 pub fn move_cursor_right(&mut self) {
227 match self.inputmode {
228 InputMode::PlaylistRename => {
229 let cursor_moved_right = self.pl_cursor_pos.saturating_add(1);
230 self.pl_cursor_pos = self.clamp_cursor(cursor_moved_right);
231 }
232 InputMode::Editing => {
233 let cursor_moved_right = self.search_cursor_pos.saturating_add(1);
234 self.search_cursor_pos = self.clamp_cursor(cursor_moved_right);
235 }
236 _ => {}
237 }
238 }
239
240 pub fn enter_char(&mut self, new_char: char) {
241 match self.inputmode {
242 InputMode::PlaylistRename => {
243 self.pl_newname_input.insert(self.pl_cursor_pos, new_char);
244 self.move_cursor_right();
245 }
246 InputMode::Editing => {
247 self.search_input.insert(self.search_cursor_pos, new_char);
248 self.move_cursor_right();
249 }
250 _ => {}
251 }
252 }
253
254 pub fn delete_char(&mut self) {
255 let is_not_cursor_leftmost = match self.inputmode {
256 InputMode::PlaylistRename => self.pl_cursor_pos != 0,
257 InputMode::Editing => self.search_cursor_pos != 0,
258 _ => false,
259 };
260
261 if is_not_cursor_leftmost {
262 // Method "remove" is not used on the saved text for deleting the selected char.
263 // Reason: Using remove on String works on bytes instead of the chars.
264 // Using remove would require special care because of char boundaries.
265
266 let current_index = match self.inputmode {
267 InputMode::Editing => self.search_cursor_pos,
268 InputMode::PlaylistRename => self.pl_cursor_pos,
269 _ => 0,
270 };
271
272 let from_left_to_current_index = current_index - 1;
273
274 if self.inputmode == InputMode::PlaylistRename {
275 // Getting all characters before the selected character.
276 let before_char_to_delete = self
277 .pl_newname_input
278 .chars()
279 .take(from_left_to_current_index);
280 // Getting all characters after selected character.
281 let after_char_to_delete = self.pl_newname_input.chars().skip(current_index);
282 // Put all characters together except the selected one.
283 // By leaving the selected one out, it is forgotten and therefore deleted.
284 self.pl_newname_input = before_char_to_delete.chain(after_char_to_delete).collect();
285 self.move_cursor_left();
286 } else if self.inputmode == InputMode::Editing {
287 let before_char_to_delete =
288 self.search_input.chars().take(from_left_to_current_index);
289 let after_char_to_delete = self.search_input.chars().skip(current_index);
290 self.search_input = before_char_to_delete.chain(after_char_to_delete).collect();
291 self.move_cursor_left();
292 }
293 }
294 }
295
296 pub fn clamp_cursor(&self, new_cursor_pos: usize) -> usize {
297 match self.inputmode {
298 InputMode::PlaylistRename => new_cursor_pos.clamp(0, self.pl_newname_input.len()),
299 InputMode::Editing => new_cursor_pos.clamp(0, self.search_input.len()),
300 _ => 0,
301 }
302 }
303
304 pub fn reset_cursor(&mut self) {
305 match self.inputmode {
306 InputMode::Editing => {
307 self.search_cursor_pos = 0;
308 }
309 InputMode::PlaylistRename => {
310 self.pl_cursor_pos = 0;
311 }
312 _ => {}
313 }
314 }
315
316 /// Given time in seconds, convert it to hh:mm:ss
317 pub fn format_time(time: Duration) -> String {
318 let time = time.as_secs();
319 let h = time / 3600;
320 let m = (time % 3600) / 60;
321 let s = (time % 3600) % 60;
322 if h == 0 {
323 format!("{:02}:{:02}", m, s)
324 } else {
325 format!("{:02}:{:02}:{:02}", h, m, s)
326 }
327 }
328
329 pub fn change_playlist_name(&mut self) -> AppResult<()> {
330 if self.selected_tab == SelectedTab::Playlists {
331 self.inputmode = InputMode::PlaylistRename;
332 }
333 Ok(())
334 }
335}