monospace 0.1.0

The interactive full-screen terminal application: the chrome around a diagram being edited
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
//! One frame of the screen: the three regions, and the order they are painted in.
//!
//! **The order is the picture.** The bar, then the region, then the status bar, then the
//! drop-down, and the overlays last of all: a widget drawn later covers the one before it, and a
//! drop-down drawn under the region could not be seen, let alone clicked. **The overlays cover the
//! drop-down as well as everything else** (D6 of #189), and at most one is up at a time; the text
//! editor is the last of them to be painted.
//!
//! **Every cell of the screen is painted on every frame.** The terminal diffs against the
//! previous frame rather than clearing, so a cell that is not painted keeps what was in it. The
//! frame therefore clears the screen before it draws anything into it, and a region that the
//! frame is not using — because the screen is too short to hold it — is cleared rather than
//! left alone.

use rat_salsa::SalsaContext;
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::{Constraint, Layout, Rect};
use ratatui_core::widgets::Widget;
use ratatui_widgets::clear::Clear;

use crate::context::AppGlobal;
use crate::state::AppState;
use crate::{diagram_widget, dialog, export, menu, open, save, status, text};

/// The height of the bar across the top.
pub(crate) const BAR_HEIGHT: u16 = 1;

/// The height of the status bar along the bottom.
pub(crate) const STATUS_HEIGHT: u16 = 2;

/// The three regions of the screen.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Regions {
    /// The bar across the top.
    pub bar: Rect,

    /// The region the diagram goes into.
    pub region: Rect,

    /// The status bar along the bottom.
    pub status: Rect,
}

/// The regions of a screen of the given size.
///
/// **The bar's row is the bar's and the status bar's row is the status bar's**, whatever the
/// size of the screen: what is left between them is the region, and it takes the rest.
pub(crate) fn regions(area: Rect) -> Regions {
    let [bar, region, status] = Layout::vertical([
        Constraint::Length(BAR_HEIGHT),
        Constraint::Fill(1),
        Constraint::Length(STATUS_HEIGHT),
    ])
    .areas(area);

    Regions {
        bar,
        region,
        status,
    }
}

/// Paints one frame.
pub(crate) fn draw(area: Rect, buf: &mut Buffer, state: &mut AppState, global: &AppGlobal) {
    let regions = regions(area);

    // Every cell of the screen is painted on every frame, and this is what paints the ones no
    // region uses.
    Clear.render(area, buf);

    let focused = state.chrome().is_bar();
    menu::draw_bar(
        regions.bar,
        buf,
        state.chrome_mut().menu_mut(),
        &global.cfg.theme,
        focused,
    );

    diagram_widget::draw(
        regions.region,
        buf,
        state.diagram_mut(),
        &global.catalog,
        &global.cfg.theme,
    );

    // **Read after the region is drawn**, because the footprint is a fact of the drawing rather than
    // of the session: the buffer this frame measured is the one the click paths will be answered
    // from, so the bar and the pointer agree about what is on screen.
    status::draw(regions.status, buf, state.diagram(), &global.cfg.theme);

    // The drop-down is drawn after the region: it hangs from the bar and covers the region, and
    // a region painted after it would erase it.
    menu::draw_drop_down(area, buf, state.chrome_mut().menu_mut(), &global.cfg.theme);

    // **The message dialog is drawn after the drop-down** (D6): it is an overlay, so it covers the
    // drop-down and everything else, and a control behind it is not there to be seen or clicked.
    dialog::draw(regions.region, buf, state.dialog_mut(), &global.cfg.theme);

    // **The open dialog, save dialog and export dialog are overlays at the top layer.** At most
    // one of the overlays is ever up, and the frame says where the field's cursor goes when one
    // is.
    let open_cursor = open::draw(regions.region, buf, state.open_mut(), &global.cfg.theme);
    let save_cursor = save::draw(regions.region, buf, state.save_mut(), &global.cfg.theme);
    let export_cursor = export::draw(regions.region, buf, state.export_mut(), &global.cfg.theme);

    // **The text editor is the last overlay**, after the open, save and export dialogs, and at
    // most one overlay is up at a time. It sets the terminal's cursor when its buffer holds the
    // focus.
    let text_cursor = text::draw(regions.region, buf, state.text_mut(), &global.cfg.theme);
    global.set_screen_cursor(
        text_cursor
            .or(open_cursor)
            .or(save_cursor)
            .or(export_cursor),
    );
}

