-
Notifications
You must be signed in to change notification settings - Fork 43
/
ui.rs
1231 lines (1120 loc) · 41.3 KB
/
ui.rs
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
use crate::common::InputMode;
use crate::csv::Row;
use crate::find;
use crate::sort;
use crate::sort::SortOrder;
use crate::view;
use crate::view::Header;
use crate::wrap;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::prelude::Position;
use ratatui::style::{Color, Modifier, Style};
use ratatui::symbols::line;
use ratatui::text::{Line, Span};
use ratatui::widgets::Widget;
use ratatui::widgets::{Block, Borders, StatefulWidget};
use regex::Regex;
use tui_input::Input;
use std::cmp::{max, min};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
const NUM_SPACES_AFTER_LINE_NUMBER: u16 = 2;
const NUM_SPACES_BETWEEN_COLUMNS: u16 = 4;
const MAX_COLUMN_WIDTH_FRACTION: f32 = 0.3;
#[derive(Debug)]
pub struct ColumnWidthOverrides {
overrides: HashMap<usize, u16>,
}
impl ColumnWidthOverrides {
pub fn new() -> Self {
Self {
overrides: HashMap::new(),
}
}
/// Sets the width override for the given origin column index
pub fn set(&mut self, col_index: usize, width: u16) {
self.overrides.insert(col_index, width);
}
/// Returns the width override for the given origin column index, if any
pub fn get(&self, col_index: usize) -> Option<&u16> {
self.overrides.get(&col_index)
}
/// Returns the list of origin column indices that have width overrides
pub fn overriden_indices(&self) -> Vec<usize> {
self.overrides.keys().cloned().collect()
}
pub fn reset(&mut self) {
self.overrides.clear();
}
}
#[derive(Debug)]
pub struct CsvTable<'a> {
header: &'a [Header],
rows: &'a [Row],
}
impl<'a> CsvTable<'a> {
pub fn new(header: &'a [Header], rows: &'a [Row]) -> Self {
Self { header, rows }
}
}
impl<'a> CsvTable<'a> {
fn get_column_widths(
&self,
area_width: u16,
overrides: &ColumnWidthOverrides,
sorter_state: &SorterState,
) -> Vec<u16> {
let mut column_widths = Vec::new();
for h in self.header {
let column_name = self.get_effective_column_name(h.name.as_str(), sorter_state);
if let Some(w) = overrides.get(h.origin_index) {
column_widths.push(*w);
continue;
} else {
column_widths.push(column_name.len() as u16);
}
}
let overriden_indices = overrides.overriden_indices();
for row in self.rows.iter() {
for (i, value) in row.fields.iter().enumerate() {
if i >= column_widths.len() {
continue;
}
if overriden_indices.contains(&self.header.get(i).unwrap().origin_index) {
continue;
}
let v = column_widths.get_mut(i).unwrap();
value.split('\n').for_each(|x| {
let value_len = x.len() as u16;
if *v < value_len {
*v = value_len;
}
});
}
}
// Limit maximum width for a column to make way for other columns
let max_single_column_width = (area_width as f32 * MAX_COLUMN_WIDTH_FRACTION) as u16;
let mut clipped_columns: Vec<(usize, u16)> = vec![];
for (i, w) in column_widths.iter_mut().enumerate() {
if overriden_indices.contains(&self.header.get(i).unwrap().origin_index) {
*w = max(*w, NUM_SPACES_BETWEEN_COLUMNS);
} else {
*w += NUM_SPACES_BETWEEN_COLUMNS;
if *w > max_single_column_width {
clipped_columns.push((i, *w));
*w = max_single_column_width;
}
}
}
// If clipping was too aggressive, redistribute the remaining width
CsvTable::redistribute_widths_after_clpping(
&mut column_widths,
area_width,
clipped_columns,
);
column_widths
}
fn redistribute_widths_after_clpping(
column_widths: &mut [u16],
area_width: u16,
mut clipped_columns: Vec<(usize, u16)>,
) {
if clipped_columns.is_empty() {
// Nothing to adjust
return;
}
let total_width: u16 = column_widths.iter().sum();
if total_width >= area_width {
// No need to adjust if we're already using the full width
return;
}
// Greedily adjust from the narrowest column by equally distributing the remaining width. If
// a column doesn't use the allocated adjustment, subsequent columns will get to use it.
clipped_columns.sort_by_key(|x| x.1);
// Subtract 1 to leave space for the right border. If not, this will be too greedy and
// consume all the space making that border disappear.
let mut remaining_width = area_width.saturating_sub(total_width).saturating_sub(1);
let mut num_columns_to_adjust = clipped_columns.len();
for (i, width_before_clipping) in clipped_columns {
let adjustment = remaining_width / num_columns_to_adjust as u16;
let width_after_adjustment = min(width_before_clipping, column_widths[i] + adjustment);
let added_width = width_after_adjustment - column_widths[i];
column_widths[i] = width_after_adjustment;
remaining_width -= added_width;
num_columns_to_adjust -= 1;
}
}
fn get_row_heights(
&self,
area_height: u16,
rows: &[Row],
column_widths: &[u16],
enable_line_wrap: bool,
is_word_wrap: bool,
) -> Vec<u16> {
if !enable_line_wrap {
return rows.iter().map(|_| 1).collect();
}
let mut total_height = 0;
let mut row_heights = Vec::new();
for (i, row) in rows.iter().enumerate() {
if total_height >= area_height {
// Exit early if we've already filled the available height. Important since
// LineWrapper at its current state is not particularly efficient...
row_heights.push(1);
continue;
}
for (j, content) in row.fields.iter().enumerate() {
let num_lines = match column_widths.get(j) {
Some(w) => {
let usable_width = (*w).saturating_sub(NUM_SPACES_BETWEEN_COLUMNS);
if usable_width > 0 {
let spans = [Span::styled(content.as_str(), Style::default())];
let mut line_wrapper =
wrap::LineWrapper::new(&spans, usable_width as usize, is_word_wrap);
let mut num_lines = 0;
loop {
line_wrapper.next();
num_lines += 1;
if line_wrapper.finished() {
break;
}
}
num_lines
} else {
1
}
}
None => 1,
};
if let Some(height) = row_heights.get_mut(i) {
if *height < num_lines {
*height = num_lines;
}
} else {
row_heights.push(num_lines);
}
}
total_height += row_heights[i];
}
row_heights
}
fn render_row_numbers(
&self,
buf: &mut Buffer,
state: &mut CsvTableState,
area: Rect,
rows: &[Row],
view_layout: &ViewLayout,
) {
// Render line numbers
let y_first_record = area.y;
let mut y = area.y;
for (i, row) in rows.iter().enumerate() {
let row_num_formatted = row.record_num.to_string();
let mut style = Style::default().fg(Color::Rgb(64, 64, 64));
if let Some(selection) = &state.selection {
if selection.row.is_selected(i) {
style = style
.add_modifier(Modifier::BOLD)
.add_modifier(Modifier::UNDERLINED);
}
}
let span = Span::styled(row_num_formatted, style);
buf.set_span(0, y, &span, view_layout.row_number_layout.max_length);
y += view_layout.row_heights[i];
if y >= area.bottom() {
break;
}
}
state.borders_state = Some(BordersState {
x_row_separator: view_layout.row_number_layout.x_row_separator,
y_first_record,
});
}
fn render_header_borders(&self, buf: &mut Buffer, area: Rect) -> (u16, u16) {
let block = Block::default()
.borders(Borders::TOP | Borders::BOTTOM)
.border_style(Style::default().fg(Color::Rgb(64, 64, 64)));
let height = 3;
let area = Rect::new(0, 0, area.width, height);
block.render(area, buf);
// y pos of header text and next line
(height.saturating_sub(2), height)
}
fn render_other_borders(&self, buf: &mut Buffer, area: Rect, state: &CsvTableState) {
// TODO: maybe should be combined with render_header_borders() above
// Render vertical separator
if state.borders_state.is_none() {
return;
}
let borders_state = state.borders_state.as_ref().unwrap();
let y_first_record = borders_state.y_first_record;
let section_width = borders_state.x_row_separator;
if area.width < section_width {
return;
}
let line_number_block = Block::default()
.borders(Borders::RIGHT)
.border_style(Style::default().fg(Color::Rgb(64, 64, 64)));
let line_number_area = Rect::new(0, y_first_record, section_width, area.height);
line_number_block.render(line_number_area, buf);
// Intersection with header separator
if let Some(cell) = buf.cell_mut(Position::new(section_width - 1, y_first_record - 1)) {
cell.set_symbol(line::HORIZONTAL_DOWN);
}
// Status separator at the bottom (rendered here first for the interesection)
let block = Block::default()
.borders(Borders::TOP)
.border_style(Style::default().fg(Color::Rgb(64, 64, 64)));
let status_separator_area = Rect::new(0, y_first_record + area.height, area.width, 1);
block.render(status_separator_area, buf);
// Intersection with bottom separator
if let Some(cell) = buf.cell_mut(Position::new(
section_width - 1,
y_first_record + area.height,
)) {
cell.set_symbol(line::HORIZONTAL_UP);
}
// Vertical line after last rendered column
// TODO: refactor
let col_ending_pos_x = state.col_ending_pos_x;
if !state.has_more_cols_to_show() && col_ending_pos_x < area.right() {
if let Some(cell) = buf.cell_mut(Position::new(
col_ending_pos_x,
y_first_record.saturating_sub(1),
)) {
cell.set_style(Style::default().fg(Color::Rgb(64, 64, 64)))
.set_symbol(line::HORIZONTAL_DOWN);
}
for y in y_first_record..y_first_record + area.height {
if let Some(cell) = buf.cell_mut(Position::new(col_ending_pos_x, y)) {
cell.set_style(Style::default().fg(Color::Rgb(64, 64, 64)))
.set_symbol(line::VERTICAL);
}
}
if let Some(cell) = buf.cell_mut(Position::new(
col_ending_pos_x,
y_first_record + area.height,
)) {
cell.set_style(Style::default().fg(Color::Rgb(64, 64, 64)))
.set_symbol(line::HORIZONTAL_UP);
}
}
}
fn get_effective_column_name(&self, column_name: &str, sorter_state: &SorterState) -> String {
if let SorterState::Enabled(info) = sorter_state {
if info.status == sort::SorterStatus::Finished && info.column_name == column_name {
let indicator = match info.order {
SortOrder::Ascending => "▴",
SortOrder::Descending => "▾",
};
return format!("{} [{}]", column_name, indicator);
}
}
column_name.to_string()
}
#[allow(clippy::too_many_arguments)]
fn render_row(
&self,
buf: &mut Buffer,
state: &mut CsvTableState,
column_widths: &[u16],
area: Rect,
x: u16,
y: u16,
row_type: RowType,
row: &'a [String],
row_index: Option<usize>,
view_layout: &ViewLayout,
remaining_height: Option<u16>,
) -> u16 {
let mut x_offset_header = x;
let mut remaining_width = area.width.saturating_sub(x);
let cols_offset = state.cols_offset as usize;
// TODO: seems strange that these have to be set every row
let mut has_more_cols_to_show = false;
let mut col_ending_pos_x = 0;
let mut num_cols_rendered: u64 = 0;
let row_height = match row_type {
RowType::Header => 1,
RowType::Record(i) => match remaining_height {
Some(h) => min(h, view_layout.row_heights[i]),
None => view_layout.row_heights[i],
},
};
for (col_index, (hname, &hlen)) in row.iter().zip(column_widths).enumerate() {
if col_index < cols_offset {
continue;
}
let effective_width = min(remaining_width, hlen);
let mut content_style = Style::default();
if let RowType::Header = row_type {
content_style = content_style.add_modifier(Modifier::BOLD);
if let Some(selection) = &state.selection {
if selection.column.is_selected(num_cols_rendered as usize) {
content_style = content_style.add_modifier(Modifier::UNDERLINED);
}
}
}
let is_selected = if let Some(selection) = &state.selection {
Self::is_position_selected(selection, &row_type, num_cols_rendered)
} else {
false
};
let mut filler_style = Style::default();
if is_selected {
let selected_style = Style::default()
.fg(Color::Rgb(192, 192, 192))
.bg(Color::Rgb(64, 64, 64))
.add_modifier(Modifier::BOLD);
filler_style = filler_style.patch(selected_style);
content_style = content_style.patch(selected_style);
}
let short_padding = match &state.selection {
Some(selection) => !matches!(selection.selection_type(), view::SelectionType::Row),
None => false,
};
let filler_style = FillerStyle {
style: filler_style,
short_padding,
};
let should_highlight_cell = |active: &FinderActiveState, content: &str| {
if let Some((target_column_index, _)) = active.column_index {
if target_column_index != col_index {
return false;
}
}
active.target.is_match(content) && !matches!(row_type, RowType::Header)
};
match &state.finder_state {
// TODO: seems like doing a bit too much of heavy lifting of
// checking for matches (finder's work)
FinderState::FinderActive(active) if should_highlight_cell(active, hname) => {
let mut highlight_style = filler_style.style.fg(Color::Rgb(200, 0, 0));
if let Some(hl) = &active.found_record {
if let Some(row_index) = row_index {
// TODO: vec::contains slow or does it even matter?
if row_index == hl.row_index()
&& hl.column_indices().contains(&col_index)
{
highlight_style = highlight_style.bg(Color::LightYellow);
}
}
}
let spans = CsvTable::get_highlighted_spans(
active,
hname,
content_style,
highlight_style,
);
self.set_spans(
buf,
&spans,
x_offset_header,
y,
effective_width,
row_height,
filler_style,
state.is_word_wrap,
);
}
_ => {
let span = Span::styled((*hname).as_str(), content_style);
self.set_spans(
buf,
&[span],
x_offset_header,
y,
effective_width,
row_height,
filler_style,
state.is_word_wrap,
);
}
};
x_offset_header += hlen;
col_ending_pos_x = x_offset_header;
num_cols_rendered += 1;
if remaining_width < hlen {
has_more_cols_to_show = true;
break;
}
remaining_width = remaining_width.saturating_sub(hlen);
}
state.num_cols_rendered = max(state.num_cols_rendered, num_cols_rendered);
state.set_more_cols_to_show(has_more_cols_to_show);
state.col_ending_pos_x = max(state.col_ending_pos_x, col_ending_pos_x);
row_height
}
fn is_position_selected(
selection: &view::Selection,
row_type: &RowType,
num_cols_rendered: u64,
) -> bool {
match selection.selection_type() {
view::SelectionType::Row => {
if let RowType::Record(i) = *row_type {
selection.row.is_selected(i)
} else {
false
}
}
view::SelectionType::Column => {
if let RowType::Record(_) = *row_type {
selection.column.is_selected(num_cols_rendered as usize)
} else {
false
}
}
view::SelectionType::Cell => {
if let RowType::Record(i) = *row_type {
selection.row.is_selected(i)
&& selection.column.is_selected(num_cols_rendered as usize)
} else {
false
}
}
_ => false,
}
}
fn get_highlighted_spans(
active: &FinderActiveState,
hname: &'a str,
style: Style,
highlight_style: Style,
) -> Vec<Span<'a>> {
// Each span can only have one style, hence split content into matches and non-matches and
// set styles accordingly
let mut matches = active.target.find_iter(hname);
let non_matches = active.target.split(hname);
let mut spans = vec![];
for part in non_matches {
if !part.is_empty() {
spans.push(Span::styled(part, style));
}
if let Some(m) = matches.next() {
spans.push(Span::styled(m.as_str(), highlight_style));
}
}
spans
}
#[allow(clippy::too_many_arguments)]
fn set_spans(
&self,
buf: &mut Buffer,
spans: &[Span],
x: u16,
y: u16,
width: u16,
height: u16,
filler_style: FillerStyle,
is_word_wrap: bool,
) {
const SUFFIX: &str = "…";
const SUFFIX_LEN: u16 = 1;
// Reserve some space before the next column (same number used in get_column_widths)
let effective_width = width.saturating_sub(NUM_SPACES_BETWEEN_COLUMNS);
let buffer_space = if filler_style.short_padding {
NUM_SPACES_BETWEEN_COLUMNS / 2
} else {
NUM_SPACES_BETWEEN_COLUMNS
} as usize;
let mut line_wrapper =
wrap::LineWrapper::new(spans, effective_width as usize, is_word_wrap);
for offset in 0..height {
if let Some(mut line) = line_wrapper.next() {
// There is some content to render. Truncate with ... if there is no more vertical
// space available.
if offset == height - 1 && !line_wrapper.finished() {
if let Some(last_span) = line.spans.pop() {
let truncate_length = last_span.width().saturating_sub(SUFFIX_LEN as usize);
let truncated_content: String =
last_span.content.chars().take(truncate_length).collect();
let truncated_span = Span::styled(truncated_content, last_span.style);
line.spans.push(truncated_span);
line.spans.push(Span::styled(SUFFIX, last_span.style));
}
}
let padding_width = min(
(effective_width as usize + buffer_space).saturating_sub(line.width()),
width as usize,
);
if padding_width > 0 {
line.spans
.push(Span::styled(" ".repeat(padding_width), filler_style.style));
}
buf.set_line(x, y + offset, &line, width);
} else {
// There are extra vertical spaces that are just empty lines. Fill them with the
// correct style.
let mut content =
" ".repeat(min(effective_width as usize + buffer_space, width as usize));
// It's possible that no spans are yielded due to insufficient remaining width.
// Render ... in this case.
if !line_wrapper.finished() {
let truncated_content: String = content
.chars()
.take(content.len().saturating_sub(1))
.collect();
content = format!("{SUFFIX}{}", truncated_content.as_str());
}
let span = Span::styled(content, filler_style.style);
buf.set_line(x, y + offset, &Line::from(vec![span]), width);
}
}
}
fn render_status(&self, area: Rect, buf: &mut Buffer, state: &mut CsvTableState) {
// Content of status line (separator already plotted elsewhere)
let style = Style::default().fg(Color::Rgb(128, 128, 128));
let mut content: String;
state.cursor_xy = None;
if let Some(msg) = &state.transient_message {
content = msg.to_owned();
} else if let BufferState::Enabled(buffer_mode, input) = &state.buffer_content {
let get_prefix = |&input_mode| {
let prefix = match input_mode {
InputMode::GotoLine => "Go to line",
InputMode::Find => "Find",
InputMode::Filter => "Filter",
InputMode::FilterColumns => "Columns regex",
InputMode::Option => "Option",
_ => "",
};
if prefix.is_empty() {
"".to_string()
} else {
format!("{prefix}: ")
}
};
let prefix = get_prefix(buffer_mode);
content = format!("{prefix}{}", input.value());
state.cursor_xy = Some((
area.x
.saturating_add(prefix.len() as u16)
.saturating_add(input.cursor() as u16),
area.bottom().saturating_sub(1),
));
} else {
// Filename
if let Some(f) = &state.filename {
content = f.to_string();
} else {
content = "stdin".to_string();
}
// Row / Col
let total_str = match state.total_line_number {
Some((total, false)) => format!("{}", total),
Some((total, true)) => format!("{}+", total),
_ => "?".to_owned(),
};
let current_row;
if let Some(selection) = &state.selection {
current_row = if let Some(i) = selection.row.index() {
self.rows.get(i as usize)
} else {
self.rows.first()
}
} else {
current_row = self.rows.first()
}
let row_num = match current_row {
Some(row) => row.record_num.to_string(),
_ => "-".to_owned(),
};
content += format!(
" [Row {}/{}, Col {}/{}]",
row_num,
total_str,
state.cols_offset + 1,
state.total_cols,
)
.as_str();
// Finder
if let FinderState::FinderActive(s) = &state.finder_state {
content += format!(" {}", s.status_line()).as_str();
}
if let Some(stats_line) = &state.debug_stats.status_line() {
content += format!(" {stats_line}").as_str();
}
// Filter columns
if let FilterColumnsState::Enabled(info) = &state.filter_columns_state {
content += format!(" {}", info.status_line()).as_str();
}
// Sorter
if let SorterState::Enabled(info) = &state.sorter_state {
let sorter_status_line = info.status_line();
if !sorter_status_line.is_empty() {
content += format!(" {}", sorter_status_line).as_str();
}
}
// Echo option
if let Some(column_name) = &state.echo_column {
content += format!(" [Echo {column_name} ↵]").as_str();
}
// Ignore case option
if state.ignore_case {
content += " [ignore-case]";
}
// Debug
if !state.debug.is_empty() {
content += format!(" (debug: {})", state.debug).as_str();
}
}
let span = Span::styled(content, style);
buf.set_span(area.x, area.bottom().saturating_sub(1), &span, area.width);
}
fn get_view_layout(&self, area: Rect, state: &mut CsvTableState, rows: &[Row]) -> ViewLayout {
let max_row_num = rows.iter().map(|x| x.record_num).max().unwrap_or(0);
let max_row_num_length = format!("{max_row_num}").len() as u16;
let row_num_section_width_with_spaces =
max_row_num_length + 2 * NUM_SPACES_AFTER_LINE_NUMBER + 1;
let x_row_separator = max_row_num_length + NUM_SPACES_AFTER_LINE_NUMBER + 1;
let column_widths = self.get_column_widths(
area.width.saturating_sub(row_num_section_width_with_spaces),
&state.column_width_overrides,
&state.sorter_state,
);
let _tic = std::time::Instant::now();
let row_heights = self.get_row_heights(
area.height,
self.rows,
&column_widths,
state.enable_line_wrap,
state.is_word_wrap,
);
state.num_cols_rendered = 0;
state.col_ending_pos_x = 0;
let row_number_layout = RowNumberLayout {
max_length: max_row_num_length,
width_with_spaces: row_num_section_width_with_spaces,
x_row_separator,
};
ViewLayout {
column_widths,
row_heights,
row_number_layout,
}
}
}
impl<'a> StatefulWidget for CsvTable<'a> {
type State = CsvTableState;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
// TODO: draw relative to the provided area
if area.area() == 0 {
return;
}
let status_height = 2;
let layout = self.get_view_layout(area, state, self.rows);
state.view_layout = Some(layout.clone());
let (y_header, y_first_record) = self.render_header_borders(buf, area);
// row area: including row numbers and row content
let rows_area = Rect::new(
area.x,
y_first_record,
area.width,
area.height
.saturating_sub(y_first_record)
.saturating_sub(status_height),
);
self.render_row_numbers(buf, state, rows_area, self.rows, &layout);
let row_num_section_width = layout.row_number_layout.width_with_spaces;
self.render_row(
buf,
state,
&layout.column_widths,
rows_area,
row_num_section_width,
y_header,
RowType::Header,
&self
.header
.iter()
.map(|h| self.get_effective_column_name(h.name.as_str(), &state.sorter_state))
.collect::<Vec<String>>(),
None,
&layout,
None,
);
let mut remaining_height = rows_area.height;
let mut y_offset = y_first_record;
for (i, row) in self.rows.iter().enumerate() {
let rendered_height = self.render_row(
buf,
state,
&layout.column_widths,
rows_area,
row_num_section_width,
y_offset,
RowType::Record(i),
&row.fields,
Some(row.record_num - 1),
&layout,
Some(remaining_height),
);
remaining_height = remaining_height.saturating_sub(rendered_height);
y_offset += rendered_height;
if y_offset >= rows_area.bottom() {
break;
}
}
let status_area = Rect::new(
area.x,
area.bottom().saturating_sub(status_height),
area.width,
status_height,
);
self.render_status(status_area, buf, state);
self.render_other_borders(buf, rows_area, state);
}
}
pub enum RowType {
/// Header row
Header,
/// Regular row. Contains the row index (not the record number) and the row itself.
Record(usize),
}
/// Style to use for the fillers (spaces and elipses) between columns
#[derive(Clone, Copy)]
struct FillerStyle {
style: Style,
short_padding: bool,
}
#[derive(Debug, Clone)]
pub struct RowNumberLayout {
pub max_length: u16,
pub width_with_spaces: u16,
pub x_row_separator: u16,
}
#[derive(Debug, Clone)]
pub struct ViewLayout {
pub column_widths: Vec<u16>,
pub row_heights: Vec<u16>,
pub row_number_layout: RowNumberLayout,
}
impl ViewLayout {
pub fn num_rows_renderable(&self, frame_height: u16) -> usize {
let mut out = 0;
let mut remaining = frame_height;
for h in &self.row_heights {
if *h > remaining {
if remaining > 0 {
// Include partially rendered row
out += 1;
}
break;
}
out += 1;
remaining -= h;
}
out
}
}
pub enum BufferState {
Disabled,
Enabled(InputMode, Input),
}
pub enum FinderState {
FinderInactive,
FinderActive(FinderActiveState),
}
impl FinderState {
pub fn from_finder(finder: &find::Finder, rows_view: &view::RowsView) -> FinderState {
let active_state = FinderActiveState::new(finder, rows_view);
FinderState::FinderActive(active_state)
}
}
pub struct FinderActiveState {
find_complete: bool,
total_found: u64,
cursor_index: Option<u64>,
target: Regex,
column_index: Option<(usize, String)>,
found_record: Option<find::FoundRecord>,
selected_offset: Option<u64>,
is_filter: bool,
}
impl FinderActiveState {
pub fn new(finder: &find::Finder, rows_view: &view::RowsView) -> Self {
FinderActiveState {
find_complete: finder.done(),
total_found: finder.count() as u64,
cursor_index: finder.cursor().map(|x| x as u64),
target: finder.target(),
column_index: finder
.column_index()
.map(|i| (i, rows_view.get_column_name_from_global_index(i))),
found_record: finder.current(),
selected_offset: rows_view.selected_offset(),
is_filter: rows_view.is_filter(),
}
}
fn status_line(&self) -> String {
let plus_marker;
let line;
if self.total_found == 0 {
if self.find_complete {
line = "Not found".to_owned();
} else {
line = "Finding...".to_owned();
}
} else {
if self.find_complete {
plus_marker = "";
} else {
plus_marker = "+";
}
let cursor_str;
if self.is_filter {
if let Some(i) = self.selected_offset {
cursor_str = i.saturating_add(1).to_string();
} else {
cursor_str = "-".to_owned();
}
} else if let Some(i) = self.cursor_index {
cursor_str = (i.saturating_add(1)).to_string();
} else {
cursor_str = "-".to_owned();
}
line = format!("{cursor_str}/{}{plus_marker}", self.total_found);
}
let action = if self.is_filter { "Filter" } else { "Find" };
let target_column = self
.column_index
.as_ref()
.map(|(_, name)| format!(" in {}", name))
.unwrap_or_default();
format!("[{action} \"{}\"{target_column}: {line}]", self.target)
}
}
pub enum FilterColumnsState {
Disabled,
Enabled(FilterColumnsInfo),
}
impl FilterColumnsState {
pub fn from_rows_view(rows_view: &view::RowsView) -> Self {
if let Some(columns_filter) = rows_view.columns_filter() {
Self::Enabled(FilterColumnsInfo {
pattern: columns_filter.pattern(),
shown: columns_filter.num_filtered(),
total: columns_filter.num_original(),
disabled_because_no_match: columns_filter.disabled_because_no_match(),
})
} else {
Self::Disabled
}
}
}
pub struct FilterColumnsInfo {
pattern: Regex,
shown: usize,
total: usize,
disabled_because_no_match: bool,