rat-ftable2 0.4.0

ratatui table widget for large data
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
use crate::_private::NonExhaustive;
use crate::TableSelection;
use crate::event::{DoubleClickOutcome, TableOutcome};
use crate::selection::{CellSelection, NoSelection, RowSelection, RowSetSelection};
use rat_cursor::HasScreenCursor;
use rat_event::crossterm::event::Event;
use rat_event::util::MouseFlags;
use rat_event::{DoubleClick, HandleEvent, MouseOnly, Regular, ct_event};
use rat_focus::{FocusBuilder, FocusFlag, HasFocus};
use rat_reloc::{RelocatableState, relocate_areas};
use rat_scrolled::ScrollState;
use ratatui_core::layout::Rect;
use std::cmp::min;
use std::collections::HashSet;

/// State for the table table.
#[derive(Debug)]
pub struct TableState<Selection = RowSelection> {
    /// Current focus state.
    /// __read+write__
    pub focus: FocusFlag,

    /// Total area.
    /// __read only__ Renewed with each render.
    pub area: Rect,
    /// Area inside the border and scrollbars
    /// __read only__ Renewed with each render.
    pub inner: Rect,

    /// Total header area.
    /// __read only__ Renewed with each render.
    pub header_area: Rect,
    /// Total table area.
    /// __read only__ Renewed with each render.
    pub table_area: Rect,
    /// Area per visible row. The first element is at row_offset.
    /// __read only__ Renewed with each render.
    pub row_areas: Vec<Rect>,
    /// Height for every row.
    pub row_heights: RowHeights,
    /// Area for each column plus the following spacer if any.
    /// Invisible columns have width 0, height is the height of the table_area.
    /// __read only__ Renewed with each render.
    pub column_areas: Vec<Rect>,
    /// Layout areas for each column plus the following spacer if any.
    /// Positions are 0-based, y and height are 0.
    /// __read only__ Renewed with each render.
    pub column_layout: Vec<Rect>,
    /// Total footer area.
    /// __read only__ Renewed with each render.
    pub footer_area: Rect,

    /// Row count.
    /// __read+write__ Renewed with each render.
    pub rows: usize,
    /// Column count.
    /// __read only__ Renewed with each render.
    pub columns: usize,

    /// Row scrolling data.
    /// __read+write__ max_offset set with each render.
    pub vscroll: ScrollState,
    /// Column scrolling data.
    /// __read+write__ max_offset set with each render.
    pub hscroll: ScrollState,

    /// Selection data.
    /// __read+write__ selection model.
    /// selection is not bound by actual rows.
    pub selection: Selection,

    /// Helper for mouse interactions.
    pub mouse: MouseFlags,

    pub non_exhaustive: NonExhaustive,
}

/// Row heights for every row.
#[derive(Debug, Clone)]
pub enum RowHeights {
    Uniform(u8),
    Varying(Vec<u8>),
}

impl Default for RowHeights {
    fn default() -> Self {
        RowHeights::Uniform(1)
    }
}

impl RowHeights {
    pub(crate) fn clear(&mut self) {
        match self {
            RowHeights::Uniform(_) => {}
            RowHeights::Varying(h) => h.clear(),
        }
    }

    pub(crate) fn push(&mut self, row_height: u8, varying: bool) {
        if varying {
            match self {
                RowHeights::Uniform(_) => {
                    *self = RowHeights::Varying(vec![row_height]);
                }
                RowHeights::Varying(h) => h.push(row_height),
            }
        } else {
            *self = RowHeights::Uniform(row_height);
        }
    }

    pub(crate) fn items_added(&mut self, pos: usize, n: usize) {
        match self {
            RowHeights::Uniform(_) => {}
            RowHeights::Varying(h) => {
                if pos <= h.len() {
                    for _ in 0..n {
                        h.insert(pos, 1);
                    }
                }
            }
        }
    }

    pub(crate) fn items_added_with_heights(&mut self, pos: usize, height: &[u8]) {
        match self {
            RowHeights::Uniform(_) => {}
            RowHeights::Varying(h) => {
                if pos <= h.len() {
                    h.splice(pos..pos, height.into_iter().copied());
                }
            }
        }
    }

