Krolyxon
Tag v0.1.2

rmptuisrcui.rs

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