tuitube 0.4.0

YouTube in your terminal: a vim-style client with local subscriptions, built on yt-dlp and mpv
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
//! Drawing: a top bar with the search box, the sidebar, the grid of video
//! cards, the player bar and the status line, laid out like YouTube's page.

mod grid;
mod list;
mod sidebar;

use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Margin, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Block, BorderType, Clear, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState,
};
use unicode_width::UnicodeWidthStr;

use crate::app::{App, Confirm, Focus, HelpMenu, HelpTab, JukeboxState, Playing, PromptKind, View};
use crate::icons::Icons;
use crate::settings::{self, Settings};
use crate::theme::{self, Colors};
use crate::ytdlp::AudioQuality;
use crate::{chapters, sponsorblock, video};

/// Below this width the sidebar and the grid take turns.
const NARROW: u16 = 70;

pub fn draw(frame: &mut Frame, app: &mut App) {
    app.images.placed.clear();
    let area = frame.area();
    let c = app.colors.clone();
    frame.render_widget(Block::new().style(Style::new().bg(c.bg).fg(c.text)), area);
    // The player's block: what's playing in its border, where it is inside.
    let player_rows = 3 * u16::from(app.playing.is_some() || app.resolving.is_some());
    let [body, player, status] = Layout::vertical([
        Constraint::Fill(1),
        Constraint::Length(player_rows),
        Constraint::Length(1),
    ])
    .areas(area);

    // The search box is in the videos' border, so they show while it's open.
    let narrow = body.width < NARROW;
    let side_width = if narrow {
        if app.focus == Focus::Sidebar && app.prompt.is_none() {
            body.width
        } else {
            0
        }
    } else {
        app.settings.sidebar_width().min(body.width / 2)
    };
    let [side, grid] =
        Layout::horizontal([Constraint::Length(side_width), Constraint::Fill(1)]).areas(body);
    if side.width > 0 {
        sidebar::draw(frame, app, side);
    }
    if grid.width > 0 {
        grid::draw(frame, app, grid);
    }
    if player_rows > 0 {
        player_bar(frame, app, player);
    }
    status_bar(frame, app, status);
    if app.help.is_some() {
        help(frame, app, area);
    }
    if app.chapter_menu.is_some() {
        chapter_menu(frame, app, area);
    }
    if app.command.is_some() {
        command_menu(frame, app, area, status);
    }
    if app.confirm.is_some() {
        confirm(frame, app, area);
    }
}

/// A video's mark while it plays from the Jukebox, in its color.
pub(super) fn jukebox_mark(
    state: JukeboxState,
    icons: &Icons,
    c: &Colors,
) -> (&'static str, &'static str, Style) {
    let red = Style::new().fg(c.red).add_modifier(Modifier::BOLD);
    match state {
        JukeboxState::Playing => (icons.play, "Playing", red),
        JukeboxState::Paused => (icons.pause, "Paused", red),
        JukeboxState::Loading => (icons.loading, "Loading", Style::new().fg(c.accent)),
    }
}

/// The question waiting for `y`, in a popup in the middle: what it does,
/// and the keys.
fn confirm(frame: &mut Frame, app: &App, area: Rect) {
    let c = &app.colors;
    let Some(confirm) = app.confirm else {
        return;
    };
    let (title, text, hint) = match confirm {
        Confirm::ClearJukebox => {
            let n = app.jukebox.len();
            let videos = if n == 1 { "video" } else { "videos" };
            (
                " Clear the Jukebox? ",
                format!("All {n} {videos} in it are taken off. This can't be undone."),
                " `y` clear · any other key keeps them ",
            )
        }
    };
    let hint_width = hint.replace('`', "").width();
    let width = (text.width().max(hint_width).max(title.width()) + 6).min(usize::from(area.width));
    let popup = Rect {
        x: area.x + area.width.saturating_sub(width as u16) / 2,
        y: area.y + area.height.saturating_sub(5) / 2,
        width: width as u16,
        height: 5.min(area.height),
    };
    frame.render_widget(Clear, popup);
    let block = bordered()
        .border_style(border(true, c))
        .title(Span::styled(
            title,
            Style::new().fg(c.text).add_modifier(Modifier::BOLD),
        ))
        .title_bottom(Line::from(hint_spans(hint, c)).right_aligned())
        .style(Style::new().bg(c.panel));
    let inner = block.inner(popup);
    frame.render_widget(block, popup);
    let line = Line::from(Span::styled(
        fit(&format!(" {text}"), usize::from(inner.width)),
        Style::new().fg(c.text),
    ));
    frame.render_widget(Paragraph::new(vec![Line::default(), line]), inner);
}

/// A box with a round border all round, as tuigram's panes.
fn bordered<'a>() -> Block<'a> {
    Block::bordered().border_type(BorderType::Rounded)
}

/// The border of what has the keys is in the accent color.
fn border(focused: bool, c: &Colors) -> Style {
    Style::new().fg(if focused { c.accent } else { c.border })
}

/// Key hints with the keys in backticks, like "`Enter` play · `a` listen",
/// as tuigram writes them: the keys stand out in the accent color, and
/// what they do is dim.
fn hint_spans(hints: &str, c: &Colors) -> Vec<Span<'static>> {
    let key = Style::new().fg(c.accent).add_modifier(Modifier::BOLD);
    let text = Style::new().fg(c.dim);
    hints
        .split('`')
        .enumerate()
        .filter(|(_, part)| !part.is_empty())
        .map(|(i, part)| Span::styled(part.to_string(), if i % 2 == 1 { key } else { text }))
        .collect()
}

/// As many of `hints` (separated by " · ") as fit in `width`, whole, as
/// `hint_spans`; cut with `…` if not even the first fits.
fn hints_fitting(hints: &str, width: usize, c: &Colors) -> Vec<Span<'static>> {
    let shown = |items: &[&str]| items.join(" · ").replace('`', "").width();
    let mut items: Vec<&str> = hints.split(" · ").collect();
    while items.len() > 1 && shown(&items) > width {
        items.pop();
    }
    if shown(&items) > width {
        let plain = items.join(" · ").replace('`', "");
        return vec![Span::styled(fit(&plain, width), Style::new().fg(c.dim))];
    }
    hint_spans(&items.join(" · "), c)
}

/// `text` cut to `width` columns, with `…` if it was longer.
pub fn fit(text: &str, width: usize) -> String {
    if text.width() <= width {
        return text.to_string();
    }
    if width == 0 {
        return String::new();
    }
    let mut out = String::new();
    let mut used = 0;
    for ch in text.chars() {
        let w = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
        if used + w > width - 1 {
            break;
        }
        used += w;
        out.push(ch);
    }
    out.push('…');
    out
}

/// The end of `text` that fits in `width` columns, found in one pass from
/// the end.
fn tail(text: &str, width: usize) -> &str {
    let mut used = 0;
    let mut start = text.len();
    for (i, ch) in text.char_indices().rev() {
        let w = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
        if used + w > width {
            break;
        }
        used += w;
        start = i;
    }
    &text[start..]
}

/// Narrower than this, the search box shows only its icon and a word.
const MIN_SEARCH: usize = 12;