    pub(crate) fn items_removed(&mut self, pos: usize, n: usize) {
        match self {
            RowHeights::Uniform(_) => {}
            RowHeights::Varying(h) => {
                if pos < h.len() {
                    if pos + n < h.len() {
                        h.drain(pos..pos + n);
                    } else {
                        h.drain(pos..);
                    }
                }
            }
        }
    }
}

impl<Selection: Clone> Clone for TableState<Selection> {
    fn clone(&self) -> Self {
        Self {
            focus: self.focus.new_instance(),
            area: self.area,
            inner: self.inner,
            header_area: self.header_area,
            table_area: self.table_area,
            row_areas: self.row_areas.clone(),
            row_heights: self.row_heights.clone(),
            column_areas: self.column_areas.clone(),
            column_layout: self.column_layout.clone(),
            footer_area: self.footer_area,
            rows: self.rows,
            columns: self.columns,
            vscroll: self.vscroll.clone(),
            hscroll: self.hscroll.clone(),
            selection: self.selection.clone(),
            mouse: Default::default(),
            non_exhaustive: NonExhaustive,
        }
    }
}

impl<Selection: Default> Default for TableState<Selection> {
    fn default() -> Self {
        Self {
            focus: Default::default(),
            area: Default::default(),
            inner: Default::default(),
            header_area: Default::default(),
            table_area: Default::default(),
            row_areas: Default::default(),
            row_heights: Default::default(),
            column_areas: Default::default(),
            column_layout: Default::default(),
            footer_area: Default::default(),
            rows: Default::default(),
            columns: Default::default(),
            vscroll: Default::default(),
            hscroll: Default::default(),
            selection: Default::default(),
            mouse: Default::default(),
            non_exhaustive: NonExhaustive,
        }
    }
}

impl<Selection> HasFocus for TableState<Selection> {
    fn build(&self, builder: &mut FocusBuilder) {
        builder.leaf_widget(self);
    }

    #[inline]
    fn focus(&self) -> FocusFlag {
        self.focus.clone()
    }

    #[inline]
    fn area(&self) -> Rect {
        self.area
    }
}

impl<Selection> HasScreenCursor for TableState<Selection> {
    fn screen_cursor(&self) -> Option<(u16, u16)> {
        None
    }
}

impl<Selection> RelocatableState for TableState<Selection> {
    fn relocate(&mut self, shift: (i16, i16), clip: Rect) {
        self.area.relocate(shift, clip);
        self.inner.relocate(shift, clip);
        self.header_area.relocate(shift, clip);
        self.table_area.relocate(shift, clip);
        relocate_areas(self.row_areas.as_mut_slice(), shift, clip);
        relocate_areas(self.column_areas.as_mut_slice(), shift, clip);
        relocate_areas(self.column_layout.as_mut_slice(), shift, clip);
        self.footer_area.relocate(shift, clip);
        self.hscroll.relocate(shift, clip);
        self.vscroll.relocate(shift, clip);
    }
}

impl<Selection> TableState<Selection>
where
    Selection: Default,
{
    /// New widget.
    pub fn new() -> Self {
        Self::default()
    }

    /// New named widget.
    pub fn named(name: &str) -> Self {
        Self {
            focus: FocusFlag::new().with_name(name),
            ..TableState::default()
        }
    }
}

// Baseline
impl<Selection> TableState<Selection> {
    /// Number of rows.
    #[inline]
    pub fn rows(&self) -> usize {
        self.rows
    }

    /// Number of columns.
    #[inline]
    pub fn columns(&self) -> usize {
        self.columns
    }
}

// Table areas
impl<Selection> TableState<Selection> {
    /// Returns the whole row-area and the cell-areas for the
    /// given row, if it is visible.
    ///
    /// Attention: These areas might be 0-length if the column is scrolled
    /// beyond the table-area.
    pub fn row_cells(&self, row: usize) -> Option<(Rect, Vec<Rect>)> {
        if row < self.vscroll.offset() || row >= self.vscroll.offset() + self.vscroll.page_len() {
            return None;
        }

        let mut areas = Vec::new();

        let r = self.row_areas[row - self.vscroll.offset()];
        for c in &self.column_areas {
            areas.push(Rect::new(c.x, r.y, c.width, r.height));
        }

        Some((r, areas))
    }

