-
Notifications
You must be signed in to change notification settings - Fork 695
/
CursesDriver.cs
1286 lines (1153 loc) · 39.3 KB
/
CursesDriver.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
//
// Driver.cs: Curses-based Driver
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using NStack;
using Unix.Terminal;
namespace Terminal.Gui {
/// <summary>
/// This is the Curses driver for the gui.cs/Terminal framework.
/// </summary>
internal class CursesDriver : ConsoleDriver {
public override int Cols => Curses.Cols;
public override int Rows => Curses.Lines;
public override int Left => 0;
public override int Top => 0;
[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 override IClipboard Clipboard { get => clipboard; }
CursorVisibility? initialCursorVisibility = null;
CursorVisibility? currentCursorVisibility = null;
IClipboard clipboard;
int [,,] contents;
public override int [,,] Contents => contents;
// Current row, and current col, tracked by Move/AddRune only
int ccol, crow;
bool needMove;
public override void Move (int col, int row)
{
ccol = col;
crow = row;
if (Clip.Contains (col, row)) {
Curses.move (row, col);
needMove = false;
} else {
Curses.move (Clip.Y, Clip.X);
needMove = true;
}
}
static bool sync = false;
public override void AddRune (Rune rune)
{
rune = MakePrintable (rune);
var runeWidth = Rune.ColumnWidth (rune);
var validClip = IsValidContent (ccol, crow, Clip);
if (validClip) {
if (needMove) {
Curses.move (crow, ccol);
needMove = false;
}
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];
Curses.mvaddch (crow, ccol - 1, (int)(uint)c);
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) {
var curAtttib = CurrentAttribute;
Curses.attrset (contents [crow, ccol - 1, 1]);
Curses.mvaddch (crow, ccol - 1, (int)(uint)' ');
contents [crow, ccol - 1, 0] = (int)(uint)' ';
Curses.move (crow, ccol);
Curses.attrset (curAtttib);
} else if (runeWidth < 2 && ccol <= Clip.Right - 1
&& Rune.ColumnWidth ((char)contents [crow, ccol, 0]) > 1) {
var curAtttib = CurrentAttribute;
Curses.attrset (contents [crow, ccol + 1, 1]);
Curses.mvaddch (crow, ccol + 1, (int)(uint)' ');
contents [crow, ccol + 1, 0] = (int)(uint)' ';
Curses.move (crow, ccol);
Curses.attrset (curAtttib);
}
if (runeWidth > 1 && ccol == Clip.Right - 1) {
Curses.addch ((int)(uint)' ');
contents [crow, ccol, 0] = (int)(uint)' ';
} else {
Curses.addch ((int)(uint)rune);
contents [crow, ccol, 0] = (int)(uint)rune;
}
contents [crow, ccol, 1] = CurrentAttribute;
contents [crow, ccol, 2] = 1;
}
} else {
needMove = 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)
{
// TODO; optimize this to determine if the str fits in the clip region, and if so, use Curses.addstr directly
foreach (var rune in str)
AddRune (rune);
}
public override void Refresh ()
{
Curses.raw ();
Curses.noecho ();
Curses.refresh ();
ProcessWinChange ();
}
private void ProcessWinChange ()
{
if (Curses.CheckWinChange ()) {
ResizeScreen ();
UpdateOffScreen ();
TerminalResized?.Invoke ();
}
}
public override void UpdateCursor () => Refresh ();
public override void End ()
{
StopReportingMouseMoves ();
SetCursorVisibility (CursorVisibility.Default);
// throws away any typeahead that has been typed by
// the user and has not yet been read by the program.
Curses.flushinp ();
Curses.endwin ();
}
public override void UpdateScreen () => window.redrawwin ();
public override void SetAttribute (Attribute c)
{
base.SetAttribute (c);
Curses.attrset (CurrentAttribute);
}
public Curses.Window window;
//static short last_color_pair = 16;
/// <summary>
/// Creates a curses color from the provided foreground and background colors
/// </summary>
/// <param name="foreground">Contains the curses attributes for the foreground (color, plus any attributes)</param>
/// <param name="background">Contains the curses attributes for the background (color, plus any attributes)</param>
/// <returns></returns>
public static Attribute MakeColor (short foreground, short background)
{
var v = (short)((int)foreground | background << 4);
//Curses.InitColorPair (++last_color_pair, foreground, background);
Curses.InitColorPair (v, foreground, background);
return new Attribute (
//value: Curses.ColorPair (last_color_pair),
value: Curses.ColorPair (v),
//foreground: (Color)foreground,
foreground: MapCursesColor (foreground),
//background: (Color)background);
background: MapCursesColor (background));
}
public override Attribute MakeColor (Color fore, Color back)
{
return MakeColor ((short)MapColor (fore), (short)MapColor (back));
}
int [,] colorPairs = new int [16, 16];
public override void SetColors (ConsoleColor foreground, ConsoleColor background)
{
// BUGBUG: This code is never called ?? See Issue #2300
int f = (short)foreground;
int b = (short)background;
var v = colorPairs [f, b];
if ((v & 0x10000) == 0) {
b &= 0x7;
bool bold = (f & 0x8) != 0;
f &= 0x7;
v = MakeColor ((short)f, (short)b) | (bold ? Curses.A_BOLD : 0);
colorPairs [(int)foreground, (int)background] = v | 0x1000;
}
SetAttribute (v & 0xffff);
}
Dictionary<int, int> rawPairs = new Dictionary<int, int> ();
public override void SetColors (short foreColorId, short backgroundColorId)
{
// BUGBUG: This code is never called ?? See Issue #2300
int key = ((ushort)foreColorId << 16) | (ushort)backgroundColorId;
if (!rawPairs.TryGetValue (key, out var v)) {
v = MakeColor (foreColorId, backgroundColorId);
rawPairs [key] = v;
}
SetAttribute (v);
}
static Key MapCursesKey (int cursesKey)
{
switch (cursesKey) {
case Curses.KeyF1: return Key.F1;
case Curses.KeyF2: return Key.F2;
case Curses.KeyF3: return Key.F3;
case Curses.KeyF4: return Key.F4;
case Curses.KeyF5: return Key.F5;
case Curses.KeyF6: return Key.F6;
case Curses.KeyF7: return Key.F7;
case Curses.KeyF8: return Key.F8;
case Curses.KeyF9: return Key.F9;
case Curses.KeyF10: return Key.F10;
case Curses.KeyF11: return Key.F11;
case Curses.KeyF12: return Key.F12;
case Curses.KeyUp: return Key.CursorUp;
case Curses.KeyDown: return Key.CursorDown;
case Curses.KeyLeft: return Key.CursorLeft;
case Curses.KeyRight: return Key.CursorRight;
case Curses.KeyHome: return Key.Home;
case Curses.KeyEnd: return Key.End;
case Curses.KeyNPage: return Key.PageDown;
case Curses.KeyPPage: return Key.PageUp;
case Curses.KeyDeleteChar: return Key.DeleteChar;
case Curses.KeyInsertChar: return Key.InsertChar;
case Curses.KeyTab: return Key.Tab;
case Curses.KeyBackTab: return Key.BackTab;
case Curses.KeyBackspace: return Key.Backspace;
case Curses.ShiftKeyUp: return Key.CursorUp | Key.ShiftMask;
case Curses.ShiftKeyDown: return Key.CursorDown | Key.ShiftMask;
case Curses.ShiftKeyLeft: return Key.CursorLeft | Key.ShiftMask;
case Curses.ShiftKeyRight: return Key.CursorRight | Key.ShiftMask;
case Curses.ShiftKeyHome: return Key.Home | Key.ShiftMask;
case Curses.ShiftKeyEnd: return Key.End | Key.ShiftMask;
case Curses.ShiftKeyNPage: return Key.PageDown | Key.ShiftMask;
case Curses.ShiftKeyPPage: return Key.PageUp | Key.ShiftMask;
case Curses.AltKeyUp: return Key.CursorUp | Key.AltMask;
case Curses.AltKeyDown: return Key.CursorDown | Key.AltMask;
case Curses.AltKeyLeft: return Key.CursorLeft | Key.AltMask;
case Curses.AltKeyRight: return Key.CursorRight | Key.AltMask;
case Curses.AltKeyHome: return Key.Home | Key.AltMask;
case Curses.AltKeyEnd: return Key.End | Key.AltMask;
case Curses.AltKeyNPage: return Key.PageDown | Key.AltMask;
case Curses.AltKeyPPage: return Key.PageUp | Key.AltMask;
case Curses.CtrlKeyUp: return Key.CursorUp | Key.CtrlMask;
case Curses.CtrlKeyDown: return Key.CursorDown | Key.CtrlMask;
case Curses.CtrlKeyLeft: return Key.CursorLeft | Key.CtrlMask;
case Curses.CtrlKeyRight: return Key.CursorRight | Key.CtrlMask;
case Curses.CtrlKeyHome: return Key.Home | Key.CtrlMask;
case Curses.CtrlKeyEnd: return Key.End | Key.CtrlMask;
case Curses.CtrlKeyNPage: return Key.PageDown | Key.CtrlMask;
case Curses.CtrlKeyPPage: return Key.PageUp | Key.CtrlMask;
case Curses.ShiftCtrlKeyUp: return Key.CursorUp | Key.ShiftMask | Key.CtrlMask;
case Curses.ShiftCtrlKeyDown: return Key.CursorDown | Key.ShiftMask | Key.CtrlMask;
case Curses.ShiftCtrlKeyLeft: return Key.CursorLeft | Key.ShiftMask | Key.CtrlMask;
case Curses.ShiftCtrlKeyRight: return Key.CursorRight | Key.ShiftMask | Key.CtrlMask;
case Curses.ShiftCtrlKeyHome: return Key.Home | Key.ShiftMask | Key.CtrlMask;
case Curses.ShiftCtrlKeyEnd: return Key.End | Key.ShiftMask | Key.CtrlMask;
case Curses.ShiftCtrlKeyNPage: return Key.PageDown | Key.ShiftMask | Key.CtrlMask;
case Curses.ShiftCtrlKeyPPage: return Key.PageUp | Key.ShiftMask | Key.CtrlMask;
case Curses.ShiftAltKeyUp: return Key.CursorUp | Key.ShiftMask | Key.AltMask;
case Curses.ShiftAltKeyDown: return Key.CursorDown | Key.ShiftMask | Key.AltMask;
case Curses.ShiftAltKeyLeft: return Key.CursorLeft | Key.ShiftMask | Key.AltMask;
case Curses.ShiftAltKeyRight: return Key.CursorRight | Key.ShiftMask | Key.AltMask;
case Curses.ShiftAltKeyNPage: return Key.PageDown | Key.ShiftMask | Key.AltMask;
case Curses.ShiftAltKeyPPage: return Key.PageUp | Key.ShiftMask | Key.AltMask;
case Curses.ShiftAltKeyHome: return Key.Home | Key.ShiftMask | Key.AltMask;
case Curses.ShiftAltKeyEnd: return Key.End | Key.ShiftMask | Key.AltMask;
case Curses.AltCtrlKeyNPage: return Key.PageDown | Key.AltMask | Key.CtrlMask;
case Curses.AltCtrlKeyPPage: return Key.PageUp | Key.AltMask | Key.CtrlMask;
case Curses.AltCtrlKeyHome: return Key.Home | Key.AltMask | Key.CtrlMask;
case Curses.AltCtrlKeyEnd: return Key.End | Key.AltMask | Key.CtrlMask;
default: return Key.Unknown;
}
}
KeyModifiers keyModifiers;
KeyModifiers MapKeyModifiers (Key key)
{
if (keyModifiers == null)
keyModifiers = new KeyModifiers ();
if (!keyModifiers.Shift && (key & Key.ShiftMask) != 0)
keyModifiers.Shift = true;
if (!keyModifiers.Alt && (key & Key.AltMask) != 0)
keyModifiers.Alt = true;
if (!keyModifiers.Ctrl && (key & Key.CtrlMask) != 0)
keyModifiers.Ctrl = true;
return keyModifiers;
}
void ProcessInput ()
{
int wch;
var code = Curses.get_wch (out wch);
//System.Diagnostics.Debug.WriteLine ($"code: {code}; wch: {wch}");
if (code == Curses.ERR)
return;
keyModifiers = new KeyModifiers ();
Key k = Key.Null;
if (code == Curses.KEY_CODE_YES) {
var lastWch = wch;
while (code == Curses.KEY_CODE_YES && wch == Curses.KeyResize) {
ProcessWinChange ();
code = Curses.get_wch (out wch);
}
if (wch == 0) {
return;
}
if (wch == Curses.KeyMouse) {
int wch2 = wch;
while (wch2 == Curses.KeyMouse) {
KeyEvent key = null;
ConsoleKeyInfo [] cki = new ConsoleKeyInfo [] {
new ConsoleKeyInfo ((char)Key.Esc, 0, false, false, false),
new ConsoleKeyInfo ('[', 0, false, false, false),
new ConsoleKeyInfo ('<', 0, false, false, false)
};
code = 0;
GetEscSeq (ref code, ref k, ref wch2, ref key, ref cki);
}
return;
}
k = MapCursesKey (wch);
if (wch >= 277 && wch <= 288) { // Shift+(F1 - F12)
wch -= 12;
k = Key.ShiftMask | MapCursesKey (wch);
} else if (wch >= 289 && wch <= 300) { // Ctrl+(F1 - F12)
wch -= 24;
k = Key.CtrlMask | MapCursesKey (wch);
} else if (wch >= 301 && wch <= 312) { // Ctrl+Shift+(F1 - F12)
wch -= 36;
k = Key.CtrlMask | Key.ShiftMask | MapCursesKey (wch);
} else if (wch >= 313 && wch <= 324) { // Alt+(F1 - F12)
wch -= 48;
k = Key.AltMask | MapCursesKey (wch);
} else if (wch >= 325 && wch <= 327) { // Shift+Alt+(F1 - F3)
wch -= 60;
k = Key.ShiftMask | Key.AltMask | MapCursesKey (wch);
} else {
code = Curses.get_wch (out wch);
if (code == 0) {
switch (wch) {
// Shift code.
case 16:
keyModifiers.Shift = true;
break;
default:
if (lastWch == Curses.KeyResize && wch == 91) {
// Returns this keys to the std input which is a CSI (\x1b[).
Curses.ungetch (91); // [
Curses.ungetch (27); // Esc
return;
} else {
throw new Exception ();
}
}
}
}
keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
keyUpHandler (new KeyEvent (k, MapKeyModifiers (k)));
return;
}
// Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
if (wch == 27) {
code = Curses.get_wch (out int wch2);
if (code == Curses.KEY_CODE_YES) {
k = Key.AltMask | MapCursesKey (wch);
}
if (code == 0) {
KeyEvent key = null;
// The ESC-number handling, debatable.
// Simulates the AltMask itself by pressing Alt + Space.
if (wch2 == (int)Key.Space) {
k = Key.AltMask;
} else if (wch2 - (int)Key.Space >= (uint)Key.A && wch2 - (int)Key.Space <= (uint)Key.Z) {
k = (Key)((uint)Key.AltMask + (wch2 - (int)Key.Space));
} else if (wch2 >= (uint)Key.A - 64 && wch2 <= (uint)Key.Z - 64) {
k = (Key)((uint)(Key.AltMask | Key.CtrlMask) + (wch2 + 64));
} else if (wch2 >= (uint)Key.D0 && wch2 <= (uint)Key.D9) {
k = (Key)((uint)Key.AltMask + (uint)Key.D0 + (wch2 - (uint)Key.D0));
} else if (wch2 == Curses.KeyCSI) {
ConsoleKeyInfo [] cki = new ConsoleKeyInfo [] {
new ConsoleKeyInfo ((char)Key.Esc, 0, false, false, false),
new ConsoleKeyInfo ('[', 0, false, false, false)
};
GetEscSeq (ref code, ref k, ref wch2, ref key, ref cki);
return;
} else {
// Unfortunately there are no way to differentiate Ctrl+Alt+alfa and Ctrl+Shift+Alt+alfa.
if (((Key)wch2 & Key.CtrlMask) != 0) {
keyModifiers.Ctrl = true;
}
if (wch2 == 0) {
k = Key.CtrlMask | Key.AltMask | Key.Space;
} else if (wch >= (uint)Key.A && wch <= (uint)Key.Z) {
keyModifiers.Shift = true;
keyModifiers.Alt = true;
} else if (wch2 == Curses.KeySS3) {
while (code > -1) {
code = Curses.get_wch (out wch2);
if (code == 0) {
switch (wch2) {
case 16:
keyModifiers.Shift = true;
break;
case 108:
k = (Key)'+';
break;
case 109:
k = (Key)'-';
break;
case 112:
k = Key.InsertChar;
break;
case 113:
k = Key.End;
break;
case 114:
k = Key.CursorDown;
break;
case 115:
k = Key.PageDown;
break;
case 116:
k = Key.CursorLeft;
break;
case 117:
k = Key.Clear;
break;
case 118:
k = Key.CursorRight;
break;
case 119:
k = Key.Home;
break;
case 120:
k = Key.CursorUp;
break;
case 121:
k = Key.PageUp;
break;
default:
k = (Key)wch2;
break;
}
}
}
} else if (wch2 < 256) {
k = (Key)wch2;
keyModifiers.Alt = true;
} else {
k = (Key)((uint)(Key.AltMask | Key.CtrlMask) + wch2);
}
}
key = new KeyEvent (k, MapKeyModifiers (k));
keyDownHandler (key);
keyHandler (key);
} else {
k = Key.Esc;
keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
}
} else if (wch == Curses.KeyTab) {
k = MapCursesKey (wch);
keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
} else {
// Unfortunately there are no way to differentiate Ctrl+alfa and Ctrl+Shift+alfa.
k = (Key)wch;
if (wch == 0) {
k = Key.CtrlMask | Key.Space;
} else if (wch >= (uint)Key.A - 64 && wch <= (uint)Key.Z - 64) {
if ((Key)(wch + 64) != Key.J) {
k = Key.CtrlMask | (Key)(wch + 64);
}
} else if (wch >= (uint)Key.A && wch <= (uint)Key.Z) {
keyModifiers.Shift = true;
}
keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
keyUpHandler (new KeyEvent (k, MapKeyModifiers (k)));
}
// Cause OnKeyUp and OnKeyPressed. Note that the special handling for ESC above
// will not impact KeyUp.
// This is causing ESC firing even if another keystroke was handled.
//if (wch == Curses.KeyTab) {
// keyUpHandler (new KeyEvent (MapCursesKey (wch), keyModifiers));
//} else {
// keyUpHandler (new KeyEvent ((Key)wch, keyModifiers));
//}
}
void GetEscSeq (ref int code, ref Key k, ref int wch2, ref KeyEvent key, ref ConsoleKeyInfo [] cki)
{
ConsoleKey ck = 0;
ConsoleModifiers mod = 0;
while (code == 0) {
code = Curses.get_wch (out wch2);
var consoleKeyInfo = new ConsoleKeyInfo ((char)wch2, 0, false, false, false);
if (wch2 == 0 || wch2 == 27 || wch2 == Curses.KeyMouse) {
EscSeqUtils.DecodeEscSeq (null, ref consoleKeyInfo, ref ck, cki, ref mod, out _, out _, out _, out _, out bool isKeyMouse, out List<MouseFlags> mouseFlags, out Point pos, out _, ProcessContinuousButtonPressed);
if (isKeyMouse) {
foreach (var mf in mouseFlags) {
ProcessMouseEvent (mf, pos);
}
cki = null;
if (wch2 == 27) {
cki = EscSeqUtils.ResizeArray (new ConsoleKeyInfo ((char)Key.Esc, 0,
false, false, false), cki);
}
} else {
k = ConsoleKeyMapping.MapConsoleKeyToKey (consoleKeyInfo.Key, out _);
k = ConsoleKeyMapping.MapKeyModifiers (consoleKeyInfo, k);
key = new KeyEvent (k, MapKeyModifiers (k));
keyDownHandler (key);
keyHandler (key);
}
} else {
cki = EscSeqUtils.ResizeArray (consoleKeyInfo, cki);
}
}
}
MouseFlags lastMouseFlags;
void ProcessMouseEvent (MouseFlags mouseFlag, Point pos)
{
bool WasButtonReleased (MouseFlags flag)
{
return flag.HasFlag (MouseFlags.Button1Released) ||
flag.HasFlag (MouseFlags.Button2Released) ||
flag.HasFlag (MouseFlags.Button3Released) ||
flag.HasFlag (MouseFlags.Button4Released);
}
bool IsButtonNotPressed (MouseFlags flag)
{
return !flag.HasFlag (MouseFlags.Button1Pressed) &&
!flag.HasFlag (MouseFlags.Button2Pressed) &&
!flag.HasFlag (MouseFlags.Button3Pressed) &&
!flag.HasFlag (MouseFlags.Button4Pressed);
}
bool IsButtonClickedOrDoubleClicked (MouseFlags flag)
{
return flag.HasFlag (MouseFlags.Button1Clicked) ||
flag.HasFlag (MouseFlags.Button2Clicked) ||
flag.HasFlag (MouseFlags.Button3Clicked) ||
flag.HasFlag (MouseFlags.Button4Clicked) ||
flag.HasFlag (MouseFlags.Button1DoubleClicked) ||
flag.HasFlag (MouseFlags.Button2DoubleClicked) ||
flag.HasFlag (MouseFlags.Button3DoubleClicked) ||
flag.HasFlag (MouseFlags.Button4DoubleClicked);
}
if ((WasButtonReleased (mouseFlag) && IsButtonNotPressed (lastMouseFlags)) ||
(IsButtonClickedOrDoubleClicked (mouseFlag) && lastMouseFlags == 0)) {
return;
}
lastMouseFlags = mouseFlag;
var me = new MouseEvent () {
Flags = mouseFlag,
X = pos.X,
Y = pos.Y
};
mouseHandler (me);
}
void ProcessContinuousButtonPressed (MouseFlags mouseFlag, Point pos)
{
ProcessMouseEvent (mouseFlag, pos);
}
Action<KeyEvent> keyHandler;
Action<KeyEvent> keyDownHandler;
Action<KeyEvent> keyUpHandler;
Action<MouseEvent> mouseHandler;
public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
{
// Note: Curses doesn't support keydown/up events and thus any passed keyDown/UpHandlers will never be called
this.keyHandler = keyHandler;
this.keyDownHandler = keyDownHandler;
this.keyUpHandler = keyUpHandler;
this.mouseHandler = mouseHandler;
var mLoop = mainLoop.Driver as UnixMainLoop;
mLoop.AddWatch (0, UnixMainLoop.Condition.PollIn, x => {
ProcessInput ();
return true;
});
mLoop.WinChanged += () => ProcessWinChange ();
}
public override void Init (Action terminalResized)
{
if (window != null)
return;
try {
window = Curses.initscr ();
Curses.set_escdelay (10);
Curses.nodelay (window.Handle, true);
} catch (Exception e) {
throw new Exception ($"Curses failed to initialize, the exception is: {e.Message}");
}
// Ensures that all procedures are performed at some previous closing.
Curses.doupdate ();
//
// We are setting Invisible as default so we could ignore XTerm DECSUSR setting
//
switch (Curses.curs_set (0)) {
case 0:
currentCursorVisibility = initialCursorVisibility = CursorVisibility.Invisible;
break;
case 1:
currentCursorVisibility = initialCursorVisibility = CursorVisibility.Underline;
Curses.curs_set (1);
break;
case 2:
currentCursorVisibility = initialCursorVisibility = CursorVisibility.Box;
Curses.curs_set (2);
break;
default:
currentCursorVisibility = initialCursorVisibility = null;
break;
}
if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX)) {
clipboard = new MacOSXClipboard ();
} else {
if (Is_WSL_Platform ()) {
clipboard = new WSLClipboard ();
} else {
clipboard = new CursesClipboard ();
}
}
Curses.raw ();
Curses.noecho ();
Curses.Window.Standard.keypad (true);
TerminalResized = terminalResized;
StartReportingMouseMoves ();
CurrentAttribute = MakeColor (Color.White, Color.Black);
if (Curses.HasColors) {
Curses.StartColor ();
Curses.UseDefaultColors ();
InitalizeColorSchemes ();
} else {
InitalizeColorSchemes (false);
// BUGBUG: This is a hack to make the colors work on the Mac?
// The new Theme support overwrites these colors, so this is not needed?
Colors.TopLevel.Normal = Curses.COLOR_GREEN;
Colors.TopLevel.Focus = Curses.COLOR_WHITE;
Colors.TopLevel.HotNormal = Curses.COLOR_YELLOW;
Colors.TopLevel.HotFocus = Curses.COLOR_YELLOW;
Colors.TopLevel.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
Colors.Base.Normal = Curses.A_NORMAL;
Colors.Base.Focus = Curses.A_REVERSE;
Colors.Base.HotNormal = Curses.A_BOLD;
Colors.Base.HotFocus = Curses.A_BOLD | Curses.A_REVERSE;
Colors.Base.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
Colors.Menu.Normal = Curses.A_REVERSE;
Colors.Menu.Focus = Curses.A_NORMAL;
Colors.Menu.HotNormal = Curses.A_BOLD;
Colors.Menu.HotFocus = Curses.A_NORMAL;
Colors.Menu.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
Colors.Dialog.Normal = Curses.A_REVERSE;
Colors.Dialog.Focus = Curses.A_NORMAL;
Colors.Dialog.HotNormal = Curses.A_BOLD;
Colors.Dialog.HotFocus = Curses.A_NORMAL;
Colors.Dialog.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
Colors.Error.Normal = Curses.A_BOLD;
Colors.Error.Focus = Curses.A_BOLD | Curses.A_REVERSE;
Colors.Error.HotNormal = Curses.A_BOLD | Curses.A_REVERSE;
Colors.Error.HotFocus = Curses.A_REVERSE;
Colors.Error.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
}
ResizeScreen ();
UpdateOffScreen ();
}
public override void ResizeScreen ()
{
Clip = new Rect (0, 0, Cols, Rows);
}
public override void UpdateOffScreen ()
{
contents = new int [Rows, Cols, 3];
for (int row = 0; row < Rows; row++) {
for (int col = 0; col < Cols; col++) {
Curses.move (row, col);
Curses.attrset (Colors.TopLevel.Normal);
Curses.addch ((int)(uint)' ');
contents [row, col, 0] = ' ';
contents [row, col, 1] = Colors.TopLevel.Normal;
contents [row, col, 2] = 0;
}
}
}
public static bool Is_WSL_Platform ()
{
// xclip does not work on WSL, so we need to use the Windows clipboard vis Powershell
//if (new CursesClipboard ().IsSupported) {
// // If xclip is installed on Linux under WSL, this will return true.
// return false;
//}
var (exitCode, result) = ClipboardProcessRunner.Bash ("uname -a", waitForOutput: true);
if (exitCode == 0 && result.Contains ("microsoft") && result.Contains ("WSL")) {
return true;
}
return false;
}
static int MapColor (Color color)
{
switch (color) {
case Color.Black:
return Curses.COLOR_BLACK;
case Color.Blue:
return Curses.COLOR_BLUE;
case Color.Green:
return Curses.COLOR_GREEN;
case Color.Cyan:
return Curses.COLOR_CYAN;
case Color.Red:
return Curses.COLOR_RED;
case Color.Magenta:
return Curses.COLOR_MAGENTA;
case Color.Brown:
return Curses.COLOR_YELLOW;
case Color.Gray:
return Curses.COLOR_WHITE;
case Color.DarkGray:
//return Curses.COLOR_BLACK | Curses.A_BOLD;
return Curses.COLOR_GRAY;
case Color.BrightBlue:
return Curses.COLOR_BLUE | Curses.A_BOLD | Curses.COLOR_GRAY;
case Color.BrightGreen:
return Curses.COLOR_GREEN | Curses.A_BOLD | Curses.COLOR_GRAY;
case Color.BrightCyan:
return Curses.COLOR_CYAN | Curses.A_BOLD | Curses.COLOR_GRAY;
case Color.BrightRed:
return Curses.COLOR_RED | Curses.A_BOLD | Curses.COLOR_GRAY;
case Color.BrightMagenta:
return Curses.COLOR_MAGENTA | Curses.A_BOLD | Curses.COLOR_GRAY;
case Color.BrightYellow:
return Curses.COLOR_YELLOW | Curses.A_BOLD | Curses.COLOR_GRAY;
case Color.White:
return Curses.COLOR_WHITE | Curses.A_BOLD | Curses.COLOR_GRAY;
}
throw new ArgumentException ("Invalid color code");
}
static Color MapCursesColor (int color)
{
switch (color) {
case Curses.COLOR_BLACK:
return Color.Black;
case Curses.COLOR_BLUE:
return Color.Blue;
case Curses.COLOR_GREEN:
return Color.Green;
case Curses.COLOR_CYAN:
return Color.Cyan;
case Curses.COLOR_RED:
return Color.Red;
case Curses.COLOR_MAGENTA:
return Color.Magenta;
case Curses.COLOR_YELLOW:
return Color.Brown;
case Curses.COLOR_WHITE:
return Color.Gray;
case Curses.COLOR_GRAY:
return Color.DarkGray;
case Curses.COLOR_BLUE | Curses.COLOR_GRAY:
return Color.BrightBlue;
case Curses.COLOR_GREEN | Curses.COLOR_GRAY:
return Color.BrightGreen;
case Curses.COLOR_CYAN | Curses.COLOR_GRAY:
return Color.BrightCyan;
case Curses.COLOR_RED | Curses.COLOR_GRAY:
return Color.BrightRed;
case Curses.COLOR_MAGENTA | Curses.COLOR_GRAY:
return Color.BrightMagenta;
case Curses.COLOR_YELLOW | Curses.COLOR_GRAY:
return Color.BrightYellow;
case Curses.COLOR_WHITE | Curses.COLOR_GRAY:
return Color.White;
}
throw new ArgumentException ("Invalid curses color code");
}
public override Attribute MakeAttribute (Color fore, Color back)
{
var f = MapColor (fore);
//return MakeColor ((short)(f & 0xffff), (short)MapColor (back)) | ((f & Curses.A_BOLD) != 0 ? Curses.A_BOLD : 0);
return MakeColor ((short)(f & 0xffff), (short)MapColor (back));
}
public override void Suspend ()
{
StopReportingMouseMoves ();
Platform.Suspend ();
Curses.Window.Standard.redrawwin ();
Curses.refresh ();
StartReportingMouseMoves ();
}
public override void StartReportingMouseMoves ()
{
Console.Out.Write (EscSeqUtils.EnableMouseEvents);
}
public override void StopReportingMouseMoves ()
{
Console.Out.Write (EscSeqUtils.DisableMouseEvents);
}
//int lastMouseInterval;
//bool mouseGrabbed;
public override void UncookMouse ()
{
//if (mouseGrabbed)
// return;
//lastMouseInterval = Curses.mouseinterval (0);
//mouseGrabbed = true;
}
public override void CookMouse ()
{
//mouseGrabbed = false;
//Curses.mouseinterval (lastMouseInterval);
}
/// <inheritdoc/>
public override bool GetCursorVisibility (out CursorVisibility visibility)
{
visibility = CursorVisibility.Invisible;
if (!currentCursorVisibility.HasValue)
return false;
visibility = currentCursorVisibility.Value;
return true;
}
/// <inheritdoc/>
public override bool SetCursorVisibility (CursorVisibility visibility)
{
if (initialCursorVisibility.HasValue == false)
return false;
Curses.curs_set (((int)visibility >> 16) & 0x000000FF);
if (visibility != CursorVisibility.Invisible) {
Console.Out.Write ("\x1b[{0} q", ((int)visibility >> 24) & 0xFF);
}
currentCursorVisibility = visibility;
return true;
}
/// <inheritdoc/>
public override bool EnsureCursorVisibility ()
{
return false;
}
public override void SendKeys (char keyChar, ConsoleKey consoleKey, bool shift, bool alt, bool control)
{
Key key;
if (consoleKey == ConsoleKey.Packet) {
ConsoleModifiers mod = new ConsoleModifiers ();
if (shift) {
mod |= ConsoleModifiers.Shift;
}
if (alt) {
mod |= ConsoleModifiers.Alt;
}
if (control) {
mod |= ConsoleModifiers.Control;
}
var kchar = ConsoleKeyMapping.GetKeyCharFromConsoleKey (keyChar, mod, out uint ckey, out _);
key = ConsoleKeyMapping.MapConsoleKeyToKey ((ConsoleKey)ckey, out bool mappable);
if (mappable) {
key = (Key)kchar;
}
} else {
key = (Key)keyChar;
}
KeyModifiers km = new KeyModifiers ();
if (shift) {
if (keyChar == 0) {
key |= Key.ShiftMask;
}
km.Shift = shift;
}
if (alt) {
key |= Key.AltMask;
km.Alt = alt;
}
if (control) {
key |= Key.CtrlMask;
km.Ctrl = control;
}
keyDownHandler (new KeyEvent (key, km));
keyHandler (new KeyEvent (key, km));
keyUpHandler (new KeyEvent (key, km));
}
public override bool GetColors (int value, out Color foreground, out Color background)
{
bool hasColor = false;
foreground = default;
background = default;
int back = -1;
IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
.OfType<ConsoleColor> ()
.Select (s => (int)s);
if (values.Contains ((value >> 12) & 0xffff)) {
hasColor = true;
back = (value >> 12) & 0xffff;
background = MapCursesColor (back);
}
if (values.Contains ((value - (back << 12)) >> 8)) {
hasColor = true;
foreground = MapCursesColor ((value - (back << 12)) >> 8);
}
return hasColor;
}