Krolyxon
Commit 4194bda

rmptuisrcapp.rs

260 lines · 8.5 KB · Rust

1use crate::browser::FileBrowser;
2use crate::connection::Connection;
3use crate::list::ContentList;
4use crate::ui::InputMode;
5use mpd::Client;
6
7// Application result type
8pub type AppResult<T> = std::result::Result<T, Box<dyn std::error::Error>>;
9
10/// Application
11#[derive(Debug)]
12pub struct App {
13 /// check if app is running
14 pub running: bool,
15 pub conn: Connection,
16 pub queue_list: ContentList<String>,
17 pub pl_list: ContentList<String>,
18 pub selected_tab: SelectedTab,
19 pub browser: FileBrowser,
20
21 // Search
22 pub inputmode: InputMode,
23 pub search_input: String,
24 pub cursor_position: usize,
25
26 // add to playlists
27 pub playlist_popup: bool,
28 pub append_list: ContentList<String>,
29}
30
31#[derive(Debug, PartialEq, Clone)]
32pub enum SelectedTab {
33 DirectoryBrowser,
34 Queue,
35 Playlists,
36}
37
38impl App {
39 pub fn builder(addrs: &str) -> AppResult<Self> {
40 let mut conn = Connection::new(addrs).unwrap();
41 let mut queue_list = ContentList::new();
42 let mut pl_list = ContentList::new();
43 pl_list.list = Self::get_playlist(&mut conn.conn)?;
44
45 let append_list = Self::get_append_list(&mut conn.conn)?;
46 Self::get_queue(&mut conn, &mut queue_list.list);
47
48 let browser = FileBrowser::new();
49
50 Ok(Self {
51 running: true,
52 conn,
53 queue_list,
54 pl_list,
55 selected_tab: SelectedTab::DirectoryBrowser,
56 browser,
57 inputmode: InputMode::Normal,
58 search_input: String::new(),
59 cursor_position: 0,
60 playlist_popup: false,
61 append_list,
62 })
63 }
64
65 pub fn tick(&mut self) {
66 self.conn.update_status();
67 self.update_queue();
68 }
69
70 pub fn quit(&mut self) {
71 self.running = false;
72 }
73
74 pub fn get_queue(conn: &mut Connection, vec: &mut Vec<String>) {
75 // conn.conn.queue().unwrap().into_iter().for_each(|x| {
76 // if let Some(title) = x.title {
77 // if let Some(artist) = x.artist {
78 // vec.push(format!("{} - {}", artist, title));
79 // } else {
80 // vec.push(title)
81 // }
82 // } else {
83 // vec.push(x.file)
84 // }
85 // });
86 conn.conn.queue().unwrap().into_iter().for_each(|x| {
87 vec.push(x.file);
88 });
89 }
90
91 pub fn update_queue(&mut self) {
92 self.queue_list.list.clear();
93 Self::get_queue(&mut self.conn, &mut self.queue_list.list);
94 }
95
96 pub fn get_playlist(conn: &mut Client) -> AppResult<Vec<String>> {
97 let list: Vec<String> = conn.playlists()?.iter().map(|p| p.clone().name).collect();
98 Ok(list)
99 }
100
101 pub fn get_append_list(conn: &mut Client) -> AppResult<ContentList<String>> {
102 let mut list = ContentList::new();
103 list.list.push("Current Playlist".to_string());
104 for item in Self::get_playlist(conn)? {
105 list.list.push(item.to_string());
106 }
107
108 Ok(list)
109 }
110
111 pub fn update_playlist(&mut self) -> AppResult<()> {
112 Self::get_playlist(&mut self.conn.conn)?;
113 Ok(())
114 }
115
116 pub fn handle_remove_or_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 self.browser.selected += 1;
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 let song = self
131 .conn
132 .get_song_with_only_filename(&self.conn.get_full_path(&file).unwrap());
133 self.conn.conn.push(&song)?;
134 }
135 }
136
137 SelectedTab::Queue => {
138 let file = self
139 .queue_list
140 .list
141 .get(self.queue_list.index)
142 .unwrap()
143 .to_string();
144
145 for (i, song) in self.queue_list.list.clone().iter().enumerate() {
146 if song.contains(&file) {
147 self.conn.conn.delete(i as u32).unwrap();
148 }
149 }
150 }
151
152 _ => {}
153 }
154
155 self.update_queue();
156 Ok(())
157 }
158
159 pub fn cycle_tabls(&mut self) {
160 self.selected_tab = match self.selected_tab {
161 SelectedTab::DirectoryBrowser => SelectedTab::Queue,
162 SelectedTab::Queue => SelectedTab::Playlists,
163 SelectedTab::Playlists => SelectedTab::DirectoryBrowser,
164 };
165 }
166
167 pub fn handle_enter(&mut self) -> AppResult<()> {
168 let browser = &mut self.browser;
169 let (t, path) = browser.filetree.get(browser.selected).unwrap();
170 if t == "directory" {
171 if path != "." {
172 browser.prev_path = browser.path.clone();
173 browser.path = browser.prev_path.clone() + "/" + path;
174 browser.update_directory(&mut self.conn)?;
175 browser.prev_selected = browser.selected;
176 browser.selected = 0;
177 }
178 } else {
179 // let list = conn
180 // .songs_filenames
181 // .iter()
182 // .map(|f| f.as_str())
183 // .collect::<Vec<&str>>();
184 // let (filename, _) = rust_fuzzy_search::fuzzy_search_sorted(&path, &list)
185 // .get(0)
186 // .unwrap()
187 // .clone();
188 let index = self.queue_list.list.iter().position(|x| x.contains(path));
189
190 if index.is_some() {
191 self.conn.conn.switch(index.unwrap() as u32)?;
192 } else {
193 for filename in self.conn.songs_filenames.clone().iter() {
194 if filename.contains(path) {
195 let song = self.conn.get_song_with_only_filename(filename);
196 self.conn.push(&song)?;
197 }
198 }
199
200 // updating queue, to avoid multiple pushes of the same songs if we enter multiple times before the queue gets updated
201 self.update_queue();
202 }
203 }
204 Ok(())
205 }
206
207 pub fn search_song(&mut self) -> AppResult<()> {
208 let filename = self.conn.get_full_path(&self.search_input)?;
209 let song = self.conn.get_song_with_only_filename(&filename);
210 self.conn.push(&song)?;
211 Ok(())
212 }
213
214 // Cursor movements
215 pub fn move_cursor_left(&mut self) {
216 let cursor_moved_left = self.cursor_position.saturating_sub(1);
217 self.cursor_position = self.clamp_cursor(cursor_moved_left);
218 }
219
220 pub fn move_cursor_right(&mut self) {
221 let cursor_moved_right = self.cursor_position.saturating_add(1);
222 self.cursor_position = self.clamp_cursor(cursor_moved_right);
223 }
224
225 pub fn enter_char(&mut self, new_char: char) {
226 self.search_input.insert(self.cursor_position, new_char);
227
228 self.move_cursor_right();
229 }
230
231 pub fn delete_char(&mut self) {
232 let is_not_cursor_leftmost = self.cursor_position != 0;
233 if is_not_cursor_leftmost {
234 // Method "remove" is not used on the saved text for deleting the selected char.
235 // Reason: Using remove on String works on bytes instead of the chars.
236 // Using remove would require special care because of char boundaries.
237
238 let current_index = self.cursor_position;
239 let from_left_to_current_index = current_index - 1;
240
241 // Getting all characters before the selected character.
242 let before_char_to_delete = self.search_input.chars().take(from_left_to_current_index);
243 // Getting all characters after selected character.
244 let after_char_to_delete = self.search_input.chars().skip(current_index);
245
246 // Put all characters together except the selected one.
247 // By leaving the selected one out, it is forgotten and therefore deleted.
248 self.search_input = before_char_to_delete.chain(after_char_to_delete).collect();
249 self.move_cursor_left();
250 }
251 }
252
253 pub fn clamp_cursor(&self, new_cursor_pos: usize) -> usize {
254 new_cursor_pos.clamp(0, self.search_input.len())
255 }
256
257 pub fn reset_cursor(&mut self) {
258 self.cursor_position = 0;
259 }
260}