croft-software 0.2.182

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
//! Screen snapshots ("goldens"): whole frames drawn exactly as the running
//! app draws them, compared against text files saved beside this module.
//!
//! Each scene builds an [`App`], draws it with `render_for_terminal` (the
//! path the real main loop takes, which also fits colours to the terminal's
//! depth) into ratatui's `TestBackend`, and writes the result as text: a
//! header, every row's symbols, the cells that are not one plain narrow
//! glyph, and every row's style runs with exact colours. A refactor that
//! changes any cell, colour, modifier, glyph or the caret fails the scene
//! with a diff of the first differing lines. The actual text is written to
//! `target/golden-actual/<scene>.txt`.
//!
//! `CROFT_BLESS=1 cargo test --bin croft -- app::tests::golden` rewrites
//! the saved files in `src/app/tests/golden/` instead of comparing. A scene
//! with no saved file fails unless blessed, and a saved file no scene owns
//! fails `every_golden_belongs_to_a_scene`. The published crate leaves the
//! saved files out (`exclude` in Cargo.toml), so `cargo test` run from its
//! source skips every scene with a note instead.
//!
//! # Determinism
//!
//! A golden that changes on its own is worse than none, so every input the
//! frame reads is pinned at its source:
//!
//! * Workspace: a temp dir holding a folder named `golden`, so the Explorer
//!   and every relative path show the same name. No scene draws an absolute
//!   path.
//! * The user's own files. Under `cfg(test)` `App::new` already ignores the
//!   user's settings layers, `config.json` and the theme in it, keymap,
//!   problem matchers, profile, locale, layout and command history (see the
//!   `cfg!(test)` guards there and in `config_layers`), and lists only the
//!   bundled extensions, whose manifests `mcp::registry` reads without the
//!   user's. It still reads the macros, snippets, terminal triggers and
//!   agent table from the user's config folder and the hosts refused a
//!   remote offer from the cache folder, and keeps the real config folder
//!   as `config_dir`, where the Extensions view and the test worker look for
//!   added extensions. [`without_user_files`] points all of these at an
//!   empty folder beside the workspace. Only the config watcher, which
//!   nothing but the tick polls, and the embedded terminal's shell, which no
//!   scene shows, still look at the real folders.
//! * The terminal's environment (`TERM`, `COLORTERM`, `TERM_PROGRAM`,
//!   `VTE_VERSION`, `SSH_*`, Termux's markers, `CROFT_FORCE_*`,
//!   `CROFT_UNDERLINE_COLORS`) is read into App fields at startup;
//!   [`hermetic`] overwrites them (`color_depth`, `underline_colors`,
//!   `inline_protocol`, `sixel_supported`, `cell_pixel`, `is_remote`,
//!   `persistence_warning`, `osk_auto`) as soon as the App is built, so what
//!   a scene does runs on the pinned values, and again just before drawing,
//!   since a theme switch reads the environment again. Two reads made
//!   during a frame have no App field:
//!   `iterm2_inline::detect_iterm2_inline_support` (`TERM_PROGRAM` and
//!   `CROFT_FORCE_INLINE_IMAGES`; under iTerm2 or WezTerm the frame leaves
//!   the canvas to the session background), and
//!   `iterm2_inline::detect_inline_image_protocol`, which a picture open in
//!   an editor reads for its canvas. `set_var` would race every other test
//!   in the process, so [`draw`] answers both for its own thread through
//!   the `cfg(test)`-only `PLAIN_HOST_FRAMES` ([`PlainHost`]). A third,
//!   the unsupported-terminal warning naming the terminal from
//!   `TERM_PROGRAM` or `TERM`, is left to the machine: its scene masks
//!   that row (`terminal` under Masks).
//! * The status line starts from a process-wide latch other tests may set
//!   (`VIEW_BIND_ERROR`); scenes pin it to the "Ready" a clean start shows.
//! * The caret blinks on the wall clock. [`draw`] resets the blink and
//!   redraws if a frame took longer than the visible half-period
//!   (`cursor_blink::HALF`), so every frame is drawn in the caret's visible
//!   phase.
//! * Syntax colouring runs on a background thread; under test the editor
//!   waits for it before it returns from `open` (`highlight_budget` is
//!   `None`). The code palette it reads is process-wide, and under test it
//!   stays Base16 whatever the theme, since other tests pin those colours
//!   (`highlight::set_syntax_palette`). So each scene's thread gets a
//!   palette of its own ([`ThreadPalette`]): the push of the theme's palette
//!   that `App::new` makes lands there, the editor's highlight pass carries
//!   it to its worker, and the code shows each theme's own colours, as in
//!   the running app.
//! * Scenes never run the main loop's tick: git, the file watcher, search,
//!   language servers and the embedded terminal answer on background
//!   threads at a time no test controls, and only the tick drains them. A
//!   scene sets the state those answers would set (the Problems list, for
//!   one) directly, or drains the one answer it shows and waits until that
//!   work is done. So no spinner or progress mark is turning when a scene
//!   is drawn. The embedded terminal's shell output depends on the user's
//!   shell and rc files, so no scene shows the terminal tab.
//! * Time: no scene draws the clock, a date or an age. COMMITS can show a
//!   commit's age, though not at the width Source Control's scene leaves
//!   it; that scene's commit is dated in 2099, so the age would read
//!   `0 seconds ago` on every earlier clock ([`hermetic_git`]).
//! * Git: every workspace but Source Control's is a temp dir that is no
//!   repository. Source Control's repository is made with fixed names,
//!   emails and dates, no global or system config, no template and no
//!   hooks, and pins in its own config the keys a user's global config
//!   would change in what the app's git runs print, the commit template
//!   among them. The app's own git commands inherit the environment, so a
//!   run with git's repository variables set, as inside a git hook, or
//!   with settings passed in the environment (`GIT_CONFIG_COUNT`,
//!   `GIT_CONFIG_PARAMETERS`), which outrank the repository's own, cannot
//!   pass that scene, which then fails at once saying so.
//! * Host and user names: the hostname is drawn only beside a forwarded
//!   port in PORTS and a shell's host only on a terminal tab; no scene
//!   shows either, and `is_remote` is pinned to a local session.
//! * Each scene is drawn until two frames in a row match, and the header
//!   says how many frames that took. Every scene's first frame is final
//!   today, so a change that leaves the first frame after an action wrong
//!   fails even when the next frame would repair it. A scene that never
//!   settles fails.
//! * Platform: chords are spelled per platform (`Cmd` against `Ctrl`) and
//!   paths per OS, so the module runs on Linux only.
//!
//! # Masks
//!
//! Only things a build changes on purpose, or the one row a scene reads
//! from the machine's terminal, are masked, each with a fixed
//! fill (`MASK_SYMBOL`, reset colours) over whole rows of a named region
//! so a longer or shorter value cannot shift what is compared:
//!
//! * `version`: any editor-area row showing this build's version
//!   (`CARGO_PKG_VERSION`). On the welcome page that is the wordmark row,
//!   whose wordmark and version pill are centred as one group, and the
//!   release card's heading row, which also says whether the build carries
//!   unreleased notes. The card's notes are pinned with `set_test_notes`,
//!   so they are compared, not masked.
//! * `terminal`: the unsupported-terminal warning's row that names the
//!   terminal croft runs in, which it reads from `TERM_PROGRAM` or `TERM`
//!   as it draws.
//!
//! # Not covered
//!
//! Only the plain-terminal path is drawn. The inline-image paths (iTerm2,
//! Kitty and sixel graphics, which draw croft's icons and wordmark on the
//! terminals that offer them) and the caret's shape, which
//! `sync_caret_style` sends after each frame, are not compared.

