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
//! Draws the review panel. It is laid out afresh each frame, and everything that can be
//! clicked records where it landed.

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

mod change;
mod flow;

use change::*;
use flow::*;

/// 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()
}

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 mut right = inner.right();
    {
        let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, inner, 0.0);
        let close = button("\u{2715}", Click::Close);
        let w = f.button_width(&close);
        right -= w;
        f.button_at(Rect::new(right, inner.y, w, header_h), close);
        right -= 6.0 * s;
        f.put(inner.x, inner.y + (header_h - ch) * 0.5, &title, colors.fg, STYLE_BOLD, right - inner.x);
        if !short(inner.h, ch) {
            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 * if short(inner.h, ch) { 0.35 } else { 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(_) => {
            let again = draw_change(ctx, view, body, out);
            draw_menu(ctx, view, rect, out);
            return again;
        }
        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.keys(&[("esc", "back to the list"), ("r", "try again")]);
            }
        }
    }
    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 cw = ctx.glyphs.cell_w;
    let hints: Hints = if g.busy {
        Vec::new()
    } else if g.form.is_some() || g.preview.is_some() {
        vec![("enter", "confirm"), ("esc", "cancel")]
    } else if g.tab == Tab::Branches {
        vec![
            ("\u{2191}\u{2193}", "choose"),
            ("enter", "switch"),
            ("n", "new"),
            ("/", "filter"),
            ("tab", "commits"),
            ("p", "PR"),
            ("c", "copy"),
            ("esc", "terminal"),
        ]
    } else {
        vec![
            ("\u{2191}\u{2193}", "choose"),
            ("space", "select to here"),
            ("enter", "review"),
            ("m", "move"),
            ("u", "undo"),
            ("y", "publish"),
            ("tab", "branches"),
            ("esc", "terminal"),
        ]
    };
    let said = if view.status.is_some() { ch * 3.75 } else { 0.0 };
    let footer_h = said + ch + hint_rows(&hints, body.w, cw) as f32 * hint_row_height(ch);
    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", Control::Accept).key("enter"), action("Cancel", Control::Cancel).key("esc")]);
    } 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", Control::PullRequest).key("p"),
            action("Refresh", Control::Refresh).key("r"),
            action("Fetch", Control::Fetch).key("f"),
        ]);
        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 = below(body, area.bottom() + ch * 0.3, 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();
        }
    }
    if g.busy {
        f.para("Working\u{2026}", c.muted, 0, 0.0);
    } else {
        f.keys(&hints);
    }
    (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 said = if view.status.is_some() { ch * 3.0 } else { 0.0 };
    let footer_h = said + ch + 2.0 * hint_row_height(ch);
    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: Hints = 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);
            vec![("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)]);
            vec![("r", "try again"), ("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),
            ]);
            vec![("enter", "review it"), ("o", "browser"), ("c", "copy link"), ("esc", "back")]
        }
        CreateStage::Form | CreateStage::Confirm | CreateStage::Sending => match &c.proposal {
            None => vec![("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]);
                    vec![("tab", "next field"), ("enter", "next, or a new line in the description"), ("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);
                        vec![("esc", "terminal; it carries on")]
                    } else {
                        f.buttons(vec![
                            press("Create", Press::Accept).key("enter"),
                            press("Back", Press::Cancel).key("esc"),
                        ]);
                        vec![("enter", "create"), ("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 = below(body, area.bottom() + ch * 0.3, 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.keys(&hint);
    (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 hints: Hints = if view.focused {
        vec![("\u{2191}\u{2193}", "choose"), ("enter", "review"), ("type", "to filter"), ("esc", "clear, or terminal")]
    } else {
        vec![("click", "here to type")]
    };
    let rows_h = hint_rows(&hints, body.w, ctx.glyphs.cell_w) as f32 * hint_row_height(ch);
    let footer_h = rows_h + (ch * 0.3).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() - rows_h, body.w, rows_h);
    Flow::new(ctx, out, &mut view.hits, view.mouse, foot, 0.0).keys(&hints);
}

/// Whether there is too little height for everything around a review.
fn short(height: f32, cell: f32) -> bool {
    height < cell * 22.0
}

/// A strip of `body` from `y` down, cut off where `body` ends: in a small pane, nothing
/// may reach into the one below.
fn below(body: Rect, y: f32, h: f32) -> Rect {
    Rect::new(body.x, y, body.w, h.min(body.bottom() - y).max(0.0))
}

/// 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));
}

/// The list of actions, over the review.
fn draw_menu(ctx: &mut Ctx, view: &mut ReviewView, rect: Rect, out: &mut Vec<Quad>) {
    let Screen::Open(o) = &view.screen else { return };
    let Some(menu) = &o.menu else { return };
    let actions = o.menu_actions();
    let (query, selected, mut scroll) = (menu.query.clone(), menu.selected, menu.scroll);
    let colors = Colors::new(ctx);
    let (cw, ch, s) = (ctx.glyphs.cell_w, ctx.glyphs.cell_h, ctx.scale);

    let radius = ctx.config.radius * s;
    out.push(rounded(rect, with_alpha(ctx.palette.background, 0.7), radius, 0.0, [0.0; 4], crate::render::NO_CLIP));
    // A click beside the list puts it away.
    view.hits.push((rect, Click::Menu));

    let pad = (cw * 1.2).round();
    let w = (rect.w - 2.0 * pad).min(cw * 80.0).max(0.0);
    // A short window has no room for how to move about; the list itself matters more.
    let mut moving: Hints = vec![
        ("\u{2191}\u{2193}", "read on"),
        ("j k", "jump"),
        ("\u{2190}\u{2192}", "stage"),
        ("1-9", "stage by number"),
        ("PgUp PgDn", "page"),
        ("Home End", "first, last"),
    ];
    if rect.h < ch * 24.0 {
        moving.clear();
    }
    let inner_w = w - 2.0 * pad;
    let moving_h = if moving.is_empty() { 0.0 } else { hint_rows(&moving, inner_w, cw) as f32 * hint_row_height(ch) };
    let field_h = (ch * 1.8).round();
    let row_h = (ch * 1.55).round();
    let heading_h = (ch * 1.6).round();
    let fixed = pad * 2.0 + field_h + (ch * 1.3).round() + moving_h + hint_row_height(ch);

    // Where each row falls in the list, headings included.
    let mut places = Vec::new();
    let mut total = 0.0;
    let mut group = "";
    for a in &actions {
        if a.group != group {
            group = a.group;
            total += heading_h;
        }
        places.push(total);
        total += row_h;
    }
    let top = rect.y + (rect.h * 0.07).max(pad).round();
    let room = (rect.bottom() - pad - top - fixed).max(row_h);
    let list_h = total.max(row_h).min(room);
    let card = Rect::new(rect.x + ((rect.w - w) * 0.5).round(), top, w, (fixed + list_h).min(rect.bottom() - top));
    out.push(rounded(
        card,
        colors.panel,
        12.0 * s,
        s.max(1.0),
        mix(colors.panel, colors.accent, 0.55),
        crate::render::NO_CLIP,
    ));
    view.hits.push((card, Click::Inert));

    let inner = Rect::new(card.x + pad, card.y + pad, inner_w, card.h - 2.0 * pad);
    let list_top = inner.y + field_h + (ch * 0.5).round();
    {
        let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, inner, 0.0);
        f.field(&query, "Type to find an action", view.focused, None);
    }
    let list = Rect::new(inner.x, list_top, inner.w, list_h);
    if let Some(&at) = places.get(selected) {
        scroll = scrolled_to(scroll, (at, row_h), list.h, heading_h);
    }
    scroll = scroll.clamp(0.0, (total - list.h).max(0.0));
    {
        let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, list, scroll);
        let start = f.y;
        if actions.is_empty() {
            f.put(f.x + f.cw, f.y + f.ch * 0.25, "Nothing matches", colors.muted, 0, f.w);
        }
        let mut group = "";
        for (i, (a, at)) in actions.iter().zip(&places).enumerate() {
            if a.group != group {
                group = a.group;
                let y = start + at - heading_h + ch * 0.45;
                f.put(f.x, y, &group.to_uppercase(), colors.muted, STYLE_BOLD, f.w);
            }
            let r = Rect::new(f.x, start + at, f.w, row_h - (2.0 * s).round());
            if i == selected {
                f.fill(r, mix(colors.panel, colors.accent, 0.2), 6.0);
            } else if f.hovered(r) {
                f.fill(r, colors.raised, 6.0);
            }
            let ty = r.y + (r.h - ch) * 0.5;
            let key_w = a.key.chars().count() as f32 * cw;
            if !a.key.is_empty() {
                f.put(r.right() - cw - key_w, ty, &a.key, colors.muted, 0, key_w + 1.0);
            }
            let color = if i == selected { colors.fg } else { colors.soft };
            f.put(r.x + cw, ty, &a.label, color, 0, (r.w - key_w - cw * 3.0).max(0.0));
            f.hit(r, Click::MenuRow(i));
        }
    }
    scrollbar(out, list, scroll, (total - list.h).max(0.0), s, colors);
    let foot =
        Rect::new(inner.x, list.bottom() + (ch * 0.4).round(), inner.w, (card.bottom() - list.bottom()).max(0.0));
    {
        let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, foot, 0.0);
        f.rule();
        f.gap(0.4);
        if !moving.is_empty() {
            f.keys(&moving);
        }
        f.keys(&[("enter", "run"), ("esc", "close")]);
    }
    if let Some(menu) = view.opened().and_then(|o| o.menu.as_mut()) {
        menu.scroll = scroll;
    }
}

#[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);
    }
}