    /// Cell at given position.
    pub fn cell_at_clicked(&self, pos: (u16, u16)) -> Option<(usize, usize)> {
        let col = self.column_at_clicked(pos);
        let row = self.row_at_clicked(pos);

        match (col, row) {
            (Some(col), Some(row)) => Some((col, row)),
            _ => None,
        }
    }

    /// Column at given position.
    pub fn column_at_clicked(&self, pos: (u16, u16)) -> Option<usize> {
        self.mouse.column_at(&self.column_areas, pos.0)
    }

    /// Row at given position.
    pub fn row_at_clicked(&self, pos: (u16, u16)) -> Option<usize> {
        self.mouse
            .row_at(&self.row_areas, pos.1)
            .map(|v| self.vscroll.offset() + v)
    }

    /// Cell when dragging. Position can be outside the table area.
    /// See [row_at_drag](TableState::row_at_drag), [col_at_drag](TableState::column_at_drag)
    pub fn cell_at_drag(&self, pos: (u16, u16)) -> (usize, usize) {
        let col = self.column_at_drag(pos);
        let row = self.row_at_drag(pos);

        (col, row)
    }

    /// Row when dragging. Position can be outside the table area.
    /// If the position is above the table-area this returns offset - #rows.
    /// If the position is below the table-area this returns offset + page_len + #rows.
    ///
    /// This doesn't account for the row-height of the actual rows outside
    /// the table area, just assumes '1'.
    pub fn row_at_drag(&self, pos: (u16, u16)) -> usize {
        match self
            .mouse
            .row_at_drag(self.table_area, &self.row_areas, pos.1)
        {
            Ok(v) => self.vscroll.offset() + v,
            Err(v) if v <= 0 => self.vscroll.offset().saturating_sub((-v) as usize),
            Err(v) => self.vscroll.offset() + self.row_areas.len() + v as usize,
        }
    }

    /// Column when dragging. Position can be outside the table area.
    /// If the position is left of the table area this returns offset - 1.
    /// If the position is right of the table area this returns offset + page_width + 1.
    pub fn column_at_drag(&self, pos: (u16, u16)) -> usize {
        match self
            .mouse
            .column_at_drag(self.table_area, &self.column_areas, pos.0)
        {
            Ok(v) => v,
            Err(v) if v <= 0 => self.hscroll.offset().saturating_sub((-v) as usize),
            Err(v) => self.hscroll.offset() + self.hscroll.page_len() + v as usize,
        }
    }
}

// Offset related.
impl<Selection: TableSelection> TableState<Selection> {
    /// Clear the selection.
    #[inline]
    pub fn clear_selection(&mut self) {
        self.selection.clear();
    }

    /// Update the state to match adding items *during* event-handling.
    /// A lot of functions use the number of rows, so when you change the
    /// underlying data you might want to immediately reflect this in the
    /// table-state.
    ///
    /// This corrects the number of rows, offset and selection.
    pub fn items_added(&mut self, pos: usize, n: usize) {
        self.rows = self.rows.saturating_add(n);
        self.vscroll.items_added(pos, n);
        self.row_heights.items_added(pos, n);
        self.selection.items_added(pos, n);
    }

    /// Update the state to match adding items.
    /// Use this function if you have varying row-heights.
    ///
    /// This corrects the number of rows, offset and selection.
    /// This also corrects the stored row-heights with the
    /// given heights.
    pub fn items_added_with_heigths(&mut self, pos: usize, height: &[u8]) {
        self.rows = self.rows.saturating_add(height.len());
        self.vscroll.items_added(pos, height.len());
        self.row_heights.items_added_with_heights(pos, height);
        self.selection.items_added(pos, height.len());
    }

    /// Update the state to match removing items *during* event-handling.
    /// A lot of functions use the number of rows, so when you change the
    /// underlying data you might want to immediately reflect this in the
    /// table-state.
    ///
    /// This corrects the number of rows, offset and selection.
    pub fn items_removed(&mut self, pos: usize, n: usize) {
        self.rows = self.rows.saturating_sub(n);
        self.vscroll.items_removed(pos, n);
        self.row_heights.items_removed(pos, n);
        self.selection.items_removed(pos, n, self.rows);
    }

