Krolyxon
Commit 412e00f

rmptuisrcapp.rs

280 lines · 9.5 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;
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 /// check if app is running
16 pub running: bool,
17 pub conn: Connection,
18 pub browser: FileBrowser, // Directory browser
19 pub queue_list: ContentList<String>, // Stores the current playing queue
20 pub pl_list: ContentList<String>, // Stores list of playlists
21 pub selected_tab: SelectedTab, // Used to switch between tabs
22
23 // Search
24 pub inputmode: InputMode, // Defines input mode, Normal or Search
25 pub search_input: String, // Stores the userinput to be searched
26 pub cursor_position: usize, // Stores the cursor position
27
28 // playlist variables
29 // used to show playlist popup
30 pub playlist_popup: bool,
31 pub append_list: ContentList<String>,
32}
33
34#[derive(Debug, PartialEq, Clone)]
35pub enum SelectedTab {
36 DirectoryBrowser,
37 Queue,
38 Playlists,
39}
40
41impl App {
42 pub fn builder(addrs: &str) -> AppResult<Self> {
43 let mut conn = Connection::new(addrs).unwrap();
44 let mut queue_list = ContentList::new();
45 let mut pl_list = ContentList::new();
46 pl_list.list = Self::get_playlist(&mut conn.conn)?;
47
48 let append_list = Self::get_append_list(&mut conn.conn)?;
49 Self::get_queue(&mut conn, &mut queue_list.list);
50
51 let browser = FileBrowser::new();
52
53 Ok(Self {
54 running: true,
55 conn,
56 queue_list,
57 pl_list,
58 selected_tab: SelectedTab::Queue,
59 browser,
60 inputmode: InputMode::Normal,
61 search_input: String::new(),
62 cursor_position: 0,
63 playlist_popup: false,
64 append_list,
65 })
66 }
67
68 pub fn tick(&mut self) {
69 self.conn.update_status();
70 self.update_queue();
71 }
72
73 pub fn quit(&mut self) {
74 self.running = false;
75 }
76
77 pub fn get_queue(conn: &mut Connection, vec: &mut Vec<String>) {
78 // conn.conn.queue().unwrap().into_iter().for_each(|x| {
79 // if let Some(title) = x.title {
80 // if let Some(artist) = x.artist {
81 // vec.push(format!("{} - {}", artist, title));
82 // } else {
83 // vec.push(title)
84 // }
85 // } else {
86 // vec.push(x.file)
87 // }
88 // });
89 conn.conn.queue().unwrap().into_iter().for_each(|x| {
90 vec.push(x.file);
91 });
92 }
93
94 // Rescan the queue into queue_list
95 pub fn update_queue(&mut self) {
96 self.queue_list.list.clear();
97 Self::get_queue(&mut self.conn, &mut self.queue_list.list);
98 }
99
100 fn get_playlist(conn: &mut Client) -> AppResult<Vec<String>> {
101 let list: Vec<String> = conn.playlists()?.iter().map(|p| p.clone().name).collect();
102 Ok(list)
103 }
104
105 pub fn get_append_list(conn: &mut Client) -> AppResult<ContentList<String>> {
106 let mut list = ContentList::new();
107 list.list.push("Current Playlist".to_string());
108 for item in Self::get_playlist(conn)? {
109 list.list.push(item.to_string());
110 }
111
112 Ok(list)
113 }
114
115 /// Handles the <Space> event key
116 pub fn handle_add_or_remove_from_current_playlist(&mut self) -> AppResult<()> {
117 match self.selected_tab {
118 SelectedTab::DirectoryBrowser => {
119 let (_, file) = self.browser.filetree.get(self.browser.selected).unwrap();
120
121 let mut status = false;
122 for (i, song) in self.queue_list.list.clone().iter().enumerate() {
123 if song.contains(file) {
124 self.conn.conn.delete(i as u32).unwrap();
125 status = true;
126 }
127 }
128
129 if !status {
130 if let Some(full_path) = &self.conn.get_full_path(&file) {
131 let song = self.conn.get_song_with_only_filename(full_path);
132 self.conn.conn.push(&song)?;
133 }
134 }
135
136 if self.browser.selected != self.browser.filetree.len() - 1 {
137 self.browser.selected += 1;
138 }
139 }
140
141 SelectedTab::Queue => {
142 if self.queue_list.list.len() == 0 {
143 return Ok(());
144 }
145 let file = self
146 .queue_list
147 .list
148 .get(self.queue_list.index)
149 .unwrap()
150 .to_string();
151
152 for (i, song) in self.queue_list.list.clone().iter().enumerate() {
153 if song.contains(&file) {
154 self.conn.conn.delete(i as u32).unwrap();
155 if self.queue_list.index == self.queue_list.list.len() - 1
156 && self.queue_list.index != 0
157 {
158 self.queue_list.index -= 1;
159 }
160 }
161 }
162 }
163
164 _ => {}
165 }
166
167 self.update_queue();
168 Ok(())
169 }
170
171 /// Cycle through tabs
172 pub fn cycle_tabls(&mut self) {
173 self.selected_tab = match self.selected_tab {
174 SelectedTab::Queue => SelectedTab::DirectoryBrowser,
175 SelectedTab::DirectoryBrowser => SelectedTab::Playlists,
176 SelectedTab::Playlists => SelectedTab::DirectoryBrowser,
177 };
178 }
179
180 /// handles the Enter event on the directory browser
181 pub fn handle_enter(&mut self) -> AppResult<()> {
182 let browser = &mut self.browser;
183 let (t, path) = browser.filetree.get(browser.selected).unwrap();
184 if t == "directory" {
185 if path != "." {
186 browser.prev_path = browser.path.clone();
187 browser.path = browser.prev_path.clone() + "/" + path;
188 browser.update_directory(&mut self.conn)?;
189 browser.prev_selected = browser.selected;
190 browser.selected = 0;
191 }
192 } else {
193 // let list = conn
194 // .songs_filenames
195 // .iter()
196 // .map(|f| f.as_str())
197 // .collect::<Vec<&str>>();
198 // let (filename, _) = rust_fuzzy_search::fuzzy_search_sorted(&path, &list)
199 // .get(0)
200 // .unwrap()
201 // .clone();
202 let index = self.queue_list.list.iter().position(|x| x.contains(path));
203
204 if index.is_some() {
205 self.conn.conn.switch(index.unwrap() as u32)?;
206 } else {
207 for filename in self.conn.songs_filenames.clone().iter() {
208 if filename.contains(path) {
209 let song = self.conn.get_song_with_only_filename(filename);
210 self.conn.push(&song)?;
211 }
212 }
213
214 // updating queue, to avoid multiple pushes of the same songs if we enter multiple times before the queue gets updated
215 self.update_queue();
216 }
217 }
218 Ok(())
219 }
220
221 // Cursor movements
222 pub fn move_cursor_left(&mut self) {
223 let cursor_moved_left = self.cursor_position.saturating_sub(1);
224 self.cursor_position = self.clamp_cursor(cursor_moved_left);
225 }
226
227 pub fn move_cursor_right(&mut self) {
228 let cursor_moved_right = self.cursor_position.saturating_add(1);
229 self.cursor_position = self.clamp_cursor(cursor_moved_right);
230 }
231
232 pub fn enter_char(&mut self, new_char: char) {
233 self.search_input.insert(self.cursor_position, new_char);
234
235 self.move_cursor_right();
236 }
237
238 pub fn delete_char(&mut self) {
239 let is_not_cursor_leftmost = self.cursor_position != 0;
240 if is_not_cursor_leftmost {
241 // Method "remove" is not used on the saved text for deleting the selected char.
242 // Reason: Using remove on String works on bytes instead of the chars.
243 // Using remove would require special care because of char boundaries.
244
245 let current_index = self.cursor_position;
246 let from_left_to_current_index = current_index - 1;
247
248 // Getting all characters before the selected character.
249 let before_char_to_delete = self.search_input.chars().take(from_left_to_current_index);
250 // Getting all characters after selected character.
251 let after_char_to_delete = self.search_input.chars().skip(current_index);
252
253 // Put all characters together except the selected one.
254 // By leaving the selected one out, it is forgotten and therefore deleted.
255 self.search_input = before_char_to_delete.chain(after_char_to_delete).collect();
256 self.move_cursor_left();
257 }
258 }
259
260 pub fn clamp_cursor(&self, new_cursor_pos: usize) -> usize {
261 new_cursor_pos.clamp(0, self.search_input.len())
262 }
263
264 pub fn reset_cursor(&mut self) {
265 self.cursor_position = 0;
266 }
267
268 /// Given time in seconds, convert it to hh:mm:ss
269 pub fn format_time(time: Duration) -> String {
270 let time = time.as_secs();
271 let h = time / 3600;
272 let m = (time % 3600) / 60;
273 let s = (time % 3600) % 60;
274 if h == 0 {
275 format!("{:02}:{:02}", m, s)
276 } else {
277 format!("{:02}:{:02}:{:02}", h, m, s)
278 }
279 }
280}