rustimal 0.7.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
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
//! Draws the review panel. It is laid out afresh each frame, and everything that can be
//! clicked records where it landed.

use crate::review::forge::Method;
use super::{CreateStage, Field, Press};
use super::{Click, Opened, ReviewView, Row, Screen, Tab, Thing};
use crate::config::Rgba;
use crate::glyphs::STYLE_BOLD;
use crate::gpu::{MODE_SOLID, Quad};
use crate::layout::Rect;
use crate::render::{Ctx, mix, quad, rounded, text, with_alpha};
use crate::review::render::snippet;
use crate::review::rules::{Finding, Level};
use crate::review::diff::{FileDiff, Kind as DiffKind, Status};
use crate::review::guide::{self, Kind as StageKind};
use crate::review::session::{self, Seen, State, Verdict};

/// A run of text, and whether it was in backticks.
pub type Piece = (String, bool);

/// Word wrap to `cols` characters, dropping paired backticks but remembering what they held.
/// Words longer than a line are cut.
pub fn wrap(source: &str, cols: usize) -> Vec<Vec<Piece>> {
    let cols = cols.max(4);
    // A lone backtick is an ordinary character.
    let paired = source.matches('`').count() / 2 * 2;
    let mut seen = 0;
    let mut code = false;
    let mut words: Vec<Vec<(char, bool)>> = vec![Vec::new()];
    for c in source.chars() {
        if c == '`' && seen < paired {
            seen += 1;
            code = !code;
        } else if c == ' ' || c == '\n' || c == '\t' {
            words.push(Vec::new());
        } else if !c.is_control() {
            words.last_mut().expect("never empty").push((c, code));
        }
    }
    let mut lines: Vec<Vec<(char, bool)>> = vec![Vec::new()];
    for word in words.into_iter().filter(|w| !w.is_empty()) {
        let line = lines.last_mut().expect("never empty");
        if !line.is_empty() {
            if line.len() + 1 + word.len() <= cols {
                // The space is code only inside one snippet.
                let inside = line.last().is_some_and(|l| l.1) && word[0].1;
                line.push((' ', inside));
            } else {
                lines.push(Vec::new());
            }
        }
        for c in word {
            if lines.last().expect("never empty").len() >= cols {
                lines.push(Vec::new());
            }
            lines.last_mut().expect("never empty").push(c);
        }
    }
    lines
        .into_iter()
        .map(|line| {
            let mut pieces: Vec<Piece> = Vec::new();
            for (c, code) in line {
                match pieces.last_mut() {
                    Some(p) if p.1 == code => p.0.push(c),
                    _ => pieces.push((c.to_string(), code)),
                }
            }
            pieces
        })
        .collect()
}

#[derive(Clone, Copy)]
struct Colors {
    fg: Rgba,
    soft: Rgba,
    muted: Rgba,
    accent: Rgba,
    code: Rgba,
    panel: Rgba,
    raised: Rgba,
    line: Rgba,
    red: Rgba,
    green: Rgba,
    yellow: Rgba,
    cyan: Rgba,
}

impl Colors {
    fn new(ctx: &Ctx) -> Colors {
        let p = ctx.palette;
        let panel = mix(p.surface, p.foreground, 0.025);
        let solid = |c: Rgba| [c[0], c[1], c[2], 1.0];
        Colors {
            fg: p.foreground,
            soft: mix(p.foreground, p.surface, 0.2),
            muted: mix(p.foreground, p.surface, 0.5),
            accent: p.accent,
            code: mix(p.accent, p.foreground, 0.35),
            // Opaque: text has to stay readable over whatever is behind.
            panel: solid(panel),
            raised: solid(mix(panel, p.foreground, 0.06)),
            line: solid(mix(panel, p.foreground, 0.14)),
            red: p.ansi[1],
            green: p.ansi[2],
            yellow: p.ansi[3],
            cyan: p.ansi[6],
        }
    }

    fn level(&self, level: Level) -> Rgba {
        match level {
            Level::Risk => self.red,
            Level::Warn => self.yellow,
            Level::Note => self.cyan,
        }
    }

    /// The mark and color for a step's state.
    fn state(&self, state: State) -> (&'static str, Rgba) {
        match state {
            State::Untested => ("\u{25cb}", self.muted),
            State::Done(Verdict::Passed) => ("\u{2713}", self.green),
            State::Done(Verdict::Failed) => ("\u{2717}", self.red),
            State::Done(Verdict::Skipped) => ("\u{2013}", self.muted),
            State::Stale(_) => ("\u{21bb}", self.yellow),
        }
    }
}

struct Button {
    label: String,
    click: Click,
    /// Its color, and whether it is the one in effect.
    tone: Option<Rgba>,
    on: bool,
}

fn button(label: &str, click: Click) -> Button {
    Button { label: label.to_string(), click, tone: None, on: false }
}

impl Button {
    fn tone(mut self, color: Rgba, on: bool) -> Button {
        self.tone = Some(color);
        self.on = on;
        self
    }
}

/// A column being filled from the top down. What falls outside `area` is not drawn and
/// cannot be clicked.
struct Flow<'a, 'c> {
    ctx: &'a mut Ctx<'c>,
    out: &'a mut Vec<Quad>,
    hits: &'a mut Vec<(Rect, Click)>,
    colors: Colors,
    mouse: (f32, f32),
    area: Rect,
    x: f32,
    w: f32,
    y: f32,
    cw: f32,
    ch: f32,
    s: f32,
}

impl<'a, 'c> Flow<'a, 'c> {
    fn new(
        ctx: &'a mut Ctx<'c>,
        out: &'a mut Vec<Quad>,
        hits: &'a mut Vec<(Rect, Click)>,
        mouse: (f32, f32),
        area: Rect,
        scroll: f32,
    ) -> Self {
        let colors = Colors::new(ctx);
        let (cw, ch, s) = (ctx.glyphs.cell_w, ctx.glyphs.cell_h, ctx.scale);
        Flow { ctx, out, hits, colors, mouse, area, x: area.x, w: area.w, y: area.y - scroll.round(), cw, ch, s }
    }

    fn clip(&self) -> [f32; 4] {
        [self.area.x, self.area.y, self.area.right(), self.area.bottom()]
    }

    fn shows(&self, y: f32, h: f32) -> bool {
        y + h >= self.area.y && y <= self.area.bottom()
    }

    fn line_height(&self) -> f32 {
        (self.ch * 1.25).round()
    }

    fn cols(&self, width: f32) -> usize {
        (width / self.cw).floor().max(4.0) as usize
    }

    fn gap(&mut self, lines: f32) {
        self.y += (self.ch * lines).round();
    }

    fn fill(&mut self, r: Rect, color: Rgba, radius: f32) {
        if self.shows(r.y, r.h) {
            let clip = self.clip();
            self.out.push(rounded(r, color, radius * self.s, 0.0, [0.0; 4], clip));
        }
    }

    fn framed(&mut self, r: Rect, color: Rgba, border: Rgba, radius: f32) {
        if self.shows(r.y, r.h) {
            let clip = self.clip();
            self.out.push(rounded(r, color, radius * self.s, self.s.max(1.0), border, clip));
        }
    }

    /// One line at a point; returns the width used.
    fn put(&mut self, x: f32, y: f32, content: &str, color: Rgba, style: u8, max_w: f32) -> f32 {
        if !self.shows(y, self.ch) || max_w < self.cw {
            return 0.0;
        }
        let content: String = content.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();
        let clip = self.clip();
        text(self.ctx, self.out, x.round(), y.round(), &content, color, style, max_w, clip)
    }

    /// Wrapped text, with backticked parts picked out.
    fn para(&mut self, content: &str, color: Rgba, style: u8, indent: f32) {
        let width = self.w - indent;
        let lines = wrap(content, self.cols(width));
        let (lh, code) = (self.line_height(), self.colors.code);
        for line in lines {
            let mut x = self.x + indent;
            for (piece, is_code) in line {
                let chars = piece.chars().count() as f32;
                let color = if is_code { code } else { color };
                self.put(x, self.y, &piece, color, style, (chars + 0.5) * self.cw);
                x += chars * self.cw;
            }
            self.y += lh;
        }
    }

    /// Remember where something clickable is, as far as it can be seen.
    fn hit(&mut self, r: Rect, click: Click) {
        let (top, bottom) = (r.y.max(self.area.y), r.bottom().min(self.area.bottom()));
        if bottom > top {
            self.hits.push((Rect::new(r.x, top, r.w, bottom - top), click));
        }
    }

    fn hovered(&self, r: Rect) -> bool {
        r.contains(self.mouse.0, self.mouse.1) && self.area.contains(self.mouse.0, self.mouse.1)
    }

    fn button_width(&self, label: &str) -> f32 {
        (label.chars().count() as f32 + 2.0) * self.cw
    }

    fn button_at(&mut self, r: Rect, b: Button) {
        let c = self.colors;
        let tone = b.tone.unwrap_or(c.fg);
        let hover = self.hovered(r);
        let fill = if b.on { mix(c.panel, tone, 0.34) } else if hover { mix(c.raised, c.fg, 0.08) } else { c.raised };
        let border = if b.on || (hover && b.tone.is_some()) { tone } else { c.line };
        self.framed(r, fill, border, 6.0);
        let width = b.label.chars().count() as f32 * self.cw;
        let color = if b.tone.is_some() && !b.on { mix(tone, c.fg, 0.25) } else { c.fg };
        self.put(r.x + (r.w - width) * 0.5, r.y + (r.h - self.ch) * 0.5, &b.label, color, 0, width + 1.0);
        self.hit(r, b.click);
    }

