croft-software 0.2.232

VSCode-style TUI written in Rust
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
//! Pane and overlay chrome for a theme that draws layered surfaces instead of
//! line boxes ([`Theme::surfaces`], Croft Loch).
//!
//! A pane keeps its `Borders::ALL` inset under every theme, so its inner
//! rect, its hit targets and every test of where content lands are the same
//! with or without surfaces. Only what the frame cells show changes: padding
//! in the pane's surface tone, a hairline seam where two surfaces meet (drawn
//! by the workbench, which knows the layout), and a rule along the focused
//! pane's top edge. Overlays get a card edge and a one-cell shadow in place
//! of the gradient box.

use ratatui::{
    buffer::{Buffer, Cell},
    layout::Rect,
    style::{Color, Modifier, Style},
    symbols::border,
    text::Span,
    widgets::{Block, Borders},
};

use crate::gradient::{GRAD_TL, GRAD_TR, lerp_rgb, rgb_color};
use crate::theme::Theme;
use crate::theme::{Tones, tones};

/// The selected row's accent bar: a quarter-cell stripe on the row's left
/// edge, the same mark the activity bar puts beside the active view.
pub const ROW_BAR: &str = "\u{258e}";

/// The warm amber a `surfaces` theme tints find matches toward: the hue
/// every editor uses for "found here", softened from croft's old #ffd74a so
/// a tint of it sits calmly on the canvas. It is a fill, never an ink, and
/// is kept clear of the accent so teal still means focus alone.
pub const MATCH_AMBER: (u8, u8, u8) = (0xe0, 0xb0, 0x4a);

/// How far a find match's fill moves from its surface toward
/// [`MATCH_AMBER`]: enough to read as a mark on black, little enough that
/// body text on it keeps well past 4.5:1.
const MATCH_SOFT: f32 = 0.30;

/// [`MATCH_SOFT`] for the current match (the one the caret, a Find Next or
/// the selected search result points at): the same amber a clear step
/// stronger, so it stands out among its siblings by weight rather than by a
/// second hue, and the strong ink still reads on it at better than 4.5:1.
const MATCH_ACTIVE: f32 = 0.50;

/// The WCAG floor a match's ink must clear on its tint before it is kept.
const MATCH_MIN_CONTRAST: f64 = 4.5;

/// How far a tint eases back toward its surface, per step, when even the
/// strong ink would not read on it (a current match over a selection band).
const MATCH_EASE_STEP: f32 = 0.05;

/// Restyle a cell (or span) `style` as a find match on a `surfaces` theme,
/// the one definition the editor, the diff, a rendered log, the terminal and
/// the Search view share so matches read alike everywhere.
///
/// The cell's own background is warmed toward [`MATCH_AMBER`], softly for
/// every match and a clear step further for the `active` one, and its own
/// ink is kept, so a match in code still reads in its syntax colour, unless
/// that ink would fall under 4.5:1 on the tint (a comment, a muted preview),
/// when it lifts to the strong ink. Over an already bright surface (the
/// selection, a selected row's band) where even the strong ink would fall
/// short, the tint eases back until it reads. Modifiers are left as they
/// are: a match needs no bold to be found.
///
/// A handful of float operations per matched cell, with no allocation, so
/// it is safe on the render path.
pub fn match_style(style: Style, t: Tones, theme: Theme, active: bool) -> Style {
    use crate::theme::contrast_ratio;
    let base = cell_rgb(style.bg.unwrap_or(Color::Reset), theme, t.canvas);
    let own = style.fg.map(|c| cell_rgb(c, theme, t.text));
    let mut mix = if active { MATCH_ACTIVE } else { MATCH_SOFT };
    loop {
        let fill = lerp_rgb(base, MATCH_AMBER, mix);
        if let Some(fg) = own
            && contrast_ratio(fg, fill) >= MATCH_MIN_CONTRAST
        {
            return style.bg(rgb_color(fill)).fg(rgb_color(fg));
        }
        if mix <= 0.0 || contrast_ratio(t.strong, fill) >= MATCH_MIN_CONTRAST {
            return style.bg(rgb_color(fill)).fg(t.strong());
        }
        mix -= MATCH_EASE_STEP;
    }
}

/// How many steps [`legible_ink`] takes from an ink to the strong one.
const LEGIBLE_STEPS: u8 = 10;

/// `fg` as it must be drawn on `bg` to read at 4.5:1 on a `surfaces`
/// theme: unchanged when it already does, else eased toward the strong
/// ink one step at a time until it does, so a syntax colour on a tinted
/// fill (a diff row, its changed characters) keeps as much of its hue as
/// the fill allows, and only a hopeless one becomes the strong ink, as
/// [`match_style`] lifts a match's ink. A few float operations per call
/// and no allocation; callers on the render path call it once per run of
/// one ink, not per cell.
pub fn legible_ink(fg: (u8, u8, u8), bg: (u8, u8, u8), t: Tones) -> (u8, u8, u8) {
    use crate::theme::contrast_ratio;
    let mut ink = fg;
    for step in 1..=LEGIBLE_STEPS {
        if contrast_ratio(ink, bg) >= MATCH_MIN_CONTRAST {
            break;
        }
        ink = lerp_rgb(fg, t.strong, f32::from(step) / f32::from(LEGIBLE_STEPS));
    }
    ink
}

/// Paint `row` as the selected row of a list on a `surfaces` theme: the
/// band over every cell, and, when the list has the keyboard, the accent
/// [`ROW_BAR`] in its first cell (a pad cell or the card's left edge). The
/// row's text keeps its colours. Without focus the band is the hairline
/// tone, as VS Code greys an inactive selection.
pub fn paint_selected_row(
    buf: &mut Buffer,
    row: Rect,
    t: Tones,
    base: (u8, u8, u8),
    focused: bool,
) {
    let row = row.intersection(buf.area);
    if row.width == 0 || row.height == 0 {
        return;
    }
    let band = rgb_color(selected_row_fill(t, base, focused));
    buf.set_style(row, Style::default().bg(band));
    if focused {
        for y in row.top()..row.bottom() {
            let cell = &mut buf[(row.x, y)];
            cell.set_symbol(ROW_BAR);
            cell.set_fg(t.accent());
            cell.set_bg(band);
        }
    }
}

/// The fill [`paint_selected_row`] lays on surface `base`: the accent band
/// while the list has the keyboard, a neutral grey step without it. For a
/// row that paints a mark of its own over the band (a search match's tint)
/// and so needs to know what it sits on.
pub fn selected_row_fill(t: Tones, base: (u8, u8, u8), focused: bool) -> (u8, u8, u8) {
    if focused {
        lerp_rgb(base, t.accent, 0.24)
    } else {
        lerp_rgb(base, t.lift, 0.07)
    }
}

/// A key-binding hint as keycaps on a `surfaces` theme: each key of a chord
/// in its own chip, the chord's keys joined by a muted `+`, chords a space
/// apart. `row` is the fill of the row the caps sit on, so a selected row's
/// chips lift off its band rather than the card.
///
/// The `+` is muted, not faint: on the selected row's band a faint `+`
/// falls to about 1.2:1 and `Ctrl+K Ctrl+L` reads as four loose keys
/// rather than two chords, and muted keeps it past 3:1 on both the band
/// and the card. A selected row's labels take the body ink so the chord
/// still reads past 4.5:1 on chips lifted off the brighter band; an idle
/// row's stay muted, so the keys recede behind the command names.
pub fn keycap_spans(hint: &str, t: Tones, row: Color, selected: bool) -> Vec<Span<'static>> {
    let cap = Style::default()
        .bg(t.keycap_on(row))
        .fg(if selected { t.text() } else { t.muted() });
    let sep = Style::default().fg(t.muted()).bg(row);
    let mut out = Vec::new();
    for (i, chord) in hint.split(' ').filter(|c| !c.is_empty()).enumerate() {
        if i > 0 {
            out.push(Span::styled(" ", sep));
        }
        for (j, key) in chord_keys(chord).into_iter().enumerate() {
            if j > 0 {
                out.push(Span::styled("+", sep));
            }
            out.push(Span::styled(format!(" {key} "), cap));
        }
    }
    out
}