use super::*;
use ratatui::backend::{Backend, TestBackend};
use ratatui::buffer::{Buffer, Cell};
use ratatui::layout::Position;
use unicode_width::UnicodeWidthStr;

/// The fill a masked cell is serialised with.
const MASK_SYMBOL: &str = "\u{2591}";

/// What a cell that is not one printable glyph is written as in its row,
/// so the row keeps one column per cell. The `cells` section says what the
/// cell really held.
const ODD_SYMBOL: &str = "\u{00a4}";

/// A named region painted over before a frame is compared.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Mask {
    name: &'static str,
    area: Rect,
}

/// The caret as the terminal would show it after the frame.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Caret {
    shown: bool,
    at: Position,
}

/// One drawn frame: what the terminal holds after it.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Shot {
    buffer: Buffer,
    caret: Caret,
}

/// Paint `masks` over `shot` with the fixed fill.
fn apply_masks(shot: &mut Shot, masks: &[Mask]) {
    for mask in masks {
        for y in mask.area.top()..mask.area.bottom() {
            for x in mask.area.left()..mask.area.right() {
                let cell = &mut shot.buffer[(x, y)];
                cell.reset();
                cell.set_symbol(MASK_SYMBOL);
            }
        }
    }
}

/// How a colour is written: `#rrggbb`, `idx<n>` or the ANSI name.
fn colour(c: Color) -> String {
    match c {
        Color::Reset => String::from("reset"),
        Color::Black => String::from("black"),
        Color::Red => String::from("red"),
        Color::Green => String::from("green"),
        Color::Yellow => String::from("yellow"),
        Color::Blue => String::from("blue"),
        Color::Magenta => String::from("magenta"),
        Color::Cyan => String::from("cyan"),
        Color::Gray => String::from("gray"),
        Color::DarkGray => String::from("darkgray"),
        Color::LightRed => String::from("lightred"),
        Color::LightGreen => String::from("lightgreen"),
        Color::LightYellow => String::from("lightyellow"),
        Color::LightBlue => String::from("lightblue"),
        Color::LightMagenta => String::from("lightmagenta"),
        Color::LightCyan => String::from("lightcyan"),
        Color::White => String::from("white"),
        Color::Indexed(i) => format!("idx{i}"),
        Color::Rgb(r, g, b) => format!("#{r:02x}{g:02x}{b:02x}"),
    }
}

/// Whether `c` is in a Unicode private use area, where Nerd Font icons live.
fn private_use(c: char) -> bool {
    matches!(c as u32, 0xE000..=0xF8FF | 0xF0000..=0xFFFFD | 0x100000..=0x10FFFD)
}

/// A cell's style as one run key: colours, then modifiers and `skip`.
fn style_key(cell: &Cell) -> String {
    let mut key = format!("fg={} bg={}", colour(cell.fg), colour(cell.bg));
    if cell.underline_color != Color::Reset {
        key.push_str(&format!(" ul={}", colour(cell.underline_color)));
    }
    if !cell.modifier.is_empty() {
        let names: Vec<&str> = cell.modifier.iter_names().map(|(name, _)| name).collect();
        key.push_str(&format!(" mod={}", names.join("+")));
    }
    if cell.skip {
        key.push_str(" skip");
    }
    key
}

/// What a scene is, for the header.
struct Header<'a> {
    scene: &'a str,
    theme: crate::theme::Theme,
    depth: crate::color_depth::ColorDepth,
    /// The first frame that already showed the compared one (1: the first
    /// frame drawn was final).
    settled: usize,
}

/// `shot` as the golden text: header, symbols, odd cells, style runs.
fn serialise(header: &Header, shot: &Shot, masks: &[Mask]) -> String {
    use std::fmt::Write as _;
    let area = shot.buffer.area;
    let depth = match header.depth {
        crate::color_depth::ColorDepth::TrueColor => "truecolor",
        crate::color_depth::ColorDepth::Ansi256 => "256",
        crate::color_depth::ColorDepth::Ansi16 => "16",
    };
    let mut out = String::new();
    let _ = writeln!(out, "croft screen golden v1");
    let _ = writeln!(out, "scene: {}", header.scene);
    let _ = writeln!(out, "size: {}x{}", area.width, area.height);
    let _ = writeln!(out, "theme: {}", header.theme.id());
    let _ = writeln!(out, "colour depth: {depth}");
    let frames = if header.settled == 1 {
        "frame"
    } else {
        "frames"
    };
    let _ = writeln!(out, "settled after: {} {frames}", header.settled);
    if shot.caret.shown {
        let _ = writeln!(
            out,
            "caret: row {} col {}",
            shot.caret.at.y, shot.caret.at.x
        );
    } else {
        let _ = writeln!(out, "caret: hidden");
    }
    for m in masks {
        let _ = writeln!(
            out,
            "mask: {} rows {}..{} cols {}..{}",
            m.name,
            m.area.top(),
            m.area.bottom(),
            m.area.left(),
            m.area.right()
        );
    }
    let _ = writeln!(out, "--- symbols");
    let mut odd = Vec::new();
    for y in 0..area.height {
        let mut row = String::new();
        // Cells a wide glyph to their left already covers: the terminal
        // shows the glyph there, so the row adds nothing for them.
        let mut covered = 0usize;
        for x in 0..area.width {
            let sym = shot.buffer[(x, y)].symbol();
            if covered > 0 {
                covered -= 1;
                if sym != " " {
                    odd.push(format!("r{y:02} c{x:03} hidden {sym:?}"));
                }
                continue;
            }
            let width = sym.width();
            if width == 0 || sym.chars().any(char::is_control) {
                odd.push(format!("r{y:02} c{x:03} odd {sym:?}"));
                row.push_str(ODD_SYMBOL);
                continue;
            }
            row.push_str(sym);
            if width > 1 {
                odd.push(format!("r{y:02} c{x:03} wide {sym:?} {width} cells"));
                covered = width - 1;
            } else if sym.chars().any(private_use) {
                // A Nerd Font icon is one cell to ratatui and to the
                // terminal, but a viewer without the font may draw it
                // narrower or wider, so the row alone could read shifted.
                let points: Vec<String> =
                    sym.chars().map(|c| format!("U+{:04X}", c as u32)).collect();
                odd.push(format!("r{y:02} c{x:03} icon {}", points.join(" ")));
            }
        }
        let _ = writeln!(out, "{y:02}|{row}|");
    }
    let _ = writeln!(out, "--- cells");
    for line in odd {
        let _ = writeln!(out, "{line}");
    }
    let _ = writeln!(out, "--- styles");
    for y in 0..area.height {
        let mut x = 0;
        while x < area.width {
            let key = style_key(&shot.buffer[(x, y)]);
            let start = x;
            while x < area.width && style_key(&shot.buffer[(x, y)]) == key {
                x += 1;
            }
            let _ = writeln!(out, "r{y:02} c{start:03}-{:03} {key}", x - 1);
        }
    }
    out
}

