Krolyxon
Commit 6af7553

rmptuisrcui.rs

435 lines · 13.5 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.stats.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().enumerate().map(|(i, 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 let pos = app.conn.current_song.place.unwrap_or_default().pos;
179 if i == pos as usize {
180 row.magenta().bold()
181 } else {
182 row
183 }
184 });
185
186 let mut state = TableState::new();
187 let header = ["Artist", "Track", "Title", "Album", "Time"]
188 .into_iter()
189 .map(Cell::from)
190 .collect::<Row>()
191 .bold()
192 .height(1);
193 let table = Table::new(
194 rows,
195 [
196 Constraint::Percentage(34),
197 Constraint::Percentage(3),
198 Constraint::Min(30),
199 Constraint::Percentage(30),
200 Constraint::Percentage(3),
201 ],
202 )
203 .block(
204 Block::default()
205 .title(Title::from("Play Queue".green().bold()))
206 .title(Title::from(
207 format!("({} items)", app.queue_list.list.len()).bold(),
208 ))
209 .title(
210 Title::from(format!("Volume: {}%", app.conn.volume).bold().green())
211 .alignment(Alignment::Right),
212 )
213 .borders(Borders::ALL),
214 )
215 .highlight_style(
216 Style::default()
217 .add_modifier(Modifier::REVERSED)
218 .fg(Color::Cyan)
219 .bg(Color::Black),
220 )
221 .header(header)
222 .flex(layout::Flex::Legacy);
223
224 state.select(Some(app.queue_list.index));
225 frame.render_stateful_widget(table, size, &mut state);
226}
227
228// Draw search bar
229fn draw_search_bar(frame: &mut Frame, app: &mut App, size: Rect) {
230 // Make the cursor visible and ask ratatui to put it at the specified coordinates after
231 // rendering
232 #[allow(clippy::cast_possible_truncation)]
233 frame.set_cursor(
234 // Draw the cursor at the current position in the input field.
235 // This position is can be controlled via the left and right arrow key
236 size.x + app.search_cursor_pos as u16 + 2,
237 // Move one line down, from the border to the input line
238 size.y + 1,
239 );
240
241 let input = Paragraph::new("/".to_string() + &app.search_input)
242 .style(Style::default())
243 .block(
244 Block::default()
245 .borders(Borders::ALL)
246 .title("Search Forward: ".bold().green()),
247 );
248 frame.render_widget(input, size);
249}
250
251/// Draws Progress Bar
252fn draw_progress_bar(frame: &mut Frame, app: &mut App, size: Rect) {
253 // Get the current playing song
254 let song = app
255 .conn
256 .now_playing()
257 .unwrap()
258 .unwrap_or_else(|| "No Title Found".to_string());
259
260 // Get the current playing state
261 let mut state: String = String::new();
262 if !app.queue_list.list.is_empty() {
263 state = app.conn.state.clone();
264 state.push(':');
265 }
266
267 // Get the current modes
268 let mut modes_bottom: String = String::new();
269 // we do this to check if at least one mode is enabled so we can push "[]"
270 if app.conn.repeat | app.conn.random {
271 modes_bottom.push('r');
272 }
273
274 if !modes_bottom.is_empty() {
275 modes_bottom.clear();
276 modes_bottom.push('[');
277 if app.conn.repeat {
278 modes_bottom.push('r');
279 }
280 if app.conn.random {
281 modes_bottom.push('z');
282 }
283 modes_bottom.push(']');
284 };
285
286 // get the duration
287 let duration = if app.conn.total_duration.as_secs() != 0 {
288 format!(
289 "[{}/{}]",
290 App::format_time(app.conn.elapsed),
291 App::format_time(app.conn.total_duration)
292 )
293 } else {
294 "".to_string()
295 };
296
297 // Define the title
298 let title = Block::default()
299 .title(Title::from(state.red().bold()))
300 .title(Title::from(song.green().bold()))
301 .title(Title::from(duration.cyan().bold()).alignment(Alignment::Right))
302 .title(Title::from(modes_bottom).position(block::Position::Bottom))
303 .borders(Borders::ALL);
304
305 let progress_bar = LineGauge::default()
306 .block(title.borders(Borders::ALL))
307 .gauge_style(
308 Style::default()
309 .fg(Color::Blue)
310 .bg(Color::Black)
311 .add_modifier(Modifier::BOLD),
312 )
313 .line_set(symbols::line::THICK)
314 .ratio(app.conn.get_progress_ratio());
315
316 frame.render_widget(progress_bar, size);
317}
318
319fn draw_playlist_viewer(frame: &mut Frame, app: &mut App, area: Rect) {
320 let layouts = Layout::default()
321 .direction(Direction::Horizontal)
322 .constraints(vec![Constraint::Percentage(40), Constraint::Percentage(60)])
323 .split(area);
324
325 // Draw list of playlists
326 let mut state = ListState::default();
327 let title = Block::default().title(Title::from("Playlist".green().bold()));
328 let list = List::new(app.pl_list.list.clone())
329 .block(title.borders(Borders::ALL))
330 .highlight_style(
331 Style::new()
332 .fg(Color::Cyan)
333 .bg(Color::Black)
334 .add_modifier(Modifier::BOLD)
335 .add_modifier(Modifier::REVERSED),
336 )
337 .repeat_highlight_symbol(true);
338 state.select(Some(app.pl_list.index));
339 frame.render_stateful_widget(list, layouts[0], &mut state);
340
341 // Playlist viewer
342 let pl_name = app.pl_list.list.get(app.pl_list.index).unwrap();
343 let songs = app.conn.conn.playlist(pl_name).unwrap();
344 let rows = songs.iter().map(|song| {
345 let title = song.clone().title.unwrap_or_default().cyan();
346 let artist = song.clone().artist.unwrap_or_else(|| song.clone().file);
347 let time = App::format_time(song.clone().duration.unwrap_or_else(|| Duration::new(0, 0)));
348
349 let row = Row::new(vec![
350 Cell::from(artist),
351 Cell::from(title),
352 Cell::from(time.to_string().green()),
353 ]);
354 row
355 });
356
357 let title = Block::default()
358 .title(format!("Content: ({} items)", songs.len()).bold())
359 .borders(Borders::ALL);
360 let table = Table::new(
361 rows,
362 vec![
363 Constraint::Min(48),
364 Constraint::Percentage(48),
365 Constraint::Percentage(4),
366 ],
367 )
368 .block(title)
369 .highlight_style(
370 Style::default()
371 .add_modifier(Modifier::REVERSED)
372 .fg(Color::Cyan)
373 .bg(Color::Black),
374 )
375 .flex(layout::Flex::SpaceBetween);
376 frame.render_widget(table, layouts[1]);
377}
378
379fn draw_add_to_playlist(frame: &mut Frame, app: &mut App, area: Rect) {
380 let area = centered_rect(40, 50, area);
381 let mut state = ListState::default();
382 let title = Block::default()
383 .title(Title::from("Add Selected Item to: "))
384 .title(Title::from("<Esc> to Cancel".green().bold()).alignment(Alignment::Right));
385 let list = List::new(app.append_list.list.clone())
386 .block(title.borders(Borders::ALL))
387 .highlight_style(
388 Style::new()
389 .fg(Color::Cyan)
390 .bg(Color::Black)
391 .add_modifier(Modifier::BOLD)
392 .add_modifier(Modifier::REVERSED),
393 )
394 .repeat_highlight_symbol(true);
395
396 state.select(Some(app.append_list.index));
397 frame.render_widget(Clear, area); //this clears out the background
398 frame.render_stateful_widget(list, area, &mut state);
399}
400
401fn draw_rename_playlist(frame: &mut Frame, app: &mut App, area: Rect) {
402 #[allow(clippy::cast_possible_truncation)]
403 frame.set_cursor(
404 // Draw the cursor at the current position in the input field.
405 // This position is can be controlled via the left and right arrow key
406 area.x + app.pl_cursor_pos as u16 + 2,
407 // Move one line down, from the border to the input line
408 area.y + 1,
409 );
410
411 let input = Paragraph::new("/".to_string() + &app.pl_newname_input)
412 .style(Style::default())
413 .block(
414 Block::default()
415 .borders(Borders::ALL)
416 .title("Enter New Name: ".bold().green()),
417 );
418 frame.render_widget(input, area);
419}
420
421fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
422 let popup_layout = Layout::vertical([
423 Constraint::Percentage((100 - percent_y) / 2),
424 Constraint::Percentage(percent_y),
425 Constraint::Percentage((100 - percent_y) / 2),
426 ])
427 .split(r);
428
429 Layout::horizontal([
430 Constraint::Percentage((100 - percent_x) / 2),
431 Constraint::Percentage(percent_x),
432 Constraint::Percentage((100 - percent_x) / 2),
433 ])
434 .split(popup_layout[1])[1]
435}