arnaucube
arnaucube/octo-tuiPublic Self-hosted repository
octo-tui/src/ui.rs
src/ui.rsRaw
   1use crate::{
   2    app::{App, NAV},
   3    model::{Item, time},
   4};
   5use ratatui::{
   6    Frame,
   7    layout::{Constraint, Direction, Layout, Rect},
   8    style::{Modifier, Style},
   9    text::{Line, Span},
  10    widgets::{
  11        Block, Borders, Clear, Gauge, List, ListItem, ListState, Paragraph, Row, Table, Wrap,
  12    },
  13};
  14
  15/// Keep the browser and transport visible, with a compact layout for narrow terminals.
  16pub fn draw(frame: &mut Frame, app: &mut App) {
  17    let area = frame.area();
  18    let colors = app.theme.palette();
  19    frame.render_widget(
  20        Block::default().style(Style::default().bg(colors.bg).fg(colors.text)),
  21        area,
  22    );
  23    if area.width < 45 || area.height < 14 {
  24        frame.render_widget(
  25            Paragraph::new("Octo · enlarge terminal to at least 45 × 14\nq quits")
  26                .wrap(Wrap { trim: false }),
  27            area,
  28        );
  29        return;
  30    }
  31    let selected_download = app
  32        .items
  33        .get(app.table.selected().unwrap_or(0))
  34        .and_then(|item| match item {
  35            Item::Song(song) => app.downloads.get(&song.id),
  36            _ => None,
  37        })
  38        .map(|download| download.detail());
  39    let rows = Layout::default()
  40        .direction(Direction::Vertical)
  41        .constraints([
  42            Constraint::Length(3),
  43            Constraint::Min(4),
  44            Constraint::Length(4),
  45            Constraint::Length(
  46                (if area.width < 100 { 4 } else { 3 }) + u16::from(selected_download.is_some()),
  47            ),
  48        ])
  49        .split(area);
  50    let mode = if app.library_only {
  51        "LIBRARY ONLY · m toggles"
  52    } else {
  53        "SUBSONIC / OCTO · m library only"
  54    };
  55    frame.render_widget(
  56        Paragraph::new(Line::from(vec![
  57            Span::styled(
  58                "  ◉ OCTO ",
  59                Style::default()
  60                    .fg(colors.accent)
  61                    .add_modifier(Modifier::BOLD),
  62            ),
  63            Span::styled(
  64                " / terminal listening room",
  65                Style::default().fg(colors.muted),
  66            ),
  67            Span::raw(format!("    {mode}")),
  68        ]))
  69        .block(
  70            Block::default()
  71                .borders(Borders::BOTTOM)
  72                .border_style(Style::default().fg(colors.border)),
  73        ),
  74        rows[0],
  75    );
  76    let show_cover = app.artwork.enabled
  77        && area.width >= 100
  78        && area.height >= 20
  79        && (!matches!(app.view, crate::model::View::Home) || app.current.is_some());
  80    let show_queue =
  81        area.width >= 100 && area.height >= 20 && (show_cover || !app.queue.is_empty());
  82    let cols = Layout::default()
  83        .direction(Direction::Horizontal)
  84        .constraints([
  85            Constraint::Length(if area.width < 75 { 16 } else { 23 }),
  86            Constraint::Min(20),
  87            Constraint::Length(if show_queue { 28 } else { 0 }),
  88        ])
  89        .split(rows[1]);
  90    let nav: Vec<_> = NAV
  91        .iter()
  92        .enumerate()
  93        .map(|(i, name)| {
  94            let active = i == app.nav;
  95            let style = if active {
  96                Style::default()
  97                    .fg(colors.accent)
  98                    .bg(colors.panel)
  99                    .add_modifier(Modifier::BOLD)
 100            } else {
 101                Style::default().fg(colors.muted)
 102            };
 103            ListItem::new(format!(
 104                " {} {} {}",
 105                if active { "›" } else { " " },
 106                i,
 107                name
 108            ))
 109            .style(style)
 110        })
 111        .collect();
 112    let mut nav_state = ListState::default().with_selected(Some(app.nav));
 113    frame.render_stateful_widget(
 114        List::new(nav).block(
 115            Block::default()
 116                .title(if app.sidebar {
 117                    " Browse ● "
 118                } else {
 119                    " Browse "
 120                })
 121                .borders(Borders::ALL)
 122                .border_style(Style::default().fg(if app.sidebar {
 123                    colors.accent
 124                } else {
 125                    colors.border
 126                })),
 127        ),
 128        cols[0],
 129        &mut nav_state,
 130    );
 131    let block = Block::default()
 132        .title(format!(" {} · {} ", app.view.title(), app.items.len()))
 133        .borders(Borders::ALL)
 134        .border_style(Style::default().fg(if app.sidebar {
 135            colors.border
 136        } else {
 137            colors.accent
 138        }));
 139    if app.items.is_empty() {
 140        let message = if let Some(error) = &app.load_error {
 141            format!("Could not load {}:\n{error}\nR retries", app.view.title())
 142        } else if matches!(app.view, crate::model::View::History) && !app.library_only {
 143            "No listening history yet.\nSongs appear after playback starts.".into()
 144        } else if app.loading {
 145            "Loading music…\nYou can keep browsing or press q to quit.".into()
 146        } else if matches!(app.view, crate::model::View::Playlists) {
 147            "No playlists returned for this account.\nSelect a song and press a to create one.\nR refreshes".into()
 148        } else if app.library_only {
 149            "No library songs in this view.\nm includes online songs · R refreshes".into()
 150        } else if matches!(
 151            app.view,
 152            crate::model::View::Stations | crate::model::View::Station(_)
 153        ) {
 154            "No station tracks returned.\nOcto station tracks require the octoStations extension.\nR refreshes".into()
 155        } else {
 156            "No results.\n1 server search · 6 discover · R refresh".into()
 157        };
 158        frame.render_widget(
 159            Paragraph::new(message)
 160                .style(Style::default().fg(colors.muted))
 161                .wrap(Wrap { trim: false })
 162                .block(block),
 163            cols[1],
 164        );
 165    } else if matches!(app.view, crate::model::View::Home) {
 166        let entries = app
 167            .items
 168            .iter()
 169            .map(|item| Row::new([item.title().to_owned(), item.detail()]));
 170        let widths = [
 171            Constraint::Min(20),
 172            if cols[1].width >= 55 {
 173                Constraint::Percentage(55)
 174            } else {
 175                Constraint::Length(0)
 176            },
 177        ];
 178        frame.render_stateful_widget(
 179            Table::new(entries, widths)
 180                .header(
 181                    Row::new(["SECTION", "BROWSE"])
 182                        .style(Style::default().fg(colors.muted))
 183                        .bottom_margin(1),
 184                )
 185                .block(block)
 186                .row_highlight_style(
 187                    Style::default()
 188                        .bg(colors.selection)
 189                        .add_modifier(Modifier::BOLD),
 190                )
 191                .highlight_symbol("› "),
 192            cols[1],
 193            &mut app.table,
 194        );
 195    } else {
 196        let artist_view = matches!(
 197            app.view,
 198            crate::model::View::Artist(_) | crate::model::View::ArtistByName(_)
 199        );
 200        let table_rows: Vec<_> = app
 201            .items
 202            .iter()
 203            .enumerate()
 204            .map(|(i, item)| {
 205                let playing=if matches!(app.view,crate::model::View::Queue) {
 206                    app.current==Some(i)
 207                } else {
 208                    matches!(item,Item::Song(song) if app.current.and_then(|index|app.queue.get(index)).is_some_and(|current|current.id==song.id))
 209                };
 210                let download = match item {
 211                    Item::Song(song) => app.downloads.get(&song.id),
 212                    _ => None,
 213                };
 214                let title = if playing {
 215                    let progress = download
 216                        .map(|d| format!("[{}] ", d.label()))
 217                        .unwrap_or_default();
 218                    format!(
 219                        "{} {progress}{}",
 220                        if app.paused { "Ⅱ" } else { "▶" },
 221                        item.title()
 222                    )
 223                } else {
 224                    item.title().to_owned()
 225                };
 226                let duration = if let Item::Song(s) = item {
 227                    time(s.duration)
 228                } else {
 229                    String::new()
 230                };
 231                Row::new(vec![
 232                    if playing {
 233                        if app.paused {
 234                            "Ⅱ PAUSED"
 235                        } else {
 236                            "▶ PLAYING"
 237                        }
 238                        .into()
 239                    } else if let Some(download) = download {
 240                        download.label()
 241                    } else {
 242                        item.label().to_owned()
 243                    },
 244                    title,
 245                    if artist_view {
 246                        match item { Item::Song(song) => song.album.clone(), _ => item.detail() }
 247                    } else {
 248                        item.detail()
 249                    },
 250                    item.recommendation_source().to_owned(),
 251                    item.playback_source().to_owned(),
 252                    match item {
 253                        Item::Song(song) => song.year.filter(|year| *year > 0).map(|year| year.to_string()).unwrap_or_else(|| "—".into()),
 254                        _ => String::new(),
 255                    },
 256                    duration,
 257                ])
 258                .style(
 259                    Style::default()
 260                        .fg(if matches!(item,Item::Song(s) if s.is_external) {
 261                            colors.accent
 262                        } else {
 263                            colors.text
 264                        })
 265                        .add_modifier(if playing {
 266                            Modifier::BOLD
 267                        } else {
 268                            Modifier::empty()
 269                        }),
 270                )
 271            })
 272            .collect();
 273        let table_width = cols[1].width;
 274        let source_width = if table_width >= if artist_view { 110 } else { 82 } {
 275            18
 276        } else {
 277            0
 278        };
 279        let show_year =
 280            table_width >= 60 && app.items.iter().any(|item| matches!(item, Item::Song(_)));
 281        let widths = vec![
 282            Constraint::Length(9),
 283            Constraint::Min(12),
 284            if artist_view && table_width >= 45 {
 285                Constraint::Percentage(30)
 286            } else if table_width >= 110 {
 287                Constraint::Percentage(28)
 288            } else {
 289                Constraint::Length(0)
 290            },
 291            Constraint::Length(source_width),
 292            Constraint::Length(source_width),
 293            Constraint::Length(if show_year { 4 } else { 0 }),
 294            Constraint::Length(5),
 295        ];
 296        frame.render_stateful_widget(
 297            Table::new(table_rows, widths)
 298                .header(
 299                    Row::new([
 300                        "STATUS",
 301                        "TITLE",
 302                        if artist_view {
 303                            "ALBUM"
 304                        } else {
 305                            "ARTIST / ALBUM"
 306                        },
 307                        "SUGGESTED BY",
 308                        "LOADED FROM",
 309                        "YEAR",
 310                        "TIME",
 311                    ])
 312                    .style(Style::default().fg(colors.muted))
 313                    .bottom_margin(1),
 314                )
 315                .block(block)
 316                .row_highlight_style(
 317                    Style::default()
 318                        .bg(colors.selection)
 319                        .add_modifier(Modifier::BOLD),
 320                )
 321                .highlight_symbol("› "),
 322            cols[1],
 323            &mut app.table,
 324        );
 325    }
 326    let now = app.current.and_then(|i| app.queue.get(i));
 327    let side = if show_cover {
 328        let image_height = app.artwork.height_for_width(
 329            cols[2].width.saturating_sub(2),
 330            cols[2].height.saturating_sub(8),
 331        );
 332        Layout::vertical([Constraint::Length(image_height + 4), Constraint::Min(4)]).split(cols[2])
 333    } else {
 334        Layout::vertical([Constraint::Length(0), Constraint::Min(0)]).split(cols[2])
 335    };
 336    if show_cover {
 337        let block = Block::default()
 338            .title(" Cover · SIXEL ")
 339            .borders(Borders::ALL)
 340            .border_style(Style::default().fg(colors.border));
 341        let inner = block.inner(side[0]);
 342        frame.render_widget(block, side[0]);
 343        let parts = Layout::vertical([Constraint::Min(1), Constraint::Length(2)]).split(inner);
 344        if !app.help && app.playlist_dialog.is_none() {
 345            if let Some(protocol) = &mut app.artwork.protocol {
 346                frame.render_stateful_widget(
 347                    ratatui_image::StatefulImage::default().resize(ratatui_image::Resize::Scale(
 348                        Some(ratatui_image::FilterType::Triangle),
 349                    )),
 350                    parts[0],
 351                    protocol,
 352                );
 353            } else {
 354                frame.render_widget(
 355                    Paragraph::new(app.artwork.message.as_str())
 356                        .style(Style::default().fg(colors.muted))
 357                        .wrap(Wrap { trim: false }),
 358                    parts[0],
 359                );
 360            }
 361        }
 362        frame.render_widget(
 363            Paragraph::new(vec![
 364                Line::from(Span::styled(
 365                    app.artwork.title.as_str(),
 366                    Style::default().fg(colors.text),
 367                )),
 368                Line::from(Span::styled(
 369                    now.map(|song| song.artist.as_str()).unwrap_or_default(),
 370                    Style::default().fg(colors.muted),
 371                )),
 372            ]),
 373            parts[1],
 374        );
 375    }
 376    if show_queue {
 377        draw_queue(frame, app, side[1]);
 378    }
 379    let title = now
 380        .map(|s| format!("{} — {}", s.title, s.artist))
 381        .unwrap_or_else(|| "Choose a song to start listening".into());
 382    let state = if app.current.is_none() {
 383        "STOP"
 384    } else if app.paused {
 385        "PAUSE"
 386    } else {
 387        "PLAY"
 388    };
 389    let player = Block::default()
 390        .title(format!(" {state} · {title} "))
 391        .borders(Borders::ALL)
 392        .border_style(Style::default().fg(colors.border));
 393    let inside = player.inner(rows[2]);
 394    frame.render_widget(player, rows[2]);
 395    let playback = Layout::default()
 396        .direction(Direction::Vertical)
 397        .constraints([Constraint::Length(1), Constraint::Length(1)])
 398        .split(inside);
 399    let ratio = if app.duration > 0. {
 400        (app.position / app.duration).clamp(0., 1.)
 401    } else {
 402        0.
 403    };
 404    frame.render_widget(
 405        Gauge::default()
 406            .gauge_style(Style::default().fg(colors.accent).bg(colors.panel))
 407            .ratio(ratio)
 408            .label(format!(
 409                "{} / {}",
 410                time(app.position as u64),
 411                time(app.duration as u64)
 412            )),
 413        playback[0],
 414    );
 415    let suggestion = now
 416        .and_then(|s| s.octo_suggested_by.as_deref())
 417        .unwrap_or("");
 418    frame.render_widget(
 419        Paragraph::new(format!(
 420            "vol {}% · {} queued · repeat {}   {} · Loaded from: {}",
 421            app.volume,
 422            app.queue.len(),
 423            if app.repeat { "on" } else { "off" },
 424            suggestion,
 425            now.map(|s| if s.is_external {
 426                s.playback_source.as_deref().unwrap_or("Unknown")
 427            } else {
 428                "Library"
 429            })
 430            .unwrap_or("—")
 431        ))
 432        .style(Style::default().fg(colors.muted)),
 433        playback[1],
 434    );
 435    let selected_source = app
 436        .items
 437        .get(app.table.selected().unwrap_or(0))
 438        .map(Item::recommendation_source)
 439        .unwrap_or("—");
 440    let selected_playback = app
 441        .items
 442        .get(app.table.selected().unwrap_or(0))
 443        .map(Item::playback_source)
 444        .unwrap_or("—");
 445    let source_line = if matches!(app.view, crate::model::View::Home) {
 446        format!(
 447            "0 Home · Enter opens section · theme: {} (t)",
 448            app.theme.name()
 449        )
 450    } else if area.width < 100 {
 451        format!(
 452            "Suggested by: {selected_source}\nLoaded from: {selected_playback} · theme: {} (t)",
 453            app.theme.name()
 454        )
 455    } else {
 456        format!(
 457            "Suggested by: {selected_source} · Loaded from: {selected_playback} · theme: {} (t)",
 458            app.theme.name()
 459        )
 460    };
 461    let source_line = if let Some(download) = selected_download {
 462        format!("{source_line}\nDownload: {download}")
 463    } else {
 464        source_line
 465    };
 466    let footer = if let Some(input) = &app.input {
 467        if app.server_search {
 468            format!("Search server: {input}▏  Enter search · Esc cancel")
 469        } else {
 470            format!("/ {input}▏  Find in view · Enter keep position · Esc cancel")
 471        }
 472    } else {
 473        format!(
 474            "{}\n{}\nj/k move · Enter play/open · / find · 1 server search · a playlist · e queue · r radio · d library · ? help",
 475            app.status, source_line
 476        )
 477    };
 478    frame.render_widget(
 479        Paragraph::new(footer).style(Style::default().fg(if app.input.is_some() {
 480            colors.accent
 481        } else {
 482            colors.muted
 483        })),
 484        rows[3],
 485    );
 486    if app.help {
 487        draw_help(frame, app);
 488    }
 489    if app.playlist_dialog.is_some() {
 490        draw_playlist_dialog(frame, app);
 491    }
 492}
 493
 494/// Keep playlist selection and naming in one modal without changing the browser's song.
 495fn draw_playlist_dialog(frame: &mut Frame, app: &App) {
 496    let dialog = app.playlist_dialog.as_ref().unwrap();
 497    let colors = app.theme.palette();
 498    let area = frame.area();
 499    let width = area.width.saturating_sub(4).min(72);
 500    let height = area.height.saturating_sub(2).min(22);
 501    let popup = Rect::new(
 502        (area.width - width) / 2,
 503        (area.height - height) / 2,
 504        width,
 505        height,
 506    );
 507    let block = Block::default()
 508        .title(" Add song to playlist ")
 509        .borders(Borders::ALL)
 510        .border_style(Style::default().fg(colors.accent))
 511        .style(Style::default().fg(colors.text).bg(colors.panel));
 512    let inner = block.inner(popup);
 513    frame.render_widget(Clear, popup);
 514    frame.render_widget(block, popup);
 515    let rows = Layout::vertical([
 516        Constraint::Length(3),
 517        Constraint::Min(1),
 518        Constraint::Length(3),
 519    ])
 520    .split(inner);
 521    frame.render_widget(
 522        Paragraph::new(vec![
 523            Line::from(Span::styled(
 524                dialog.song.title.as_str(),
 525                Style::default().add_modifier(Modifier::BOLD),
 526            )),
 527            Line::from(dialog.song.artist.as_str()),
 528        ]),
 529        rows[0],
 530    );
 531    if let Some(name) = &dialog.new_name {
 532        frame.render_widget(
 533            Paragraph::new(format!("New playlist name:\n{name}▏"))
 534                .style(Style::default().fg(colors.accent)),
 535            rows[1],
 536        );
 537    } else {
 538        let entries = std::iter::once(
 539            ListItem::new("+ Create new playlist").style(Style::default().fg(colors.accent)),
 540        )
 541        .chain(dialog.choices.iter().map(|p| {
 542            ListItem::new(format!("{}{}", p.name, p.suffix())).style(Style::default().fg(
 543                if p.addition_error().is_some() {
 544                    colors.muted
 545                } else {
 546                    colors.text
 547                },
 548            ))
 549        }));
 550        let mut state = ListState::default().with_selected(Some(dialog.selected));
 551        frame.render_stateful_widget(
 552            List::new(entries).highlight_symbol("› ").highlight_style(
 553                Style::default()
 554                    .bg(colors.selection)
 555                    .add_modifier(Modifier::BOLD),
 556            ),
 557            rows[1],
 558            &mut state,
 559        );
 560    }
 561    let instructions = if dialog.pending_target.is_some() {
 562        "Waiting for library indexing… Esc cancels"
 563    } else if dialog.saving {
 564        "Adding song…"
 565    } else if dialog.new_name.is_some() {
 566        "Enter creates and adds · Esc returns"
 567    } else {
 568        "j/k move · Enter adds · n new · Esc cancels"
 569    };
 570    let status = dialog.error.as_deref().unwrap_or(if dialog.loading {
 571        "Loading playlists…"
 572    } else if dialog.choices.is_empty() {
 573        "No existing playlists returned; n creates one"
 574    } else {
 575        ""
 576    });
 577    frame.render_widget(
 578        Paragraph::new(vec![
 579            Line::from(Span::styled(status, Style::default().fg(colors.accent))),
 580            Line::from(instructions),
 581        ])
 582        .wrap(Wrap { trim: false }),
 583        rows[2],
 584    );
 585}
 586
 587/// Give keys their own accent color and let small terminals scroll through every binding.
 588fn draw_help(frame: &mut Frame, app: &mut App) {
 589    let colors = app.theme.palette();
 590    let entries = [
 591        ("", "BROWSE"),
 592        ("j / k · arrows", "Move selection"),
 593        ("gg / G", "First / last entry"),
 594        ("Ctrl-d / Ctrl-u", "Move ten rows"),
 595        ("h / Tab", "Focus sidebar / toggle focus"),
 596        ("l / Enter", "Open selection or play"),
 597        ("i", "Open selected song’s artist"),
 598        ("m", "Toggle library-only mode"),
 599        ("Esc / Backspace", "Go back"),
 600        ("0", "Home"),
 601        ("2–9", "Artists through History"),
 602        ("/", "Find in current view as you type"),
 603        ("1", "Search the server"),
 604        ("< / >", "Previous / next album or song page"),
 605        ("o / R", "Cycle album order / refresh"),
 606        ("t", "Cycle theme"),
 607        ("", "PLAYBACK"),
 608        ("Enter", "Play visible list from selection"),
 609        ("Space", "Pause / resume"),
 610        ("H / L", "Previous / next song (Shift-h/l)"),
 611        ("[ / ]", "Seek backward / forward 10 seconds"),
 612        ("- / =", "Volume down / up 5%"),
 613        ("", "PLAYLISTS"),
 614        ("a", "Add selected song to a playlist"),
 615        ("9", "Recently played songs (History)"),
 616        ("", "QUEUE"),
 617        ("e / A", "Append selected / all visible songs"),
 618        ("s", "Shuffle upcoming songs"),
 619        ("z", "Toggle queue repeat"),
 620        ("8", "Open full queue"),
 621        ("x", "Remove selected queue song"),
 622        ("J / K", "Move queue song down / up"),
 623        ("", "DISCOVER"),
 624        ("6 / 7", "Discover / Stations"),
 625        ("r", "Radio from selected song"),
 626        ("f", "Toggle favorite"),
 627        ("d / +", "Download external song to library"),
 628        ("", "DISCOVER labels songs not owned"),
 629        ("? / Esc", "Close help"),
 630        ("q / Ctrl-c", "Quit player (outside help)"),
 631    ];
 632    let area = frame.area();
 633    let width = area.width.saturating_sub(6).min(86);
 634    let narrow = width < 64;
 635    let key_style = Style::default()
 636        .fg(colors.accent)
 637        .add_modifier(Modifier::BOLD);
 638    let description_style = Style::default().fg(colors.text);
 639    let mut lines = Vec::new();
 640    for (key, description) in entries {
 641        if key.is_empty() {
 642            lines.push(Line::from(Span::styled(
 643                description,
 644                Style::default()
 645                    .fg(colors.muted)
 646                    .add_modifier(Modifier::BOLD),
 647            )));
 648        } else if narrow {
 649            lines.push(Line::from(Span::styled(key, key_style)));
 650            lines.push(Line::from(Span::styled(
 651                format!("  {description}"),
 652                description_style,
 653            )));
 654        } else {
 655            lines.push(Line::from(vec![
 656                Span::styled(format!("{key:<20}"), key_style),
 657                Span::styled(description, description_style),
 658            ]));
 659        }
 660    }
 661    let height = area.height.saturating_sub(2).min(lines.len() as u16 + 2);
 662    let popup = Rect::new(
 663        (area.width - width) / 2,
 664        (area.height - height) / 2,
 665        width,
 666        height,
 667    );
 668    let block = Block::default()
 669        .title(" Shortcuts ")
 670        .title_bottom(Line::from(vec![
 671            Span::styled(" j/k · PgUp/PgDn ", key_style),
 672            Span::styled("scroll · Esc close ", description_style),
 673        ]))
 674        .borders(Borders::ALL)
 675        .border_style(Style::default().fg(colors.accent));
 676    let inner = block.inner(popup);
 677    app.help_scroll = app
 678        .help_scroll
 679        .min((lines.len() as u16).saturating_sub(inner.height));
 680    frame.render_widget(Clear, popup);
 681    frame.render_widget(
 682        Paragraph::new(lines)
 683            .scroll((app.help_scroll, 0))
 684            .style(Style::default().bg(colors.panel))
 685            .block(block),
 686        popup,
 687    );
 688}
 689
 690/// Follow playback and render the live queue without moving the browser's selection.
 691fn draw_queue(frame: &mut Frame, app: &App, area: Rect) {
 692    let colors = app.theme.palette();
 693    let block = Block::default()
 694        .title(" Queue ")
 695        .title_style(
 696            Style::default()
 697                .fg(colors.accent)
 698                .add_modifier(Modifier::BOLD),
 699        )
 700        .borders(Borders::ALL)
 701        .border_style(Style::default().fg(colors.border));
 702    let inner = block.inner(area);
 703    frame.render_widget(block, area);
 704    if app.queue.is_empty() {
 705        frame.render_widget(
 706            Paragraph::new("Queue is empty\ne adds a song · 8 opens queue")
 707                .wrap(Wrap { trim: false })
 708                .style(Style::default().fg(colors.muted)),
 709            inner,
 710        );
 711        return;
 712    }
 713    let start = app
 714        .current
 715        .unwrap_or(0)
 716        .min(app.queue.len().saturating_sub(1));
 717    let entries = app
 718        .queue
 719        .iter()
 720        .enumerate()
 721        .skip(start)
 722        .map(|(index, song)| {
 723            let playing = app.current == Some(index);
 724            let marker = if playing {
 725                if app.paused { "Ⅱ" } else { "▶" }
 726            } else {
 727                "·"
 728            };
 729            let download = app
 730                .downloads
 731                .get(&song.id)
 732                .map(|d| format!("[{}] ", d.label()))
 733                .unwrap_or_default();
 734            ListItem::new(format!("{marker} {}. {download}{}", index + 1, song.title)).style(
 735                Style::default().fg(colors.text).add_modifier(if playing {
 736                    Modifier::BOLD
 737                } else {
 738                    Modifier::empty()
 739                }),
 740            )
 741        });
 742    frame.render_widget(List::new(entries), inner);
 743}
 744
 745#[cfg(test)]
 746mod tests {
 747    use super::*;
 748    use ratatui::{Terminal, backend::TestBackend};
 749    #[test]
 750    fn suggestion_service_remains_visible_on_narrow_terminals() {
 751        let mut app = App::for_tests();
 752        app.view = crate::model::View::Discover;
 753        app.items = vec![Item::Song(crate::model::Song {
 754            title: "Suggested track".into(),
 755            is_external: true,
 756            octo_suggested_by: Some("YouTube Music".into()),
 757            ..Default::default()
 758        })];
 759        for width in [45, 80, 140] {
 760            let mut terminal = Terminal::new(TestBackend::new(width, 30)).unwrap();
 761            terminal.draw(|f| draw(f, &mut app)).unwrap();
 762            let text = terminal
 763                .backend()
 764                .buffer()
 765                .content
 766                .iter()
 767                .map(|c| c.symbol())
 768                .collect::<String>();
 769            assert!(text.contains("YouTube Music"));
 770        }
 771    }
 772    #[test]
 773    fn home_sections_and_numbered_sidebar_render() {
 774        let mut app = App::for_tests();
 775        let mut terminal = Terminal::new(TestBackend::new(120, 30)).unwrap();
 776        terminal.draw(|f| draw(f, &mut app)).unwrap();
 777        let text = terminal
 778            .backend()
 779            .buffer()
 780            .content
 781            .iter()
 782            .map(|c| c.symbol())
 783            .collect::<String>();
 784        for label in [
 785            "0 Home",
 786            "1 Search",
 787            "2 Artists",
 788            "8 Queue",
 789            "9 History",
 790            "Recently played",
 791            "Recently added",
 792            "Most played",
 793            "Highest rated",
 794        ] {
 795            assert!(text.contains(label), "Missing {label}");
 796        }
 797        let queue_position = text.find("8 Queue").unwrap();
 798        let history_position = text.find("9 History").unwrap();
 799        assert!(history_position > queue_position);
 800        assert!(!text.contains("Favorites"));
 801        app.key(crossterm::event::KeyEvent::new(
 802            crossterm::event::KeyCode::Char('8'),
 803            crossterm::event::KeyModifiers::NONE,
 804        ));
 805        let mut terminal = Terminal::new(TestBackend::new(65, 20)).unwrap();
 806        terminal.draw(|f| draw(f, &mut app)).unwrap();
 807        let text = terminal
 808            .backend()
 809            .buffer()
 810            .content
 811            .iter()
 812            .map(|c| c.symbol())
 813            .collect::<String>();
 814        assert!(text.contains("8 Queue"));
 815    }
 816    #[test]
 817    fn cover_caption_shows_playing_artist_independently_of_cursor_and_long_titles() {
 818        let mut app = App::for_tests();
 819        app.artwork.enabled = true;
 820        app.queue = crate::test_support::songs();
 821        app.queue[0].artist = "First artist".into();
 822        app.queue[1].artist = "Next artist".into();
 823        app.current = Some(0);
 824        app.items = vec![Item::Song(app.queue[1].clone())];
 825        app.table.select(Some(0));
 826        app.artwork.title =
 827            "A very long song title that should not push the artist out of view".into();
 828        for (current, artist) in [(0, "First artist"), (1, "Next artist")] {
 829            app.current = Some(current);
 830            app.paused = true;
 831            let mut terminal = Terminal::new(TestBackend::new(140, 40)).unwrap();
 832            terminal.draw(|f| draw(f, &mut app)).unwrap();
 833            let buffer = terminal.backend().buffer();
 834            let caption: String = (113..139).map(|x| buffer[(x, 18)].symbol()).collect();
 835            assert!(caption.contains(artist));
 836            assert_eq!(buffer[(113, 18)].fg, app.theme.palette().muted);
 837        }
 838        app.current = None;
 839        let mut terminal = Terminal::new(TestBackend::new(140, 40)).unwrap();
 840        app.view = crate::model::View::Songs { offset: 0 };
 841        terminal.draw(|f| draw(f, &mut app)).unwrap();
 842        let caption: String = (113..139)
 843            .map(|x| terminal.backend().buffer()[(x, 18)].symbol())
 844            .collect();
 845        assert!(!caption.contains("artist"));
 846    }
 847
 848    #[test]
 849    fn queue_stays_close_to_cover_as_terminal_height_grows() {
 850        let mut app = App::for_tests();
 851        app.artwork.enabled = true;
 852        app.artwork.title = "Current cover".into();
 853        app.queue = crate::test_support::songs();
 854        app.current = Some(0);
 855        for height in [40, 70] {
 856            let mut terminal = Terminal::new(TestBackend::new(140, height)).unwrap();
 857            terminal.draw(|f| draw(f, &mut app)).unwrap();
 858            let buffer = terminal.backend().buffer();
 859            let queue_row = (3..height - 7)
 860                .find(|y| {
 861                    (112..140)
 862                        .map(|x| buffer[(x, *y)].symbol())
 863                        .collect::<String>()
 864                        .contains("Queue")
 865                })
 866                .unwrap();
 867            // A 26-column square cover uses 13 rows, plus two caption rows and borders.
 868            assert_eq!(queue_row, 20);
 869            assert_eq!(buffer[(112, queue_row - 1)].symbol(), "└");
 870            assert_eq!(buffer[(139, queue_row - 1)].symbol(), "┘");
 871            let caption: String = (113..139)
 872                .map(|x| buffer[(x, queue_row - 3)].symbol())
 873                .collect();
 874            assert!(caption.contains("Current cover"));
 875        }
 876    }
 877
 878    #[test]
 879    fn queue_preview_follows_current_track_and_live_edits_without_art() {
 880        let mut app = App::for_tests();
 881        app.queue = crate::test_support::songs();
 882        app.current = Some(1);
 883        let mut terminal = Terminal::new(TestBackend::new(140, 30)).unwrap();
 884        terminal.draw(|f| draw(f, &mut app)).unwrap();
 885        let queue_text = |terminal: &Terminal<TestBackend>| {
 886            let buffer = terminal.backend().buffer();
 887            (3..23)
 888                .flat_map(|y| (112..140).map(move |x| buffer[(x, y)].symbol()))
 889                .collect::<String>()
 890        };
 891        let text = queue_text(&terminal);
 892        assert!(text.contains("Queue"));
 893        assert!(text.contains("▶ 2."));
 894        assert!(text.contains("Track 2"));
 895        assert!(!text.contains("Track 0"));
 896        app.current = Some(2);
 897        app.queue.remove(3);
 898        terminal.draw(|f| draw(f, &mut app)).unwrap();
 899        let text = queue_text(&terminal);
 900        assert!(text.contains("▶ 3. Track 2"));
 901        assert!(!text.contains("Track 1"));
 902        assert!(!text.contains("Track 3"));
 903        app.artwork.enabled = true;
 904        app.view = crate::model::View::Songs { offset: 0 };
 905        app.queue.clear();
 906        app.current = None;
 907        terminal.draw(|f| draw(f, &mut app)).unwrap();
 908        let text = queue_text(&terminal);
 909        assert!(text.contains("Cover"));
 910        assert!(text.contains("Queue is empty"));
 911        for (w, h) in [(100, 20), (80, 24)] {
 912            let mut t = Terminal::new(TestBackend::new(w, h)).unwrap();
 913            t.draw(|f| draw(f, &mut app)).unwrap();
 914        }
 915    }
 916    #[test]
 917    fn queue_title_and_help_keys_have_visible_theme_accents() {
 918        let mut app = App::for_tests();
 919        app.queue = crate::test_support::songs();
 920        let mut terminal = Terminal::new(TestBackend::new(140, 40)).unwrap();
 921        terminal.draw(|f| draw(f, &mut app)).unwrap();
 922        let buffer = terminal.backend().buffer();
 923        let title = (112..140)
 924            .find_map(|x| (buffer[(x, 3)].symbol() == "Q").then_some(&buffer[(x, 3)]))
 925            .unwrap();
 926        assert_eq!(title.fg, app.theme.palette().accent);
 927        assert!(title.modifier.contains(Modifier::BOLD));
 928        app.help = true;
 929        terminal.draw(|f| draw(f, &mut app)).unwrap();
 930        let key = terminal
 931            .backend()
 932            .buffer()
 933            .content
 934            .windows(21)
 935            .find(|cells| {
 936                cells[0].symbol() == "H" && cells[2].symbol() == "/" && cells[4].symbol() == "L"
 937            })
 938            .unwrap();
 939        assert_eq!(key[0].fg, app.theme.palette().accent);
 940        assert_eq!(key[20].fg, app.theme.palette().text);
 941        let selection = app.table.selected();
 942        app.key(crossterm::event::KeyEvent::new(
 943            crossterm::event::KeyCode::Char('j'),
 944            crossterm::event::KeyModifiers::NONE,
 945        ));
 946        assert_eq!(app.help_scroll, 1);
 947        assert_eq!(app.table.selected(), selection);
 948        let mut terminal = Terminal::new(TestBackend::new(60, 20)).unwrap();
 949        app.help_scroll = u16::MAX;
 950        terminal.draw(|f| draw(f, &mut app)).unwrap();
 951        let text = terminal
 952            .backend()
 953            .buffer()
 954            .content
 955            .iter()
 956            .map(|c| c.symbol())
 957            .collect::<String>();
 958        assert!(text.contains("Download external song"));
 959        assert!(text.contains("Close help"));
 960    }
 961    #[test]
 962    fn full_queue_marks_playback_separately_from_cursor_and_updates_when_paused() {
 963        let mut app = App::for_tests();
 964        app.queue = crate::test_support::songs();
 965        app.current = Some(2);
 966        app.key(crossterm::event::KeyEvent::new(
 967            crossterm::event::KeyCode::Char('8'),
 968            crossterm::event::KeyModifiers::NONE,
 969        ));
 970        assert_eq!(app.table.selected(), Some(2));
 971        app.table.select(Some(0));
 972        let mut terminal = Terminal::new(TestBackend::new(140, 30)).unwrap();
 973        terminal.draw(|f| draw(f, &mut app)).unwrap();
 974        let status_text = |t: &Terminal<TestBackend>| {
 975            let buffer = t.backend().buffer();
 976            (3..23)
 977                .flat_map(|y| (23..112).map(move |x| buffer[(x, y)].symbol()))
 978                .collect::<String>()
 979        };
 980        let text = status_text(&terminal);
 981        assert!(text.contains("▶ PLAYING"));
 982        assert!(text.contains("▶ Track 2"));
 983        let buffer = terminal.backend().buffer();
 984        let marker = (3..23)
 985            .find_map(|y| {
 986                (23..112).find_map(|x| (buffer[(x, y)].symbol() == "▶").then_some(&buffer[(x, y)]))
 987            })
 988            .unwrap();
 989        assert_eq!(marker.fg, app.theme.palette().text);
 990        assert!(marker.modifier.contains(Modifier::BOLD));
 991        app.key(crossterm::event::KeyEvent::new(
 992            crossterm::event::KeyCode::Char('L'),
 993            crossterm::event::KeyModifiers::SHIFT,
 994        ));
 995        assert_eq!(app.table.selected(), Some(0));
 996        app.paused = true;
 997        terminal.draw(|f| draw(f, &mut app)).unwrap();
 998        let text = status_text(&terminal);
 999        assert!(text.contains("Ⅱ PAUSED"));
1000        assert!(!text.contains("▶ PLAYING"));
1001        assert!(!text.contains("▶ Track 2"));
1002    }
1003    #[test]
1004    fn per_song_download_status_is_visible_in_queue_and_narrow_footer() {
1005        let mut app = App::for_tests();
1006        let song = crate::test_support::songs().remove(4);
1007        let mut download = crate::downloads::Download::requesting();
1008        download.update(&crate::downloads::Acquisition {
1009            state: "downloading".into(),
1010            progress: Some(0.42),
1011            source: Some("Soulseek".into()),
1012            ..Default::default()
1013        });
1014        app.downloads.insert(song.id.clone(), download);
1015        app.queue = vec![song];
1016        app.key(crossterm::event::KeyEvent::new(
1017            crossterm::event::KeyCode::Char('8'),
1018            crossterm::event::KeyModifiers::NONE,
1019        ));
1020        for width in [65, 140] {
1021            let mut terminal = Terminal::new(TestBackend::new(width, 30)).unwrap();
1022            terminal.draw(|f| draw(f, &mut app)).unwrap();
1023            let text = terminal
1024                .backend()
1025                .buffer()
1026                .content
1027                .iter()
1028                .map(|c| c.symbol())
1029                .collect::<String>();
1030            assert!(text.contains("↓ 42%"));
1031            assert!(text.contains("Download: ↓ 42% · Soulseek"));
1032        }
1033    }
1034    #[test]
1035    fn playing_status_survives_download_completion_and_track_changes() {
1036        use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
1037        let mut app = App::for_tests();
1038        app.queue = crate::test_support::songs()
1039            .into_iter()
1040            .skip(4)
1041            .take(2)
1042            .collect();
1043        for (i, state) in ["downloading", "done"].into_iter().enumerate() {
1044            let mut download = crate::downloads::Download::requesting();
1045            download.update(&crate::downloads::Acquisition {
1046                state: state.into(),
1047                progress: Some(0.42),
1048                ..Default::default()
1049            });
1050            app.downloads.insert(app.queue[i].id.clone(), download);
1051        }
1052        let key = |app: &mut App, c| app.key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE));
1053        key(&mut app, '8');
1054        app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
1055        let mut terminal = Terminal::new(TestBackend::new(140, 30)).unwrap();
1056        let main_text = |terminal: &Terminal<TestBackend>| {
1057            let buffer = terminal.backend().buffer();
1058            (3..23)
1059                .flat_map(|y| (23..112).map(move |x| buffer[(x, y)].symbol()))
1060                .collect::<String>()
1061        };
1062        terminal.draw(|f| draw(f, &mut app)).unwrap();
1063        let text = main_text(&terminal);
1064        assert_eq!(text.matches("▶ PLAYING").count(), 1);
1065        assert!(text.contains("[↓ 42%] Track 4"));
1066        key(&mut app, 'L');
1067        terminal.draw(|f| draw(f, &mut app)).unwrap();
1068        let text = main_text(&terminal);
1069        assert_eq!(text.matches("▶ PLAYING").count(), 1);
1070        assert!(text.contains("▶ [✓ ADDED] Track 5"));
1071        key(&mut app, ' ');
1072        terminal.draw(|f| draw(f, &mut app)).unwrap();
1073        let text = main_text(&terminal);
1074        assert!(text.contains("Ⅱ PAUSED"));
1075        assert!(!text.contains("▶ PLAYING"));
1076        assert!(text.contains("[✓ ADDED] Track 5"));
1077        key(&mut app, 'H');
1078        terminal.draw(|f| draw(f, &mut app)).unwrap();
1079        let text = main_text(&terminal);
1080        assert!(text.contains("▶ PLAYING"));
1081        assert!(text.contains("▶ [↓ 42%] Track 4"));
1082    }
1083    #[test]
1084    fn playlist_modal_renders_choices_and_name_field_on_small_terminals() {
1085        let mut app = App::for_tests();
1086        let mut dialog =
1087            crate::playlists::PlaylistDialog::new(1, crate::test_support::songs().remove(0));
1088        dialog.loading = false;
1089        dialog.choices = vec![crate::playlists::PlaylistChoice {
1090            name: "Evening playlist".into(),
1091            ..Default::default()
1092        }];
1093        dialog.choices.push(crate::playlists::PlaylistChoice {
1094            id: "station".into(),
1095            name: "Station".into(),
1096            readonly: true,
1097            ..Default::default()
1098        });
1099        app.playlist_dialog = Some(dialog);
1100        for width in [45, 120] {
1101            let mut terminal = Terminal::new(TestBackend::new(width, 30)).unwrap();
1102            terminal.draw(|f| draw(f, &mut app)).unwrap();
1103            let text = terminal
1104                .backend()
1105                .buffer()
1106                .content
1107                .iter()
1108                .map(|c| c.symbol())
1109                .collect::<String>();
1110            assert!(text.contains("Add song to playlist"));
1111            assert!(text.contains("Create new playlist"));
1112            assert!(text.contains("Evening playlist"));
1113            assert!(text.contains("Station [read-only]"));
1114        }
1115        app.playlist_dialog.as_mut().unwrap().new_name = Some("Café".into());
1116        let mut terminal = Terminal::new(TestBackend::new(100, 30)).unwrap();
1117        terminal.draw(|f| draw(f, &mut app)).unwrap();
1118        let text = terminal
1119            .backend()
1120            .buffer()
1121            .content
1122            .iter()
1123            .map(|c| c.symbol())
1124            .collect::<String>();
1125        assert!(text.contains("Café"));
1126    }
1127    #[test]
1128    fn playlists_show_empty_state_or_actual_load_error() {
1129        let mut app = App::for_tests();
1130        app.view = crate::model::View::Playlists;
1131        app.items.clear();
1132        app.loading = false;
1133        let mut terminal = Terminal::new(TestBackend::new(120, 30)).unwrap();
1134        terminal.draw(|f| draw(f, &mut app)).unwrap();
1135        let text: String = terminal
1136            .backend()
1137            .buffer()
1138            .content
1139            .iter()
1140            .map(|c| c.symbol())
1141            .collect();
1142        assert!(text.contains("No playlists returned for this account"));
1143        assert!(!text.contains("Octo-only"));
1144        app.load_error = Some("getPlaylists: HTTP 403 Forbidden".into());
1145        terminal.draw(|f| draw(f, &mut app)).unwrap();
1146        let text: String = terminal
1147            .backend()
1148            .buffer()
1149            .content
1150            .iter()
1151            .map(|c| c.symbol())
1152            .collect();
1153        assert!(text.contains("HTTP 403 Forbidden"));
1154        assert!(!text.contains("No playlists returned"));
1155    }
1156
1157    #[test]
1158    fn song_panels_show_years_and_unknown_dates_in_the_year_column() {
1159        use crate::model::{Song, View};
1160        let songs: Vec<_> = [("Dated", Some(2024)), ("Missing", None), ("Zero", Some(0))]
1161            .into_iter()
1162            .map(|(title, year)| Song {
1163                id: title.into(),
1164                title: title.into(),
1165                year,
1166                ..Default::default()
1167            })
1168            .collect();
1169        for view in [
1170            View::Search("test".into()),
1171            View::Songs { offset: 0 },
1172            View::Album("album".into()),
1173            View::Artist("artist".into()),
1174            View::ArtistByName("artist".into()),
1175            View::Playlist("list".into()),
1176            View::Queue,
1177            View::History,
1178            View::Discover,
1179            View::Station("station".into()),
1180            View::Radio("song".into()),
1181            View::Genre("Rock".into()),
1182        ] {
1183            let mut app = App::for_tests();
1184            app.view = view;
1185            app.queue = songs.clone();
1186            app.items = songs.iter().cloned().map(Item::Song).collect();
1187            for width in [120, 180] {
1188                let mut terminal = Terminal::new(TestBackend::new(width, 30)).unwrap();
1189                terminal.draw(|f| draw(f, &mut app)).unwrap();
1190                let buffer = terminal.backend().buffer();
1191                let year_column = (0..20)
1192                    .find_map(|y| {
1193                        (23..width - 3).find(|x| {
1194                            (*x..*x + 4)
1195                                .map(|x| buffer[(x, y)].symbol())
1196                                .collect::<String>()
1197                                == "YEAR"
1198                        })
1199                    })
1200                    .expect("Year header missing");
1201                for (title, expected) in [("Dated", "2024"), ("Missing", "—"), ("Zero", "—")] {
1202                    let row = (0..20)
1203                        .find(|y| {
1204                            (23..width - 28)
1205                                .map(|x| buffer[(x, *y)].symbol())
1206                                .collect::<String>()
1207                                .contains(title)
1208                        })
1209                        .unwrap();
1210                    let value: String = (year_column..year_column + 4)
1211                        .map(|x| buffer[(x, row)].symbol())
1212                        .collect();
1213                    assert_eq!(value.trim(), expected);
1214                }
1215            }
1216        }
1217    }
1218
1219    #[test]
1220    fn library_mode_is_visible_and_explains_empty_filtered_views() {
1221        let mut app = App::for_tests();
1222        app.library_only = true;
1223        app.view = crate::model::View::Radio("song".into());
1224        app.items.clear();
1225        app.loading = false;
1226        let mut terminal = Terminal::new(TestBackend::new(120, 30)).unwrap();
1227        terminal.draw(|f| draw(f, &mut app)).unwrap();
1228        let text: String = terminal
1229            .backend()
1230            .buffer()
1231            .content
1232            .iter()
1233            .map(|cell| cell.symbol())
1234            .collect();
1235        assert!(text.contains("LIBRARY ONLY"));
1236        assert!(text.contains("No library songs in this view"));
1237        assert!(text.contains("m includes online songs"));
1238        app.help = true;
1239        let mut terminal = Terminal::new(TestBackend::new(120, 65)).unwrap();
1240        terminal.draw(|f| draw(f, &mut app)).unwrap();
1241        let text: String = terminal
1242            .backend()
1243            .buffer()
1244            .content
1245            .iter()
1246            .map(|cell| cell.symbol())
1247            .collect();
1248        assert!(text.contains("Toggle library-only mode"));
1249    }
1250
1251    #[test]
1252    fn artist_tracks_show_album_column_on_medium_and_wide_terminals() {
1253        for view in [
1254            crate::model::View::Artist("id".into()),
1255            crate::model::View::ArtistByName("Artist".into()),
1256        ] {
1257            let mut app = App::for_tests();
1258            app.view = view;
1259            app.items = vec![Item::Song(crate::model::Song {
1260                id: "song".into(),
1261                title: "Example song".into(),
1262                artist: "Example artist".into(),
1263                album: "Example album".into(),
1264                ..Default::default()
1265            })];
1266            for width in [100, 160] {
1267                let mut terminal = Terminal::new(TestBackend::new(width, 30)).unwrap();
1268                terminal.draw(|f| draw(f, &mut app)).unwrap();
1269                let buffer = terminal.backend().buffer();
1270                let text: String = (0..20)
1271                    .flat_map(|y| (0..width).map(move |x| buffer[(x, y)].symbol()))
1272                    .collect();
1273                assert!(text.contains("ALBUM"));
1274                assert!(text.contains("Example album"));
1275                assert!(text.contains("Example song"));
1276                assert!(!text.contains("ARTIST / ALBUM"));
1277            }
1278        }
1279    }
1280
1281    #[test]
1282    fn history_shows_clear_empty_state_and_needs_no_server_request() {
1283        let mut app = App::for_tests();
1284        app.key(crossterm::event::KeyEvent::new(
1285            crossterm::event::KeyCode::Char('9'),
1286            crossterm::event::KeyModifiers::NONE,
1287        ));
1288        let mut terminal = Terminal::new(TestBackend::new(120, 30)).unwrap();
1289        terminal.draw(|f| draw(f, &mut app)).unwrap();
1290        let text = terminal
1291            .backend()
1292            .buffer()
1293            .content
1294            .iter()
1295            .map(|c| c.symbol())
1296            .collect::<String>();
1297        assert!(text.contains("No listening history yet"));
1298        assert!(!app.loading);
1299    }
1300    #[test]
1301    fn every_song_panel_marks_current_song_by_id_and_updates_on_track_changes() {
1302        use crate::model::View;
1303        let mut app = App::for_tests();
1304        let songs = crate::test_support::songs();
1305        app.queue = songs.clone();
1306        app.current = Some(1);
1307        // Reverse rows to prove that the marker follows IDs rather than browsing position.
1308        app.items = vec![
1309            Item::Song(songs[2].clone()),
1310            Item::Song(songs[1].clone()),
1311            Item::Song(songs[0].clone()),
1312        ];
1313        let main_text = |terminal: &Terminal<TestBackend>| {
1314            let buffer = terminal.backend().buffer();
1315            (3..23)
1316                .flat_map(|y| (23..112).map(move |x| buffer[(x, y)].symbol()))
1317                .collect::<String>()
1318        };
1319        for view in [
1320            View::Search("test".into()),
1321            View::Album("album".into()),
1322            View::Playlist("list".into()),
1323            View::Discover,
1324            View::Station("station".into()),
1325            View::Radio("seed".into()),
1326            View::History,
1327            View::Songs { offset: 0 },
1328            View::Genre("Rock".into()),
1329        ] {
1330            app.view = view;
1331            app.current = Some(1);
1332            app.paused = false;
1333            let mut terminal = Terminal::new(TestBackend::new(140, 30)).unwrap();
1334            terminal.draw(|f| draw(f, &mut app)).unwrap();
1335            let text = main_text(&terminal);
1336            assert_eq!(text.matches("▶ PLAYING").count(), 1);
1337            assert!(text.contains("▶ Track 1"));
1338            app.current = Some(2);
1339            app.paused = true;
1340            terminal.draw(|f| draw(f, &mut app)).unwrap();
1341            let text = main_text(&terminal);
1342            assert_eq!(text.matches("Ⅱ PAUSED").count(), 1);
1343            assert!(text.contains("Ⅱ Track 2"));
1344            assert!(!text.contains("▶ Track 1"));
1345            app.current = None;
1346            terminal.draw(|f| draw(f, &mut app)).unwrap();
1347            let text = main_text(&terminal);
1348            assert!(!text.contains("▶ PLAYING"));
1349            assert!(!text.contains("Ⅱ PAUSED"));
1350        }
1351    }
1352    #[test]
1353    fn queue_duplicate_ids_mark_only_the_active_entry() {
1354        let mut app = App::for_tests();
1355        let song = crate::test_support::songs().remove(0);
1356        app.queue = vec![song.clone(), song.clone()];
1357        app.items = vec![Item::Song(song.clone()), Item::Song(song)];
1358        app.view = crate::model::View::Queue;
1359        app.current = Some(1);
1360        let mut terminal = Terminal::new(TestBackend::new(140, 30)).unwrap();
1361        terminal.draw(|f| draw(f, &mut app)).unwrap();
1362        let buffer = terminal.backend().buffer();
1363        let text = (3..23)
1364            .flat_map(|y| (23..112).map(move |x| buffer[(x, y)].symbol()))
1365            .collect::<String>();
1366        assert_eq!(text.matches("▶ PLAYING").count(), 1);
1367    }
1368    #[test]
1369    fn renders_small_and_large_terminals() {
1370        let mut app = App::for_tests();
1371        for (width, height) in [(20, 8), (45, 14), (100, 30), (160, 45)] {
1372            app.theme = app.theme.next();
1373            let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
1374            terminal.draw(|f| draw(f, &mut app)).unwrap();
1375            app.help = true;
1376            terminal.draw(|f| draw(f, &mut app)).unwrap();
1377            app.help = false;
1378        }
1379    }
1380}