    /// Buttons side by side, going to a new row when they run out of room.
    fn buttons(&mut self, buttons: Vec<Button>) {
        let (h, gap) = ((self.ch * 1.6).round(), (6.0 * self.s).round());
        let mut x = self.x;
        for b in buttons {
            let w = self.button_width(&b.label).min(self.w);
            if x > self.x && x + w > self.x + self.w {
                x = self.x;
                self.y += h + gap;
            }
            self.button_at(Rect::new(x, self.y, w, h), b);
            x += w + gap;
        }
        self.y += h;
    }

    /// A text field with a caret at the end, showing the end of long text.
    fn field(&mut self, content: &str, placeholder: &str, focused: bool, click: Option<Click>) {
        let c = self.colors;
        let r = Rect::new(self.x, self.y, self.w, (self.ch * 1.8).round());
        self.framed(r, c.raised, if focused { c.accent } else { c.line }, 7.0);
        let ty = r.y + (r.h - self.ch) * 0.5;
        let room = self.cols(r.w - 2.0 * self.cw).saturating_sub(1);
        let chars: Vec<char> = content.chars().collect();
        let shown: String = chars[chars.len().saturating_sub(room)..].iter().collect();
        if shown.is_empty() {
            self.put(r.x + self.cw, ty, placeholder, c.muted, 0, r.w - 2.0 * self.cw);
        } else {
            self.put(r.x + self.cw, ty, &shown, c.fg, 0, r.w - self.cw);
        }
        if focused && self.shows(r.y, r.h) {
            let cx = r.x + self.cw + shown.chars().count() as f32 * self.cw + 1.0;
            let caret = Rect::new(cx, ty + self.ch * 0.12, (1.5 * self.s).round().max(1.0), self.ch * 0.76);
            let clip = self.clip();
            self.out.push(quad(caret, with_alpha(c.accent, self.ctx.cursor_alpha.max(0.25)), clip, MODE_SOLID));
        }
        if let Some(click) = click {
            self.hit(r, click);
        }
        self.y = r.bottom();
    }

    /// A box for text of many lines, with the caret at its end.
    fn text_box(&mut self, content: &str, focused: bool, click: Click) {
        let c = self.colors;
        let cols = self.cols(self.w - 2.0 * self.cw).saturating_sub(1).max(1);
        let mut lines: Vec<String> = Vec::new();
        for line in content.split('\n') {
            let chars: Vec<char> = line.chars().collect();
            if chars.is_empty() {
                lines.push(String::new());
            }
            lines.extend(chars.chunks(cols).map(|part| part.iter().collect::<String>()));
        }
        let lh = self.line_height();
        let height = (lines.len().max(5) as f32 * lh + self.ch * 0.6).round();
        let r = Rect::new(self.x, self.y, self.w, height);
        self.framed(r, c.raised, if focused { c.accent } else { c.line }, 7.0);
        let top = r.y + self.ch * 0.3;
        for (i, line) in lines.iter().enumerate() {
            self.put(r.x + self.cw, top + i as f32 * lh, line, c.fg, 0, r.w - self.cw);
        }
        if focused {
            let last = lines.last().map_or(0, |l| l.chars().count());
            let cx = r.x + self.cw * (last as f32 + 1.0) + 1.0;
            let cy = top + (lines.len() - 1) as f32 * lh;
            if self.shows(cy, self.ch) {
                let caret = Rect::new(cx, cy + self.ch * 0.12, (1.5 * self.s).round().max(1.0), self.ch * 0.76);
                let clip = self.clip();
                self.out.push(quad(caret, with_alpha(c.accent, self.ctx.cursor_alpha.max(0.25)), clip, MODE_SOLID));
            }
        }
        self.hit(r, click);
        self.y = r.bottom();
    }

    fn rule(&mut self) {
        let r = Rect::new(self.x, self.y, self.w, self.s.max(1.0).round());
        let line = self.colors.line;
        self.fill(r, line, 0.0);
        self.y = r.bottom();
    }

    /// A tinted box with a bar on its left, around wrapped text.
    fn callout(&mut self, content: &str, color: Rgba) {
        let pad = self.cw;
        let height = wrap(content, self.cols(self.w - 2.5 * pad)).len() as f32 * self.line_height() + self.ch * 0.5;
        let r = Rect::new(self.x, self.y, self.w, height.round());
        let tint = mix(self.colors.panel, color, 0.12);
        self.fill(r, tint, 6.0);
        self.fill(Rect::new(r.x, r.y, (3.0 * self.s).round(), r.h), color, 1.0);
        self.y += (self.ch * 0.25).round();
        let (x, w) = (self.x, self.w);
        self.x += 1.5 * pad;
        self.w -= 2.5 * pad;
        let fg = self.colors.fg;
        self.para(content, fg, 0, 0.0);
        (self.x, self.w) = (x, w);
        self.y = r.bottom();
    }

    /// A file position as a link, then the line itself with the part that matters underlined.
    fn place(&mut self, f: &Finding) {
        let Some(span) = &f.span else { return };
        let c = self.colors;
        let from_description = span.file == "PR description" || span.file == "commit messages";
        let place = format!("{}:{}", span.file, span.line);
        let width = (place.chars().count() as f32 * self.cw).min(self.w);
        let r = Rect::new(self.x, self.y, width, self.line_height());
        let color = if from_description { c.muted } else if self.hovered(r) { c.accent } else { c.code };
        self.put(self.x, self.y, &place, color, 0, self.w);
        if !from_description {
            self.hit(r, Click::File(span.file.clone(), span.line));
        }
        self.y += self.line_height();

        let (shown, col, len) = snippet(span, self.cols(self.w - 2.0 * self.cw));
        let r = Rect::new(self.x, self.y, self.w, (self.ch * 1.7).round());
        self.fill(r, c.raised, 6.0);
        let ty = r.y + self.ch * 0.25;
        self.put(r.x + self.cw, ty, &shown, c.fg, 0, r.w - self.cw);
        let under = Rect::new(r.x + self.cw * (col as f32 + 1.0), ty + self.ch * 1.08, len as f32 * self.cw, (2.0 * self.s).round());
        let color = c.level(f.level);
        self.fill(under, color, 1.0);
        self.y = r.bottom() + (self.ch * 0.15).round();
        self.para(&span.label, color, 0, self.cw);
    }
}

fn level_tag(level: Level) -> &'static str {
    match level {
        Level::Risk => "RISK",
        Level::Warn => "WARNING",
        Level::Note => "NOTE",
    }
}

/// Draw the panel into `rect`. Returns true if it needs another frame (to scroll to the
/// selection, which is only known once it has been laid out).
pub fn draw(ctx: &mut Ctx, view: &mut ReviewView, rect: Rect, out: &mut Vec<Quad>) -> bool {
    let colors = Colors::new(ctx);
    let (cw, ch, s) = (ctx.glyphs.cell_w, ctx.glyphs.cell_h, ctx.scale);
    view.rect = rect;
    view.list_rect = Rect::default();
    view.hits.clear();
    let radius = ctx.config.radius * s;
    let edge = if view.focused && ctx.focused { colors.accent } else { colors.line };
    out.push(rounded(rect, colors.panel, radius, (1.5 * s).round().max(1.0), edge, crate::render::NO_CLIP));

    let pad = (14.0 * s).round().min(rect.w * 0.05);
    let inner = Rect::new(rect.x + pad, rect.y + pad, (rect.w - 2.0 * pad).max(0.0), (rect.h - 2.0 * pad).max(0.0));
    if inner.w < cw * 12.0 || inner.h < ch * 8.0 {
        return false;
    }

    // Header: the title, and the buttons for the panel itself.
    let (title, subtitle) = titles(view);
    let header_h = (ch * 1.6).round();
    let wide_label = if view.wide { "Side" } else { "Wide" };
    let mut right = inner.right();
    {
        let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, inner, 0.0);
        for b in [button("\u{2715}", Click::Close), button(wide_label, Click::Wide)] {
            let w = f.button_width(&b.label);
            right -= w;
            f.button_at(Rect::new(right, inner.y, w, header_h), b);
            right -= 6.0 * s;
        }
        f.put(inner.x, inner.y + (header_h - ch) * 0.5, &title, colors.fg, STYLE_BOLD, right - inner.x);
        f.y = inner.y + header_h + (ch * 0.25).round();
        f.put(inner.x, f.y, &subtitle, colors.muted, 0, inner.w);
    }
    let top = inner.y + header_h + (ch * 1.75).round();
    let body = Rect::new(inner.x, top, inner.w, (inner.bottom() - top).max(0.0));

    let focused = view.focused;
    match &view.screen {
        Screen::Git(_) => return draw_git(ctx, view, body, out),
        Screen::Create(_) => return draw_create(ctx, view, body, out),
        Screen::Pick(_) => draw_picker(ctx, view, body, out),
        Screen::Open(_) => return draw_change(ctx, view, body, out),
        Screen::Loading(what) => {
            let what = what.clone();
            let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, body, 0.0);
            f.gap(1.0);
            f.para(&format!("{what}\u{2026}"), colors.soft, 0, 0.0);
            f.gap(0.5);
            f.para("A pull request is fetched from its host first.", colors.muted, 0, 0.0);
        }
        Screen::Message { text: message, error } => {
            let (message, error) = (message.clone(), *error);
            let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, body, 0.0);
            f.gap(0.5);
            f.callout(&message, if error { colors.red } else { colors.cyan });
            f.gap(1.0);
            f.buttons(vec![button("\u{2039} All changes", Click::Back), button("Try again", Click::Reload)]);
            if focused {
                f.gap(1.0);
                f.para("esc: back to the list   r: try again", colors.muted, 0, 0.0);
            }
        }
    }
    false
}