    /// Update the number of rows *during* event-handling.
    /// A lot of functions use the number of rows, so when you change the
    /// underlying data you might want to immediately reflect this in the
    /// table-state.
    ///
    /// This corrects the number of rows, offset and selection.
    pub fn rows_changed(&mut self, rows: usize) {
        self.selection.validate_rows(rows);
        self.vscroll.rows_changed(rows);
        self.row_heights.clear();
        self.rows = rows;
    }

    /// Sets both offsets to 0.
    pub fn clear_offset(&mut self) {
        self.vscroll.set_offset(0);
        self.hscroll.set_offset(0);
    }

    /// Maximum offset that is accessible with scrolling.
    ///
    /// This is shorter than the length by whatever fills the last page.
    /// This is the base for the scrollbar content_length.
    pub fn row_max_offset(&self) -> usize {
        self.vscroll.max_offset()
    }

    /// Current vertical offset.
    pub fn row_offset(&self) -> usize {
        self.vscroll.offset()
    }

    /// Change the vertical offset.
    /// The vertical offset may be beyond the number of rows.
    ///
    /// The widget returns true if the offset changed at all.
    pub fn set_row_offset(&mut self, offset: usize) -> bool {
        self.vscroll.set_offset(offset)
    }

    /// Vertical page-size at the current offset.
    pub fn page_len(&self) -> usize {
        self.vscroll.page_len()
    }

    /// Suggested scroll per scroll-event.
    pub fn row_scroll_by(&self) -> usize {
        self.vscroll.scroll_by()
    }

    /// Maximum offset that is accessible with scrolling.
    /// This is the table-width minus the widget-width plus some overscroll.
    pub fn x_max_offset(&self) -> usize {
        self.hscroll.max_offset()
    }

    /// Current horizontal offset.
    pub fn x_offset(&self) -> usize {
        self.hscroll.offset()
    }

    /// Change the horizontal offset.
    /// The offset may be beyond the table-width.
    ///
    /// The widget returns true if the offset changed at all.
    pub fn set_x_offset(&mut self, offset: usize) -> bool {
        self.hscroll.set_offset(offset)
    }

    /// Horizontal page-size at the current offset.
    pub fn page_width(&self) -> usize {
        self.hscroll.page_len()
    }

    /// Suggested scroll per scroll-event.
    pub fn x_scroll_by(&self) -> usize {
        self.hscroll.scroll_by()
    }

    /// Ensures that the selected item is visible.
    /// Caveat: This doesn't work nicely if you have varying row-heights.
    /// Caveat: Number of rows needs to be correct.
    pub fn scroll_to_selected(&mut self) -> bool {
        if let Some(selected) = self.selection.lead_selection() {
            let c = self.scroll_to_col(selected.0);
            let r = self.scroll_to_row(selected.1);
            r || c
        } else {
            false
        }
    }

    /// Ensures that the given row is visible.
    /// Caveat: This doesn't work nicely if you have varying row-heights.
    /// Caveat: Number of rows needs to be correct.
    pub fn scroll_to_row(&mut self, mut pos: usize) -> bool {
        if pos >= self.rows {
            false
        } else if self.inner.is_empty() {
            self.set_row_offset(pos)
        } else if let RowHeights::Uniform(row_height) = &self.row_heights {
            let page_len = self.inner.height.div_ceil(*row_height as u16) as usize;
            if pos >= self.row_offset().saturating_add(page_len - 1) {
                if page_len as u16 * (*row_height) as u16 > self.table_area.height {
                    self.set_row_offset(pos.saturating_sub(page_len - 2))
                } else {
                    self.set_row_offset(pos.saturating_sub(page_len - 1))
                }
            } else if pos < self.row_offset() {
                self.set_row_offset(pos)
            } else {
                false
            }
        } else if let RowHeights::Varying(row_heights) = &self.row_heights {
            if pos >= self.row_offset().saturating_add(self.page_len() - 1) {
                if pos >= row_heights.len() {
                    self.set_row_offset(pos)
                } else {
                    let mut sum_height = row_heights[pos];
                    if sum_height < self.table_area.height as u8 {
                        loop {
                            if pos < 1 {
                                break;
                            }
                            sum_height += row_heights[pos - 1];
                            if sum_height > self.table_area.height as u8 {
                                break;
                            }
                            pos -= 1;
                        }
                    }
                    self.set_row_offset(pos)
                }
            } else if pos < self.row_offset() {
                self.set_row_offset(pos)
            } else {
                false
            }
        } else {
            false
        }
    }

