datui-lib 0.4.1

Data Exploration in the Terminal (library)
Documentation
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
//! The mouse: what a click, a drag or a turn of the wheel means where it lands.
//!
//! Keys stay the interface and the mouse is a shortcut to them. The wheel presses
//! the arrows of whatever has the keys, a click on a footer key presses it, a click on
//! a form's row focuses it and presses Space, a click on a tab steps the tab bar to
//! it, and a click on the table or the home list moves the cursor there, a double
//! click then pressing Enter. A click on a chart's plot puts the crosshair there, as
//! `x` and the arrows would. Dragging a header moves its column as `H` / `L` do, and
//! dragging the gap after it sets its width as `<` / `>` do; a double click on a header
//! sorts by it as `[` / `]` do, and on the gap after it fits it as `=` does. A right
//! click on a cell opens a menu of the keys that act on it. Nothing here changes what a key does.
//!
//! A pointer is aimed at what is on screen when it is used, so mouse input is never
//! held for later the way typed keys are: where a typed key would wait, a mouse event
//! is dropped (see [`crate::event_pump::EventPump::terminal_mouse`]).
//!
//! What a click can land on is recorded while a frame is drawn ([`record`]): the
//! widget that lays a row or a tab out says where it put it, so nothing computes the
//! layout a second time.

use std::cell::RefCell;
use std::time::{Duration, Instant};

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
use ratatui::layout::{Position, Rect};

use crate::form::{FieldKind, Form};
use crate::widgets::datatable::CellHit;
use crate::{App, InputMode};

/// Rows a notch of the wheel moves.
pub const WHEEL_ROWS: usize = 3;

/// Two clicks on one cell this close together are a double click.
pub const DOUBLE_CLICK: Duration = Duration::from_millis(500);

/// The mouse events the app acts on: a left press, its drag and release, a right
/// press, and the wheel. Motion with no button down and the middle button are left
/// alone.
pub fn wanted(mouse: &MouseEvent) -> bool {
    matches!(
        mouse.kind,
        MouseEventKind::Down(MouseButton::Left | MouseButton::Right)
            | MouseEventKind::Drag(MouseButton::Left)
            | MouseEventKind::Up(MouseButton::Left)
            | MouseEventKind::ScrollDown
            | MouseEventKind::ScrollUp
            | MouseEventKind::ScrollLeft
            | MouseEventKind::ScrollRight
    )
}

/// Ask the terminal for presses, releases, motion while a button is down (a drag)
/// and the wheel, SGR-encoded so a wide screen's far columns report right. Not
/// crossterm's `EnableMouseCapture`, which also asks for every motion with no button
/// down: a stream of events the app would only throw away. Undone by
/// `DisableMouseCapture`, which turns off every mode.
pub struct EnableMouse;

impl crossterm::Command for EnableMouse {
    fn write_ansi(&self, f: &mut impl std::fmt::Write) -> std::fmt::Result {
        f.write_str("\x1b[?1000h\x1b[?1002h\x1b[?1006h")
    }

    #[cfg(windows)]
    fn execute_winapi(&self) -> std::io::Result<()> {
        crossterm::Command::execute_winapi(&crossterm::event::EnableMouseCapture)
    }

    #[cfg(windows)]
    fn is_ansi_code_supported(&self) -> bool {
        crossterm::Command::is_ansi_code_supported(&crossterm::event::EnableMouseCapture)
    }
}

/// Take the mouse from the terminal when `on` (`display.mouse`, `--mouse`); off, the
/// terminal keeps it, and selecting text works as it does anywhere.
pub fn capture(on: bool, out: &mut impl std::io::Write) {
    if on {
        let _ = crossterm::execute!(out, EnableMouse);
    }
}

/// A form's field as drawn: the form, by its type, and the field, by name. Kept as
/// text so a frame's regions need not know every form's field type.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldId {
    form: &'static str,
    field: String,
}

impl FieldId {
    pub fn of<T: Form>(field: T::Field) -> Self {
        Self {
            form: std::any::type_name::<T>(),
            field: format!("{field:?}"),
        }
    }

    /// Focus this field in `form` when it is that form's and shown there. Says what
    /// the field is and whether the click acts on it too.
    pub fn focus_in<T: Form>(&self, form: &mut T) -> Option<Clicked> {
        if self.form != std::any::type_name::<T>() {
            return None;
        }
        let (field, kind) = form
            .fields()
            .into_iter()
            .find(|(f, _)| format!("{f:?}") == self.field)?;
        let focused_already = form.focused() == field;
        let acts = !form.list_row(field) || focused_already;
        form.focus(field).then_some(Clicked { kind, acts })
    }
}

/// A field a click focused: its kind, and whether the click acts on it as well (a
/// list row's first click only focuses it: [`Form::list_row`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Clicked {
    pub kind: FieldKind,
    pub acts: bool,
}