fn titles(view: &ReviewView) -> (String, String) {
    let folder = view.cwd.to_string_lossy().into_owned();
    match &view.screen {
        Screen::Git(g) => ("Git".into(), g.snapshot.as_ref().map_or(folder, |s| {
            format!("{} \u{00b7} {} changed \u{00b7} {}", s.branch, s.dirty, s.root.display())
        })),
        Screen::Pick(_) => ("Review a change".to_string(), folder),
        Screen::Create(_) => ("New pull request".to_string(), folder),
        Screen::Loading(_) | Screen::Message { .. } => ("Review".to_string(), folder),
        Screen::Open(o) => {
            let r = &o.change.report;
            let project = if r.project.is_empty() { String::new() } else { format!(" \u{00b7} {}", r.project.join(", ")) };
            let files = if r.files == 1 { "file" } else { "files" };
            (o.change.title.clone(), format!("{} \u{00b7} {} {files} +{} \u{2212}{}{project}", r.against, r.files, r.added, r.removed))
        }
    }
}

fn draw_git(ctx: &mut Ctx, view: &mut ReviewView, body: Rect, out: &mut Vec<Quad>) -> bool {
    use super::workspace::{Control, Form, Tab};
    use crate::review::workspace::Action;
    let Screen::Git(g) = &view.screen else { return false };
    let c = Colors::new(ctx);
    let ch = ctx.glyphs.cell_h;
    let footer_h = ch * if view.status.is_some() { 6.0 } else { 3.5 };
    let area = Rect::new(body.x, body.y, body.w, (body.h - footer_h).max(0.0));
    let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, area, view.scroll);
    let start = f.y;
    let mut chosen = None;
    let action = |name, control| button(name, Click::GitAction(control));
    if let Some(preview) = &g.preview {
        let (title, movement) = match preview {
            Action::Move(m) => ("Move commits", Some(m)),
            Action::Undo(m) => ("Undo move", Some(m)),
            Action::Publish { movement, .. } => ("Publish recovery", Some(movement)),
            _ => ("Git", None),
        };
        f.para(title, c.fg, STYLE_BOLD, 0.0);
        f.gap(0.7);
        if let Some(m) = movement {
            let short = |id: &str| id.chars().take(8).collect::<String>();
            let (from, to) = if matches!(preview, Action::Undo(_)) { (&m.base, &m.old) } else { (&m.old, &m.base) };
            if let Action::Publish { expected, desired, remote, .. } = preview {
                f.para(&crate::review::workspace::remote_label(remote), c.soft, 0, 0.0);
                f.para(&format!("Remote {}: {} \u{2192} {}", m.source, short(expected), short(desired)), c.fg, 0, 0.0);
                f.para("Atomic push \u{00b7} force-with-lease", c.yellow, 0, 0.0);
            } else {
                f.para(&format!("{}: {} \u{2192} {}", m.source, short(from), short(to)), c.fg, 0, 0.0);
            }
            f.para(&format!("{}: {} \u{00b7} {} commits", m.destination, short(&m.old), m.count), c.soft, 0, 0.0);
            f.gap(0.7);
            if !matches!(preview, Action::Publish { .. }) {
                f.para("Local only \u{00b7} undo available", c.muted, 0, 0.0);
            }
        }
        f.gap(1.0);
        f.buttons(vec![action("Confirm Enter", Control::Accept), action("Cancel Esc", Control::Cancel)]);
    } else {
        f.buttons(vec![
            action(if g.tab == Tab::Branches { "Branches \u{2022}" } else { "Branches" }, Control::Branches),
            action(if g.tab == Tab::Commits { "Commits \u{2022}" } else { "Commits" }, Control::Commits),
            action("PR p", Control::PullRequest), action("Refresh r", Control::Refresh),
            action("Fetch f", Control::Fetch),
        ]);
        f.gap(0.5);
        if let Some(form) = g.form {
            let label = match form { Form::Create => "New branch", Form::Move(_) => "Move to new branch", Form::Filter => "Filter branches" };
            f.para(label, c.soft, 0, 0.0);
            f.field(&g.text, "enter name", view.focused, None);
            f.gap(0.5);
        } else if !g.filter.is_empty() && g.tab == Tab::Branches {
            f.para(&format!("/ {}", g.filter), c.muted, 0, 0.0);
        }
        if let Some(s) = &g.snapshot {
            if g.tab == Tab::Commits {
                f.para(&format!("{} selected \u{00b7} latest first", (g.oldest + 1).min(s.commits.len())), c.muted, 0, 0.0);
                f.gap(0.3);
            }
            if s.recovery.is_some() {
                f.para(if s.undo.is_some() { "Recovery \u{00b7} undo u \u{00b7} publish y" } else { "Restored \u{00b7} publish y" }, c.soft, 0, 0.0);
                f.gap(0.4);
            }
            let rows = g.rows();
            if rows.is_empty() { f.para("No matches", c.muted, 0, 0.0); }
            for (i, (name, detail)) in rows.iter().enumerate() {
                let row = Rect::new(f.x, f.y, f.w, (f.ch * 1.65).round());
                let selected = i == g.selected;
                if selected { f.fill(row, mix(c.panel, c.accent, 0.18), 6.0); }
                else if f.hovered(row) { f.fill(row, c.raised, 6.0); }
                let label = if detail == "current" { format!("\u{2022} {name}") }
                    else if detail == "remote" { format!("{name} \u{00b7} remote") } else { name.clone() };
                f.put(row.x + f.cw, row.y + f.ch * 0.25, &label, if selected { c.fg } else { c.soft }, 0, row.w - f.cw * 2.0);
                f.hit(row, Click::GitRow(i));
                f.y = row.bottom();
                if selected { chosen = Some((row.y - start, row.h)); }
            }
        } else {
            f.para(if g.busy { "Loading\u{2026}" } else { "Refresh to retry" }, c.muted, 0, 0.0);
        }
    }
    let height = f.y - start;
    view.max_scroll = (height - area.h).max(0.0);
    let previous = view.scroll;
    if view.reveal {
        if let Some(chosen) = chosen.filter(|_| g.form.is_none()) { view.scroll = scrolled_to(view.scroll, chosen, area.h, ch); }
        view.reveal = false;
    }
    view.scroll = view.scroll.clamp(0.0, view.max_scroll);
    scrollbar(out, area, view.scroll, view.max_scroll, ctx.scale, c);
    let footer = Rect::new(body.x, area.bottom() + ch * 0.3, body.w, footer_h - ch * 0.3);
    let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, footer, 0.0);
    f.rule();
    f.gap(0.3);
    if let Some((message, error)) = &view.status {
        for line in wrap(message, f.cols(f.w)).into_iter().take(3) {
            let text: String = line.into_iter().map(|(s, _)| s).collect();
            f.put(f.x, f.y, &text, if *error { c.red } else { c.green }, 0, f.w);
            f.y += f.line_height();
        }
    }
    let hint = if g.busy { "Working\u{2026}" }
        else if g.form.is_some() || g.preview.is_some() { "enter confirm  esc cancel" }
        else if g.tab == Tab::Branches { "enter switch  n new  / filter  tab commits  p PR  c copy  esc close" }
        else { "space select through here  m move  u undo  y publish  enter review  tab branches" };
    f.para(hint, c.muted, 0, 0.0);
    (previous - view.scroll).abs() > 1.0
}