/// The search box, as the title of the videos' block (`width` columns
/// wide, `right` of them taken by its title on the right): a field from
/// the thumbnails' left edge, with what's typed or a hint and `/` at its
/// end. `line` is the border's style, which leads into the field.
pub(super) fn search_box(app: &App, width: u16, right: u16, line: Style) -> Line<'static> {
    let c = &app.colors;
    let lead = "─ ";
    // The corners, the lead, a space after the field and one of border
    // before the title on the right.
    let taken = 2 + lead.width() + 1 + if right > 0 { usize::from(right) + 1 } else { 0 };
    let box_width = usize::from(width).saturating_sub(taken).min(70);
    let bg = if app.prompt.is_some() {
        c.selected
    } else {
        c.panel
    };
    let inner = box_width.saturating_sub(4);
    let mut spans = match &app.prompt {
        Some(prompt) => {
            let label = match prompt.kind {
                PromptKind::Search => "",
                PromptKind::Import => "subscriptions.csv: ",
            };
            // The end of what's typed stays in view.
            let room = inner.saturating_sub(label.width() + 1);
            let shown = tail(&prompt.text, room).to_string();
            vec![
                Span::styled(format!(" {} ", app.icons.search), Style::new().fg(c.accent)),
                Span::styled(label, Style::new().fg(c.dim)),
                Span::styled(shown, Style::new().fg(c.text)),
                Span::styled("▏", Style::new().fg(c.accent)),
            ]
        }
        None => vec![
            Span::styled(format!(" {} ", app.icons.search), Style::new().fg(c.dim)),
            Span::styled(
                fit("Search", inner.saturating_sub(4)),
                Style::new().fg(c.dim),
            ),
        ],
    };
    let hint = app.prompt.is_none() && box_width > MIN_SEARCH;
    let used: usize = spans.iter().map(Span::width).sum();
    let pad = box_width.saturating_sub(used + if hint { 3 } else { 0 });
    spans.push(Span::raw(" ".repeat(pad)));
    let mut spans: Vec<Span> = spans
        .into_iter()
        .map(|s| s.patch_style(Style::new().bg(bg)))
        .collect();
    if hint {
        spans.push(Span::styled(" / ", Style::new().fg(c.dim).bg(c.selected)));
    }
    spans.insert(0, Span::styled(lead, line));
    spans.push(Span::raw(" "));
    Line::from(spans)
}

/// What's playing, in a box: the title in its border (and on the right
/// what plays next, when there's room), and inside how far along it is and
/// the keys that control it.
fn player_bar(frame: &mut Frame, app: &App, area: Rect) {
    let c = &app.colors;
    let width = area.width.saturating_sub(2) as usize;
    let mut block = bordered().border_style(border(false, c));
    let row = if let Some(playing) = &app.playing {
        let (title, right) = title_row(app, playing, width);
        block = block.title(title).title(right.right_aligned());
        progress_row(app, playing, width)
    } else if let Some(resolving) = &app.resolving {
        Line::from(vec![
            Span::styled(
                format!(" {} ", app.icons.loading),
                Style::new().fg(c.accent),
            ),
            Span::styled(
                fit(
                    &format!("Loading “{}”…", resolving.video.title),
                    width.saturating_sub(4),
                ),
                Style::new().fg(c.subtext),
            ),
        ])
    } else {
        Line::default()
    };
    let inner = block.inner(area);
    frame.render_widget(block, area);
    frame.render_widget(Paragraph::new(row), inner);
}

/// "Next: …" shows only with this many columns to spare beside the title.
const MIN_NEXT: usize = 24;

/// For the player's border, `width` columns inside its corners: playing or
/// paused, sound only or not, the title and channel; and for its right, a
/// SponsorBlock skip just made, in yellow, or else what autoplay plays
/// next, if the title leaves room for it.
fn title_row(app: &App, playing: &Playing, width: usize) -> (Line<'static>, Line<'static>) {
    let c = &app.colors;
    let state = if playing.paused {
        app.icons.pause
    } else {
        app.icons.play
    };
    let state = format!(" {state} ");
    let sound = if playing.audio_only {
        format!("{} ", app.icons.sound)
    } else {
        String::new()
    };
    let title = &playing.video.title;
    let channel = if playing.video.channel.is_empty() {
        String::new()
    } else {
        format!("  ·  {}", playing.video.channel)
    };
    // A space after the channel, before the border goes on.
    let room = width.saturating_sub(state.width() + sound.width() + 1);
    let skip = playing.shown_skip().map_or(String::new(), |skip| {
        let seconds = if skip.seconds < 60.0 {
            format!("{:.0} s", skip.seconds)
        } else {
            video::duration(skip.seconds as u32)
        };
        let what = sponsorblock::shown(skip.category);
        fit(&format!(" [SKIP] {what} · {seconds} "), room)
    });
    let room = room.saturating_sub(skip.width());
    let spare = room.saturating_sub(title.width() + channel.width());
    // At least two columns of border between the title and "Next: …".
    let next = match app.plays_next() {
        Some(video) if skip.is_empty() && spare >= MIN_NEXT => {
            fit(&format!(" Next: {} ", video.title), spare - 2)
        }
        _ => String::new(),
    };
    let room = room.saturating_sub(next.width());
    let title = fit(title, room);
    let channel = fit(&channel, room.saturating_sub(title.width()));
    let left = Line::from(vec![
        Span::styled(state, Style::new().fg(c.red).add_modifier(Modifier::BOLD)),
        Span::styled(sound, Style::new().fg(c.text)),
        Span::styled(title, Style::new().fg(c.text).add_modifier(Modifier::BOLD)),
        Span::styled(channel, Style::new().fg(c.subtext)),
        Span::raw(" "),
    ]);
    let right = Line::from(vec![
        Span::styled(next, Style::new().fg(c.dim)),
        Span::styled(
            skip,
            Style::new().fg(c.warning).add_modifier(Modifier::BOLD),
        ),
    ]);
    (left, right)
}

/// The bar is at least this wide beside the chapter's title, or the title
/// isn't shown.
const MIN_BAR: usize = 20;
/// The most columns the chapter's title takes in the player bar.
const MAX_CHAPTER_SHOWN: usize = 32;

/// Where it is and the chapter it's in, a bar across with a dot where it
/// is, its length and quality, then the keys, each after its icon and in
/// the accent color, as in the status bar (autoplay's icon lit while it's
/// on). The keys and the quality go first when the window is too narrow
/// for a useful bar, then the chapter.
fn progress_row(app: &App, playing: &Playing, width: usize) -> Line<'static> {
    let c = &app.colors;
    let icons = &app.icons;
    let controllable = playing.controllable();
    // Under the state icon in the border above.
    let at = if controllable || playing.duration.is_some() {
        format!(" {} ", video::duration(playing.position as u32))
    } else {
        " ".into()
    };
    let length = playing
        .duration
        .map_or(String::new(), |l| format!(" {}", video::duration(l as u32)));

    let dim = Style::new().fg(c.dim);
    let mut keys: Vec<(&str, &str, Style)> = Vec::new();
    if controllable {
        let toggle = if playing.paused {
            icons.play
        } else {
            icons.pause
        };
        keys.push((icons.back, ",", dim));
        keys.push((toggle, "Space", dim));
        keys.push((icons.ahead, ".", dim));
        keys.push((icons.chapters, "t", dim));
    }
    if app.next_video().is_some() {
        keys.push((icons.next, "N", dim));
    }
    keys.push((icons.stop, "X", dim));
    let autoplay = if app.settings.autoplay {
        Style::new().fg(c.accent)
    } else {
        dim
    };
    keys.push((icons.autoplay, "A", autoplay));
    let key = Style::new().fg(c.accent).add_modifier(Modifier::BOLD);
    let mut key_spans = vec![Span::raw(" ")];
    if let Some(quality) = &playing.quality {
        key_spans.push(Span::styled(format!(" {quality}"), dim));
    }
    for (icon, name, style) in keys {
        key_spans.push(Span::raw("  "));
        key_spans.push(Span::styled(format!("{icon} "), style));
        key_spans.push(Span::styled(name, key));
    }
    key_spans.push(Span::raw(" "));
    let keys_width: usize = key_spans.iter().map(Span::width).sum();

    let mut bar = width.saturating_sub(at.width() + length.width() + keys_width);
    if bar < 10 {
        key_spans.clear();
        bar = width.saturating_sub(at.width() + length.width() + 1);
    }
    let chapter = chapters::current(&playing.chapters, playing.position)
        .map(|i| playing.chapters[i].title.as_str())
        .filter(|title| !title.is_empty());
    let room = MAX_CHAPTER_SHOWN.min(bar.saturating_sub(MIN_BAR));
    let chapter = match chapter {
        Some(title) if room >= 8 => format!("· {} ", fit(title, room - 3)),
        _ => String::new(),
    };
    bar -= chapter.width();
    let mut spans = vec![
        Span::styled(at, Style::new().fg(c.subtext)),
        Span::styled(chapter, Style::new().fg(c.text)),
    ];
    match playing.duration.filter(|l| *l > 0.0) {
        Some(l) if bar > 0 => {
            let ratio = (playing.position / l).clamp(0.0, 1.0);
            let done = (ratio * (bar - 1) as f64).round() as usize;
            spans.push(Span::styled("━".repeat(done), Style::new().fg(c.red)));
            spans.push(Span::styled("●", Style::new().fg(c.red)));
            spans.push(Span::styled(
                "─".repeat(bar - 1 - done),
                Style::new().fg(c.border),
            ));
        }
        // A live stream: no length to measure against.
        _ => spans.push(Span::styled("─".repeat(bar), Style::new().fg(c.border))),
    }
    spans.push(Span::styled(length, Style::new().fg(c.subtext)));
    spans.extend(key_spans);
    Line::from(spans)
}