/// What a region of the frame is, for a click.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Hit {
    /// A form's row: a click focuses it, then acts as Space.
    Field(FieldId),
    /// One of a choice's values drawn side by side, a tab bar's tab: a click focuses
    /// the field, when there is one, then steps it there with ← / →.
    Option {
        field: Option<FieldId>,
        index: usize,
        current: usize,
    },
    /// A line of an open picker: its place in the list as narrowed, the cursor's, and
    /// whether the list takes several. A click moves the cursor there and chooses.
    PickerItem {
        visible: usize,
        selected: usize,
        multi: bool,
    },
    /// An open picker's whole area. While one is open only it takes clicks.
    Picker,
    /// A row edited in place, such as a filter: while it is, nothing else takes
    /// clicks.
    Editor,
    /// A line of the analysis tools list.
    Tool(usize),
    /// Something a key names, a chart kind's tab (`1`-`6`): a click presses it.
    Key(KeyEvent),
    /// A dialog's footer chip: a click presses its key, even while a picker or an
    /// editor has the other clicks, or a question is up.
    Chip(KeyEvent),
    /// A line of the context menu.
    MenuItem(usize),
    /// The context menu's frame.
    Menu,
    /// A dialog that owns the keys, drawn over what came before: a click outside
    /// it does nothing, and only what is drawn after it, inside it, takes clicks.
    Modal,
}

thread_local! {
    /// The regions of the frame being drawn; `None` outside one, so a widget drawn on
    /// its own (a test's buffer) records nothing.
    static DRAWING: RefCell<Option<Vec<(Rect, Hit)>>> = const { RefCell::new(None) };
}

/// Say what a region of the frame being drawn is. Later regions lie on top.
pub fn record(rect: Rect, hit: Hit) {
    if rect.width == 0 || rect.height == 0 {
        return;
    }
    DRAWING.with_borrow_mut(|drawing| {
        if let Some(regions) = drawing {
            regions.push((rect, hit));
        }
    });
}

/// Say that `rect` is form `T`'s row for `field`.
pub fn record_field<T: Form>(rect: Rect, field: T::Field) {
    record(rect, Hit::Field(FieldId::of::<T>(field)));
}

/// Record a line's spans that a click picks among: each `(span, hit)` names a span of
/// `line`, drawn left-aligned from `area.x` on `area.y`. Their places are summed from
/// the spans drawn, so they agree with the line on screen.
pub fn record_spans(area: Rect, line: &ratatui::text::Line, spans: Vec<(usize, Hit)>) {
    let mut x = area.x;
    let mut at = Vec::with_capacity(line.spans.len());
    for span in &line.spans {
        let w = span.width() as u16;
        at.push((x, w));
        x = x.saturating_add(w);
    }
    for (i, hit) in spans {
        let Some(&(x, w)) = at.get(i) else { continue };
        if x >= area.right() {
            continue;
        }
        record(Rect::new(x, area.y, w.min(area.right() - x), 1), hit);
    }
}

/// What `draw` records, as a frame would: for a widget's tests.
#[cfg(test)]
pub(crate) fn recording(draw: impl FnOnce()) -> Vec<(Rect, Hit)> {
    begin_recording();
    draw();
    end_recording()
}

fn begin_recording() {
    DRAWING.with_borrow_mut(|drawing| *drawing = Some(Vec::new()));
}

fn end_recording() -> Vec<(Rect, Hit)> {
    DRAWING.with_borrow_mut(|drawing| drawing.take().unwrap_or_default())
}

/// What a mouse event comes to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Pointer {
    Nothing,
    /// Press these keys in order, as if typed, as far as typed keys would act now.
    Keys(Vec<KeyEvent>),
    /// Move to what was clicked, then press the key if there is one (a double
    /// click's Enter).
    Point(Target, Option<KeyEvent>),
    /// Focus a form's field, when one is named, then press keys: with `act`, the key
    /// for what the field is ([`act_key`]; `true` for a right click), else `keys`.
    Form {
        field: Option<FieldId>,
        act: Option<bool>,
        keys: Vec<KeyEvent>,
    },
    /// The analysis tools list: put its cursor on this tool and press Enter.
    Tool(usize),
    /// Start setting a column's width by dragging the gap after it.
    Resize {
        column: String,
        x: u16,
    },
    /// A width dragged to: set it, as `<` and `>` do.
    Width {
        column: String,
        width: u16,
    },
    /// A header let go over another column: move it there, as `H` and `L` do.
    Drop {
        column: String,
        onto: String,
    },
    /// Open the context menu on this cell, at this point.
    Menu(CellHit, Position),
    /// A line of the context menu: close it and press its key.
    MenuChoose(usize),
    /// A click outside the open menu: close it, nothing more.
    CloseMenu,
    /// Nothing to press, but what is drawn changed (a header carried over another
    /// column): a frame is due.
    Redraw,
}

/// Where a click or the wheel moves the cursor.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Target {
    /// A cell of the table as drawn.
    Table(CellHit),
    /// A row of the home list, by its place among those listed.
    HomeRow(usize),
    /// The home list's selection, moved this many rows and stopped at the ends: the
    /// arrows there go round, which a wheel must not.
    HomeStep(isize),
    /// The chart's crosshair, on the point drawn nearest this column; the plot takes
    /// the keys, as `x` gives them to it.
    ChartColumn(u16),
}

/// A drag in progress, from a press on the table's header.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Drag {
    /// A header picked up: the column, and the column it is over now.
    Move { column: String, over: String },
    /// The gap after a header: the column, where the press was, and its width then.
    Resize { column: String, x: u16, width: u16 },
}