/// Where goldens are read from (at run time, so a blessed file needs no
/// rebuild) and where a mismatching scene's actual text is written.
struct Dirs {
    golden: PathBuf,
    actual: PathBuf,
    /// Whether this is a published crate's source, which leaves the
    /// goldens out.
    packaged: bool,
}

impl Dirs {
    fn repo() -> Self {
        let root = Path::new(env!("CARGO_MANIFEST_DIR"));
        Dirs {
            golden: root.join("src/app/tests/golden"),
            actual: root.join("target/golden-actual"),
            packaged: packaged_source(),
        }
    }
}

/// Whether this is a published crate's source, which leaves the saved
/// goldens and the key ledger out. `cargo package` keeps the manifest it
/// was given under this name beside the one it publishes; a checkout never
/// has it.
pub(super) fn packaged_source() -> bool {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("Cargo.toml.orig")
        .is_file()
}

/// Whether this run rewrites goldens instead of comparing them.
fn blessing() -> bool {
    std::env::var_os("CROFT_BLESS").is_some_and(|v| v == "1")
}

/// The first differing lines of `expected` and `actual` (symbol rows,
/// cells and style runs alike), as a unified diff; `None` when they match.
fn first_differences(expected: &str, actual: &str) -> Option<String> {
    const MAX_LINES: usize = 60;
    if expected == actual {
        return None;
    }
    let diff = similar::TextDiff::from_lines(expected, actual);
    let text = diff
        .unified_diff()
        .context_radius(1)
        .header("golden", "actual")
        .to_string();
    let mut lines: Vec<&str> = text.lines().take(MAX_LINES + 1).collect();
    if lines.len() > MAX_LINES {
        lines.truncate(MAX_LINES);
        lines.push("... (more differences follow)");
    }
    Some(lines.join("\n"))
}

/// Compare `actual` with scene `name`'s golden in `dirs`, or rewrite the
/// golden when `bless`.
fn compare(dirs: &Dirs, name: &str, actual: &str, bless: bool) -> Result<(), String> {
    let path = dirs.golden.join(format!("{name}.txt"));
    if bless {
        std::fs::create_dir_all(&dirs.golden).unwrap();
        std::fs::write(&path, actual).unwrap();
        return Ok(());
    }
    if dirs.packaged && !dirs.golden.exists() {
        eprintln!(
            "scene {name:?} skipped: the published crate leaves its golden out; \
             run the suite from a checkout to compare it"
        );
        return Ok(());
    }
    let expected = std::fs::read_to_string(&path).map_err(|e| {
        format!(
            "no golden for scene {name:?} at {} ({e}); run with CROFT_BLESS=1 to write it",
            path.display()
        )
    })?;
    let Some(diff) = first_differences(&expected, actual) else {
        return Ok(());
    };
    let out = dirs.actual.join(format!("{name}.txt"));
    std::fs::create_dir_all(&dirs.actual).unwrap();
    std::fs::write(&out, actual).unwrap();
    Err(format!(
        "scene {name:?} no longer matches its golden {}.\nThe actual frame is in {}; \
         if the change is intended, rerun with CROFT_BLESS=1.\n{diff}",
        path.display(),
        out.display(),
    ))
}

/// Compare `text` with the golden `name` that a test outside the scenes
/// saves here, or rewrite it under `CROFT_BLESS=1`, failing the test with
/// the first differences on a mismatch.
pub(super) fn check_text(name: &str, text: &str) {
    if let Err(err) = compare(&Dirs::repo(), name, text, blessing()) {
        panic!("{err}");
    }
}

/// A hand-built shot of `width` x 1 cells for the harness's own tests.
fn shot_of(width: u16, paint: impl FnOnce(&mut Buffer)) -> Shot {
    let mut buffer = Buffer::empty(Rect::new(0, 0, width, 1));
    paint(&mut buffer);
    Shot {
        buffer,
        caret: Caret {
            shown: false,
            at: Position::new(0, 0),
        },
    }
}

/// `shot` serialised under a fixed header.
fn text_of(shot: &Shot, masks: &[Mask]) -> String {
    let header = Header {
        scene: "harness",
        theme: crate::theme::Theme::default(),
        depth: crate::color_depth::ColorDepth::TrueColor,
        settled: 1,
    };
    serialise(&header, shot, masks)
}

/// The lines of `section` (`symbols`, `cells` or `styles`) in `text`.
fn section<'a>(text: &'a str, section: &str) -> Vec<&'a str> {
    let start = format!("--- {section}");
    text.lines()
        .skip_while(|l| *l != start)
        .skip(1)
        .take_while(|l| !l.starts_with("--- "))
        .collect()
}

#[test]
fn golden_rows_keep_one_column_per_cell_around_wide_and_icon_glyphs() {
    let red = Style::default().fg(Color::Red);
    let shot = shot_of(12, |b| {
        b.set_string(0, 0, "a\u{4e2d}b\u{1f980}\u{e7a8}", Style::default());
        b.set_string(7, 0, "d", red);
        b[(8, 0)].set_symbol("");
        b.set_string(9, 0, "e", red);
    });
    let text = text_of(&shot, &[]);
    // Each wide glyph is followed by nothing for the cell it covers, so the
    // row is exactly 12 columns wide and `d` and `e` stay where they were
    // drawn; the empty cell is written as one placeholder column.
    let row = section(&text, "symbols")[0];
    assert_eq!(row, "00|a\u{4e2d}b\u{1f980}\u{e7a8}d\u{a4}e  |");
    assert_eq!(UnicodeWidthStr::width(&row[3..row.len() - 1]), 12);
    assert_eq!(
        section(&text, "cells"),
        vec![
            "r00 c001 wide \"\u{4e2d}\" 2 cells",
            "r00 c004 wide \"\u{1f980}\" 2 cells",
            "r00 c006 icon U+E7A8",
            "r00 c008 odd \"\"",
        ]
    );
    let styles = section(&text, "styles");
    assert!(
        styles.contains(&"r00 c007-007 fg=red bg=reset"),
        "{styles:?}"
    );
    assert!(
        styles.contains(&"r00 c009-009 fg=red bg=reset"),
        "{styles:?}"
    );
}

#[test]
fn golden_lists_a_hidden_symbol_under_a_wide_glyph() {
    let shot = shot_of(4, |b| {
        b.set_string(0, 0, "\u{4e2d}", Style::default());
        b[(1, 0)].set_symbol("x");
    });
    let text = text_of(&shot, &[]);
    assert_eq!(section(&text, "symbols")[0], "00|\u{4e2d}  |");
    assert!(section(&text, "cells").contains(&"r00 c001 hidden \"x\""));
}

