Krolyxon
Commit c15bb22

rmptuisrcui.rs

434 lines · 13.4 KB · Rust

1use std::time::Duration;
2
3use crate::app::{App, SelectedTab};
4use ratatui::{
5 prelude::*,
6 widgets::{block::Title, *},
7};
8
9#[derive(Debug, PartialEq)]
10pub enum InputMode {
11 Editing,
12 Normal,
13 PlaylistRename,
14}
15
16/// Renders the user interface widgets
17pub fn render(app: &mut App, frame: &mut Frame) {
18 // Layout
19 let layout = Layout::default()
20 .direction(Direction::Vertical)
21 .constraints(vec![Constraint::Percentage(93), Constraint::Min(3)])
22 .split(frame.size());
23
24 match app.selected_tab {
25 SelectedTab::Queue => draw_queue(frame, app, layout[0]),
26 SelectedTab::Playlists => draw_playlist_viewer(frame, app, layout[0]),
27 SelectedTab::DirectoryBrowser => draw_directory_browser(frame, app, layout[0]),
28 }
29
30 match app.inputmode {
31 InputMode::Normal => {
32 draw_progress_bar(frame, app, layout[1]);
33 }
34 InputMode::Editing => {
35 draw_search_bar(frame, app, layout[1]);
36 }
37 InputMode::PlaylistRename => {
38 draw_rename_playlist(frame, app, layout[1]);
39 }
40 }
41
42 if app.playlist_popup {
43 draw_add_to_playlist(frame, app, layout[0]);
44 }
45}
46
47/// Draws the directory
48fn draw_directory_browser(frame: &mut Frame, app: &mut App, size: Rect) {
49 let total_songs = app.conn.conn.stats().unwrap().songs.to_string();
50
51 let rows = app.browser.filetree.iter().enumerate().map(|(i, (t, s))| {
52 if t == "file" {
53 let song = app.browser.songs.get(i).unwrap().clone();
54
55 // metadata
56 let title = song.clone().title.unwrap_or_else(|| song.clone().file);
57 let artist = song.clone().artist.unwrap_or_default().cyan();
58 let album = song
59 .tags
60 .iter()
61 .filter(|(x, _)| x == "Album")
62 .map(|(_, l)| l.clone())
63 .collect::<Vec<String>>()
64 .join("");
65
66 let track = song
67 .tags
68 .iter()
69 .filter(|(x, _)| x == "Track")
70 .map(|(_, l)| l.clone())
71 .collect::<Vec<String>>()
72 .join("");
73
74 let time =
75 App::format_time(song.clone().duration.unwrap_or_else(|| Duration::new(0, 0)));
76
77 let mut status: bool = false;
78 for sn in app.queue_list.list.iter() {
79 if sn.file.contains(s) {
80 status = true;
81 }
82 }
83
84 let row = Row::new(vec![
85 Cell::from(artist),
86 Cell::from(track.green()),
87 Cell::from(title),
88 Cell::from(album.cyan()),
89 Cell::from(time.to_string().magenta()),
90 ]);
91
92 if status {
93 row.magenta().bold()
94 } else {
95 row
96 }
97 } else {
98 let row = Row::new(vec![Cell::from(format!("[{}]", *s))]);
99 row
100 }
101 });
102
103 let mut state = TableState::new();
104 let header = ["Artist", "Track", "Title", "Album", "Time"]
105 .into_iter()
106 .map(Cell::from)
107 .collect::<Row>()
108 .bold()
109 .height(1);
110 let table = Table::new(
111 rows,
112 [
113 Constraint::Percentage(34),
114 Constraint::Percentage(3),
115 Constraint::Min(30),
116 Constraint::Percentage(30),
117 Constraint::Percentage(3),
118 ],
119 )
120 .block(
121 Block::default()
122 .title(format!("Song Browser: {}", app.browser.path.clone()).bold())
123 .title(
124 Title::from(format!("Total Songs: {}", total_songs).bold().green())
125 .alignment(Alignment::Center),
126 )
127 .title(
128 Title::from(format!("Volume: {}%", app.conn.volume).bold().green())
129 .alignment(Alignment::Right),
130 )
131 .borders(Borders::ALL),
132 )
133 .highlight_style(
134 Style::default()
135 .add_modifier(Modifier::REVERSED)
136 .fg(Color::Cyan)
137 .bg(Color::Black),
138 )
139 .header(header)
140 .flex(layout::Flex::Legacy);
141
142 state.select(Some(app.browser.selected));
143 frame.render_stateful_widget(table, size, &mut state);
144}
145
146/// draws playing queue
147fn draw_queue(frame: &mut Frame, app: &mut App, size: Rect) {
148 let rows = app.queue_list.list.iter().map(|song| {
149 // metadata
150 let title = song.clone().title.unwrap_or_else(|| song.clone().file);
151 let artist = song.clone().artist.unwrap_or_default().cyan();
152 let album = song
153 .tags
154 .iter()
155 .filter(|(x, _)| x == "Album")
156 .map(|(_, l)| l.clone())
157 .collect::<Vec<String>>()
158 .join("");
159
160 let track = song
161 .tags
162 .iter()
163 .filter(|(x, _)| x == "Track")
164 .map(|(_, l)| l.clone())
165 .collect::<Vec<String>>()
166 .join("");
167
168 let time = App::format_time(song.clone().duration.unwrap_or_else(|| Duration::new(0, 0)));
169
170 let row = Row::new(vec![
171 Cell::from(artist),
172 Cell::from(track.green()),
173 Cell::from(title),
174 Cell::from(album.cyan()),
175 Cell::from(time.to_string().magenta()),
176 ]);
177
178 if song.file.contains(&app.conn.current_song.file) {
179 row.magenta().bold()
180 } else {
181 row
182 }
183 });
184
185 let mut state = TableState::new();
186 let header = ["Artist", "Track", "Title", "Album", "Time"]
187 .into_iter()
188 .map(Cell::from)
189 .collect::<Row>()
190 .bold()
191 .height(1);
192 let table = Table::new(
193 rows,
194 [
195 Constraint::Percentage(34),
196 Constraint::Percentage(3),
197 Constraint::Min(30),
198 Constraint::Percentage(30),
199 Constraint::Percentage(3),
200 ],
201 )
202 .block(
203 Block::default()
204 .title(Title::from("Play Queue".green().bold()))
205 .title(Title::from(
206 format!("({} items)", app.queue_list.list.len()).bold(),
207 ))
208 .title(
209 Title::from(format!("Volume: {}%", app.conn.volume).bold().green())
210 .alignment(Alignment::Right),
211 )
212 .borders(Borders::ALL),
213 )
214 .highlight_style(
215 Style::default()
216 .add_modifier(Modifier::REVERSED)
217 .fg(Color::Cyan)
218 .bg(Color::Black),
219 )
220 .header(header)
221 .flex(layout::Flex::Legacy);
222
223 state.select(Some(app.queue_list.index));
224 frame.render_stateful_widget(table, size, &mut state);
225}
226
227// Draw search bar
228fn draw_search_bar(frame: &mut Frame, app: &mut App, size: Rect) {
229 // Make the cursor visible and ask ratatui to put it at the specified coordinates after
230 // rendering
231 #[allow(clippy::cast_possible_truncation)]
232 frame.set_cursor(
233 // Draw the cursor at the current position in the input field.
234 // This position is can be controlled via the left and right arrow key
235 size.x + app.search_cursor_pos as u16 + 2,
236 // Move one line down, from the border to the input line
237 size.y + 1,
238 );
239
240 let input = Paragraph::new("/".to_string() + &app.search_input)
241 .style(Style::default())
242 .block(
243 Block::default()
244 .borders(Borders::ALL)
245 .title("Search Forward: ".bold().green()),
246 );
247 frame.render_widget(input, size);
248}
249
250/// Draws Progress Bar
251fn draw_progress_bar(frame: &mut Frame, app: &mut App, size: Rect) {
252 // Get the current playing song
253 let song = app
254 .conn
255 .now_playing()
256 .unwrap()
257 .unwrap_or_else(|| "No Title Found".to_string());
258
259 // Get the current playing state
260 let mut state: String = String::new();
261 if !app.queue_list.list.is_empty() {
262 state = app.conn.state.clone();
263 state.push(':');
264 }
265
266 // Get the current modes
267 let mut modes_bottom: String = String::new();
268 // we do this to check if at least one mode is enabled so we can push "[]"
269 if app.conn.repeat | app.conn.random {
270 modes_bottom.push('r');
271 }
272
273 if !modes_bottom.is_empty() {
274 modes_bottom.clear();
275 modes_bottom.push('[');
276 if app.conn.repeat {
277 modes_bottom.push('r');
278 }
279 if app.conn.random {
280 modes_bottom.push('z');
281 }
282 modes_bottom.push(']');
283 };
284
285 // get the duration
286 let duration = if app.conn.total_duration.as_secs() != 0 {
287 format!(
288 "[{}/{}]",
289 App::format_time(app.conn.elapsed),
290 App::format_time(app.conn.total_duration)
291 )
292 } else {
293 "".to_string()
294 };
295
296 // Define the title
297 let title = Block::default()
298 .title(Title::from(state.red().bold()))
299 .title(Title::from(song.green().bold()))
300 .title(Title::from(duration.cyan().bold()).alignment(Alignment::Right))
301 .title(Title::from(modes_bottom).position(block::Position::Bottom))
302 .borders(Borders::ALL);
303
304 let progress_bar = LineGauge::default()
305 .block(title.borders(Borders::ALL))
306 .gauge_style(
307 Style::default()
308 .fg(Color::Blue)
309 .bg(Color::Black)
310 .add_modifier(Modifier::BOLD),
311 )
312 .line_set(symbols::line::THICK)
313 .ratio(app.conn.get_progress_ratio());
314
315 frame.render_widget(progress_bar, size);
316}
317
318fn draw_playlist_viewer(frame: &mut Frame, app: &mut App, area: Rect) {
319 let layouts = Layout::default()
320 .direction(Direction::Horizontal)
321 .constraints(vec![Constraint::Percentage(40), Constraint::Percentage(60)])
322 .split(area);
323
324 // Draw list of playlists
325 let mut state = ListState::default();
326 let title = Block::default().title(Title::from("Playlist".green().bold()));
327 let list = List::new(app.pl_list.list.clone())
328 .block(title.borders(Borders::ALL))
329 .highlight_style(
330 Style::new()
331 .fg(Color::Cyan)
332 .bg(Color::Black)
333 .add_modifier(Modifier::BOLD)
334 .add_modifier(Modifier::REVERSED),
335 )
336 .repeat_highlight_symbol(true);
337 state.select(Some(app.pl_list.index));
338 frame.render_stateful_widget(list, layouts[0], &mut state);
339
340 // Playlist viewer
341 let pl_name = app.pl_list.list.get(app.pl_list.index).unwrap();
342 let songs = app.conn.conn.playlist(pl_name).unwrap();
343 let rows = songs.iter().map(|song| {
344 let title = song.clone().title.unwrap_or_default().cyan();
345 let artist = song.clone().artist.unwrap_or_else(|| song.clone().file);
346 let time = App::format_time(song.clone().duration.unwrap_or_else(|| Duration::new(0, 0)));
347
348 let row = Row::new(vec![
349 Cell::from(artist),
350 Cell::from(title),
351 Cell::from(time.to_string().green()),
352 ]);
353 row
354 });
355
356 let title = Block::default()
357 .title(format!("Content: ({} items)", songs.len()).bold())
358 .borders(Borders::ALL);
359 let table = Table::new(
360 rows,
361 vec![
362 Constraint::Min(48),
363 Constraint::Percentage(48),
364 Constraint::Percentage(4),
365 ],
366 )
367 .block(title)
368 .highlight_style(
369 Style::default()
370 .add_modifier(Modifier::REVERSED)
371 .fg(Color::Cyan)
372 .bg(Color::Black),
373 )
374 .flex(layout::Flex::SpaceBetween);
375 frame.render_widget(table, layouts[1]);
376}
377
378fn draw_add_to_playlist(frame: &mut Frame, app: &mut App, area: Rect) {
379 let area = centered_rect(40, 50, area);
380 let mut state = ListState::default();
381 let title = Block::default()
382 .title(Title::from("Add Selected Item to: "))
383 .title(Title::from("<Esc> to Cancel".green().bold()).alignment(Alignment::Right));
384 let list = List::new(app.append_list.list.clone())
385 .block(title.borders(Borders::ALL))
386 .highlight_style(
387 Style::new()
388 .fg(Color::Cyan)
389 .bg(Color::Black)
390 .add_modifier(Modifier::BOLD)
391 .add_modifier(Modifier::REVERSED),
392 )
393 .repeat_highlight_symbol(true);
394
395 state.select(Some(app.append_list.index));
396 frame.render_widget(Clear, area); //this clears out the background
397 frame.render_stateful_widget(list, area, &mut state);
398}
399
400fn draw_rename_playlist(frame: &mut Frame, app: &mut App, area: Rect) {
401 #[allow(clippy::cast_possible_truncation)]
402 frame.set_cursor(
403 // Draw the cursor at the current position in the input field.
404 // This position is can be controlled via the left and right arrow key
405 area.x + app.pl_cursor_pos as u16 + 2,
406 // Move one line down, from the border to the input line
407 area.y + 1,
408 );
409
410 let input = Paragraph::new("/".to_string() + &app.pl_newname_input)
411 .style(Style::default())
412 .block(
413 Block::default()
414 .borders(Borders::ALL)
415 .title("Enter New Name: ".bold().green()),
416 );
417 frame.render_widget(input, area);
418}
419
420fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
421 let popup_layout = Layout::vertical([
422 Constraint::Percentage((100 - percent_y) / 2),
423 Constraint::Percentage(percent_y),
424 Constraint::Percentage((100 - percent_y) / 2),
425 ])
426 .split(r);
427
428 Layout::horizontal([
429 Constraint::Percentage((100 - percent_x) / 2),
430 Constraint::Percentage(percent_x),
431 Constraint::Percentage((100 - percent_x) / 2),
432 ])
433 .split(popup_layout[1])[1]
434}