/// What the last frame drew where, the last click, and a drag in progress.
#[derive(Debug, Default)]
pub struct Pointing {
    /// The footer's keys and the key each presses.
    chips: Vec<(Rect, KeyEvent)>,
    /// The home list: its area and the row on each of its lines.
    home_list: Option<(Rect, Vec<Option<usize>>)>,
    /// Everything else the frame said a click can land on, bottom first.
    hits: Vec<(Rect, Hit)>,
    last_click: Option<(u16, u16, Instant)>,
    drag: Option<Drag>,
    /// Something was handled after the last frame was painted, so what it shows may
    /// not be what a click there would now land on.
    changed: bool,
}

impl Pointing {
    /// Something was handled: the frame on screen may be out of date.
    pub fn changed(&mut self) {
        self.changed = true;
    }

    /// A frame was painted: the screen shows the app as it is.
    pub fn painted(&mut self) {
        self.changed = false;
    }

    /// Whether the frame on screen shows the app as it is, so the regions recorded
    /// while drawing it are where a click lands.
    pub fn on_screen(&self) -> bool {
        !self.changed
    }

    /// A frame begins: what it does not draw cannot be clicked.
    pub fn forget_drawn(&mut self) {
        self.chips.clear();
        self.home_list = None;
        self.hits.clear();
        begin_recording();
    }

    /// The frame is drawn: keep what it recorded.
    pub fn drawn(&mut self) {
        self.hits = end_recording();
    }

    /// The footer's keys as drawn. A key that is not one key (`↑↓`) presses nothing.
    pub fn chips_drawn(&mut self, chips: Vec<(Rect, &str)>) {
        self.chips = chips
            .into_iter()
            .filter_map(|(rect, key)| chip_key(key).map(|key| (rect, key)))
            .collect();
    }

    /// The home list as drawn: `lines[i]` is the row on the list's line `i`.
    pub fn home_list_drawn(&mut self, area: Rect, lines: Vec<Option<usize>>) {
        self.home_list = Some((area, lines));
    }

    /// The drag in progress, if any.
    pub fn drag(&self) -> Option<&Drag> {
        self.drag.as_ref()
    }

    fn chip_at(&self, at: Position) -> Option<KeyEvent> {
        self.chips
            .iter()
            .find(|(rect, _)| rect.contains(at))
            .map(|(_, key)| *key)
    }

    fn home_row_at(&self, at: Position) -> Option<usize> {
        let (area, lines) = self.home_list.as_ref()?;
        if !area.contains(at) {
            return None;
        }
        lines.get(usize::from(at.y - area.y)).copied().flatten()
    }

    /// What the frame drew at `at`, topmost first. Under a dialog, only what it
    /// drew; while a picker or an editor is open, only a picker's lines.
    fn hit_at(&self, at: Position) -> Option<&Hit> {
        let hits = match self.hits.iter().rposition(|(_, hit)| *hit == Hit::Modal) {
            Some(i) if !self.hits[i].0.contains(at) => return None,
            Some(i) => &self.hits[i + 1..],
            None => &self.hits[..],
        };
        let open = hits
            .iter()
            .any(|(_, hit)| matches!(hit, Hit::Picker | Hit::Editor));
        hits.iter()
            .rev()
            .filter(|(_, hit)| {
                !open || matches!(hit, Hit::Picker | Hit::PickerItem { .. } | Hit::Chip(_))
            })
            .find(|(rect, _)| rect.contains(at))
            .map(|(_, hit)| hit)
    }

    /// Whether the frame has an open picker under `at`.
    fn over_picker(&self, at: Position) -> bool {
        self.hits
            .iter()
            .any(|(rect, hit)| *hit == Hit::Picker && rect.contains(at))
    }

    /// Whether a click at `at` is the second of a double click. A third click starts
    /// over, so a triple click is a double click and then a click.
    fn second_click(&mut self, at: Position, now: Instant) -> bool {
        let double = self.last_click.is_some_and(|(x, y, then)| {
            (x, y) == (at.x, at.y) && now.saturating_duration_since(then) <= DOUBLE_CLICK
        });
        self.last_click = if double {
            None
        } else {
            Some((at.x, at.y, now))
        };
        double
    }
}

/// The key a double click on `column`'s header presses: `[` sorts up by it, `]` turns
/// that sort down, and `]` again takes it away, as the same key again does.
fn header_sort_key(state: &crate::widgets::datatable::DataTableState, column: &str) -> char {
    if state.view_sort_columns() == [column] {
        ']'
    } else {
        '['
    }
}

/// The key a chip's label names, when it names one key: `Enter`, `^O`, `q`, `F1`.
pub fn chip_key(label: &str) -> Option<KeyEvent> {
    let named = |code| Some(KeyEvent::new(code, KeyModifiers::NONE));
    match label {
        "Enter" => return named(KeyCode::Enter),
        "Esc" => return named(KeyCode::Esc),
        "Tab" => return named(KeyCode::Tab),
        "Space" => return named(KeyCode::Char(' ')),
        "F1" => return named(KeyCode::F(1)),
        _ => {}
    }
    let mut chars = label.chars();
    match (chars.next(), chars.next(), chars.next()) {
        (Some('^'), Some(c), None) if c.is_ascii_alphabetic() => Some(KeyEvent::new(
            KeyCode::Char(c.to_ascii_lowercase()),
            KeyModifiers::CONTROL,
        )),
        // As a terminal reports it: an upper-case letter comes with Shift.
        (Some(c), None, None) if c.is_ascii_uppercase() => {
            Some(KeyEvent::new(KeyCode::Char(c), KeyModifiers::SHIFT))
        }
        (Some(c), None, None) if c.is_ascii_graphic() => named(KeyCode::Char(c)),
        _ => None,
    }
}