/// The command line, as vim's: `:` and what's typed, then why it didn't
/// run, or its keys, on the right.
fn command_line(frame: &mut Frame, app: &App, area: Rect) {
    let c = &app.colors;
    let Some(line) = &app.command else {
        return;
    };
    let width = usize::from(area.width);
    let right = match &line.error {
        Some(error) => vec![Span::styled(
            fit(&format!(" {error} "), width / 2),
            Style::new().fg(c.red),
        )],
        None => hints_fitting(" `Tab` complete · `Enter` run · `Esc` close ", width / 2, c),
    };
    let right_width: usize = right.iter().map(Span::width).sum();
    let room = width.saturating_sub(right_width + 2);
    let typed = tail(&line.text, room);
    let used = 2 + typed.width();
    let mut spans = vec![
        Span::styled(":", Style::new().fg(c.accent).add_modifier(Modifier::BOLD)),
        Span::styled(typed.to_string(), Style::new().fg(c.text)),
        Span::styled("▏", Style::new().fg(c.accent)),
        Span::raw(" ".repeat(width.saturating_sub(used + right_width))),
    ];
    spans.extend(right);
    frame.render_widget(
        Paragraph::new(Line::from(spans)).style(Style::new().bg(c.bg)),
        area,
    );
}

/// Completions shown at once, at most; the rest scroll.
const MAX_COMPLETIONS: usize = 12;
/// The most columns a completion's name, and what it does, take.
const MAX_NAME_SHOWN: usize = 36;
const MAX_ABOUT_SHOWN: usize = 64;

/// The command line's completions, in a box over it, lined up under the
/// word they complete: each command (with its argument) or value, what it
/// does and its key. The one Enter takes is lit, the value in use marked,
/// and a command that can't run now dimmed.
fn command_menu(frame: &mut Frame, app: &mut App, area: Rect, status: Rect) {
    let c = app.colors.clone();
    let Some(line) = app.command.as_mut() else {
        return;
    };
    let list = &line.completion.candidates;
    let room = usize::from(status.y.saturating_sub(area.y)).saturating_sub(2);
    let rows = list.len().min(MAX_COMPLETIONS).min(room);
    if rows == 0 {
        return;
    }
    let names: Vec<String> = list
        .iter()
        .map(|k| {
            if k.hint.is_empty() {
                k.text.clone()
            } else {
                format!("{} {}", k.text, k.hint)
            }
        })
        .collect();
    let widest = |widths: &mut dyn Iterator<Item = usize>| widths.max().unwrap_or(0);
    let name_width = widest(&mut names.iter().map(|n| n.width())).min(MAX_NAME_SHOWN);
    let about_width = widest(&mut list.iter().map(|k| k.about.width())).min(MAX_ABOUT_SHOWN);
    let key_width = widest(&mut list.iter().map(|k| k.key.width()));
    let key_room = if key_width > 0 { key_width + 2 } else { 0 };
    let title = fit(&format!(" {} ", line.completion.title), MAX_ABOUT_SHOWN);
    // The border, a bar, the mark, the name, two spaces, what it does,
    // the key, a space and the border.
    let width = (name_width + about_width + key_room + 8)
        .max(title.width() + 4)
        .min(usize::from(area.width)) as u16;
    let height = rows as u16 + 2;
    // The names start four columns in: under the word, after the `:`.
    let word = 1 + line.source()[..line.completion.from].width() as u16;
    let x = (status.x + word)
        .saturating_sub(4)
        .min(area.right().saturating_sub(width))
        .max(area.x);
    let popup = Rect {
        x,
        y: status.y - height,
        width,
        height,
    };
    let lit = line.selected.unwrap_or(0);
    line.scroll = line.scroll.min(lit);
    if lit >= line.scroll + rows {
        line.scroll = lit + 1 - rows;
    }
    frame.render_widget(Clear, popup);
    let block = bordered()
        .border_style(border(true, &c))
        .title(Span::styled(
            title,
            Style::new().fg(c.text).add_modifier(Modifier::BOLD),
        ))
        .style(Style::new().bg(c.panel));
    let inner = block.inner(popup);
    frame.render_widget(block, popup);
    let inner_width = usize::from(inner.width);
    let name_room = name_width.min(inner_width.saturating_sub(3));
    let about_room = inner_width.saturating_sub(3 + name_room + 2 + key_room + 1);
    let lines: Vec<Line> = list
        .iter()
        .zip(&names)
        .enumerate()
        .skip(line.scroll)
        .take(rows)
        .map(|(i, (k, name))| {
            let chosen = i == lit;
            let bar = if chosen {
                Span::styled("▌", Style::new().fg(c.accent))
            } else {
                Span::raw(" ")
            };
            let mark = if k.current {
                Span::styled("● ", Style::new().fg(c.accent))
            } else {
                Span::raw("  ")
            };
            let name_color = if k.ready { c.text } else { c.dim };
            let name = fit(name, name_room);
            let pad = name_room.saturating_sub(name.width()) + 2;
            let about = fit(&k.about, about_room);
            let gap = about_room.saturating_sub(about.width());
            let mut spans = vec![
                bar,
                mark,
                Span::styled(
                    name,
                    Style::new().fg(name_color).add_modifier(Modifier::BOLD),
                ),
                Span::raw(" ".repeat(pad)),
                Span::styled(about, Style::new().fg(c.subtext)),
            ];
            if key_room > 0 && inner_width >= 3 + name_room + 2 + key_room {
                spans.push(Span::raw(" ".repeat(gap + 2)));
                spans.push(Span::styled(
                    format!("{:>key_width$}", k.key),
                    Style::new().fg(c.accent),
                ));
            }
            let row = Line::from(spans);
            if chosen {
                row.style(Style::new().bg(c.selected))
            } else {
                row
            }
        })
        .collect();
    frame.render_widget(Paragraph::new(lines), inner);
    let hidden = list.len().saturating_sub(rows);
    if hidden > 0 {
        let mut state = ScrollbarState::new(hidden).position(line.scroll);
        frame.render_stateful_widget(
            Scrollbar::new(ScrollbarOrientation::VerticalRight)
                .begin_symbol(None)
                .end_symbol(None)
                .style(Style::new().fg(c.dim)),
            popup.inner(Margin::new(0, 1)),
            &mut state,
        );
    }
}

