-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathViewTable.cs
615 lines (449 loc) · 20 KB
/
ViewTable.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
// Developed by Bulat Bagaviev (@sunnyyssh).
// This file is licensed to you under the MIT license.
using System.Collections.Immutable;
using Sunnyyssh.ConsoleUI.Binding;
// ReSharper disable AutoPropertyCanBeMadeGetOnly.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable CollectionNeverUpdated.Global
// ReSharper disable PrivateFieldCanBeConvertedToLocalVariable
namespace Sunnyyssh.ConsoleUI;
public sealed class ViewTable : UIElement, IFocusable
{
private static readonly VerticalAligning CellTextVerticalAligning = VerticalAligning.Top;
private static readonly HorizontalAligning CellTextHorizontalAligning = HorizontalAligning.Left;
private static readonly VerticalAligning HeaderTextVerticalAligning = VerticalAligning.Top;
private static readonly HorizontalAligning HeaderTextHorizontalAligning = HorizontalAligning.Left;
private readonly ImmutableList<ImmutableList<string?>> _initData;
private readonly string?[][] _dataRows;
// ReSharper disable once NotAccessedField.Local
private ForceTakeFocusHandler? _forceTakeFocusHandler;
// ReSharper disable once NotAccessedField.Local
private ForceLoseFocusHandler? _forceLoseFocusHandler;
private IObservable<IDataTable<string?>, DataTableUpdateArgs<string?>>? _observing;
private IBindable<IDataTable<string?>, DataTableUpdateArgs<string?>>? _bound;
public int CurrentTopAreaRow { get; private set; } = 0;
public int CurrentViewRow { get; private set; } = 0;
public int CurrentColumn { get; private set; } = 0;
public IReadOnlyList<string> Headers { get; }
public LineCharSet BorderCharSet { get; }
public AbsoluteGridDefinition AbsoluteGridDefinition { get; }
public int ViewRowsCount { get; }
public bool Scrollable { get; }
public int HeadersCount => Headers.Count;
public int DataRowsCount => _dataRows.Length;
#region init properties.
public bool EnterOnCellChange { get; init; }
public Color CellNotFocusedBackground { get; init; } = Color.Default;
public Color HeaderBackground { get; init; } = Color.Default;
public Color CellNotFocusedForeground { get; init; } = Color.Default;
public Color HeaderForeground { get; init; } = Color.Default;
public Color CellFocusedBackground { get; init; } = Color.Default;
public Color CellFocusedForeground { get; init; } = Color.Default;
public Color BorderColorNotFocused { get; init; } = Color.Default;
public Color BorderColorFocused { get; init; } = Color.Default;
public ImmutableList<ConsoleKey>? MoveRightKeys { get; init; }
public ImmutableList<ConsoleKey>? MoveLeftKeys { get; init; }
public ImmutableList<ConsoleKey>? MoveUpKeys { get; init; }
public ImmutableList<ConsoleKey>? MoveDownKeys { get; init; }
public bool CellsWordWrap { get; init; } = true;
public bool UserEditable { get; init; } = true;
public bool LoseFocusOnEnter { get; init; } = false;
#endregion
public bool IsFocused { get; private set; }
public bool IsWaitingFocus { get; set; } = true;
bool IFocusable.IsWaitingFocus => IsWaitingFocus && (UserEditable || Scrollable);
public string? this[int row, int column]
{
get => _dataRows[row][column];
set => SetText(row, column, value);
}
private void SetText(int row, int column, string? value)
{
value = CharHelper.RemoveSpecialChars(value, false);
_dataRows[row][column] = value;
int possibleViewRow = row - CurrentTopAreaRow;
if (IsStateInitialized && possibleViewRow >= 0 && possibleViewRow < ViewRowsCount)
{
RedrawCell(possibleViewRow, column);
}
}
#region Binding.
public void Observe(IObservable<IDataTable<string?>, DataTableUpdateArgs<string?>> tableObservable)
{
ArgumentNullException.ThrowIfNull(tableObservable, nameof(tableObservable));
if (UserEditable)
{
throw new InvalidOperationException($"Can't observe {nameof(tableObservable)} when {nameof(UserEditable)}=true." +
$"Try {nameof(Bind)} or set {nameof(UserEditable)}=false.");
}
if (_observing is not null)
{
_observing.Updated -= HandleObservableUpdate;
}
_observing = tableObservable;
_observing.Updated += HandleObservableUpdate;
_observing.Value
.ToRowArray()
.CopyTo(_dataRows, 0);
if (IsStateInitialized)
{
Redraw(CreateDrawState());
}
}
public void Unobserve()
{
if (_observing is null)
{
throw new InvalidOperationException("Nothing was observed.");
}
_observing.Updated -= HandleObservableUpdate;
_observing = null;
_initData
.Select(Enumerable.ToArray)
.ToArray()
.CopyTo(_dataRows, 0);
if (IsStateInitialized)
{
Redraw(CreateDrawState());
}
}
public void Bind(IBindable<IDataTable<string?>, DataTableUpdateArgs<string?>> tableBindable)
{
ArgumentNullException.ThrowIfNull(tableBindable, nameof(tableBindable));
if (_observing is not null)
{
_observing.Updated -= HandleObservableUpdate;
}
_observing = tableBindable;
_observing.Updated += HandleObservableUpdate;
_observing.Value
.ToRowArray()
.CopyTo(_dataRows, 0);
if (IsStateInitialized)
{
Redraw(CreateDrawState());
}
_bound = tableBindable;
}
public void Unbind()
{
if (_observing is null)
{
throw new InvalidOperationException("Nothing was observed.");
}
_observing.Updated -= HandleObservableUpdate;
_observing = null;
_initData
.Select(Enumerable.ToArray)
.ToArray()
.CopyTo(_dataRows, 0);
if (IsStateInitialized)
{
Redraw(CreateDrawState());
}
_bound = null;
}
private void HandleObservableUpdate(IObservable<IDataTable<string?>, DataTableUpdateArgs<string?>> sender, DataTableUpdateArgs<string?> args)
{
SetText(args.Row, args.Column, args.NewValue);
}
private void OnTextEntered(int row, int column, string? text)
{
if (_bound is null)
return;
if (_bound.Value[row, column] == text)
return;
var args = new DataTableUpdateArgs<string?>(row, column, text);
_bound.HandleUpdate(args);
}
#endregion
#region Drawing stuff.
private void RedrawCell(int viewRow, int column)
{
int cellLeft = 1 + AbsoluteGridDefinition.Columns.Take(column).Sum(gridColumn => gridColumn.Width + 1);
int cellTop = 1 + AbsoluteGridDefinition.Rows.Take(viewRow + 1).Sum(gridRow => gridRow.Height + 1);
int cellWidth = AbsoluteGridDefinition.Columns[column].Width;
int cellHeight = AbsoluteGridDefinition.Rows[viewRow + 1].Height;
var stateBuilder = new DrawStateBuilder(cellWidth, cellHeight);
bool isCellFocused = IsFocused && viewRow == CurrentViewRow && column == CurrentColumn;
var cellBackground = isCellFocused ? CellFocusedBackground : CellNotFocusedBackground;
var cellForeground = isCellFocused ? CellFocusedForeground : CellNotFocusedForeground;
stateBuilder.Fill(cellBackground);
var text = this[CurrentTopAreaRow + viewRow, column];
if (text is not null)
{
TextHelper.PlaceText(0, 0, cellWidth, cellHeight,
CellsWordWrap, text, cellBackground, cellForeground,
CellTextVerticalAligning, CellTextHorizontalAligning,
stateBuilder);
}
var builtState = stateBuilder.ToDrawState().Shift(cellLeft, cellTop);
Redraw(builtState);
}
protected override DrawState CreateDrawState()
{
var stateBuilder = new DrawStateBuilder(Width, Height);
int headersAreaHeight = AbsoluteGridDefinition.Rows[0].Height + 2; // + 2 for borders.
// Filling headers background.
stateBuilder.Fill(0, 0, Width, headersAreaHeight, new PixelInfo(HeaderBackground));
// Filling cells background.
stateBuilder.Fill(0, headersAreaHeight, Width, Height - headersAreaHeight,
new PixelInfo(CellNotFocusedBackground));
var borderColor = IsFocused ? BorderColorFocused : BorderColorNotFocused;
var border = GridBuilder.CreateBorder(Width, Height, AbsoluteGridDefinition, BorderCharSet, borderColor);
// Creating border.
var borderState = border.RequestDrawState(new DrawOptions());
stateBuilder.OverlapWith(borderState);
PlaceHeaders(stateBuilder);
PlaceCells(stateBuilder);
return stateBuilder.ToDrawState();
}
private void PlaceHeaders(DrawStateBuilder stateBuilder)
{
int top = 1; // init 1 for border.
int accumulatedLeft = 1; // init 1 for border.
int rowHeight = AbsoluteGridDefinition.Rows[0].Height;
for (int column = 0; column < HeadersCount; column++)
{
int columnWidth = AbsoluteGridDefinition.Columns[column].Width;
TextHelper.PlaceText(accumulatedLeft, top, Width, rowHeight,
// No need in word-wrapping headers.
false, Headers[column], HeaderBackground, HeaderForeground,
HeaderTextVerticalAligning, HeaderTextHorizontalAligning, stateBuilder);
accumulatedLeft += columnWidth + 1;
}
}
private void PlaceCells(DrawStateBuilder stateBuilder)
{
int accumulatedTop = 2 + AbsoluteGridDefinition.Rows[0].Height; // init 2 because of 2 borders and headers row.
for (int viewRow = 0; viewRow < ViewRowsCount; viewRow++)
{
int accumulatedLeft = 1; // init 1 because of border.
int rowHeight = AbsoluteGridDefinition.Rows[viewRow + 1].Height;
var thisRow = _dataRows[CurrentTopAreaRow + viewRow];
for (int column = 0; column < HeadersCount; column++)
{
int columnWidth = AbsoluteGridDefinition.Columns[column].Width;
var cellBackground = CellNotFocusedBackground;
var cellForeground = CellNotFocusedForeground;
if (viewRow == CurrentViewRow && column == CurrentColumn && IsFocused)
{
cellBackground = CellFocusedBackground;
cellForeground = CellFocusedForeground;
// Filling focused cell.
stateBuilder.Fill(accumulatedLeft, accumulatedTop, columnWidth, rowHeight,
new PixelInfo(cellBackground));
}
var text = thisRow[column];
if (text is not null)
{
TextHelper.PlaceText(accumulatedLeft, accumulatedTop, columnWidth, rowHeight,
CellsWordWrap, text, cellBackground, cellForeground,
CellTextVerticalAligning, CellTextHorizontalAligning,
stateBuilder);
}
accumulatedLeft += columnWidth + 1; // + 1 for border.
}
accumulatedTop += rowHeight + 1; // + 1 for border.
}
}
#endregion
#region Handling keys
bool IFocusable.HandlePressedKey(ConsoleKeyInfo keyInfo)
{
var key = keyInfo.Key;
if (MoveUpKeys?.Contains(key) ?? false)
{
MoveUp();
return true;
}
if (MoveDownKeys?.Contains(key) ?? false)
{
MoveDown();
return true;
}
if (MoveLeftKeys?.Contains(key) ?? false)
{
MoveLeft();
return true;
}
if (MoveRightKeys?.Contains(key) ?? false)
{
MoveRight();
return true;
}
if (UserEditable)
{
return HandleCellEdit(keyInfo);
}
return true;
}
private bool HandleCellEdit(ConsoleKeyInfo keyInfo)
{
if (IsSpecialKey(keyInfo.Key))
{
HandleSpecialKey(keyInfo.Key, out bool loseFocus);
return !loseFocus;
}
char newChar = keyInfo.KeyChar;
if (newChar == '\0')
return true;
this[CurrentTopAreaRow + CurrentViewRow, CurrentColumn] += newChar;
return true;
}
private static readonly ConsoleKey[] SpecialKeys = new[] { ConsoleKey.Backspace, ConsoleKey.Enter };
private bool IsSpecialKey(ConsoleKey key)
{
return SpecialKeys.Contains(key);
}
private void HandleSpecialKey(ConsoleKey key, out bool loseFocus)
{
int currentDataRow = CurrentTopAreaRow + CurrentViewRow;
if (key == ConsoleKey.Enter)
{
OnTextEntered(currentDataRow, CurrentColumn, this[currentDataRow, CurrentColumn]);
loseFocus = LoseFocusOnEnter;
return;
}
if (key == ConsoleKey.Backspace)
{
if (this[currentDataRow, CurrentColumn]?.Length > 0)
{
this[currentDataRow, CurrentColumn] = this[currentDataRow, CurrentColumn]![..^1];
}
loseFocus = false;
return;
}
throw new ArgumentException("Key wasn't special.", nameof(key));
}
private void MoveUp()
{
if (CurrentViewRow == 0)
{
if (CurrentTopAreaRow == 0)
return;
int prevViewRow = CurrentTopAreaRow--;
string? enteredText = this[prevViewRow + CurrentViewRow, CurrentColumn];
OnTextEntered(prevViewRow + CurrentViewRow, CurrentColumn, enteredText);
if (IsStateInitialized)
{
Redraw(CreateDrawState());
}
return;
}
int prevRow = CurrentViewRow;
CurrentViewRow--;
RedrawCell(prevRow, CurrentColumn);
RedrawCell(CurrentViewRow, CurrentColumn);
string? text = this[prevRow + CurrentTopAreaRow, CurrentColumn];
OnTextEntered(prevRow + CurrentTopAreaRow, CurrentColumn, text);
}
private void MoveDown()
{
if (CurrentViewRow == ViewRowsCount - 1)
{
if (CurrentTopAreaRow == _dataRows.Length - ViewRowsCount)
return;
int prevViewRow = CurrentTopAreaRow++;
string? enteredText = this[prevViewRow + CurrentViewRow, CurrentColumn];
OnTextEntered(prevViewRow + CurrentViewRow, CurrentColumn, enteredText);
if (IsStateInitialized)
{
Redraw(CreateDrawState());
}
return;
}
int prevRow = CurrentViewRow;
CurrentViewRow++;
RedrawCell(prevRow, CurrentColumn);
RedrawCell(CurrentViewRow, CurrentColumn);
string? text = this[prevRow + CurrentTopAreaRow, CurrentColumn];
OnTextEntered(prevRow + CurrentTopAreaRow, CurrentColumn, text);
}
private void MoveRight()
{
if (CurrentColumn == HeadersCount - 1)
return;
int prevColumn = CurrentColumn;
CurrentColumn++;
RedrawCell(CurrentViewRow, prevColumn);
RedrawCell(CurrentViewRow, CurrentColumn);
string? text = this[CurrentTopAreaRow + CurrentViewRow, prevColumn];
OnTextEntered(CurrentTopAreaRow + CurrentViewRow, prevColumn, text);
}
private void MoveLeft()
{
if (CurrentColumn == 0)
return;
int prevColumn = CurrentColumn;
CurrentColumn--;
RedrawCell(CurrentViewRow, prevColumn);
RedrawCell(CurrentViewRow, CurrentColumn);
string? text = this[CurrentTopAreaRow + CurrentViewRow, prevColumn];
OnTextEntered(CurrentTopAreaRow + CurrentViewRow, prevColumn, text);
}
#endregion
#region IFocusable stuff.
void IFocusable.TakeFocus()
{
IsFocused = true;
if (IsStateInitialized)
{
if (BorderColorFocused != BorderColorNotFocused)
{
Redraw(CreateDrawState());
return;
}
RedrawCell(CurrentViewRow, CurrentColumn);
}
}
void IFocusable.LoseFocus()
{
IsFocused = false;
if (IsStateInitialized)
{
if (BorderColorFocused != BorderColorNotFocused)
{
Redraw(CreateDrawState());
return;
}
RedrawCell(CurrentViewRow, CurrentColumn);
}
}
event ForceTakeFocusHandler IFocusable.ForceTakeFocus
{
add => _forceTakeFocusHandler += value ?? throw new ArgumentNullException(nameof(value));
remove => _forceTakeFocusHandler -= value ?? throw new ArgumentNullException(nameof(value));
}
event ForceLoseFocusHandler IFocusable.ForceLoseFocus
{
add => _forceLoseFocusHandler += value ?? throw new ArgumentNullException(nameof(value));
remove => _forceLoseFocusHandler -= value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
internal ViewTable(int width, int height, ImmutableList<string> headers, LineCharSet borderCharSet,
ImmutableList<ImmutableList<string?>> initData, AbsoluteGridDefinition absoluteGridDefinition,
OverlappingPriority overlappingPriority)
: base(width, height, overlappingPriority)
{
ArgumentNullException.ThrowIfNull(headers, nameof(headers));
ArgumentNullException.ThrowIfNull(borderCharSet, nameof(borderCharSet));
ArgumentNullException.ThrowIfNull(absoluteGridDefinition, nameof(absoluteGridDefinition));
ArgumentNullException.ThrowIfNull(initData, nameof(initData));
Headers = headers;
BorderCharSet = borderCharSet;
AbsoluteGridDefinition = absoluteGridDefinition;
if (Headers.Count != absoluteGridDefinition.ColumnCount)
throw new ArgumentException("Headers count doesn't match grid rows count.", nameof(absoluteGridDefinition));
ViewRowsCount = absoluteGridDefinition.RowCount - 1;
if (ViewRowsCount < 1)
throw new ArgumentException("It must have at least two rows.", nameof(absoluteGridDefinition));
if (initData.Count < ViewRowsCount)
throw new ArgumentException("Data rows count must be not less than view rows count.", nameof(initData));
if (initData.Any(row => row.Count != Headers.Count))
throw new ArgumentException("Data size doesn't match headers count.", nameof(initData));
_initData = initData;
_dataRows = initData.Select(Enumerable.ToArray).ToArray();
Scrollable = _dataRows.Length > ViewRowsCount;
}
}