fn press(code: KeyCode) -> KeyEvent {
    KeyEvent::new(code, KeyModifiers::NONE)
}

/// `delta` presses of `forward`, or of `back` when it is negative.
fn steps(delta: isize, back: KeyCode, forward: KeyCode) -> Vec<KeyEvent> {
    let code = if delta < 0 { back } else { forward };
    vec![press(code); delta.unsigned_abs()]
}

/// The key a click presses on a field it focused: Space acts on it (toggles,
/// steps, opens, presses); a right click steps a choice back, as ← does, and only
/// focuses anything else. A text field only takes focus.
pub fn act_key(kind: FieldKind, back: bool) -> Option<KeyEvent> {
    match kind {
        FieldKind::Text | FieldKind::MultilineText => None,
        FieldKind::Choice | FieldKind::Picker { multi: false } if back => {
            Some(press(KeyCode::Left))
        }
        _ if back => None,
        _ => Some(press(KeyCode::Char(' '))),
    }
}

/// What a click on `hit` does; `back` for a right click.
fn click_hit(hit: &Hit, back: bool) -> Pointer {
    match hit {
        Hit::Field(id) => Pointer::Form {
            field: Some(id.clone()),
            act: Some(back),
            keys: Vec::new(),
        },
        Hit::Option {
            field,
            index,
            current,
        } => Pointer::Form {
            field: field.clone(),
            act: None,
            keys: steps(
                *index as isize - *current as isize,
                KeyCode::Left,
                KeyCode::Right,
            ),
        },
        Hit::PickerItem {
            visible,
            selected,
            multi,
        } => {
            let mut keys = steps(
                *visible as isize - *selected as isize,
                KeyCode::Up,
                KeyCode::Down,
            );
            keys.push(press(if *multi {
                KeyCode::Char(' ')
            } else {
                KeyCode::Enter
            }));
            Pointer::Keys(keys)
        }
        Hit::Tool(i) => Pointer::Tool(*i),
        Hit::Key(key) | Hit::Chip(key) => Pointer::Keys(vec![*key]),
        Hit::MenuItem(i) => Pointer::MenuChoose(*i),
        Hit::Picker | Hit::Editor | Hit::Menu | Hit::Modal => Pointer::Nothing,
    }
}

impl App {
    /// What a mouse event means on the screen last drawn.
    pub fn pointer(&mut self, mouse: &MouseEvent, now: Instant) -> Pointer {
        let shift = mouse.modifiers.contains(KeyModifiers::SHIFT);
        // A menu something else has covered since is gone, as for a key.
        if self.context_menu.is_some() && !self.menu_showing() {
            self.close_context_menu();
        }
        let at = Position {
            x: mouse.column,
            y: mouse.row,
        };
        match mouse.kind {
            MouseEventKind::ScrollDown if shift => self.wheel_across(true),
            MouseEventKind::ScrollUp if shift => self.wheel_across(false),
            MouseEventKind::ScrollRight => self.wheel_across(true),
            MouseEventKind::ScrollLeft => self.wheel_across(false),
            MouseEventKind::ScrollDown => self.wheel(true, at),
            MouseEventKind::ScrollUp => self.wheel(false, at),
            MouseEventKind::Down(MouseButton::Left) => {
                self.pointer.drag = None;
                self.click(at, now)
            }
            MouseEventKind::Down(MouseButton::Right) => {
                self.pointer.drag = None;
                self.right_click(at)
            }
            MouseEventKind::Drag(MouseButton::Left) => self.drag_to(at),
            MouseEventKind::Up(MouseButton::Left) => self.release(),
            _ => Pointer::Nothing,
        }
    }

    /// A key was pressed: a header being carried is put back, and its mark goes.
    pub fn cancel_drag(&mut self) {
        self.pointer.drag = None;
    }

    /// Forget the last click and any drag: it was dropped, so the next is not its
    /// second, and nothing was picked up.
    pub fn forget_click(&mut self) {
        self.pointer.last_click = None;
        self.pointer.drag = None;
    }

    /// Move the cursor to what a click or the wheel landed on. A press on a header
    /// picks the column up, for a drag to move.
    pub fn point(&mut self, target: &Target) {
        // As a key does: the line about the last action is stale now.
        self.flash = None;
        match target {
            Target::Table(hit) => {
                if let Some(state) = self.data_table_state.as_mut() {
                    state.point_at(hit);
                }
                if let (None, Some(column)) = (hit.row, &hit.column) {
                    self.pointer.drag = Some(Drag::Move {
                        column: column.clone(),
                        over: column.clone(),
                    });
                }
            }
            Target::HomeRow(row) => {
                self.home.status = None;
                self.home.select(*row);
            }
            Target::HomeStep(rows) => {
                self.home.status = None;
                self.home.page_selection(*rows);
            }
            Target::ChartColumn(column) => {
                self.chart_modal.plot_focus = true;
                self.move_crosshair_to(Some(*column));
            }
        }
    }

    /// Put the cursor on the cell a right click landed on, for the menu. Returns
    /// whether it is there: rows that moved since they were drawn are not the ones
    /// clicked, and the menu would act on another cell.
    pub fn point_for_menu(&mut self, hit: &CellHit) -> bool {
        self.flash = None;
        self.data_table_state
            .as_mut()
            .is_some_and(|state| state.point_at(hit))
    }