/// Iterator over the keys of one chord without allocating (`Ctrl+Shift+P` →
/// `Ctrl`, `Shift`, `P`; `Ctrl++` → `Ctrl`, `+`).
fn chord_key_iter(chord: &str) -> impl Iterator<Item = &str> {
    let mut rest = chord;
    std::iter::from_fn(move || {
        let first = rest.chars().next()?;
        let skip = first.len_utf8();
        match rest[skip..].find('+') {
            Some(k) => {
                let key = &rest[..skip + k];
                rest = &rest[skip + k + 1..];
                Some(key)
            }
            None => {
                let key = rest;
                rest = "";
                Some(key)
            }
        }
    })
}

/// The keys of one chord: `Ctrl+Shift+P` is Ctrl, Shift and P, and a `+`
/// that is itself the key (`Ctrl++`) stays a key.
pub fn chord_keys(chord: &str) -> Vec<&str> {
    chord_key_iter(chord).collect()
}

/// Display width in terminal cells that [`keycap_spans`] / [`paint_keycaps`]
/// take for `hint`, without allocating (#2062).
pub fn keycap_width(hint: &str) -> u16 {
    let mut width = 0usize;
    for (i, chord) in hint.split(' ').filter(|c| !c.is_empty()).enumerate() {
        if i > 0 {
            width += 1;
        }
        for (j, key) in chord_key_iter(chord).enumerate() {
            if j > 0 {
                width += 1;
            }
            width += unicode_width::UnicodeWidthStr::width(key) + 2;
        }
    }
    width as u16
}

/// Paint [`keycap_spans`] directly into `buf` at `(x, y)` without allocating
/// `Span`s or `String`s (#2062).
pub fn paint_keycaps(
    buf: &mut Buffer,
    x: u16,
    y: u16,
    hint: &str,
    t: Tones,
    row: Color,
    selected: bool,
) {
    if y < buf.area.top() || y >= buf.area.bottom() {
        return;
    }
    let cap = Style::default()
        .bg(t.keycap_on(row))
        .fg(if selected { t.text() } else { t.muted() });
    let sep = Style::default().fg(t.muted()).bg(row);
    let right = buf.area.right();
    let mut cx = x;
    let mut put = |s: &str, style: Style| {
        if cx < right {
            let (nx, _) = buf.set_stringn(cx, y, s, usize::from(right - cx), style);
            cx = nx;
        }
    };
    for (i, chord) in hint.split(' ').filter(|c| !c.is_empty()).enumerate() {
        if i > 0 {
            put(" ", sep);
        }
        for (j, key) in chord_key_iter(chord).enumerate() {
            if j > 0 {
                put("+", sep);
            }
            put(" ", cap);
            put(key, cap);
            put(" ", cap);
        }
    }
}

/// A cell colour as bytes for blending: RGB as is, the named and indexed
/// ANSI colours through the theme's palette, the terminal default as the
/// canvas (`bg`) or body text (`fg`).
fn cell_rgb(c: Color, theme: Theme, fallback: (u8, u8, u8)) -> (u8, u8, u8) {
    known_rgb(c, theme).unwrap_or(fallback)
}

/// The bytes a cell colour stands for, where croft knows them: RGB as is,
/// the named and the first sixteen indexed colours through the theme's ANSI
/// palette. `None` for the terminal default and the 256-colour indexes,
/// whose bytes only the terminal knows: [`cell_rgb`] puts a fallback there,
/// and [`dim_backdrop`] leaves such an underline colour as it is.
fn known_rgb(c: Color, theme: Theme) -> Option<(u8, u8, u8)> {
    let ansi = theme.ansi();
    Some(match c {
        Color::Rgb(r, g, b) => (r, g, b),
        Color::Black => ansi[0],
        Color::Red => ansi[1],
        Color::Green => ansi[2],
        Color::Yellow => ansi[3],
        Color::Blue => ansi[4],
        Color::Magenta => ansi[5],
        Color::Cyan => ansi[6],
        Color::Gray => ansi[7],
        Color::DarkGray => ansi[8],
        Color::LightRed => ansi[9],
        Color::LightGreen => ansi[10],
        Color::LightYellow => ansi[11],
        Color::LightBlue => ansi[12],
        Color::LightMagenta => ansi[13],
        Color::LightCyan => ansi[14],
        Color::White => ansi[15],
        Color::Indexed(i) if i < 16 => ansi[usize::from(i)],
        _ => return None,
    })
}

/// Recede everything outside `keep` behind a modal on a `surfaces` theme,
/// the scrim Zed, Linear and Raycast draw under a command bar: each cell's
/// text sinks most of the way into its own background and the background
/// darkens a step, so the card is the only thing at full contrast. A no-op
/// on a boxed theme.
///
/// A coloured underline sinks with the text: the active tab's accent
/// underline (or a diagnostic's squiggle) is drawn in the cell's underline
/// colour, not its ink, and left alone it would stay full-strength teal
/// behind the palette, a second focus mark competing with the card's. An
/// underline in the terminal default already follows the sunk ink.
pub fn dim_backdrop(buf: &mut Buffer, keep: Rect, theme: Theme) {
    let Some(t) = tones(theme) else {
        return;
    };
    let area = buf.area;
    let sink = if theme.is_light() { 0.0 } else { 0.30 };
    for y in area.top()..area.bottom() {
        for x in area.left()..area.right() {
            if keep.contains(ratatui::layout::Position { x, y }) {
                continue;
            }
            let cell = &mut buf[(x, y)];
            let bg = cell_rgb(cell.bg, theme, t.canvas);
            let fg = cell_rgb(cell.fg, theme, t.text);
            let bg2 = lerp_rgb(bg, (0, 0, 0), sink);
            cell.set_fg(rgb_color(lerp_rgb(fg, bg2, 0.58)));
            if let Some(under) = known_rgb(cell.underline_color, theme) {
                cell.underline_color = rgb_color(lerp_rgb(under, bg2, 0.58));
            }
            cell.set_bg(rgb_color(bg2));
            cell.modifier.remove(Modifier::BOLD);
        }
    }
}

/// Which side of its cells a seam hugs. The glyphs are one-eighth blocks, so
/// a seam sits on the cell boundary instead of the cell's middle, and two
/// panes' seams on either side of one boundary read as a single line.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Edge {
    Top,
    Bottom,
    Left,
    Right,
}

impl Edge {
    fn glyph(self) -> &'static str {
        match self {
            Edge::Top => "\u{2594}",
            Edge::Bottom => "\u{2581}",
            Edge::Left => "\u{258f}",
            Edge::Right => "\u{2595}",
        }
    }
}

/// One-eighth blocks on the outer edge of a frame: a seam on the cell
/// boundary instead of a line through the cell's middle. The corners reuse
/// the edge glyphs; at an eighth of a cell the missing corner pixel is not
/// visible.
pub const HAIRLINE: border::Set = border::Set {
    top_left: "\u{2594}",
    top_right: "\u{2594}",
    bottom_left: "\u{2581}",
    bottom_right: "\u{2581}",
    vertical_left: "\u{258f}",
    vertical_right: "\u{2595}",
    horizontal_top: "\u{2594}",
    horizontal_bottom: "\u{2581}",
};

/// The rule a stacked side-bar section draws between itself and the next
/// (Outline, Timeline, Open Editors, Dependencies, the agent lane, the
/// commit graph): the dim line in `style` on a boxed theme, a hairline under
/// `surfaces`.
pub fn section_block<'a>(theme: Theme, borders: Borders, style: Style) -> Block<'a> {
    match theme.surfaces() {
        Some(s) => Block::default()
            .borders(borders)
            .border_set(HAIRLINE)
            .border_style(Style::default().fg(s.hairline())),
        None => Block::default().borders(borders).border_style(style),
    }
}