    /// Ensures that the given column is completely visible.
    pub fn scroll_to_col(&mut self, pos: usize) -> bool {
        if let Some(col) = self.column_layout.get(pos) {
            self.hscroll
                .scroll_to_range(col.x as usize..col.right() as usize)
        } else {
            false
        }
    }

    /// Ensures that the given position is visible.
    pub fn scroll_to_x(&mut self, pos: usize) -> bool {
        self.hscroll.scroll_to_pos(pos)
    }

    /// Reduce the row-offset by n.
    pub fn scroll_up(&mut self, n: usize) -> bool {
        self.vscroll.scroll_up(n)
    }

    /// Increase the row-offset by n.
    pub fn scroll_down(&mut self, n: usize) -> bool {
        self.vscroll.scroll_down(n)
    }

    /// Reduce the col-offset by n.
    pub fn scroll_left(&mut self, n: usize) -> bool {
        self.hscroll.scroll_left(n)
    }

    /// Increase the col-offset by n.
    pub fn scroll_right(&mut self, n: usize) -> bool {
        self.hscroll.scroll_right(n)
    }
}

impl TableState<RowSelection> {
    /// When scrolling the table, change the selection instead of the offset.
    #[inline]
    pub fn set_scroll_selection(&mut self, scroll: bool) {
        self.selection.set_scroll_selected(scroll);
    }

    /// Anything selected?
    #[inline]
    pub fn has_selection(&mut self) -> bool {
        self.selection.has_selection()
    }

    /// Selected row.
    /// The selected row is not constrained by the row-count.
    #[inline]
    pub fn selected(&self) -> Option<usize> {
        self.selection.selected()
    }

    /// Return the selected row and ensure it is in the
    /// range `0..rows`.
    #[inline]
    #[allow(clippy::manual_filter)]
    pub fn selected_checked(&self) -> Option<usize> {
        if let Some(selected) = self.selection.selected() {
            if selected < self.rows {
                Some(selected)
            } else {
                None
            }
        } else {
            None
        }
    }

    /// Select the row.
    /// The selection is not constrained by the row-count.
    #[inline]
    pub fn select(&mut self, row: Option<usize>) -> bool {
        self.selection.select(row)
    }

    /// Scroll delivers a value between 0 and max_offset as offset.
    /// This remaps the ratio to the selection with a range 0..row_len.
    /// Info: This is used when scroll_selected is active.
    pub(crate) fn remap_offset_selection(&self, offset: usize) -> usize {
        if self.vscroll.max_offset() > 0 {
            (self.rows * offset) / self.vscroll.max_offset()
        } else {
            0
        }
    }

    /// Set the selection to None and set the offset to 0
    #[inline]
    pub fn move_deselect(&mut self) -> bool {
        let r = self.selection.select(None);
        let s = self.set_row_offset(0);
        r || s
    }

    /// Move the selection to the given row.
    /// Ensures the row is visible afterward.
    #[inline]
    pub fn move_to(&mut self, row: usize) -> bool {
        let r = self.selection.move_to(row, self.rows.saturating_sub(1));
        let s = self.scroll_to_row(self.selection.selected().expect("row"));
        r || s
    }

    /// Move the selection up n rows.
    /// Ensures the row is visible afterward.
    #[inline]
    pub fn move_up(&mut self, n: usize) -> bool {
        let r = self.selection.move_up(n, self.rows.saturating_sub(1));
        let s = self.scroll_to_row(self.selection.selected().expect("row"));
        r || s
    }

    /// Move the selection down n rows.
    /// Ensures the row is visible afterward.
    #[inline]
    pub fn move_down(&mut self, n: usize) -> bool {
        let r = self.selection.move_down(n, self.rows.saturating_sub(1));
        let s = self.scroll_to_row(self.selection.selected().expect("row"));
        r || s
    }
}

impl TableState<RowSetSelection> {
    /// Anything selected?
    #[inline]
    pub fn has_selection(&mut self) -> bool {
        self.selection.has_selection()
    }

    /// Selected rows.
    #[inline]
    pub fn selected(&self) -> HashSet<usize> {
        self.selection.selected()
    }