    /// Focus the field a click landed on, in whichever form drew it.
    pub fn focus_field(&mut self, id: &FieldId) -> Option<Clicked> {
        self.flash = None;
        if let Some(kind) = id.focus_in(&mut self.chart_modal) {
            // The option rows take the keys back from the plot's crosshair.
            self.chart_modal.plot_focus = false;
            return Some(kind);
        }
        let shown = id
            .focus_in(&mut self.export_modal)
            .or_else(|| id.focus_in(&mut self.copy_modal))
            .or_else(|| id.focus_in(&mut self.chart_export_modal))
            .or_else(|| id.focus_in(&mut self.pivot_melt_modal))
            .or_else(|| id.focus_in(&mut self.sort_filter_modal))
            .or_else(|| id.focus_in(&mut self.view_modal))
            .or_else(|| self.combine.as_mut().and_then(|c| id.focus_in(c)))
            .or_else(|| self.sample_form.as_mut().and_then(|f| id.focus_in(f)));
        if shown.is_some() {
            return shown;
        }
        let analysis = &mut self.analysis_modal;
        let kind = analysis
            .sample_form
            .as_mut()
            .and_then(|f| id.focus_in(f))
            .or_else(|| {
                analysis
                    .data_quality_expected_form
                    .as_mut()
                    .and_then(|f| id.focus_in(f))
            })
            .or_else(|| {
                analysis
                    .data_quality_intent_form
                    .as_mut()
                    .and_then(|f| id.focus_in(f))
            })?;
        // A form in the result pane takes the keys once the pane has them.
        analysis.focus = crate::analysis_modal::AnalysisFocus::Main;
        Some(kind)
    }

    /// Put the analysis tools list's cursor on `tool`, the list focused, as Tab and
    /// the arrows would.
    pub fn point_at_tool(&mut self, tool: usize) {
        self.flash = None;
        self.analysis_modal.focus = crate::analysis_modal::AnalysisFocus::Sidebar;
        self.analysis_modal.sidebar_state.select(Some(tool));
    }

    /// Start a width drag on `column`, from the width it has now.
    pub fn start_resize(&mut self, column: String, x: u16) {
        use crate::widgets::column_widths::{UNSEEN_WIDTH, WidthChoice};
        let width = self
            .data_table_state
            .as_ref()
            .and_then(|state| match state.width_choice(&column) {
                WidthChoice::Manual(w) => Some(w),
                _ => state.on_screen_width(&column),
            })
            .unwrap_or(UNSEEN_WIDTH);
        self.pointer.drag = Some(Drag::Resize { column, x, width });
    }

    /// Set a column's width by hand, as `<` and `>` do, within their bounds.
    pub fn set_dragged_width(&mut self, column: String, width: u16) {
        use crate::widgets::column_widths::{MAX_WIDTH, MIN_WIDTH, WidthChoice};
        self.flash = None;
        if let Some(state) = self.data_table_state.as_mut() {
            let width = width.clamp(MIN_WIDTH, MAX_WIDTH);
            state.set_width_choices([(column, WidthChoice::Manual(width))]);
        }
    }

    /// The home screen is up with nothing over it, so its keys go to it.
    fn home_has_the_keys(&self) -> bool {
        self.input_mode == InputMode::Home
            && !self.help_visible()
            && !self.error_modal.active
            && !self.confirmation_modal.active
    }

    /// The chart view is up with nothing over it: no export dialog, Picker, help or
    /// modal.
    fn chart_has_the_keys(&self) -> bool {
        self.input_mode == InputMode::Chart
            && self.chart_modal.active
            && self.chart_modal.picker.is_none()
            && !self.chart_export_modal.active
            && !self.help_visible()
            && !self.error_modal.active
            && !self.confirmation_modal.active
    }

    /// A dialog that takes every key is over the screen: the help, an error, a
    /// question. What is drawn under it takes no clicks.
    fn dialog_over_all(&self) -> bool {
        self.help_visible() || self.error_modal.active || self.confirmation_modal.active
    }

    /// The wheel: the arrows of whatever has the keys. Not where ↑↓ walk a text
    /// field's history, and not in the prompt for a path on the home screen; over an
    /// open picker, its list.
    fn wheel(&self, down: bool, at: Position) -> Pointer {
        let code = if down { KeyCode::Down } else { KeyCode::Up };
        let arrows = Pointer::Keys(vec![press(code); WHEEL_ROWS]);
        if self.context_menu.is_some() {
            return Pointer::Nothing;
        }
        if self.home_has_the_keys() {
            if self.home.path_input_active {
                return Pointer::Nothing;
            }
            let rows = WHEEL_ROWS as isize;
            return Pointer::Point(Target::HomeStep(if down { rows } else { -rows }), None);
        }
        if !self.dialog_over_all() && self.pointer.over_picker(at) {
            return arrows;
        }
        if self.text_field_focused() {
            return Pointer::Nothing;
        }
        arrows
    }

    /// The wheel across, or Shift with it: the column cursor, at the table only.
    /// Elsewhere ←→ switch tabs or step rows, which a sideways scroll should not.
    fn wheel_across(&self, right: bool) -> Pointer {
        if !self.in_normal_table_view() || self.data_table_state.is_none() {
            return Pointer::Nothing;
        }
        let code = if right { KeyCode::Right } else { KeyCode::Left };
        Pointer::Keys(vec![press(code)])
    }