/// The codicon chevrons a `surfaces` theme folds rows with (`chevron-right`,
/// `chevron-down`), the pair the panel's own toggles already draw, so the
/// side bar and the panel speak one icon family.
pub const CHEVRON_FOLDED: char = '\u{eab6}';
pub const CHEVRON_UNFOLDED: char = '\u{eab4}';

/// The chevron a folding row shows: the codicon pair under `surfaces`, the
/// geometric triangles ([`crate::icons::CHEVRON_OPEN`]) a boxed theme has
/// always drawn. Both are one cell wide, so nothing after them moves.
pub fn chevron(theme: Theme, open: bool) -> char {
    match (theme.surfaces().is_some(), open) {
        (true, true) => CHEVRON_UNFOLDED,
        (true, false) => CHEVRON_FOLDED,
        (false, true) => crate::icons::CHEVRON_OPEN,
        (false, false) => crate::icons::CHEVRON_CLOSED,
    }
}

/// The boxed themes' section-header inks: a dim chevron and a near-white
/// bold label, shared by every stacked section so they can never drift.
const SECTION_DIM: Color = Color::Rgb(0x60, 0x68, 0x78);
const SECTION_LABEL: Color = Color::Rgb(0xE8, 0xEE, 0xF8);

/// Paint the header of a stacked side-bar section (Outline, Timeline,
/// Dependencies, Open Editors, the agent lane, the commit graph) on `row`:
/// the chevron, the label and any `tail` spans after it (a count).
///
/// On a boxed theme this is the dim triangle and the bold near-white label
/// those sections have always drawn. Under `surfaces` the header steps back
/// a level from the view title: a muted codicon chevron, the label muted
/// while folded and body text while open (calm, so the rows beneath carry
/// the weight), and the pointer lifts the row the way it lifts a tree row,
/// with the label taking the strong ink. `row` is the clickable header row;
/// its last cell is the pane's right padding and stays out of the lift.
pub fn paint_section_header(
    buf: &mut Buffer,
    row: Rect,
    theme: Theme,
    open: bool,
    label: &str,
    tail: Vec<Span<'static>>,
    hovered: bool,
) {
    use ratatui::text::Line;
    use ratatui::widgets::{Paragraph, Widget};
    let row = row.intersection(buf.area);
    if row.width == 0 || row.height == 0 {
        return;
    }
    let chev = chevron(theme, open);
    let Some(t) = tones(theme) else {
        let mut spans = vec![
            Span::styled(
                format!("{chev} "),
                Style::default().fg(theme.ui(SECTION_DIM)),
            ),
            Span::styled(
                label.to_string(),
                Style::default()
                    .fg(theme.ui(SECTION_LABEL))
                    .add_modifier(Modifier::BOLD),
            ),
        ];
        spans.extend(tail);
        Paragraph::new(Line::from(spans)).render(row, buf);
        return;
    };
    if hovered {
        let lift = Rect {
            width: row.width.saturating_sub(1).max(1),
            ..row
        };
        buf.set_style(lift, Style::default().bg(t.hover_on(t.chrome)));
    }
    let label_fg = if hovered {
        t.strong()
    } else if open {
        t.text()
    } else {
        t.muted()
    };
    let mut spans = vec![
        Span::styled(
            format!("{chev} "),
            Style::default().fg(if hovered { t.text() } else { t.muted() }),
        ),
        Span::styled(
            label.to_string(),
            Style::default().fg(label_fg).add_modifier(Modifier::BOLD),
        ),
    ];
    spans.extend(tail);
    buf.set_line(row.x, row.y, &Line::from(spans), row.width);
}

/// A text field on a `surfaces` theme: `rect`'s inner cells on the raised
/// tone, ringed by a one-eighth-block outline in `edge` that hugs them from
/// the frame cells around (`▁` above, `▔` below, `▕` and `▏` at the sides),
/// so the field reads as a recessed well with a crisp edge rather than a
/// line box. The corners stay blank: at an eighth of a cell the missing
/// corner pixel is not visible. The inner rect is a bordered block's, so
/// text and caret land exactly where they would inside a line box.
pub fn paint_field(buf: &mut Buffer, rect: Rect, t: Tones, edge: Color) {
    if rect.width < 2 || rect.height < 2 || rect.intersection(buf.area) != rect {
        return;
    }
    let inner = Rect::new(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2);
    buf.set_style(inner, Style::default().bg(t.raised()));
    let (right, bottom) = (rect.right() - 1, rect.bottom() - 1);
    for x in rect.x..=right {
        let corner = x == rect.x || x == right;
        for (y, glyph) in [(rect.y, "\u{2581}"), (bottom, "\u{2594}")] {
            let cell = &mut buf[(x, y)];
            cell.set_symbol(if corner { " " } else { glyph });
            cell.set_fg(edge);
        }
    }
    for y in inner.top()..inner.bottom() {
        for (x, glyph) in [(rect.x, "\u{2595}"), (right, "\u{258f}")] {
            let cell = &mut buf[(x, y)];
            cell.set_symbol(glyph);
            cell.set_fg(edge);
        }
    }
}

/// A button's face on a `surfaces` theme: one row, `area`'s middle (the row
/// its label sits on), filled with `fill` and ended by half-block caps (`▐`
/// on the left, `▌` on the right) on the ends that are `round`, so it reads
/// as a calm pill. The rows above and below stay the surface it sits on: a
/// three-row slab with half-block bands and quadrant corners read as a lumpy
/// cross, its middle row wider than the bands, and terminals leave a thin
/// gap between a band and the row under it. An unrounded end is where a
/// split button's halves join, so the face runs to the cell edge there.
/// The click target stays the full `area`; only what is painted is calmer.
/// Returns the face's cells between the caps, where a label centres.
pub fn paint_soft_button(
    buf: &mut Buffer,
    area: Rect,
    fill: Color,
    round_left: bool,
    round_right: bool,
) -> Rect {
    let area = area.intersection(buf.area);
    if area.width == 0 || area.height == 0 {
        return Rect::default();
    }
    for y in area.top()..area.bottom() {
        for x in area.left()..area.right() {
            buf[(x, y)].set_symbol(" ");
        }
    }
    // Caps only where a face cell is left between them: a sliver of a
    // button is a plain slab rather than two caps with nothing inside.
    let (left, right) = (u16::from(round_left), u16::from(round_right));
    let (left, right) = if area.width > left + right {
        (left, right)
    } else {
        (0, 0)
    };
    let y = area.y + area.height / 2;
    let face = Rect::new(area.x + left, y, area.width - left - right, 1);
    buf.set_style(face, Style::default().bg(fill));
    if left > 0 {
        buf[(area.x, y)].set_symbol("\u{2590}").set_fg(fill);
    }
    if right > 0 {
        buf[(area.right() - 1, y)]
            .set_symbol("\u{258c}")
            .set_fg(fill);
    }
    face
}

/// The block a pane renders under a `surfaces` theme: the same one-cell
/// inset as a bordered box, painted as padding in `fill`, which also becomes
/// the background of everything the pane leaves unpainted.
pub fn pane_block<'a>(fill: Color) -> Block<'a> {
    Block::default()
        .borders(Borders::ALL)
        .border_set(border::EMPTY)
        .style(Style::default().bg(fill))
}

/// The tone a pane fills its frame with: the chrome surface for the side
/// bars, the code canvas for the editor and the panel views.
pub fn pane_fill(theme: Theme, chrome: bool) -> Color {
    match theme.surfaces() {
        Some(s) if chrome => s.chrome(),
        _ => theme.editor_bg(),
    }
}

/// The frame a side-bar or panel view renders: the bordered box in
/// `border_style` on a boxed theme, padding in the view's surface tone under
/// `surfaces` (`chrome` for the side bars, the canvas otherwise). The inner
/// rect is the same either way.
pub fn view_block<'a>(theme: Theme, chrome: bool, border_style: Style) -> Block<'a> {
    match theme.surfaces() {
        Some(_) => pane_block(pane_fill(theme, chrome)),
        None => Block::default()
            .borders(Borders::ALL)
            .border_style(border_style),
    }
}