    /// Change the lead-selection. Limits the value to the number of rows.
    /// If extend is false the current selection is cleared and both lead and
    /// anchor are set to the given value.
    /// If extend is true, the anchor is kept where it is and lead is changed.
    /// Everything in the range `anchor..lead` is selected. It doesn't matter
    /// if anchor < lead.
    #[inline]
    pub fn set_lead(&mut self, row: Option<usize>, extend: bool) -> bool {
        self.selection.set_lead(row, extend)
    }

    /// Current lead.
    #[inline]
    pub fn lead(&self) -> Option<usize> {
        self.selection.lead()
    }

    /// Current anchor.
    #[inline]
    pub fn anchor(&self) -> Option<usize> {
        self.selection.anchor()
    }

    /// Retire the current anchor/lead selection to the set of selected rows.
    /// Resets lead and anchor and starts a new selection round.
    #[inline]
    pub fn retire_selection(&mut self) {
        self.selection.retire_selection();
    }

    /// Add to selection. Only works for retired selections, not for the
    /// active anchor-lead range.
    ///
    /// To be sure call [retire_selection][Self::retire_selection] first.
    #[inline]
    pub fn add_selected(&mut self, idx: usize) {
        self.selection.add(idx);
    }

    /// Remove from selection. Only works for retired selections, not for the
    /// active anchor-lead range.
    ///
    /// To be sure call [retire_selection][Self::retire_selection] first.
    #[inline]
    pub fn remove_selected(&mut self, idx: usize) {
        self.selection.remove(idx);
    }

    /// Move the selection to the given row.
    /// Ensures the row is visible afterward.
    #[inline]
    pub fn move_to(&mut self, row: usize, extend: bool) -> bool {
        let r = self
            .selection
            .move_to(row, self.rows.saturating_sub(1), extend);
        let s = self.scroll_to_row(self.selection.lead().expect("row"));
        r || s
    }

    /// Move the selection up n rows.
    /// Ensures the row is visible afterward.
    #[inline]
    pub fn move_up(&mut self, n: usize, extend: bool) -> bool {
        let r = self
            .selection
            .move_up(n, self.rows.saturating_sub(1), extend);
        let s = self.scroll_to_row(self.selection.lead().expect("row"));
        r || s
    }

    /// Move the selection down n rows.
    /// Ensures the row is visible afterwards.
    #[inline]
    pub fn move_down(&mut self, n: usize, extend: bool) -> bool {
        let r = self
            .selection
            .move_down(n, self.rows.saturating_sub(1), extend);
        let s = self.scroll_to_row(self.selection.lead().expect("row"));
        r || s
    }
}

impl TableState<CellSelection> {
    #[inline]
    pub fn has_selection(&mut self) -> bool {
        self.selection.has_selection()
    }

    /// Selected cell.
    #[inline]
    pub fn selected(&self) -> Option<(usize, usize)> {
        self.selection.selected()
    }

    /// Select a cell.
    #[inline]
    pub fn select_cell(&mut self, select: Option<(usize, usize)>) -> bool {
        self.selection.select_cell(select)
    }

    /// Select a row. Column stays the same.
    #[inline]
    pub fn select_row(&mut self, row: Option<usize>) -> bool {
        if let Some(row) = row {
            self.selection
                .select_row(Some(min(row, self.rows.saturating_sub(1))))
        } else {
            self.selection.select_row(None)
        }
    }

    /// Select a column, row stays the same.
    #[inline]
    pub fn select_column(&mut self, column: Option<usize>) -> bool {
        if let Some(column) = column {
            self.selection
                .select_column(Some(min(column, self.columns.saturating_sub(1))))
        } else {
            self.selection.select_column(None)
        }
    }

    /// Select a cell, limit to maximum.
    #[inline]
    pub fn move_to(&mut self, select: (usize, usize)) -> bool {
        let r = self.selection.move_to(
            select,
            (self.columns.saturating_sub(1), self.rows.saturating_sub(1)),
        );
        let s = self.scroll_to_selected();
        r || s
    }

    /// Select a row, limit to maximum.
    #[inline]
    pub fn move_to_row(&mut self, row: usize) -> bool {
        let r = self.selection.move_to_row(row, self.rows.saturating_sub(1));
        let s = self.scroll_to_selected();
        r || s
    }