#[test]
fn golden_style_runs_write_every_colour_and_modifier_exactly() {
    let shot = shot_of(6, |b| {
        b.set_string(
            0,
            0,
            "ab",
            Style::default()
                .fg(Color::Rgb(0x12, 0xab, 0xef))
                .bg(Color::Indexed(236))
                .add_modifier(Modifier::BOLD | Modifier::ITALIC),
        );
        b.set_string(2, 0, "c", Style::default().fg(Color::DarkGray));
        b.set_string(
            3,
            0,
            "d",
            Style::default()
                .fg(Color::Rgb(0x12, 0xab, 0xef))
                .underline_color(Color::LightMagenta)
                .add_modifier(Modifier::UNDERLINED),
        );
        b[(4, 0)].skip = true;
    });
    let text = text_of(&shot, &[]);
    assert_eq!(
        section(&text, "styles"),
        vec![
            "r00 c000-001 fg=#12abef bg=idx236 mod=BOLD+ITALIC",
            "r00 c002-002 fg=darkgray bg=reset",
            "r00 c003-003 fg=#12abef bg=reset ul=lightmagenta mod=UNDERLINED",
            "r00 c004-004 fg=reset bg=reset skip",
            "r00 c005-005 fg=reset bg=reset",
        ]
    );
}

#[test]
fn golden_masks_fill_their_region_and_are_named_in_the_header() {
    let mut shot = shot_of(6, |b| {
        b.set_string(0, 0, "v1.2.3", Style::default().fg(Color::Red));
    });
    let masks = [Mask {
        name: "version",
        area: Rect::new(1, 0, 4, 1),
    }];
    apply_masks(&mut shot, &masks);
    let text = text_of(&shot, &masks);
    assert!(
        text.contains("\nmask: version rows 0..1 cols 1..5\n"),
        "{text}"
    );
    assert_eq!(
        section(&text, "symbols")[0],
        "00|v\u{2591}\u{2591}\u{2591}\u{2591}3|"
    );
    assert!(section(&text, "styles").contains(&"r00 c001-004 fg=reset bg=reset"));
}

#[test]
fn golden_comparison_fails_on_one_changed_cell_or_colour_and_saves_the_actual() {
    let tmp = tempfile::tempdir().unwrap();
    let dirs = Dirs {
        golden: tmp.path().join("golden"),
        actual: tmp.path().join("actual"),
        packaged: false,
    };
    let paint = |b: &mut Buffer| {
        b.set_string(0, 0, "fn main", Style::default().fg(Color::Rgb(1, 2, 3)));
    };
    let saved = text_of(&shot_of(8, paint), &[]);
    let missing = compare(&dirs, "scene", &saved, false).unwrap_err();
    assert!(missing.contains("CROFT_BLESS=1"), "{missing}");
    compare(&dirs, "scene", &saved, true).unwrap();
    compare(&dirs, "scene", &saved, false).unwrap();

    let mut glyph = shot_of(8, paint);
    glyph.buffer[(3, 0)].set_symbol("M");
    let err = compare(&dirs, "scene", &text_of(&glyph, &[]), false).unwrap_err();
    assert!(
        err.contains("-00|fn main |") && err.contains("+00|fn Main |"),
        "{err}"
    );
    assert_eq!(
        std::fs::read_to_string(dirs.actual.join("scene.txt")).unwrap(),
        text_of(&glyph, &[])
    );

    let mut colour = shot_of(8, paint);
    colour.buffer[(3, 0)].fg = Color::Rgb(1, 2, 4);
    let err = compare(&dirs, "scene", &text_of(&colour, &[]), false).unwrap_err();
    assert!(err.contains("+r00 c003-003 fg=#010204 bg=reset"), "{err}");
    assert!(err.contains("-r00 c000-006 fg=#010203 bg=reset"), "{err}");
}

/// A published crate's source, which has no golden folder, skips its
/// scenes; a missing golden anywhere else fails.
#[test]
fn golden_scenes_are_skipped_only_in_a_published_crate_without_goldens() {
    let tmp = tempfile::tempdir().unwrap();
    let mut dirs = Dirs {
        golden: tmp.path().join("golden"),
        actual: tmp.path().join("actual"),
        packaged: true,
    };
    compare(&dirs, "scene", "text", false).unwrap();
    std::fs::create_dir_all(&dirs.golden).unwrap();
    compare(&dirs, "scene", "text", false).unwrap_err();
    std::fs::remove_dir(&dirs.golden).unwrap();
    dirs.packaged = false;
    compare(&dirs, "scene", "text", false).unwrap_err();
}

/// How many frames a scene may take to settle.
const MAX_FRAMES: usize = 4;

// The snapshots record whether the caret is shown, which `TestBackend`
// keeps private.
use super::CaretBackend as GoldenBackend;

/// Pin every App field that startup reads from the terminal's environment,
/// as the module doc lists. Run as soon as the App is built and again just
/// before drawing, since a theme switch reads the environment again.
fn hermetic(app: &mut App, depth: crate::color_depth::ColorDepth) {
    app.color_depth = depth;
    app.underline_colors = true;
    app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::None;
    app.sixel_supported = false;
    app.cell_pixel = None;
    app.is_remote = false;
    app.persistence_warning = None;
    app.osk_auto = false;
}

/// While alive, this thread highlights code with a palette of its own
/// (`highlight::set_thread_syntax_palette`), seeded as the shared one is,
/// so the theme's palette an App pushes lands there, as it lands in the
/// shared one in the running app.
struct ThreadPalette {
    before: Option<crate::theme::SyntaxPalette>,
}

impl ThreadPalette {
    fn enter() -> Self {
        let before = crate::highlight::thread_syntax_palette();
        crate::highlight::set_thread_syntax_palette(Some(crate::theme::SyntaxPalette::BASE16));
        ThreadPalette { before }
    }
}

impl Drop for ThreadPalette {
    fn drop(&mut self) {
        crate::highlight::set_thread_syntax_palette(self.before);
    }
}

/// A scene's workspace and its thread's code palette, which last as long
/// as the test holds this.
struct Fixture {
    _dir: tempfile::TempDir,
    _palette: ThreadPalette,
}

/// A fresh workspace: a temp dir holding a folder named `golden`, so the
/// name the Explorer shows never varies, and a code palette of this
/// thread's own for the App built on it. Returns the guard and the root.
fn workspace(files: &[(&str, &str)]) -> (Fixture, PathBuf) {
    let palette = ThreadPalette::enter();
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("golden");
    for (rel, text) in files {
        let path = root.join(rel);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, text).unwrap();
    }
    std::fs::create_dir_all(&root).unwrap();
    let fixture = Fixture {
        _dir: tmp,
        _palette: palette,
    };
    (fixture, root)
}