/// The new pull request screen. Returns true if it needs another frame.
fn draw_create(ctx: &mut Ctx, view: &mut ReviewView, body: Rect, out: &mut Vec<Quad>) -> bool {
    let Screen::Create(c) = &view.screen else { return false };
    let colors = Colors::new(ctx);
    let ch = ctx.glyphs.cell_h;
    let footer_h = ch * if view.status.is_some() { 5.5 } else { 2.5 };
    let area = Rect::new(body.x, body.y, body.w, (body.h - footer_h).max(0.0));
    let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, area, view.scroll);
    let start = f.y;
    // Where the field being typed in is, to keep it in view.
    let mut chosen = None;
    let press = |name: &str, p: Press| button(name, Click::Create(p));
    let hint = match &c.stage {
        CreateStage::Loading => {
            f.gap(0.5);
            f.para("Looking at the branch and asking the host\u{2026}", colors.soft, 0, 0.0);
            "esc back"
        }
        CreateStage::Failed(why) => {
            f.gap(0.5);
            f.callout(why, colors.red);
            f.gap(1.0);
            f.buttons(vec![press("\u{2039} All changes", Press::Cancel)]);
            "r try again \u{00b7} esc back"
        }
        CreateStage::Done { pull, created } => {
            f.gap(0.5);
            let said = match created {
                Some(host) => format!("Created pull request #{} on {host}", pull.number),
                None => format!("This branch already has an open pull request, #{}", pull.number),
            };
            f.callout(&said, colors.green);
            f.gap(0.7);
            f.para(&pull.title, colors.fg, STYLE_BOLD, 0.0);
            f.para(&pull.url, colors.muted, 0, 0.0);
            f.gap(1.0);
            f.buttons(vec![
                press("Review it", Press::Review),
                press("Open in browser", Press::Open),
                press("Copy link", Press::Copy),
            ]);
            "enter review it \u{00b7} o browser \u{00b7} c copy link \u{00b7} esc back"
        }
        CreateStage::Form | CreateStage::Confirm | CreateStage::Sending => match &c.proposal {
            None => "esc back",
            Some(p) => {
                f.para(&format!("{} \u{2192} {}", p.pull.head, p.pull.base), colors.accent, STYLE_BOLD, 0.0);
                let count = if p.commits.len() == 1 { "1 commit".into() } else { format!("{} commits", p.commits.len()) };
                f.para(&format!("{count} \u{00b7} {}", p.host), colors.muted, 0, 0.0);
                if p.dirty > 0 {
                    f.gap(0.4);
                    let left = format!("Uncommitted changes in {} files are not part of it", p.dirty);
                    f.callout(&left, colors.yellow);
                }
                f.gap(0.8);
                if matches!(c.stage, CreateStage::Form) {
                    for (label, field, value) in [
                        ("Title", Field::Title, &p.pull.title),
                        ("Merge into", Field::Base, &p.pull.base),
                    ] {
                        let top = f.y;
                        f.para(label, colors.soft, 0, 0.0);
                        let on = c.field == field;
                        f.field(value, label, on && view.focused, Some(Click::Create(Press::Focus(field))));
                        if on {
                            chosen = Some((top - start, f.y - top));
                        }
                        f.gap(0.6);
                    }
                    let top = f.y;
                    f.para("Description", colors.soft, 0, 0.0);
                    let on = c.field == Field::Description;
                    f.text_box(&p.pull.body, on && view.focused, Click::Create(Press::Focus(Field::Description)));
                    if on {
                        // The end of the text is where typing happens.
                        let (from, to) = (top - start, f.y - start);
                        let shown = (to - from).min(area.h * 0.8);
                        chosen = Some((to - shown, shown));
                    }
                    f.gap(0.8);
                    let top = f.y;
                    let mut next = press("Continue \u{203a}", Press::Accept);
                    if c.field == Field::Continue {
                        next = next.tone(colors.accent, true);
                        chosen = Some((top - start, ch * 2.0));
                    }
                    f.buttons(vec![next]);
                    "tab next field \u{00b7} enter new line in the description \u{00b7} esc back"
                } else {
                    f.para(&p.pull.title, colors.fg, STYLE_BOLD, 0.0);
                    f.gap(0.4);
                    for line in p.pull.body.lines() {
                        f.para(line, colors.soft, 0, 0.0);
                    }
                    f.gap(0.8);
                    let push = if p.push {
                        format!("1. Push {} to {} (not forced). ", p.pull.head, p.remote) + "2. "
                    } else {
                        String::new()
                    };
                    let will = format!("{push}Create a pull request on {} into {}.", p.host, p.pull.base);
                    f.callout(&will, colors.yellow);
                    f.gap(1.0);
                    if matches!(c.stage, CreateStage::Sending) {
                        f.para("Sending\u{2026}", colors.soft, 0, 0.0);
                        "esc close the panel; it carries on"
                    } else {
                        f.buttons(vec![press("Create Enter", Press::Accept), press("Back Esc", Press::Cancel)]);
                        "enter create \u{00b7} esc back to editing"
                    }
                }
            }
        },
    };
    let height = f.y - start;
    view.max_scroll = (height - area.h).max(0.0);
    let previous = view.scroll;
    if view.reveal {
        if let Some(chosen) = chosen {
            view.scroll = scrolled_to(view.scroll, chosen, area.h, ch);
        }
        view.reveal = false;
    }
    view.scroll = view.scroll.clamp(0.0, view.max_scroll);
    scrollbar(out, area, view.scroll, view.max_scroll, ctx.scale, colors);
    let footer = Rect::new(body.x, area.bottom() + ch * 0.3, body.w, footer_h - ch * 0.3);
    let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, footer, 0.0);
    f.rule();
    f.gap(0.3);
    if let Some((message, error)) = &view.status {
        let color = if *error { colors.red } else { colors.green };
        for line in wrap(message, f.cols(f.w)).into_iter().take(3) {
            let text: String = line.into_iter().map(|(s, _)| s).collect();
            f.put(f.x, f.y, &text, color, 0, f.w);
            f.y += f.line_height();
        }
    }
    f.para(hint, colors.muted, 0, 0.0);
    (previous - view.scroll).abs() > 1.0
}

fn draw_picker(ctx: &mut Ctx, view: &mut ReviewView, body: Rect, out: &mut Vec<Quad>) {
    let Screen::Pick(picker) = &view.screen else { return };
    let rows = picker.rows();
    let (filter, selected) = (picker.filter.clone(), picker.selected);
    let (ch, s) = (ctx.glyphs.cell_h, ctx.scale);
    let colors = Colors::new(ctx);

    let footer_h = (ch * 1.6).round();
    let field_end = {
        let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, body, 0.0);
        f.field(&filter, "Filter, or type a PR number, branch or commit", view.focused, None);
        f.y
    };
    let list = Rect::new(body.x, field_end + (ch * 0.5).round(), body.w, (body.bottom() - footer_h - field_end - ch * 0.5).max(0.0));

    // Heights are known up front, so the selection can be kept in view right away.
    let entry_h = (ch * 2.55).round();
    let heading_h = (ch * 1.9).round();
    let note_h = |text: &str, cols: usize| wrap(text, cols).len() as f32 * (ch * 1.25).round() + (ch * 0.3).round();
    let note_cols = ((list.w - 2.0 * ctx.glyphs.cell_w) / ctx.glyphs.cell_w).floor().max(4.0) as usize;
    let mut total = 0.0;
    let mut chosen = (0.0, 0.0);
    let mut n = 0;
    for row in &rows {
        let h = match row {
            Row::Heading(_) => heading_h,
            Row::Note(t) => note_h(t, note_cols),
            Row::Entry(_) => {
                if n == selected {
                    chosen = (total, entry_h);
                }
                n += 1;
                entry_h
            }
        };
        total += h;
    }
    view.max_scroll = (total - list.h).max(0.0);
    if view.reveal {
        view.scroll = scrolled_to(view.scroll, chosen, list.h, heading_h);
        view.reveal = false;
    }
    view.scroll = view.scroll.clamp(0.0, view.max_scroll);

    let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, list, view.scroll);
    let mut n = 0;
    for row in &rows {
        match row {
            Row::Heading(name) => {
                f.put(f.x, f.y + ch * 0.7, &name.to_uppercase(), colors.muted, STYLE_BOLD, f.w);
                f.y += heading_h;
            }
            Row::Note(message) => {
                let start = f.y;
                f.para(message, colors.muted, 0, f.cw);
                f.y = start + note_h(message, note_cols);
            }
            Row::Entry(entry) => {
                let r = Rect::new(f.x, f.y, f.w, entry_h - (3.0 * s).round());
                let hover = f.hovered(r);
                if n == selected {
                    let fill = mix(colors.panel, colors.accent, 0.18);
                    f.framed(r, fill, mix(colors.panel, colors.accent, 0.5), 7.0);
                } else if hover {
                    f.fill(r, colors.raised, 7.0);
                }
                f.put(r.x + f.cw, r.y + ch * 0.15, &entry.title, colors.fg, 0, r.w - 2.0 * f.cw);
                f.put(r.x + f.cw, r.y + ch * 1.25, &entry.detail, colors.muted, 0, r.w - 2.0 * f.cw);
                f.hit(r, Click::Choose(n));
                f.y += entry_h;
                n += 1;
            }
        }
    }
    scrollbar(out, list, view.scroll, view.max_scroll, s, colors);

    let foot = Rect::new(body.x, body.bottom() - ch * 1.2, body.w, ch * 1.2);
    let hint = if view.focused { "\u{2191}\u{2193} choose   enter review   esc close" } else { "click here to type" };
    Flow::new(ctx, out, &mut view.hits, view.mouse, foot, 0.0).put(foot.x, foot.y, hint, colors.muted, 0, foot.w);
}

/// The scroll that brings `(top, height)` into a view of `h`, leaving some room above.
fn scrolled_to(scroll: f32, (top, height): (f32, f32), h: f32, above: f32) -> f32 {
    if top - above < scroll {
        (top - above).max(0.0)
    } else if top + height > scroll + h {
        top + height - h
    } else {
        scroll
    }
}

