rustimal 0.8.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
//! The page of an opened change: its stages, files, items and findings.

use super::*;

/// How far the whole review is: files read and items judged, over all stages.
pub(super) 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();
}

pub(super) 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();
    // In a short pane the review itself comes first: no progress bar, and no buttons,
    // whose keys still work and which the list of actions holds.
    let compact = short(view.rect.h, ch);
    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);
        if !compact {
            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).key("b")];
    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).key("a").tone(colors.green, on));
        actions.extend(merge_buttons(o, colors));
    }
    if o.change.branch.is_some() {
        actions.push(button("Open pull request", Click::Propose).key("m").tone(colors.accent, false));
    }
    if !o.items.is_empty() {
        actions.push(button("Copy results", Click::CopyResults).key("y"));
    }
    actions.push(button("Actions", Click::Menu).key("?").tone(colors.accent, o.menu.is_some()));
    let mut hints = if focused { review_hints(o) } else { vec![("click", "here, or move here, to use its keys")] };
    if compact && focused && o.note.is_none() {
        // One row: the two that lead to all the others.
        hints = hints.split_off(hints.len().saturating_sub(2));
    }
    let hints_h = hint_rows(&hints, body.w, cw) as f32 * hint_row_height(ch);
    // How many rows the actions take.
    let mut rows = 1.0;
    let mut used = 0.0;
    for b in &actions {
        let w = (button_chars(b) 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 = if compact { 0.0 } else { 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 + hints_h + (ch * 0.9).round();
    let footer = below(body, (body.bottom() - footer_h).max(tabs_end), 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;
        }
        if !compact {
            f.buttons(actions);
        }
        f.gap(0.3);
        f.keys(&hints);
    }

    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.view_h = main.h;
    view.chosen = chosen.map(|(top, h)| (top - start, h));
    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
}

/// The keys that matter for what is chosen; the rest are in the list of actions.
pub(super) fn review_hints(o: &Opened) -> Hints {
    if o.note.is_some() {
        return vec![("enter", "save and go on"), ("esc", "cancel")];
    }
    let arrows = "\u{2191}\u{2193}";
    let stages = ("\u{2190}\u{2192}", "stage");
    let mut hints: Hints = match (o.tab, o.thing()) {
        (Tab::Guide, Some(Thing::File(_))) => {
            vec![(arrows, "read on"), ("enter", "read"), ("x", "fold"), ("o", "open"), stages]
        }
        (Tab::Guide, Some(Thing::Item(i))) => {
            let (pass, fail) = if o.items[i].check { ("fine", "problem") } else { ("pass", "fail") };
            let mut hints = vec![(arrows, "move"), ("enter", pass), ("bksp", fail), ("s", "skip"), stages];
            if o.quoted_here().is_some_and(|(_, command)| command) {
                hints.push(("t", "type command"));
            }
            hints
        }
        (Tab::Guide, None) => vec![(arrows, "move"), ("enter", "continue"), stages],
        (Tab::Findings, _) => vec![(arrows, "choose"), ("enter", "fold"), ("space", "go to step"), ("o", "open")],
        (Tab::Description, _) => vec![(arrows, "scroll"), ("space", "page"), ("tab", "next tab")],
    };
    hints.push(("?", "all actions"));
    hints.push(("esc", if o.tab == Tab::Guide { "terminal" } else { "guide" }));
    hints
}

/// Where the change has to be checked out, and anything odd about how it was read.
pub(super) 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 {
            let keys = o.checkout_keys();
            f.gap(0.35);
            f.buttons(vec![
                button(&format!("Type: {command}"), Click::Type(command.clone())).key(keys.0),
                button("Copy", Click::Copy(command.clone())).key(keys.1),
            ]);
        }
        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.
pub(super) 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.
pub(super) 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.
pub(super) 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).
pub(super) 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.
pub(super) 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.
pub(super) 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).key("a").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).key("m").tone(c.accent, false));
    }
    buttons.push(button("Copy results", Click::CopyResults).key("y"));
    f.buttons(buttons);
}

/// The two ways to merge, or that it is done or on its way.
pub(super) 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, "q", "Squash and merge", "Really squash and merge?"),
        (Method::Commit, "g", "Merge", "Really merge?"),
    ]
    .into_iter()
    .map(|(how, key, label, again)| {
        let armed = o.confirm_merge == Some(how);
        button(if armed { again } else { label }, Click::Merge(how)).key(key).tone(colors.accent, armed)
    })
    .collect()
}

/// A file in a stage, one line: its tick, how it changed, its path and its size.
pub(super) 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.
pub(super) 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.
pub(super) 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)).key("p").tone(c.green, is(Verdict::Passed)),
        button(fail, Click::Verdict(Verdict::Failed)).key("f").tone(c.red, is(Verdict::Failed)),
        button("Skip", Click::Verdict(Verdict::Skipped)).key("s").tone(c.soft, is(Verdict::Skipped)),
    ];
    if record.is_some() {
        verdicts.push(button("Clear", Click::Clear).key("u"));
    }
    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();
        // The keys are for one of them: the one `c` and `t` take.
        let keyed = o.quoted_here().is_some_and(|(text, _)| text == snippet);
        let mut actions = vec![button("Copy", Click::Copy(snippet.clone())).key(if keyed { "c" } else { "" })];
        if session::is_command(&snippet) {
            actions.push(button("Type in terminal", Click::Type(snippet.clone())).key(if keyed { "t" } else { "" }));
        }
        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.
pub(super) 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)).key("v").tone(c.green, true),
        _ => button("Mark as read", Click::Seen(i)).key("v").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)).key("o"));
    }
    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;
            // A long line goes on below itself, so all of it can be read without panning.
            const ROWS: usize = 8;
            let room = f.cols(f.w - gutter - 2.0 * f.cw).max(8);
            let source: Vec<char> = l.text.replace('\t', "    ").chars().collect();
            let rows = source.len().div_ceil(room).clamp(1, ROWS);
            let height = rows as f32 * lh;
            if !f.shows(f.y, height) {
                f.y += height;
                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, height);
            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,
            };
            f.put(r.x + gutter, ty, sign, color, 0, 2.0 * f.cw);
            for row in 0..rows {
                let from = (row * room).min(source.len());
                let to = (from + room).min(source.len());
                let mut shown: String = source[from..to].iter().collect();
                if row + 1 == rows && to < source.len() {
                    shown.pop();
                    shown.push('\u{2026}');
                }
                let x = r.x + gutter + f.cw;
                f.put(x, ty + row as f32 * lh, &shown, color, 0, r.right() - x);
            }
            f.y += height;
        }
    }
    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).
pub(super) 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
}

pub(super) 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())).key("o")]);
        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,
            );
        }
    }
}