/// A message, or the keys for where you are; your subscription count on
/// the right. The command line takes its place while it's open.
fn status_bar(frame: &mut Frame, app: &App, area: Rect) {
    if app.command.is_some() {
        return command_line(frame, app, area);
    }
    let c = &app.colors;
    let width = area.width as usize;
    let right = format!(" {} subscriptions ", app.subscriptions.len());
    let room = width.saturating_sub(right.width());
    let left = match (&app.status, &app.prompt) {
        (_, Some(prompt)) => {
            let keys = match prompt.kind {
                PromptKind::Search => " `Enter` search · `Esc` cancel · `Ctrl-u` clear",
                PromptKind::Import => {
                    " Paste or drop the path to subscriptions.csv from Google Takeout · `Enter` import · `Esc` cancel"
                }
            };
            hints_fitting(keys, room, c)
        }
        (Some(status), None) => {
            let color = if status.error { c.red } else { c.ok };
            vec![Span::styled(
                fit(&format!(" {}", status.text), room),
                Style::new().fg(color),
            )]
        }
        (None, None) => {
            let keys = match app.focus {
                Focus::Grid if app.view == View::Jukebox => {
                    " `Enter` play · `:` commands · `a` listen · `J` `K` move · `E` next · `x` remove · `C` clear · `v` list or cards · `?` help"
                }
                Focus::Grid => {
                    " `Enter` play · `:` commands · `a` listen · `e` jukebox · `m` mix · `w` watch later · `c` channel · `S` subscribe · `/` search · `?` help"
                }
                Focus::Sidebar => {
                    " `↑↓` move · `Enter` open · `:` commands · `Tab` videos · `/` search · `I` import · `?` help"
                }
            };
            hints_fitting(keys, room, c)
        }
    };
    let used: usize = left.iter().map(Span::width).sum();
    let mut spans = left;
    spans.push(Span::raw(" ".repeat(room.saturating_sub(used))));
    spans.push(Span::styled(right, Style::new().fg(c.dim)));
    let line = Line::from(spans);
    frame.render_widget(Paragraph::new(line).style(Style::new().bg(c.bg)), area);
}

const HELP: [(&str, &str); 26] = [
    ("←↓↑→  h j k l", "move"),
    ("gg  G  Home  End", "first, last"),
    ("PgUp PgDn  Ctrl-u Ctrl-d", "a page, half a page"),
    ("Tab", "sidebar ↔ videos"),
    ("Enter", "play"),
    ("a", "listen (sound only)"),
    ("m", "YouTube's Mix of the video (music only)"),
    (
        "e  /  E",
        "into the Jukebox: last  /  next, after the one playing",
    ),
    (
        "J  K  /  v  /  C",
        "in the Jukebox: move  /  list or cards  /  clear it",
    ),
    ("N  /  A", "next video  /  autoplay on or off"),
    ("w", "watch later (again to remove)"),
    ("x", "remove from the Jukebox, Watch later or History"),
    ("c", "the video's channel"),
    ("S  /  u", "subscribe or unsubscribe  /  undo"),
    ("/  s", "search YouTube"),
    ("Backspace  Ctrl-o", "back"),
    ("o  /  y", "open in the browser  /  copy the link"),
    ("R", "refresh"),
    ("I", "import subscriptions from Google Takeout"),
    ("Space", "pause or play"),
    (",  .  /  <  >", "back or ahead 10 s  /  1 min;  X stops"),
    ("t", "chapters, or go to a time: 1:23, +30, 50%"),
    ("[  ]", "the chapter before  /  the next chapter"),
    (
        ":",
        "commands: any action or setting by name, Tab completes (:quality 720)",
    ),
    (
        "?  /  O",
        "these keys  /  settings: quality, theme, Shorts…",
    ),
    ("q", "quit"),
];

/// The `?` popup, centered: a tab with every key, and one with the
/// settings. Both are as big as the bigger one, so the tabs don't move.
fn help(frame: &mut Frame, app: &mut App, area: Rect) {
    let c = app.colors.clone();
    let Some(menu) = app.help.as_mut() else {
        return;
    };
    let keys = key_lines(&c);
    let (settings, cursor) = settings_lines(&app.settings, menu.selected, &c);
    let widest = |lines: &[Line]| lines.iter().map(Line::width).max().unwrap_or(0);
    let width = (widest(&keys).max(widest(&settings)) + 3).min(area.width as usize) as u16;
    let height = (keys.len().max(settings.len()) as u16 + 2).min(area.height);
    let popup = Rect {
        x: area.x + area.width.saturating_sub(width) / 2,
        y: area.y + area.height.saturating_sub(height) / 2,
        width,
        height,
    };
    let tab = |label: &'static str, active: bool| {
        if active {
            Span::styled(
                label,
                Style::new()
                    .fg(c.bg)
                    .bg(c.accent)
                    .add_modifier(Modifier::BOLD),
            )
        } else {
            Span::styled(label, Style::new().fg(c.dim))
        }
    };
    let tabs = Line::from(vec![
        Span::raw(" "),
        tab(" Keys ", menu.tab == HelpTab::Keys),
        Span::raw(" "),
        tab(" Settings ", menu.tab == HelpTab::Settings),
        Span::raw(" "),
    ]);
    let hint = match menu.tab {
        HelpTab::Keys => " `j k` scroll · `Tab` settings · `Esc` close ",
        HelpTab::Settings if HelpMenu::is_choice(menu.selected) => {
            " `Enter` use · `Tab` keys · `Esc` close "
        }
        HelpTab::Settings => " `Enter` on/off · `Tab` keys · `Esc` close ",
    };
    frame.render_widget(Clear, popup);
    let block = bordered()
        .border_style(border(true, &c))
        .title(tabs)
        .title_bottom(Line::from(hint_spans(hint, &c)).right_aligned())
        .style(Style::new().bg(c.panel));
    let inner = block.inner(popup);
    frame.render_widget(block, popup);

    let rows = usize::from(inner.height);
    let (lines, scroll) = match menu.tab {
        HelpTab::Keys => (keys, &mut menu.scroll),
        HelpTab::Settings => {
            // Scrolled as little as keeps the cursor in view, with the line
            // above it: the heading, for the first row of a group. On the
            // last theme, the end shows.
            let scroll = &mut menu.settings_scroll;
            *scroll = (*scroll).min(cursor.saturating_sub(1));
            let cursor_end = if menu.selected == HelpMenu::LAST {
                settings.len() - 1
            } else {
                cursor
            };
            if cursor_end >= *scroll + rows {
                *scroll = cursor_end + 1 - rows;
            }
            (settings, scroll)
        }
    };
    let max = lines.len().saturating_sub(rows);
    *scroll = (*scroll).min(max);
    frame.render_widget(Paragraph::new(lines).scroll((*scroll as u16, 0)), inner);
    if max > 0 {
        let mut state = ScrollbarState::new(max).position(*scroll);
        frame.render_stateful_widget(
            Scrollbar::new(ScrollbarOrientation::VerticalRight)
                .begin_symbol(None)
                .end_symbol(None)
                .style(Style::new().fg(c.dim)),
            popup.inner(Margin::new(0, 1)),
            &mut state,
        );
    }
}