fn scrollbar(out: &mut Vec<Quad>, area: Rect, scroll: f32, max: f32, s: f32, colors: Colors) {
    if max <= 0.0 || area.h <= 0.0 {
        return;
    }
    let thumb = (area.h * area.h / (area.h + max)).max(18.0 * s).min(area.h);
    let y = area.y + (scroll / max) * (area.h - thumb);
    let r = Rect::new(area.right() + 3.0 * s, y, 3.0 * s, thumb);
    out.push(rounded(r, with_alpha(colors.fg, 0.25), 1.5 * s, 0.0, [0.0; 4], crate::render::NO_CLIP));
}

/// How far the whole review is: files read and items judged, over all stages.
fn progress(f: &mut Flow, o: &Opened) {
    let c = f.colors;
    let (mut done, mut total, mut failed) = (0, 0, 0);
    for stage in 0..o.stages.len() {
        let (d, t) = o.stage_counts(stage);
        done += d;
        total += t;
    }
    for i in &o.items {
        failed += usize::from(o.session.state(&i.id) == State::Done(Verdict::Failed));
    }
    let bar = Rect::new(f.x, f.y, f.w, (6.0 * f.s).round());
    f.fill(bar, c.line, 3.0);
    if total > 0 {
        let color = if failed > 0 { c.red } else { c.green };
        f.fill(Rect::new(bar.x, bar.y, bar.w * done as f32 / total as f32, bar.h), color, 2.0);
    }
    f.y = bar.bottom() + (f.ch * 0.3).round();
    let mut line = format!("{done} of {total} done");
    if failed > 0 {
        line += &format!(" \u{00b7} {failed} failed");
    }
    if o.session.approved() {
        line += " \u{00b7} approved";
    }
    f.put(f.x, f.y, &line, if failed > 0 { mix(c.red, c.fg, 0.3) } else { c.soft }, 0, f.w);
    f.y += f.line_height();
}

fn draw_change(ctx: &mut Ctx, view: &mut ReviewView, body: Rect, out: &mut Vec<Quad>) -> bool {
    let (cw, ch, s) = (ctx.glyphs.cell_w, ctx.glyphs.cell_h, ctx.scale);
    let colors = Colors::new(ctx);
    let focused = view.focused;
    let status = view.status.clone();
    let Screen::Open(o) = &view.screen else { return false };

    // Above the scrolling part: progress and the tabs.
    let tabs_end = {
        let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, body, 0.0);
        progress(&mut f, o);
        f.gap(0.3);
        let tabs = Tab::ALL
            .iter()
            .map(|&t| {
                let label = match t {
                    Tab::Guide => format!("Guide ({}/{})", o.stage + 1, o.stages.len()),
                    Tab::Findings => format!("Findings ({})", o.change.report.findings.len()),
                    Tab::Description => "Description".to_string(),
                };
                button(&label, Click::Tab(t)).tone(colors.accent, o.tab == t)
            })
            .collect();
        f.buttons(tabs);
        f.gap(0.4);
        f.rule();
        f.y
    };

    // Below it: what can be done with the whole review, and the keys.
    let mut actions = vec![button("\u{2039} All changes", Click::Back), button("Reload", Click::Reload)];
    if o.change.pull.is_some() {
        let (label, on) = if o.approving {
            ("Approving\u{2026}", false)
        } else if o.session.approved() {
            ("\u{2713} Approved", true)
        } else if o.confirm_approve {
            ("Really approve?", true)
        } else {
            ("Approve", false)
        };
        actions.push(button(label, Click::Approve).tone(colors.green, on));
        actions.extend(merge_buttons(o, colors));
    }
    if o.change.branch.is_some() {
        actions.push(button("Open pull request", Click::Propose).tone(colors.accent, false));
    }
    if !o.items.is_empty() {
        actions.push(button("Copy results", Click::CopyResults));
        let label = if o.confirm_reset { "Really reset?" } else { "Reset" };
        actions.push(button(label, Click::Reset).tone(colors.red, o.confirm_reset));
    }
    let hint = if !focused {
        "click the panel to use its keys".to_string()
    } else if o.note.is_some() {
        "type what went wrong   enter save and go on   esc cancel".to_string()
    } else {
        match (o.tab, o.thing()) {
            (Tab::Guide, Some(Thing::File(_))) => {
                "enter read  \u{2191}\u{2193} move  \u{2190}\u{2192} stage  o open  esc terminal".to_string()
            }
            (Tab::Guide, _) => {
                "enter fine  backspace problem  s skip  \u{2191}\u{2193} move  \u{2190}\u{2192} stage  t type  esc terminal"
                    .to_string()
            }
            (Tab::Findings, _) => "\u{2191}\u{2193} choose  enter unfold  o open  tab next  w wide  esc terminal".to_string(),
            (Tab::Description, _) => "\u{2191}\u{2193} scroll  tab next  w wide  esc terminal".to_string(),
        }
    };
    let hint = if focused && o.note.is_none() && o.change.pull.is_some() && !o.merged {
        format!("a approve \u{00b7} q squash and merge \u{00b7} g merge \u{00b7} {hint}")
    } else {
        hint
    };
    // First, so that a narrow panel does not cut it off.
    let hint = if focused && o.note.is_none() && o.change.branch.is_some() {
        format!("m pull request \u{00b7} {hint}")
    } else {
        hint
    };
    let hint_lines = wrap(&hint, (body.w / cw).floor().max(4.0) as usize).len().min(2);
    // How many rows the actions take.
    let mut rows = 1.0;
    let mut used = 0.0;
    for b in &actions {
        let w = (b.label.chars().count() as f32 + 2.0) * cw + (6.0 * s).round();
        if used > 0.0 && used + w > body.w + (6.0 * s).round() {
            rows += 1.0;
            used = 0.0;
        }
        used += w;
    }
    let actions_h = rows * (ch * 1.6).round() + (rows - 1.0) * (6.0 * s).round();
    let status_lines = status.as_ref().map_or(0, |(m, _)| wrap(m, (body.w / cw).floor().max(4.0) as usize).len().min(3));
    let status_h = if status_lines > 0 { status_lines as f32 * (ch * 1.25).round() + (ch * 0.2).round() } else { 0.0 };
    let footer_h = actions_h + status_h + hint_lines as f32 * (ch * 1.25).round() + (ch * 0.9).round();
    let footer = Rect::new(body.x, (body.bottom() - footer_h).max(tabs_end), body.w, footer_h);
    {
        let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, footer, 0.0);
        f.rule();
        f.gap(0.35);
        if let Some((message, problem)) = &status {
            let color = if *problem { colors.red } else { colors.green };
            let top = f.y;
            for line in wrap(message, f.cols(f.w)).iter().take(status_lines) {
                let line: String = line.iter().map(|(piece, _)| piece.as_str()).collect();
                f.put(f.x, f.y, &line, color, 0, f.w);
                f.y += f.line_height();
            }
            f.y = top + status_h;
        }
        f.buttons(actions);
        f.gap(0.3);
        f.para(&hint, colors.muted, 0, 0.0);
    }

    let area = Rect::new(body.x, tabs_end + (ch * 0.5).round(), body.w, (footer.y - tabs_end - ch).max(0.0));
    // With room for two columns, the stages get their own down the side.
    let split = o.tab == Tab::Guide && area.w > cw * 96.0;
    let main = if split {
        let list_w = (area.w * 0.26).clamp(cw * 26.0, cw * 44.0).round();
        let list = Rect::new(area.x, area.y, list_w, area.h);
        view.list_rect = list;
        let row_h = (ch * 1.55).round();
        let head_h = (ch * 1.6).round();
        view.list_max = (o.stages.len() as f32 * row_h + head_h - list.h).max(0.0);
        if view.reveal {
            let top = o.stage as f32 * row_h + head_h;
            view.list_scroll = scrolled_to(view.list_scroll, (top, row_h), list.h, head_h);
        }
        view.list_scroll = view.list_scroll.clamp(0.0, view.list_max);
        let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, list, view.list_scroll);
        stage_rail(&mut f, o);
        scrollbar(out, list, view.list_scroll, view.list_max, s, colors);
        let x = list.right() + (cw * 2.0).round();
        Rect::new(x, area.y, area.right() - x, area.h)
    } else {
        area
    };

    let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, main, view.scroll);
    let start = f.y;
    // Where the chosen finding landed, to scroll to it.
    let mut chosen = None;
    match o.tab {
        Tab::Guide => chosen = guide_tab(&mut f, o, focused),
        Tab::Findings => chosen = findings_tab(&mut f, o),
        Tab::Description => description_tab(&mut f, o),
    }
    f.gap(0.5);
    let height = f.y - start;
    view.max_scroll = (height - main.h).max(0.0);
    let mut again = false;
    if view.reveal {
        view.reveal = false;
        let at_top = std::mem::take(&mut view.at_top);
        if let Some((top, h)) = chosen.filter(|_| !at_top) {
            let wanted = scrolled_to(view.scroll, (top - start, h.min(main.h)), main.h, 0.0).clamp(0.0, view.max_scroll);
            again = (wanted - view.scroll).abs() > 1.0;
            view.scroll = wanted;
        }
    }
    if view.scroll > view.max_scroll {
        view.scroll = view.max_scroll;
        again = true;
    }
    scrollbar(out, main, view.scroll, view.max_scroll, s, colors);
    again
}