/// One frame of `app` at `width` x `height`, drawn as the main loop draws
/// it, in the caret's visible blink phase.
fn draw_once(app: &mut App, width: u16, height: u16) -> Shot {
    // A frame that takes longer than the blink's visible half could see the
    // caret both shown and hidden; draw it again until one is quick enough.
    for _ in 0..8 {
        let started = std::time::Instant::now();
        let backend = GoldenBackend {
            inner: TestBackend::new(width, height),
            caret_shown: false,
        };
        let mut terminal = ratatui::Terminal::new(backend).unwrap();
        app.cursor_blink.poke();
        terminal.draw(|f| app.render_for_terminal(f)).unwrap();
        if started.elapsed() < super::cursor_blink::HALF && app.cursor_visible_phase() {
            let backend = terminal.backend_mut();
            let at = backend.get_cursor_position().unwrap();
            return Shot {
                buffer: backend.inner.buffer().clone(),
                caret: Caret {
                    shown: backend.caret_shown,
                    at,
                },
            };
        }
    }
    panic!(
        "no frame drew within the caret's {:?} visible phase in 8 tries",
        super::cursor_blink::HALF
    );
}

/// While alive, frames drawn on this thread are drawn as a plain terminal
/// draws them, with no iTerm2 session background and no inline-image
/// protocol, whatever terminal runs the suite.
struct PlainHost;

impl PlainHost {
    fn enter() -> Self {
        crate::iterm2_inline::PLAIN_HOST_FRAMES.with(|f| f.set(true));
        PlainHost
    }
}

impl Drop for PlainHost {
    fn drop(&mut self) {
        crate::iterm2_inline::PLAIN_HOST_FRAMES.with(|f| f.set(false));
    }
}

/// Draw `app` until two frames in a row match. Returns that frame and the
/// number of the first frame that already showed it (1: the first frame
/// drawn was final).
fn draw(app: &mut App, width: u16, height: u16) -> (Shot, usize) {
    let _plain = PlainHost::enter();
    let mut last = draw_once(app, width, height);
    for frame in 1..MAX_FRAMES {
        let next = draw_once(app, width, height);
        if next == last {
            return (next, frame);
        }
        last = next;
    }
    panic!("the scene did not settle: frame {MAX_FRAMES} still differed from the one before");
}

/// The symbols of row `y` of `buffer` from `x0` to `x1`, joined.
fn row_text(buffer: &Buffer, y: u16, x0: u16, x1: u16) -> String {
    (x0..x1).map(|x| buffer[(x, y)].symbol()).collect()
}

/// The `version` mask: every row of `area` that shows this build's version.
fn version_rows(shot: &Shot, area: Rect) -> Vec<Mask> {
    let version = concat!("v", env!("CARGO_PKG_VERSION"));
    (area.top()..area.bottom())
        .filter(|&y| row_text(&shot.buffer, y, area.left(), area.right()).contains(version))
        .map(|y| Mask {
            name: "version",
            area: Rect::new(area.x, y, area.width, 1),
        })
        .collect()
}

/// Pin `app` ([`hermetic`], at colour `depth`), draw it, mask what `masks`
/// picks from the frame, and compare the result with scene `name`'s golden.
fn scene(
    name: &str,
    app: &mut App,
    (width, height): (u16, u16),
    depth: crate::color_depth::ColorDepth,
    masks: impl Fn(&App, &Shot) -> Vec<Mask>,
) -> Result<(), String> {
    assert!(
        !app.show_terminal || app.bottom_panel_tab != BottomPanelTab::Terminal,
        "scene {name:?} shows the embedded terminal, whose shell prints what \
         the user's shell and rc files say, when they say it"
    );
    hermetic(app, depth);
    let (mut shot, settled) = draw(app, width, height);
    let picked = masks(app, &shot);
    apply_masks(&mut shot, &picked);
    let header = Header {
        scene: name,
        theme: app.theme,
        depth: app.color_depth,
        settled,
    };
    let text = serialise(&header, &shot, &picked);
    compare(&Dirs::repo(), name, &text, blessing())
}

/// [`scene`], failing the test on a mismatch.
fn check_scene(
    name: &str,
    app: &mut App,
    size: (u16, u16),
    depth: crate::color_depth::ColorDepth,
    masks: impl Fn(&App, &Shot) -> Vec<Mask>,
) {
    if let Err(e) = scene(name, app, size, depth, masks) {
        panic!("{e}");
    }
}

/// The masks a scene with nothing to mask uses.
fn no_masks(_: &App, _: &Shot) -> Vec<Mask> {
    Vec::new()
}

const MAIN_RS: &str = "\
//! A tiny greeter.

use std::fmt;

/// Who to greet, and how.
pub struct Greeting<'a> {
    name: &'a str,
    excited: bool,
}

impl fmt::Display for Greeting<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mark = if self.excited { '!' } else { '.' };
        write!(f, \"Hello, {}{mark}\", self.name)
    }
}