/// Mark a focused view: the focus rule under `surfaces`, the gradient box on
/// a boxed brand theme (`focus_gradient`), nothing otherwise, where the
/// border colour already says it. Returns true when the gradient box went
/// over the top row, so a caller with a title there re-stamps it.
pub fn paint_view_focus(
    buf: &mut Buffer,
    area: Rect,
    theme: Theme,
    focused: bool,
    focus_gradient: bool,
) -> bool {
    if !focused {
        return false;
    }
    if theme.surfaces().is_some() {
        paint_focus_rule(buf, area, theme);
        false
    } else if focus_gradient {
        crate::gradient::paint_gradient_box(buf, area);
        true
    } else {
        false
    }
}

/// A frame cell a seam or rule may draw over: blank padding or a line glyph
/// from a frame. Titles, buttons, badges and gauges are left alone.
fn is_frame_cell(cell: &Cell) -> bool {
    matches!(
        cell.symbol(),
        " " | "\u{2500}"
            | "\u{2502}"
            | "\u{250c}"
            | "\u{2510}"
            | "\u{2514}"
            | "\u{2518}"
            | "\u{256d}"
            | "\u{256e}"
            | "\u{2570}"
            | "\u{256f}"
            | "\u{2581}"
            | "\u{2594}"
            | "\u{258f}"
            | "\u{2595}"
    )
}

/// Draw `glyph` along row `y` from `x` for `width` cells, colouring the
/// `i`th with `color(i)`, over the frame cells only. A lone space between
/// two painted characters is a title's word gap (`REMOTE EXPLORER`), not
/// padding, so it stays a space.
///
/// Each cell is judged by what the row held before any of it was painted:
/// its neighbours' frame flags ride along (#2062), the left one kept from
/// before it was painted and the right one not painted yet, so a seam
/// allocates nothing.
fn paint_edge_row(
    buf: &mut Buffer,
    x: u16,
    y: u16,
    width: u16,
    glyph: &str,
    color: impl Fn(u16) -> Color,
) {
    let frame_at = |buf: &Buffer, i: u16| i < width && is_frame_cell(&buf[(x + i, y)]);
    let mut left = false;
    let mut here = frame_at(buf, 0);
    for i in 0..width {
        let right = frame_at(buf, i + 1);
        let word_gap = i > 0 && i + 1 < width && !left && !right && buf[(x + i, y)].symbol() == " ";
        if here && !word_gap {
            let cell = &mut buf[(x + i, y)];
            cell.set_symbol(glyph);
            cell.set_fg(color(i));
        }
        left = here;
        here = right;
    }
}

/// Write `glyph` into the one cell at (`x`, `y`) with `style` laid over the
/// cell's own, as a one-cell `Paragraph` of that glyph and style does, but
/// without building one: no string, no lines or spans (#2062). A cell off
/// the buffer is left alone, as the paragraph would leave it.
pub fn paint_glyph(buf: &mut Buffer, x: u16, y: u16, glyph: char, style: Style) {
    if let Some(cell) = buf.cell_mut((x, y)) {
        cell.set_style(style);
        cell.set_char(glyph);
    }
}

/// Draw a seam along `edge` of every frame cell in `rect`, in `color` over
/// each cell's own background. A row of text on the seam's row (the
/// scrubber on the editor's bottom edge) keeps its word gaps, as under the
/// focus rule.
pub fn paint_seam(buf: &mut Buffer, rect: Rect, edge: Edge, color: Color) {
    let rect = rect.intersection(buf.area);
    for y in rect.top()..rect.bottom() {
        paint_edge_row(buf, rect.x, y, rect.width, edge.glyph(), |_| color);
    }
}

/// The brand gradient's colour at cell `i` of `n` (teal to orange), or the
/// flat accent on a theme without the gradient. Kept for the boxed brand
/// theme's callers; a `surfaces` theme draws its rules with [`lip_color`].
#[allow(dead_code)]
fn rule_color(theme: Theme, i: u16, n: u16) -> Color {
    if theme.gradient() {
        let t = if n > 1 {
            f32::from(i) / f32::from(n - 1)
        } else {
            0.0
        };
        rgb_color(lerp_rgb(GRAD_TL, GRAD_TR, t))
    } else {
        theme.accent()
    }
}

/// The accent lip's colour at cell `i` of `n`: the accent at the leading
/// edge easing into `rest` across the first two fifths of the run (never
/// fewer than six cells), so a focused pane or a card is marked at its
/// corner and the rest of the edge is a quiet line. One hue, one meaning:
/// the accent says "this has the keyboard".
fn lip_color(accent: (u8, u8, u8), rest: (u8, u8, u8), i: u16, n: u16) -> Color {
    let span = (f32::from(n) * 0.4).max(6.0);
    let t = (f32::from(i) / span).clamp(0.0, 1.0);
    let eased = t * t * (3.0 - 2.0 * t);
    rgb_color(lerp_rgb(accent, rest, eased))
}

/// The focused pane's marker under a `surfaces` theme: a rule along the top
/// edge of its frame row, the accent easing into the hairline, broken
/// wherever the pane painted a title or a button there. It stands where VS
/// Code puts `tab.activeBorderTop`, and replaces the whole-pane focus box.
pub fn paint_focus_rule(buf: &mut Buffer, area: Rect, theme: Theme) {
    let area = area.intersection(buf.area);
    if area.height < 2 {
        return;
    }
    let Some(t) = tones(theme) else {
        paint_edge_row(buf, area.x, area.y, area.width, Edge::Top.glyph(), |i| {
            rule_color(theme, i, area.width)
        });
        return;
    };
    paint_edge_row(buf, area.x, area.y, area.width, Edge::Top.glyph(), |i| {
        lip_color(t.accent, t.hairline, i, area.width)
    });
}

/// A pane's top edge under a `surfaces` theme, focused or not: the focus
/// rule while it has the keyboard, the plain hairline otherwise, so the seam
/// between a header (tab strip, breadcrumbs, panel tabs) and the content
/// below it is always drawn and only its colour says where focus is.
pub fn paint_pane_top(buf: &mut Buffer, area: Rect, theme: Theme, focused: bool) {
    let Some(t) = tones(theme) else {
        return;
    };
    let area = area.intersection(buf.area);
    if area.height < 2 {
        return;
    }
    if focused {
        paint_focus_rule(buf, area, theme);
    } else {
        paint_edge_row(buf, area.x, area.y, area.width, Edge::Top.glyph(), |_| {
            t.hairline()
        });
    }
}

/// Darken a colour toward black, for the overlay shadow. A cell left on the
/// terminal's default background shows the theme background, so that is
/// what gets darkened.
fn shade(c: Color, theme: Theme) -> Color {
    let (r, g, b) = match c {
        Color::Rgb(r, g, b) => (r, g, b),
        _ => theme.editor_bg_rgb(),
    };
    rgb_color(lerp_rgb((r, g, b), (0, 0, 0), 0.55))
}

/// The frame an overlay draws (Command Palette, pickers, popups, dialogs).
/// On a boxed brand theme it is the gradient box. Under `surfaces` it is a
/// card edge in one-eighth blocks hugging the overlay's outer boundary: an
/// accent lip along the top that fades into the card, no visible line on
/// the other three sides (the card reads as lifted by its shadow, never
/// outlined), with a one-cell shadow below and to the right; a title
/// painted on the top row keeps its cells.
pub fn paint_overlay_frame(buf: &mut Buffer, rect: Rect, theme: Theme) {
    let Some(t) = tones(theme) else {
        crate::gradient::paint_gradient_box(buf, rect);
        return;
    };
    paint_card_edge(buf, rect, theme, Some(t.accent), None);
}

/// [`paint_overlay_frame`], or with `quiet` [`paint_quiet_frame`], for a
/// card that floats beside the line of text it is about: the hover, a
/// completion list and its details, parameter hints. Its shadow skips
/// `anchor_row`, so a card placed just above its line never dims the very
/// symbol or caret it describes; everywhere else it falls as usual. A boxed
/// theme draws the gradient box its siblings do.
pub fn paint_anchored_frame(
    buf: &mut Buffer,
    rect: Rect,
    theme: Theme,
    anchor_row: u16,
    quiet: bool,
) {
    let Some(t) = tones(theme) else {
        crate::gradient::paint_gradient_box(buf, rect);
        return;
    };
    let lip = (!quiet).then_some(t.accent);
    paint_card_edge(buf, rect, theme, lip, Some(anchor_row));
}