/// Where the change has to be checked out, and anything odd about how it was read.
fn warnings(f: &mut Flow, o: &Opened) {
    let c = f.colors;
    if !o.change.checked_out {
        f.callout("Your working copy is not on this change. Switch to it before testing, then reload.", c.yellow);
        if let Some(command) = &o.change.checkout {
            f.gap(0.35);
            f.buttons(vec![
                button(&format!("Type: {command}"), Click::Type(command.clone())),
                button("Copy", Click::Copy(command.clone())),
            ]);
        }
        f.gap(0.8);
    }
    for note in &o.change.notes {
        f.callout(note, c.cyan);
        f.gap(0.8);
    }
}

/// The stages down the side: done, being gone through, or still to come.
fn stage_rail(f: &mut Flow, o: &Opened) {
    let c = f.colors;
    let row_h = (f.ch * 1.55).round();
    f.put(f.x, f.y + f.ch * 0.4, "STAGES", c.muted, STYLE_BOLD, f.w);
    f.y += (f.ch * 1.6).round();
    for (i, stage) in o.stages.iter().enumerate() {
        let r = Rect::new(f.x, f.y, f.w, row_h - (2.0 * f.s).round());
        let current = i == o.stage;
        if current {
            f.fill(r, mix(c.panel, c.accent, 0.18), 6.0);
        } else if f.hovered(r) {
            f.fill(r, c.raised, 6.0);
        }
        let ty = r.y + (r.h - f.ch) * 0.5;
        let (done, total) = o.stage_counts(i);
        let failed = stage.items.iter().any(|&k| o.session.state(&o.items[k].id) == State::Done(Verdict::Failed));
        let (mark, color) = if failed {
            ("\u{2717}", c.red)
        } else if total > 0 && done == total {
            ("\u{2713}", c.green)
        } else if current {
            ("\u{25cf}", c.accent)
        } else {
            ("\u{25cb}", c.muted)
        };
        f.put(r.x + f.cw * 0.5, ty, mark, color, STYLE_BOLD, f.cw * 2.0);
        let count = if total > 0 { format!("{done}/{total}") } else { String::new() };
        let count_w = count.chars().count() as f32 * f.cw;
        f.put(r.right() - f.cw * 0.5 - count_w, ty, &count, c.muted, 0, count_w + 1.0);
        let color = if current { c.fg } else if total > 0 && done == total { c.muted } else { c.soft };
        f.put(r.x + f.cw * 2.5, ty, &stage.title, color, if current { STYLE_BOLD } else { 0 }, r.w - f.cw * 3.5 - count_w);
        f.hit(r, Click::Stage(i));
        f.y += row_h;
    }
}

/// A heading over a group of things in a stage.
fn group_heading(f: &mut Flow, name: &str) {
    let c = f.colors;
    f.gap(0.6);
    f.put(f.x, f.y, name, c.muted, STYLE_BOLD, f.w);
    f.y += f.line_height();
    f.gap(0.15);
}

/// A clear boundary between reading code, inspecting findings and testing behavior.
fn phase_heading(f: &mut Flow, name: &str) {
    let c = f.colors;
    f.gap(0.6);
    f.rule();
    f.gap(0.5);
    let pad = f.cw;
    let width = f.w - pad * 2.5;
    let lines = wrap(name, f.cols(width)).len();
    let r = Rect::new(f.x, f.y, f.w, lines as f32 * f.line_height() + f.ch * 0.5);
    f.fill(r, mix(c.panel, c.accent, 0.10), 6.0);
    f.fill(Rect::new(r.x, r.y, (3.0 * f.s).round(), r.h), c.accent, 1.0);
    let (x, w) = (f.x, f.w);
    f.x += pad * 1.5;
    f.w = width;
    f.y += f.ch * 0.25;
    f.para(name, c.fg, STYLE_BOLD, 0.0);
    (f.x, f.w) = (x, w);
    f.y = r.bottom();
    f.gap(0.5);
}

/// The stage being gone through: what it is for, its files, what to look at and what to
/// try, then on to the next. Returns where the chosen thing is: (top, height).
fn guide_tab(f: &mut Flow, o: &Opened, focused: bool) -> Option<(f32, f32)> {
    let c = f.colors;
    let stage = o.stages.get(o.stage)?;
    let (done, total) = o.stage_counts(o.stage);
    let heading = format!("STAGE {} OF {}", o.stage + 1, o.stages.len());
    let used = f.put(f.x, f.y, &heading, c.muted, STYLE_BOLD, f.w);
    if total > 0 {
        let x = f.x + used + 2.0 * f.cw;
        let color = if done == total { c.green } else { c.soft };
        f.put(x, f.y, &format!("{done} of {total} done"), color, 0, f.x + f.w - x);
    }
    f.y += f.line_height();
    f.gap(0.2);
    f.para(&stage.title, c.fg, STYLE_BOLD, 0.0);
    f.gap(0.6);

    match stage.kind {
        StageKind::Overview => overview(f, o),
        StageKind::Setup => warnings(f, o),
        StageKind::Finish => finish(f, o),
        _ => {}
    }

    let mut chosen = None;
    let things = o.things(o.stage);
    let mut group = None;
    for (k, &thing) in things.iter().enumerate() {
        let name = match thing {
            Thing::File(_) => "Code",
            Thing::Item(i) => match guide::order(&o.items[i]) {
                0 => "Inspect",
                1 => "PR tests",
                2 => "Try it",
                _ => "Run checks",
            },
        };
        let start = f.y;
        if group != Some(name) {
            group = Some(name);
            phase_heading(f, name);
        }
        let selected = k == o.cursor && o.tab == Tab::Guide;
        match thing {
            Thing::File(i) => {
                file_row(f, o, i, selected);
                if selected && o.file_open {
                    let found = o.findings_in(&o.change.files[i].path);
                    file_detail(f, o, &o.change.files[i], i, &found);
                    f.gap(0.6);
                }
            }
            Thing::Item(i) => {
                item_row(f, o, i, selected);
                if selected {
                    item_detail(f, o, i, focused);
                    f.gap(0.6);
                }
            }
        }
        if selected {
            chosen = Some((start, f.y - start));
        }
    }

    // On to the next stage.
    if let Some(next) = o.stages.get(o.stage + 1) {
        f.gap(1.0);
        let mut buttons = Vec::new();
        if o.stage > 0 {
            buttons.push(button("\u{2039} Back", Click::Stage(o.stage - 1)));
        }
        let label = format!("Next: {} \u{203a}", next.title);
        buttons.push(button(&label, Click::Stage(o.stage + 1)).tone(c.accent, total > 0 && done == total));
        f.buttons(buttons);
    }
    chosen
}

/// The first stage: the change's description and any checkout warnings.
fn overview(f: &mut Flow, o: &Opened) {
    let c = f.colors;
    warnings(f, o);
    let text = o.change.description.trim();
    if text.is_empty() {
        f.para("No description.", c.muted, 0, 0.0);
    } else {
        const SHOWN: usize = 14;
        let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty() && !l.trim_start().starts_with("<!--")).collect();
        for line in lines.iter().take(SHOWN) {
            let heading = line.trim_start().starts_with('#');
            let shown = line.trim_start().trim_start_matches('#').trim_start();
            f.para(shown, if heading { c.fg } else { c.soft }, if heading { STYLE_BOLD } else { 0 }, 0.0);
        }
        if lines.len() > SHOWN {
            f.para(&format!("\u{2026} {} more lines on the Description tab", lines.len() - SHOWN), c.muted, 0, 0.0);
        }
    }
}

/// The last stage: what became of everything, and the verdict.
fn finish(f: &mut Flow, o: &Opened) {
    let c = f.colors;
    let files = &o.change.files;
    let (checks, tests): (Vec<&session::Item>, Vec<&session::Item>) = o.items.iter().partition(|i| i.check);
    let judged = |list: &[&session::Item]| list.iter().filter(|i| matches!(o.session.state(&i.id), State::Done(_))).count();
    for (label, n, total) in [
        ("Files read", o.session.seen_count(files), files.len()),
        ("Findings looked at", judged(&checks), checks.len()),
        ("Steps tried", judged(&tests), tests.len()),
    ] {
        if total > 0 {
            let color = if n == total { c.green } else { c.soft };
            f.para(&format!("{label}: {n} of {total}"), color, 0, 0.0);
        }
    }
    let failed: Vec<usize> = (0..o.items.len()).filter(|&i| o.session.state(&o.items[i].id) == State::Done(Verdict::Failed)).collect();
    if !failed.is_empty() {
        group_heading(f, "FAILED");
        for i in failed {
            let start = f.y;
            let item = &o.items[i];
            f.para(&format!("\u{2717} {}", item.text), c.red, 0, 0.0);
            if let Some(r) = o.session.record(&item.id).filter(|r| !r.note.is_empty()) {
                f.para(&r.note, c.soft, 0, 2.0 * f.cw);
            }
            let r = Rect::new(f.x, start, f.w, f.y - start);
            f.hit(r, Click::Step(i));
        }
    }
    f.gap(0.6);
    let open = o.still_open();
    if o.session.approved() {
        f.callout("You approved this version.", c.green);
    } else if open.is_empty() {
        f.callout("Everything is done.", c.green);
    } else {
        f.callout(&format!("Still open: {}.", open.join(", ")), c.yellow);
    }
    f.gap(0.6);
    let mut buttons = Vec::new();
    if o.change.pull.is_some() && !o.session.approved() {
        let label = if o.confirm_approve { "Really approve?" } else { "Approve" };
        buttons.push(button(label, Click::Approve).tone(c.green, o.confirm_approve));
    }
    if o.change.pull.is_some() {
        buttons.extend(merge_buttons(o, c));
    }
    if o.change.branch.is_some() {
        buttons.push(button("Open pull request", Click::Propose).tone(c.accent, false));
    }
    buttons.push(button("Copy results", Click::CopyResults));
    f.buttons(buttons);
}