fn main() {
    let greeting = Greeting { name: \"croft\", excited: true };
    println!(\"{greeting}\");
    let count = 42;
}
";

/// An app on `root` started with `theme` as its saved theme: what
/// `App::new` does with the theme it loads (`apply_theme` would also
/// re-detect the image protocol from the environment). It is pinned by
/// [`hermetic`] and reads nothing from the user's own folders.
fn app_with_theme(root: &Path, theme: crate::theme::Theme) -> App {
    let mut app = App::new(root.to_path_buf()).unwrap();
    hermetic(&mut app, crate::color_depth::ColorDepth::TrueColor);
    without_user_files(&mut app, &root.with_file_name("config"));
    // A clean start says "Ready"; `App::new` reads that from a process-wide
    // latch other tests may set.
    app.status = String::from("Ready");
    // The panel opens on TERMINAL, whose shell prints when it likes, its
    // prompt naming the temp dir: every scene keeps PROBLEMS in front.
    app.bottom_panel_tab = BottomPanelTab::Problems;
    app.theme = theme;
    crate::highlight::set_syntax_palette(theme.syntax());
    app.sync_focus_flags();
    app
}

/// Read again from `config`, an empty folder of the test's own, what
/// `App::new` under test still reads from the user's config and cache
/// folders: the macros, snippets, terminal triggers and agent table, the
/// hosts refused a remote offer, and `config_dir` itself, where the command
/// palette, the Extensions view and the test worker look for added
/// extensions. A developer's own extension or snippet then cannot change
/// what a test sees.
pub(super) fn without_user_files(app: &mut App, config: &Path) {
    app.config_dir = config.to_path_buf();
    app.test_worker.set_extensions_dir(app.extensions_dir());
    app.macros_path = config.join("macros.json");
    app.macro_registers = crate::macros::load(&app.macros_path);
    app.snippets = crate::snippets::SnippetSet::load(&config.join("snippets.json"));
    app.triggers = std::sync::Arc::new(
        crate::triggers::TriggerSet::load(&config.join("triggers.json")).with_builtin_redactions(),
    );
    app.agents = crate::agents::AgentTable::load(&config.join("agents.json"));
    app.remote_offer_refused = Default::default();
}

/// The workbench fixture: a small tree with `src/main.rs` open, the
/// Explorer showing the tree and the bottom panel on PROBLEMS with one
/// warning on `main.rs`.
fn workbench(theme: crate::theme::Theme) -> (Fixture, App) {
    let (fixture, root) = workspace(&[
        ("src/main.rs", MAIN_RS),
        ("src/greeting.rs", "pub fn hello() {}\n"),
        ("README.md", "# golden\n\nA fixture workspace.\n"),
        ("notes.txt", "Nothing to see.\n"),
    ]);
    let mut app = app_with_theme(&root, theme);
    let main = root.join("src/main.rs");
    assert!(app.open_file_at_launch(&main));
    assert!(app.tree.reveal_path(&main));
    let mut by_server = std::collections::HashMap::new();
    by_server.insert(
        String::from("rust-analyzer"),
        vec![crate::lsp::manager::Diagnostic {
            start_line: 20,
            start_char: 8,
            end_line: 20,
            end_char: 13,
            severity: crate::lsp::manager::DiagnosticSeverity::Warning,
            message: String::from("unused variable: `count`"),
            tags: Default::default(),
            code: None,
            origin: None,
        }],
    );
    app.lsp_diagnostics.insert(main.clone(), by_server);
    let merged = app.merged_diagnostics(&main);
    app.editor.apply_diagnostics(main, merged);
    app.rebuild_problems();
    app.refresh_problems_badge();
    (fixture, app)
}

#[test]
fn workbench_default_theme() {
    let (_fixture, mut app) = workbench(crate::theme::Theme::default());
    check_scene(
        "workbench",
        &mut app,
        (120, 40),
        crate::color_depth::ColorDepth::TrueColor,
        no_masks,
    );
}

#[test]
fn welcome_page() {
    let (_fixture, root) = workspace(&[("README.md", "# golden\n")]);
    let mut app = app_with_theme(&root, crate::theme::Theme::default());
    app.welcome.set_test_notes(vec![
        crate::release_notes::ReleaseNote {
            kind: crate::release_notes::NoteKind::Feature,
            summary: "Screen goldens compare **every cell** of a frame",
        },
        crate::release_notes::ReleaseNote {
            kind: crate::release_notes::NoteKind::Fix,
            summary: "A `wide` glyph never shifts the columns after it",
        },
    ]);
    check_scene(
        "welcome",
        &mut app,
        (120, 40),
        crate::color_depth::ColorDepth::TrueColor,
        |app, shot| version_rows(shot, app.editor.last_full_area),
    );
}

/// The name of every golden a scene in this module owns.
fn owned_goldens() -> Vec<String> {
    let fixed = [
        "workbench",
        "welcome",
        "workbench-256",
        "workbench-16",
        "workbench-80x24",
        "command-palette",
        "quick-open",
        "unsaved-changes-prompt",
        "explorer-context-menu",
        "settings-editor",
        "search-results",
        "source-control",
    ];
    let confirms = CONFIRM_SCENES.iter().map(|s| s.name.to_string());
    let confirms_themed = confirm_goldens_in_other_themes();
    let themed = crate::theme::Theme::all()
        .iter()
        .filter(|&&theme| theme != crate::theme::Theme::default())
        .map(|theme| format!("workbench-theme-{}", theme.id()));
    fixed
        .into_iter()
        .map(String::from)
        .chain(confirms)
        .chain(confirms_themed)
        .chain(themed)
        .collect()
}

/// A golden no scene owns, left by a renamed scene or a theme that left the
/// bundle, fails here instead of lingering until a later scene takes its
/// name and passes against a frame nobody blessed for it.
#[test]
fn every_golden_belongs_to_a_scene() {
    let dirs = Dirs::repo();
    let Ok(entries) = std::fs::read_dir(&dirs.golden) else {
        assert!(
            dirs.packaged,
            "no golden folder at {}",
            dirs.golden.display()
        );
        return;
    };
    // Goldens other test modules save here: the key ledger's and the
    // command registry's.
    const SAVED_ELSEWHERE: [&str; 2] = ["key-ledger", "commands"];
    let owned: Vec<String> = owned_goldens()
        .into_iter()
        .chain(SAVED_ELSEWHERE.map(String::from))
        .map(|name| format!("{name}.txt"))
        .collect();
    let mut orphans: Vec<String> = entries
        .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
        .filter(|file| !owned.contains(file))
        .collect();
    orphans.sort();
    assert!(
        orphans.is_empty(),
        "goldens no scene owns (delete them, or add their scene to owned_goldens): {orphans:?}"
    );
}

/// The workbench in every bundled theme but the default, whose scene is
/// `workbench`. A theme added to the bundle fails here until its golden is
/// blessed. Every theme is drawn before the test fails, so one run names
/// them all.
#[test]
fn workbench_in_every_bundled_theme() {
    let themes = crate::theme::Theme::all();
    assert!(themes.contains(&crate::theme::Theme::default()));
    let failures: Vec<String> = themes
        .iter()
        .filter(|&&theme| theme != crate::theme::Theme::default())
        .filter_map(|&theme| {
            let (_fixture, mut app) = workbench(theme);
            let name = format!("workbench-theme-{}", theme.id());
            scene(
                &name,
                &mut app,
                (120, 40),
                crate::color_depth::ColorDepth::TrueColor,
                no_masks,
            )
            .err()
        })
        .collect();
    assert!(failures.is_empty(), "{}", failures.join("\n\n"));
}

#[test]
fn workbench_at_256_colours() {
    let (_fixture, mut app) = workbench(crate::theme::Theme::default());
    check_scene(
        "workbench-256",
        &mut app,
        (120, 40),
        crate::color_depth::ColorDepth::Ansi256,
        no_masks,
    );
}

#[test]
fn workbench_at_16_colours() {
    let (_fixture, mut app) = workbench(crate::theme::Theme::default());
    check_scene(
        "workbench-16",
        &mut app,
        (120, 40),
        crate::color_depth::ColorDepth::Ansi16,
        no_masks,
    );
}

#[test]
fn workbench_in_an_80x24_terminal() {
    let (_fixture, mut app) = workbench(crate::theme::Theme::default());
    check_scene(
        "workbench-80x24",
        &mut app,
        (80, 24),
        crate::color_depth::ColorDepth::TrueColor,
        no_masks,
    );
}

/// Type `text` as plain key presses.
fn type_text(app: &mut App, text: &str) {
    for c in text.chars() {
        app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
            .unwrap();
    }
}

/// The cell where `needle` first starts on screen, searching row by row.
fn find_on_screen(shot: &Shot, needle: &str) -> Option<(u16, u16)> {
    let area = shot.buffer.area;
    (0..area.height).find_map(|y| {
        (0..area.width).find_map(|x| {
            row_text(&shot.buffer, y, x, area.width)
                .starts_with(needle)
                .then_some((x, y))
        })
    })
}

/// [`workbench`] drawn as a scene in the default theme at 120x40.
fn workbench_scene(name: &str, app: &mut App) {
    check_scene(
        name,
        app,
        (120, 40),
        crate::color_depth::ColorDepth::TrueColor,
        no_masks,
    );
}

#[test]
fn command_palette_with_a_typed_query() {
    let (_fixture, mut app) = workbench(crate::theme::Theme::default());
    app.open_command_palette();
    type_text(&mut app, "toggle side");
    workbench_scene("command-palette", &mut app);
}

#[test]
fn quick_open_with_a_typed_query() {
    let (_fixture, mut app) = workbench(crate::theme::Theme::default());
    // The index is walked on a background thread; take it once it lands so
    // the finder never opens on the synchronous fallback walk instead.
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(500),
        "the Go to File index to be built",
        || {
            app.poll_file_finder_index();
            app.file_finder_index.is_some()
        },
    );
    app.run_command(crate::widgets::command_palette::Command::QuickOpen);
    type_text(&mut app, "re");
    workbench_scene("quick-open", &mut app);
}

#[test]
fn unsaved_changes_prompt_on_closing_a_tab() {
    let (_fixture, mut app) = workbench(crate::theme::Theme::default());
    type_text(&mut app, "x");
    assert!(app.editor.dirty);
    app.run_command(crate::widgets::command_palette::Command::CloseEditor);
    assert!(app.pending_unsaved.is_some());
    workbench_scene("unsaved-changes-prompt", &mut app);
}

#[test]
fn explorer_context_menu_on_a_file() {
    let (_fixture, mut app) = workbench(crate::theme::Theme::default());
    let (laid_out, _) = draw(&mut app, 120, 40);
    let (x, y) = find_on_screen(&laid_out, "README.md").expect("README.md is in the tree");
    app.handle_mouse(crossterm::event::MouseEvent {
        kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Right),
        column: x,
        row: y,
        modifiers: KeyModifiers::NONE,
    });
    assert!(app.context_menu.is_some());
    workbench_scene("explorer-context-menu", &mut app);
}

