Krolyxon
Commit e95e1bb

rmptuisrcui.rs

456 lines · 14.2 KB · Rust

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