/// The two ways to merge, or that it is done or on its way.
fn merge_buttons(o: &Opened, colors: Colors) -> Vec<Button> {
    if o.merged {
        return vec![button("\u{2713} Merged", Click::Merge(Method::Squash)).tone(colors.accent, true)];
    }
    if o.merging {
        return vec![button("Merging\u{2026}", Click::Merge(Method::Squash)).tone(colors.accent, false)];
    }
    [(Method::Squash, "Squash and merge", "Really squash and merge?"), (Method::Commit, "Merge", "Really merge?")]
        .into_iter()
        .map(|(how, label, again)| {
            let armed = o.confirm_merge == Some(how);
            button(if armed { again } else { label }, Click::Merge(how)).tone(colors.accent, armed)
        })
        .collect()
}

/// A file in a stage, one line: its tick, how it changed, its path and its size.
fn file_row(f: &mut Flow, o: &Opened, i: usize, selected: bool) {
    let c = f.colors;
    let file = &o.change.files[i];
    let row_h = (f.ch * 1.55).round();
    let r = Rect::new(f.x, f.y, f.w, row_h - (2.0 * f.s).round());
    if selected {
        f.fill(r, mix(c.panel, c.accent, 0.18), 6.0);
    } else if f.hovered(r) {
        f.fill(r, c.raised, 6.0);
    }
    let ty = r.y + (r.h - f.ch) * 0.5;
    f.hit(r, Click::ChangedFile(i));
    // The tick is a target of its own, on top of the row.
    let tick = Rect::new(r.x, r.y, f.cw * 3.0, r.h);
    let state = o.session.seen(file);
    let (mark, color) = match state {
        Seen::Yes => ("\u{2713}", c.green),
        Seen::Changed => ("\u{21bb}", c.yellow),
        Seen::No => ("\u{25a1}", if f.hovered(tick) { c.fg } else { c.muted }),
    };
    f.put(r.x + f.cw * 0.75, ty, mark, color, STYLE_BOLD, f.cw * 2.0);
    f.hit(tick, Click::Seen(i));
    let (letter, tone) = match file.status {
        Status::Added => ("A", c.green),
        Status::Deleted => ("D", c.red),
        Status::Renamed => ("R", c.cyan),
        Status::Copied => ("C", c.cyan),
        Status::Modified => ("M", c.soft),
    };
    f.put(r.x + f.cw * 3.0, ty, letter, tone, STYLE_BOLD, f.cw * 1.5);
    let found = o.findings_in(&file.path);
    if let Some(level) = found.iter().map(|&k| o.change.report.findings[k].level).min() {
        let dot = (5.0 * f.s).round();
        f.fill(Rect::new(r.x + f.cw * 4.8, r.y + (r.h - dot) * 0.5, dot, dot), c.level(level), 3.0);
    }
    let counts = if file.binary { "binary".to_string() } else { format!("+{} -{}", file.added_count(), file.removed_count()) };
    let counts_w = counts.chars().count() as f32 * f.cw;
    let right = r.right() - f.cw * 0.5;
    f.put(right - counts_w, ty, &counts, c.muted, 0, counts_w + 1.0);
    let path_x = r.x + f.cw * 6.0;
    let color = if selected { c.fg } else if state == Seen::Yes { c.muted } else { c.soft };
    // A long path keeps its end, which is the part that tells files apart.
    let room = f.cols(right - counts_w - f.cw - path_x);
    let chars: Vec<char> = file.path.chars().collect();
    let path: String = if chars.len() > room {
        std::iter::once('\u{2026}').chain(chars[chars.len() + 1 - room.max(2)..].iter().copied()).collect()
    } else {
        file.path.clone()
    };
    f.put(path_x, ty, &path, color, 0, right - counts_w - f.cw - path_x);
    f.y += row_h;
}

/// An item in a stage, one line: its state, how serious, and what it says.
fn item_row(f: &mut Flow, o: &Opened, i: usize, selected: bool) {
    let c = f.colors;
    let item = &o.items[i];
    let row_h = (f.ch * 1.55).round();
    let r = Rect::new(f.x, f.y, f.w, row_h - (2.0 * f.s).round());
    if selected {
        f.fill(r, mix(c.panel, c.accent, 0.18), 6.0);
    } else if f.hovered(r) {
        f.fill(r, c.raised, 6.0);
    }
    let ty = r.y + (r.h - f.ch) * 0.5;
    let state = o.session.state(&item.id);
    let (mark, color) = c.state(state);
    f.put(r.x + f.cw * 0.75, ty, mark, color, STYLE_BOLD, f.cw * 2.0);
    if let Some(level) = item.level {
        let dot = (5.0 * f.s).round();
        f.fill(Rect::new(r.x + f.cw * 3.0, r.y + (r.h - dot) * 0.5, dot, dot), c.level(level), 3.0);
    }
    let label: String = item.text.chars().filter(|c| *c != '\u{60}').collect();
    let color = if selected { c.fg } else if matches!(state, State::Done(_)) { c.muted } else { c.soft };
    f.put(r.x + f.cw * 4.5, ty, &label, color, 0, r.w - f.cw * 5.0);
    f.hit(r, Click::Step(i));
    f.y += row_h;
}

/// The chosen item, unfolded: all it says, the verdict, a note, its commands and why it
/// is there.
fn item_detail(f: &mut Flow, o: &Opened, i: usize, focused: bool) {
    let c = f.colors;
    let item = &o.items[i];
    let (x, w) = (f.x, f.w);
    f.x += f.cw * 2.0;
    f.w -= f.cw * 2.0;
    // Only repeat the title if the row could not show it in full.
    if item.text.chars().filter(|c| *c != '\u{60}').count() > f.cols(w - f.cw * 5.0) {
        f.gap(0.3);
        f.para(&item.text, c.fg, 0, 0.0);
    }

    let state = o.session.state(&item.id);
    let record = o.session.record(&item.id);
    if let State::Stale(verdict) = state {
        let was = format!("It {} on an earlier version of this change. Look again.", match verdict {
            Verdict::Passed => "passed",
            Verdict::Failed => "failed",
            Verdict::Skipped => "was skipped",
        });
        f.gap(0.4);
        f.callout(&was, c.yellow);
    }

    f.gap(0.5);
    let is = |v| state == State::Done(v);
    let (pass, fail) = if item.check { ("\u{2713} Looks fine", "\u{2717} Problem") } else { ("\u{2713} Pass", "\u{2717} Fail") };
    let mut verdicts = vec![
        button(pass, Click::Verdict(Verdict::Passed)).tone(c.green, is(Verdict::Passed)),
        button(fail, Click::Verdict(Verdict::Failed)).tone(c.red, is(Verdict::Failed)),
        button("Skip", Click::Verdict(Verdict::Skipped)).tone(c.soft, is(Verdict::Skipped)),
    ];
    if record.is_some() {
        verdicts.push(button("Clear", Click::Clear));
    }
    f.buttons(verdicts);

    // The note: being typed, written, or offered.
    if let Some(note) = &o.note {
        f.gap(0.5);
        f.field(note, "What went wrong? (enter to save)", focused, Some(Click::EditNote));
    } else if let Some(r) = record {
        f.gap(0.5);
        let start = f.y;
        if r.note.is_empty() {
            f.para("+ add a note", c.muted, 0, 0.0);
        } else {
            f.para(&format!("Note: {}", r.note), c.soft, 0, 0.0);
        }
        let r = Rect::new(f.x, start, f.w, f.y - start);
        f.hit(r, Click::EditNote);
    }

    // Commands and snippets the step quotes.
    for snippet in session::quoted(&item.text) {
        if !snippet.contains(' ') && !session::is_command(&snippet) {
            continue;
        }
        f.gap(0.6);
        let code = c.code;
        let lines = wrap(&snippet, f.cols(f.w - 2.0 * f.cw)).len() as f32;
        let r = Rect::new(f.x, f.y, f.w, (lines * f.line_height() + f.ch * 0.4).round());
        f.fill(r, c.raised, 6.0);
        f.y += (f.ch * 0.2).round();
        let cw = f.cw;
        f.para(&snippet, code, 0, cw);
        f.y = r.bottom() + (f.ch * 0.3).round();
        let mut actions = vec![button("Copy", Click::Copy(snippet.clone()))];
        if session::is_command(&snippet) {
            actions.push(button("Type in terminal", Click::Type(snippet.clone())));
        }
        f.buttons(actions);
    }

    // What led to it. A finding to look at is shown whole; a step lists what it is for.
    if !item.findings.is_empty() {
        f.gap(0.8);
        f.put(f.x, f.y, if item.check { "WHERE" } else { "WHY" }, c.muted, STYLE_BOLD, f.w);
        f.y += f.line_height();
        const SHOWN: usize = 4;
        for &k in item.findings.iter().take(SHOWN) {
            let finding = &o.change.report.findings[k];
            f.gap(0.3);
            if !item.check {
                let start = f.y;
                f.para(&format!("{}  {}", finding.code, finding.title), c.level(finding.level), STYLE_BOLD, 0.0);
                let r = Rect::new(f.x, start, f.w, f.y - start);
                f.hit(r, Click::Finding(k));
            }
            f.place(finding);
            let mut parts: Vec<(&str, &String)> = finding.check.iter().map(|t| ("Look for", t)).collect();
            if item.check {
                parts.extend(finding.note.iter().map(|t| ("Why", t)));
                parts.extend(finding.help.iter().map(|t| ("Fix", t)));
            }
            for (label, text) in parts {
                f.gap(0.2);
                f.para(&format!("{label}: {text}"), c.soft, 0, 0.0);
            }
        }
        if item.findings.len() > SHOWN {
            f.para(&format!("\u{2026} and {} more on the Findings tab", item.findings.len() - SHOWN), c.muted, 0, 0.0);
        }
    }
    (f.x, f.w) = (x, w);
}