#[test]
fn settings_editor() {
    let (_fixture, mut app) = workbench(crate::theme::Theme::default());
    app.run_command(crate::widgets::command_palette::Command::OpenSettingsEditor);
    assert!(app.settings_editor.is_some());
    workbench_scene("settings-editor", &mut app);
}

#[test]
fn search_view_with_results() {
    let (_fixture, mut app) = workbench(crate::theme::Theme::default());
    app.run_command(crate::widgets::command_palette::Command::ShowSearch);
    type_text(&mut app, "greet");
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(500),
        "the search to finish",
        || {
            app.drain_search_results();
            app.search.progress == SearchProgress::Finished
        },
    );
    assert!(!app.search.hits.is_empty());
    workbench_scene("search-results", &mut app);
}

/// Fail at once, saying why, when the environment carries git state the
/// app's own git commands would inherit. Git's repository variables, set
/// inside a git hook, point them at that repository instead of the
/// fixture's, so the scene could only time out. Settings passed in the
/// environment outrank the repository's own config, so a `log.decorate`
/// there would change what COMMITS shows.
pub(super) fn refuse_inherited_git_state() {
    for var in [
        "GIT_DIR",
        "GIT_WORK_TREE",
        "GIT_INDEX_FILE",
        "GIT_OBJECT_DIRECTORY",
        "GIT_COMMON_DIR",
    ] {
        assert!(
            std::env::var_os(var).is_none(),
            "{var} is set, as inside a git hook: the app's git commands would \
             read that repository, not the fixture's. Run the suite outside \
             the hook."
        );
    }
    for var in ["GIT_CONFIG_COUNT", "GIT_CONFIG_PARAMETERS"] {
        assert!(
            std::env::var_os(var).is_none(),
            "{var} is set: the git settings it passes outrank the fixture's \
             own config in the app's git commands. Run this scene with it \
             unset."
        );
    }
}