/// [`paint_overlay_frame`] without the accent lip: no visible edge at
/// all. For hints and tooltips that never take the keyboard, so the accent
/// keeps meaning focus.
pub fn paint_quiet_frame(buf: &mut Buffer, rect: Rect, theme: Theme) {
    if tones(theme).is_none() {
        crate::gradient::paint_gradient_box(buf, rect);
        return;
    }
    paint_card_edge(buf, rect, theme, None, None);
}

/// [`paint_overlay_frame`] with the lip in `tint` instead of the accent: a
/// warning or a destructive confirmation marks its card in its own colour.
pub fn paint_tinted_frame(buf: &mut Buffer, rect: Rect, theme: Theme, tint: (u8, u8, u8)) {
    if tones(theme).is_none() {
        crate::gradient::paint_gradient_box(buf, rect);
        return;
    }
    paint_card_edge(buf, rect, theme, Some(tint), None);
}

/// The card edge every overlay frame shares: the top in the `lip` fading
/// into the card (nothing without one), no visible line on the other
/// sides, and the one-cell shadow below and to the right, except on `spare_row`.
fn paint_card_edge(
    buf: &mut Buffer,
    rect: Rect,
    theme: Theme,
    lip: Option<(u8, u8, u8)>,
    spare_row: Option<u16>,
) {
    let Some(t) = tones(theme) else {
        return;
    };
    let area = buf.area;
    if rect.width < 2 || rect.height < 2 || rect.intersection(area) != rect {
        return;
    }
    let (right, bottom) = (rect.right() - 1, rect.bottom() - 1);
    // The edge glyphs stay in place (a selected row's bar and a scroll cue
    // recolour them), but each takes its own cell's fill, so it cannot be
    // seen: the card has no outline, and the shadow alone lifts it.
    let unseen = |cell: &Cell| match cell.bg {
        Color::Rgb(..) => cell.bg,
        _ => t.raised(),
    };
    paint_edge_row(buf, rect.x, rect.y, rect.width, Edge::Top.glyph(), |_| {
        t.raised()
    });
    paint_edge_row(
        buf,
        rect.x,
        bottom,
        rect.width,
        Edge::Bottom.glyph(),
        |_| t.raised(),
    );
    for x in rect.x..=right {
        for (y, top) in [(rect.y, true), (bottom, false)] {
            let cell = &mut buf[(x, y)];
            let glyph = if top { Edge::Top } else { Edge::Bottom }.glyph();
            if cell.symbol() != glyph {
                continue;
            }
            let fg = match lip {
                Some(a) if top => {
                    let rest = match unseen(cell) {
                        Color::Rgb(r, g, b) => (r, g, b),
                        _ => t.raised,
                    };
                    lip_color(a, rest, x - rect.x, rect.width)
                }
                _ => unseen(cell),
            };
            cell.set_fg(fg);
        }
    }
    for y in rect.y + 1..bottom {
        for (x, edge) in [(rect.x, Edge::Left), (right, Edge::Right)] {
            let cell = &mut buf[(x, y)];
            if is_frame_cell(cell) {
                let fg = unseen(cell);
                cell.set_symbol(edge.glyph());
                cell.set_fg(fg);
            }
        }
    }
    // The shadow falls one cell right and one cell down, offset by a cell
    // so the card reads as lifted rather than outlined.
    let shadow = |cell: &mut Cell| {
        let (fg, bg) = (shade(cell.fg, theme), shade(cell.bg, theme));
        cell.set_fg(fg);
        cell.set_bg(bg);
    };
    if rect.right() < area.right() {
        for y in (rect.y + 1..=bottom).filter(|&y| Some(y) != spare_row) {
            shadow(&mut buf[(rect.right(), y)]);
        }
    }
    if rect.bottom() < area.bottom() && Some(rect.bottom()) != spare_row {
        for x in rect.x + 1..=rect.right().min(area.right() - 1) {
            shadow(&mut buf[(x, rect.bottom())]);
        }
    }
}