/// What the chosen file holds: what was found in it, a tick button, and its diff.
fn file_detail(f: &mut Flow, o: &Opened, file: &FileDiff, i: usize, found: &[usize]) {
    let c = f.colors;
    let (x, w) = (f.x, f.w);
    f.x += f.cw * 2.0;
    f.w -= f.cw * 2.0;
    f.gap(0.3);
    if let Some(old) = &file.old_path {
        f.para(&format!("from {old}"), c.muted, 0, 0.0);
    }
    let state = o.session.seen(file);
    if state == Seen::Changed {
        f.callout("It changed after you read it. Look at it again.", c.yellow);
        f.gap(0.3);
    }
    let tick = match state {
        Seen::Yes => button("\u{2713} Read", Click::Seen(i)).tone(c.green, true),
        _ => button("Mark as read", Click::Seen(i)).tone(c.green, false),
    };
    let line = file.lines().find(|l| l.kind != DiffKind::Context).and_then(|l| l.new_no.or(l.old_no)).unwrap_or(1);
    let mut actions = vec![tick];
    if file.status != Status::Deleted {
        actions.push(button("Open", Click::File(file.path.clone(), line)));
    }
    f.buttons(actions);

    // Lines with something found on them get a mark in the gutter.
    let mut marked: Vec<(u32, Level)> = Vec::new();
    for &k in found {
        let finding = &o.change.report.findings[k];
        if let Some(span) = &finding.span {
            marked.push((span.line, finding.level));
        }
        f.gap(0.3);
        let start = f.y;
        let at = finding.span.as_ref().map(|s| format!("  line {}", s.line)).unwrap_or_default();
        f.para(&format!("{}  {}{at}", finding.code, finding.title), c.level(finding.level), 0, 0.0);
        let r = Rect::new(f.x, start, f.w, f.y - start);
        f.hit(r, Click::Finding(k));
    }
    f.gap(0.5);

    if file.binary {
        f.para("A binary file; open it to look.", c.muted, 0, 0.0);
    }
    const SHOWN: usize = 400;
    let lh = f.line_height();
    let gutter = f.cw * 6.0;
    let total = file.lines().count();
    let mut drawn = 0;
    'hunks: for (h, hunk) in file.hunks.iter().enumerate() {
        if h > 0 {
            f.put(f.x + gutter, f.y, "\u{22ef}", c.muted, 0, f.w - gutter);
            f.y += lh;
        }
        for l in &hunk.lines {
            if drawn == SHOWN {
                break 'hunks;
            }
            drawn += 1;
            if !f.shows(f.y, lh) {
                f.y += lh;
                continue;
            }
            let (sign, tint) = match l.kind {
                DiffKind::Added => ("+", Some(c.green)),
                DiffKind::Removed => ("-", Some(c.red)),
                DiffKind::Context => (" ", None),
            };
            let r = Rect::new(f.x, f.y, f.w, lh);
            if let Some(tint) = tint {
                f.fill(r, mix(c.panel, tint, 0.13), 0.0);
            }
            let number = l.new_no.or(l.old_no).unwrap_or(0);
            let mark = l.new_no.and_then(|n| marked.iter().filter(|(m, _)| *m == n).map(|(_, lv)| *lv).min());
            if let Some(level) = mark {
                f.fill(Rect::new(r.x, r.y, (3.0 * f.s).round(), r.h), c.level(level), 0.0);
            }
            let ty = r.y + (lh - f.ch) * 0.5;
            let number = format!("{number:>5}");
            f.put(r.x, ty, &number, c.muted, 0, gutter);
            let color = match tint {
                Some(t) => mix(t, c.fg, 0.45),
                None => c.soft,
            };
            let text = format!("{sign}{}", l.text.replace('\t', "    "));
            f.put(r.x + gutter, ty, &text, color, 0, r.w - gutter);
            f.y += lh;
        }
    }
    if total > drawn {
        f.gap(0.3);
        f.para(&format!("\u{2026} {} more lines. Open the file to read the rest.", total - drawn), c.muted, 0, 0.0);
    }
    (f.x, f.w) = (x, w);
}

/// Returns where the chosen finding is: (top, height).
fn findings_tab(f: &mut Flow, o: &Opened) -> Option<(f32, f32)> {
    let c = f.colors;
    warnings(f, o);
    if o.change.report.findings.is_empty() {
        f.para("No findings. That is not proof that the change works; it still wants a run.", c.soft, 0, 0.0);
        return None;
    }
    let mut chosen = None;
    for (i, finding) in o.change.report.findings.iter().enumerate() {
        let start = f.y;
        let selected = i == o.finding;
        let color = c.level(finding.level);
        let title = format!("{}  {}", finding.code, finding.title);
        let lines = wrap(&title, f.cols(f.w - 2.0 * f.cw)).len() as f32;
        let head = Rect::new(f.x, f.y, f.w, (lines * f.line_height() + f.ch * 0.4).round());
        if selected {
            f.fill(head, mix(c.panel, c.accent, 0.18), 6.0);
        } else if f.hovered(head) {
            f.fill(head, c.raised, 6.0);
        }
        f.fill(Rect::new(head.x, head.y + 3.0 * f.s, (3.0 * f.s).round(), head.h - 6.0 * f.s), color, 1.0);
        f.y += (f.ch * 0.2).round();
        let cw = f.cw;
        f.para(&title, c.fg, 0, 1.5 * cw);
        f.y = head.bottom();
        f.hit(head, Click::Finding(i));
        if selected && o.unfolded {
            f.gap(0.3);
            f.put(f.x, f.y, level_tag(finding.level), color, STYLE_BOLD, f.w);
            f.y += f.line_height();
            f.place(finding);
            for (label, items) in [("Why", &finding.note), ("Look for", &finding.check), ("Test", &finding.test), ("Fix", &finding.help)] {
                for item in items {
                    f.gap(0.3);
                    f.para(&format!("{label}: {item}"), c.soft, 0, 0.0);
                }
            }
            f.gap(0.8);
            chosen = Some((start, f.y - start));
        } else if selected {
            chosen = Some((start, head.h));
        }
        f.gap(0.2);
    }
    chosen
}

fn description_tab(f: &mut Flow, o: &Opened) {
    let c = f.colors;
    if let Some(url) = &o.change.url {
        f.buttons(vec![button("Open in the browser", Click::Url(url.clone()))]);
        f.gap(0.6);
    }
    if o.change.description.trim().is_empty() {
        f.para("There is no description.", c.muted, 0, 0.0);
        return;
    }
    // Enough for any description a person would read.
    for line in o.change.description.lines().take(600) {
        let heading = line.trim_start().starts_with('#');
        let shown = if heading { line.trim_start().trim_start_matches('#').trim_start() } else { line };
        if shown.trim().is_empty() {
            f.gap(0.6);
        } else {
            let indent = (line.len() - line.trim_start().len()).min(12) as f32 * f.cw;
            f.para(shown.trim_start(), if heading { c.fg } else { c.soft }, if heading { STYLE_BOLD } else { 0 }, indent);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn flat(lines: &[Vec<Piece>]) -> Vec<String> {
        lines.iter().map(|l| l.iter().map(|(t, code)| if *code { format!("[{t}]") } else { t.clone() }).collect()).collect()
    }

    #[test]
    fn wraps_words_and_marks_code() {
        assert_eq!(flat(&wrap("run `php artisan test` now please", 12)), ["run [php]", "[artisan test]", "now please"]);
        assert_eq!(flat(&wrap("a lone ` tick", 40)), ["a lone ` tick"]);
        assert_eq!(flat(&wrap("abcdefghij kl", 4)), ["abcd", "efgh", "ij", "kl"]);
        assert_eq!(flat(&wrap("", 10)), [""]);
        assert_eq!(flat(&wrap("a\x1bb\r\nc", 10)), ["ab c"]);
    }

    #[test]
    fn scrolls_only_as_far_as_needed() {
        assert_eq!(scrolled_to(100.0, (150.0, 20.0), 200.0, 10.0), 100.0);
        assert_eq!(scrolled_to(100.0, (50.0, 20.0), 200.0, 10.0), 40.0);
        assert_eq!(scrolled_to(0.0, (300.0, 20.0), 200.0, 10.0), 120.0);
    }
}