/// Run `git` in `dir` through [`test_git`] as a fixed author and committer
/// on a fixed date, running no hook, so the commit (and its hash) is the
/// same on every machine. The date is in 2099, past any clock this suite
/// runs on: COMMITS can show a commit's age, which a past date would grow
/// by a year every year; a future one clamps to `0 seconds ago`, every run.
fn hermetic_git(dir: &Path, args: &[&str]) {
    const WHEN: &str = "2099-01-01T00:00:00+00:00";
    let out = test_git(dir)
        .args(["-c", "core.hooksPath=/dev/null"])
        .args(args)
        .env("GIT_AUTHOR_NAME", "Golden Author")
        .env("GIT_AUTHOR_EMAIL", "author@example.invalid")
        .env("GIT_AUTHOR_DATE", WHEN)
        .env("GIT_COMMITTER_NAME", "Golden Author")
        .env("GIT_COMMITTER_EMAIL", "author@example.invalid")
        .env("GIT_COMMITTER_DATE", WHEN)
        .output()
        .expect("git runs");
    assert!(
        out.status.success(),
        "git {args:?}: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn source_control_with_a_staged_and_an_unstaged_change() {
    refuse_inherited_git_state();
    let (_fixture, root) = workspace(&[("src/main.rs", MAIN_RS), ("README.md", "# golden\n")]);
    // No template: its hooks and excludes would be the developer's.
    hermetic_git(&root, &["init", "-q", "--template=", "-b", "main"]);
    // The app's own git runs read the user's global config, which the
    // repository's own overrides: a global `log.decorate = full` turns
    // COMMITS' `main` into `refs/heads/main`, and `log.showSignature`
    // mixes signature checks into the log the graph reads.
    hermetic_git(&root, &["config", "log.decorate", "short"]);
    hermetic_git(&root, &["config", "log.showSignature", "false"]);
    // A global `commit.template` would seed the empty message box with the
    // developer's own text; an empty one seeds nothing.
    hermetic_git(&root, &["config", "commit.template", "/dev/null"]);
    hermetic_git(&root, &["add", "."]);
    hermetic_git(&root, &["commit", "-q", "-m", "Add the greeter"]);
    std::fs::write(root.join("src/greeting.rs"), "pub fn hello() {}\n").unwrap();
    hermetic_git(&root, &["add", "src/greeting.rs"]);
    std::fs::write(root.join("README.md"), "# golden\n\nNow with a greeting.\n").unwrap();

    let mut app = app_with_theme(&root, crate::theme::Theme::default());
    assert!(app.open_file_at_launch(&root.join("src/main.rs")));
    app.run_command(crate::widgets::command_palette::Command::ShowSourceControl);
    // Status, the change list, the default branch and the COMMITS graph
    // each come back from a thread of their own; take them all. Nothing
    // changes the repository after this, so a reply that lands later says
    // the same.
    crate::test_budget::await_spawned(
        std::time::Duration::from_millis(1000),
        "git to report the changes, the default branch and the commits",
        || {
            app.drain_git_responses();
            app.sync_explorer_panels();
            app.source_control.entries.len() == 2
                && app.default_branch_ask.is_none()
                && app.commit_graph.is_loaded()
                && !app.graph_fetch.is_some()
        },
    );
    workbench_scene("source-control", &mut app);
}

/// A confirm dialog over the workbench, raised by setting the state its
/// command would set: what the dialog draws reads only that state.
struct ConfirmScene {
    name: &'static str,
    raise: fn(&mut App, &Path),
}

/// Every dialog drawn in the centred frame 50 to 96 columns wide but the
/// unsaved-changes prompt, which `unsaved_changes_prompt_on_closing_a_tab`
/// draws: eleven confirms, the run-block one in both its colours, and the
/// unsupported-terminal warning.
const CONFIRM_SCENES: [ConfirmScene; 13] = [
    ConfirmScene {
        name: "confirm-local-open",
        raise: |app, _| app.pending_local_open = Some(String::from("http://localhost:5173/")),
    },
    ConfirmScene {
        name: "confirm-discard",
        raise: |app, _| {
            app.pending_discard = Some(PendingDiscard {
                rel_path: String::from("src/main.rs"),
                untracked: false,
                staged: false,
            });
        },
    },
    ConfirmScene {
        name: "confirm-revert-hunk",
        raise: |app, _| {
            app.pending_revert_hunk = Some(PendingRevertHunk {
                rel_path: String::from("src/main.rs"),
                patch: String::new(),
            });
        },
    },
    ConfirmScene {
        name: "confirm-discard-all",
        raise: |app, _| app.pending_discard_all = true,
    },
    ConfirmScene {
        name: "confirm-stash-drop",
        raise: |app, root| {
            app.pending_stash_drop = Some(PendingStashDrop {
                root: root.to_path_buf(),
                oid: String::from("0123456789abcdef0123456789abcdef01234567"),
                label: String::from("stash@{0}: On main: try the greeter"),
            });
        },
    },
    ConfirmScene {
        name: "confirm-unsaved-scm",
        raise: |app, root| {
            app.pending_unsaved_scm = Some(PendingUnsavedScm {
                op: ScmWrite::Commit,
                root: root.to_path_buf(),
                files: vec![root.join("src/main.rs"), root.join("notes.txt")],
            });
        },
    },
    ConfirmScene {
        name: "confirm-replace-all",
        raise: |app, _| {
            app.search.replace = String::from("farewell");
            app.pending_replace_all = Some((12, 3, 1));
        },
    },
    ConfirmScene {
        name: "confirm-broadcast",
        raise: |app, _| app.pending_broadcast_enable = true,
    },
    ConfirmScene {
        name: "confirm-terminal-paste",
        raise: |app, _| {
            app.pending_terminal_paste =
                Some(b"cargo fmt\ncargo clippy\ncargo test\ncargo build\n".to_vec());
        },
    },
    ConfirmScene {
        name: "confirm-run-block",
        raise: |app, _| app.pending_run_block = Some(run_block(false)),
    },
    ConfirmScene {
        name: "confirm-run-block-destructive",
        raise: |app, _| app.pending_run_block = Some(run_block(true)),
    },
    ConfirmScene {
        name: "confirm-lossy-save",
        raise: |app, root| {
            app.pending_lossy_save = Some(LossySave {
                path: Some(root.join("notes.txt")),
                encoding: "windows-1252",
                chars: vec!['\u{30a2}'],
            });
        },
    },
    ConfirmScene {
        name: "terminal-warning",
        raise: |app, _| app.pending_terminal_warning = true,
    },
];

/// The fenced block the run-block scenes ask about. The directory is
/// relative, so no scene draws the temp dir's absolute path.
fn run_block(destructive: bool) -> PendingRunBlock {
    PendingRunBlock {
        pane_name: String::from("Terminal 1"),
        cwd: PathBuf::from("golden"),
        command: String::from("cargo build && cargo test"),
        code: String::from("cargo build\ncargo test"),
        destructive,
        doc: None,
        block_line: 0,
        persist: false,
        capture_timeout: None,
    }
}

/// The unsupported-terminal warning names the terminal croft runs in, read
/// from `TERM_PROGRAM` or `TERM` as it is drawn; that row is masked.
fn terminal_name_row(_: &App, shot: &Shot) -> Vec<Mask> {
    let (_, above) = find_on_screen(shot, "Croft draws its icons").unwrap_or_else(|| {
        panic!("the unsupported-terminal warning is not on screen");
    });
    let area = shot.buffer.area;
    let row = above + 1;
    // A long terminal name runs the rest of the line off the dialog, so
    // only the word before the name is sure to be on the row.
    assert!(
        row_text(&shot.buffer, row, 0, area.width).contains(" that "),
        "the row under the warning's first line no longer names the terminal"
    );
    vec![Mask {
        name: "terminal",
        area: Rect {
            x: 0,
            y: row,
            width: area.width,
            height: 1,
        },
    }]
}

/// [`CONFIRM_SCENES`] drawn as scenes in `theme`, at 80x24, the size a
/// confirm dialog is narrowest at short of the frame's 50-column floor:
/// those named in `only`, or every one. Every scene is drawn before the
/// test fails, so one run names them all.
fn confirm_scenes(theme: crate::theme::Theme, only: Option<&[&str]>, suffix: &str) -> Vec<String> {
    CONFIRM_SCENES
        .iter()
        .filter(|s| only.is_none_or(|names| names.contains(&s.name)))
        .filter_map(|s| {
            let (_fixture, mut app) = workbench(theme);
            let root = app.workspace_root().to_path_buf();
            (s.raise)(&mut app, &root);
            let masks = if s.name == "terminal-warning" {
                terminal_name_row
            } else {
                no_masks
            };
            scene(
                &format!("{}{suffix}", s.name),
                &mut app,
                (80, 24),
                crate::color_depth::ColorDepth::TrueColor,
                masks,
            )
            .err()
        })
        .collect()
}

#[test]
fn every_confirm_dialog() {
    let failures = confirm_scenes(crate::theme::Theme::default(), None, "");
    assert!(failures.is_empty(), "{}", failures.join("\n\n"));
}

/// The themes [`every_confirm_dialog_in_other_themes`] draws the dialogs
/// in, each with the dialogs it draws (`None`: every one). The default
/// theme lays the warning card's tones over a dialog, which redraw its
/// title and keys at normal weight, so Dark Blue, a boxed theme, draws
/// every dialog with its own colours and weights as given. Light and High
/// Contrast Black take colours through other paths of `Theme::ui`: one red
/// dialog and one amber one, with the frame's narrow padding, cover the
/// frame there.
const CONFIRM_THEMES: [(&str, Option<&[&str]>); 3] = [
    ("dark-blue", None),
    ("light", Some(&["confirm-discard", "confirm-replace-all"])),
    (
        "hc-black",
        Some(&["confirm-discard", "confirm-replace-all"]),
    ),
];

/// The name of every golden [`every_confirm_dialog_in_other_themes`]
/// owns.
fn confirm_goldens_in_other_themes() -> Vec<String> {
    CONFIRM_THEMES
        .into_iter()
        .flat_map(|(id, only)| {
            CONFIRM_SCENES
                .iter()
                .filter(move |s| only.is_none_or(|names| names.contains(&s.name)))
                .map(move |s| format!("{}-{id}", s.name))
        })
        .collect()
}

#[test]
fn every_confirm_dialog_in_other_themes() {
    let failures: Vec<String> = CONFIRM_THEMES
        .into_iter()
        .flat_map(|(id, only)| {
            let theme = crate::theme::Theme::from_id(id);
            // `from_id` falls back to the default theme on a name it lacks.
            assert_eq!(theme.id(), id, "no bundled theme {id:?}");
            confirm_scenes(theme, only, &format!("-{id}"))
        })
        .collect();
    assert!(failures.is_empty(), "{}", failures.join("\n\n"));
}