/// The chapters popup (`t`), centered: where a typed time goes, then the
/// chapters, each at its start, the one playing marked and the one under
/// the cursor lit.
fn chapter_menu(frame: &mut Frame, app: &mut App, area: Rect) {
    let c = app.colors.clone();
    let icons = app.icons;
    let (Some(menu), Some(playing)) = (app.chapter_menu.as_mut(), app.playing.as_ref()) else {
        return;
    };
    let list = &playing.chapters;
    let playing_now = chapters::current(list, playing.position);
    let times: Vec<String> = list
        .iter()
        .map(|ch| video::duration(ch.start as u32))
        .collect();
    let time_width = times.iter().map(|t| t.width()).max().unwrap_or(0);
    let widest = list.iter().map(|ch| ch.title.width()).max().unwrap_or(0);
    // A bar, the mark, the time, two spaces, the title, a space.
    let width = (widest + time_width + 7).clamp(48, 80) + 2;
    let width = width.min(usize::from(area.width)) as u16;
    let height = (list.len().max(1) as u16 + 4).min(area.height.saturating_sub(2).max(5));
    let height = height.min(area.height);
    let popup = Rect {
        x: area.x + area.width.saturating_sub(width) / 2,
        y: area.y + area.height.saturating_sub(height) / 2,
        width,
        height,
    };
    let title = if list.is_empty() {
        " Go to a time ".to_string()
    } else {
        format!(" Chapters · {} ", list.len())
    };
    let hint = if list.is_empty() {
        " `Enter` go · `Esc` close "
    } else if menu.typed.is_empty() {
        " `Enter` go · `j k` choose · `Esc` close "
    } else {
        " `Enter` go to the time · `Esc` close "
    };
    frame.render_widget(Clear, popup);
    let block = bordered()
        .border_style(border(true, &c))
        .title(Span::styled(
            title,
            Style::new().fg(c.text).add_modifier(Modifier::BOLD),
        ))
        .title_bottom(Line::from(hint_spans(hint, &c)).right_aligned())
        .style(Style::new().bg(c.panel));
    let inner = block.inner(popup);
    frame.render_widget(block, popup);
    let inner_width = usize::from(inner.width);

    let mut lines = Vec::new();
    let mut typed = vec![
        Span::styled(" Go to ", Style::new().fg(c.dim)),
        Span::styled(
            menu.typed.clone(),
            Style::new().fg(c.text).add_modifier(Modifier::BOLD),
        ),
        Span::styled("▏", Style::new().fg(c.accent)),
    ];
    if menu.typed.is_empty() {
        typed.push(Span::styled(
            "type a time: 1:23 · 90 · +30 · 50%",
            Style::new().fg(c.dim),
        ));
    }
    lines.push(Line::from(typed));
    lines.push(Line::default());
    let rows = usize::from(inner.height).saturating_sub(lines.len());
    if list.is_empty() {
        lines.push(Line::from(Span::styled(
            " This video has no chapters",
            Style::new().fg(c.dim),
        )));
    } else {
        // Scrolled as little as keeps the cursor in view.
        menu.selected = menu.selected.min(list.len() - 1);
        menu.scroll = menu.scroll.min(menu.selected);
        if rows > 0 && menu.selected >= menu.scroll + rows {
            menu.scroll = menu.selected + 1 - rows;
        }
        let end = (menu.scroll + rows).min(list.len());
        for i in menu.scroll..end {
            let chosen = i == menu.selected;
            let bar = if chosen {
                Span::styled("▌", Style::new().fg(c.accent))
            } else {
                Span::raw(" ")
            };
            let mark = if playing_now == Some(i) {
                Span::styled(
                    format!("{} ", icons.play),
                    Style::new().fg(c.red).add_modifier(Modifier::BOLD),
                )
            } else {
                Span::raw("  ")
            };
            let time = format!("{:>time_width$}  ", times[i]);
            let room = inner_width.saturating_sub(3 + time.width() + 1);
            let line = Line::from(vec![
                bar,
                mark,
                Span::styled(time, Style::new().fg(c.accent)),
                Span::styled(fit(&list[i].title, room), Style::new().fg(c.text)),
            ]);
            lines.push(if chosen {
                line.style(Style::new().bg(c.selected))
            } else {
                line
            });
        }
        let hidden = list.len().saturating_sub(rows);
        if hidden > 0 && rows > 0 {
            let mut state = ScrollbarState::new(hidden).position(menu.scroll);
            frame.render_stateful_widget(
                Scrollbar::new(ScrollbarOrientation::VerticalRight)
                    .begin_symbol(None)
                    .end_symbol(None)
                    .style(Style::new().fg(c.dim)),
                // Beside the chapters, on the right border.
                Rect {
                    y: inner.y + 2,
                    height: inner.height.saturating_sub(2),
                    ..popup
                },
                &mut state,
            );
        }
    }
    frame.render_widget(Paragraph::new(lines), inner);
}

/// The keys tab: every key, and what it does.
fn key_lines(c: &Colors) -> Vec<Line<'static>> {
    let key_width = HELP.iter().map(|(k, _)| k.width()).max().unwrap_or(0);
    HELP.iter()
        .map(|(key, what)| {
            Line::from(vec![
                Span::styled(format!(" {key:<key_width$}  "), Style::new().fg(c.accent)),
                Span::styled(*what, Style::new().fg(c.text)),
            ])
        })
        .collect()
}

