use crate::{ app::{App, NAV}, model::{Item, time}, }; use ratatui::{ Frame, layout::{Constraint, Direction, Layout, Rect}, style::{Modifier, Style}, text::{Line, Span}, widgets::{ Block, Borders, Clear, Gauge, List, ListItem, ListState, Paragraph, Row, Table, Wrap, }, }; /// Keep the browser and transport visible, with a compact layout for narrow terminals. pub fn draw(frame: &mut Frame, app: &mut App) { let area = frame.area(); let colors = app.theme.palette(); frame.render_widget( Block::default().style(Style::default().bg(colors.bg).fg(colors.text)), area, ); if area.width < 45 || area.height < 14 { frame.render_widget( Paragraph::new("Octo · enlarge terminal to at least 45 × 14\nq quits") .wrap(Wrap { trim: false }), area, ); return; } let selected_download = app .items .get(app.table.selected().unwrap_or(0)) .and_then(|item| match item { Item::Song(song) => app.downloads.get(&song.id), _ => None, }) .map(|download| download.detail()); let rows = Layout::default() .direction(Direction::Vertical) .constraints([ Constraint::Length(3), Constraint::Min(4), Constraint::Length(4), Constraint::Length( (if area.width < 100 { 4 } else { 3 }) + u16::from(selected_download.is_some()), ), ]) .split(area); let mode = if app.library_only { "LIBRARY ONLY · m toggles" } else { "SUBSONIC / OCTO · m library only" }; frame.render_widget( Paragraph::new(Line::from(vec![ Span::styled( " ◉ OCTO ", Style::default() .fg(colors.accent) .add_modifier(Modifier::BOLD), ), Span::styled( " / terminal listening room", Style::default().fg(colors.muted), ), Span::raw(format!(" {mode}")), ])) .block( Block::default() .borders(Borders::BOTTOM) .border_style(Style::default().fg(colors.border)), ), rows[0], ); let show_cover = app.artwork.enabled && area.width >= 100 && area.height >= 20 && (!matches!(app.view, crate::model::View::Home) || app.current.is_some()); let show_queue = area.width >= 100 && area.height >= 20 && (show_cover || !app.queue.is_empty()); let cols = Layout::default() .direction(Direction::Horizontal) .constraints([ Constraint::Length(if area.width < 75 { 16 } else { 23 }), Constraint::Min(20), Constraint::Length(if show_queue { 28 } else { 0 }), ]) .split(rows[1]); let nav: Vec<_> = NAV .iter() .enumerate() .map(|(i, name)| { let active = i == app.nav; let style = if active { Style::default() .fg(colors.accent) .bg(colors.panel) .add_modifier(Modifier::BOLD) } else { Style::default().fg(colors.muted) }; ListItem::new(format!( " {} {} {}", if active { "›" } else { " " }, i, name )) .style(style) }) .collect(); let mut nav_state = ListState::default().with_selected(Some(app.nav)); frame.render_stateful_widget( List::new(nav).block( Block::default() .title(if app.sidebar { " Browse ● " } else { " Browse " }) .borders(Borders::ALL) .border_style(Style::default().fg(if app.sidebar { colors.accent } else { colors.border })), ), cols[0], &mut nav_state, ); let block = Block::default() .title(format!(" {} · {} ", app.view.title(), app.items.len())) .borders(Borders::ALL) .border_style(Style::default().fg(if app.sidebar { colors.border } else { colors.accent })); if app.items.is_empty() { let message = if let Some(error) = &app.load_error { format!("Could not load {}:\n{error}\nR retries", app.view.title()) } else if matches!(app.view, crate::model::View::History) && !app.library_only { "No listening history yet.\nSongs appear after playback starts.".into() } else if app.loading { "Loading music…\nYou can keep browsing or press q to quit.".into() } else if matches!(app.view, crate::model::View::Playlists) { "No playlists returned for this account.\nSelect a song and press a to create one.\nR refreshes".into() } else if app.library_only { "No library songs in this view.\nm includes online songs · R refreshes".into() } else if matches!( app.view, crate::model::View::Stations | crate::model::View::Station(_) ) { "No station tracks returned.\nOcto station tracks require the octoStations extension.\nR refreshes".into() } else { "No results.\n1 server search · 6 discover · R refresh".into() }; frame.render_widget( Paragraph::new(message) .style(Style::default().fg(colors.muted)) .wrap(Wrap { trim: false }) .block(block), cols[1], ); } else if matches!(app.view, crate::model::View::Home) { let entries = app .items .iter() .map(|item| Row::new([item.title().to_owned(), item.detail()])); let widths = [ Constraint::Min(20), if cols[1].width >= 55 { Constraint::Percentage(55) } else { Constraint::Length(0) }, ]; frame.render_stateful_widget( Table::new(entries, widths) .header( Row::new(["SECTION", "BROWSE"]) .style(Style::default().fg(colors.muted)) .bottom_margin(1), ) .block(block) .row_highlight_style( Style::default() .bg(colors.selection) .add_modifier(Modifier::BOLD), ) .highlight_symbol("› "), cols[1], &mut app.table, ); } else { let artist_view = matches!( app.view, crate::model::View::Artist(_) | crate::model::View::ArtistByName(_) ); let table_rows: Vec<_> = app .items .iter() .enumerate() .map(|(i, item)| { let playing=if matches!(app.view,crate::model::View::Queue) { app.current==Some(i) } else { matches!(item,Item::Song(song) if app.current.and_then(|index|app.queue.get(index)).is_some_and(|current|current.id==song.id)) }; let download = match item { Item::Song(song) => app.downloads.get(&song.id), _ => None, }; let title = if playing { let progress = download .map(|d| format!("[{}] ", d.label())) .unwrap_or_default(); format!( "{} {progress}{}", if app.paused { "Ⅱ" } else { "▶" }, item.title() ) } else { item.title().to_owned() }; let duration = if let Item::Song(s) = item { time(s.duration) } else { String::new() }; Row::new(vec![ if playing { if app.paused { "Ⅱ PAUSED" } else { "▶ PLAYING" } .into() } else if let Some(download) = download { download.label() } else { item.label().to_owned() }, title, if artist_view { match item { Item::Song(song) => song.album.clone(), _ => item.detail() } } else { item.detail() }, item.recommendation_source().to_owned(), item.playback_source().to_owned(), match item { Item::Song(song) => song.year.filter(|year| *year > 0).map(|year| year.to_string()).unwrap_or_else(|| "—".into()), _ => String::new(), }, duration, ]) .style( Style::default() .fg(if matches!(item,Item::Song(s) if s.is_external) { colors.accent } else { colors.text }) .add_modifier(if playing { Modifier::BOLD } else { Modifier::empty() }), ) }) .collect(); let table_width = cols[1].width; let source_width = if table_width >= if artist_view { 110 } else { 82 } { 18 } else { 0 }; let show_year = table_width >= 60 && app.items.iter().any(|item| matches!(item, Item::Song(_))); let widths = vec![ Constraint::Length(9), Constraint::Min(12), if artist_view && table_width >= 45 { Constraint::Percentage(30) } else if table_width >= 110 { Constraint::Percentage(28) } else { Constraint::Length(0) }, Constraint::Length(source_width), Constraint::Length(source_width), Constraint::Length(if show_year { 4 } else { 0 }), Constraint::Length(5), ]; frame.render_stateful_widget( Table::new(table_rows, widths) .header( Row::new([ "STATUS", "TITLE", if artist_view { "ALBUM" } else { "ARTIST / ALBUM" }, "SUGGESTED BY", "LOADED FROM", "YEAR", "TIME", ]) .style(Style::default().fg(colors.muted)) .bottom_margin(1), ) .block(block) .row_highlight_style( Style::default() .bg(colors.selection) .add_modifier(Modifier::BOLD), ) .highlight_symbol("› "), cols[1], &mut app.table, ); } let now = app.current.and_then(|i| app.queue.get(i)); let side = if show_cover { let image_height = app.artwork.height_for_width( cols[2].width.saturating_sub(2), cols[2].height.saturating_sub(8), ); Layout::vertical([Constraint::Length(image_height + 4), Constraint::Min(4)]).split(cols[2]) } else { Layout::vertical([Constraint::Length(0), Constraint::Min(0)]).split(cols[2]) }; if show_cover { let block = Block::default() .title(" Cover · SIXEL ") .borders(Borders::ALL) .border_style(Style::default().fg(colors.border)); let inner = block.inner(side[0]); frame.render_widget(block, side[0]); let parts = Layout::vertical([Constraint::Min(1), Constraint::Length(2)]).split(inner); if !app.help && app.playlist_dialog.is_none() { if let Some(protocol) = &mut app.artwork.protocol { frame.render_stateful_widget( ratatui_image::StatefulImage::default().resize(ratatui_image::Resize::Scale( Some(ratatui_image::FilterType::Triangle), )), parts[0], protocol, ); } else { frame.render_widget( Paragraph::new(app.artwork.message.as_str()) .style(Style::default().fg(colors.muted)) .wrap(Wrap { trim: false }), parts[0], ); } } frame.render_widget( Paragraph::new(vec![ Line::from(Span::styled( app.artwork.title.as_str(), Style::default().fg(colors.text), )), Line::from(Span::styled( now.map(|song| song.artist.as_str()).unwrap_or_default(), Style::default().fg(colors.muted), )), ]), parts[1], ); } if show_queue { draw_queue(frame, app, side[1]); } let title = now .map(|s| format!("{} — {}", s.title, s.artist)) .unwrap_or_else(|| "Choose a song to start listening".into()); let state = if app.current.is_none() { "STOP" } else if app.paused { "PAUSE" } else { "PLAY" }; let player = Block::default() .title(format!(" {state} · {title} ")) .borders(Borders::ALL) .border_style(Style::default().fg(colors.border)); let inside = player.inner(rows[2]); frame.render_widget(player, rows[2]); let playback = Layout::default() .direction(Direction::Vertical) .constraints([Constraint::Length(1), Constraint::Length(1)]) .split(inside); let ratio = if app.duration > 0. { (app.position / app.duration).clamp(0., 1.) } else { 0. }; frame.render_widget( Gauge::default() .gauge_style(Style::default().fg(colors.accent).bg(colors.panel)) .ratio(ratio) .label(format!( "{} / {}", time(app.position as u64), time(app.duration as u64) )), playback[0], ); let suggestion = now .and_then(|s| s.octo_suggested_by.as_deref()) .unwrap_or(""); frame.render_widget( Paragraph::new(format!( "vol {}% · {} queued · repeat {} {} · Loaded from: {}", app.volume, app.queue.len(), if app.repeat { "on" } else { "off" }, suggestion, now.map(|s| if s.is_external { s.playback_source.as_deref().unwrap_or("Unknown") } else { "Library" }) .unwrap_or("—") )) .style(Style::default().fg(colors.muted)), playback[1], ); let selected_source = app .items .get(app.table.selected().unwrap_or(0)) .map(Item::recommendation_source) .unwrap_or("—"); let selected_playback = app .items .get(app.table.selected().unwrap_or(0)) .map(Item::playback_source) .unwrap_or("—"); let source_line = if matches!(app.view, crate::model::View::Home) { format!( "0 Home · Enter opens section · theme: {} (t)", app.theme.name() ) } else if area.width < 100 { format!( "Suggested by: {selected_source}\nLoaded from: {selected_playback} · theme: {} (t)", app.theme.name() ) } else { format!( "Suggested by: {selected_source} · Loaded from: {selected_playback} · theme: {} (t)", app.theme.name() ) }; let source_line = if let Some(download) = selected_download { format!("{source_line}\nDownload: {download}") } else { source_line }; let footer = if let Some(input) = &app.input { if app.server_search { format!("Search server: {input}▏ Enter search · Esc cancel") } else { format!("/ {input}▏ Find in view · Enter keep position · Esc cancel") } } else { format!( "{}\n{}\nj/k move · Enter play/open · / find · 1 server search · a playlist · e queue · r radio · d library · ? help", app.status, source_line ) }; frame.render_widget( Paragraph::new(footer).style(Style::default().fg(if app.input.is_some() { colors.accent } else { colors.muted })), rows[3], ); if app.help { draw_help(frame, app); } if app.playlist_dialog.is_some() { draw_playlist_dialog(frame, app); } } /// Keep playlist selection and naming in one modal without changing the browser's song. fn draw_playlist_dialog(frame: &mut Frame, app: &App) { let dialog = app.playlist_dialog.as_ref().unwrap(); let colors = app.theme.palette(); let area = frame.area(); let width = area.width.saturating_sub(4).min(72); let height = area.height.saturating_sub(2).min(22); let popup = Rect::new( (area.width - width) / 2, (area.height - height) / 2, width, height, ); let block = Block::default() .title(" Add song to playlist ") .borders(Borders::ALL) .border_style(Style::default().fg(colors.accent)) .style(Style::default().fg(colors.text).bg(colors.panel)); let inner = block.inner(popup); frame.render_widget(Clear, popup); frame.render_widget(block, popup); let rows = Layout::vertical([ Constraint::Length(3), Constraint::Min(1), Constraint::Length(3), ]) .split(inner); frame.render_widget( Paragraph::new(vec![ Line::from(Span::styled( dialog.song.title.as_str(), Style::default().add_modifier(Modifier::BOLD), )), Line::from(dialog.song.artist.as_str()), ]), rows[0], ); if let Some(name) = &dialog.new_name { frame.render_widget( Paragraph::new(format!("New playlist name:\n{name}▏")) .style(Style::default().fg(colors.accent)), rows[1], ); } else { let entries = std::iter::once( ListItem::new("+ Create new playlist").style(Style::default().fg(colors.accent)), ) .chain(dialog.choices.iter().map(|p| { ListItem::new(format!("{}{}", p.name, p.suffix())).style(Style::default().fg( if p.addition_error().is_some() { colors.muted } else { colors.text }, )) })); let mut state = ListState::default().with_selected(Some(dialog.selected)); frame.render_stateful_widget( List::new(entries).highlight_symbol("› ").highlight_style( Style::default() .bg(colors.selection) .add_modifier(Modifier::BOLD), ), rows[1], &mut state, ); } let instructions = if dialog.pending_target.is_some() { "Waiting for library indexing… Esc cancels" } else if dialog.saving { "Adding song…" } else if dialog.new_name.is_some() { "Enter creates and adds · Esc returns" } else { "j/k move · Enter adds · n new · Esc cancels" }; let status = dialog.error.as_deref().unwrap_or(if dialog.loading { "Loading playlists…" } else if dialog.choices.is_empty() { "No existing playlists returned; n creates one" } else { "" }); frame.render_widget( Paragraph::new(vec![ Line::from(Span::styled(status, Style::default().fg(colors.accent))), Line::from(instructions), ]) .wrap(Wrap { trim: false }), rows[2], ); } /// Give keys their own accent color and let small terminals scroll through every binding. fn draw_help(frame: &mut Frame, app: &mut App) { let colors = app.theme.palette(); let entries = [ ("", "BROWSE"), ("j / k · arrows", "Move selection"), ("gg / G", "First / last entry"), ("Ctrl-d / Ctrl-u", "Move ten rows"), ("h / Tab", "Focus sidebar / toggle focus"), ("l / Enter", "Open selection or play"), ("i", "Open selected song’s artist"), ("m", "Toggle library-only mode"), ("Esc / Backspace", "Go back"), ("0", "Home"), ("2–9", "Artists through History"), ("/", "Find in current view as you type"), ("1", "Search the server"), ("< / >", "Previous / next album or song page"), ("o / R", "Cycle album order / refresh"), ("t", "Cycle theme"), ("", "PLAYBACK"), ("Enter", "Play visible list from selection"), ("Space", "Pause / resume"), ("H / L", "Previous / next song (Shift-h/l)"), ("[ / ]", "Seek backward / forward 10 seconds"), ("- / =", "Volume down / up 5%"), ("", "PLAYLISTS"), ("a", "Add selected song to a playlist"), ("9", "Recently played songs (History)"), ("", "QUEUE"), ("e / A", "Append selected / all visible songs"), ("s", "Shuffle upcoming songs"), ("z", "Toggle queue repeat"), ("8", "Open full queue"), ("x", "Remove selected queue song"), ("J / K", "Move queue song down / up"), ("", "DISCOVER"), ("6 / 7", "Discover / Stations"), ("r", "Radio from selected song"), ("f", "Toggle favorite"), ("d / +", "Download external song to library"), ("", "DISCOVER labels songs not owned"), ("? / Esc", "Close help"), ("q / Ctrl-c", "Quit player (outside help)"), ]; let area = frame.area(); let width = area.width.saturating_sub(6).min(86); let narrow = width < 64; let key_style = Style::default() .fg(colors.accent) .add_modifier(Modifier::BOLD); let description_style = Style::default().fg(colors.text); let mut lines = Vec::new(); for (key, description) in entries { if key.is_empty() { lines.push(Line::from(Span::styled( description, Style::default() .fg(colors.muted) .add_modifier(Modifier::BOLD), ))); } else if narrow { lines.push(Line::from(Span::styled(key, key_style))); lines.push(Line::from(Span::styled( format!(" {description}"), description_style, ))); } else { lines.push(Line::from(vec![ Span::styled(format!("{key:<20}"), key_style), Span::styled(description, description_style), ])); } } let height = area.height.saturating_sub(2).min(lines.len() as u16 + 2); let popup = Rect::new( (area.width - width) / 2, (area.height - height) / 2, width, height, ); let block = Block::default() .title(" Shortcuts ") .title_bottom(Line::from(vec![ Span::styled(" j/k · PgUp/PgDn ", key_style), Span::styled("scroll · Esc close ", description_style), ])) .borders(Borders::ALL) .border_style(Style::default().fg(colors.accent)); let inner = block.inner(popup); app.help_scroll = app .help_scroll .min((lines.len() as u16).saturating_sub(inner.height)); frame.render_widget(Clear, popup); frame.render_widget( Paragraph::new(lines) .scroll((app.help_scroll, 0)) .style(Style::default().bg(colors.panel)) .block(block), popup, ); } /// Follow playback and render the live queue without moving the browser's selection. fn draw_queue(frame: &mut Frame, app: &App, area: Rect) { let colors = app.theme.palette(); let block = Block::default() .title(" Queue ") .title_style( Style::default() .fg(colors.accent) .add_modifier(Modifier::BOLD), ) .borders(Borders::ALL) .border_style(Style::default().fg(colors.border)); let inner = block.inner(area); frame.render_widget(block, area); if app.queue.is_empty() { frame.render_widget( Paragraph::new("Queue is empty\ne adds a song · 8 opens queue") .wrap(Wrap { trim: false }) .style(Style::default().fg(colors.muted)), inner, ); return; } let start = app .current .unwrap_or(0) .min(app.queue.len().saturating_sub(1)); let entries = app .queue .iter() .enumerate() .skip(start) .map(|(index, song)| { let playing = app.current == Some(index); let marker = if playing { if app.paused { "Ⅱ" } else { "▶" } } else { "·" }; let download = app .downloads .get(&song.id) .map(|d| format!("[{}] ", d.label())) .unwrap_or_default(); ListItem::new(format!("{marker} {}. {download}{}", index + 1, song.title)).style( Style::default().fg(colors.text).add_modifier(if playing { Modifier::BOLD } else { Modifier::empty() }), ) }); frame.render_widget(List::new(entries), inner); } #[cfg(test)] mod tests { use super::*; use ratatui::{Terminal, backend::TestBackend}; #[test] fn suggestion_service_remains_visible_on_narrow_terminals() { let mut app = App::for_tests(); app.view = crate::model::View::Discover; app.items = vec![Item::Song(crate::model::Song { title: "Suggested track".into(), is_external: true, octo_suggested_by: Some("YouTube Music".into()), ..Default::default() })]; for width in [45, 80, 140] { let mut terminal = Terminal::new(TestBackend::new(width, 30)).unwrap(); terminal.draw(|f| draw(f, &mut app)).unwrap(); let text = terminal .backend() .buffer() .content .iter() .map(|c| c.symbol()) .collect::(); assert!(text.contains("YouTube Music")); } } #[test] fn home_sections_and_numbered_sidebar_render() { let mut app = App::for_tests(); let mut terminal = Terminal::new(TestBackend::new(120, 30)).unwrap(); terminal.draw(|f| draw(f, &mut app)).unwrap(); let text = terminal .backend() .buffer() .content .iter() .map(|c| c.symbol()) .collect::(); for label in [ "0 Home", "1 Search", "2 Artists", "8 Queue", "9 History", "Recently played", "Recently added", "Most played", "Highest rated", ] { assert!(text.contains(label), "Missing {label}"); } let queue_position = text.find("8 Queue").unwrap(); let history_position = text.find("9 History").unwrap(); assert!(history_position > queue_position); assert!(!text.contains("Favorites")); app.key(crossterm::event::KeyEvent::new( crossterm::event::KeyCode::Char('8'), crossterm::event::KeyModifiers::NONE, )); let mut terminal = Terminal::new(TestBackend::new(65, 20)).unwrap(); terminal.draw(|f| draw(f, &mut app)).unwrap(); let text = terminal .backend() .buffer() .content .iter() .map(|c| c.symbol()) .collect::(); assert!(text.contains("8 Queue")); } #[test] fn cover_caption_shows_playing_artist_independently_of_cursor_and_long_titles() { let mut app = App::for_tests(); app.artwork.enabled = true; app.queue = crate::test_support::songs(); app.queue[0].artist = "First artist".into(); app.queue[1].artist = "Next artist".into(); app.current = Some(0); app.items = vec![Item::Song(app.queue[1].clone())]; app.table.select(Some(0)); app.artwork.title = "A very long song title that should not push the artist out of view".into(); for (current, artist) in [(0, "First artist"), (1, "Next artist")] { app.current = Some(current); app.paused = true; let mut terminal = Terminal::new(TestBackend::new(140, 40)).unwrap(); terminal.draw(|f| draw(f, &mut app)).unwrap(); let buffer = terminal.backend().buffer(); let caption: String = (113..139).map(|x| buffer[(x, 18)].symbol()).collect(); assert!(caption.contains(artist)); assert_eq!(buffer[(113, 18)].fg, app.theme.palette().muted); } app.current = None; let mut terminal = Terminal::new(TestBackend::new(140, 40)).unwrap(); app.view = crate::model::View::Songs { offset: 0 }; terminal.draw(|f| draw(f, &mut app)).unwrap(); let caption: String = (113..139) .map(|x| terminal.backend().buffer()[(x, 18)].symbol()) .collect(); assert!(!caption.contains("artist")); } #[test] fn queue_stays_close_to_cover_as_terminal_height_grows() { let mut app = App::for_tests(); app.artwork.enabled = true; app.artwork.title = "Current cover".into(); app.queue = crate::test_support::songs(); app.current = Some(0); for height in [40, 70] { let mut terminal = Terminal::new(TestBackend::new(140, height)).unwrap(); terminal.draw(|f| draw(f, &mut app)).unwrap(); let buffer = terminal.backend().buffer(); let queue_row = (3..height - 7) .find(|y| { (112..140) .map(|x| buffer[(x, *y)].symbol()) .collect::() .contains("Queue") }) .unwrap(); // A 26-column square cover uses 13 rows, plus two caption rows and borders. assert_eq!(queue_row, 20); assert_eq!(buffer[(112, queue_row - 1)].symbol(), "└"); assert_eq!(buffer[(139, queue_row - 1)].symbol(), "┘"); let caption: String = (113..139) .map(|x| buffer[(x, queue_row - 3)].symbol()) .collect(); assert!(caption.contains("Current cover")); } } #[test] fn queue_preview_follows_current_track_and_live_edits_without_art() { let mut app = App::for_tests(); app.queue = crate::test_support::songs(); app.current = Some(1); let mut terminal = Terminal::new(TestBackend::new(140, 30)).unwrap(); terminal.draw(|f| draw(f, &mut app)).unwrap(); let queue_text = |terminal: &Terminal| { let buffer = terminal.backend().buffer(); (3..23) .flat_map(|y| (112..140).map(move |x| buffer[(x, y)].symbol())) .collect::() }; let text = queue_text(&terminal); assert!(text.contains("Queue")); assert!(text.contains("▶ 2.")); assert!(text.contains("Track 2")); assert!(!text.contains("Track 0")); app.current = Some(2); app.queue.remove(3); terminal.draw(|f| draw(f, &mut app)).unwrap(); let text = queue_text(&terminal); assert!(text.contains("▶ 3. Track 2")); assert!(!text.contains("Track 1")); assert!(!text.contains("Track 3")); app.artwork.enabled = true; app.view = crate::model::View::Songs { offset: 0 }; app.queue.clear(); app.current = None; terminal.draw(|f| draw(f, &mut app)).unwrap(); let text = queue_text(&terminal); assert!(text.contains("Cover")); assert!(text.contains("Queue is empty")); for (w, h) in [(100, 20), (80, 24)] { let mut t = Terminal::new(TestBackend::new(w, h)).unwrap(); t.draw(|f| draw(f, &mut app)).unwrap(); } } #[test] fn queue_title_and_help_keys_have_visible_theme_accents() { let mut app = App::for_tests(); app.queue = crate::test_support::songs(); let mut terminal = Terminal::new(TestBackend::new(140, 40)).unwrap(); terminal.draw(|f| draw(f, &mut app)).unwrap(); let buffer = terminal.backend().buffer(); let title = (112..140) .find_map(|x| (buffer[(x, 3)].symbol() == "Q").then_some(&buffer[(x, 3)])) .unwrap(); assert_eq!(title.fg, app.theme.palette().accent); assert!(title.modifier.contains(Modifier::BOLD)); app.help = true; terminal.draw(|f| draw(f, &mut app)).unwrap(); let key = terminal .backend() .buffer() .content .windows(21) .find(|cells| { cells[0].symbol() == "H" && cells[2].symbol() == "/" && cells[4].symbol() == "L" }) .unwrap(); assert_eq!(key[0].fg, app.theme.palette().accent); assert_eq!(key[20].fg, app.theme.palette().text); let selection = app.table.selected(); app.key(crossterm::event::KeyEvent::new( crossterm::event::KeyCode::Char('j'), crossterm::event::KeyModifiers::NONE, )); assert_eq!(app.help_scroll, 1); assert_eq!(app.table.selected(), selection); let mut terminal = Terminal::new(TestBackend::new(60, 20)).unwrap(); app.help_scroll = u16::MAX; terminal.draw(|f| draw(f, &mut app)).unwrap(); let text = terminal .backend() .buffer() .content .iter() .map(|c| c.symbol()) .collect::(); assert!(text.contains("Download external song")); assert!(text.contains("Close help")); } #[test] fn full_queue_marks_playback_separately_from_cursor_and_updates_when_paused() { let mut app = App::for_tests(); app.queue = crate::test_support::songs(); app.current = Some(2); app.key(crossterm::event::KeyEvent::new( crossterm::event::KeyCode::Char('8'), crossterm::event::KeyModifiers::NONE, )); assert_eq!(app.table.selected(), Some(2)); app.table.select(Some(0)); let mut terminal = Terminal::new(TestBackend::new(140, 30)).unwrap(); terminal.draw(|f| draw(f, &mut app)).unwrap(); let status_text = |t: &Terminal| { let buffer = t.backend().buffer(); (3..23) .flat_map(|y| (23..112).map(move |x| buffer[(x, y)].symbol())) .collect::() }; let text = status_text(&terminal); assert!(text.contains("▶ PLAYING")); assert!(text.contains("▶ Track 2")); let buffer = terminal.backend().buffer(); let marker = (3..23) .find_map(|y| { (23..112).find_map(|x| (buffer[(x, y)].symbol() == "▶").then_some(&buffer[(x, y)])) }) .unwrap(); assert_eq!(marker.fg, app.theme.palette().text); assert!(marker.modifier.contains(Modifier::BOLD)); app.key(crossterm::event::KeyEvent::new( crossterm::event::KeyCode::Char('L'), crossterm::event::KeyModifiers::SHIFT, )); assert_eq!(app.table.selected(), Some(0)); app.paused = true; terminal.draw(|f| draw(f, &mut app)).unwrap(); let text = status_text(&terminal); assert!(text.contains("Ⅱ PAUSED")); assert!(!text.contains("▶ PLAYING")); assert!(!text.contains("▶ Track 2")); } #[test] fn per_song_download_status_is_visible_in_queue_and_narrow_footer() { let mut app = App::for_tests(); let song = crate::test_support::songs().remove(4); let mut download = crate::downloads::Download::requesting(); download.update(&crate::downloads::Acquisition { state: "downloading".into(), progress: Some(0.42), source: Some("Soulseek".into()), ..Default::default() }); app.downloads.insert(song.id.clone(), download); app.queue = vec![song]; app.key(crossterm::event::KeyEvent::new( crossterm::event::KeyCode::Char('8'), crossterm::event::KeyModifiers::NONE, )); for width in [65, 140] { let mut terminal = Terminal::new(TestBackend::new(width, 30)).unwrap(); terminal.draw(|f| draw(f, &mut app)).unwrap(); let text = terminal .backend() .buffer() .content .iter() .map(|c| c.symbol()) .collect::(); assert!(text.contains("↓ 42%")); assert!(text.contains("Download: ↓ 42% · Soulseek")); } } #[test] fn playing_status_survives_download_completion_and_track_changes() { use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; let mut app = App::for_tests(); app.queue = crate::test_support::songs() .into_iter() .skip(4) .take(2) .collect(); for (i, state) in ["downloading", "done"].into_iter().enumerate() { let mut download = crate::downloads::Download::requesting(); download.update(&crate::downloads::Acquisition { state: state.into(), progress: Some(0.42), ..Default::default() }); app.downloads.insert(app.queue[i].id.clone(), download); } let key = |app: &mut App, c| app.key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)); key(&mut app, '8'); app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); let mut terminal = Terminal::new(TestBackend::new(140, 30)).unwrap(); let main_text = |terminal: &Terminal| { let buffer = terminal.backend().buffer(); (3..23) .flat_map(|y| (23..112).map(move |x| buffer[(x, y)].symbol())) .collect::() }; terminal.draw(|f| draw(f, &mut app)).unwrap(); let text = main_text(&terminal); assert_eq!(text.matches("▶ PLAYING").count(), 1); assert!(text.contains("[↓ 42%] Track 4")); key(&mut app, 'L'); terminal.draw(|f| draw(f, &mut app)).unwrap(); let text = main_text(&terminal); assert_eq!(text.matches("▶ PLAYING").count(), 1); assert!(text.contains("▶ [✓ ADDED] Track 5")); key(&mut app, ' '); terminal.draw(|f| draw(f, &mut app)).unwrap(); let text = main_text(&terminal); assert!(text.contains("Ⅱ PAUSED")); assert!(!text.contains("▶ PLAYING")); assert!(text.contains("[✓ ADDED] Track 5")); key(&mut app, 'H'); terminal.draw(|f| draw(f, &mut app)).unwrap(); let text = main_text(&terminal); assert!(text.contains("▶ PLAYING")); assert!(text.contains("▶ [↓ 42%] Track 4")); } #[test] fn playlist_modal_renders_choices_and_name_field_on_small_terminals() { let mut app = App::for_tests(); let mut dialog = crate::playlists::PlaylistDialog::new(1, crate::test_support::songs().remove(0)); dialog.loading = false; dialog.choices = vec![crate::playlists::PlaylistChoice { name: "Evening playlist".into(), ..Default::default() }]; dialog.choices.push(crate::playlists::PlaylistChoice { id: "station".into(), name: "Station".into(), readonly: true, ..Default::default() }); app.playlist_dialog = Some(dialog); for width in [45, 120] { let mut terminal = Terminal::new(TestBackend::new(width, 30)).unwrap(); terminal.draw(|f| draw(f, &mut app)).unwrap(); let text = terminal .backend() .buffer() .content .iter() .map(|c| c.symbol()) .collect::(); assert!(text.contains("Add song to playlist")); assert!(text.contains("Create new playlist")); assert!(text.contains("Evening playlist")); assert!(text.contains("Station [read-only]")); } app.playlist_dialog.as_mut().unwrap().new_name = Some("Café".into()); let mut terminal = Terminal::new(TestBackend::new(100, 30)).unwrap(); terminal.draw(|f| draw(f, &mut app)).unwrap(); let text = terminal .backend() .buffer() .content .iter() .map(|c| c.symbol()) .collect::(); assert!(text.contains("Café")); } #[test] fn playlists_show_empty_state_or_actual_load_error() { let mut app = App::for_tests(); app.view = crate::model::View::Playlists; app.items.clear(); app.loading = false; let mut terminal = Terminal::new(TestBackend::new(120, 30)).unwrap(); terminal.draw(|f| draw(f, &mut app)).unwrap(); let text: String = terminal .backend() .buffer() .content .iter() .map(|c| c.symbol()) .collect(); assert!(text.contains("No playlists returned for this account")); assert!(!text.contains("Octo-only")); app.load_error = Some("getPlaylists: HTTP 403 Forbidden".into()); terminal.draw(|f| draw(f, &mut app)).unwrap(); let text: String = terminal .backend() .buffer() .content .iter() .map(|c| c.symbol()) .collect(); assert!(text.contains("HTTP 403 Forbidden")); assert!(!text.contains("No playlists returned")); } #[test] fn song_panels_show_years_and_unknown_dates_in_the_year_column() { use crate::model::{Song, View}; let songs: Vec<_> = [("Dated", Some(2024)), ("Missing", None), ("Zero", Some(0))] .into_iter() .map(|(title, year)| Song { id: title.into(), title: title.into(), year, ..Default::default() }) .collect(); for view in [ View::Search("test".into()), View::Songs { offset: 0 }, View::Album("album".into()), View::Artist("artist".into()), View::ArtistByName("artist".into()), View::Playlist("list".into()), View::Queue, View::History, View::Discover, View::Station("station".into()), View::Radio("song".into()), View::Genre("Rock".into()), ] { let mut app = App::for_tests(); app.view = view; app.queue = songs.clone(); app.items = songs.iter().cloned().map(Item::Song).collect(); for width in [120, 180] { let mut terminal = Terminal::new(TestBackend::new(width, 30)).unwrap(); terminal.draw(|f| draw(f, &mut app)).unwrap(); let buffer = terminal.backend().buffer(); let year_column = (0..20) .find_map(|y| { (23..width - 3).find(|x| { (*x..*x + 4) .map(|x| buffer[(x, y)].symbol()) .collect::() == "YEAR" }) }) .expect("Year header missing"); for (title, expected) in [("Dated", "2024"), ("Missing", "—"), ("Zero", "—")] { let row = (0..20) .find(|y| { (23..width - 28) .map(|x| buffer[(x, *y)].symbol()) .collect::() .contains(title) }) .unwrap(); let value: String = (year_column..year_column + 4) .map(|x| buffer[(x, row)].symbol()) .collect(); assert_eq!(value.trim(), expected); } } } } #[test] fn library_mode_is_visible_and_explains_empty_filtered_views() { let mut app = App::for_tests(); app.library_only = true; app.view = crate::model::View::Radio("song".into()); app.items.clear(); app.loading = false; let mut terminal = Terminal::new(TestBackend::new(120, 30)).unwrap(); terminal.draw(|f| draw(f, &mut app)).unwrap(); let text: String = terminal .backend() .buffer() .content .iter() .map(|cell| cell.symbol()) .collect(); assert!(text.contains("LIBRARY ONLY")); assert!(text.contains("No library songs in this view")); assert!(text.contains("m includes online songs")); app.help = true; let mut terminal = Terminal::new(TestBackend::new(120, 65)).unwrap(); terminal.draw(|f| draw(f, &mut app)).unwrap(); let text: String = terminal .backend() .buffer() .content .iter() .map(|cell| cell.symbol()) .collect(); assert!(text.contains("Toggle library-only mode")); } #[test] fn artist_tracks_show_album_column_on_medium_and_wide_terminals() { for view in [ crate::model::View::Artist("id".into()), crate::model::View::ArtistByName("Artist".into()), ] { let mut app = App::for_tests(); app.view = view; app.items = vec![Item::Song(crate::model::Song { id: "song".into(), title: "Example song".into(), artist: "Example artist".into(), album: "Example album".into(), ..Default::default() })]; for width in [100, 160] { let mut terminal = Terminal::new(TestBackend::new(width, 30)).unwrap(); terminal.draw(|f| draw(f, &mut app)).unwrap(); let buffer = terminal.backend().buffer(); let text: String = (0..20) .flat_map(|y| (0..width).map(move |x| buffer[(x, y)].symbol())) .collect(); assert!(text.contains("ALBUM")); assert!(text.contains("Example album")); assert!(text.contains("Example song")); assert!(!text.contains("ARTIST / ALBUM")); } } } #[test] fn history_shows_clear_empty_state_and_needs_no_server_request() { let mut app = App::for_tests(); app.key(crossterm::event::KeyEvent::new( crossterm::event::KeyCode::Char('9'), crossterm::event::KeyModifiers::NONE, )); let mut terminal = Terminal::new(TestBackend::new(120, 30)).unwrap(); terminal.draw(|f| draw(f, &mut app)).unwrap(); let text = terminal .backend() .buffer() .content .iter() .map(|c| c.symbol()) .collect::(); assert!(text.contains("No listening history yet")); assert!(!app.loading); } #[test] fn every_song_panel_marks_current_song_by_id_and_updates_on_track_changes() { use crate::model::View; let mut app = App::for_tests(); let songs = crate::test_support::songs(); app.queue = songs.clone(); app.current = Some(1); // Reverse rows to prove that the marker follows IDs rather than browsing position. app.items = vec![ Item::Song(songs[2].clone()), Item::Song(songs[1].clone()), Item::Song(songs[0].clone()), ]; let main_text = |terminal: &Terminal| { let buffer = terminal.backend().buffer(); (3..23) .flat_map(|y| (23..112).map(move |x| buffer[(x, y)].symbol())) .collect::() }; for view in [ View::Search("test".into()), View::Album("album".into()), View::Playlist("list".into()), View::Discover, View::Station("station".into()), View::Radio("seed".into()), View::History, View::Songs { offset: 0 }, View::Genre("Rock".into()), ] { app.view = view; app.current = Some(1); app.paused = false; let mut terminal = Terminal::new(TestBackend::new(140, 30)).unwrap(); terminal.draw(|f| draw(f, &mut app)).unwrap(); let text = main_text(&terminal); assert_eq!(text.matches("▶ PLAYING").count(), 1); assert!(text.contains("▶ Track 1")); app.current = Some(2); app.paused = true; terminal.draw(|f| draw(f, &mut app)).unwrap(); let text = main_text(&terminal); assert_eq!(text.matches("Ⅱ PAUSED").count(), 1); assert!(text.contains("Ⅱ Track 2")); assert!(!text.contains("▶ Track 1")); app.current = None; terminal.draw(|f| draw(f, &mut app)).unwrap(); let text = main_text(&terminal); assert!(!text.contains("▶ PLAYING")); assert!(!text.contains("Ⅱ PAUSED")); } } #[test] fn queue_duplicate_ids_mark_only_the_active_entry() { let mut app = App::for_tests(); let song = crate::test_support::songs().remove(0); app.queue = vec![song.clone(), song.clone()]; app.items = vec![Item::Song(song.clone()), Item::Song(song)]; app.view = crate::model::View::Queue; app.current = Some(1); let mut terminal = Terminal::new(TestBackend::new(140, 30)).unwrap(); terminal.draw(|f| draw(f, &mut app)).unwrap(); let buffer = terminal.backend().buffer(); let text = (3..23) .flat_map(|y| (23..112).map(move |x| buffer[(x, y)].symbol())) .collect::(); assert_eq!(text.matches("▶ PLAYING").count(), 1); } #[test] fn renders_small_and_large_terminals() { let mut app = App::for_tests(); for (width, height) in [(20, 8), (45, 14), (100, 30), (160, 45)] { app.theme = app.theme.next(); let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); terminal.draw(|f| draw(f, &mut app)).unwrap(); app.help = true; terminal.draw(|f| draw(f, &mut app)).unwrap(); app.help = false; } } }