-
Notifications
You must be signed in to change notification settings - Fork 695
/
NetDriver.cs
1583 lines (1397 loc) · 45.1 KB
/
NetDriver.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
//
// NetDriver.cs: The System.Console-based .NET driver, works on Windows and Unix, but is not particularly efficient.
//
// Authors:
// Miguel de Icaza ([email protected])
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using NStack;
namespace Terminal.Gui {
internal class NetWinVTConsole {
IntPtr InputHandle, OutputHandle, ErrorHandle;
uint originalInputConsoleMode, originalOutputConsoleMode, originalErrorConsoleMode;
public NetWinVTConsole ()
{
InputHandle = GetStdHandle (STD_INPUT_HANDLE);
if (!GetConsoleMode (InputHandle, out uint mode)) {
throw new ApplicationException ($"Failed to get input console mode, error code: {GetLastError ()}.");
}
originalInputConsoleMode = mode;
if ((mode & ENABLE_VIRTUAL_TERMINAL_INPUT) < ENABLE_VIRTUAL_TERMINAL_INPUT) {
mode |= ENABLE_VIRTUAL_TERMINAL_INPUT;
if (!SetConsoleMode (InputHandle, mode)) {
throw new ApplicationException ($"Failed to set input console mode, error code: {GetLastError ()}.");
}
}
OutputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
if (!GetConsoleMode (OutputHandle, out mode)) {
throw new ApplicationException ($"Failed to get output console mode, error code: {GetLastError ()}.");
}
originalOutputConsoleMode = mode;
if ((mode & (ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN)) < DISABLE_NEWLINE_AUTO_RETURN) {
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN;
if (!SetConsoleMode (OutputHandle, mode)) {
throw new ApplicationException ($"Failed to set output console mode, error code: {GetLastError ()}.");
}
}
ErrorHandle = GetStdHandle (STD_ERROR_HANDLE);
if (!GetConsoleMode (ErrorHandle, out mode)) {
throw new ApplicationException ($"Failed to get error console mode, error code: {GetLastError ()}.");
}
originalErrorConsoleMode = mode;
if ((mode & (DISABLE_NEWLINE_AUTO_RETURN)) < DISABLE_NEWLINE_AUTO_RETURN) {
mode |= DISABLE_NEWLINE_AUTO_RETURN;
if (!SetConsoleMode (ErrorHandle, mode)) {
throw new ApplicationException ($"Failed to set error console mode, error code: {GetLastError ()}.");
}
}
}
public void Cleanup ()
{
if (!SetConsoleMode (InputHandle, originalInputConsoleMode)) {
throw new ApplicationException ($"Failed to restore input console mode, error code: {GetLastError ()}.");
}
if (!SetConsoleMode (OutputHandle, originalOutputConsoleMode)) {
throw new ApplicationException ($"Failed to restore output console mode, error code: {GetLastError ()}.");
}
if (!SetConsoleMode (ErrorHandle, originalErrorConsoleMode)) {
throw new ApplicationException ($"Failed to restore error console mode, error code: {GetLastError ()}.");
}
}
const int STD_INPUT_HANDLE = -10;
const int STD_OUTPUT_HANDLE = -11;
const int STD_ERROR_HANDLE = -12;
// Input modes.
const uint ENABLE_PROCESSED_INPUT = 1;
const uint ENABLE_LINE_INPUT = 2;
const uint ENABLE_ECHO_INPUT = 4;
const uint ENABLE_WINDOW_INPUT = 8;
const uint ENABLE_MOUSE_INPUT = 16;
const uint ENABLE_INSERT_MODE = 32;
const uint ENABLE_QUICK_EDIT_MODE = 64;
const uint ENABLE_EXTENDED_FLAGS = 128;
const uint ENABLE_VIRTUAL_TERMINAL_INPUT = 512;
// Output modes.
const uint ENABLE_PROCESSED_OUTPUT = 1;
const uint ENABLE_WRAP_AT_EOL_OUTPUT = 2;
const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4;
const uint DISABLE_NEWLINE_AUTO_RETURN = 8;
const uint ENABLE_LVB_GRID_WORLDWIDE = 10;
[DllImport ("kernel32.dll", SetLastError = true)]
static extern IntPtr GetStdHandle (int nStdHandle);
[DllImport ("kernel32.dll")]
static extern bool GetConsoleMode (IntPtr hConsoleHandle, out uint lpMode);
[DllImport ("kernel32.dll")]
static extern bool SetConsoleMode (IntPtr hConsoleHandle, uint dwMode);
[DllImport ("kernel32.dll")]
static extern uint GetLastError ();
}
internal class NetEvents {
ManualResetEventSlim inputReady = new ManualResetEventSlim (false);
ManualResetEventSlim waitForStart = new ManualResetEventSlim (false);
ManualResetEventSlim winChange = new ManualResetEventSlim (false);
Queue<InputResult?> inputResultQueue = new Queue<InputResult?> ();
ConsoleDriver consoleDriver;
volatile ConsoleKeyInfo [] cki = null;
static volatile bool isEscSeq;
internal CancellationTokenSource TokenSource = new CancellationTokenSource ();
#if PROCESS_REQUEST
bool neededProcessRequest;
#endif
public EscSeqReqProc EscSeqReqProc { get; } = new EscSeqReqProc ();
public NetEvents (ConsoleDriver consoleDriver)
{
if (consoleDriver == null) {
throw new ArgumentNullException ("Console driver instance must be provided.");
}
this.consoleDriver = consoleDriver;
Task.Run (ProcessInputResultQueue, TokenSource.Token);
Task.Run (CheckWinChange, TokenSource.Token);
}
public InputResult? ReadConsoleInput ()
{
while (!TokenSource.IsCancellationRequested) {
waitForStart.Set ();
winChange.Set ();
if (inputResultQueue.Count == 0) {
inputReady.Wait ();
inputReady.Reset ();
}
#if PROCESS_REQUEST
neededProcessRequest = false;
#endif
if (inputResultQueue.Count > 0) {
return inputResultQueue.Dequeue ();
}
}
return null;
}
void ProcessInputResultQueue ()
{
while (!TokenSource.IsCancellationRequested) {
waitForStart.Wait ();
waitForStart.Reset ();
if (inputResultQueue.Count == 0) {
GetConsoleKey ();
}
inputReady.Set ();
}
}
void GetConsoleKey ()
{
ConsoleKey key = 0;
ConsoleModifiers mod = 0;
ConsoleKeyInfo newConsoleKeyInfo = default;
while (!TokenSource.IsCancellationRequested) {
ConsoleKeyInfo consoleKeyInfo = default;
try {
if (Console.KeyAvailable) {
consoleKeyInfo = Console.ReadKey (true);
} else {
Task.Delay (100, TokenSource.Token).Wait (TokenSource.Token);
if (Console.KeyAvailable) {
consoleKeyInfo = Console.ReadKey (true);
}
}
} catch (OperationCanceledException) {
return;
}
if ((consoleKeyInfo.KeyChar == (char)Key.Esc && !isEscSeq)
|| (consoleKeyInfo.KeyChar != (char)Key.Esc && isEscSeq)) {
if (cki == null && consoleKeyInfo.KeyChar != (char)Key.Esc && isEscSeq) {
cki = EscSeqUtils.ResizeArray (new ConsoleKeyInfo ((char)Key.Esc, 0,
false, false, false), cki);
}
isEscSeq = true;
newConsoleKeyInfo = consoleKeyInfo;
cki = EscSeqUtils.ResizeArray (consoleKeyInfo, cki);
if (!Console.KeyAvailable) {
DecodeEscSeq (ref newConsoleKeyInfo, ref key, cki, ref mod);
cki = null;
isEscSeq = false;
break;
}
} else if (consoleKeyInfo.KeyChar == (char)Key.Esc && isEscSeq) {
DecodeEscSeq (ref newConsoleKeyInfo, ref key, cki, ref mod);
cki = null;
if (!Console.KeyAvailable) {
isEscSeq = false;
}
break;
} else {
if (consoleKeyInfo != default) {
GetConsoleInputType (consoleKeyInfo);
break;
}
}
TokenSource.Token.ThrowIfCancellationRequested ();
}
}
void CheckWinChange ()
{
while (!TokenSource.IsCancellationRequested) {
winChange.Wait ();
winChange.Reset ();
WaitWinChange ();
inputReady.Set ();
}
}
void WaitWinChange ()
{
while (!TokenSource.IsCancellationRequested) {
try {
// Wait for a while then check if screen has changed sizes
Task.Delay (500, TokenSource.Token).Wait (TokenSource.Token);
} catch (OperationCanceledException) {
return;
}
int buffHeight, buffWidth;
if (((NetDriver)consoleDriver).IsWinPlatform) {
buffHeight = Math.Max (Console.BufferHeight, 0);
buffWidth = Math.Max (Console.BufferWidth, 0);
} else {
buffHeight = consoleDriver.Rows;
buffWidth = consoleDriver.Cols;
}
if (IsWinChanged (
Math.Max (Console.WindowHeight, 0),
Math.Max (Console.WindowWidth, 0),
buffHeight,
buffWidth)) {
return;
}
}
}
bool IsWinChanged (int winHeight, int winWidth, int buffHeight, int buffWidth)
{
if (winWidth != consoleDriver.Cols || winHeight != consoleDriver.Rows) {
var w = Math.Max (winWidth, 0);
var h = Math.Max (winHeight, 0);
GetWindowSizeEvent (new Size (w, h));
return true;
}
return false;
}
void GetWindowSizeEvent (Size size)
{
WindowSizeEvent windowSizeEvent = new WindowSizeEvent () {
Size = size
};
inputResultQueue.Enqueue (new InputResult () {
EventType = EventType.WindowSize,
WindowSizeEvent = windowSizeEvent
});
}
void GetConsoleInputType (ConsoleKeyInfo consoleKeyInfo)
{
InputResult inputResult = new InputResult {
EventType = EventType.Key
};
MouseEvent mouseEvent = new MouseEvent ();
ConsoleKeyInfo newConsoleKeyInfo = EscSeqUtils.GetConsoleInputKey (consoleKeyInfo);
if (inputResult.EventType == EventType.Key) {
inputResult.ConsoleKeyInfo = newConsoleKeyInfo;
} else {
inputResult.MouseEvent = mouseEvent;
}
inputResultQueue.Enqueue (inputResult);
}
void DecodeEscSeq (ref ConsoleKeyInfo newConsoleKeyInfo, ref ConsoleKey key, ConsoleKeyInfo [] cki, ref ConsoleModifiers mod)
{
string c1Control, code, terminating;
string [] values;
// isKeyMouse is true if it's CSI<, false otherwise
bool isKeyMouse;
bool isReq;
List<MouseFlags> mouseFlags;
Point pos;
EscSeqUtils.DecodeEscSeq (EscSeqReqProc, ref newConsoleKeyInfo, ref key, cki, ref mod, out c1Control, out code, out values, out terminating, out isKeyMouse, out mouseFlags, out pos, out isReq, ProcessContinuousButtonPressed);
if (isKeyMouse) {
foreach (var mf in mouseFlags) {
GetMouseEvent (MapMouseFlags (mf), pos);
}
return;
} else if (isReq) {
GetRequestEvent (c1Control, code, values, terminating);
return;
}
InputResult inputResult = new InputResult {
EventType = EventType.Key,
ConsoleKeyInfo = newConsoleKeyInfo
};
inputResultQueue.Enqueue (inputResult);
}
void ProcessContinuousButtonPressed (MouseFlags mouseFlag, Point pos)
{
GetMouseEvent (MapMouseFlags (mouseFlag), pos);
}
MouseButtonState MapMouseFlags (MouseFlags mouseFlags)
{
MouseButtonState mbs = default;
foreach (var flag in Enum.GetValues (mouseFlags.GetType ())) {
if (mouseFlags.HasFlag ((MouseFlags)flag)) {
switch (flag) {
case MouseFlags.Button1Pressed:
mbs |= MouseButtonState.Button1Pressed;
break;
case MouseFlags.Button1Released:
mbs |= MouseButtonState.Button1Released;
break;
case MouseFlags.Button1Clicked:
mbs |= MouseButtonState.Button1Clicked;
break;
case MouseFlags.Button1DoubleClicked:
mbs |= MouseButtonState.Button1DoubleClicked;
break;
case MouseFlags.Button1TripleClicked:
mbs |= MouseButtonState.Button1TripleClicked;
break;
case MouseFlags.Button2Pressed:
mbs |= MouseButtonState.Button2Pressed;
break;
case MouseFlags.Button2Released:
mbs |= MouseButtonState.Button2Released;
break;
case MouseFlags.Button2Clicked:
mbs |= MouseButtonState.Button2Clicked;
break;
case MouseFlags.Button2DoubleClicked:
mbs |= MouseButtonState.Button2DoubleClicked;
break;
case MouseFlags.Button2TripleClicked:
mbs |= MouseButtonState.Button2TripleClicked;
break;
case MouseFlags.Button3Pressed:
mbs |= MouseButtonState.Button3Pressed;
break;
case MouseFlags.Button3Released:
mbs |= MouseButtonState.Button3Released;
break;
case MouseFlags.Button3Clicked:
mbs |= MouseButtonState.Button3Clicked;
break;
case MouseFlags.Button3DoubleClicked:
mbs |= MouseButtonState.Button3DoubleClicked;
break;
case MouseFlags.Button3TripleClicked:
mbs |= MouseButtonState.Button3TripleClicked;
break;
case MouseFlags.WheeledUp:
mbs |= MouseButtonState.ButtonWheeledUp;
break;
case MouseFlags.WheeledDown:
mbs |= MouseButtonState.ButtonWheeledDown;
break;
case MouseFlags.WheeledLeft:
mbs |= MouseButtonState.ButtonWheeledLeft;
break;
case MouseFlags.WheeledRight:
mbs |= MouseButtonState.ButtonWheeledRight;
break;
case MouseFlags.Button4Pressed:
mbs |= MouseButtonState.Button4Pressed;
break;
case MouseFlags.Button4Released:
mbs |= MouseButtonState.Button4Released;
break;
case MouseFlags.Button4Clicked:
mbs |= MouseButtonState.Button4Clicked;
break;
case MouseFlags.Button4DoubleClicked:
mbs |= MouseButtonState.Button4DoubleClicked;
break;
case MouseFlags.Button4TripleClicked:
mbs |= MouseButtonState.Button4TripleClicked;
break;
case MouseFlags.ButtonShift:
mbs |= MouseButtonState.ButtonShift;
break;
case MouseFlags.ButtonCtrl:
mbs |= MouseButtonState.ButtonCtrl;
break;
case MouseFlags.ButtonAlt:
mbs |= MouseButtonState.ButtonAlt;
break;
case MouseFlags.ReportMousePosition:
mbs |= MouseButtonState.ReportMousePosition;
break;
case MouseFlags.AllEvents:
mbs |= MouseButtonState.AllEvents;
break;
}
}
}
return mbs;
}
Point lastCursorPosition;
void GetRequestEvent (string c1Control, string code, string [] values, string terminating)
{
EventType eventType = new EventType ();
switch (terminating) {
case "R": // Reports cursor position as CSI r ; c R
Point point = new Point {
X = int.Parse (values [1]) - 1,
Y = int.Parse (values [0]) - 1
};
if (lastCursorPosition.Y != point.Y) {
lastCursorPosition = point;
eventType = EventType.WindowPosition;
var winPositionEv = new WindowPositionEvent () {
CursorPosition = point
};
inputResultQueue.Enqueue (new InputResult () {
EventType = eventType,
WindowPositionEvent = winPositionEv
});
} else {
return;
}
break;
default:
SetRequestedEvent (c1Control, code, values, terminating);
break;
}
inputReady.Set ();
}
void SetRequestedEvent (string c1Control, string code, string [] values, string terminating)
{
EventType eventType = EventType.RequestResponse;
var requestRespEv = new RequestResponseEvent () {
ResultTuple = (c1Control, code, values, terminating)
};
inputResultQueue.Enqueue (new InputResult () {
EventType = eventType,
RequestResponseEvent = requestRespEv
});
}
void GetMouseEvent (MouseButtonState buttonState, Point pos)
{
MouseEvent mouseEvent = new MouseEvent () {
Position = pos,
ButtonState = buttonState,
};
inputResultQueue.Enqueue (new InputResult () {
EventType = EventType.Mouse,
MouseEvent = mouseEvent
});
inputReady.Set ();
}
public enum EventType {
Key = 1,
Mouse = 2,
WindowSize = 3,
WindowPosition = 4,
RequestResponse = 5
}
[Flags]
public enum MouseButtonState {
Button1Pressed = 0x1,
Button1Released = 0x2,
Button1Clicked = 0x4,
Button1DoubleClicked = 0x8,
Button1TripleClicked = 0x10,
Button2Pressed = 0x20,
Button2Released = 0x40,
Button2Clicked = 0x80,
Button2DoubleClicked = 0x100,
Button2TripleClicked = 0x200,
Button3Pressed = 0x400,
Button3Released = 0x800,
Button3Clicked = 0x1000,
Button3DoubleClicked = 0x2000,
Button3TripleClicked = 0x4000,
ButtonWheeledUp = 0x8000,
ButtonWheeledDown = 0x10000,
ButtonWheeledLeft = 0x20000,
ButtonWheeledRight = 0x40000,
Button4Pressed = 0x80000,
Button4Released = 0x100000,
Button4Clicked = 0x200000,
Button4DoubleClicked = 0x400000,
Button4TripleClicked = 0x800000,
ButtonShift = 0x1000000,
ButtonCtrl = 0x2000000,
ButtonAlt = 0x4000000,
ReportMousePosition = 0x8000000,
AllEvents = -1
}
public struct MouseEvent {
public Point Position;
public MouseButtonState ButtonState;
}
public struct WindowSizeEvent {
public Size Size;
}
public struct WindowPositionEvent {
public int Top;
public int Left;
public Point CursorPosition;
}
public struct RequestResponseEvent {
public (string c1Control, string code, string [] values, string terminating) ResultTuple;
}
public struct InputResult {
public EventType EventType;
public ConsoleKeyInfo ConsoleKeyInfo;
public MouseEvent MouseEvent;
public WindowSizeEvent WindowSizeEvent;
public WindowPositionEvent WindowPositionEvent;
public RequestResponseEvent RequestResponseEvent;
}
}
internal class NetDriver : ConsoleDriver {
const int COLOR_BLACK = 30;
const int COLOR_RED = 31;
const int COLOR_GREEN = 32;
const int COLOR_YELLOW = 33;
const int COLOR_BLUE = 34;
const int COLOR_MAGENTA = 35;
const int COLOR_CYAN = 36;
const int COLOR_WHITE = 37;
const int COLOR_BRIGHT_BLACK = 90;
const int COLOR_BRIGHT_RED = 91;
const int COLOR_BRIGHT_GREEN = 92;
const int COLOR_BRIGHT_YELLOW = 93;
const int COLOR_BRIGHT_BLUE = 94;
const int COLOR_BRIGHT_MAGENTA = 95;
const int COLOR_BRIGHT_CYAN = 96;
const int COLOR_BRIGHT_WHITE = 97;
int cols, rows, left, top;
public override int Cols => cols;
public override int Rows => rows;
public override int Left => left;
public override int Top => top;
[Obsolete ("This API is deprecated", false)]
public override bool EnableConsoleScrolling { get; set; }
[Obsolete ("This API is deprecated", false)]
public override bool HeightAsBuffer { get; set; }
public NetWinVTConsole NetWinConsole { get; }
public bool IsWinPlatform { get; }
public override IClipboard Clipboard { get; }
public override int [,,] Contents => contents;
public NetDriver ()
{
var p = Environment.OSVersion.Platform;
if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows) {
IsWinPlatform = true;
NetWinConsole = new NetWinVTConsole ();
}
if (IsWinPlatform) {
Clipboard = new WindowsClipboard ();
} else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX)) {
Clipboard = new MacOSXClipboard ();
} else {
if (CursesDriver.Is_WSL_Platform ()) {
Clipboard = new WSLClipboard ();
} else {
Clipboard = new CursesClipboard ();
}
}
}
// The format is rows, columns and 3 values on the last column: Rune, Attribute and Dirty Flag
int [,,] contents;
bool [] dirtyLine;
static bool sync = false;
// Current row, and current col, tracked by Move/AddCh only
int ccol, crow;
public override void Move (int col, int row)
{
ccol = col;
crow = row;
}
public override void AddRune (Rune rune)
{
if (contents.Length != Rows * Cols * 3) {
return;
}
rune = MakePrintable (rune);
var runeWidth = Rune.ColumnWidth (rune);
var validClip = IsValidContent (ccol, crow, Clip);
if (validClip) {
if (runeWidth == 0 && ccol > 0) {
var r = contents [crow, ccol - 1, 0];
var s = new string (new char [] { (char)r, (char)rune });
string sn;
if (!s.IsNormalized ()) {
sn = s.Normalize ();
} else {
sn = s;
}
var c = sn [0];
contents [crow, ccol - 1, 0] = c;
contents [crow, ccol - 1, 1] = CurrentAttribute;
contents [crow, ccol - 1, 2] = 1;
} else {
if (runeWidth < 2 && ccol > 0
&& Rune.ColumnWidth ((char)contents [crow, ccol - 1, 0]) > 1) {
contents [crow, ccol - 1, 0] = (int)(uint)' ';
} else if (runeWidth < 2 && ccol <= Clip.Right - 1
&& Rune.ColumnWidth ((char)contents [crow, ccol, 0]) > 1) {
contents [crow, ccol + 1, 0] = (int)(uint)' ';
contents [crow, ccol + 1, 2] = 1;
}
if (runeWidth > 1 && ccol == Clip.Right - 1) {
contents [crow, ccol, 0] = (int)(uint)' ';
} else {
contents [crow, ccol, 0] = (int)(uint)rune;
}
contents [crow, ccol, 1] = CurrentAttribute;
contents [crow, ccol, 2] = 1;
}
dirtyLine [crow] = true;
}
if (runeWidth < 0 || runeWidth > 0) {
ccol++;
}
if (runeWidth > 1) {
if (validClip && ccol < Clip.Right) {
contents [crow, ccol, 1] = CurrentAttribute;
contents [crow, ccol, 2] = 0;
}
ccol++;
}
if (sync) {
UpdateScreen ();
}
}
public override void AddStr (ustring str)
{
foreach (var rune in str)
AddRune (rune);
}
public override void End ()
{
mainLoop.Dispose ();
if (IsWinPlatform) {
NetWinConsole.Cleanup ();
}
StopReportingMouseMoves ();
Console.ResetColor ();
//Disable alternative screen buffer.
Console.Out.Write ("\x1b[?1049l");
//Set cursor key to cursor.
Console.Out.Write ("\x1b[?25h");
Console.Out.Close ();
}
public override Attribute MakeColor (Color foreground, Color background)
{
return MakeColor ((ConsoleColor)foreground, (ConsoleColor)background);
}
static Attribute MakeColor (ConsoleColor f, ConsoleColor b)
{
// Encode the colors into the int value.
return new Attribute (
value: ((((int)f) & 0xffff) << 16) | (((int)b) & 0xffff),
foreground: (Color)f,
background: (Color)b
);
}
public override void Init (Action terminalResized)
{
TerminalResized = terminalResized;
//Enable alternative screen buffer.
Console.Out.Write ("\x1b[?1049h");
//Set cursor key to application.
Console.Out.Write ("\x1b[?25l");
Console.TreatControlCAsInput = true;
cols = Console.WindowWidth;
rows = Console.WindowHeight;
CurrentAttribute = MakeColor (Color.White, Color.Black);
InitalizeColorSchemes ();
CurrentAttribute = MakeColor (Color.White, Color.Black);
InitalizeColorSchemes ();
ResizeScreen ();
UpdateOffScreen ();
StartReportingMouseMoves ();
}
public override void ResizeScreen ()
{
if (Console.WindowHeight > 0) {
// Not supported on Unix.
if (IsWinPlatform) {
// Can raise an exception while is still resizing.
try {
#pragma warning disable CA1416
Console.CursorTop = 0;
Console.CursorLeft = 0;
Console.WindowTop = 0;
Console.WindowLeft = 0;
if (Console.WindowHeight > Rows) {
Console.SetWindowSize (Cols, Rows);
}
Console.SetBufferSize (Cols, Rows);
#pragma warning restore CA1416
} catch (System.IO.IOException) {
setClip ();
} catch (ArgumentOutOfRangeException) {
setClip ();
}
} else {
Console.Out.Write ($"\x1b[8;{Rows};{Cols}t");
}
}
setClip ();
void setClip ()
{
Clip = new Rect (0, 0, Cols, Rows);
}
}
public override void UpdateOffScreen ()
{
contents = new int [Rows, Cols, 3];
dirtyLine = new bool [Rows];
lock (contents) {
// Can raise an exception while is still resizing.
try {
for (int row = 0; row < rows; row++) {
for (int c = 0; c < cols; c++) {
contents [row, c, 0] = ' ';
contents [row, c, 1] = (ushort)Colors.TopLevel.Normal;
contents [row, c, 2] = 0;
dirtyLine [row] = true;
}
}
} catch (IndexOutOfRangeException) { }
}
}
public override Attribute MakeAttribute (Color fore, Color back)
{
return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
}
public override void Refresh ()
{
UpdateScreen ();
UpdateCursor ();
}
public override void UpdateScreen ()
{
if (winChanging || Console.WindowHeight < 1 || contents.Length != Rows * Cols * 3 || Rows != Console.WindowHeight) {
return;
}
int top = 0;
int left = 0;
int rows = Rows;
int cols = Cols;
System.Text.StringBuilder output = new System.Text.StringBuilder ();
int redrawAttr = -1;
var lastCol = -1;
Console.CursorVisible = false;
for (int row = top; row < rows; row++) {
if (Console.WindowHeight < 1) {
return;
}
if (!dirtyLine [row]) {
continue;
}
if (!SetCursorPosition (0, row)) {
return;
}
dirtyLine [row] = false;
output.Clear ();
for (int col = left; col < cols; col++) {
lastCol = -1;
var outputWidth = 0;
for (; col < cols; col++) {
if (contents [row, col, 2] == 0) {
if (output.Length > 0) {
SetCursorPosition (lastCol, row);
Console.Write (output);
output.Clear ();
lastCol += outputWidth;
outputWidth = 0;
} else if (lastCol == -1) {
lastCol = col;
}
if (lastCol + 1 < cols)
lastCol++;
continue;
}
if (lastCol == -1)
lastCol = col;
var attr = contents [row, col, 1];
if (attr != redrawAttr) {
redrawAttr = attr;
output.Append (WriteAttributes (attr));
}
outputWidth++;
var rune = contents [row, col, 0];
char [] spair;
if (Rune.DecodeSurrogatePair ((uint)rune, out spair)) {
output.Append (spair);
} else {
output.Append ((char)rune);
}
contents [row, col, 2] = 0;
}
}
if (output.Length > 0) {
SetCursorPosition (lastCol, row);
Console.Write (output);
}
}
SetCursorPosition (0, 0);
}
void SetVirtualCursorPosition (int col, int row)
{
Console.Out.Write ($"\x1b[{row + 1};{col + 1}H");
}
System.Text.StringBuilder WriteAttributes (int attr)
{
const string CSI = "\x1b[";
int bg = 0;
int fg = 0;
System.Text.StringBuilder sb = new System.Text.StringBuilder ();
IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
.OfType<ConsoleColor> ()
.Select (s => (int)s);
if (values.Contains (attr & 0xffff)) {
bg = MapColors ((ConsoleColor)(attr & 0xffff), false);
}
if (values.Contains ((attr >> 16) & 0xffff)) {
fg = MapColors ((ConsoleColor)((attr >> 16) & 0xffff));
}
sb.Append ($"{CSI}{bg};{fg}m");
return sb;
}
int MapColors (ConsoleColor color, bool isForeground = true)
{
switch (color) {
case ConsoleColor.Black:
return isForeground ? COLOR_BLACK : COLOR_BLACK + 10;
case ConsoleColor.DarkBlue:
return isForeground ? COLOR_BLUE : COLOR_BLUE + 10;
case ConsoleColor.DarkGreen:
return isForeground ? COLOR_GREEN : COLOR_GREEN + 10;
case ConsoleColor.DarkCyan:
return isForeground ? COLOR_CYAN : COLOR_CYAN + 10;
case ConsoleColor.DarkRed:
return isForeground ? COLOR_RED : COLOR_RED + 10;
case ConsoleColor.DarkMagenta:
return isForeground ? COLOR_MAGENTA : COLOR_MAGENTA + 10;
case ConsoleColor.DarkYellow:
return isForeground ? COLOR_YELLOW : COLOR_YELLOW + 10;
case ConsoleColor.Gray:
return isForeground ? COLOR_WHITE : COLOR_WHITE + 10;
case ConsoleColor.DarkGray:
return isForeground ? COLOR_BRIGHT_BLACK : COLOR_BRIGHT_BLACK + 10;
case ConsoleColor.Blue:
return isForeground ? COLOR_BRIGHT_BLUE : COLOR_BRIGHT_BLUE + 10;
case ConsoleColor.Green:
return isForeground ? COLOR_BRIGHT_GREEN : COLOR_BRIGHT_GREEN + 10;
case ConsoleColor.Cyan:
return isForeground ? COLOR_BRIGHT_CYAN : COLOR_BRIGHT_CYAN + 10;
case ConsoleColor.Red:
return isForeground ? COLOR_BRIGHT_RED : COLOR_BRIGHT_RED + 10;
case ConsoleColor.Magenta:
return isForeground ? COLOR_BRIGHT_MAGENTA : COLOR_BRIGHT_MAGENTA + 10;
case ConsoleColor.Yellow:
return isForeground ? COLOR_BRIGHT_YELLOW : COLOR_BRIGHT_YELLOW + 10;
case ConsoleColor.White:
return isForeground ? COLOR_BRIGHT_WHITE : COLOR_BRIGHT_WHITE + 10;
}
return 0;
}
bool SetCursorPosition (int col, int row)
{
if (IsWinPlatform) {
// Could happens that the windows is still resizing and the col is bigger than Console.WindowWidth.
try {
Console.SetCursorPosition (col, row);
return true;
} catch (Exception) {
return false;
}
} else {
SetVirtualCursorPosition (col, row);
return true;
}
}
private void SetWindowPosition (int col, int row)
{
top = Console.WindowTop;
left = Console.WindowLeft;
}
private bool EnsureBufferSize ()
{
#pragma warning disable CA1416
if (IsWinPlatform && Console.BufferHeight < Rows) {
try {