/// The settings tab, and the line of the row `selected`.
fn settings_lines(settings: &Settings, selected: usize, c: &Colors) -> (Vec<Line<'static>>, usize) {
    let mut lines = Vec::new();
    let mut cursor = 0;
    let mut add = |lines: &mut Vec<Line<'static>>, row: usize, mark: &'static str, label: &str| {
        let chosen = row == selected;
        let bar = if chosen {
            Span::styled("▌", Style::new().fg(c.accent))
        } else {
            Span::raw(" ")
        };
        let line = Line::from(vec![
            bar,
            Span::styled(mark, Style::new().fg(c.accent)),
            Span::styled(label.to_string(), Style::new().fg(c.text)),
        ]);
        if chosen {
            cursor = lines.len();
            lines.push(line.style(Style::new().bg(c.selected)));
        } else {
            lines.push(line);
        }
    };
    let heading = |text: &'static str| {
        Line::from(Span::styled(
            text,
            Style::new().fg(c.dim).add_modifier(Modifier::BOLD),
        ))
    };
    let check = |on: bool| if on { " [✓] " } else { " [ ] " };

    lines.push(heading(" Videos"));
    add(
        &mut lines,
        HelpMenu::SHORTS,
        check(settings.shorts),
        "Show Shorts",
    );
    add(
        &mut lines,
        HelpMenu::LIVE,
        check(settings.live),
        "Show live streams and premieres",
    );
    add(
        &mut lines,
        HelpMenu::DESCRIPTIONS,
        check(settings.descriptions),
        "Show the start of each description",
    );
    lines.push(Line::default());
    lines.push(heading(" Playing"));
    add(
        &mut lines,
        HelpMenu::AUTOPLAY,
        check(settings.autoplay),
        "Autoplay: the next video when one ends (the Jukebox always)",
    );
    add(
        &mut lines,
        HelpMenu::SPONSORBLOCK,
        check(settings.sponsorblock),
        "Skip sponsors with SponsorBlock (asks sponsor.ajay.app)",
    );
    lines.push(Line::default());
    // The dot marks the one in use, as for the themes.
    let dot = |on: bool| if on { " ● " } else { " ○ " };
    lines.push(heading(" Video quality"));
    for (i, &height) in settings::HEIGHTS.iter().enumerate() {
        let on = settings.height_choice() == Some(i);
        let label = settings::height_label(height);
        add(&mut lines, HelpMenu::VIDEO_QUALITY + i, dot(on), &label);
    }
    lines.push(Line::default());
    lines.push(heading(" Sound quality"));
    for (i, quality) in AudioQuality::ALL.iter().enumerate() {
        let label = match quality {
            AudioQuality::High => "High: about 130 kbps, the best without an account",
            AudioQuality::Low => "Low: about 70 kbps, to save data",
        };
        let on = settings.audio_quality == *quality;
        add(&mut lines, HelpMenu::AUDIO_QUALITY + i, dot(on), label);
    }
    lines.push(Line::default());
    lines.push(heading(" Jukebox"));
    add(
        &mut lines,
        HelpMenu::JUKEBOX_LIST,
        check(settings.jukebox_list),
        "Show it as a list, without thumbnails",
    );
    add(
        &mut lines,
        HelpMenu::JUKEBOX_AUTOREMOVE,
        check(settings.jukebox_autoremove),
        "Take a video off once it has played to its end",
    );
    lines.push(Line::default());
    lines.push(heading(" Privacy"));
    add(
        &mut lines,
        HelpMenu::HISTORY,
        check(settings.history),
        "Keep a history of what you watch, here only",
    );
    lines.push(Line::default());
    lines.push(heading(" Theme"));
    for (i, (id, name)) in theme::names().iter().enumerate() {
        add(
            &mut lines,
            HelpMenu::THEMES + i,
            dot(*id == settings.theme),
            name,
        );
    }
    (lines, cursor)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::Prompt;
    use crate::app::tests::{app, mpv_control, sponsor_at, with_feed};
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    fn drawn(app: &mut App, width: u16, height: u16) -> ratatui::buffer::Buffer {
        let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
        terminal.draw(|f| draw(f, app)).unwrap();
        terminal.backend().buffer().clone()
    }

    fn screen(app: &mut App, width: u16, height: u16) -> String {
        let buffer = drawn(app, width, height);
        let mut out = String::new();
        for y in 0..buffer.area.height {
            for x in 0..buffer.area.width {
                out.push_str(buffer[(x, y)].symbol());
            }
            out.push('\n');
        }
        out
    }

    #[test]
    fn the_prompt_shows_the_end_of_what_was_typed() {
        assert_eq!(tail("hello world", 5), "world");
        assert_eq!(tail("日本語テキスト", 5), "スト", "two columns each");
        assert_eq!(tail("abc", 10), "abc");
        assert_eq!(tail("abc", 0), "");
    }

    #[test]
    fn text_is_cut_to_fit_with_an_ellipsis() {
        assert_eq!(fit("hello", 10), "hello");
        assert_eq!(fit("hello world", 6), "hello…");
        assert_eq!(fit("日本語テキスト", 5), "日本…");
        assert_eq!(fit("abc", 0), "");
    }

    #[tokio::test]
    async fn an_empty_home_explains_how_to_import_subscriptions() {
        let mut app = app();
        app.status = None;
        let shown = screen(&mut app, 120, 40);
        assert!(shown.contains("tuitube"));
        assert!(shown.contains("Google Takeout"), "{shown}");
        assert!(shown.contains("Home"));
        assert!(shown.contains("Watch later"));
    }

    #[tokio::test]
    async fn the_feed_shows_as_a_grid_of_cards() {
        let mut app = app();
        app.status = None;
        with_feed(&mut app, 8);
        let shown = screen(&mut app, 140, 45);
        assert!(shown.contains("Video vid00000007"), "{shown}");
        assert!(shown.contains("BekBrace"));
        let shape = app.grid.get();
        assert!(shape.cols >= 2, "{shape:?}");
        // The selected card has a ring.
        assert!(shown.contains('╭'));
    }

    #[tokio::test]
    async fn the_next_row_shows_cut_off_at_any_window_height() {
        let mut app = app();
        with_feed(&mut app, 20);
        for height in 8..70 {
            let shown = screen(&mut app, 140, height);
            assert!(shown.contains("tuitube"), "{height}");
        }
        // 45 rows hold two rows of cards and the top of a third, whose
        // titles are cut off.
        let shown = screen(&mut app, 140, 45);
        assert_eq!(app.grid.get().rows, 2);
        assert!(shown.contains("Video vid00000014"), "the second row");
        assert!(
            !shown.contains("Video vid00000013"),
            "the third row's text is cut off"
        );
    }

    #[tokio::test]
    async fn the_header_and_search_box_line_up_with_the_thumbnails() {
        let mut app = app();
        with_feed(&mut app, 6);
        let buffer = drawn(&mut app, 140, 45);
        let side = app.settings.sidebar_width();
        // The videos' box starts where the sidebar's ends; its border, a
        // column in, then the cards.
        assert_eq!(buffer[(side, 0)].symbol(), "╭");
        let content = side + 3;
        // The first card is selected: its ring is a column left of its
        // thumbnail.
        assert_eq!(buffer[(content - 1, 2)].symbol(), "╭");
        assert_eq!(buffer[(content, 1)].symbol(), "H", "the header's Home");
        assert_eq!(buffer[(content - 1, 1)].symbol(), " ");
        // The search box's background starts there too, in the border.
        assert_eq!(buffer[(content, 0)].bg, app.colors.panel);
        assert_ne!(buffer[(content - 1, 0)].bg, app.colors.panel);
        assert_eq!(buffer[(side + 1, 0)].symbol(), "─");
    }

    #[tokio::test]
    async fn the_sidebar_and_the_videos_are_boxes_lit_where_the_keys_go() {
        let mut app = app();
        app.status = None;
        with_feed(&mut app, 6);
        let shown = screen(&mut app, 140, 45);
        let lines: Vec<&str> = shown.lines().collect();
        assert!(lines[0].starts_with("╭  ▶  tuitube ─"), "{shown}");
        assert!(lines[1].starts_with("│"), "Home under the logo: {shown}");
        assert!(lines[1].contains("Home"));
        let rule = lines
            .iter()
            .find(|l| l.contains("Subscriptions ("))
            .expect(&shown);
        let side = app.settings.sidebar_width() as usize;
        let rule: String = rule.chars().take(side).collect();
        let heading = format!("├─ Subscriptions ({}) ─", app.subscriptions.len());
        assert!(rule.starts_with(&heading), "{rule}");
        assert!(rule.ends_with("─┤"), "{rule}");

        let side = side as u16;
        let buffer = drawn(&mut app, 140, 45);
        assert_eq!(app.focus, Focus::Grid);
        assert_eq!(buffer[(side, 10)].fg, app.colors.accent, "the videos'");
        assert_eq!(buffer[(0, 10)].fg, app.colors.border);
        app.focus = Focus::Sidebar;
        let buffer = drawn(&mut app, 140, 45);
        assert_eq!(buffer[(side, 10)].fg, app.colors.border);
        assert_eq!(buffer[(0, 10)].fg, app.colors.accent, "the sidebar's");
        // Typing in the search box, in the videos' border, lights it.
        app.prompt = Some(Prompt {
            kind: PromptKind::Search,
            text: "rust".into(),
        });
        let buffer = drawn(&mut app, 140, 45);
        assert_eq!(buffer[(side, 10)].fg, app.colors.accent);
        assert_eq!(buffer[(0, 10)].fg, app.colors.border);
        assert!(
            screen(&mut app, 140, 45)
                .lines()
                .next()
                .unwrap()
                .contains("rust▏")
        );
    }

    #[tokio::test]
    async fn a_narrow_window_shows_the_search_box_while_it_is_open() {
        let mut app = app();
        with_feed(&mut app, 3);
        app.focus = Focus::Sidebar;
        assert!(screen(&mut app, 50, 30).contains("Watch later"));
        app.prompt = Some(Prompt {
            kind: PromptKind::Search,
            text: "lofi".into(),
        });
        let shown = screen(&mut app, 50, 30);
        assert!(!shown.contains("Watch later"), "the videos have the window");
        assert!(shown.contains("lofi▏"), "{shown}");
    }

    #[test]
    fn key_hints_show_their_keys_in_the_accent_color_and_fit_whole() {
        let c = Colors::named(theme::DEFAULT);
        let spans = hint_spans(" `Enter` play · `a` listen", &c);
        let texts: Vec<&str> = spans.iter().map(|s| s.content.as_ref()).collect();
        assert_eq!(texts, [" ", "Enter", " play · ", "a", " listen"]);
        assert_eq!(spans[1].style.fg, Some(c.accent));
        assert!(spans[1].style.add_modifier.contains(Modifier::BOLD));
        assert_eq!(spans[2].style.fg, Some(c.dim));

        let hints = " `Enter` play · `a` listen · `m` mix";
        let text = |spans: Vec<Span>| {
            spans
                .iter()
                .map(|s| s.content.to_string())
                .collect::<String>()
        };
        assert_eq!(
            text(hints_fitting(hints, 40, &c)),
            " Enter play · a listen · m mix"
        );
        assert_eq!(text(hints_fitting(hints, 22, &c)), " Enter play · a listen");
        assert_eq!(text(hints_fitting(hints, 21, &c)), " Enter play");
        assert_eq!(text(hints_fitting(hints, 6, &c)), " Ente…");
    }

    #[tokio::test]
    async fn the_status_bar_shows_its_keys_in_the_accent_color() {
        let mut app = app();
        app.status = None;
        with_feed(&mut app, 3);
        let buffer = drawn(&mut app, 140, 40);
        let shown = screen(&mut app, 140, 40);
        let status = shown.lines().last().unwrap();
        assert!(status.starts_with(" Enter play · : commands"), "{status}");
        let enter = buffer[(1, 39)].clone();
        assert_eq!(enter.fg, app.colors.accent);
        assert!(enter.modifier.contains(Modifier::BOLD));
        assert_eq!(buffer[(7, 39)].fg, app.colors.dim, "play");
    }

    #[tokio::test]
    async fn a_narrow_window_shows_the_sidebar_or_the_grid() {
        let mut app = app();
        with_feed(&mut app, 3);
        let shown = screen(&mut app, 50, 30);
        assert!(!shown.contains("Watch later"), "the grid has the window");
        app.focus = Focus::Sidebar;
        let shown = screen(&mut app, 50, 30);
        assert!(shown.contains("Watch later"));
    }

    #[tokio::test]
    async fn the_help_lists_the_keys_then_the_settings() {
        let mut app = app();
        app.help = Some(HelpMenu::new(HelpTab::Keys));
        let shown = screen(&mut app, 120, 40);
        assert!(shown.contains("listen (sound only)"));
        assert!(shown.contains("autoplay on or off"));
        assert!(shown.contains(" Keys ") && shown.contains(" Settings "));
        assert!(!shown.contains("Show Shorts"));

        app.help = Some(HelpMenu::new(HelpTab::Settings));
        app.settings.sponsorblock = true;
        app.settings.live = false;
        let shown = screen(&mut app, 120, 40);
        assert!(!shown.contains("listen (sound only)"));
        let line = |text: &str| {
            shown
                .lines()
                .find(|l| l.contains(text))
                .unwrap_or_else(|| panic!("{text}: {shown}"))
                .to_string()
        };
        assert!(line("Show Shorts").contains("▌ [✓]"), "selected, and on");
        assert!(line("Show live streams").contains("[ ]"));
        assert!(line("SponsorBlock").contains("[✓]"));
        assert!(line("Catppuccin Mocha").contains("●"), "the theme in use");
        assert!(line("Catppuccin Latte").contains("○"));
        assert!(shown.contains("Enter on/off"));

        // In a short window, the cursor's row stays on screen.
        app.help.as_mut().unwrap().selected = HelpMenu::LAST;
        let shown = screen(&mut app, 80, 12);
        assert!(
            shown.contains("Rosé Pine") || shown.contains("Rose Pine"),
            "{shown}"
        );
        assert!(!shown.contains("Show Shorts"));
        assert!(shown.contains("Enter use"));
    }

    #[tokio::test]
    async fn the_player_bar_is_a_box_with_the_title_in_its_border() {
        let mut app = app();
        app.icons = crate::icons::PLAIN;
        with_feed(&mut app, 3);
        app.status = None;
        app.show_playing(app.videos[0].clone(), 10.0, 100.0, false);
        let shown = screen(&mut app, 140, 40);
        let lines: Vec<&str> = shown.lines().collect();
        let title = lines
            .iter()
            .position(|l| l.contains("╭ ▶ Video vid00000002  ·  Channel"))
            .expect(&shown);
        let progress = lines[title + 1];
        assert!(progress.starts_with("│ 0:10 ━"), "{progress}");
        assert!(progress.ends_with("│"), "{progress}");
        assert!(lines[title + 2].starts_with("╰─"));
        assert!(progress.contains("0:10 ━"), "{progress}");
        assert!(progress.contains("● 1:40") || progress.contains("─ 1:40"));
        // Windows can't pause or seek mpv yet: only X and A there.
        let progress_row = |app: &mut App| {
            let shown = screen(app, 140, 40);
            let row = shown
                .lines()
                .find(|l| l.starts_with("│ 0:10 "))
                .map(str::to_string);
            row.expect(&shown)
        };
        for (controllable, keys) in [
            (false, "1:40   ■ X  ⟳ A"),
            (true, "« ,  ⏸ Space  » .  § t  ■ X  ⟳ A"),
        ] {
            mpv_control(&mut app, controllable);
            let progress = progress_row(&mut app);
            assert!(progress.contains(keys), "{progress}");
        }
        assert!(!shown.contains("Next:"));

        app.up_next = app.videos[1..].iter().cloned().collect();
        let shown = screen(&mut app, 140, 40);
        let title_line = shown
            .lines()
            .find(|l| l.contains("▶ Video vid00000002"))
            .unwrap();
        assert!(
            title_line.ends_with("─ Next: Video vid00000001 ╮"),
            "{title_line}"
        );
        assert!(shown.contains("  ⏭ N  ■ X"), "{shown}");
        app.settings.autoplay = false;
        assert!(
            !screen(&mut app, 140, 40).contains("Next:"),
            "autoplay won't play it"
        );
        for width in 1..140 {
            screen(&mut app, width, 40);
        }
        for height in 1..12 {
            screen(&mut app, 140, height);
        }
    }

    #[tokio::test]
    async fn the_jukebox_shows_as_cards_or_as_a_list() {
        let mut app = app();
        app.icons = crate::icons::PLAIN;
        with_feed(&mut app, 6);
        app.show(View::Jukebox, false);
        app.status = None;
        assert!(screen(&mut app, 140, 45).contains("The Jukebox is empty"));

        app.show(View::Home, false);
        for i in [1, 3] {
            app.selected = i;
            app.on_key(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::NONE));
        }
        app.status = None;
        let shown = screen(&mut app, 140, 45);
        assert!(shown.contains("≡  Jukebox  2"), "its count: {shown}");
        assert!(
            shown.contains(" ≡1") && shown.contains(" ≡2"),
            "the cards say their place"
        );

        app.show(View::Jukebox, false);
        let shown = screen(&mut app, 140, 45);
        assert!(shown.contains("Jukebox  2 videos"), "{shown}");
        assert!(shown.contains("Video vid00000004"));
        assert!(!shown.contains(" ≡1"), "no place on its own cards");
        assert!(app.grid.get().cols >= 2, "cards");
        let status = shown.lines().last().unwrap().to_string();
        assert!(status.contains("J K move"), "{status}");
        // The one playing from it is marked.
        app.show_playing(app.videos[0].clone(), 10.0, 100.0, false);
        let shown = screen(&mut app, 140, 45);
        assert!(shown.contains("▶ Playing ·"), "{shown}");

        app.settings.jukebox_list = true;
        let shown = screen(&mut app, 140, 45);
        assert_eq!(app.grid.get().cols, 1, "a list");
        let row = |n: &str| {
            shown
                .lines()
                .find(|l| l.contains(n))
                .unwrap_or_else(|| panic!("{n}: {shown}"))
                .to_string()
        };
        assert!(row("Video vid00000004").contains("▌▶  Video vid00000004"));
        assert!(row("Video vid00000002").contains(" 2  Video vid00000002"));
        assert!(row("Video vid00000002").contains("Channel"));
        assert!(!shown.contains("Video vid00000005"), "only the Jukebox's");
        // Clearing it asks first, in a popup.
        app.confirm = Some(Confirm::ClearJukebox);
        let shown = screen(&mut app, 140, 45);
        assert!(shown.contains("Clear the Jukebox?"), "{shown}");
        assert!(shown.contains("All 2 videos in it are taken off"));
        assert!(shown.contains("y clear"));
        for width in 1..140 {
            screen(&mut app, width, 45);
        }
        for height in 1..12 {
            screen(&mut app, 140, height);
        }
    }

    /// Chapters at 0:00, 1:00 and 3:00 of the video playing.
    fn with_chapters(app: &mut App) {
        let playing = app.playing.as_mut().unwrap();
        playing.chapters = [(0.0, "Intro"), (60.0, "The middle part"), (180.0, "Outro")]
            .map(|(start, title)| crate::chapters::Chapter {
                start,
                title: title.into(),
            })
            .into();
    }

    #[tokio::test]
    async fn the_player_bar_says_the_chapter_and_the_quality() {
        let mut app = app();
        app.icons = crate::icons::PLAIN;
        with_feed(&mut app, 3);
        app.status = None;
        app.show_playing(app.videos[0].clone(), 75.0, 600.0, false);
        with_chapters(&mut app);
        app.playing.as_mut().unwrap().quality = Some("1080p60".into());
        // The keys after the quality: Windows has only X and A.
        for (controllable, after) in [
            (false, "10:00  1080p60  ■ X"),
            (true, "10:00  1080p60  « ,"),
        ] {
            mpv_control(&mut app, controllable);
            let shown = screen(&mut app, 140, 40);
            let progress = shown
                .lines()
                .find(|l| l.starts_with("│ 1:15 "))
                .expect(&shown);
            assert!(progress.contains("1:15 · The middle part ━"), "{progress}");
            assert!(progress.contains(after), "{progress}");
        }
        // Narrow: the keys and the quality go, then the chapter.
        let shown = screen(&mut app, 50, 40);
        assert!(!shown.contains("1080p60") && shown.contains("The middle"));
        let shown = screen(&mut app, 30, 40);
        assert!(!shown.contains("The middle"), "{shown}");
        for width in 1..140 {
            screen(&mut app, width, 40);
        }
    }

    #[tokio::test]
    async fn the_chapters_popup_lists_them_and_marks_the_one_playing() {
        let mut app = app();
        app.icons = crate::icons::PLAIN;
        with_feed(&mut app, 3);
        app.status = None;
        app.show_playing(app.videos[0].clone(), 75.0, 600.0, false);
        with_chapters(&mut app);
        app.on_key(KeyEvent::new(KeyCode::Char('t'), KeyModifiers::NONE));
        assert!(app.popup_open());
        let shown = screen(&mut app, 120, 40);
        assert!(shown.contains(" Chapters · 3 "), "{shown}");
        assert!(shown.contains("type a time: 1:23 · 90 · +30 · 50%"));
        let line = |text: &str| {
            shown
                .lines()
                .find(|l| l.contains(text))
                .unwrap_or_else(|| panic!("{text}: {shown}"))
                .to_string()
        };
        assert!(
            line("Intro").contains("│   0:00  Intro"),
            "{}",
            line("Intro")
        );
        assert!(
            line("The middle part").contains("│▌▶ 1:00  The middle part"),
            "selected, and playing: {}",
            line("The middle part")
        );
        assert!(line("Outro").contains("3:00  Outro"));
        assert!(shown.contains("Enter go · j k choose · Esc close"));

        // A time typed shows, and Enter goes there instead.
        for c in "2:30".chars() {
            app.on_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE));
        }
        let shown = screen(&mut app, 120, 40);
        assert!(shown.contains("Go to 2:30▏"), "{shown}");
        assert!(shown.contains("Enter go to the time"));

        // A long list scrolls to keep the cursor in view; small windows
        // don't break it.
        let playing = app.playing.as_mut().unwrap();
        playing.chapters = (0..60)
            .map(|i| crate::chapters::Chapter {
                start: f64::from(i) * 10.0,
                title: format!("Part {i}"),
            })
            .collect();
        app.chapter_menu.as_mut().unwrap().selected = 59;
        let shown = screen(&mut app, 120, 30);
        assert!(
            shown.contains("Part 59") && !shown.contains("Part 1 "),
            "{shown}"
        );
        app.playing.as_mut().unwrap().chapters.clear();
        let shown = screen(&mut app, 120, 30);
        assert!(shown.contains(" Go to a time ") && shown.contains("no chapters"));
        for width in 1..120 {
            screen(&mut app, width, 30);
        }
        for height in 1..12 {
            screen(&mut app, 120, height);
        }
    }

    #[tokio::test]
    async fn the_settings_show_the_video_and_sound_quality_in_use() {
        let mut app = app();
        app.settings.max_height = 900;
        app.settings.audio_quality = AudioQuality::Low;
        let mut menu = HelpMenu::new(HelpTab::Settings);
        menu.selected = HelpMenu::VIDEO_QUALITY + 1;
        app.help = Some(menu);
        let shown = screen(&mut app, 120, 60);
        let line = |text: &str| {
            shown
                .lines()
                .find(|l| l.contains(text))
                .unwrap_or_else(|| panic!("{text}: {shown}"))
                .to_string()
        };
        assert!(shown.contains(" Video quality") && shown.contains(" Sound quality"));
        assert!(line("Up to 720p").contains("●"), "900 plays as 720p");
        assert!(line("Up to 1080p (HD)").contains("○"));
        assert!(line("Up to 1440p").contains("▌ ○"), "the cursor");
        assert!(line("Low: about 70 kbps").contains("●"));
        assert!(line("High: about 130 kbps").contains("○"));
        assert!(shown.contains("Enter use"), "a choice, not on/off");
    }

    #[tokio::test]
    async fn the_command_line_lists_what_completes_it_under_the_word() {
        let mut app = app();
        with_feed(&mut app, 3);
        let typed = |app: &mut App, text: &str| {
            for c in text.chars() {
                app.on_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE));
            }
        };
        typed(&mut app, ":");
        let shown = screen(&mut app, 140, 40);
        let lines: Vec<&str> = shown.lines().collect();
        assert!(lines[39].starts_with(":▏"), "{}", lines[39]);
        assert!(lines[39].contains("Tab complete · Enter run · Esc close"));
        assert!(shown.contains(" Commands "), "{shown}");
        let row = |shown: &str, text: &str| {
            shown
                .lines()
                .find(|l| l.contains(text))
                .unwrap_or_else(|| panic!("{text}: {shown}"))
                .to_string()
        };
        let quality = row(&shown, "quality <height>");
        assert!(quality.contains("│▌  quality <height>"), "lit: {quality}");
        assert!(quality.contains("Video quality: up to 360p"), "{quality}");
        let autoplay = row(&shown, "autoplay [on|off]");
        assert!(
            autoplay.contains("when one ends") && autoplay.contains("  A "),
            "its key"
        );

        // The argument's values, under it, the one in use marked.
        typed(&mut app, "quality ");
        let shown = screen(&mut app, 140, 40);
        assert!(shown.lines().last().unwrap().starts_with(":quality ▏"));
        let column = |line: &str, text: &str| line[..line.find(text).unwrap()].chars().count();
        let in_use = row(&shown, "Up to 1080p (HD)");
        assert!(in_use.contains("● 1080"), "{in_use}");
        assert_eq!(
            column(&in_use, "1080"),
            ":quality ".len(),
            "under the word: {in_use}"
        );
        // Why a line didn't run shows in red on its right.
        typed(&mut app, "999");
        app.on_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        let buffer = drawn(&mut app, 140, 40);
        let status = screen(&mut app, 140, 40)
            .lines()
            .last()
            .unwrap()
            .to_string();
        assert!(status.contains("quality takes 2160, 1440"), "{status}");
        let x = column(&status, "quality takes") as u16;
        assert_eq!(buffer[(x, 39)].fg, app.colors.red, "{status}");
        assert!(app.popup_open());
        for width in 1..140 {
            screen(&mut app, width, 40);
        }
        for height in 1..12 {
            screen(&mut app, 140, height);
        }
    }

    #[tokio::test]
    async fn a_sponsorblock_skip_shows_in_yellow_where_next_goes() {
        let mut app = app();
        app.icons = crate::icons::PLAIN;
        with_feed(&mut app, 3);
        app.settings.sponsorblock = true;
        app.up_next = app.videos[1..].iter().cloned().collect();
        app.show_playing(app.videos[0].clone(), 0.0, 600.0, false);
        sponsor_at(&mut app, 10.0, 75.0, 10.0);
        let buffer = drawn(&mut app, 140, 40);
        let shown = screen(&mut app, 140, 40);
        let (y, line) = shown
            .lines()
            .enumerate()
            .find(|(_, l)| l.contains("▶ Video vid00000002"))
            .expect(&shown);
        assert!(line.contains("[SKIP] Sponsor · 1:05"), "{line}");
        assert!(!line.contains("Next:"), "{line}");
        let x = line.chars().take_while(|&c| c != '[').count() as u16;
        assert_eq!(buffer[(x, y as u16)].fg, app.colors.warning, "yellow");

        sponsor_at(&mut app, 100.0, 120.0, 100.0);
        assert!(screen(&mut app, 140, 40).contains("[SKIP] Sponsor · 20 s"));
        for width in 1..140 {
            screen(&mut app, width, 40);
        }
    }
}