-
Notifications
You must be signed in to change notification settings - Fork 704
/
Copy pathWindowsDriver.cs
2108 lines (1795 loc) · 62.4 KB
/
WindowsDriver.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
//
// WindowsDriver.cs: Windows specific driver
//
using NStack;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace Terminal.Gui {
internal class WindowsConsole {
public const int STD_OUTPUT_HANDLE = -11;
public const int STD_INPUT_HANDLE = -10;
public const int STD_ERROR_HANDLE = -12;
internal IntPtr InputHandle, OutputHandle;
IntPtr ScreenBuffer;
readonly uint originalConsoleMode;
CursorVisibility? initialCursorVisibility = null;
CursorVisibility? currentCursorVisibility = null;
CursorVisibility? pendingCursorVisibility = null;
public WindowsConsole ()
{
InputHandle = GetStdHandle (STD_INPUT_HANDLE);
OutputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
originalConsoleMode = ConsoleMode;
var newConsoleMode = originalConsoleMode;
newConsoleMode |= (uint)(ConsoleModes.EnableMouseInput | ConsoleModes.EnableExtendedFlags);
newConsoleMode &= ~(uint)ConsoleModes.EnableQuickEditMode;
newConsoleMode &= ~(uint)ConsoleModes.EnableProcessedInput;
ConsoleMode = newConsoleMode;
}
public CharInfo [] OriginalStdOutChars;
public bool WriteToConsole (Size size, CharInfo [] charInfoBuffer, Coord coords, SmallRect window)
{
if (ScreenBuffer == IntPtr.Zero) {
ReadFromConsoleOutput (size, coords, ref window);
}
return WriteConsoleOutput (ScreenBuffer, charInfoBuffer, coords, new Coord () { X = window.Left, Y = window.Top }, ref window);
}
public void ReadFromConsoleOutput (Size size, Coord coords, ref SmallRect window)
{
ScreenBuffer = CreateConsoleScreenBuffer (
DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
ShareMode.FileShareRead | ShareMode.FileShareWrite,
IntPtr.Zero,
1,
IntPtr.Zero
);
if (ScreenBuffer == INVALID_HANDLE_VALUE) {
var err = Marshal.GetLastWin32Error ();
if (err != 0)
throw new System.ComponentModel.Win32Exception (err);
}
if (!initialCursorVisibility.HasValue && GetCursorVisibility (out CursorVisibility visibility)) {
initialCursorVisibility = visibility;
}
if (!SetConsoleActiveScreenBuffer (ScreenBuffer)) {
throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
}
OriginalStdOutChars = new CharInfo [size.Height * size.Width];
if (!ReadConsoleOutput (ScreenBuffer, OriginalStdOutChars, coords, new Coord () { X = 0, Y = 0 }, ref window)) {
throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
}
}
public bool SetCursorPosition (Coord position)
{
return SetConsoleCursorPosition (ScreenBuffer, position);
}
public void SetInitialCursorVisibility ()
{
if (initialCursorVisibility.HasValue == false && GetCursorVisibility (out CursorVisibility visibility)) {
initialCursorVisibility = visibility;
}
}
public bool GetCursorVisibility (out CursorVisibility visibility)
{
if (ScreenBuffer == IntPtr.Zero) {
visibility = CursorVisibility.Invisible;
return false;
}
if (!GetConsoleCursorInfo (ScreenBuffer, out ConsoleCursorInfo info)) {
var err = Marshal.GetLastWin32Error ();
if (err != 0) {
throw new System.ComponentModel.Win32Exception (err);
}
visibility = Gui.CursorVisibility.Default;
return false;
}
if (!info.bVisible)
visibility = CursorVisibility.Invisible;
else if (info.dwSize > 50)
visibility = CursorVisibility.Box;
else
visibility = CursorVisibility.Underline;
return true;
}
public bool EnsureCursorVisibility ()
{
if (initialCursorVisibility.HasValue && pendingCursorVisibility.HasValue && SetCursorVisibility (pendingCursorVisibility.Value)) {
pendingCursorVisibility = null;
return true;
}
return false;
}
public void ForceRefreshCursorVisibility ()
{
if (currentCursorVisibility.HasValue) {
pendingCursorVisibility = currentCursorVisibility;
currentCursorVisibility = null;
}
}
public bool SetCursorVisibility (CursorVisibility visibility)
{
if (initialCursorVisibility.HasValue == false) {
pendingCursorVisibility = visibility;
return false;
}
if (currentCursorVisibility.HasValue == false || currentCursorVisibility.Value != visibility) {
ConsoleCursorInfo info = new ConsoleCursorInfo {
dwSize = (uint)visibility & 0x00FF,
bVisible = ((uint)visibility & 0xFF00) != 0
};
if (!SetConsoleCursorInfo (ScreenBuffer, ref info))
return false;
currentCursorVisibility = visibility;
}
return true;
}
public void Cleanup ()
{
if (initialCursorVisibility.HasValue) {
SetCursorVisibility (initialCursorVisibility.Value);
}
ConsoleMode = originalConsoleMode;
if (!SetConsoleActiveScreenBuffer (OutputHandle)) {
var err = Marshal.GetLastWin32Error ();
Console.WriteLine ("Error: {0}", err);
}
if (ScreenBuffer != IntPtr.Zero) {
CloseHandle (ScreenBuffer);
}
ScreenBuffer = IntPtr.Zero;
}
internal Size GetConsoleBufferWindow (out Point position)
{
if (ScreenBuffer == IntPtr.Zero) {
position = Point.Empty;
return Size.Empty;
}
var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
csbi.cbSize = (uint)Marshal.SizeOf (csbi);
if (!GetConsoleScreenBufferInfoEx (ScreenBuffer, ref csbi)) {
//throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
position = Point.Empty;
return Size.Empty;
}
var sz = new Size (csbi.srWindow.Right - csbi.srWindow.Left + 1,
csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
position = new Point (csbi.srWindow.Left, csbi.srWindow.Top);
return sz;
}
internal Size GetConsoleOutputWindow (out Point position)
{
var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
csbi.cbSize = (uint)Marshal.SizeOf (csbi);
if (!GetConsoleScreenBufferInfoEx (OutputHandle, ref csbi)) {
throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
}
var sz = new Size (csbi.srWindow.Right - csbi.srWindow.Left + 1,
csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
position = new Point (csbi.srWindow.Left, csbi.srWindow.Top);
return sz;
}
internal Size SetConsoleWindow (short cols, short rows)
{
var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
csbi.cbSize = (uint)Marshal.SizeOf (csbi);
if (!GetConsoleScreenBufferInfoEx (ScreenBuffer, ref csbi)) {
throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
}
var maxWinSize = GetLargestConsoleWindowSize (ScreenBuffer);
var newCols = Math.Min (cols, maxWinSize.X);
var newRows = Math.Min (rows, maxWinSize.Y);
csbi.dwSize = new Coord (newCols, Math.Max (newRows, (short)1));
csbi.srWindow = new SmallRect (0, 0, newCols, newRows);
csbi.dwMaximumWindowSize = new Coord (newCols, newRows);
if (!SetConsoleScreenBufferInfoEx (ScreenBuffer, ref csbi)) {
throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
}
var winRect = new SmallRect (0, 0, (short)(newCols - 1), (short)Math.Max (newRows - 1, 0));
if (!SetConsoleWindowInfo (OutputHandle, true, ref winRect)) {
//throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
return new Size (cols, rows);
}
SetConsoleOutputWindow (csbi);
return new Size (winRect.Right + 1, newRows - 1 < 0 ? 0 : winRect.Bottom + 1);
}
void SetConsoleOutputWindow (CONSOLE_SCREEN_BUFFER_INFOEX csbi)
{
if (ScreenBuffer != IntPtr.Zero && !SetConsoleScreenBufferInfoEx (ScreenBuffer, ref csbi)) {
throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
}
}
internal Size SetConsoleOutputWindow (out Point position)
{
if (ScreenBuffer == IntPtr.Zero) {
position = Point.Empty;
return Size.Empty;
}
var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
csbi.cbSize = (uint)Marshal.SizeOf (csbi);
if (!GetConsoleScreenBufferInfoEx (ScreenBuffer, ref csbi)) {
throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
}
var sz = new Size (csbi.srWindow.Right - csbi.srWindow.Left + 1,
Math.Max (csbi.srWindow.Bottom - csbi.srWindow.Top + 1, 0));
position = new Point (csbi.srWindow.Left, csbi.srWindow.Top);
SetConsoleOutputWindow (csbi);
var winRect = new SmallRect (0, 0, (short)(sz.Width - 1), (short)Math.Max (sz.Height - 1, 0));
if (!SetConsoleScreenBufferInfoEx (OutputHandle, ref csbi)) {
throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
}
if (!SetConsoleWindowInfo (OutputHandle, true, ref winRect)) {
throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
}
return sz;
}
//bool ContinueListeningForConsoleEvents = true;
public uint ConsoleMode {
get {
GetConsoleMode (InputHandle, out uint v);
return v;
}
set {
SetConsoleMode (InputHandle, value);
}
}
[Flags]
public enum ConsoleModes : uint {
EnableProcessedInput = 1,
EnableMouseInput = 16,
EnableQuickEditMode = 64,
EnableExtendedFlags = 128,
}
[StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
public struct KeyEventRecord {
[FieldOffset (0), MarshalAs (UnmanagedType.Bool)]
public bool bKeyDown;
[FieldOffset (4), MarshalAs (UnmanagedType.U2)]
public ushort wRepeatCount;
[FieldOffset (6), MarshalAs (UnmanagedType.U2)]
public ushort wVirtualKeyCode;
[FieldOffset (8), MarshalAs (UnmanagedType.U2)]
public ushort wVirtualScanCode;
[FieldOffset (10)]
public char UnicodeChar;
[FieldOffset (12), MarshalAs (UnmanagedType.U4)]
public ControlKeyState dwControlKeyState;
}
[Flags]
public enum ButtonState {
Button1Pressed = 1,
Button2Pressed = 4,
Button3Pressed = 8,
Button4Pressed = 16,
RightmostButtonPressed = 2
}
[Flags]
public enum ControlKeyState {
RightAltPressed = 1,
LeftAltPressed = 2,
RightControlPressed = 4,
LeftControlPressed = 8,
ShiftPressed = 16,
NumlockOn = 32,
ScrolllockOn = 64,
CapslockOn = 128,
EnhancedKey = 256
}
[Flags]
public enum EventFlags {
MouseMoved = 1,
DoubleClick = 2,
MouseWheeled = 4,
MouseHorizontalWheeled = 8
}
[StructLayout (LayoutKind.Explicit)]
public struct MouseEventRecord {
[FieldOffset (0)]
public Coord MousePosition;
[FieldOffset (4)]
public ButtonState ButtonState;
[FieldOffset (8)]
public ControlKeyState ControlKeyState;
[FieldOffset (12)]
public EventFlags EventFlags;
public override string ToString ()
{
return $"[Mouse({MousePosition},{ButtonState},{ControlKeyState},{EventFlags}";
}
}
public struct WindowBufferSizeRecord {
public Coord size;
public WindowBufferSizeRecord (short x, short y)
{
this.size = new Coord (x, y);
}
public override string ToString () => $"[WindowBufferSize{size}";
}
[StructLayout (LayoutKind.Sequential)]
public struct MenuEventRecord {
public uint dwCommandId;
}
[StructLayout (LayoutKind.Sequential)]
public struct FocusEventRecord {
public uint bSetFocus;
}
public enum EventType : ushort {
Focus = 0x10,
Key = 0x1,
Menu = 0x8,
Mouse = 2,
WindowBufferSize = 4
}
[StructLayout (LayoutKind.Explicit)]
public struct InputRecord {
[FieldOffset (0)]
public EventType EventType;
[FieldOffset (4)]
public KeyEventRecord KeyEvent;
[FieldOffset (4)]
public MouseEventRecord MouseEvent;
[FieldOffset (4)]
public WindowBufferSizeRecord WindowBufferSizeEvent;
[FieldOffset (4)]
public MenuEventRecord MenuEvent;
[FieldOffset (4)]
public FocusEventRecord FocusEvent;
public override string ToString ()
{
switch (EventType) {
case EventType.Focus:
return FocusEvent.ToString ();
case EventType.Key:
return KeyEvent.ToString ();
case EventType.Menu:
return MenuEvent.ToString ();
case EventType.Mouse:
return MouseEvent.ToString ();
case EventType.WindowBufferSize:
return WindowBufferSizeEvent.ToString ();
default:
return "Unknown event type: " + EventType;
}
}
};
[Flags]
enum ShareMode : uint {
FileShareRead = 1,
FileShareWrite = 2,
}
[Flags]
enum DesiredAccess : uint {
GenericRead = 2147483648,
GenericWrite = 1073741824,
}
[StructLayout (LayoutKind.Sequential)]
public struct ConsoleScreenBufferInfo {
public Coord dwSize;
public Coord dwCursorPosition;
public ushort wAttributes;
public SmallRect srWindow;
public Coord dwMaximumWindowSize;
}
[StructLayout (LayoutKind.Sequential)]
public struct Coord {
public short X;
public short Y;
public Coord (short X, short Y)
{
this.X = X;
this.Y = Y;
}
public override string ToString () => $"({X},{Y})";
};
[StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
public struct CharUnion {
[FieldOffset (0)] public char UnicodeChar;
[FieldOffset (0)] public byte AsciiChar;
}
[StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
public struct CharInfo {
[FieldOffset (0)] public CharUnion Char;
[FieldOffset (2)] public ushort Attributes;
}
[StructLayout (LayoutKind.Sequential)]
public struct SmallRect {
public short Left;
public short Top;
public short Right;
public short Bottom;
public SmallRect (short left, short top, short right, short bottom)
{
Left = left;
Top = top;
Right = right;
Bottom = bottom;
}
public static void MakeEmpty (ref SmallRect rect)
{
rect.Left = -1;
}
public static void Update (ref SmallRect rect, short col, short row)
{
if (rect.Left == -1) {
//System.Diagnostics.Debugger.Log (0, "debug", $"damager From Empty {col},{row}\n");
rect.Left = rect.Right = col;
rect.Bottom = rect.Top = row;
return;
}
if (col >= rect.Left && col <= rect.Right && row >= rect.Top && row <= rect.Bottom)
return;
if (col < rect.Left)
rect.Left = col;
if (col > rect.Right)
rect.Right = col;
if (row < rect.Top)
rect.Top = row;
if (row > rect.Bottom)
rect.Bottom = row;
//System.Diagnostics.Debugger.Log (0, "debug", $"Expanding {rect.ToString ()}\n");
}
public override string ToString ()
{
return $"Left={Left},Top={Top},Right={Right},Bottom={Bottom}";
}
}
[StructLayout (LayoutKind.Sequential)]
public struct ConsoleKeyInfoEx {
public ConsoleKeyInfo consoleKeyInfo;
public bool CapsLock;
public bool NumLock;
public bool Scrolllock;
public ConsoleKeyInfoEx (ConsoleKeyInfo consoleKeyInfo, bool capslock, bool numlock, bool scrolllock)
{
this.consoleKeyInfo = consoleKeyInfo;
CapsLock = capslock;
NumLock = numlock;
Scrolllock = scrolllock;
}
}
[DllImport ("kernel32.dll", SetLastError = true)]
static extern IntPtr GetStdHandle (int nStdHandle);
[DllImport ("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle (IntPtr handle);
[DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)]
public static extern bool ReadConsoleInput (
IntPtr hConsoleInput,
IntPtr lpBuffer,
uint nLength,
out uint lpNumberOfEventsRead);
[DllImport ("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern bool ReadConsoleOutput (
IntPtr hConsoleOutput,
[Out] CharInfo [] lpBuffer,
Coord dwBufferSize,
Coord dwBufferCoord,
ref SmallRect lpReadRegion
);
[DllImport ("kernel32.dll", EntryPoint = "WriteConsoleOutput", SetLastError = true, CharSet = CharSet.Unicode)]
static extern bool WriteConsoleOutput (
IntPtr hConsoleOutput,
CharInfo [] lpBuffer,
Coord dwBufferSize,
Coord dwBufferCoord,
ref SmallRect lpWriteRegion
);
[DllImport ("kernel32.dll")]
static extern bool SetConsoleCursorPosition (IntPtr hConsoleOutput, Coord dwCursorPosition);
[StructLayout (LayoutKind.Sequential)]
public struct ConsoleCursorInfo {
public uint dwSize;
public bool bVisible;
}
[DllImport ("kernel32.dll", SetLastError = true)]
static extern bool SetConsoleCursorInfo (IntPtr hConsoleOutput, [In] ref ConsoleCursorInfo lpConsoleCursorInfo);
[DllImport ("kernel32.dll", SetLastError = true)]
static extern bool GetConsoleCursorInfo (IntPtr hConsoleOutput, out ConsoleCursorInfo lpConsoleCursorInfo);
[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", SetLastError = true)]
static extern IntPtr CreateConsoleScreenBuffer (
DesiredAccess dwDesiredAccess,
ShareMode dwShareMode,
IntPtr secutiryAttributes,
uint flags,
IntPtr screenBufferData
);
internal static IntPtr INVALID_HANDLE_VALUE = new IntPtr (-1);
[DllImport ("kernel32.dll", SetLastError = true)]
static extern bool SetConsoleActiveScreenBuffer (IntPtr Handle);
[DllImport ("kernel32.dll", SetLastError = true)]
static extern bool GetNumberOfConsoleInputEvents (IntPtr handle, out uint lpcNumberOfEvents);
public uint InputEventCount {
get {
GetNumberOfConsoleInputEvents (InputHandle, out uint v);
return v;
}
}
public InputRecord [] ReadConsoleInput ()
{
const int bufferSize = 1;
var pRecord = Marshal.AllocHGlobal (Marshal.SizeOf<InputRecord> () * bufferSize);
try {
ReadConsoleInput (InputHandle, pRecord, bufferSize,
out var numberEventsRead);
return numberEventsRead == 0
? null
: new [] { Marshal.PtrToStructure<InputRecord> (pRecord) };
} catch (Exception) {
return null;
} finally {
Marshal.FreeHGlobal (pRecord);
}
}
#if false // Not needed on the constructor. Perhaps could be used on resizing. To study.
[DllImport ("kernel32.dll", ExactSpelling = true)]
static extern IntPtr GetConsoleWindow ();
[DllImport ("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool ShowWindow (IntPtr hWnd, int nCmdShow);
public const int HIDE = 0;
public const int MAXIMIZE = 3;
public const int MINIMIZE = 6;
public const int RESTORE = 9;
internal void ShowWindow (int state)
{
IntPtr thisConsole = GetConsoleWindow ();
ShowWindow (thisConsole, state);
}
#endif
// See: https://github.com/gui-cs/Terminal.Gui/issues/357
[StructLayout (LayoutKind.Sequential)]
public struct CONSOLE_SCREEN_BUFFER_INFOEX {
public uint cbSize;
public Coord dwSize;
public Coord dwCursorPosition;
public ushort wAttributes;
public SmallRect srWindow;
public Coord dwMaximumWindowSize;
public ushort wPopupAttributes;
public bool bFullscreenSupported;
[MarshalAs (UnmanagedType.ByValArray, SizeConst = 16)]
public COLORREF [] ColorTable;
}
[StructLayout (LayoutKind.Explicit, Size = 4)]
public struct COLORREF {
public COLORREF (byte r, byte g, byte b)
{
Value = 0;
R = r;
G = g;
B = b;
}
public COLORREF (uint value)
{
R = 0;
G = 0;
B = 0;
Value = value & 0x00FFFFFF;
}
[FieldOffset (0)]
public byte R;
[FieldOffset (1)]
public byte G;
[FieldOffset (2)]
public byte B;
[FieldOffset (0)]
public uint Value;
}
[DllImport ("kernel32.dll", SetLastError = true)]
static extern bool GetConsoleScreenBufferInfoEx (IntPtr hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX csbi);
[DllImport ("kernel32.dll", SetLastError = true)]
static extern bool SetConsoleScreenBufferInfoEx (IntPtr hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX ConsoleScreenBufferInfo);
[DllImport ("kernel32.dll", SetLastError = true)]
static extern bool SetConsoleWindowInfo (
IntPtr hConsoleOutput,
bool bAbsolute,
[In] ref SmallRect lpConsoleWindow);
[DllImport ("kernel32.dll", SetLastError = true)]
static extern Coord GetLargestConsoleWindowSize (
IntPtr hConsoleOutput);
}
internal class WindowsDriver : ConsoleDriver {
static bool sync = false;
WindowsConsole.CharInfo [] OutputBuffer;
int cols, rows, left, top;
WindowsConsole.SmallRect damageRegion;
IClipboard clipboard;
int [,,] contents;
readonly bool isWindowsTerminal;
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 override IClipboard Clipboard => clipboard;
public override int [,,] Contents => contents;
public WindowsConsole WinConsole { get; private set; }
Action<KeyEvent> keyHandler;
Action<KeyEvent> keyDownHandler;
Action<KeyEvent> keyUpHandler;
Action<MouseEvent> mouseHandler;
public WindowsDriver ()
{
WinConsole = new WindowsConsole ();
clipboard = new WindowsClipboard ();
isWindowsTerminal = Environment.GetEnvironmentVariable ("WT_SESSION") != null;
}
public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
{
this.keyHandler = keyHandler;
this.keyDownHandler = keyDownHandler;
this.keyUpHandler = keyUpHandler;
this.mouseHandler = mouseHandler;
var mLoop = mainLoop.Driver as WindowsMainLoop;
mLoop.ProcessInput = (e) => ProcessInput (e);
mLoop.WinChanged = (e) => {
ChangeWin (e);
};
}
private void ChangeWin (Size e)
{
var w = e.Width;
if (w == cols - 3 && e.Height < rows) {
w += 3;
}
var newSize = WinConsole.SetConsoleWindow (
(short)Math.Max (w, 16), (short)Math.Max (e.Height, 0));
left = 0;
top = 0;
cols = newSize.Width;
rows = newSize.Height;
ResizeScreen ();
UpdateOffScreen ();
TerminalResized.Invoke ();
}
void ProcessInput (WindowsConsole.InputRecord inputEvent)
{
switch (inputEvent.EventType) {
case WindowsConsole.EventType.Key:
var fromPacketKey = inputEvent.KeyEvent.wVirtualKeyCode == (uint)ConsoleKey.Packet;
if (fromPacketKey) {
inputEvent.KeyEvent = FromVKPacketToKeyEventRecord (inputEvent.KeyEvent);
}
var map = MapKey (ToConsoleKeyInfoEx (inputEvent.KeyEvent));
//var ke = inputEvent.KeyEvent;
//System.Diagnostics.Debug.WriteLine ($"fromPacketKey: {fromPacketKey}");
//if (ke.UnicodeChar == '\0') {
// System.Diagnostics.Debug.WriteLine ("UnicodeChar: 0'\\0'");
//} else if (ke.UnicodeChar == 13) {
// System.Diagnostics.Debug.WriteLine ("UnicodeChar: 13'\\n'");
//} else {
// System.Diagnostics.Debug.WriteLine ($"UnicodeChar: {(uint)ke.UnicodeChar}'{ke.UnicodeChar}'");
//}
//System.Diagnostics.Debug.WriteLine ($"bKeyDown: {ke.bKeyDown}");
//System.Diagnostics.Debug.WriteLine ($"dwControlKeyState: {ke.dwControlKeyState}");
//System.Diagnostics.Debug.WriteLine ($"wRepeatCount: {ke.wRepeatCount}");
//System.Diagnostics.Debug.WriteLine ($"wVirtualKeyCode: {ke.wVirtualKeyCode}");
//System.Diagnostics.Debug.WriteLine ($"wVirtualScanCode: {ke.wVirtualScanCode}");
if (map == (Key)0xffffffff) {
KeyEvent key = new KeyEvent ();
// Shift = VK_SHIFT = 0x10
// Ctrl = VK_CONTROL = 0x11
// Alt = VK_MENU = 0x12
if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.CapslockOn)) {
inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.CapslockOn;
}
if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ScrolllockOn)) {
inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.ScrolllockOn;
}
if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.NumlockOn)) {
inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.NumlockOn;
}
switch (inputEvent.KeyEvent.dwControlKeyState) {
case WindowsConsole.ControlKeyState.RightAltPressed:
case WindowsConsole.ControlKeyState.RightAltPressed |
WindowsConsole.ControlKeyState.LeftControlPressed |
WindowsConsole.ControlKeyState.EnhancedKey:
case WindowsConsole.ControlKeyState.EnhancedKey:
key = new KeyEvent (Key.CtrlMask | Key.AltMask, keyModifiers);
break;
case WindowsConsole.ControlKeyState.LeftAltPressed:
key = new KeyEvent (Key.AltMask, keyModifiers);
break;
case WindowsConsole.ControlKeyState.RightControlPressed:
case WindowsConsole.ControlKeyState.LeftControlPressed:
key = new KeyEvent (Key.CtrlMask, keyModifiers);
break;
case WindowsConsole.ControlKeyState.ShiftPressed:
key = new KeyEvent (Key.ShiftMask, keyModifiers);
break;
case WindowsConsole.ControlKeyState.NumlockOn:
break;
case WindowsConsole.ControlKeyState.ScrolllockOn:
break;
case WindowsConsole.ControlKeyState.CapslockOn:
break;
default:
switch (inputEvent.KeyEvent.wVirtualKeyCode) {
case 0x10:
key = new KeyEvent (Key.ShiftMask, keyModifiers);
break;
case 0x11:
key = new KeyEvent (Key.CtrlMask, keyModifiers);
break;
case 0x12:
key = new KeyEvent (Key.AltMask, keyModifiers);
break;
default:
key = new KeyEvent (Key.Unknown, keyModifiers);
break;
}
break;
}
if (inputEvent.KeyEvent.bKeyDown)
keyDownHandler (key);
else
keyUpHandler (key);
} else {
if (inputEvent.KeyEvent.bKeyDown) {
// May occurs using SendKeys
if (keyModifiers == null)
keyModifiers = new KeyModifiers ();
// Key Down - Fire KeyDown Event and KeyStroke (ProcessKey) Event
keyDownHandler (new KeyEvent (map, keyModifiers));
keyHandler (new KeyEvent (map, keyModifiers));
} else {
keyUpHandler (new KeyEvent (map, keyModifiers));
}
}
if (!inputEvent.KeyEvent.bKeyDown && (inputEvent.KeyEvent.dwControlKeyState == 0 || inputEvent.KeyEvent.dwControlKeyState == WindowsConsole.ControlKeyState.EnhancedKey)) {
keyModifiers = null;
}
break;
case WindowsConsole.EventType.Mouse:
var me = ToDriverMouse (inputEvent.MouseEvent);
mouseHandler (me);
if (processButtonClick) {
mouseHandler (
new MouseEvent () {
X = me.X,
Y = me.Y,
Flags = ProcessButtonClick (inputEvent.MouseEvent)
});
}
break;
case WindowsConsole.EventType.Focus:
keyModifiers = null;
break;
}
}
WindowsConsole.ButtonState? lastMouseButtonPressed = null;
bool isButtonPressed = false;
bool isButtonReleased = false;
bool isButtonDoubleClicked = false;
Point? point;
Point pointMove;
//int buttonPressedCount;
bool isOneFingerDoubleClicked = false;
bool processButtonClick;
MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
{
MouseFlags mouseFlag = MouseFlags.AllEvents;
//System.Diagnostics.Debug.WriteLine (
// $"X:{mouseEvent.MousePosition.X};Y:{mouseEvent.MousePosition.Y};ButtonState:{mouseEvent.ButtonState};EventFlags:{mouseEvent.EventFlags}");
if (isButtonDoubleClicked || isOneFingerDoubleClicked) {
Application.MainLoop.AddIdle (() => {
Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
return false;
});
}
// The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
// This will tell when a mouse button is pressed. When the button is released this event will
// be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
// To map to the correct driver events we save the last pressed mouse button so we can
// map to the correct clicked event.
if ((lastMouseButtonPressed != null || isButtonReleased) && mouseEvent.ButtonState != 0) {
lastMouseButtonPressed = null;
//isButtonPressed = false;
isButtonReleased = false;
}
var p = new Point () {
X = mouseEvent.MousePosition.X,
Y = mouseEvent.MousePosition.Y
};
//if (!isButtonPressed && buttonPressedCount < 2
// && mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
// && (mouseEvent.ButtonState == WindowsConsole.ButtonState.Button1Pressed
// || mouseEvent.ButtonState == WindowsConsole.ButtonState.Button2Pressed
// || mouseEvent.ButtonState == WindowsConsole.ButtonState.Button3Pressed)) {
// lastMouseButtonPressed = mouseEvent.ButtonState;
// buttonPressedCount++;
//} else if (!isButtonPressed && buttonPressedCount > 0 && mouseEvent.ButtonState == 0
// && mouseEvent.EventFlags == 0) {
// buttonPressedCount++;
//}
//System.Diagnostics.Debug.WriteLine ($"isButtonPressed: {isButtonPressed};buttonPressedCount: {buttonPressedCount};lastMouseButtonPressed: {lastMouseButtonPressed}");
//System.Diagnostics.Debug.WriteLine ($"isOneFingerDoubleClicked: {isOneFingerDoubleClicked}");
//if (buttonPressedCount == 1 && lastMouseButtonPressed != null && p == point
// && lastMouseButtonPressed == WindowsConsole.ButtonState.Button1Pressed
// || lastMouseButtonPressed == WindowsConsole.ButtonState.Button2Pressed
// || lastMouseButtonPressed == WindowsConsole.ButtonState.Button3Pressed) {
// switch (lastMouseButtonPressed) {
// case WindowsConsole.ButtonState.Button1Pressed:
// mouseFlag = MouseFlags.Button1DoubleClicked;
// break;
// case WindowsConsole.ButtonState.Button2Pressed:
// mouseFlag = MouseFlags.Button2DoubleClicked;
// break;
// case WindowsConsole.ButtonState.Button3Pressed:
// mouseFlag = MouseFlags.Button3DoubleClicked;
// break;
// }
// isOneFingerDoubleClicked = true;
//} else if (buttonPressedCount == 3 && lastMouseButtonPressed != null && isOneFingerDoubleClicked && p == point
// && lastMouseButtonPressed == WindowsConsole.ButtonState.Button1Pressed
// || lastMouseButtonPressed == WindowsConsole.ButtonState.Button2Pressed
// || lastMouseButtonPressed == WindowsConsole.ButtonState.Button3Pressed) {
// switch (lastMouseButtonPressed) {
// case WindowsConsole.ButtonState.Button1Pressed:
// mouseFlag = MouseFlags.Button1TripleClicked;
// break;
// case WindowsConsole.ButtonState.Button2Pressed:
// mouseFlag = MouseFlags.Button2TripleClicked;
// break;
// case WindowsConsole.ButtonState.Button3Pressed:
// mouseFlag = MouseFlags.Button3TripleClicked;
// break;
// }
// buttonPressedCount = 0;
// lastMouseButtonPressed = null;
// isOneFingerDoubleClicked = false;
// isButtonReleased = false;
//}
if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && lastMouseButtonPressed == null && !isButtonDoubleClicked) ||
(lastMouseButtonPressed == null && mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved) &&