    /// Select a cell, clamp between 0 and maximum.
    #[inline]
    pub fn move_to_col(&mut self, col: usize) -> bool {
        let r = self
            .selection
            .move_to_col(col, self.columns.saturating_sub(1));
        let s = self.scroll_to_selected();
        r || s
    }

    /// Move the selection up n rows.
    /// Ensures the row is visible afterwards.
    #[inline]
    pub fn move_up(&mut self, n: usize) -> bool {
        let r = self.selection.move_up(n, self.rows.saturating_sub(1));
        let s = self.scroll_to_selected();
        r || s
    }

    /// Move the selection down n rows.
    /// Ensures the row is visible afterwards.
    #[inline]
    pub fn move_down(&mut self, n: usize) -> bool {
        let r = self.selection.move_down(n, self.rows.saturating_sub(1));
        let s = self.scroll_to_selected();
        r || s
    }

    /// Move the selection left n columns.
    /// Ensures the row is visible afterwards.
    #[inline]
    pub fn move_left(&mut self, n: usize) -> bool {
        let r = self.selection.move_left(n, self.columns.saturating_sub(1));
        let s = self.scroll_to_selected();
        r || s
    }

    /// Move the selection right n columns.
    /// Ensures the row is visible afterwards.
    #[inline]
    pub fn move_right(&mut self, n: usize) -> bool {
        let r = self.selection.move_right(n, self.columns.saturating_sub(1));
        let s = self.scroll_to_selected();
        r || s
    }
}

impl<Selection> HandleEvent<Event, DoubleClick, DoubleClickOutcome> for TableState<Selection> {
    /// Handles double-click events on the table.
    fn handle(&mut self, event: &Event, _keymap: DoubleClick) -> DoubleClickOutcome {
        if self.focus.is_obscured() {
            return DoubleClickOutcome::Continue;
        }

        match event {
            ct_event!(mouse any for m) if self.mouse.doubleclick(self.table_area, m) => {
                if let Some((col, row)) = self.cell_at_clicked((m.column, m.row)) {
                    DoubleClickOutcome::ClickClick(col, row)
                } else {
                    DoubleClickOutcome::Continue
                }
            }
            _ => DoubleClickOutcome::Continue,
        }
    }
}

impl<Selection> TableState<Selection> {
    /// Handle all events for recognizing double-clicks.
    pub fn handle_doubleclick_events(&mut self, event: &Event) -> DoubleClickOutcome {
        self.handle(event, DoubleClick)
    }
}

impl TableState<RowSelection> {
    /// Handle all events.
    /// Table events are only processed if focus is true.
    /// Mouse events are processed if they are in range.
    pub fn handle_events(&mut self, focus: bool, event: &Event) -> TableOutcome {
        self.focus.set(focus);
        self.handle(event, Regular)
    }

    /// Handle only mouse-events.
    pub fn handle_mouse_events(&mut self, event: &Event) -> TableOutcome {
        self.handle(event, MouseOnly)
    }
}

impl TableState<CellSelection> {
    /// Handle all events.
    /// Table events are only processed if focus is true.
    /// Mouse events are processed if they are in range.
    pub fn handle_events(&mut self, focus: bool, event: &Event) -> TableOutcome {
        self.focus.set(focus);
        self.handle(event, Regular)
    }

    /// Handle only mouse-events.
    pub fn handle_mouse_events(&mut self, event: &Event) -> TableOutcome {
        self.handle(event, MouseOnly)
    }
}

impl TableState<NoSelection> {
    /// Handle all events.
    /// Table events are only processed if focus is true.
    /// Mouse events are processed if they are in range.
    pub fn handle_events(&mut self, focus: bool, event: &Event) -> TableOutcome {
        self.focus.set(focus);
        self.handle(event, Regular)
    }

    /// Handle only mouse-events.
    pub fn handle_mouse_events(&mut self, event: &Event) -> TableOutcome {
        self.handle(event, MouseOnly)
    }
}

impl TableState<RowSetSelection> {
    /// Handle all events.
    /// Table events are only processed if focus is true.
    /// Mouse events are processed if they are in range.
    pub fn handle_events(&mut self, focus: bool, event: &Event) -> TableOutcome {
        self.focus.set(focus);
        self.handle(event, Regular)
    }

    /// Handle only mouse-events.
    pub fn handle_mouse_events(&mut self, event: &Event) -> TableOutcome {
        self.handle(event, MouseOnly)
    }
}