/// Where a piece of text is on a frame, found in the frame itself so that a growing label
/// does not move a click away from it.
#[cfg(test)]
pub(crate) fn cell_of(buffer: &Buffer, text: &str) -> (u16, u16) {
    (buffer.area.top()..buffer.area.bottom())
        .find_map(|line| {
            let row: String = (buffer.area.left()..buffer.area.right())
                .map(|column| buffer[(column, line)].symbol().to_string())
                .collect();

            row.find(text).map(|offset| {
                let column =
                    buffer.area.left() + u16::try_from(offset).expect("an offset fits a frame");
                (column, line)
            })
        })
        .unwrap_or_else(|| panic!("{text} is not on the frame"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;
    use crate::context::AppGlobal;
    use crate::diagram_state::{End, SubMode};
    use crate::state::AppState;
    use crate::status;
    use crate::text::TextEditorState;
    use crate::vocabulary::Reply;
    use monospace_core::{Offset, ShapeId};
    use monospace_diagram::Text;
    use monospace_editing::Command;
    use rat_theme4::palettes::dark::BASE16;
    use rat_theme4::themes::create_dark;
    use ratatui_core::buffer::Buffer;
    use ratatui_core::layout::Position;
    use ratatui_core::style::Modifier;
    use ratatui_crossterm::crossterm::event::{
        Event, KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
    };
    use std::num::NonZeroU16;

    /// The width of the screens these tests draw.
    const WIDTH: u16 = 40;

    /// The height of the screens these tests draw.
    const HEIGHT: u16 = 10;

    /// What one snapshot says about itself, so that a reader of the file knows what it is
    /// looking at without opening the code.
    const WHAT: &str = concat!(
        "A picture of the screen, as the frame paints it. The three regions are counted under ",
        "the picture: the bar across the top, the region the diagram goes into, and the status ",
        "bar along the bottom. The count of the cells that are not blank is there because a ",
        "picture alone cannot say how much of the screen is spoken for, and because a number ",
        "that is derived from the frame cannot be wrong the way a hand-written expectation is.",
    );

    /// The state of an application that starts with nothing in it.
    fn a_state() -> AppState {
        AppState::new(crate::empty_session())
    }

    /// The state of an application over the diagram `json` describes.
    fn a_state_over(json: &str) -> AppState {
        let diagram =
            monospace_description::parse(json).expect("the test's description is readable");

        AppState::new(monospace_editing::Session::new(diagram))
    }

    /// A description whose only shape is a light 4×3 box at `(2, 1)` of the window.
    const A_BOX: &str = r#"{
        "next_id": 2,
        "shapes": [ { "kind": "box", "id": 1, "at": { "x": 2, "y": 1 },
                      "size": { "width": 4, "height": 3 }, "stroke": "light" } ]
    }"#;

    /// A description whose only shape is a light 4×3 box at `(2, 1)` holding `hi`.
    const A_BOX_WITH_TEXT: &str = r#"{
        "next_id": 2,
        "shapes": [ { "kind": "box", "id": 1, "at": { "x": 2, "y": 1 },
                      "size": { "width": 4, "height": 3 }, "stroke": "light",
                      "text": "hi" } ]
    }"#;

    /// A description whose only shape is a 2×2 light box at `(2, 1)` of the window.
    const A_NARROW_BOX: &str = r#"{
        "next_id": 2,
        "shapes": [ { "kind": "box", "id": 1, "at": { "x": 2, "y": 1 },
                      "size": { "width": 2, "height": 2 }, "stroke": "light" } ]
    }"#;

    /// Two light 4×3 boxes side by side, the left at `(2, 1)` of the window and the right at
    /// `(6, 1)`: the second is as close to the first as a shape can be without sharing a cell.
    const A_BOX_AND_ITS_NEIGHBOR: &str = r#"{
        "next_id": 3,
        "shapes": [ { "kind": "box", "id": 1, "at": { "x": 2, "y": 1 },
                      "size": { "width": 4, "height": 3 }, "stroke": "light" },
                    { "kind": "box", "id": 2, "at": { "x": 6, "y": 1 },
                      "size": { "width": 4, "height": 3 }, "stroke": "light" } ]
    }"#;

    /// A description whose only shape is a 4×3 box in the ASCII table.
    const AN_ASCII_BOX: &str = r#"{
        "next_id": 2,
        "shapes": [ { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 },
                      "size": { "width": 4, "height": 3 }, "stroke": "ascii" } ]
    }"#;

    /// A description whose only shape names a stroke no table answers.
    const A_BOX_IN_NO_TABLE: &str = r#"{
        "next_id": 2,
        "shapes": [ { "kind": "box", "id": 1, "at": { "x": 0, "y": 0 },
                      "size": { "width": 4, "height": 3 }, "stroke": "mystery" } ]
    }"#;

    /// The configuration the application starts with.
    fn a_global() -> AppGlobal {
        AppGlobal::new(Config::default(), monospace_glyph_sets::all())
    }

    /// Paints a frame into a buffer of the given size.
    fn paint(state: &mut AppState, global: &AppGlobal, width: u16, height: u16) -> Buffer {
        let area = Rect::new(0, 0, width, height);
        let mut buffer = Buffer::empty(area);
        draw(area, &mut buffer, state, global);
        buffer
    }

    /// One row of a frame, as text.
    fn row_of(buffer: &Buffer, line: u16) -> String {
        (buffer.area.left()..buffer.area.right())
            .map(|column| buffer[(column, line)].symbol().to_string())
            .collect()
    }

    /// The picture of a frame, as text, with the trailing blanks of each row cut.
    fn picture(buffer: &Buffer) -> String {
        (buffer.area.top()..buffer.area.bottom())
            .map(|line| row_of(buffer, line).trim_end().to_string())
            .collect::<Vec<String>>()
            .join("\n")
    }

    /// The drop-down's own cells, cut out of the frame.
    ///
    /// **The pop-up is drawn over what it covers**, so a picture of the frame holds the region
    /// behind it, and two frames of the same menu over two drawings would differ in the part the
    /// menu does not own. The cut is the pop-up's box: from the row under the bar to the row of its
    /// lower border, and from its upper-left corner to its upper-right one.
    fn drop_down_picture(buffer: &Buffer) -> String {
        let top = BAR_HEIGHT;
        let row: Vec<char> = row_of(buffer, top).chars().collect();

        // The region draws a corner of its own on this row, so the drop-down's is the last one.
        let mut left = None;

        for (column, glyph) in row.iter().enumerate() {
            if *glyph == '┌' {
                left = Some(column);
            }
        }

        let left = left.expect("the drop-down has no upper-left corner");
        let right = row
            .iter()
            .skip(left)
            .position(|glyph| *glyph == '┐')
            .map(|offset| left + offset)
            .expect("the drop-down has no upper-right corner");

        let mut lines = Vec::new();

        for line in top..buffer.area.bottom() {
            let text: String = row_of(buffer, line)
                .chars()
                .skip(left)
                .take(right - left + 1)
                .collect();
            let last = text.starts_with('└');

            lines.push(text);

            if last {
                break;
            }
        }

        lines.join("\n")
    }

    /// The number of cells of the frame that are not blank.
    fn written(buffer: &Buffer) -> usize {
        (buffer.area.top()..buffer.area.bottom())
            .flat_map(|line| {
                (buffer.area.left()..buffer.area.right()).map(move |column| (line, column))
            })
            .filter(|(line, column)| buffer[(*column, *line)].symbol() != " ")
            .count()
    }

    /// The counts of a frame: how many rows each region has, and how many cells are not blank.
    fn counts(buffer: &Buffer, regions: Regions) -> String {
        let total = usize::from(buffer.area.width) * usize::from(buffer.area.height);

        format!(
            "the bar is {} {}, the region is {} {} and the status is {} {}\n\
             {} of {total} cells are not blank",
            regions.bar.height,
            rows(regions.bar.height),
            regions.region.height,
            rows(regions.region.height),
            regions.status.height,
            rows(regions.status.height),
            written(buffer),
        )
    }

    /// What a number of rows is called.
    fn rows(count: u16) -> &'static str {
        if count == 1 { "row" } else { "rows" }
    }

    /// Writes one snapshot.
    fn snap(name: &str, body: &str) {
        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/src/snapshots/contract"
        ));
        settings.set_description(WHAT);
        settings.bind(|| insta::assert_snapshot!(name, body));
    }

    /// Opens the drop-down of `navigation`, the way a person does.
    ///
    /// **The bar is drawn first**: the widget knows where its labels are only once a frame has
    /// been drawn, and a key that arrives before that finds nothing to open.
    fn open_the_drop_down(state: &mut AppState, global: &AppGlobal, navigation: char) {
        let _ = paint(state, global, WIDTH, HEIGHT);
        state.chrome_mut().move_to_bar();
        let event = Event::Key(KeyEvent::new(KeyCode::Char(navigation), KeyModifiers::NONE));
        let _ = crate::menu::handle(&event, state.chrome_mut());
        assert!(
            state.chrome().popup_active(),
            "the navigation character did not open the drop-down"
        );
    }

    /// The picture of a frame, with the counts under it.
    fn described(buffer: &Buffer, regions: Regions) -> String {
        format!("{}\n{}", picture(buffer), counts(buffer, regions))
    }

    /// Whether the cell at a frame position is painted in reverse video.
    fn reversed(buffer: &Buffer, column: u16, line: u16) -> bool {
        buffer[(column, line)]
            .style()
            .add_modifier
            .contains(Modifier::REVERSED)
    }

    /// The frame positions whose cell is painted in reverse video, in the order the frame is read.
    fn inverted(buffer: &Buffer) -> Vec<(u16, u16)> {
        (buffer.area.top()..buffer.area.bottom())
            .flat_map(|line| {
                (buffer.area.left()..buffer.area.right()).map(move |column| (column, line))
            })
            .filter(|(column, line)| reversed(buffer, *column, *line))
            .collect()
    }

    /// The screen positions the box of `A_BOX` writes: its border, at `(2, 1)` of the window and
    /// four cells wide and three tall.
    ///
    /// **A box's interior is not a cell of the drawing**, so nothing is written there and nothing
    /// is inverted there: the ten cells here are what the copy writes for the box. The window's
    /// corner is the screen's `(1, 2)`.
    fn cells_of_the_box() -> Vec<(u16, u16)> {
        vec![
            (3, 3),
            (4, 3),
            (5, 3),
            (6, 3),
            (3, 4),
            (6, 4),
            (3, 5),
            (4, 5),
            (5, 5),
            (6, 5),
        ]
    }

    /// Clicks the screen position `(column, line)` with the left button, the way a person does.
    fn click(state: &mut AppState, column: u16, line: u16) {
        let event = Event::Mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column,
            row: line,
            modifiers: KeyModifiers::NONE,
        });

        let target = state.target_at(Position::new(column, line));
        let leaf = state.chrome().leaf();
        let outcome = crate::diagram_widget::handle(&event, state.diagram_mut(), leaf, target);

        assert!(
            matches!(outcome, Reply::Repaint),
            "({column}, {line}) selected nothing: {outcome:?}"
        );
    }

    #[test]
    fn the_bar_is_at_the_top_and_the_status_bar_is_at_the_bottom() {
        let buffer = paint(&mut a_state(), &a_global(), WIDTH, HEIGHT);
        let regions = regions(Rect::new(0, 0, WIDTH, HEIGHT));

        let bar = row_of(&buffer, 0);
        let region = row_of(&buffer, 1);
        let status_bar = row_of(&buffer, regions.status.top());
        let command_bar = row_of(&buffer, regions.status.top() + 1);

        assert!(bar.contains("File"), "the bar has no File on it: {bar:?}");
        assert!(
            region.starts_with('┌'),
            "the region does not start under the bar: {region:?}"
        );
        assert!(
            status_bar.contains(status::NAME),
            "the status bar says nothing: {status_bar:?}"
        );
        assert!(
            command_bar.starts_with("CREATE: [b] Box [l] Line [c] Connector"),
            "the command bar offers shape creation when diagram has no shapes: {command_bar:?}"
        );
    }

    #[test]
    fn the_region_between_them_takes_the_rest_of_the_screen() {
        for height in [3, 10, 24] {
            let regions = regions(Rect::new(0, 0, WIDTH, height));

            assert_eq!(regions.bar.height, BAR_HEIGHT, "{height} rows");
            assert_eq!(regions.status.height, STATUS_HEIGHT, "{height} rows");
            assert_eq!(
                regions.region.height,
                height - BAR_HEIGHT - STATUS_HEIGHT,
                "{height} rows"
            );
            assert_eq!(regions.region.top(), BAR_HEIGHT, "{height} rows");
            assert_eq!(
                regions.region.bottom(),
                height - STATUS_HEIGHT,
                "{height} rows"
            );
        }
    }

    #[test]
    fn the_interior_is_the_window_the_diagram_is_drawn_into() {
        let mut state = a_state_over(A_BOX);
        let buffer = paint(&mut state, &a_global(), WIDTH, HEIGHT);

        // The box is at `(2, 1)` of the window, and the window starts one cell in from the
        // region's corner: the region's row is 1, so the box's top-left is row 3, column 3.
        assert_eq!(
            buffer[(3, 3)].symbol(),
            "┌",
            "the box's top-left is not at the interior's (2, 1)"
        );
        assert_eq!(
            buffer[(6, 3)].symbol(),
            "┐",
            "the box is not four cells wide from the interior's corner"
        );
        assert_eq!(
            buffer[(3, 5)].symbol(),
            "└",
            "the box is not three cells tall from the interior's corner"
        );
        assert_eq!(
            buffer[(1, 2)].symbol(),
            " ",
            "the interior's own corner holds something"
        );

        // The record counts the offset from the same corner the drawing does.
        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_some(),
            "the box does not own the cell it drew"
        );
    }

    #[test]
    fn the_diagram_is_drawn_again_on_every_frame() {
        let mut state = a_state_over(A_BOX);
        let global = a_global();

        let _ = paint(&mut state, &global, WIDTH, HEIGHT);
        assert!(
            state.diagram().owner(Offset { x: 2, y: 2 }).is_some(),
            "the first frame did not draw the box"
        );

        // A screen three rows shorter: the interior is two rows tall, and the box's third row
        // is outside it. The drawing of the frame that follows is what answers.
        let _ = paint(&mut state, &global, WIDTH, 6);
        assert!(
            state.diagram().owner(Offset { x: 2, y: 2 }).is_none(),
            "the drawing of the first frame survived the second"
        );
    }

    #[test]
    fn a_cell_no_shape_wrote_is_a_space() {
        let buffer = paint(&mut a_state_over(A_BOX), &a_global(), WIDTH, HEIGHT);

        assert_eq!(
            buffer[(1, 2)].symbol(),
            " ",
            "the interior's corner, which no shape wrote, is not a space"
        );
    }

    #[test]
    fn a_glyph_the_catalog_does_not_know_is_a_space() {
        let buffer = paint(
            &mut a_state_over(A_BOX_IN_NO_TABLE),
            &a_global(),
            WIDTH,
            HEIGHT,
        );

        // The box's own cells are at `(0, 0)` through `(3, 2)` of the window, and no table has a
        // rule for its stroke: every one of them renders as a space.
        for line in 2..5 {
            for column in 1..5 {
                assert_eq!(
                    buffer[(column, line)].symbol(),
                    " ",
                    "({column}, {line}) is not a space"
                );
            }
        }
    }

    #[test]
    fn the_owner_survives_the_copy() {
        let mut state = a_state_over(A_BOX);
        let buffer = paint(&mut state, &a_global(), WIDTH, HEIGHT);
        let diagram = state.diagram();

        let top_left = Offset { x: 2, y: 1 };
        let top_right = Offset { x: 5, y: 1 };

        assert!(
            diagram.owner(top_left).is_some(),
            "the copy took the record with it"
        );
        assert_eq!(
            diagram.owner(top_left),
            diagram.owner(top_right),
            "two cells of the same box name two different shapes"
        );

        // The picture and the record are the same drawing.
        assert_eq!(buffer[(3, 3)].symbol(), "┌", "the copy drew no box");
        assert_eq!(buffer[(6, 3)].symbol(), "┐", "the copy drew no box");
    }

    #[test]
    fn the_owner_is_asked_with_the_click_offset_and_nothing_added() {
        let mut state = a_state_over(A_NARROW_BOX);
        let _ = paint(&mut state, &a_global(), WIDTH, HEIGHT);
        let diagram = state.diagram();

        // The box is at `(2, 1)` of the window and covers two rows: `(3, 3)` is the click with
        // the interior's corner `(1, 2)` added to it, and it names a cell nobody wrote.
        assert!(
            diagram.owner(Offset { x: 2, y: 1 }).is_some(),
            "the click's own offset is not the one asked"
        );
        assert!(
            diagram.owner(Offset { x: 3, y: 3 }).is_none(),
            "the interior's corner was added to the click"
        );
    }

    #[test]
    fn the_buffer_of_the_last_frame_answers_a_click() {
        let mut state = a_state_over(A_BOX);
        let global = a_global();

        assert!(
            state.diagram().owner(Offset { x: 2, y: 1 }).is_none(),
            "the empty drawing answered a click"
        );

        let _ = paint(&mut state, &global, WIDTH, HEIGHT);
        let asked = state.diagram().owner(Offset { x: 2, y: 1 });
        assert!(asked.is_some(), "the frame's drawing does not answer");

        let _ = paint(&mut state, &global, WIDTH, HEIGHT);
        assert_eq!(
            state.diagram().owner(Offset { x: 2, y: 1 }),
            asked,
            "the second frame's drawing does not answer the same click"
        );
    }

    /// **A click is a question and not a command.** The session is only read, so the frame that
    /// follows holds the same cells and the same record; what the click changed is the style of
    /// those cells, which a picture of symbols does not show.
    #[test]
    fn a_click_changes_no_diagram() {
        let mut state = a_state_over(A_BOX);
        let global = a_global();

        let before = paint(&mut state, &global, WIDTH, HEIGHT);
        let asked = state.diagram().owner(Offset { x: 2, y: 1 });
        assert!(asked.is_some(), "the box is not in the drawing");

        // The box's top-left is the screen's `(3, 3)`.
        click(&mut state, 3, 3);

        let after = paint(&mut state, &global, WIDTH, HEIGHT);

        assert_eq!(
            state.diagram().owner(Offset { x: 2, y: 1 }),
            asked,
            "the click changed which shape the drawing records"
        );
        let region = regions(Rect::new(0, 0, WIDTH, HEIGHT)).region;
        for line in region.top()..region.bottom() {
            assert_eq!(
                row_of(&before, line),
                row_of(&after, line),
                "the click changed row {line} in the region"
            );
        }
        assert!(
            !inverted(&after).is_empty(),
            "the click selected nothing, so the frame proves nothing"
        );
    }

    /// **The inversion is the record's answer, cell by cell.** The cells of the selected shape are
    /// reverse video and no others, however close another shape's cells are.
    #[test]
    fn the_selected_shapes_cells_are_inverted_and_no_others() {
        let mut state = a_state_over(A_BOX_AND_ITS_NEIGHBOR);
        let global = a_global();
        let _ = paint(&mut state, &global, WIDTH, HEIGHT);

        // The left box's top-left, and no cell of the right one.
        click(&mut state, 3, 3);
        let buffer = paint(&mut state, &global, WIDTH, HEIGHT);

        assert_eq!(
            inverted(&buffer),
            cells_of_the_box(),
            "the cells the frame inverts are not the selected box's"
        );
        assert!(
            !reversed(&buffer, 7, 3),
            "the neighboring box's border is inverted"
        );
    }

    /// A description with a box, a detached connector and a neighboring box.
    const A_BOX_A_CONNECTOR_AND_A_NEIGHBOR: &str = r#"{
        "next_id": 4,
        "shapes": [
            { "kind": "box", "id": 1, "at": { "x": 2, "y": 1 },
              "size": { "width": 4, "height": 3 }, "stroke": "light" },
            { "kind": "connector", "id": 2,
              "from": { "at": { "kind": "point", "x": 8, "y": 2 },
                        "leaving": "right", "terminal": { "kind": "arm" } },
              "to": { "at": { "kind": "point", "x": 12, "y": 2 },
                      "leaving": "left", "terminal": { "kind": "arm" } },
              "stroke": "light" },
            { "kind": "box", "id": 3, "at": { "x": 16, "y": 1 },
              "size": { "width": 4, "height": 3 }, "stroke": "light" }
        ]
    }"#;

    /// **The attach picker inverts both the focused target and the selected connector.**
    /// Any neighboring shape that is not the target is not inverted.
    #[test]
    fn the_attach_picker_inverts_the_target_and_the_selected_connector() {
        let mut state = a_state_over(A_BOX_A_CONNECTOR_AND_A_NEIGHBOR);
        let global = a_global();
        let id1 = ShapeId::new(NonZeroU16::new(1).expect("1 is non-zero"));
        let id2 = ShapeId::new(NonZeroU16::new(2).expect("2 is non-zero"));

        // Select the connector first to determine its inverted cells
        state.diagram_mut().select(Some(id2));
        let conn_buffer = paint(&mut state, &global, WIDTH, HEIGHT);
        let conn_cells = inverted(&conn_buffer);
        assert!(
            !conn_cells.is_empty(),
            "connector cells should not be empty"
        );

        // Focus box #1 as attach target in AttachSelect
        state
            .diagram_mut()
            .set_sub_mode(Some(SubMode::AttachSelect {
                end: End::From,
                target: id1,
            }));
        let buffer = paint(&mut state, &global, WIDTH, HEIGHT);

        let mut expected = cells_of_the_box();
        expected.extend(conn_cells);
        expected.sort_by_key(|&(x, y)| (y, x));
        expected.dedup();

        assert_eq!(
            inverted(&buffer),
            expected,
            "the attach picker inverts exactly the target box and the selected connector"
        );
        assert!(
            !reversed(&buffer, 17, 3),
            "the neighboring box's border is inverted"
        );
    }

    /// **The inversion is read from the record and not from the selection.** An identity no cell of
    /// the drawing names inverts nothing, which is what leaves a command that removes the selected
    /// shape a frame with no inversion rather than a stale one (rule 7).
    #[test]
    fn a_selection_the_drawing_does_not_record_inverts_nothing() {
        let mut state = a_state_over(A_BOX);
        let global = a_global();
        let _ = paint(&mut state, &global, WIDTH, HEIGHT);

        let unrecorded = ShapeId::new(NonZeroU16::new(9).expect("9 is not zero"));
        assert!(
            state.diagram_mut().select(Some(unrecorded)),
            "the selection did not move"
        );

        let buffer = paint(&mut state, &global, WIDTH, HEIGHT);

        assert!(
            inverted(&buffer).is_empty(),
            "an identity no cell records inverted cells"
        );
    }

    /// **A shape the window does not hold is still selected.** The state holds the identity, so a
    /// frame that holds the shape again inverts it: the selection is what the click recorded, and
    /// not the cells the frame that answered it happened to hold.
    #[test]
    fn a_selected_shape_with_no_cell_in_the_window_is_still_selected() {
        let mut state = a_state_over(A_BOX);
        let global = a_global();
        let _ = paint(&mut state, &global, WIDTH, HEIGHT);
        click(&mut state, 3, 3);

        // Four rows leave the region two and its interior none: the window holds no cell of the
        // box, so nothing is drawn and nothing is inverted.
        let empty = paint(&mut state, &global, WIDTH, 4);
        assert!(
            inverted(&empty).is_empty(),
            "a cell of a shape the window does not hold is inverted"
        );
        assert!(
            state.diagram().selected().is_some(),
            "the selection was dropped when the window stopped holding the shape"
        );

        let held_again = paint(&mut state, &global, WIDTH, HEIGHT);

        assert_eq!(
            inverted(&held_again),
            cells_of_the_box(),
            "the frame that holds the box again does not invert it"
        );
    }

    /// **The selection is an identity, so a resize recomputes what it covers.** A screen shorter
    /// than the box clips it: the part the window holds is inverted and the rest is not, and the
    /// screen that holds the whole box again inverts the whole box.
    #[test]
    fn the_selection_survives_a_resize() {
        let mut state = a_state_over(A_BOX);
        let global = a_global();
        let _ = paint(&mut state, &global, WIDTH, HEIGHT);
        click(&mut state, 3, 3);

        // Eight rows leave the region five rows and its interior three: the box's third row is
        // outside the window.
        let clipped = paint(&mut state, &global, WIDTH, 8);
        let rows_the_window_holds: Vec<(u16, u16)> = cells_of_the_box()
            .into_iter()
            .filter(|(_, line)| *line < 5)
            .collect();

        assert_eq!(
            inverted(&clipped),
            rows_the_window_holds,
            "the resize inverted cells the window does not hold, or dropped the cells it does"
        );

        let restored = paint(&mut state, &global, WIDTH, HEIGHT);

        assert_eq!(
            inverted(&restored),
            cells_of_the_box(),
            "the selection did not survive the resize"
        );
    }

    /// **The dialog is drawn over the drop-down** (rule 9): it is an overlay, so it covers the
    /// drop-down as well as the region, and a control behind it is not there to be seen.
    #[test]
    fn the_dialog_is_drawn_over_the_drop_down() {
        let mut state = a_state();
        let global = a_global();

        open_the_drop_down(&mut state, &global, 'f');
        state.dialog_mut().show(crate::about::open());
        let frame = picture(&paint(&mut state, &global, WIDTH, HEIGHT));

        assert!(
            frame.contains(&format!("About {}", status::NAME)),
            "the dialog is not on the frame: {frame:?}"
        );
        assert!(
            !frame.contains("Quit"),
            "the drop-down is drawn over the dialog: {frame:?}"
        );
    }

    /// **The palette is the dark BASE16 theme** (rule 12): the frame the default configuration
    /// paints is the one the theme paints, cell for cell, so nothing reads a terminal color and no
    /// other palette is in use.
    #[test]
    fn the_palette_is_the_dark_base16_theme() {
        let by_default = paint(&mut a_state(), &a_global(), WIDTH, HEIGHT);

        let dark = AppGlobal::new(
            Config {
                theme: create_dark(BASE16),
            },
            monospace_glyph_sets::all(),
        );
        let by_the_theme = paint(&mut a_state(), &dark, WIDTH, HEIGHT);

        for line in 0..HEIGHT {
            for column in 0..WIDTH {
                assert_eq!(
                    by_default[(column, line)].symbol(),
                    by_the_theme[(column, line)].symbol(),
                    "({column}, {line}) is not what the dark BASE16 theme paints"
                );
                assert_eq!(
                    by_default[(column, line)].style(),
                    by_the_theme[(column, line)].style(),
                    "({column}, {line}) is painted in another palette"
                );
            }
        }
    }

    /// **The region has no focus cue of its own** (D2 of #189): it is the body, and it is drawn the
    /// same whether or not it holds the keyboard. A cue lives on a control that has one, so the
    /// frame that moves the keyboard to the bar leaves every cell of the region untouched.
    #[test]
    fn the_region_is_drawn_the_same_with_and_without_the_keyboard() {
        let mut state = a_state_over(A_BOX);
        let global = a_global();
        let area = Rect::new(0, 0, WIDTH, HEIGHT);
        let region = regions(area).region;

        state.chrome_mut().move_to_region();
        let without = paint(&mut state, &global, WIDTH, HEIGHT);
        state.chrome_mut().move_to_bar();
        let with = paint(&mut state, &global, WIDTH, HEIGHT);

        for line in region.top()..region.bottom() {
            for column in region.left()..region.right() {
                assert_eq!(
                    with[(column, line)].symbol(),
                    without[(column, line)].symbol(),
                    "({column}, {line}) changed with the keyboard"
                );
                assert_eq!(
                    with[(column, line)].style(),
                    without[(column, line)].style(),
                    "({column}, {line}) was painted differently with the keyboard"
                );
            }
        }
    }

    #[test]
    fn an_ascii_box_is_drawn_with_the_ascii_table() {
        let buffer = paint(&mut a_state_over(AN_ASCII_BOX), &a_global(), WIDTH, HEIGHT);

        assert!(
            row_of(&buffer, 2).starts_with("│+--+"),
            "the box's top is not in the ASCII table: {:?}",
            row_of(&buffer, 2)
        );
        assert!(
            row_of(&buffer, 3).starts_with("│|  |"),
            "the box's sides are not in the ASCII table: {:?}",
            row_of(&buffer, 3)
        );
        assert!(
            row_of(&buffer, 4).starts_with("│+--+"),
            "the box's bottom is not in the ASCII table: {:?}",
            row_of(&buffer, 4)
        );
    }

    #[test]
    fn an_empty_diagram_draws_nothing() {
        let buffer = paint(&mut a_state(), &a_global(), WIDTH, HEIGHT);
        let region = regions(Rect::new(0, 0, WIDTH, HEIGHT)).region;

        for line in region.top() + 1..region.bottom() - 1 {
            for column in region.left() + 1..region.right() - 1 {
                assert_eq!(
                    buffer[(column, line)].symbol(),
                    " ",
                    "({column}, {line}) is not blank"
                );
            }
        }

        assert!(
            row_of(&buffer, region.top()).starts_with('┌'),
            "the frame went with the diagram"
        );
    }

    #[test]
    fn a_region_with_no_interior_draws_nothing() {
        let mut state = a_state_over(A_BOX);
        let buffer = paint(&mut state, &a_global(), WIDTH, 4);

        assert_eq!(
            row_of(&buffer, 1),
            " ".repeat(usize::from(WIDTH)),
            "a region with no interior drew something"
        );
        assert!(
            state.diagram().owner(Offset { x: 0, y: 0 }).is_none(),
            "a window with no cells owns one"
        );
    }

    #[test]
    fn the_status_bar_says_how_far_the_drawing_reaches() {
        let mut state = a_state_over(A_BOX);

        let whole = paint(&mut state, &a_global(), WIDTH, HEIGHT);

        // A screen whose interior is two rows tall: the box's third row is outside the window, and
        // the bar still says the box's own size. What the picture lost to the window is not what
        // the drawing reached.
        let clipped = paint(&mut state, &a_global(), WIDTH, 6);

        assert!(
            row_of(&whole, HEIGHT - 2).contains("4×3 at 2,1"),
            "the bar does not say where the box of A_BOX reaches: {:?}",
            row_of(&whole, HEIGHT - 2)
        );
        assert!(
            row_of(&clipped, 4).contains("4×3 at 2,1"),
            "a window too small to hold the box changed how far it reaches: {:?}",
            row_of(&clipped, 4)
        );
    }

    #[test]
    fn a_blank_diagram_is_drawn_when_no_path_is_given() {
        let session = crate::start(None).expect("startup with no path succeeds");
        let buffer = paint(&mut AppState::new(session), &a_global(), 60, HEIGHT);

        assert!(
            row_of(&buffer, HEIGHT - 2).contains("nothing drawn"),
            "the status bar does not say nothing drawn for blank startup"
        );
    }

    #[test]
    fn the_description_at_the_path_is_drawn() {
        let path =
            std::env::temp_dir().join(format!("monospace-app-frame-{}.json", std::process::id()));
        std::fs::write(&path, A_BOX).expect("the temp description should be writable");
        let named = path.to_str().expect("the temp path is UTF-8");

        let session = crate::start(Some(named)).expect("the description at the path is readable");
        let buffer = paint(&mut AppState::new(session), &a_global(), WIDTH, HEIGHT);

        let _ = std::fs::remove_file(&path);

        assert_eq!(
            buffer[(3, 3)].symbol(),
            "┌",
            "the description at the path is not drawn where its box says"
        );
    }

    /// **The demonstration's cells inside the region are the ones they were** (rule 8): its drawing
    /// is larger than the interior on both axes and was already clipped, so the two bars that now
    /// appear move the border and nothing else.
    ///
    /// **What the region holds is what the drawing puts there**, cell for cell, through the window
    /// the frame drew at — and the landmarks the picture is read by are where the one before this
    /// change had them.
    #[test]
    fn the_demonstrations_picture_keeps_its_cells() {
        let session = crate::demo().expect("the shipped demonstration is readable");
        let mut state = AppState::new(session);
        let buffer = paint(&mut state, &a_global(), WIDTH, HEIGHT);
        let region = regions(Rect::new(0, 0, WIDTH, HEIGHT)).region;
        let catalog = monospace_glyph_sets::all();

        for line in region.top() + 1..region.bottom() - 1 {
            for column in region.left() + 1..region.right() - 1 {
                let at = Offset {
                    x: column - region.left() - 1,
                    y: line - region.top() - 1,
                };
                let drawn = state.diagram().glyph(at, &catalog).unwrap_or(" ");

                assert_eq!(
                    buffer[(column, line)].symbol(),
                    drawn,
                    "({column}, {line}) is not the cell the drawing holds there"
                );
            }
        }

        let first = row_of(&buffer, region.top() + 1);
        assert!(
            first.starts_with("│┌──┐"),
            "the demonstration's first row moved: {first:?}"
        );
        assert!(
            first.contains("+--+"),
            "the demonstration's ASCII box moved: {first:?}"
        );
    }

    #[test]
    fn the_screen_with_the_demo() {
        let session = crate::demo().expect("the shipped demonstration is readable");
        let mut state = AppState::new(session);
        let area = Rect::new(0, 0, WIDTH, HEIGHT);
        let buffer = paint(&mut state, &a_global(), WIDTH, HEIGHT);

        snap(
            "the_screen_with_the_demo",
            &format!(
                "the screen with the demonstration, {WIDTH}x{HEIGHT}\n{}",
                described(&buffer, regions(area))
            ),
        );
    }

    #[test]
    fn the_bars_row_is_drawn_on_every_frame() {
        let mut state = a_state();
        let global = a_global();

        let at_rest = row_of(&paint(&mut state, &global, WIDTH, HEIGHT), 0);

        // The drop-down opens over the region, and the bar's row is still the bar's row.
        state.chrome_mut().menu_mut().bar.select(Some(0));
        state.chrome_mut().menu_mut().set_popup_active(true);
        let with_drop_down = row_of(&paint(&mut state, &global, WIDTH, HEIGHT), 0);

        assert!(
            at_rest.contains("File"),
            "the bar has no File on it: {at_rest:?}"
        );
        assert_eq!(at_rest, with_drop_down, "the drop-down took the bar's row");
    }

    #[test]
    fn a_region_that_stops_being_drawn_does_not_keep_what_was_last_in_it() {
        let mut state = a_state();
        let global = a_global();
        let mut buffer = Buffer::empty(Rect::new(0, 0, WIDTH, HEIGHT));

        // A screen tall enough for the region: the region is a box.
        draw(
            Rect::new(0, 0, WIDTH, HEIGHT),
            &mut buffer,
            &mut state,
            &global,
        );
        assert!(
            row_of(&buffer, 1).starts_with('┌'),
            "the region is not a box: {:?}",
            row_of(&buffer, 1)
        );

        // A screen too short to hold it: the region is not drawn, and what it held is gone.
        draw(Rect::new(0, 0, WIDTH, 4), &mut buffer, &mut state, &global);

        assert_eq!(
            row_of(&buffer, 1),
            " ".repeat(usize::from(WIDTH)),
            "the region kept what was last in it"
        );
    }

    #[test]
    fn a_drop_down_is_not_erased_by_the_region_being_painted_after_it() {
        let mut state = a_state();
        let global = a_global();

        open_the_drop_down(&mut state, &global, 'f');
        let buffer = paint(&mut state, &global, WIDTH, HEIGHT);
        let frame = picture(&buffer);

        assert!(
            frame.contains("Quit"),
            "the drop-down shows nothing: {frame:?}"
        );
        assert!(frame.contains('┐'), "the drop-down has no frame: {frame:?}");
    }

    #[test]
    fn a_drop_down_leaves_the_region_byte_identical_when_it_closes() {
        let mut state = a_state_over(A_BOX);
        let global = a_global();

        let before = paint(&mut state, &global, WIDTH, HEIGHT);

        // The drop-down opens over the region and closes again.
        open_the_drop_down(&mut state, &global, 'f');
        let _ = paint(&mut state, &global, WIDTH, HEIGHT);
        state.chrome_mut().menu_mut().set_popup_active(false);
        let after = paint(&mut state, &global, WIDTH, HEIGHT);

        for line in 0..HEIGHT {
            assert_eq!(
                row_of(&before, line),
                row_of(&after, line),
                "row {line} is not what it was"
            );
        }
    }

    /// **The entries do not move with the history** (rule 10). The same drop-down is drawn over a
    /// fresh session and over one a deletion has left, and the two pictures are equal: no entry
    /// carries a flag, and `can_undo` and `can_redo` are not read by the frame.
    #[test]
    fn the_edit_menu_offers_undo_and_redo_at_every_position() {
        let mut state = a_state_over(A_BOX);
        let global = a_global();

        open_the_drop_down(&mut state, &global, 'e');
        let fresh = drop_down_picture(&paint(&mut state, &global, WIDTH, HEIGHT));

        // The drop-down closes, the box is removed, and the same drop-down opens over the newest
        // position.
        state.chrome_mut().menu_mut().set_popup_active(false);
        let shape = ShapeId::new(NonZeroU16::new(1).expect("1 is not zero"));
        state.diagram_mut().perform(Command::Remove { id: shape });
        let _ = paint(&mut state, &global, WIDTH, HEIGHT);
        open_the_drop_down(&mut state, &global, 'e');
        let after_the_delete = drop_down_picture(&paint(&mut state, &global, WIDTH, HEIGHT));

        assert!(
            fresh.contains("Undo"),
            "the drop-down shows no undo: {fresh:?}"
        );
        assert!(
            fresh.contains("Redo"),
            "the drop-down shows no redo: {fresh:?}"
        );
        assert_eq!(
            fresh, after_the_delete,
            "the Edit menu moves with the history"
        );
    }

    #[test]
    fn the_screen_at_rest() {
        let mut state = a_state();
        let global = a_global();
        let area = Rect::new(0, 0, WIDTH, HEIGHT);
        let buffer = paint(&mut state, &global, WIDTH, HEIGHT);

        snap(
            "the_screen_at_rest",
            &format!(
                "the screen at rest, {WIDTH}x{HEIGHT}\n{}",
                described(&buffer, regions(area))
            ),
        );
    }

    #[test]
    fn the_drop_down_open_over_the_region() {
        let mut state = a_state();
        let global = a_global();
        let area = Rect::new(0, 0, WIDTH, HEIGHT);

        open_the_drop_down(&mut state, &global, 'f');
        let buffer = paint(&mut state, &global, WIDTH, HEIGHT);

        snap(
            "the_drop_down_open_over_the_region",
            &format!(
                "the drop-down open over the region, {WIDTH}x{HEIGHT}\n{}",
                described(&buffer, regions(area))
            ),
        );
    }

    /// **The Edit drop-down is the picture the two extra entries make.** Undo, Redo and Delete are
    /// drawn in that order, each with the shortcut the table answers to.
    #[test]
    fn the_edit_drop_down() {
        let mut state = a_state();
        let global = a_global();
        let area = Rect::new(0, 0, WIDTH, HEIGHT);

        open_the_drop_down(&mut state, &global, 'e');
        let buffer = paint(&mut state, &global, WIDTH, HEIGHT);

        snap(
            "the_edit_drop_down",
            &format!(
                "the Edit drop-down open over the region, {WIDTH}x{HEIGHT}\n{}",
                described(&buffer, regions(area))
            ),
        );
    }

    #[test]
    fn the_status_bar_below_the_region() {
        let mut state = a_state();
        let global = a_global();
        let area = Rect::new(0, 0, WIDTH, HEIGHT);
        let buffer = paint(&mut state, &global, WIDTH, HEIGHT);

        let regions = regions(area);
        let status_bar = row_of(&buffer, regions.status.top());
        let command_bar = row_of(&buffer, regions.status.top() + 1);

        assert!(
            regions.status.top() == regions.region.bottom(),
            "the status bar is not below the region"
        );
        assert!(
            status_bar.contains(status::NAME),
            "the status bar says nothing: {status_bar:?}"
        );
        assert!(
            command_bar.starts_with("CREATE: [b] Box [l] Line [c] Connector"),
            "the command bar offers shape creation when diagram has no shapes: {command_bar:?}"
        );

        snap(
            "the_status_bar_below_the_region",
            &format!(
                "the status bar below the region, {WIDTH}x{HEIGHT}\n{}",
                described(&buffer, regions)
            ),
        );
    }

    #[test]
    fn the_status_bar_is_unchanged_while_editing() {
        let mut state = a_state_over(A_BOX);
        let id = ShapeId::new(NonZeroU16::new(1).unwrap());
        state.diagram_mut().select(Some(id));

        let before = paint(&mut state, &a_global(), WIDTH, HEIGHT);
        let status = regions(Rect::new(0, 0, WIDTH, HEIGHT)).status;
        let before_rows: Vec<String> = (status.top()..status.bottom())
            .map(|line| row_of(&before, line))
            .collect();

        let text = Text::new("hi").unwrap();
        state.text_mut().show(TextEditorState::new(id, Some(&text)));

        let after = paint(&mut state, &a_global(), WIDTH, HEIGHT);
        let after_rows: Vec<String> = (status.top()..status.bottom())
            .map(|line| row_of(&after, line))
            .collect();

        assert_eq!(
            before_rows, after_rows,
            "opening the editor changed the status bar"
        );
    }

    #[test]
    fn the_text_editor_over_a_box() {
        let mut state = a_state_over(A_BOX_WITH_TEXT);
        let global = a_global();
        let area = Rect::new(0, 0, WIDTH, HEIGHT);
        let id = ShapeId::new(NonZeroU16::new(1).unwrap());
        state.diagram_mut().select(Some(id));

        let text = Text::new("hi").unwrap();
        state.text_mut().show(TextEditorState::new(id, Some(&text)));

        let buffer = paint(&mut state, &global, WIDTH, HEIGHT);

        snap(
            "a_box_with_the_text_editor_over_it",
            &format!(
                "a box with the text editor over it, {WIDTH}x{HEIGHT}\n{}",
                described(&buffer, regions(area))
            ),
        );

        state.text_mut().close();
        let buffer = paint(&mut state, &global, WIDTH, HEIGHT);

        snap(
            "the_same_box_after_the_editor_closes",
            &format!(
                "the same box after the editor closes, {WIDTH}x{HEIGHT}\n{}",
                described(&buffer, regions(area))
            ),
        );
    }
}