    fn click(&mut self, at: Position, now: Instant) -> Pointer {
        if self.context_menu.is_some() {
            self.pointer.last_click = None;
            return match self.pointer.hit_at(at) {
                Some(Hit::MenuItem(i)) => Pointer::MenuChoose(*i),
                Some(Hit::Menu) => Pointer::Nothing,
                _ => Pointer::CloseMenu,
            };
        }
        if let Some(key) = self.pointer.chip_at(at) {
            self.pointer.last_click = None;
            return Pointer::Keys(vec![key]);
        }
        // Over help, an error or a question, only its footer's keys take clicks.
        if self.dialog_over_all() {
            self.pointer.last_click = None;
            return match self.pointer.hit_at(at) {
                Some(Hit::Chip(key)) => Pointer::Keys(vec![*key]),
                _ => Pointer::Nothing,
            };
        }
        if let Some(hit) = self.pointer.hit_at(at).cloned() {
            self.pointer.last_click = None;
            return click_hit(&hit, false);
        }
        let double = self.pointer.second_click(at, now);
        let enter = double.then(|| press(KeyCode::Enter));
        if self.home_has_the_keys() {
            return match self.pointer.home_row_at(at) {
                Some(row) if !self.home.path_input_active => {
                    Pointer::Point(Target::HomeRow(row), enter)
                }
                _ => Pointer::Nothing,
            };
        }
        if self.chart_has_the_keys()
            && self.chart_modal.has_crosshair()
            && self
                .chart_modal
                .plot
                .is_some_and(|plot| plot.graph.contains(at))
        {
            return Pointer::Point(Target::ChartColumn(at.x), None);
        }
        if self.in_normal_table_view()
            && let Some(state) = self.data_table_state.as_ref()
        {
            if let Some(column) = state.drawn_edge(at.x, at.y) {
                // A double click on the gap fits the column to its rows, as `=` does
                // on the cursor's column; the first click started a drag that did not
                // move.
                if double {
                    let hit = CellHit {
                        row: None,
                        column: Some(column),
                    };
                    return Pointer::Point(Target::Table(hit), Some(press(KeyCode::Char('='))));
                }
                return Pointer::Resize { column, x: at.x };
            }
            if let Some(hit) = state.drawn_cell(at.x, at.y) {
                // Enter acts on a row. A double click on a header sorts by it, as
                // `[` and `]` do: up, then down, then off.
                let key = match (&hit.row, &hit.column) {
                    (Some(_), _) => enter,
                    (None, Some(column)) if double => {
                        Some(press(KeyCode::Char(header_sort_key(state, column))))
                    }
                    (None, _) => None,
                };
                return Pointer::Point(Target::Table(hit), key);
            }
        }
        Pointer::Nothing
    }

    /// A right click: on a table cell, the context menu; on a form's choice, a step
    /// back. Anywhere else, nothing.
    fn right_click(&mut self, at: Position) -> Pointer {
        self.pointer.last_click = None;
        if self.context_menu.is_some() {
            return Pointer::CloseMenu;
        }
        if self.dialog_over_all() {
            return Pointer::Nothing;
        }
        if let Some(hit) = self.pointer.hit_at(at).cloned() {
            return match hit {
                Hit::Field(_) => click_hit(&hit, true),
                _ => Pointer::Nothing,
            };
        }
        if self.in_normal_table_view()
            && let Some(hit) = self
                .data_table_state
                .as_ref()
                .and_then(|state| state.drawn_cell(at.x, at.y))
            && hit.row.is_some()
            && hit.column.is_some()
        {
            return Pointer::Menu(hit, at);
        }
        Pointer::Nothing
    }

    /// The pointer moved with the button down: a header carried over the columns, or
    /// the gap after one pulled to a width.
    fn drag_to(&mut self, at: Position) -> Pointer {
        match self.pointer.drag.clone() {
            Some(Drag::Move { column, .. }) => {
                // Off the table's columns it is over itself: let go there, nothing
                // moves.
                let over = self
                    .data_table_state
                    .as_ref()
                    .and_then(|state| state.drawn_cell(at.x, at.y))
                    .and_then(|hit| hit.column)
                    .unwrap_or_else(|| column.clone());
                if !matches!(&self.pointer.drag, Some(Drag::Move { over: was, .. }) if *was == over)
                {
                    // The drop mark moves: a frame is due.
                    self.pointer.drag = Some(Drag::Move { column, over });
                    return Pointer::Redraw;
                }
                Pointer::Nothing
            }
            Some(Drag::Resize { column, x, width }) => {
                let width = (i32::from(width) + i32::from(at.x) - i32::from(x)).max(0);
                Pointer::Width {
                    column,
                    width: u16::try_from(width).unwrap_or(u16::MAX),
                }
            }
            None => Pointer::Nothing,
        }
    }

