-
Notifications
You must be signed in to change notification settings - Fork 673
/
TableView.cs
2019 lines (1651 loc) · 68.7 KB
/
TableView.cs
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
using NStack;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace Terminal.Gui {
/// <summary>
/// View for tabular data based on a <see cref="DataTable"/>.
///
/// <a href="https://gui-cs.github.io/Terminal.Gui/articles/tableview.html">See TableView Deep Dive for more information</a>.
/// </summary>
public class TableView : View {
/// <summary>
/// Defines the event arguments for <see cref="TableView.CellActivated"/> event
/// </summary>
public class CellActivatedEventArgs : EventArgs {
/// <summary>
/// The current table to which the new indexes refer. May be null e.g. if selection change is the result of clearing the table from the view
/// </summary>
/// <value></value>
public DataTable Table { get; }
/// <summary>
/// The column index of the <see cref="Table"/> cell that is being activated
/// </summary>
/// <value></value>
public int Col { get; }
/// <summary>
/// The row index of the <see cref="Table"/> cell that is being activated
/// </summary>
/// <value></value>
public int Row { get; }
/// <summary>
/// Creates a new instance of arguments describing a cell being activated in <see cref="TableView"/>
/// </summary>
/// <param name="t"></param>
/// <param name="col"></param>
/// <param name="row"></param>
public CellActivatedEventArgs (DataTable t, int col, int row)
{
Table = t;
Col = col;
Row = row;
}
}
private int columnOffset;
private int rowOffset;
private int selectedRow;
private int selectedColumn;
private DataTable table;
private TableStyle style = new TableStyle ();
private Key cellActivationKey = Key.Enter;
Point? scrollLeftPoint;
Point? scrollRightPoint;
/// <summary>
/// The default maximum cell width for <see cref="TableView.MaxCellWidth"/> and <see cref="ColumnStyle.MaxWidth"/>
/// </summary>
public const int DefaultMaxCellWidth = 100;
/// <summary>
/// The default minimum cell width for <see cref="ColumnStyle.MinAcceptableWidth"/>
/// </summary>
public const int DefaultMinAcceptableWidth = 100;
/// <summary>
/// The data table to render in the view. Setting this property automatically updates and redraws the control.
/// </summary>
public DataTable Table { get => table; set { table = value; Update (); } }
/// <summary>
/// Contains options for changing how the table is rendered
/// </summary>
public TableStyle Style { get => style; set { style = value; Update (); } }
/// <summary>
/// True to select the entire row at once. False to select individual cells. Defaults to false
/// </summary>
public bool FullRowSelect { get; set; }
/// <summary>
/// True to allow regions to be selected
/// </summary>
/// <value></value>
public bool MultiSelect { get; set; } = true;
/// <summary>
/// When <see cref="MultiSelect"/> is enabled this property contain all rectangles of selected cells. Rectangles describe column/rows selected in <see cref="Table"/> (not screen coordinates)
/// </summary>
/// <returns></returns>
public Stack<TableSelection> MultiSelectedRegions { get; } = new Stack<TableSelection> ();
/// <summary>
/// Horizontal scroll offset. The index of the first column in <see cref="Table"/> to display when when rendering the view.
/// </summary>
/// <remarks>This property allows very wide tables to be rendered with horizontal scrolling</remarks>
public int ColumnOffset {
get => columnOffset;
//try to prevent this being set to an out of bounds column
set => columnOffset = TableIsNullOrInvisible() ? 0 : Math.Max (0, Math.Min (Table.Columns.Count - 1, value));
}
/// <summary>
/// Vertical scroll offset. The index of the first row in <see cref="Table"/> to display in the first non header line of the control when rendering the view.
/// </summary>
public int RowOffset {
get => rowOffset;
set => rowOffset = TableIsNullOrInvisible () ? 0 : Math.Max (0, Math.Min (Table.Rows.Count - 1, value));
}
/// <summary>
/// The index of <see cref="DataTable.Columns"/> in <see cref="Table"/> that the user has currently selected
/// </summary>
public int SelectedColumn {
get => selectedColumn;
set {
var oldValue = selectedColumn;
//try to prevent this being set to an out of bounds column
selectedColumn = TableIsNullOrInvisible () ? 0 : Math.Min (Table.Columns.Count - 1, Math.Max (0, value));
if (oldValue != selectedColumn)
OnSelectedCellChanged (new SelectedCellChangedEventArgs (Table, oldValue, SelectedColumn, SelectedRow, SelectedRow));
}
}
/// <summary>
/// The index of <see cref="DataTable.Rows"/> in <see cref="Table"/> that the user has currently selected
/// </summary>
public int SelectedRow {
get => selectedRow;
set {
var oldValue = selectedRow;
selectedRow = TableIsNullOrInvisible () ? 0 : Math.Min (Table.Rows.Count - 1, Math.Max (0, value));
if (oldValue != selectedRow)
OnSelectedCellChanged (new SelectedCellChangedEventArgs (Table, SelectedColumn, SelectedColumn, oldValue, selectedRow));
}
}
/// <summary>
/// The maximum number of characters to render in any given column. This prevents one long column from pushing out all the others
/// </summary>
public int MaxCellWidth { get; set; } = DefaultMaxCellWidth;
/// <summary>
/// The text representation that should be rendered for cells with the value <see cref="DBNull.Value"/>
/// </summary>
public string NullSymbol { get; set; } = "-";
/// <summary>
/// The symbol to add after each cell value and header value to visually seperate values (if not using vertical gridlines)
/// </summary>
public char SeparatorSymbol { get; set; } = ' ';
/// <summary>
/// This event is raised when the selected cell in the table changes.
/// </summary>
public event Action<SelectedCellChangedEventArgs> SelectedCellChanged;
/// <summary>
/// This event is raised when a cell is activated e.g. by double clicking or pressing <see cref="CellActivationKey"/>
/// </summary>
public event Action<CellActivatedEventArgs> CellActivated;
/// <summary>
/// The key which when pressed should trigger <see cref="CellActivated"/> event. Defaults to Enter.
/// </summary>
public Key CellActivationKey {
get => cellActivationKey;
set {
if (cellActivationKey != value) {
ReplaceKeyBinding (cellActivationKey, value);
// of API user is mixing and matching old and new methods of keybinding then they may have lost
// the old binding (e.g. with ClearKeybindings) so ReplaceKeyBinding alone will fail
AddKeyBinding (value, Command.Accept);
cellActivationKey = value;
}
}
}
/// <summary>
/// Initialzies a <see cref="TableView"/> class using <see cref="LayoutStyle.Computed"/> layout.
/// </summary>
/// <param name="table">The table to display in the control</param>
public TableView (DataTable table) : this ()
{
this.Table = table;
}
/// <summary>
/// Initialzies a <see cref="TableView"/> class using <see cref="LayoutStyle.Computed"/> layout. Set the <see cref="Table"/> property to begin editing
/// </summary>
public TableView () : base ()
{
CanFocus = true;
// Things this view knows how to do
AddCommand (Command.Right, () => { ChangeSelectionByOffset (1, 0, false); return true; });
AddCommand (Command.Left, () => { ChangeSelectionByOffset (-1, 0, false); return true; });
AddCommand (Command.LineUp, () => { ChangeSelectionByOffset (0, -1, false); return true; });
AddCommand (Command.LineDown, () => { ChangeSelectionByOffset (0, 1, false); return true; });
AddCommand (Command.PageUp, () => { PageUp (false); return true; });
AddCommand (Command.PageDown, () => { PageDown (false); return true; });
AddCommand (Command.LeftHome, () => { ChangeSelectionToStartOfRow (false); return true; });
AddCommand (Command.RightEnd, () => { ChangeSelectionToEndOfRow (false); return true; });
AddCommand (Command.TopHome, () => { ChangeSelectionToStartOfTable(false); return true; });
AddCommand (Command.BottomEnd, () => { ChangeSelectionToEndOfTable (false); return true; });
AddCommand (Command.RightExtend, () => { ChangeSelectionByOffset (1, 0, true); return true; });
AddCommand (Command.LeftExtend, () => { ChangeSelectionByOffset (-1, 0, true); return true; });
AddCommand (Command.LineUpExtend, () => { ChangeSelectionByOffset (0, -1, true); return true; });
AddCommand (Command.LineDownExtend, () => { ChangeSelectionByOffset (0, 1, true); return true; });
AddCommand (Command.PageUpExtend, () => { PageUp (true); return true; });
AddCommand (Command.PageDownExtend, () => { PageDown (true); return true; });
AddCommand (Command.LeftHomeExtend, () => { ChangeSelectionToStartOfRow (true); return true; });
AddCommand (Command.RightEndExtend, () => { ChangeSelectionToEndOfRow (true); return true; });
AddCommand (Command.TopHomeExtend, () => { ChangeSelectionToStartOfTable (true); return true; });
AddCommand (Command.BottomEndExtend, () => { ChangeSelectionToEndOfTable (true); return true; });
AddCommand (Command.SelectAll, () => { SelectAll(); return true; });
AddCommand (Command.Accept, () => { OnCellActivated(new CellActivatedEventArgs (Table, SelectedColumn, SelectedRow)); return true; });
// Default keybindings for this view
AddKeyBinding (Key.CursorLeft, Command.Left);
AddKeyBinding (Key.CursorRight, Command.Right);
AddKeyBinding (Key.CursorUp, Command.LineUp);
AddKeyBinding (Key.CursorDown, Command.LineDown);
AddKeyBinding (Key.PageUp, Command.PageUp);
AddKeyBinding (Key.PageDown, Command.PageDown);
AddKeyBinding (Key.Home, Command.LeftHome);
AddKeyBinding (Key.End, Command.RightEnd);
AddKeyBinding (Key.Home | Key.CtrlMask, Command.TopHome);
AddKeyBinding (Key.End | Key.CtrlMask, Command.BottomEnd);
AddKeyBinding (Key.CursorLeft | Key.ShiftMask, Command.LeftExtend);
AddKeyBinding (Key.CursorRight | Key.ShiftMask, Command.RightExtend);
AddKeyBinding (Key.CursorUp | Key.ShiftMask, Command.LineUpExtend);
AddKeyBinding (Key.CursorDown| Key.ShiftMask, Command.LineDownExtend);
AddKeyBinding (Key.PageUp | Key.ShiftMask, Command.PageUpExtend);
AddKeyBinding (Key.PageDown | Key.ShiftMask, Command.PageDownExtend);
AddKeyBinding (Key.Home | Key.ShiftMask, Command.LeftHomeExtend);
AddKeyBinding (Key.End | Key.ShiftMask, Command.RightEndExtend);
AddKeyBinding (Key.Home | Key.CtrlMask | Key.ShiftMask, Command.TopHomeExtend);
AddKeyBinding (Key.End | Key.CtrlMask | Key.ShiftMask, Command.BottomEndExtend);
AddKeyBinding (Key.A | Key.CtrlMask, Command.SelectAll);
AddKeyBinding (CellActivationKey, Command.Accept);
}
///<inheritdoc/>
public override void Redraw (Rect bounds)
{
Move (0, 0);
var frame = Frame;
scrollRightPoint = null;
scrollLeftPoint = null;
// What columns to render at what X offset in viewport
var columnsToRender = CalculateViewport (bounds).ToArray ();
Driver.SetAttribute (GetNormalColor ());
//invalidate current row (prevents scrolling around leaving old characters in the frame
Driver.AddStr (new string (' ', bounds.Width));
int line = 0;
if (ShouldRenderHeaders ()) {
// Render something like:
/*
┌────────────────────┬──────────┬───────────┬──────────────┬─────────┐
│ArithmeticComparator│chi │Healthboard│Interpretation│Labnumber│
└────────────────────┴──────────┴───────────┴──────────────┴─────────┘
*/
if (Style.ShowHorizontalHeaderOverline) {
RenderHeaderOverline (line, bounds.Width, columnsToRender);
line++;
}
RenderHeaderMidline (line, columnsToRender);
line++;
if (Style.ShowHorizontalHeaderUnderline) {
RenderHeaderUnderline (line, bounds.Width, columnsToRender);
line++;
}
}
int headerLinesConsumed = line;
//render the cells
for (; line < frame.Height; line++) {
ClearLine (line, bounds.Width);
//work out what Row to render
var rowToRender = RowOffset + (line - headerLinesConsumed);
//if we have run off the end of the table
if (TableIsNullOrInvisible () || rowToRender >= Table.Rows.Count || rowToRender < 0)
continue;
RenderRow (line, rowToRender, columnsToRender);
}
}
/// <summary>
/// Clears a line of the console by filling it with spaces
/// </summary>
/// <param name="row"></param>
/// <param name="width"></param>
private void ClearLine (int row, int width)
{
Move (0, row);
Driver.SetAttribute (GetNormalColor ());
Driver.AddStr (new string (' ', width));
}
/// <summary>
/// Returns the amount of vertical space currently occupied by the header or 0 if it is not visible.
/// </summary>
/// <returns></returns>
private int GetHeaderHeightIfAny ()
{
return ShouldRenderHeaders () ? GetHeaderHeight () : 0;
}
/// <summary>
/// Returns the amount of vertical space required to display the header
/// </summary>
/// <returns></returns>
private int GetHeaderHeight ()
{
int heightRequired = 1;
if (Style.ShowHorizontalHeaderOverline)
heightRequired++;
if (Style.ShowHorizontalHeaderUnderline)
heightRequired++;
return heightRequired;
}
private void RenderHeaderOverline (int row, int availableWidth, ColumnToRender [] columnsToRender)
{
// Renders a line above table headers (when visible) like:
// ┌────────────────────┬──────────┬───────────┬──────────────┬─────────┐
for (int c = 0; c < availableWidth; c++) {
var rune = Driver.HLine;
if (Style.ShowVerticalHeaderLines) {
if (c == 0) {
rune = Driver.ULCorner;
}
// if the next column is the start of a header
else if (columnsToRender.Any (r => r.X == c + 1)) {
rune = Driver.TopTee;
} else if (c == availableWidth - 1) {
rune = Driver.URCorner;
}
// if the next console column is the lastcolumns end
else if (Style.ExpandLastColumn == false &&
columnsToRender.Any (r => r.IsVeryLast && r.X + r.Width - 1 == c)) {
rune = Driver.TopTee;
}
}
AddRuneAt (Driver, c, row, rune);
}
}
private void RenderHeaderMidline (int row, ColumnToRender [] columnsToRender)
{
// Renders something like:
// │ArithmeticComparator│chi │Healthboard│Interpretation│Labnumber│
ClearLine (row, Bounds.Width);
//render start of line
if (style.ShowVerticalHeaderLines)
AddRune (0, row, Driver.VLine);
for (int i = 0; i < columnsToRender.Length; i++) {
var current = columnsToRender [i];
var colStyle = Style.GetColumnStyleIfAny (current.Column);
var colName = current.Column.ColumnName;
RenderSeparator (current.X - 1, row, true);
Move (current.X, row);
Driver.AddStr (TruncateOrPad (colName, colName, current.Width, colStyle));
if (Style.ExpandLastColumn == false && current.IsVeryLast) {
RenderSeparator (current.X + current.Width - 1, row, true);
}
}
//render end of line
if (style.ShowVerticalHeaderLines)
AddRune (Bounds.Width - 1, row, Driver.VLine);
}
private void RenderHeaderUnderline (int row, int availableWidth, ColumnToRender [] columnsToRender)
{
/*
* First lets work out if we should be rendering scroll indicators
*/
// are there are visible columns to the left that have been pushed
// off the screen due to horizontal scrolling?
bool moreColumnsToLeft = ColumnOffset > 0;
// if we moved left would we find a new column (or are they all invisible?)
if(!TryGetNearestVisibleColumn (ColumnOffset-1, false, false, out _)) {
moreColumnsToLeft = false;
}
// are there visible columns to the right that have not yet been reached?
// lets find out, what is the column index of the last column we are rendering
int lastColumnIdxRendered = ColumnOffset + columnsToRender.Length - 1;
// are there more valid indexes?
bool moreColumnsToRight = lastColumnIdxRendered < Table.Columns.Count;
// if we went right from the last column would we find a new visible column?
if(!TryGetNearestVisibleColumn (lastColumnIdxRendered + 1, true, false, out _)) {
// no we would not
moreColumnsToRight = false;
}
/*
* Now lets draw the line itself
*/
// Renders a line below the table headers (when visible) like:
// ├──────────┼───────────┼───────────────────┼──────────┼────────┼─────────────┤
for (int c = 0; c < availableWidth; c++) {
// Start by assuming we just draw a straight line the
// whole way but update to instead draw a header indicator
// or scroll arrow etc
var rune = Driver.HLine;
if (Style.ShowVerticalHeaderLines) {
if (c == 0) {
// for first character render line
rune = Style.ShowVerticalCellLines ? Driver.LeftTee : Driver.LLCorner;
// unless we have horizontally scrolled along
// in which case render an arrow, to indicate user
// can scroll left
if(Style.ShowHorizontalScrollIndicators && moreColumnsToLeft)
{
rune = Driver.LeftArrow;
scrollLeftPoint = new Point(c,row);
}
}
// if the next column is the start of a header
else if (columnsToRender.Any (r => r.X == c + 1)) {
/*TODO: is ┼ symbol in Driver?*/
rune = Style.ShowVerticalCellLines ? '┼' : Driver.BottomTee;
} else if (c == availableWidth - 1) {
// for the last character in the table
rune = Style.ShowVerticalCellLines ? Driver.RightTee : Driver.LRCorner;
// unless there is more of the table we could horizontally
// scroll along to see. In which case render an arrow,
// to indicate user can scroll right
if(Style.ShowHorizontalScrollIndicators && moreColumnsToRight)
{
rune = Driver.RightArrow;
scrollRightPoint = new Point(c,row);
}
}
// if the next console column is the lastcolumns end
else if (Style.ExpandLastColumn == false &&
columnsToRender.Any (r => r.IsVeryLast && r.X + r.Width - 1 == c)) {
rune = Style.ShowVerticalCellLines ? '┼' : Driver.BottomTee;
}
}
AddRuneAt (Driver, c, row, rune);
}
}
private void RenderRow (int row, int rowToRender, ColumnToRender [] columnsToRender)
{
var focused = HasFocus;
var rowScheme = (Style.RowColorGetter?.Invoke (
new RowColorGetterArgs(Table,rowToRender))) ?? ColorScheme;
//render start of line
if (style.ShowVerticalCellLines)
AddRune (0, row, Driver.VLine);
//start by clearing the entire line
Move (0, row);
Attribute color;
if(FullRowSelect && IsSelected (0, rowToRender)) {
color = focused ? rowScheme.HotFocus : rowScheme.HotNormal;
}
else
{
color = Enabled ? rowScheme.Normal : rowScheme.Disabled;
}
Driver.SetAttribute (color);
Driver.AddStr (new string (' ', Bounds.Width));
// Render cells for each visible header for the current row
for (int i = 0; i < columnsToRender.Length; i++) {
var current = columnsToRender [i];
var colStyle = Style.GetColumnStyleIfAny (current.Column);
// move to start of cell (in line with header positions)
Move (current.X, row);
// Set color scheme based on whether the current cell is the selected one
bool isSelectedCell = IsSelected (current.Column.Ordinal, rowToRender);
var val = Table.Rows [rowToRender] [current.Column];
// Render the (possibly truncated) cell value
var representation = GetRepresentation (val, colStyle);
// to get the colour scheme
var colorSchemeGetter = colStyle?.ColorGetter;
ColorScheme scheme;
if(colorSchemeGetter != null) {
// user has a delegate for defining row color per cell, call it
scheme = colorSchemeGetter(
new CellColorGetterArgs (Table, rowToRender, current.Column.Ordinal, val, representation,rowScheme));
// if users custom color getter returned null, use the row scheme
if(scheme == null) {
scheme = rowScheme;
}
}
else {
// There is no custom cell coloring delegate so use the scheme for the row
scheme = rowScheme;
}
Attribute cellColor;
if (isSelectedCell) {
cellColor = focused ? scheme.HotFocus : scheme.HotNormal;
} else {
cellColor = Enabled ? scheme.Normal : scheme.Disabled;
}
var render = TruncateOrPad (val, representation, current.Width, colStyle);
// While many cells can be selected (see MultiSelectedRegions) only one cell is the primary (drives navigation etc)
bool isPrimaryCell = current.Column.Ordinal == selectedColumn && rowToRender == selectedRow;
RenderCell (cellColor,render,isPrimaryCell);
// Reset color scheme to normal for drawing separators if we drew text with custom scheme
if (scheme != rowScheme) {
if(isSelectedCell) {
color = focused ? rowScheme.HotFocus : rowScheme.HotNormal;
}
else {
color = Enabled ? rowScheme.Normal : rowScheme.Disabled;
}
Driver.SetAttribute (color);
}
// If not in full row select mode always, reset color scheme to normal and render the vertical line (or space) at the end of the cell
if (!FullRowSelect)
Driver.SetAttribute (Enabled ? rowScheme.Normal : rowScheme.Disabled);
RenderSeparator (current.X - 1, row, false);
if (Style.ExpandLastColumn == false && current.IsVeryLast) {
RenderSeparator (current.X + current.Width - 1, row, false);
}
}
//render end of line
if (style.ShowVerticalCellLines)
AddRune (Bounds.Width - 1, row, Driver.VLine);
}
/// <summary>
/// Override to provide custom multi colouring to cells. Use <see cref="View.Driver"/> to
/// with <see cref="ConsoleDriver.AddStr(ustring)"/>. The driver will already be
/// in the correct place when rendering and you must render the full <paramref name="render"/>
/// or the view will not look right. For simpler provision of color use <see cref="ColumnStyle.ColorGetter"/>
/// For changing the content that is rendered use <see cref="ColumnStyle.RepresentationGetter"/>
/// </summary>
/// <param name="cellColor"></param>
/// <param name="render"></param>
/// <param name="isPrimaryCell"></param>
protected virtual void RenderCell (Attribute cellColor, string render,bool isPrimaryCell)
{
// If the cell is the selected col/row then draw the first rune in inverted colors
// this allows the user to track which cell is the active one during a multi cell
// selection or in full row select mode
if (Style.InvertSelectedCellFirstCharacter && isPrimaryCell) {
if (render.Length > 0) {
// invert the color of the current cell for the first character
Driver.SetAttribute (Driver.MakeAttribute (cellColor.Background, cellColor.Foreground));
Driver.AddRune (render [0]);
if (render.Length > 1) {
Driver.SetAttribute (cellColor);
Driver.AddStr (render.Substring (1));
}
}
} else {
Driver.SetAttribute (cellColor);
Driver.AddStr (render);
}
}
private void RenderSeparator (int col, int row, bool isHeader)
{
if (col < 0)
return;
var renderLines = isHeader ? style.ShowVerticalHeaderLines : style.ShowVerticalCellLines;
Rune symbol = renderLines ? Driver.VLine : SeparatorSymbol;
AddRune (col, row, symbol);
}
void AddRuneAt (ConsoleDriver d, int col, int row, Rune ch)
{
Move (col, row);
d.AddRune (ch);
}
/// <summary>
/// Truncates or pads <paramref name="representation"/> so that it occupies a exactly <paramref name="availableHorizontalSpace"/> using the alignment specified in <paramref name="colStyle"/> (or left if no style is defined)
/// </summary>
/// <param name="originalCellValue">The object in this cell of the <see cref="Table"/></param>
/// <param name="representation">The string representation of <paramref name="originalCellValue"/></param>
/// <param name="availableHorizontalSpace"></param>
/// <param name="colStyle">Optional style indicating custom alignment for the cell</param>
/// <returns></returns>
private string TruncateOrPad (object originalCellValue, string representation, int availableHorizontalSpace, ColumnStyle colStyle)
{
if (string.IsNullOrEmpty (representation))
return representation;
// if value is not wide enough
if (representation.Sum (c => Rune.ColumnWidth (c)) < availableHorizontalSpace) {
// pad it out with spaces to the given alignment
int toPad = availableHorizontalSpace - (representation.Sum (c => Rune.ColumnWidth (c)) + 1 /*leave 1 space for cell boundary*/);
switch (colStyle?.GetAlignment (originalCellValue) ?? TextAlignment.Left) {
case TextAlignment.Left:
return representation + new string (' ', toPad);
case TextAlignment.Right:
return new string (' ', toPad) + representation;
// TODO: With single line cells, centered and justified are the same right?
case TextAlignment.Centered:
case TextAlignment.Justified:
return
new string (' ', (int)Math.Floor (toPad / 2.0)) + // round down
representation +
new string (' ', (int)Math.Ceiling (toPad / 2.0)); // round up
}
}
// value is too wide
return new string (representation.TakeWhile (c => (availableHorizontalSpace -= Rune.ColumnWidth (c)) > 0).ToArray ());
}
/// <inheritdoc/>
public override bool ProcessKey (KeyEvent keyEvent)
{
if (TableIsNullOrInvisible ()) {
PositionCursor ();
return false;
}
var result = InvokeKeybindings (keyEvent);
if (result != null) {
PositionCursor ();
return true;
}
return false;
}
/// <summary>
/// Moves the <see cref="SelectedRow"/> and <see cref="SelectedColumn"/> to the given col/row in <see cref="Table"/>. Optionally starting a box selection (see <see cref="MultiSelect"/>)
/// </summary>
/// <param name="col"></param>
/// <param name="row"></param>
/// <param name="extendExistingSelection">True to create a multi cell selection or adjust an existing one</param>
public void SetSelection (int col, int row, bool extendExistingSelection)
{
// if we are trying to increase the column index then
// we are moving right otherwise we are moving left
bool lookRight = col > selectedColumn;
col = GetNearestVisibleColumn (col, lookRight, true);
if (!MultiSelect || !extendExistingSelection)
MultiSelectedRegions.Clear ();
if (extendExistingSelection) {
// If we are extending current selection but there isn't one
if (MultiSelectedRegions.Count == 0) {
// Create a new region between the old active cell and the new cell
var rect = CreateTableSelection (SelectedColumn, SelectedRow, col, row);
MultiSelectedRegions.Push (rect);
} else {
// Extend the current head selection to include the new cell
var head = MultiSelectedRegions.Pop ();
var newRect = CreateTableSelection (head.Origin.X, head.Origin.Y, col, row);
MultiSelectedRegions.Push (newRect);
}
}
SelectedColumn = col;
SelectedRow = row;
}
/// <summary>
/// Unions the current selected cell (and/or regions) with the provided cell and makes
/// it the active one.
/// </summary>
/// <param name="col"></param>
/// <param name="row"></param>
private void UnionSelection (int col, int row)
{
if (!MultiSelect || TableIsNullOrInvisible()) {
return;
}
EnsureValidSelection ();
var oldColumn = SelectedColumn;
var oldRow = SelectedRow;
// move us to the new cell
SelectedColumn = col;
SelectedRow = row;
MultiSelectedRegions.Push (
CreateTableSelection (col, row)
);
// if the old cell was not part of a rectangular select
// or otherwise selected we need to retain it in the selection
if (!IsSelected (oldColumn, oldRow)) {
MultiSelectedRegions.Push (
CreateTableSelection (oldColumn, oldRow)
);
}
}
/// <summary>
/// Moves the <see cref="SelectedRow"/> and <see cref="SelectedColumn"/> by the provided offsets. Optionally starting a box selection (see <see cref="MultiSelect"/>)
/// </summary>
/// <param name="offsetX">Offset in number of columns</param>
/// <param name="offsetY">Offset in number of rows</param>
/// <param name="extendExistingSelection">True to create a multi cell selection or adjust an existing one</param>
public void ChangeSelectionByOffset (int offsetX, int offsetY, bool extendExistingSelection)
{
SetSelection (SelectedColumn + offsetX, SelectedRow + offsetY, extendExistingSelection);
Update ();
}
/// <summary>
/// Moves the selection up by one page
/// </summary>
/// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
public void PageUp(bool extend)
{
ChangeSelectionByOffset (0, -(Bounds.Height - GetHeaderHeightIfAny ()), extend);
Update ();
}
/// <summary>
/// Moves the selection down by one page
/// </summary>
/// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
public void PageDown(bool extend)
{
ChangeSelectionByOffset (0, Bounds.Height - GetHeaderHeightIfAny (), extend);
Update ();
}
/// <summary>
/// Moves or extends the selection to the first cell in the table (0,0).
/// If <see cref="FullRowSelect"/> is enabled then selection instead moves
/// to (<see cref="SelectedColumn"/>,0) i.e. no horizontal scrolling.
/// </summary>
/// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
public void ChangeSelectionToStartOfTable (bool extend)
{
SetSelection (FullRowSelect ? SelectedColumn : 0, 0, extend);
Update ();
}
/// <summary>
/// Moves or extends the selection to the final cell in the table (nX,nY).
/// If <see cref="FullRowSelect"/> is enabled then selection instead moves
/// to (<see cref="SelectedColumn"/>,nY) i.e. no horizontal scrolling.
/// </summary>
/// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
public void ChangeSelectionToEndOfTable(bool extend)
{
var finalColumn = Table.Columns.Count - 1;
SetSelection (FullRowSelect ? SelectedColumn : finalColumn, Table.Rows.Count - 1, extend);
Update ();
}
/// <summary>
/// Moves or extends the selection to the last cell in the current row
/// </summary>
/// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
public void ChangeSelectionToEndOfRow (bool extend)
{
SetSelection (Table.Columns.Count - 1, SelectedRow, extend);
Update ();
}
/// <summary>
/// Moves or extends the selection to the first cell in the current row
/// </summary>
/// <param name="extend">true to extend the current selection (if any) instead of replacing</param>
public void ChangeSelectionToStartOfRow (bool extend)
{
SetSelection (0, SelectedRow, extend);
Update ();
}
/// <summary>
/// When <see cref="MultiSelect"/> is on, creates selection over all cells in the table (replacing any old selection regions)
/// </summary>
public void SelectAll ()
{
if (TableIsNullOrInvisible() || !MultiSelect || Table.Rows.Count == 0)
return;
MultiSelectedRegions.Clear ();
// Create a single region over entire table, set the origin of the selection to the active cell so that a followup spread selection e.g. shift-right behaves properly
MultiSelectedRegions.Push (new TableSelection (new Point (SelectedColumn, SelectedRow), new Rect (0, 0, Table.Columns.Count, table.Rows.Count)));
Update ();
}
/// <summary>
/// Returns all cells in any <see cref="MultiSelectedRegions"/> (if <see cref="MultiSelect"/> is enabled) and the selected cell
/// </summary>
/// <remarks>Return value is not affected by <see cref="FullRowSelect"/> (i.e. returned <see cref="Point"/>s are not expanded to
/// include all points on row).</remarks>
/// <returns></returns>
public IEnumerable<Point> GetAllSelectedCells ()
{
if (TableIsNullOrInvisible () || Table.Rows.Count == 0)
yield break;
EnsureValidSelection ();
// If there are one or more rectangular selections
if (MultiSelect && MultiSelectedRegions.Any ()) {
// Quiz any cells for whether they are selected. For performance we only need to check those between the top left and lower right vertex of selection regions
var yMin = MultiSelectedRegions.Min (r => r.Rect.Top);
var yMax = MultiSelectedRegions.Max (r => r.Rect.Bottom);
var xMin = FullRowSelect ? 0 : MultiSelectedRegions.Min (r => r.Rect.Left);
var xMax = FullRowSelect ? Table.Columns.Count : MultiSelectedRegions.Max (r => r.Rect.Right);
for (int y = yMin; y < yMax; y++) {
for (int x = xMin; x < xMax; x++) {
if (IsSelected (x, y)) {
yield return new Point (x, y);
}
}
}
} else {
// if there are no region selections then it is just the active cell
// if we are selecting the full row
if (FullRowSelect) {
// all cells in active row are selected
for (int x = 0; x < Table.Columns.Count; x++) {
yield return new Point (x, SelectedRow);
}
} else {
// Not full row select and no multi selections
yield return new Point (SelectedColumn, SelectedRow);
}
}
}
/// <summary>
/// Returns a new rectangle between the two points with positive width/height regardless of relative positioning of the points. pt1 is always considered the <see cref="TableSelection.Origin"/> point
/// </summary>
/// <param name="pt1X">Origin point for the selection in X</param>
/// <param name="pt1Y">Origin point for the selection in Y</param>
/// <param name="pt2X">End point for the selection in X</param>
/// <param name="pt2Y">End point for the selection in Y</param>
/// <returns></returns>
private TableSelection CreateTableSelection (int pt1X, int pt1Y, int pt2X, int pt2Y)
{
var top = Math.Max(Math.Min (pt1Y, pt2Y), 0);
var bot = Math.Max(Math.Max (pt1Y, pt2Y), 0);
var left = Math.Max(Math.Min (pt1X, pt2X), 0);
var right = Math.Max(Math.Max (pt1X, pt2X), 0);
// Rect class is inclusive of Top Left but exclusive of Bottom Right so extend by 1
return new TableSelection (new Point (pt1X, pt1Y), new Rect (left, top, right - left + 1, bot - top + 1));
}
/// <summary>
/// Returns a single point as a <see cref="TableSelection"/>
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
private TableSelection CreateTableSelection (int x, int y)
{
return CreateTableSelection (x, y, x, y);
}
/// <summary>
/// <para>
/// Returns true if the given cell is selected either because it is the active cell or part of a multi cell selection (e.g. <see cref="FullRowSelect"/>).
/// </para>
/// <remarks>Returns <see langword="false"/> if <see cref="ColumnStyle.Visible"/> is <see langword="false"/>.</remarks>
/// </summary>
/// <param name="col"></param>
/// <param name="row"></param>
/// <returns></returns>
public bool IsSelected (int col, int row)
{
if(!IsColumnVisible(col)) {
return false;
}
// Cell is also selected if in any multi selection region
if (MultiSelect && MultiSelectedRegions.Any (r => r.Rect.Contains (col, row)))
return true;
// Cell is also selected if Y axis appears in any region (when FullRowSelect is enabled)
if (FullRowSelect && MultiSelect && MultiSelectedRegions.Any (r => r.Rect.Bottom > row && r.Rect.Top <= row))
return true;
return row == SelectedRow &&
(col == SelectedColumn || FullRowSelect);
}
/// <summary>
/// Returns true if the given <paramref name="columnIndex"/> indexes a visible
/// column otherwise false. Returns false for indexes that are out of bounds.
/// </summary>