/// Write `s` at `(x, y)` styled, clipped to the half-open column range
/// `[x, right)`, and return the column just past what was drawn, so a
/// view can lay coloured segments left to right without overflowing.
pub fn put_clipped(buf: &mut Buffer, x: u16, y: u16, right: u16, s: &str, style: Style) -> u16 {
    if x >= right {
        return x;
    }
    let budget = (right - x) as usize;
    let clipped: String = s.chars().take(budget).collect();
    let drawn = clipped.chars().count() as u16;
    buf.set_string(x, y, &clipped, style);
    x + drawn
}

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

    fn loch() -> Theme {
        Theme::from_id("loch")
    }

    #[test]
    fn a_pane_block_keeps_the_bordered_inset() {
        let area = Rect::new(2, 1, 20, 8);
        let boxed = Block::default().borders(Borders::ALL).inner(area);
        assert_eq!(pane_block(Color::Black).inner(area), boxed);
    }

    #[test]
    fn a_pane_block_paints_padding_in_its_fill() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 10, 4));
        let fill = Color::Rgb(0x0e, 0x10, 0x11);
        pane_block(fill).render(buf.area, &mut buf);
        for y in 0..4 {
            for x in 0..10 {
                assert_eq!(buf[(x, y)].symbol(), " ", "({x},{y}) is padding");
                assert_eq!(buf[(x, y)].bg, fill);
            }
        }
    }

    #[test]
    fn the_focus_rule_eases_from_the_accent_into_the_hairline_and_spares_the_title() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 24, 3));
        buf.set_string(1, 0, "EX", Style::default());
        let area = buf.area;
        paint_focus_rule(&mut buf, area, loch());
        let t = tones(loch()).unwrap();
        assert_eq!(buf[(0, 0)].symbol(), "\u{2594}");
        assert_eq!(buf[(0, 0)].fg, t.accent(), "the lip starts at the accent");
        assert_eq!(buf[(23, 0)].fg, t.hairline(), "and settles on the hairline");
        assert_eq!(buf[(1, 0)].symbol(), "E", "the title keeps its cells");
        assert_eq!(buf[(5, 1)].symbol(), " ", "only the top row is touched");
    }

    #[test]
    fn an_unfocused_pane_top_is_the_hairline() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 10, 3));
        let area = buf.area;
        paint_pane_top(&mut buf, area, loch(), false);
        let t = tones(loch()).unwrap();
        for x in 0..10 {
            assert_eq!(buf[(x, 0)].symbol(), "\u{2594}");
            assert_eq!(buf[(x, 0)].fg, t.hairline());
        }
        let mut boxed = Buffer::empty(Rect::new(0, 0, 10, 3));
        paint_pane_top(&mut boxed, area, Theme::BLACK, true);
        assert_eq!(boxed, Buffer::empty(area), "a boxed theme draws nothing");
    }

    /// An ink that reads at 4.5:1 is kept; one that does not eases toward
    /// the strong ink only as far as it must, keeping its hue; and on a
    /// fill where nothing short of the strong ink would do, it is the
    /// strong ink.
    #[test]
    fn a_legible_ink_lifts_only_as_far_as_it_must() {
        use crate::theme::contrast_ratio;
        let t = tones(loch()).unwrap();
        let tint = (0x54, 0x1c, 0x19);
        let keyword = (0xc3, 0xa6, 0xf2);
        assert_eq!(legible_ink(keyword, tint, t), keyword, "already reads");
        let comment = (0x6a, 0x7a, 0x78);
        assert!(contrast_ratio(comment, tint) < 4.5);
        let lifted = legible_ink(comment, tint, t);
        assert!(contrast_ratio(lifted, tint) >= 4.5);
        assert_ne!(lifted, t.strong, "keeps some of its hue");
        assert_eq!(legible_ink(comment, (0xc0, 0xc0, 0xc0), t), t.strong);
    }

    #[test]
    fn loch_tones_rank_text_above_muted_above_faint() {
        let t = tones(loch()).unwrap();
        let l = |c: (u8, u8, u8)| u32::from(c.0) + u32::from(c.1) + u32::from(c.2);
        assert!(l(t.strong) > l(t.text));
        assert!(l(t.text) > l(t.muted));
        assert!(l(t.muted) > l(t.faint));
        assert!(l(t.faint) > l(t.canvas));
        assert!(
            l(t.rim) > l(t.raised),
            "the rim reads against the card body"
        );
        assert!(tones(Theme::BLACK).is_none());
    }

    #[test]
    fn a_selected_row_is_a_band_with_the_accent_bar_only_while_focused() {
        let t = tones(loch()).unwrap();
        let mut buf = Buffer::empty(Rect::new(0, 0, 8, 2));
        buf.set_string(1, 0, "ab", Style::default().fg(Color::Red));
        paint_selected_row(&mut buf, Rect::new(0, 0, 8, 1), t, t.raised, true);
        assert_eq!(buf[(0, 0)].symbol(), ROW_BAR);
        assert_eq!(buf[(0, 0)].fg, t.accent());
        assert_eq!(buf[(1, 0)].bg, t.band());
        assert_eq!(buf[(1, 0)].fg, Color::Red, "text keeps its colour");
        assert_eq!(buf[(0, 1)].symbol(), " ", "only the row is touched");
        paint_selected_row(&mut buf, Rect::new(0, 1, 8, 1), t, t.raised, false);
        assert_eq!(buf[(0, 1)].symbol(), " ", "no bar without focus");
        assert_ne!(buf[(3, 1)].bg, t.band());
    }

    #[test]
    fn keycaps_put_each_key_of_a_chord_in_a_chip() {
        let t = tones(loch()).unwrap();
        let spans = keycap_spans("Ctrl+K Z", t, t.raised(), false);
        let text: Vec<&str> = spans.iter().map(|s| s.content.as_ref()).collect();
        assert_eq!(text, [" Ctrl ", "+", " K ", " ", " Z "]);
        assert_eq!(spans[0].style.bg, Some(t.keycap_on(t.raised())));
        assert_eq!(spans[1].style.fg, Some(t.muted()));
        assert_eq!(chord_keys("Ctrl++"), ["Ctrl", "+"]);
    }

    #[test]
    fn paint_keycaps_matches_keycap_spans_without_allocating() {
        let t = tones(loch()).unwrap();
        let area = Rect::new(0, 0, 32, 1);
        for hint in ["Ctrl+K Z", "Ctrl++", "Cmd+Shift+P", ""] {
            let line = ratatui::text::Line::from(keycap_spans(hint, t, t.raised(), false));
            assert_eq!(keycap_width(hint) as usize, line.width(), "{hint}");
            let mut expected = Buffer::empty(area);
            expected.set_line(0, 0, &line, area.width);
            let mut actual = Buffer::empty(area);
            let ((), made) = crate::alloc_count::allocations_in(|| {
                let _ = keycap_width(hint);
                paint_keycaps(&mut actual, 0, 0, hint, t, t.raised(), false);
            });
            assert_eq!(made, 0, "{hint} should paint without allocating");
            assert_eq!(actual, expected, "{hint} cell-for-cell match");
        }
    }

    /// Croft Loch: on the selected row's band a chord still reads as one
    /// chord: the labels clear 4.5:1 on their chips and the `+` between
    /// the keys clears 3:1 on the band, as it does on an idle row.
    #[test]
    fn a_selected_rows_keycaps_read_as_chords_on_the_band() {
        use crate::theme::contrast_ratio;
        let t = tones(loch()).unwrap();
        let rgb = |c: Option<Color>| match c {
            Some(Color::Rgb(r, g, b)) => (r, g, b),
            other => panic!("not an RGB colour: {other:?}"),
        };
        for (row, selected) in [(t.band(), true), (t.raised(), false)] {
            let spans = keycap_spans("Ctrl+K Ctrl+L", t, row, selected);
            let text: Vec<&str> = spans.iter().map(|s| s.content.as_ref()).collect();
            assert_eq!(text, [" Ctrl ", "+", " K ", " ", " Ctrl ", "+", " L "]);
            let plus = &spans[1].style;
            assert_eq!(plus.fg, Some(t.muted()), "the `+` is muted");
            assert_eq!(plus.bg, Some(row));
            let ratio = contrast_ratio(rgb(plus.fg), rgb(plus.bg));
            assert!(ratio >= 3.0, "`+` at {ratio:.2}:1 (selected {selected})");
            if selected {
                let cap = &spans[0].style;
                assert_eq!(cap.fg, Some(t.text()), "the label in body ink");
                let ratio = contrast_ratio(rgb(cap.fg), rgb(cap.bg));
                assert!(ratio >= 4.5, "label at {ratio:.2}:1");
            }
        }
    }

    #[test]
    fn the_backdrop_sinks_everything_but_the_card() {
        let t = tones(loch()).unwrap();
        let mut buf = Buffer::empty(Rect::new(0, 0, 6, 3));
        buf.set_style(buf.area, Style::default().fg(t.text()).bg(t.chrome()));
        dim_backdrop(&mut buf, Rect::new(2, 1, 2, 1), loch());
        assert_eq!(buf[(2, 1)].fg, t.text(), "the card keeps its contrast");
        assert_ne!(buf[(0, 0)].fg, t.text());
        assert_ne!(buf[(0, 0)].bg, t.chrome());
        let mut boxed = Buffer::empty(Rect::new(0, 0, 6, 3));
        let before = boxed.clone();
        dim_backdrop(&mut boxed, Rect::new(2, 1, 2, 1), Theme::BLACK);
        assert_eq!(boxed, before);
    }

    /// Croft Loch: a coloured underline (the active tab's accent mark)
    /// sinks behind the scrim exactly as the text does, so no full-strength
    /// teal is left outside the card; the card's own underline is kept, a
    /// terminal-default underline (which follows the sunk ink) is left
    /// alone, and a boxed theme's buffer is untouched.
    #[test]
    fn the_backdrop_sinks_a_coloured_underline_with_the_text() {
        let t = tones(loch()).unwrap();
        let mut buf = Buffer::empty(Rect::new(0, 0, 6, 3));
        buf.set_style(
            buf.area,
            Style::default()
                .fg(t.accent())
                .bg(t.chrome())
                .underline_color(t.accent())
                .add_modifier(Modifier::UNDERLINED),
        );
        buf[(5, 2)].underline_color = Color::Reset;
        buf[(4, 2)].underline_color = Color::Cyan;
        dim_backdrop(&mut buf, Rect::new(2, 1, 2, 1), loch());
        let outside = &buf[(0, 0)];
        assert_ne!(outside.underline_color, t.accent(), "the teal recedes");
        assert_eq!(
            outside.underline_color, outside.fg,
            "the underline sinks as far as the ink it shares"
        );
        assert_eq!(buf[(2, 1)].underline_color, t.accent(), "the card keeps it");
        assert_eq!(buf[(5, 2)].underline_color, Color::Reset);
        let cyan = rgb_color(lerp_rgb(
            loch().ansi()[6],
            cell_rgb(buf[(4, 2)].bg, loch(), t.canvas),
            0.58,
        ));
        assert_eq!(buf[(4, 2)].underline_color, cyan, "a palette colour sinks");
        let mut boxed = Buffer::empty(Rect::new(0, 0, 6, 3));
        boxed.set_style(
            boxed.area,
            Style::default().underline_color(Color::Rgb(0x4f, 0xb1, 0xa6)),
        );
        let before = boxed.clone();
        dim_backdrop(&mut boxed, Rect::new(2, 1, 2, 1), Theme::BLACK);
        assert_eq!(boxed, before);
    }

    #[test]
    fn the_focus_rule_keeps_the_space_between_a_titles_words() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 20, 3));
        buf.set_string(1, 0, " REMOTE EXPLORER ", Style::default());
        let area = buf.area;
        paint_focus_rule(&mut buf, area, loch());
        assert_eq!(buf[(8, 0)].symbol(), " ", "the word gap stays a space");
        assert_eq!(
            buf[(1, 0)].symbol(),
            "\u{2594}",
            "the title's padding takes the rule"
        );
        assert_eq!(buf[(19, 0)].symbol(), "\u{2594}");
    }

    #[test]
    fn a_seam_draws_over_padding_and_frame_lines_only() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 4, 3));
        buf.set_string(3, 1, "x", Style::default());
        buf.set_string(3, 2, "\u{2500}", Style::default());
        let hair = Color::Rgb(0x23, 0x28, 0x2a);
        paint_seam(&mut buf, Rect::new(3, 0, 1, 3), Edge::Right, hair);
        assert_eq!(buf[(3, 0)].symbol(), "\u{2595}");
        assert_eq!(buf[(3, 0)].fg, hair);
        assert_eq!(buf[(3, 1)].symbol(), "x");
        assert_eq!(buf[(3, 2)].symbol(), "\u{2595}");
    }

    #[test]
    fn a_seam_along_a_row_keeps_the_space_between_words() {
        // The scrubber's label sits on the editor's bottom row, where the
        // seam against the panel runs.
        let mut buf = Buffer::empty(Rect::new(0, 0, 20, 1));
        buf.set_string(1, 0, " 2/5 \u{b7} old.py ", Style::default());
        let hair = Color::Rgb(0x23, 0x28, 0x2a);
        let area = buf.area;
        paint_seam(&mut buf, area, Edge::Bottom, hair);
        let row: String = (0..20).map(|x| buf[(x, 0)].symbol()).collect();
        let seam = Edge::Bottom.glyph();
        assert_eq!(
            row,
            format!("{seam}{seam}2/5 \u{b7} old.py{}", seam.repeat(6))
        );
    }

    #[test]
    fn an_overlay_on_a_surfaces_theme_is_a_card_with_a_shadow() {
        let theme = loch();
        let s = theme.surfaces().unwrap();
        let mut buf = Buffer::empty(Rect::new(0, 0, 12, 6));
        buf.set_style(buf.area, Style::default().bg(s.chrome()));
        let card = Rect::new(1, 1, 8, 3);
        Block::default()
            .borders(Borders::ALL)
            .title("Hi")
            .render(card, &mut buf);
        paint_overlay_frame(&mut buf, card, theme);
        assert_eq!(buf[(1, 1)].symbol(), "\u{2594}", "top edge");
        assert_eq!(buf[(2, 1)].symbol(), "H", "the title survives");
        assert_eq!(buf[(1, 3)].symbol(), "\u{2581}", "bottom edge");
        assert_eq!(buf[(1, 2)].symbol(), "\u{258f}", "left edge");
        assert_eq!(buf[(8, 2)].symbol(), "\u{2595}", "right edge");
        // No outline: every edge glyph wears its own cell's fill, so it
        // cannot be seen and the shadow alone lifts the card.
        for (x, y) in [(1, 3), (1, 2), (8, 2), (8, 3)] {
            assert_eq!(buf[(x, y)].fg, buf[(x, y)].bg, "({x}, {y}) is unseen");
        }
        // Shadow: right column from the second row, bottom row from the
        // second column; the cell diagonally past the top-left is untouched.
        let shaded = shade(s.chrome(), theme);
        assert_eq!(buf[(9, 2)].bg, shaded);
        assert_eq!(buf[(9, 4)].bg, shaded);
        assert_eq!(buf[(2, 4)].bg, shaded);
        assert_eq!(buf[(9, 1)].bg, s.chrome());
        assert_eq!(buf[(1, 4)].bg, s.chrome());
    }

    /// A card anchored to a line (a hover above the symbol it describes)
    /// keeps its shadow off that line: the row under the card stays as it
    /// was, while the shadow down the right side still falls.
    #[test]
    fn an_anchored_card_never_shadows_its_anchor_row() {
        let theme = loch();
        let s = theme.surfaces().unwrap();
        let fresh = || {
            let mut buf = Buffer::empty(Rect::new(0, 0, 12, 6));
            buf.set_style(buf.area, Style::default().bg(s.chrome()));
            buf
        };
        // The card's last row is 3; the line it is about is row 4.
        let card = Rect::new(1, 1, 8, 3);
        let mut buf = fresh();
        paint_anchored_frame(&mut buf, card, theme, 4, true);
        let shaded = shade(s.chrome(), theme);
        for x in 0..12 {
            assert_eq!(buf[(x, 4)].bg, s.chrome(), "({x}, 4) is the anchor row");
        }
        assert_eq!(buf[(9, 2)].bg, shaded, "the right shadow still falls");
        assert_eq!(buf[(9, 3)].bg, shaded);
        assert_eq!(
            buf[(1, 1)].fg,
            buf[(1, 1)].bg,
            "quiet: no accent lip, no edge"
        );
        // Anchored to a row the shadow does not reach, it is the usual card.
        let mut free = fresh();
        paint_anchored_frame(&mut free, card, theme, 0, false);
        let mut plain = fresh();
        paint_overlay_frame(&mut plain, card, theme);
        assert_eq!(free, plain);
        let mut boxed = Buffer::empty(Rect::new(0, 0, 12, 6));
        let mut gradient = boxed.clone();
        paint_anchored_frame(&mut boxed, card, Theme::BLACK, 4, true);
        crate::gradient::paint_gradient_box(&mut gradient, card);
        assert_eq!(boxed, gradient, "a boxed theme keeps the gradient box");
    }

    #[test]
    fn an_overlay_on_a_boxed_brand_theme_keeps_the_gradient_box() {
        let mut ours = Buffer::empty(Rect::new(0, 0, 10, 5));
        let mut theirs = ours.clone();
        let card = Rect::new(1, 1, 6, 3);
        paint_overlay_frame(&mut ours, card, Theme::BLACK);
        crate::gradient::paint_gradient_box(&mut theirs, card);
        assert_eq!(ours, theirs);
    }

    /// A boxed theme's section header is exactly what the six stacked
    /// sections drew before they shared it: the dim triangle and the bold
    /// near-white label.
    #[test]
    fn a_boxed_section_header_is_the_dim_triangle_and_bold_label() {
        use ratatui::text::Line;
        use ratatui::widgets::{Paragraph, Widget};
        let theme = Theme::BLACK;
        let row = Rect::new(1, 0, 20, 1);
        let mut ours = Buffer::empty(Rect::new(0, 0, 22, 1));
        paint_section_header(&mut ours, row, theme, false, "OUTLINE", Vec::new(), true);
        let mut theirs = Buffer::empty(Rect::new(0, 0, 22, 1));
        Paragraph::new(Line::from(vec![
            Span::styled(
                format!("{} ", crate::icons::CHEVRON_CLOSED),
                Style::default().fg(theme.ui(SECTION_DIM)),
            ),
            Span::styled(
                "OUTLINE",
                Style::default()
                    .fg(theme.ui(SECTION_LABEL))
                    .add_modifier(Modifier::BOLD),
            ),
        ]))
        .render(row, &mut theirs);
        assert_eq!(ours, theirs);
    }

    /// Croft Loch's section header: a muted codicon chevron, the label
    /// muted while folded and body text while open, and a neutral lift
    /// with the strong ink under the pointer that stops short of the pane's
    /// right padding.
    #[test]
    fn a_croft_loch_section_header_is_calm_and_lifts_under_the_pointer() {
        let theme = loch();
        let t = tones(theme).unwrap();
        let row = Rect::new(1, 0, 20, 1);
        let paint = |open: bool, hovered: bool| {
            let mut buf = Buffer::empty(Rect::new(0, 0, 22, 1));
            buf.set_style(buf.area, Style::default().bg(t.chrome()));
            paint_section_header(&mut buf, row, theme, open, "OUTLINE", Vec::new(), hovered);
            buf
        };
        let folded = paint(false, false);
        assert_eq!(folded[(1, 0)].symbol(), CHEVRON_FOLDED.to_string());
        assert_eq!(folded[(1, 0)].fg, t.muted());
        assert_eq!(folded[(3, 0)].fg, t.muted(), "a folded label is muted");
        assert_eq!(folded[(3, 0)].bg, t.chrome());
        let open = paint(true, false);
        assert_eq!(open[(1, 0)].symbol(), CHEVRON_UNFOLDED.to_string());
        assert_eq!(open[(3, 0)].fg, t.text());
        let hovered = paint(true, true);
        assert_eq!(hovered[(3, 0)].fg, t.strong());
        assert_eq!(hovered[(3, 0)].bg, t.hover_on(t.chrome));
        assert_eq!(hovered[(20, 0)].bg, t.chrome(), "the padding stays chrome");
    }

    /// A field's edge hugs its raised inner cells from the frame cells
    /// around them; the corners stay blank and the inner rect is untouched.
    #[test]
    fn a_field_is_a_raised_well_inside_an_eighth_block_edge() {
        let t = tones(loch()).unwrap();
        let mut buf = Buffer::empty(Rect::new(0, 0, 6, 3));
        let area = buf.area;
        paint_field(&mut buf, area, t, t.rim());
        let rows: Vec<String> = (0..3)
            .map(|y| (0..6).map(|x| buf[(x, y)].symbol()).collect())
            .collect();
        assert_eq!(rows[0], " \u{2581}\u{2581}\u{2581}\u{2581} ");
        assert_eq!(rows[1], "\u{2595}    \u{258f}");
        assert_eq!(rows[2], " \u{2594}\u{2594}\u{2594}\u{2594} ");
        assert_eq!(buf[(2, 1)].bg, t.raised());
        assert_eq!(buf[(0, 1)].fg, t.rim());
    }

    /// A soft button is a one-row pill on its middle row: half-block caps on
    /// its rounded ends, the face between them, and the rows above and below
    /// left as the surface under it (no bands, no quadrant corners).
    #[test]
    fn a_soft_button_is_a_one_row_pill_with_half_block_caps() {
        let fill = Color::Rgb(0x0e, 0x7e, 0x76);
        let mut buf = Buffer::empty(Rect::new(0, 0, 5, 3));
        let area = buf.area;
        let face = paint_soft_button(&mut buf, area, fill, true, false);
        assert_eq!(face, Rect::new(1, 1, 4, 1), "the cells between the caps");
        let rows: Vec<String> = (0..3)
            .map(|y| (0..5).map(|x| buf[(x, y)].symbol()).collect())
            .collect();
        assert_eq!(rows, ["     ", "\u{2590}    ", "     "]);
        for x in 0..5 {
            for y in [0, 2] {
                assert_eq!(buf[(x, y)].bg, Color::Reset, "plain surface at ({x}, {y})");
            }
        }
        assert_eq!(buf[(0, 1)].fg, fill);
        assert_eq!(
            buf[(0, 1)].bg,
            Color::Reset,
            "the cap keeps what is under it"
        );
        assert_eq!(buf[(4, 1)].bg, fill, "an unrounded end runs to the edge");
        let mut buf = Buffer::empty(Rect::new(0, 0, 5, 3));
        let face = paint_soft_button(&mut buf, area, fill, true, true);
        assert_eq!(face, Rect::new(1, 1, 3, 1));
        assert_eq!(buf[(4, 1)].symbol(), "\u{258c}");
        assert_eq!(buf[(4, 1)].bg, Color::Reset);
    }

    /// A find match on Croft Loch is a calm amber tint of its own surface,
    /// never the old solid yellow: a syntax ink that reads on it is kept,
    /// one that would not (a comment) lifts to the strong ink, nothing is
    /// made bold, and the current match is a clearly stronger tint.
    #[test]
    fn a_find_match_is_an_amber_tint_that_keeps_a_legible_ink() {
        use crate::theme::contrast_ratio;
        let theme = loch();
        let t = tones(theme).unwrap();
        let syn = crate::theme::SyntaxPalette::LOCH;
        let on_canvas = |fg: (u8, u8, u8), active: bool| {
            match_style(
                Style::default().fg(rgb_color(fg)).bg(t.canvas()),
                t,
                theme,
                active,
            )
        };
        let soft = on_canvas(syn.keyword, false);
        assert_eq!(
            soft.bg,
            Some(rgb_color(lerp_rgb(t.canvas, MATCH_AMBER, MATCH_SOFT)))
        );
        assert_ne!(soft.bg, Some(Color::Rgb(0xff, 0xd7, 0x4a)));
        assert_eq!(soft.fg, Some(rgb_color(syn.keyword)), "the ink is kept");
        assert!(!soft.add_modifier.contains(Modifier::BOLD));
        assert_eq!(
            on_canvas(syn.comment, false).fg,
            Some(t.strong()),
            "a comment would not read on the tint, so it lifts"
        );
        let lum = |c: Option<Color>| match c {
            Some(Color::Rgb(r, g, b)) => contrast_ratio((r, g, b), (0, 0, 0)),
            _ => 0.0,
        };
        assert!(
            lum(on_canvas(syn.keyword, true).bg) > lum(soft.bg) + 0.5,
            "the current match is a clearly stronger tint"
        );
    }

    /// Every ink a match can carry reads at 4.5:1 or better on its tint,
    /// over every surface a match sits on: the canvas, the chrome, the
    /// raised card, the hover lift, the selection and a selected row's
    /// band (focused or not), as the current match or not. Where even the
    /// strong ink would fall short (the current match on a teal band) the
    /// tint eases back rather than giving up legibility.
    #[test]
    fn every_find_match_reads_at_four_and_a_half_to_one() {
        use crate::theme::contrast_ratio;
        let theme = loch();
        let t = tones(theme).unwrap();
        let syn = crate::theme::SyntaxPalette::LOCH;
        let inks = [
            t.text,
            t.strong,
            t.muted,
            t.faint,
            syn.comment,
            syn.keyword,
            syn.string,
            syn.constant,
            syn.function,
            syn.type_,
            syn.tag,
            syn.fg,
        ];
        let bases = [
            t.canvas,
            t.chrome,
            t.raised,
            lerp_rgb(t.chrome, t.lift, 0.055),
            (0x26, 0x4f, 0x4a),
            selected_row_fill(t, t.chrome, true),
            selected_row_fill(t, t.chrome, false),
        ];
        for base in bases {
            for ink in inks {
                for active in [false, true] {
                    let s = match_style(
                        Style::default().fg(rgb_color(ink)).bg(rgb_color(base)),
                        t,
                        theme,
                        active,
                    );
                    let (Some(Color::Rgb(fr, fg, fb)), Some(Color::Rgb(br, bg, bb))) = (s.fg, s.bg)
                    else {
                        panic!("RGB inks for {ink:?} on {base:?}");
                    };
                    let ratio = contrast_ratio((fr, fg, fb), (br, bg, bb));
                    assert!(
                        ratio >= 4.5,
                        "{ink:?} on {base:?} (active {active}) reads at {ratio:.2}"
                    );
                    assert_ne!(s.bg, Some(rgb_color(base)), "the match is marked");
                }
            }
        }
    }

    #[test]
    fn selected_row_fill_is_the_band_paint_selected_row_lays() {
        let t = tones(loch()).unwrap();
        for focused in [true, false] {
            let mut buf = Buffer::empty(Rect::new(0, 0, 4, 1));
            paint_selected_row(&mut buf, Rect::new(0, 0, 4, 1), t, t.chrome, focused);
            assert_eq!(
                buf[(2, 0)].bg,
                rgb_color(selected_row_fill(t, t.chrome, focused))
            );
        }
        assert_eq!(rgb_color(selected_row_fill(t, t.raised, true)), t.band());
    }

    #[test]
    fn pane_fill_is_chrome_only_for_surfaces_side_bars() {
        let s = loch().surfaces().unwrap();
        assert_eq!(pane_fill(loch(), true), s.chrome());
        assert_eq!(pane_fill(loch(), false), loch().editor_bg());
        assert_eq!(pane_fill(Theme::BLACK, true), Theme::BLACK.editor_bg());
    }
}