    /// The button let go: a header carried to another column moves there.
    fn release(&mut self) -> Pointer {
        match self.pointer.drag.take() {
            Some(Drag::Move { column, over }) if column != over => {
                Pointer::Drop { column, onto: over }
            }
            // Back where it was picked up: the mark it may have shown goes.
            Some(Drag::Move { .. }) => Pointer::Redraw,
            _ => Pointer::Nothing,
        }
    }
}

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

    #[test]
    fn a_chip_presses_the_key_it_names() {
        let key = |code, modifiers| Some(KeyEvent::new(code, modifiers));
        assert_eq!(chip_key("Enter"), key(KeyCode::Enter, KeyModifiers::NONE));
        assert_eq!(
            chip_key("^O"),
            key(KeyCode::Char('o'), KeyModifiers::CONTROL)
        );
        assert_eq!(chip_key("q"), key(KeyCode::Char('q'), KeyModifiers::NONE));
        assert_eq!(chip_key("Q"), key(KeyCode::Char('Q'), KeyModifiers::SHIFT));
        assert_eq!(chip_key("/"), key(KeyCode::Char('/'), KeyModifiers::NONE));
        assert_eq!(chip_key("F1"), key(KeyCode::F(1), KeyModifiers::NONE));
        // Two keys, or a glyph standing for a pair: nothing to press.
        assert_eq!(chip_key("↑↓"), None);
        assert_eq!(chip_key("h/l"), None);
        assert_eq!(chip_key("PgUp"), None);
    }

    #[test]
    fn a_second_click_on_the_same_cell_soon_after_is_a_double_click() {
        let mut p = Pointing::default();
        let at = Position { x: 4, y: 7 };
        let t = Instant::now();
        assert!(!p.second_click(at, t));
        assert!(p.second_click(at, t + Duration::from_millis(200)));
        // A third starts over.
        assert!(!p.second_click(at, t + Duration::from_millis(300)));
        // Too late, or somewhere else.
        assert!(!p.second_click(at, t + Duration::from_secs(2)));
        assert!(!p.second_click(Position { x: 5, y: 7 }, t + Duration::from_secs(2)));
    }

    #[test]
    fn presses_drags_releases_a_right_press_and_the_wheel_are_wanted() {
        let mouse = |kind| MouseEvent {
            kind,
            column: 0,
            row: 0,
            modifiers: KeyModifiers::NONE,
        };
        assert!(wanted(&mouse(MouseEventKind::Down(MouseButton::Left))));
        assert!(wanted(&mouse(MouseEventKind::ScrollUp)));
        assert!(wanted(&mouse(MouseEventKind::ScrollRight)));
        assert!(wanted(&mouse(MouseEventKind::Down(MouseButton::Right))));
        assert!(wanted(&mouse(MouseEventKind::Up(MouseButton::Left))));
        assert!(wanted(&mouse(MouseEventKind::Drag(MouseButton::Left))));
        assert!(!wanted(&mouse(MouseEventKind::Moved)));
        assert!(!wanted(&mouse(MouseEventKind::Down(MouseButton::Middle))));
        assert!(!wanted(&mouse(MouseEventKind::Drag(MouseButton::Right))));
    }

    /// With `display.mouse` off nothing asks the terminal for the mouse. On, the
    /// request is presses, drags and the SGR encoding, never motion without a button.
    /// The bytes are checked from the command itself: on Windows `execute!` takes the
    /// console API and writes none.
    #[test]
    fn the_mouse_is_taken_only_when_asked_for() {
        use crossterm::Command;
        let mut out = Vec::new();
        capture(false, &mut out);
        assert!(out.is_empty(), "off: nothing is asked for");
        let mut ansi = String::new();
        EnableMouse.write_ansi(&mut ansi).unwrap();
        assert_eq!(ansi, "\x1b[?1000h\x1b[?1002h\x1b[?1006h");
        assert!(!ansi.contains("?1003h"), "no motion without a button");
        #[cfg(not(windows))]
        {
            capture(true, &mut out);
            assert_eq!(String::from_utf8(out).unwrap(), ansi, "on: it is asked for");
        }
    }

    #[test]
    fn regions_are_recorded_only_while_a_frame_is_drawn() {
        let rect = Rect::new(1, 1, 4, 1);
        record(rect, Hit::Tool(0));
        let mut p = Pointing::default();
        p.forget_drawn();
        record(rect, Hit::Tool(1));
        record(Rect::new(0, 0, 0, 1), Hit::Tool(2));
        p.drawn();
        assert_eq!(p.hits, vec![(rect, Hit::Tool(1))]);
        record(rect, Hit::Tool(3));
        p.forget_drawn();
        p.drawn();
        assert!(p.hits.is_empty(), "a frame keeps only what it drew");
    }

    #[test]
    fn the_topmost_region_takes_the_click_and_an_open_picker_takes_them_all() {
        let field = FieldId {
            form: "f",
            field: "Name".into(),
        };
        let mut p = Pointing {
            hits: vec![
                (Rect::new(0, 0, 10, 1), Hit::Field(field.clone())),
                (Rect::new(0, 0, 3, 1), Hit::Tool(2)),
            ],
            ..Pointing::default()
        };
        assert_eq!(p.hit_at(Position { x: 1, y: 0 }), Some(&Hit::Tool(2)));
        assert_eq!(
            p.hit_at(Position { x: 5, y: 0 }),
            Some(&Hit::Field(field.clone()))
        );
        assert_eq!(p.hit_at(Position { x: 5, y: 1 }), None);
        p.hits.push((Rect::new(0, 3, 10, 2), Hit::Picker));
        let item = Hit::PickerItem {
            visible: 1,
            selected: 0,
            multi: false,
        };
        p.hits.push((Rect::new(0, 4, 10, 1), item.clone()));
        assert_eq!(p.hit_at(Position { x: 5, y: 0 }), None, "the form waits");
        assert_eq!(p.hit_at(Position { x: 5, y: 4 }), Some(&item));
        assert!(p.over_picker(Position { x: 5, y: 3 }));
    }

    #[test]
    fn under_a_dialog_only_what_it_drew_takes_clicks() {
        let p = Pointing {
            hits: vec![
                (Rect::new(0, 0, 40, 1), Hit::Tool(0)),
                (Rect::new(0, 5, 40, 1), Hit::Tool(1)),
                (Rect::new(10, 4, 20, 4), Hit::Modal),
                (Rect::new(10, 5, 20, 1), Hit::Tool(2)),
            ],
            ..Pointing::default()
        };
        assert_eq!(p.hit_at(Position { x: 2, y: 0 }), None, "outside: nothing");
        assert_eq!(p.hit_at(Position { x: 2, y: 5 }), None);
        assert_eq!(p.hit_at(Position { x: 12, y: 5 }), Some(&Hit::Tool(2)));
        assert_eq!(
            p.hit_at(Position { x: 12, y: 6 }),
            None,
            "inside, on nothing"
        );
    }

    #[test]
    fn a_line_records_where_its_spans_landed() {
        use ratatui::text::{Line, Span};
        let line = Line::from(vec![
            Span::raw(" "),
            Span::raw("Pivot"),
            Span::raw(" | "),
            Span::raw("Melt"),
        ]);
        let mut p = Pointing::default();
        p.forget_drawn();
        record_spans(
            Rect::new(10, 2, 12, 1),
            &line,
            vec![(1, Hit::Tool(0)), (3, Hit::Tool(1))],
        );
        p.drawn();
        assert_eq!(
            p.hits,
            vec![
                (Rect::new(11, 2, 5, 1), Hit::Tool(0)),
                // Cut at the area's edge.
                (Rect::new(19, 2, 3, 1), Hit::Tool(1)),
            ]
        );
    }

    #[test]
    fn a_click_on_a_value_steps_to_it_and_on_a_picker_line_chooses_it() {
        let right = press(KeyCode::Right);
        let left = press(KeyCode::Left);
        let option = |index, current| Hit::Option {
            field: None,
            index,
            current,
        };
        assert_eq!(
            click_hit(&option(2, 0), false),
            Pointer::Form {
                field: None,
                act: None,
                keys: vec![right, right]
            }
        );
        assert_eq!(
            click_hit(&option(0, 1), false),
            Pointer::Form {
                field: None,
                act: None,
                keys: vec![left]
            }
        );
        let item = |visible, selected, multi| Hit::PickerItem {
            visible,
            selected,
            multi,
        };
        assert_eq!(
            click_hit(&item(0, 2, false), false),
            Pointer::Keys(vec![
                press(KeyCode::Up),
                press(KeyCode::Up),
                press(KeyCode::Enter)
            ])
        );
        assert_eq!(
            click_hit(&item(1, 1, true), false),
            Pointer::Keys(vec![press(KeyCode::Char(' '))])
        );
    }

    #[test]
    fn a_click_acts_on_a_field_as_space_and_a_right_click_steps_back() {
        let space = Some(press(KeyCode::Char(' ')));
        assert_eq!(act_key(FieldKind::Text, false), None);
        assert_eq!(act_key(FieldKind::MultilineText, true), None);
        assert_eq!(act_key(FieldKind::Checkbox, false), space);
        assert_eq!(
            act_key(FieldKind::Checkbox, true),
            None,
            "a right click focuses"
        );
        assert_eq!(act_key(FieldKind::Choice, false), space);
        assert_eq!(act_key(FieldKind::Choice, true), Some(press(KeyCode::Left)));
        assert_eq!(act_key(FieldKind::Picker { multi: true }, true), None);
        assert_eq!(act_key(FieldKind::Button, true), None);
        assert_eq!(act_key(FieldKind::Button, false), space);
    }

    #[test]
    fn a_field_id_focuses_only_its_own_form() {
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        enum F {
            A,
            B,
        }
        struct One(F, bool);
        struct Two(F);
        impl Form for One {
            type Field = F;
            fn fields(&self) -> Vec<(F, FieldKind)> {
                let mut f = vec![(F::A, FieldKind::Text)];
                if self.1 {
                    f.push((F::B, FieldKind::Checkbox));
                }
                f
            }
            fn focused(&self) -> F {
                self.0
            }
            fn set_focused(&mut self, field: F) {
                self.0 = field;
            }
        }
        impl Form for Two {
            type Field = F;
            fn fields(&self) -> Vec<(F, FieldKind)> {
                vec![(F::A, FieldKind::Text), (F::B, FieldKind::Choice)]
            }
            fn focused(&self) -> F {
                self.0
            }
            fn set_focused(&mut self, field: F) {
                self.0 = field;
            }
        }
        let id = FieldId::of::<One>(F::B);
        let mut two = Two(F::A);
        assert_eq!(id.focus_in(&mut two), None, "another form's field");
        assert_eq!(two.0, F::A);
        let mut hidden = One(F::A, false);
        assert_eq!(id.focus_in(&mut hidden), None, "a field not shown");
        let mut one = One(F::A, true);
        let clicked = |kind| Some(Clicked { kind, acts: true });
        assert_eq!(id.focus_in(&mut one), clicked(FieldKind::Checkbox));
        assert_eq!(one.0, F::B);
    }
}