WindowsDriver.cs 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953
  1. //
  2. // WindowsDriver.cs: Windows specific driver
  3. //
  4. // HACK:
  5. // WindowsConsole/Terminal has two issues:
  6. // 1) Tearing can occur when the console is resized.
  7. // 2) The values provided during Init (and the first WindowsConsole.EventType.WindowBufferSize) are not correct.
  8. //
  9. // If HACK_CHECK_WINCHANGED is defined then we ignore WindowsConsole.EventType.WindowBufferSize events
  10. // and instead check the console size every every 500ms in a thread in WidowsMainLoop.
  11. // As of Windows 11 23H2 25947.1000 and/or WT 1.19.2682 tearing no longer occurs when using
  12. // the WindowsConsole.EventType.WindowBufferSize event. However, on Init the window size is
  13. // still incorrect so we still need this hack.
  14. #define HACK_CHECK_WINCHANGED
  15. using System.Text;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.ComponentModel;
  19. using System.Runtime.InteropServices;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. using System.Diagnostics;
  23. using Terminal.Gui.ConsoleDrivers;
  24. using static Unix.Terminal.Delegates;
  25. using static Terminal.Gui.ConsoleDrivers.ConsoleKeyMapping;
  26. namespace Terminal.Gui;
  27. internal class WindowsConsole {
  28. public const int STD_OUTPUT_HANDLE = -11;
  29. public const int STD_INPUT_HANDLE = -10;
  30. IntPtr _inputHandle, _outputHandle;
  31. IntPtr _screenBuffer;
  32. readonly uint _originalConsoleMode;
  33. CursorVisibility? _initialCursorVisibility = null;
  34. CursorVisibility? _currentCursorVisibility = null;
  35. CursorVisibility? _pendingCursorVisibility = null;
  36. readonly StringBuilder _stringBuilder = new StringBuilder (256 * 1024);
  37. public WindowsConsole ()
  38. {
  39. _inputHandle = GetStdHandle (STD_INPUT_HANDLE);
  40. _outputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
  41. _originalConsoleMode = ConsoleMode;
  42. var newConsoleMode = _originalConsoleMode;
  43. newConsoleMode |= (uint)(ConsoleModes.EnableMouseInput | ConsoleModes.EnableExtendedFlags);
  44. newConsoleMode &= ~(uint)ConsoleModes.EnableQuickEditMode;
  45. newConsoleMode &= ~(uint)ConsoleModes.EnableProcessedInput;
  46. ConsoleMode = newConsoleMode;
  47. }
  48. CharInfo [] _originalStdOutChars;
  49. public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord bufferSize, SmallRect window, bool force16Colors)
  50. {
  51. if (_screenBuffer == IntPtr.Zero) {
  52. ReadFromConsoleOutput (size, bufferSize, ref window);
  53. }
  54. bool result = false;
  55. if (force16Colors) {
  56. int i = 0;
  57. CharInfo [] ci = new CharInfo [charInfoBuffer.Length];
  58. foreach (ExtendedCharInfo info in charInfoBuffer) {
  59. ci [i++] = new CharInfo () {
  60. Char = new CharUnion () { UnicodeChar = info.Char },
  61. Attributes = (ushort)(((int)info.Attribute.Foreground.ColorName) | ((int)info.Attribute.Background.ColorName << 4))
  62. };
  63. }
  64. result = WriteConsoleOutput (_screenBuffer, ci, bufferSize, new Coord () { X = window.Left, Y = window.Top }, ref window);
  65. } else {
  66. _stringBuilder.Clear ();
  67. _stringBuilder.Append (EscSeqUtils.CSI_SaveCursorPosition);
  68. _stringBuilder.Append (EscSeqUtils.CSI_SetCursorPosition (0, 0));
  69. Attribute? prev = null;
  70. foreach (var info in charInfoBuffer) {
  71. var attr = info.Attribute;
  72. if (attr != prev) {
  73. prev = attr;
  74. _stringBuilder.Append (EscSeqUtils.CSI_SetForegroundColorRGB (attr.Foreground.R, attr.Foreground.G, attr.Foreground.B));
  75. _stringBuilder.Append (EscSeqUtils.CSI_SetBackgroundColorRGB (attr.Background.R, attr.Background.G, attr.Background.B));
  76. }
  77. if (info.Char != '\x1b') {
  78. if (!info.Empty) {
  79. _stringBuilder.Append (info.Char);
  80. }
  81. } else {
  82. _stringBuilder.Append (' ');
  83. }
  84. }
  85. _stringBuilder.Append (EscSeqUtils.CSI_RestoreCursorPosition);
  86. string s = _stringBuilder.ToString ();
  87. result = WriteConsole (_screenBuffer, s, (uint)(s.Length), out uint _, null);
  88. }
  89. if (!result) {
  90. var err = Marshal.GetLastWin32Error ();
  91. if (err != 0) {
  92. throw new System.ComponentModel.Win32Exception (err);
  93. }
  94. }
  95. return result;
  96. }
  97. public void ReadFromConsoleOutput (Size size, Coord coords, ref SmallRect window)
  98. {
  99. _screenBuffer = CreateConsoleScreenBuffer (
  100. DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
  101. ShareMode.FileShareRead | ShareMode.FileShareWrite,
  102. IntPtr.Zero,
  103. 1,
  104. IntPtr.Zero
  105. );
  106. if (_screenBuffer == INVALID_HANDLE_VALUE) {
  107. var err = Marshal.GetLastWin32Error ();
  108. if (err != 0) {
  109. throw new System.ComponentModel.Win32Exception (err);
  110. }
  111. }
  112. if (!_initialCursorVisibility.HasValue && GetCursorVisibility (out CursorVisibility visibility)) {
  113. _initialCursorVisibility = visibility;
  114. }
  115. if (!SetConsoleActiveScreenBuffer (_screenBuffer)) {
  116. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  117. }
  118. _originalStdOutChars = new CharInfo [size.Height * size.Width];
  119. if (!ReadConsoleOutput (_screenBuffer, _originalStdOutChars, coords, new Coord () { X = 0, Y = 0 }, ref window)) {
  120. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  121. }
  122. }
  123. public bool SetCursorPosition (Coord position)
  124. {
  125. return SetConsoleCursorPosition (_screenBuffer, position);
  126. }
  127. public void SetInitialCursorVisibility ()
  128. {
  129. if (_initialCursorVisibility.HasValue == false && GetCursorVisibility (out CursorVisibility visibility)) {
  130. _initialCursorVisibility = visibility;
  131. }
  132. }
  133. public bool GetCursorVisibility (out CursorVisibility visibility)
  134. {
  135. if (_screenBuffer == IntPtr.Zero) {
  136. visibility = CursorVisibility.Invisible;
  137. return false;
  138. }
  139. if (!GetConsoleCursorInfo (_screenBuffer, out ConsoleCursorInfo info)) {
  140. var err = Marshal.GetLastWin32Error ();
  141. if (err != 0) {
  142. throw new System.ComponentModel.Win32Exception (err);
  143. }
  144. visibility = Gui.CursorVisibility.Default;
  145. return false;
  146. }
  147. if (!info.bVisible) {
  148. visibility = CursorVisibility.Invisible;
  149. } else if (info.dwSize > 50) {
  150. visibility = CursorVisibility.Box;
  151. } else {
  152. visibility = CursorVisibility.Underline;
  153. }
  154. return true;
  155. }
  156. public bool EnsureCursorVisibility ()
  157. {
  158. if (_initialCursorVisibility.HasValue && _pendingCursorVisibility.HasValue && SetCursorVisibility (_pendingCursorVisibility.Value)) {
  159. _pendingCursorVisibility = null;
  160. return true;
  161. }
  162. return false;
  163. }
  164. public void ForceRefreshCursorVisibility ()
  165. {
  166. if (_currentCursorVisibility.HasValue) {
  167. _pendingCursorVisibility = _currentCursorVisibility;
  168. _currentCursorVisibility = null;
  169. }
  170. }
  171. public bool SetCursorVisibility (CursorVisibility visibility)
  172. {
  173. if (_initialCursorVisibility.HasValue == false) {
  174. _pendingCursorVisibility = visibility;
  175. return false;
  176. }
  177. if (_currentCursorVisibility.HasValue == false || _currentCursorVisibility.Value != visibility) {
  178. ConsoleCursorInfo info = new ConsoleCursorInfo {
  179. dwSize = (uint)visibility & 0x00FF,
  180. bVisible = ((uint)visibility & 0xFF00) != 0
  181. };
  182. if (!SetConsoleCursorInfo (_screenBuffer, ref info)) {
  183. return false;
  184. }
  185. _currentCursorVisibility = visibility;
  186. }
  187. return true;
  188. }
  189. public void Cleanup ()
  190. {
  191. if (_initialCursorVisibility.HasValue) {
  192. SetCursorVisibility (_initialCursorVisibility.Value);
  193. }
  194. SetConsoleOutputWindow (out _);
  195. ConsoleMode = _originalConsoleMode;
  196. if (!SetConsoleActiveScreenBuffer (_outputHandle)) {
  197. var err = Marshal.GetLastWin32Error ();
  198. Console.WriteLine ("Error: {0}", err);
  199. }
  200. if (_screenBuffer != IntPtr.Zero) {
  201. CloseHandle (_screenBuffer);
  202. }
  203. _screenBuffer = IntPtr.Zero;
  204. }
  205. internal Size GetConsoleBufferWindow (out Point position)
  206. {
  207. if (_screenBuffer == IntPtr.Zero) {
  208. position = Point.Empty;
  209. return Size.Empty;
  210. }
  211. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  212. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  213. if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) {
  214. //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  215. position = Point.Empty;
  216. return Size.Empty;
  217. }
  218. var sz = new Size (csbi.srWindow.Right - csbi.srWindow.Left + 1,
  219. csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
  220. position = new Point (csbi.srWindow.Left, csbi.srWindow.Top);
  221. return sz;
  222. }
  223. internal Size GetConsoleOutputWindow (out Point position)
  224. {
  225. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  226. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  227. if (!GetConsoleScreenBufferInfoEx (_outputHandle, ref csbi)) {
  228. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  229. }
  230. var sz = new Size (csbi.srWindow.Right - csbi.srWindow.Left + 1,
  231. csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
  232. position = new Point (csbi.srWindow.Left, csbi.srWindow.Top);
  233. return sz;
  234. }
  235. internal Size SetConsoleWindow (short cols, short rows)
  236. {
  237. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  238. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  239. if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) {
  240. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  241. }
  242. var maxWinSize = GetLargestConsoleWindowSize (_screenBuffer);
  243. var newCols = Math.Min (cols, maxWinSize.X);
  244. var newRows = Math.Min (rows, maxWinSize.Y);
  245. csbi.dwSize = new Coord (newCols, Math.Max (newRows, (short)1));
  246. csbi.srWindow = new SmallRect (0, 0, newCols, newRows);
  247. csbi.dwMaximumWindowSize = new Coord (newCols, newRows);
  248. if (!SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) {
  249. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  250. }
  251. var winRect = new SmallRect (0, 0, (short)(newCols - 1), (short)Math.Max (newRows - 1, 0));
  252. if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect)) {
  253. //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  254. return new Size (cols, rows);
  255. }
  256. SetConsoleOutputWindow (csbi);
  257. return new Size (winRect.Right + 1, newRows - 1 < 0 ? 0 : winRect.Bottom + 1);
  258. }
  259. void SetConsoleOutputWindow (CONSOLE_SCREEN_BUFFER_INFOEX csbi)
  260. {
  261. if (_screenBuffer != IntPtr.Zero && !SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) {
  262. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  263. }
  264. }
  265. internal Size SetConsoleOutputWindow (out Point position)
  266. {
  267. if (_screenBuffer == IntPtr.Zero) {
  268. position = Point.Empty;
  269. return Size.Empty;
  270. }
  271. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  272. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  273. if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) {
  274. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  275. }
  276. var sz = new Size (csbi.srWindow.Right - csbi.srWindow.Left + 1,
  277. Math.Max (csbi.srWindow.Bottom - csbi.srWindow.Top + 1, 0));
  278. position = new Point (csbi.srWindow.Left, csbi.srWindow.Top);
  279. SetConsoleOutputWindow (csbi);
  280. var winRect = new SmallRect (0, 0, (short)(sz.Width - 1), (short)Math.Max (sz.Height - 1, 0));
  281. if (!SetConsoleScreenBufferInfoEx (_outputHandle, ref csbi)) {
  282. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  283. }
  284. if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect)) {
  285. throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  286. }
  287. return sz;
  288. }
  289. uint ConsoleMode {
  290. get {
  291. GetConsoleMode (_inputHandle, out uint v);
  292. return v;
  293. }
  294. set {
  295. SetConsoleMode (_inputHandle, value);
  296. }
  297. }
  298. [Flags]
  299. public enum ConsoleModes : uint {
  300. EnableProcessedInput = 1,
  301. EnableMouseInput = 16,
  302. EnableQuickEditMode = 64,
  303. EnableExtendedFlags = 128,
  304. }
  305. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  306. public struct KeyEventRecord {
  307. [FieldOffset (0), MarshalAs (UnmanagedType.Bool)]
  308. public bool bKeyDown;
  309. [FieldOffset (4), MarshalAs (UnmanagedType.U2)]
  310. public ushort wRepeatCount;
  311. [FieldOffset (6), MarshalAs (UnmanagedType.U2)]
  312. public VK wVirtualKeyCode;
  313. [FieldOffset (8), MarshalAs (UnmanagedType.U2)]
  314. public ushort wVirtualScanCode;
  315. [FieldOffset (10)]
  316. public char UnicodeChar;
  317. [FieldOffset (12), MarshalAs (UnmanagedType.U4)]
  318. public ControlKeyState dwControlKeyState;
  319. public override readonly string ToString () => $"[KeyEventRecord({(bKeyDown ? "down" : "up")},{wRepeatCount},{wVirtualKeyCode},{wVirtualScanCode},{new Rune (UnicodeChar).MakePrintable ()},{dwControlKeyState})]";
  320. }
  321. [Flags]
  322. public enum ButtonState {
  323. Button1Pressed = 1,
  324. Button2Pressed = 4,
  325. Button3Pressed = 8,
  326. Button4Pressed = 16,
  327. RightmostButtonPressed = 2
  328. }
  329. [Flags]
  330. public enum ControlKeyState {
  331. RightAltPressed = 1,
  332. LeftAltPressed = 2,
  333. RightControlPressed = 4,
  334. LeftControlPressed = 8,
  335. ShiftPressed = 16,
  336. NumlockOn = 32,
  337. ScrolllockOn = 64,
  338. CapslockOn = 128,
  339. EnhancedKey = 256
  340. }
  341. [Flags]
  342. public enum EventFlags {
  343. MouseMoved = 1,
  344. DoubleClick = 2,
  345. MouseWheeled = 4,
  346. MouseHorizontalWheeled = 8
  347. }
  348. [StructLayout (LayoutKind.Explicit)]
  349. public struct MouseEventRecord {
  350. [FieldOffset (0)]
  351. public Coord MousePosition;
  352. [FieldOffset (4)]
  353. public ButtonState ButtonState;
  354. [FieldOffset (8)]
  355. public ControlKeyState ControlKeyState;
  356. [FieldOffset (12)]
  357. public EventFlags EventFlags;
  358. public override readonly string ToString () => $"[Mouse({MousePosition},{ButtonState},{ControlKeyState},{EventFlags}";
  359. }
  360. public struct WindowBufferSizeRecord {
  361. public Coord _size;
  362. public WindowBufferSizeRecord (short x, short y)
  363. {
  364. _size = new Coord (x, y);
  365. }
  366. public override readonly string ToString () => $"[WindowBufferSize{_size}";
  367. }
  368. [StructLayout (LayoutKind.Sequential)]
  369. public struct MenuEventRecord {
  370. public uint dwCommandId;
  371. }
  372. [StructLayout (LayoutKind.Sequential)]
  373. public struct FocusEventRecord {
  374. public uint bSetFocus;
  375. }
  376. public enum EventType : ushort {
  377. Focus = 0x10,
  378. Key = 0x1,
  379. Menu = 0x8,
  380. Mouse = 2,
  381. WindowBufferSize = 4
  382. }
  383. [StructLayout (LayoutKind.Explicit)]
  384. public struct InputRecord {
  385. [FieldOffset (0)]
  386. public EventType EventType;
  387. [FieldOffset (4)]
  388. public KeyEventRecord KeyEvent;
  389. [FieldOffset (4)]
  390. public MouseEventRecord MouseEvent;
  391. [FieldOffset (4)]
  392. public WindowBufferSizeRecord WindowBufferSizeEvent;
  393. [FieldOffset (4)]
  394. public MenuEventRecord MenuEvent;
  395. [FieldOffset (4)]
  396. public FocusEventRecord FocusEvent;
  397. public override readonly string ToString ()
  398. {
  399. return EventType switch {
  400. EventType.Focus => FocusEvent.ToString (),
  401. EventType.Key => KeyEvent.ToString (),
  402. EventType.Menu => MenuEvent.ToString (),
  403. EventType.Mouse => MouseEvent.ToString (),
  404. EventType.WindowBufferSize => WindowBufferSizeEvent.ToString (),
  405. _ => "Unknown event type: " + EventType
  406. };
  407. }
  408. };
  409. [Flags]
  410. enum ShareMode : uint {
  411. FileShareRead = 1,
  412. FileShareWrite = 2,
  413. }
  414. [Flags]
  415. enum DesiredAccess : uint {
  416. GenericRead = 2147483648,
  417. GenericWrite = 1073741824,
  418. }
  419. [StructLayout (LayoutKind.Sequential)]
  420. public struct ConsoleScreenBufferInfo {
  421. public Coord dwSize;
  422. public Coord dwCursorPosition;
  423. public ushort wAttributes;
  424. public SmallRect srWindow;
  425. public Coord dwMaximumWindowSize;
  426. }
  427. [StructLayout (LayoutKind.Sequential)]
  428. public struct Coord {
  429. public short X;
  430. public short Y;
  431. public Coord (short x, short y)
  432. {
  433. X = x;
  434. Y = y;
  435. }
  436. public override readonly string ToString () => $"({X},{Y})";
  437. };
  438. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  439. public struct CharUnion {
  440. [FieldOffset (0)] public char UnicodeChar;
  441. [FieldOffset (0)] public byte AsciiChar;
  442. }
  443. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  444. public struct CharInfo {
  445. [FieldOffset (0)] public CharUnion Char;
  446. [FieldOffset (2)] public ushort Attributes;
  447. }
  448. public struct ExtendedCharInfo {
  449. public char Char { get; set; }
  450. public Attribute Attribute { get; set; }
  451. public bool Empty { get; set; } // TODO: Temp hack until virutal terminal sequences
  452. public ExtendedCharInfo (char character, Attribute attribute)
  453. {
  454. Char = character;
  455. Attribute = attribute;
  456. Empty = false;
  457. }
  458. }
  459. [StructLayout (LayoutKind.Sequential)]
  460. public struct SmallRect {
  461. public short Left;
  462. public short Top;
  463. public short Right;
  464. public short Bottom;
  465. public SmallRect (short left, short top, short right, short bottom)
  466. {
  467. Left = left;
  468. Top = top;
  469. Right = right;
  470. Bottom = bottom;
  471. }
  472. public static void MakeEmpty (ref SmallRect rect)
  473. {
  474. rect.Left = -1;
  475. }
  476. public static void Update (ref SmallRect rect, short col, short row)
  477. {
  478. if (rect.Left == -1) {
  479. rect.Left = rect.Right = col;
  480. rect.Bottom = rect.Top = row;
  481. return;
  482. }
  483. if (col >= rect.Left && col <= rect.Right && row >= rect.Top && row <= rect.Bottom)
  484. return;
  485. if (col < rect.Left)
  486. rect.Left = col;
  487. if (col > rect.Right)
  488. rect.Right = col;
  489. if (row < rect.Top)
  490. rect.Top = row;
  491. if (row > rect.Bottom)
  492. rect.Bottom = row;
  493. }
  494. public override readonly string ToString () => $"Left={Left},Top={Top},Right={Right},Bottom={Bottom}";
  495. }
  496. [StructLayout (LayoutKind.Sequential)]
  497. public struct ConsoleKeyInfoEx {
  498. public ConsoleKeyInfo ConsoleKeyInfo;
  499. public bool CapsLock;
  500. public bool NumLock;
  501. public bool ScrollLock;
  502. public ConsoleKeyInfoEx (ConsoleKeyInfo consoleKeyInfo, bool capslock, bool numlock, bool scrolllock)
  503. {
  504. ConsoleKeyInfo = consoleKeyInfo;
  505. CapsLock = capslock;
  506. NumLock = numlock;
  507. ScrollLock = scrolllock;
  508. }
  509. /// <summary>
  510. /// Prints a ConsoleKeyInfoEx structure
  511. /// </summary>
  512. /// <param name="ex"></param>
  513. /// <returns></returns>
  514. public readonly string ToString (ConsoleKeyInfoEx ex)
  515. {
  516. var ke = new Key ((KeyCode)ex.ConsoleKeyInfo.KeyChar);
  517. var sb = new StringBuilder ();
  518. sb.Append ($"Key: {(KeyCode)ex.ConsoleKeyInfo.Key} ({ex.ConsoleKeyInfo.Key})");
  519. sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0 ? " | Shift" : string.Empty);
  520. sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0 ? " | Control" : string.Empty);
  521. sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0 ? " | Alt" : string.Empty);
  522. sb.Append ($", KeyChar: {ke.AsRune.MakePrintable ()} ({(uint)ex.ConsoleKeyInfo.KeyChar}) ");
  523. sb.Append ((ex.CapsLock ? "caps," : string.Empty));
  524. sb.Append ((ex.NumLock ? "num," : string.Empty));
  525. sb.Append ((ex.ScrollLock ? "scroll," : string.Empty));
  526. var s = sb.ToString ().TrimEnd (',').TrimEnd (' ');
  527. return $"[ConsoleKeyInfoEx({s})]";
  528. }
  529. }
  530. [DllImport ("kernel32.dll", SetLastError = true)]
  531. static extern IntPtr GetStdHandle (int nStdHandle);
  532. [DllImport ("kernel32.dll", SetLastError = true)]
  533. static extern bool CloseHandle (IntPtr handle);
  534. [DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)]
  535. public static extern bool ReadConsoleInput (
  536. IntPtr hConsoleInput,
  537. IntPtr lpBuffer,
  538. uint nLength,
  539. out uint lpNumberOfEventsRead);
  540. [DllImport ("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  541. static extern bool ReadConsoleOutput (
  542. IntPtr hConsoleOutput,
  543. [Out] CharInfo [] lpBuffer,
  544. Coord dwBufferSize,
  545. Coord dwBufferCoord,
  546. ref SmallRect lpReadRegion
  547. );
  548. // TODO: This API is obsolete. See https://learn.microsoft.com/en-us/windows/console/writeconsoleoutput
  549. [DllImport ("kernel32.dll", EntryPoint = "WriteConsoleOutputW", SetLastError = true, CharSet = CharSet.Unicode)]
  550. static extern bool WriteConsoleOutput (
  551. IntPtr hConsoleOutput,
  552. CharInfo [] lpBuffer,
  553. Coord dwBufferSize,
  554. Coord dwBufferCoord,
  555. ref SmallRect lpWriteRegion
  556. );
  557. [DllImport ("kernel32.dll", EntryPoint = "WriteConsole", SetLastError = true, CharSet = CharSet.Unicode)]
  558. static extern bool WriteConsole (
  559. IntPtr hConsoleOutput,
  560. String lpbufer,
  561. UInt32 NumberOfCharsToWriten,
  562. out UInt32 lpNumberOfCharsWritten,
  563. object lpReserved
  564. );
  565. [DllImport ("kernel32.dll")]
  566. static extern bool SetConsoleCursorPosition (IntPtr hConsoleOutput, Coord dwCursorPosition);
  567. [StructLayout (LayoutKind.Sequential)]
  568. public struct ConsoleCursorInfo {
  569. public uint dwSize;
  570. public bool bVisible;
  571. }
  572. [DllImport ("kernel32.dll", SetLastError = true)]
  573. static extern bool SetConsoleCursorInfo (IntPtr hConsoleOutput, [In] ref ConsoleCursorInfo lpConsoleCursorInfo);
  574. [DllImport ("kernel32.dll", SetLastError = true)]
  575. static extern bool GetConsoleCursorInfo (IntPtr hConsoleOutput, out ConsoleCursorInfo lpConsoleCursorInfo);
  576. [DllImport ("kernel32.dll")]
  577. static extern bool GetConsoleMode (IntPtr hConsoleHandle, out uint lpMode);
  578. [DllImport ("kernel32.dll")]
  579. static extern bool SetConsoleMode (IntPtr hConsoleHandle, uint dwMode);
  580. [DllImport ("kernel32.dll", SetLastError = true)]
  581. static extern IntPtr CreateConsoleScreenBuffer (
  582. DesiredAccess dwDesiredAccess,
  583. ShareMode dwShareMode,
  584. IntPtr secutiryAttributes,
  585. uint flags,
  586. IntPtr screenBufferData
  587. );
  588. internal static IntPtr INVALID_HANDLE_VALUE = new IntPtr (-1);
  589. [DllImport ("kernel32.dll", SetLastError = true)]
  590. static extern bool SetConsoleActiveScreenBuffer (IntPtr Handle);
  591. [DllImport ("kernel32.dll", SetLastError = true)]
  592. static extern bool GetNumberOfConsoleInputEvents (IntPtr handle, out uint lpcNumberOfEvents);
  593. public InputRecord [] ReadConsoleInput ()
  594. {
  595. const int bufferSize = 1;
  596. var pRecord = Marshal.AllocHGlobal (Marshal.SizeOf<InputRecord> () * bufferSize);
  597. try {
  598. ReadConsoleInput (_inputHandle, pRecord, bufferSize,
  599. out var numberEventsRead);
  600. return numberEventsRead == 0
  601. ? null
  602. : new [] { Marshal.PtrToStructure<InputRecord> (pRecord) };
  603. } catch (Exception) {
  604. return null;
  605. } finally {
  606. Marshal.FreeHGlobal (pRecord);
  607. }
  608. }
  609. #if false // Not needed on the constructor. Perhaps could be used on resizing. To study.
  610. [DllImport ("kernel32.dll", ExactSpelling = true)]
  611. static extern IntPtr GetConsoleWindow ();
  612. [DllImport ("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  613. static extern bool ShowWindow (IntPtr hWnd, int nCmdShow);
  614. public const int HIDE = 0;
  615. public const int MAXIMIZE = 3;
  616. public const int MINIMIZE = 6;
  617. public const int RESTORE = 9;
  618. internal void ShowWindow (int state)
  619. {
  620. IntPtr thisConsole = GetConsoleWindow ();
  621. ShowWindow (thisConsole, state);
  622. }
  623. #endif
  624. // See: https://github.com/gui-cs/Terminal.Gui/issues/357
  625. [StructLayout (LayoutKind.Sequential)]
  626. public struct CONSOLE_SCREEN_BUFFER_INFOEX {
  627. public uint cbSize;
  628. public Coord dwSize;
  629. public Coord dwCursorPosition;
  630. public ushort wAttributes;
  631. public SmallRect srWindow;
  632. public Coord dwMaximumWindowSize;
  633. public ushort wPopupAttributes;
  634. public bool bFullscreenSupported;
  635. [MarshalAs (UnmanagedType.ByValArray, SizeConst = 16)]
  636. public COLORREF [] ColorTable;
  637. }
  638. [StructLayout (LayoutKind.Explicit, Size = 4)]
  639. public struct COLORREF {
  640. public COLORREF (byte r, byte g, byte b)
  641. {
  642. Value = 0;
  643. R = r;
  644. G = g;
  645. B = b;
  646. }
  647. public COLORREF (uint value)
  648. {
  649. R = 0;
  650. G = 0;
  651. B = 0;
  652. Value = value & 0x00FFFFFF;
  653. }
  654. [FieldOffset (0)]
  655. public byte R;
  656. [FieldOffset (1)]
  657. public byte G;
  658. [FieldOffset (2)]
  659. public byte B;
  660. [FieldOffset (0)]
  661. public uint Value;
  662. }
  663. [DllImport ("kernel32.dll", SetLastError = true)]
  664. static extern bool GetConsoleScreenBufferInfoEx (IntPtr hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX csbi);
  665. [DllImport ("kernel32.dll", SetLastError = true)]
  666. static extern bool SetConsoleScreenBufferInfoEx (IntPtr hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX ConsoleScreenBufferInfo);
  667. [DllImport ("kernel32.dll", SetLastError = true)]
  668. static extern bool SetConsoleWindowInfo (
  669. IntPtr hConsoleOutput,
  670. bool bAbsolute,
  671. [In] ref SmallRect lpConsoleWindow);
  672. [DllImport ("kernel32.dll", SetLastError = true)]
  673. static extern Coord GetLargestConsoleWindowSize (
  674. IntPtr hConsoleOutput);
  675. }
  676. internal class WindowsDriver : ConsoleDriver {
  677. WindowsConsole.ExtendedCharInfo [] _outputBuffer;
  678. WindowsConsole.SmallRect _damageRegion;
  679. public WindowsConsole WinConsole { get; private set; }
  680. public override bool SupportsTrueColor => RunningUnitTests || (Environment.OSVersion.Version.Build >= 14931 && _isWindowsTerminal);
  681. readonly bool _isWindowsTerminal = false;
  682. WindowsMainLoop _mainLoopDriver = null;
  683. public WindowsDriver ()
  684. {
  685. if (Environment.OSVersion.Platform == PlatformID.Win32NT) {
  686. WinConsole = new WindowsConsole ();
  687. // otherwise we're probably running in unit tests
  688. Clipboard = new WindowsClipboard ();
  689. } else {
  690. Clipboard = new FakeDriver.FakeClipboard ();
  691. }
  692. // TODO: if some other Windows-based terminal supports true color, update this logic to not
  693. // force 16color mode (.e.g ConEmu which really doesn't work well at all).
  694. _isWindowsTerminal = Environment.GetEnvironmentVariable ("WT_SESSION") != null;
  695. if (!_isWindowsTerminal) {
  696. Force16Colors = true;
  697. }
  698. }
  699. internal override MainLoop Init ()
  700. {
  701. _mainLoopDriver = new WindowsMainLoop (this);
  702. if (!RunningUnitTests) {
  703. try {
  704. if (WinConsole != null) {
  705. // BUGBUG: The results from GetConsoleOutputWindow are incorrect when called from Init.
  706. // Our thread in WindowsMainLoop.CheckWin will get the correct results. See #if HACK_CHECK_WINCHANGED
  707. var winSize = WinConsole.GetConsoleOutputWindow (out Point pos);
  708. Cols = winSize.Width;
  709. Rows = winSize.Height;
  710. }
  711. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  712. if (_isWindowsTerminal) {
  713. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  714. }
  715. } catch (Win32Exception e) {
  716. // We are being run in an environment that does not support a console
  717. // such as a unit test, or a pipe.
  718. Debug.WriteLine ($"Likely running unit tests. Setting WinConsole to null so we can test it elsewhere. Exception: {e}");
  719. WinConsole = null;
  720. }
  721. }
  722. CurrentAttribute = new Attribute (Color.White, Color.Black);
  723. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  724. Clip = new Rect (0, 0, Cols, Rows);
  725. _damageRegion = new WindowsConsole.SmallRect () {
  726. Top = 0,
  727. Left = 0,
  728. Bottom = (short)Rows,
  729. Right = (short)Cols
  730. };
  731. ClearContents ();
  732. #if HACK_CHECK_WINCHANGED
  733. _mainLoopDriver.WinChanged = ChangeWin;
  734. #endif
  735. return new MainLoop (_mainLoopDriver);
  736. }
  737. #if HACK_CHECK_WINCHANGED
  738. private void ChangeWin (Object s, SizeChangedEventArgs e)
  739. {
  740. var w = e.Size.Width;
  741. if (w == Cols - 3 && e.Size.Height < Rows) {
  742. w += 3;
  743. }
  744. Left = 0;
  745. Top = 0;
  746. Cols = e.Size.Width;
  747. Rows = e.Size.Height;
  748. if (!RunningUnitTests) {
  749. var newSize = WinConsole.SetConsoleWindow (
  750. (short)Math.Max (w, 16), (short)Math.Max (e.Size.Height, 0));
  751. Cols = newSize.Width;
  752. Rows = newSize.Height;
  753. }
  754. ResizeScreen ();
  755. ClearContents ();
  756. OnSizeChanged (new SizeChangedEventArgs (new Size (Cols, Rows)));
  757. }
  758. #endif
  759. KeyCode MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  760. {
  761. var keyInfo = keyInfoEx.ConsoleKeyInfo;
  762. switch (keyInfo.Key) {
  763. case ConsoleKey.D0:
  764. case ConsoleKey.D1:
  765. case ConsoleKey.D2:
  766. case ConsoleKey.D3:
  767. case ConsoleKey.D4:
  768. case ConsoleKey.D5:
  769. case ConsoleKey.D6:
  770. case ConsoleKey.D7:
  771. case ConsoleKey.D8:
  772. case ConsoleKey.D9:
  773. case ConsoleKey.NumPad0:
  774. case ConsoleKey.NumPad1:
  775. case ConsoleKey.NumPad2:
  776. case ConsoleKey.NumPad3:
  777. case ConsoleKey.NumPad4:
  778. case ConsoleKey.NumPad5:
  779. case ConsoleKey.NumPad6:
  780. case ConsoleKey.NumPad7:
  781. case ConsoleKey.NumPad8:
  782. case ConsoleKey.NumPad9:
  783. case ConsoleKey.Oem1:
  784. case ConsoleKey.Oem2:
  785. case ConsoleKey.Oem3:
  786. case ConsoleKey.Oem4:
  787. case ConsoleKey.Oem5:
  788. case ConsoleKey.Oem6:
  789. case ConsoleKey.Oem7:
  790. case ConsoleKey.Oem8:
  791. case ConsoleKey.Oem102:
  792. case ConsoleKey.Multiply:
  793. case ConsoleKey.Add:
  794. case ConsoleKey.Separator:
  795. case ConsoleKey.Subtract:
  796. case ConsoleKey.Decimal:
  797. case ConsoleKey.Divide:
  798. case ConsoleKey.OemPeriod:
  799. case ConsoleKey.OemComma:
  800. case ConsoleKey.OemPlus:
  801. case ConsoleKey.OemMinus:
  802. // These virtual key codes are mapped differently depending on the keyboard layout in use.
  803. // We use the Win32 API to map them to the correct character.
  804. var mapResult = MapVKtoChar ((VK)keyInfo.Key);
  805. if (mapResult == 0) {
  806. // There is no mapping - this should not happen
  807. Debug.Assert (mapResult != 0, $@"Unable to map the virtual key code {keyInfo.Key}.");
  808. return KeyCode.Null;
  809. }
  810. // An un-shifted character value is in the low order word of the return value.
  811. var mappedChar = (char)(mapResult & 0x0000FFFF);
  812. if (keyInfo.KeyChar == 0) {
  813. // If the keyChar is 0, keyInfo.Key value is not a printable character.
  814. // Dead keys (diacritics) are indicated by setting the top bit of the return value.
  815. if ((mapResult & 0x80000000) != 0) {
  816. // Dead key (e.g. Oem2 '~'/'^' on POR keyboard)
  817. // Option 1: Throw it out.
  818. // - Apps will never see the dead keys
  819. // - If user presses a key that can be combined with the dead key ('a'), the right thing happens (app will see 'ã').
  820. // - NOTE: With Dead Keys, KeyDown != KeyUp. The KeyUp event will have just the base char ('a').
  821. // - If user presses dead key again, the right thing happens (app will see `~~`)
  822. // - This is what Notepad etc... appear to do
  823. // Option 2: Expand the API to indicate the KeyCode is a dead key
  824. // - Enables apps to do their own dead key processing
  825. // - Adds complexity; no dev has asked for this (yet).
  826. // We choose Option 1 for now.
  827. return KeyCode.Null;
  828. // Note: Ctrl-Deadkey (like Oem3 '`'/'~` on ENG) can't be supported.
  829. // Sadly, the charVal is just the deadkey and subsequent key events do not contain
  830. // any info that the previous event was a deadkey.
  831. // Note WT does not support Ctrl-Deadkey either.
  832. }
  833. if (keyInfo.Modifiers != 0) {
  834. // These Oem keys have well defined chars. We ensure the representative char is used.
  835. // If we don't do this, then on some keyboard layouts the wrong char is
  836. // returned (e.g. on ENG OemPlus un-shifted is =, not +). This is important
  837. // for key persistence ("Ctrl++" vs. "Ctrl+=").
  838. mappedChar = keyInfo.Key switch {
  839. ConsoleKey.OemPeriod => '.',
  840. ConsoleKey.OemComma => ',',
  841. ConsoleKey.OemPlus => '+',
  842. ConsoleKey.OemMinus => '-',
  843. _ => mappedChar
  844. };
  845. }
  846. // Return the mappedChar with they modifiers. Because mappedChar is un-shifted, if Shift was down
  847. // we should keep it
  848. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)mappedChar);
  849. } else {
  850. // KeyChar is printable
  851. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) && keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)) {
  852. // AltGr support - AltGr is equivalent to Ctrl+Alt - the correct char is in KeyChar
  853. return (KeyCode)keyInfo.KeyChar;
  854. }
  855. if (keyInfo.Modifiers != ConsoleModifiers.Shift) {
  856. // If Shift wasn't down we don't need to do anything but return the mappedChar
  857. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(mappedChar));
  858. }
  859. // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "Ç")
  860. // and passing on Shift would be redundant.
  861. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  862. }
  863. }
  864. // A..Z are special cased:
  865. // - Alone, they represent lowercase a...z
  866. // - With ShiftMask they are A..Z
  867. // - If CapsLock is on the above is reversed.
  868. // - If Alt and/or Ctrl are present, treat as upper case
  869. if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z) {
  870. if (keyInfo.KeyChar == 0) {
  871. // KeyChar is not printable - possibly an AltGr key?
  872. // AltGr support - AltGr is equivalent to Ctrl+Alt
  873. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) && keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)) {
  874. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  875. }
  876. }
  877. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)) {
  878. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  879. }
  880. if (((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock))) {
  881. // If (ShiftMask is on and CapsLock is off) or (ShiftMask is off and CapsLock is on) add the ShiftMask
  882. if (char.IsUpper (keyInfo.KeyChar)) {
  883. return (KeyCode)((uint)keyInfo.Key) | KeyCode.ShiftMask;
  884. }
  885. }
  886. return (KeyCode)(uint)keyInfo.KeyChar;
  887. }
  888. // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC
  889. if (Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key)) {
  890. // If the key is JUST a modifier, return it as just that key
  891. if (keyInfo.Key == (ConsoleKey)VK.SHIFT) { // Shift 16
  892. return KeyCode.ShiftMask;
  893. }
  894. if (keyInfo.Key == (ConsoleKey)VK.CONTROL) { // Ctrl 17
  895. return KeyCode.CtrlMask;
  896. }
  897. if (keyInfo.Key == (ConsoleKey)VK.MENU) { // Alt 18
  898. return KeyCode.AltMask;
  899. }
  900. if (keyInfo.KeyChar == 0) {
  901. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(keyInfo.KeyChar));
  902. } else if (keyInfo.Key != ConsoleKey.None) {
  903. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(keyInfo.KeyChar));
  904. } else {
  905. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)(keyInfo.KeyChar));
  906. }
  907. }
  908. // Handle control keys (e.g. CursorUp)
  909. if (Enum.IsDefined (typeof (KeyCode), ((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint))) {
  910. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint));
  911. }
  912. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(keyInfo.KeyChar));
  913. }
  914. internal void ProcessInput (WindowsConsole.InputRecord inputEvent)
  915. {
  916. switch (inputEvent.EventType) {
  917. case WindowsConsole.EventType.Key:
  918. if (inputEvent.KeyEvent.wVirtualKeyCode == (VK)ConsoleKey.Packet) {
  919. // Used to pass Unicode characters as if they were keystrokes.
  920. // The VK_PACKET key is the low word of a 32-bit
  921. // Virtual Key value used for non-keyboard input methods.
  922. inputEvent.KeyEvent = FromVKPacketToKeyEventRecord (inputEvent.KeyEvent);
  923. }
  924. var keyInfo = ToConsoleKeyInfoEx (inputEvent.KeyEvent);
  925. //Debug.WriteLine ($"event: KBD: {GetKeyboardLayoutName()} {inputEvent.ToString ()} {keyInfo.ToString (keyInfo)}");
  926. var map = MapKey (keyInfo);
  927. if (map == KeyCode.Null) {
  928. break;
  929. }
  930. if (inputEvent.KeyEvent.bKeyDown) {
  931. // Avoid sending repeat key down events
  932. OnKeyDown (new Key (map));
  933. } else {
  934. OnKeyUp (new Key (map));
  935. }
  936. break;
  937. case WindowsConsole.EventType.Mouse:
  938. var me = ToDriverMouse (inputEvent.MouseEvent);
  939. OnMouseEvent (new MouseEventEventArgs (me));
  940. if (_processButtonClick) {
  941. OnMouseEvent (new MouseEventEventArgs (new MouseEvent () {
  942. X = me.X,
  943. Y = me.Y,
  944. Flags = ProcessButtonClick (inputEvent.MouseEvent)
  945. }));
  946. }
  947. break;
  948. case WindowsConsole.EventType.Focus:
  949. break;
  950. #if !HACK_CHECK_WINCHANGED
  951. case WindowsConsole.EventType.WindowBufferSize:
  952. Cols = inputEvent.WindowBufferSizeEvent._size.X;
  953. Rows = inputEvent.WindowBufferSizeEvent._size.Y;
  954. ResizeScreen ();
  955. ClearContents ();
  956. TerminalResized.Invoke ();
  957. break;
  958. #endif
  959. }
  960. }
  961. WindowsConsole.ButtonState? _lastMouseButtonPressed = null;
  962. bool _isButtonPressed = false;
  963. bool _isButtonReleased = false;
  964. bool _isButtonDoubleClicked = false;
  965. Point? _point;
  966. Point _pointMove;
  967. bool _isOneFingerDoubleClicked = false;
  968. bool _processButtonClick;
  969. MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  970. {
  971. MouseFlags mouseFlag = MouseFlags.AllEvents;
  972. //System.Diagnostics.Debug.WriteLine (
  973. // $"X:{mouseEvent.MousePosition.X};Y:{mouseEvent.MousePosition.Y};ButtonState:{mouseEvent.ButtonState};EventFlags:{mouseEvent.EventFlags}");
  974. if (_isButtonDoubleClicked || _isOneFingerDoubleClicked) {
  975. Application.MainLoop.AddIdle (() => {
  976. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  977. return false;
  978. });
  979. }
  980. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  981. // This will tell when a mouse button is pressed. When the button is released this event will
  982. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  983. // To map to the correct driver events we save the last pressed mouse button so we can
  984. // map to the correct clicked event.
  985. if ((_lastMouseButtonPressed != null || _isButtonReleased) && mouseEvent.ButtonState != 0) {
  986. _lastMouseButtonPressed = null;
  987. //isButtonPressed = false;
  988. _isButtonReleased = false;
  989. }
  990. var p = new Point () {
  991. X = mouseEvent.MousePosition.X,
  992. Y = mouseEvent.MousePosition.Y
  993. };
  994. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && _lastMouseButtonPressed == null && !_isButtonDoubleClicked) ||
  995. (_lastMouseButtonPressed == null && mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved) &&
  996. mouseEvent.ButtonState != 0 && !_isButtonReleased && !_isButtonDoubleClicked)) {
  997. switch (mouseEvent.ButtonState) {
  998. case WindowsConsole.ButtonState.Button1Pressed:
  999. mouseFlag = MouseFlags.Button1Pressed;
  1000. break;
  1001. case WindowsConsole.ButtonState.Button2Pressed:
  1002. mouseFlag = MouseFlags.Button2Pressed;
  1003. break;
  1004. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1005. mouseFlag = MouseFlags.Button3Pressed;
  1006. break;
  1007. }
  1008. if (_point == null) {
  1009. _point = p;
  1010. }
  1011. if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  1012. mouseFlag |= MouseFlags.ReportMousePosition;
  1013. _isButtonReleased = false;
  1014. _processButtonClick = false;
  1015. }
  1016. _lastMouseButtonPressed = mouseEvent.ButtonState;
  1017. _isButtonPressed = true;
  1018. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  1019. Application.MainLoop.AddIdle (() => {
  1020. Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseFlag));
  1021. return false;
  1022. });
  1023. }
  1024. } else if (_lastMouseButtonPressed != null && mouseEvent.EventFlags == 0
  1025. && !_isButtonReleased && !_isButtonDoubleClicked && !_isOneFingerDoubleClicked) {
  1026. switch (_lastMouseButtonPressed) {
  1027. case WindowsConsole.ButtonState.Button1Pressed:
  1028. mouseFlag = MouseFlags.Button1Released;
  1029. break;
  1030. case WindowsConsole.ButtonState.Button2Pressed:
  1031. mouseFlag = MouseFlags.Button2Released;
  1032. break;
  1033. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1034. mouseFlag = MouseFlags.Button3Released;
  1035. break;
  1036. }
  1037. _isButtonPressed = false;
  1038. _isButtonReleased = true;
  1039. if (_point != null && (((Point)_point).X == mouseEvent.MousePosition.X && ((Point)_point).Y == mouseEvent.MousePosition.Y)) {
  1040. _processButtonClick = true;
  1041. } else {
  1042. _point = null;
  1043. }
  1044. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  1045. && !_isOneFingerDoubleClicked && _isButtonReleased && p == _point) {
  1046. mouseFlag = ProcessButtonClick (mouseEvent);
  1047. } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
  1048. switch (mouseEvent.ButtonState) {
  1049. case WindowsConsole.ButtonState.Button1Pressed:
  1050. mouseFlag = MouseFlags.Button1DoubleClicked;
  1051. break;
  1052. case WindowsConsole.ButtonState.Button2Pressed:
  1053. mouseFlag = MouseFlags.Button2DoubleClicked;
  1054. break;
  1055. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1056. mouseFlag = MouseFlags.Button3DoubleClicked;
  1057. break;
  1058. }
  1059. _isButtonDoubleClicked = true;
  1060. } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && _isButtonDoubleClicked) {
  1061. switch (mouseEvent.ButtonState) {
  1062. case WindowsConsole.ButtonState.Button1Pressed:
  1063. mouseFlag = MouseFlags.Button1TripleClicked;
  1064. break;
  1065. case WindowsConsole.ButtonState.Button2Pressed:
  1066. mouseFlag = MouseFlags.Button2TripleClicked;
  1067. break;
  1068. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1069. mouseFlag = MouseFlags.Button3TripleClicked;
  1070. break;
  1071. }
  1072. _isButtonDoubleClicked = false;
  1073. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
  1074. switch ((int)mouseEvent.ButtonState) {
  1075. case int v when v > 0:
  1076. mouseFlag = MouseFlags.WheeledUp;
  1077. break;
  1078. case int v when v < 0:
  1079. mouseFlag = MouseFlags.WheeledDown;
  1080. break;
  1081. }
  1082. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled &&
  1083. mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed) {
  1084. switch ((int)mouseEvent.ButtonState) {
  1085. case int v when v > 0:
  1086. mouseFlag = MouseFlags.WheeledLeft;
  1087. break;
  1088. case int v when v < 0:
  1089. mouseFlag = MouseFlags.WheeledRight;
  1090. break;
  1091. }
  1092. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseHorizontalWheeled) {
  1093. switch ((int)mouseEvent.ButtonState) {
  1094. case int v when v < 0:
  1095. mouseFlag = MouseFlags.WheeledLeft;
  1096. break;
  1097. case int v when v > 0:
  1098. mouseFlag = MouseFlags.WheeledRight;
  1099. break;
  1100. }
  1101. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  1102. mouseFlag = MouseFlags.ReportMousePosition;
  1103. if (mouseEvent.MousePosition.X != _pointMove.X || mouseEvent.MousePosition.Y != _pointMove.Y) {
  1104. _pointMove = new Point (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y);
  1105. }
  1106. } else if (mouseEvent.ButtonState == 0 && mouseEvent.EventFlags == 0) {
  1107. mouseFlag = 0;
  1108. }
  1109. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  1110. //System.Diagnostics.Debug.WriteLine (
  1111. // $"point.X:{(point != null ? ((Point)point).X : -1)};point.Y:{(point != null ? ((Point)point).Y : -1)}");
  1112. return new MouseEvent () {
  1113. X = mouseEvent.MousePosition.X,
  1114. Y = mouseEvent.MousePosition.Y,
  1115. Flags = mouseFlag
  1116. };
  1117. }
  1118. MouseFlags ProcessButtonClick (WindowsConsole.MouseEventRecord mouseEvent)
  1119. {
  1120. MouseFlags mouseFlag = 0;
  1121. switch (_lastMouseButtonPressed) {
  1122. case WindowsConsole.ButtonState.Button1Pressed:
  1123. mouseFlag = MouseFlags.Button1Clicked;
  1124. break;
  1125. case WindowsConsole.ButtonState.Button2Pressed:
  1126. mouseFlag = MouseFlags.Button2Clicked;
  1127. break;
  1128. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1129. mouseFlag = MouseFlags.Button3Clicked;
  1130. break;
  1131. }
  1132. _point = new Point () {
  1133. X = mouseEvent.MousePosition.X,
  1134. Y = mouseEvent.MousePosition.Y
  1135. };
  1136. _lastMouseButtonPressed = null;
  1137. _isButtonReleased = false;
  1138. _processButtonClick = false;
  1139. _point = null;
  1140. return mouseFlag;
  1141. }
  1142. async Task ProcessButtonDoubleClickedAsync ()
  1143. {
  1144. await Task.Delay (300);
  1145. _isButtonDoubleClicked = false;
  1146. _isOneFingerDoubleClicked = false;
  1147. //buttonPressedCount = 0;
  1148. }
  1149. async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag)
  1150. {
  1151. while (_isButtonPressed) {
  1152. await Task.Delay (100);
  1153. var me = new MouseEvent () {
  1154. X = _pointMove.X,
  1155. Y = _pointMove.Y,
  1156. Flags = mouseFlag
  1157. };
  1158. var view = Application.WantContinuousButtonPressedView;
  1159. if (view == null) {
  1160. break;
  1161. }
  1162. if (_isButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  1163. Application.Invoke (() => OnMouseEvent (new MouseEventEventArgs (me)));
  1164. }
  1165. }
  1166. }
  1167. static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  1168. {
  1169. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
  1170. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed)) {
  1171. mouseFlag |= MouseFlags.ButtonCtrl;
  1172. }
  1173. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed)) {
  1174. mouseFlag |= MouseFlags.ButtonShift;
  1175. }
  1176. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1177. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed)) {
  1178. mouseFlag |= MouseFlags.ButtonAlt;
  1179. }
  1180. return mouseFlag;
  1181. }
  1182. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  1183. {
  1184. var state = keyEvent.dwControlKeyState;
  1185. var shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  1186. var alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  1187. var control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  1188. var capslock = (state & WindowsConsole.ControlKeyState.CapslockOn) != 0;
  1189. var numlock = (state & WindowsConsole.ControlKeyState.NumlockOn) != 0;
  1190. var scrolllock = (state & WindowsConsole.ControlKeyState.ScrolllockOn) != 0;
  1191. var cki = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  1192. return new WindowsConsole.ConsoleKeyInfoEx (cki, capslock, numlock, scrolllock);
  1193. }
  1194. public WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent)
  1195. {
  1196. if (keyEvent.wVirtualKeyCode != (VK)ConsoleKey.Packet) {
  1197. return keyEvent;
  1198. }
  1199. var mod = new ConsoleModifiers ();
  1200. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed)) {
  1201. mod |= ConsoleModifiers.Shift;
  1202. }
  1203. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1204. keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed)) {
  1205. mod |= ConsoleModifiers.Alt;
  1206. }
  1207. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed) ||
  1208. keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed)) {
  1209. mod |= ConsoleModifiers.Control;
  1210. }
  1211. var cKeyInfo = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode,
  1212. mod.HasFlag (ConsoleModifiers.Shift), mod.HasFlag (ConsoleModifiers.Alt), mod.HasFlag (ConsoleModifiers.Control));
  1213. cKeyInfo = DecodeVKPacketToKConsoleKeyInfo (cKeyInfo);
  1214. var scanCode = GetScanCodeFromConsoleKeyInfo (cKeyInfo);
  1215. return new WindowsConsole.KeyEventRecord {
  1216. UnicodeChar = cKeyInfo.KeyChar,
  1217. bKeyDown = keyEvent.bKeyDown,
  1218. dwControlKeyState = keyEvent.dwControlKeyState,
  1219. wRepeatCount = keyEvent.wRepeatCount,
  1220. wVirtualKeyCode = (VK)cKeyInfo.Key,
  1221. wVirtualScanCode = (ushort)scanCode
  1222. };
  1223. }
  1224. public override bool IsRuneSupported (Rune rune)
  1225. {
  1226. return base.IsRuneSupported (rune) && rune.IsBmp;
  1227. }
  1228. void ResizeScreen ()
  1229. {
  1230. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  1231. Clip = new Rect (0, 0, Cols, Rows);
  1232. _damageRegion = new WindowsConsole.SmallRect () {
  1233. Top = 0,
  1234. Left = 0,
  1235. Bottom = (short)Rows,
  1236. Right = (short)Cols
  1237. };
  1238. _dirtyLines = new bool [Rows];
  1239. WinConsole?.ForceRefreshCursorVisibility ();
  1240. }
  1241. public override void UpdateScreen ()
  1242. {
  1243. var windowSize = WinConsole?.GetConsoleBufferWindow (out var _) ?? new Size (Cols, Rows);
  1244. if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows)) {
  1245. return;
  1246. }
  1247. var bufferCoords = new WindowsConsole.Coord () {
  1248. X = (short)Clip.Width,
  1249. Y = (short)Clip.Height
  1250. };
  1251. for (int row = 0; row < Rows; row++) {
  1252. if (!_dirtyLines [row]) {
  1253. continue;
  1254. }
  1255. _dirtyLines [row] = false;
  1256. for (int col = 0; col < Cols; col++) {
  1257. int position = row * Cols + col;
  1258. _outputBuffer [position].Attribute = Contents [row, col].Attribute.GetValueOrDefault ();
  1259. if (Contents [row, col].IsDirty == false) {
  1260. _outputBuffer [position].Empty = true;
  1261. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  1262. continue;
  1263. }
  1264. _outputBuffer [position].Empty = false;
  1265. if (Contents [row, col].Rune.IsBmp) {
  1266. _outputBuffer [position].Char = (char)Contents [row, col].Rune.Value;
  1267. } else {
  1268. //_outputBuffer [position].Empty = true;
  1269. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  1270. if (Contents [row, col].Rune.GetColumns () > 1 && col + 1 < Cols) {
  1271. // TODO: This is a hack to deal with non-BMP and wide characters.
  1272. col++;
  1273. position = row * Cols + col;
  1274. _outputBuffer [position].Empty = false;
  1275. _outputBuffer [position].Char = ' ';
  1276. }
  1277. }
  1278. }
  1279. }
  1280. _damageRegion = new WindowsConsole.SmallRect () {
  1281. Top = 0,
  1282. Left = 0,
  1283. Bottom = (short)Rows,
  1284. Right = (short)Cols
  1285. };
  1286. if (!RunningUnitTests && WinConsole != null && !WinConsole.WriteToConsole (new Size (Cols, Rows), _outputBuffer, bufferCoords, _damageRegion, Force16Colors)) {
  1287. var err = Marshal.GetLastWin32Error ();
  1288. if (err != 0) {
  1289. throw new System.ComponentModel.Win32Exception (err);
  1290. }
  1291. }
  1292. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  1293. }
  1294. public override void Refresh ()
  1295. {
  1296. UpdateScreen ();
  1297. WinConsole?.SetInitialCursorVisibility ();
  1298. UpdateCursor ();
  1299. }
  1300. CursorVisibility _cachedCursorVisibility;
  1301. public override void UpdateCursor ()
  1302. {
  1303. if (Col < 0 || Row < 0 || Col > Cols || Row > Rows) {
  1304. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1305. _cachedCursorVisibility = cursorVisibility;
  1306. SetCursorVisibility (CursorVisibility.Invisible);
  1307. return;
  1308. }
  1309. SetCursorVisibility (_cachedCursorVisibility);
  1310. var position = new WindowsConsole.Coord () {
  1311. X = (short)Col,
  1312. Y = (short)Row
  1313. };
  1314. WinConsole?.SetCursorPosition (position);
  1315. }
  1316. /// <inheritdoc/>
  1317. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1318. {
  1319. if (WinConsole != null) {
  1320. return WinConsole.GetCursorVisibility (out visibility);
  1321. }
  1322. visibility = _cachedCursorVisibility;
  1323. return true;
  1324. }
  1325. /// <inheritdoc/>
  1326. public override bool SetCursorVisibility (CursorVisibility visibility)
  1327. {
  1328. _cachedCursorVisibility = visibility;
  1329. return WinConsole == null || WinConsole.SetCursorVisibility (visibility);
  1330. }
  1331. /// <inheritdoc/>
  1332. public override bool EnsureCursorVisibility ()
  1333. {
  1334. return WinConsole == null || WinConsole.EnsureCursorVisibility ();
  1335. }
  1336. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  1337. {
  1338. WindowsConsole.InputRecord input = new WindowsConsole.InputRecord {
  1339. EventType = WindowsConsole.EventType.Key
  1340. };
  1341. WindowsConsole.KeyEventRecord keyEvent = new WindowsConsole.KeyEventRecord {
  1342. bKeyDown = true
  1343. };
  1344. WindowsConsole.ControlKeyState controlKey = new WindowsConsole.ControlKeyState ();
  1345. if (shift) {
  1346. controlKey |= WindowsConsole.ControlKeyState.ShiftPressed;
  1347. keyEvent.UnicodeChar = '\0';
  1348. keyEvent.wVirtualKeyCode = VK.SHIFT;
  1349. }
  1350. if (alt) {
  1351. controlKey |= WindowsConsole.ControlKeyState.LeftAltPressed;
  1352. controlKey |= WindowsConsole.ControlKeyState.RightAltPressed;
  1353. keyEvent.UnicodeChar = '\0';
  1354. keyEvent.wVirtualKeyCode = VK.MENU;
  1355. }
  1356. if (control) {
  1357. controlKey |= WindowsConsole.ControlKeyState.LeftControlPressed;
  1358. controlKey |= WindowsConsole.ControlKeyState.RightControlPressed;
  1359. keyEvent.UnicodeChar = '\0';
  1360. keyEvent.wVirtualKeyCode = VK.CONTROL;
  1361. }
  1362. keyEvent.dwControlKeyState = controlKey;
  1363. input.KeyEvent = keyEvent;
  1364. if (shift || alt || control) {
  1365. ProcessInput (input);
  1366. }
  1367. keyEvent.UnicodeChar = keyChar;
  1368. //if ((uint)key < 255) {
  1369. // keyEvent.wVirtualKeyCode = (ushort)key;
  1370. //} else {
  1371. // keyEvent.wVirtualKeyCode = '\0';
  1372. //}
  1373. keyEvent.wVirtualKeyCode = (VK)key;
  1374. input.KeyEvent = keyEvent;
  1375. try {
  1376. ProcessInput (input);
  1377. } catch (OverflowException) { } finally {
  1378. keyEvent.bKeyDown = false;
  1379. input.KeyEvent = keyEvent;
  1380. ProcessInput (input);
  1381. }
  1382. }
  1383. internal override void End ()
  1384. {
  1385. if (_mainLoopDriver != null) {
  1386. #if HACK_CHECK_WINCHANGED
  1387. //_mainLoop.WinChanged -= ChangeWin;
  1388. #endif
  1389. }
  1390. _mainLoopDriver = null;
  1391. WinConsole?.Cleanup ();
  1392. WinConsole = null;
  1393. if (!RunningUnitTests && _isWindowsTerminal) {
  1394. // Disable alternative screen buffer.
  1395. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  1396. }
  1397. }
  1398. #region Not Implemented
  1399. public override void Suspend ()
  1400. {
  1401. throw new NotImplementedException ();
  1402. }
  1403. #endregion
  1404. }
  1405. /// <summary>
  1406. /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
  1407. /// only be used on Windows.
  1408. /// </summary>
  1409. /// <remarks>
  1410. /// This implementation is used for WindowsDriver.
  1411. /// </remarks>
  1412. internal class WindowsMainLoop : IMainLoopDriver {
  1413. readonly ManualResetEventSlim _eventReady = new ManualResetEventSlim (false);
  1414. readonly ManualResetEventSlim _waitForProbe = new ManualResetEventSlim (false);
  1415. MainLoop _mainLoop;
  1416. readonly ConsoleDriver _consoleDriver;
  1417. readonly WindowsConsole _winConsole;
  1418. CancellationTokenSource _eventReadyTokenSource = new CancellationTokenSource ();
  1419. CancellationTokenSource _inputHandlerTokenSource = new CancellationTokenSource ();
  1420. // The records that we keep fetching
  1421. readonly Queue<WindowsConsole.InputRecord []> _resultQueue = new Queue<WindowsConsole.InputRecord []> ();
  1422. /// <summary>
  1423. /// Invoked when the window is changed.
  1424. /// </summary>
  1425. public EventHandler<SizeChangedEventArgs> WinChanged;
  1426. public WindowsMainLoop (ConsoleDriver consoleDriver = null)
  1427. {
  1428. _consoleDriver = consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver));
  1429. _winConsole = ((WindowsDriver)consoleDriver).WinConsole;
  1430. }
  1431. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1432. {
  1433. _mainLoop = mainLoop;
  1434. Task.Run (WindowsInputHandler, _inputHandlerTokenSource.Token);
  1435. #if HACK_CHECK_WINCHANGED
  1436. Task.Run (CheckWinChange);
  1437. #endif
  1438. }
  1439. void WindowsInputHandler ()
  1440. {
  1441. while (_mainLoop != null) {
  1442. try {
  1443. if (!_inputHandlerTokenSource.IsCancellationRequested) {
  1444. _waitForProbe.Wait (_inputHandlerTokenSource.Token);
  1445. }
  1446. } catch (OperationCanceledException) {
  1447. return;
  1448. } finally {
  1449. _waitForProbe.Reset ();
  1450. }
  1451. if (_resultQueue?.Count == 0) {
  1452. _resultQueue.Enqueue (_winConsole.ReadConsoleInput ());
  1453. }
  1454. _eventReady.Set ();
  1455. }
  1456. }
  1457. #if HACK_CHECK_WINCHANGED
  1458. readonly ManualResetEventSlim _winChange = new ManualResetEventSlim (false);
  1459. bool _winChanged;
  1460. Size _windowSize;
  1461. void CheckWinChange ()
  1462. {
  1463. while (_mainLoop != null) {
  1464. _winChange.Wait ();
  1465. _winChange.Reset ();
  1466. // Check if the window size changed every half second.
  1467. // We do this to minimize the weird tearing seen on Windows when resizing the console
  1468. while (_mainLoop != null) {
  1469. Task.Delay (500).Wait ();
  1470. _windowSize = _winConsole.GetConsoleBufferWindow (out _);
  1471. if (_windowSize != Size.Empty && (_windowSize.Width != _consoleDriver.Cols
  1472. || _windowSize.Height != _consoleDriver.Rows)) {
  1473. break;
  1474. }
  1475. }
  1476. _winChanged = true;
  1477. _eventReady.Set ();
  1478. }
  1479. }
  1480. #endif
  1481. void IMainLoopDriver.Wakeup ()
  1482. {
  1483. _eventReady.Set ();
  1484. }
  1485. bool IMainLoopDriver.EventsPending ()
  1486. {
  1487. _waitForProbe.Set ();
  1488. #if HACK_CHECK_WINCHANGED
  1489. _winChange.Set ();
  1490. #endif
  1491. if (_mainLoop.CheckTimersAndIdleHandlers (out var waitTimeout)) {
  1492. return true;
  1493. }
  1494. try {
  1495. if (!_eventReadyTokenSource.IsCancellationRequested) {
  1496. // Note: ManualResetEventSlim.Wait will wait indefinitely if the timeout is -1. The timeout is -1 when there
  1497. // are no timers, but there IS an idle handler waiting.
  1498. _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token);
  1499. }
  1500. } catch (OperationCanceledException) {
  1501. return true;
  1502. } finally {
  1503. _eventReady.Reset ();
  1504. }
  1505. if (!_eventReadyTokenSource.IsCancellationRequested) {
  1506. #if HACK_CHECK_WINCHANGED
  1507. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _) || _winChanged;
  1508. #else
  1509. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _);
  1510. #endif
  1511. }
  1512. _eventReadyTokenSource.Dispose ();
  1513. _eventReadyTokenSource = new CancellationTokenSource ();
  1514. return true;
  1515. }
  1516. void IMainLoopDriver.Iteration ()
  1517. {
  1518. while (_resultQueue.Count > 0) {
  1519. var inputRecords = _resultQueue.Dequeue ();
  1520. if (inputRecords is { Length: > 0 }) {
  1521. ((WindowsDriver)_consoleDriver).ProcessInput (inputRecords [0]);
  1522. }
  1523. }
  1524. #if HACK_CHECK_WINCHANGED
  1525. if (_winChanged) {
  1526. _winChanged = false;
  1527. WinChanged?.Invoke (this, new SizeChangedEventArgs (_windowSize));
  1528. }
  1529. #endif
  1530. }
  1531. void IMainLoopDriver.TearDown ()
  1532. {
  1533. _inputHandlerTokenSource?.Cancel ();
  1534. _inputHandlerTokenSource?.Dispose ();
  1535. _eventReadyTokenSource?.Cancel ();
  1536. _eventReadyTokenSource?.Dispose ();
  1537. _eventReady?.Dispose ();
  1538. _resultQueue?.Clear ();
  1539. #if HACK_CHECK_WINCHANGED
  1540. _winChange?.Dispose ();
  1541. #endif
  1542. //_waitForProbe?.Dispose ();
  1543. _mainLoop = null;
  1544. }
  1545. }
  1546. class WindowsClipboard : ClipboardBase {
  1547. public WindowsClipboard ()
  1548. {
  1549. IsSupported = IsClipboardFormatAvailable (_cfUnicodeText);
  1550. }
  1551. public override bool IsSupported { get; }
  1552. protected override string GetClipboardDataImpl ()
  1553. {
  1554. try {
  1555. if (!OpenClipboard (IntPtr.Zero)) {
  1556. return string.Empty;
  1557. }
  1558. IntPtr handle = GetClipboardData (_cfUnicodeText);
  1559. if (handle == IntPtr.Zero) {
  1560. return string.Empty;
  1561. }
  1562. IntPtr pointer = IntPtr.Zero;
  1563. try {
  1564. pointer = GlobalLock (handle);
  1565. if (pointer == IntPtr.Zero) {
  1566. return string.Empty;
  1567. }
  1568. int size = GlobalSize (handle);
  1569. byte [] buff = new byte [size];
  1570. Marshal.Copy (pointer, buff, 0, size);
  1571. return System.Text.Encoding.Unicode.GetString (buff).TrimEnd ('\0');
  1572. } finally {
  1573. if (pointer != IntPtr.Zero) {
  1574. GlobalUnlock (handle);
  1575. }
  1576. }
  1577. } finally {
  1578. CloseClipboard ();
  1579. }
  1580. }
  1581. protected override void SetClipboardDataImpl (string text)
  1582. {
  1583. OpenClipboard ();
  1584. EmptyClipboard ();
  1585. IntPtr hGlobal = default;
  1586. try {
  1587. var bytes = (text.Length + 1) * 2;
  1588. hGlobal = Marshal.AllocHGlobal (bytes);
  1589. if (hGlobal == default) {
  1590. ThrowWin32 ();
  1591. }
  1592. var target = GlobalLock (hGlobal);
  1593. if (target == default) {
  1594. ThrowWin32 ();
  1595. }
  1596. try {
  1597. Marshal.Copy (text.ToCharArray (), 0, target, text.Length);
  1598. } finally {
  1599. GlobalUnlock (target);
  1600. }
  1601. if (SetClipboardData (_cfUnicodeText, hGlobal) == default) {
  1602. ThrowWin32 ();
  1603. }
  1604. hGlobal = default;
  1605. } finally {
  1606. if (hGlobal != default) {
  1607. Marshal.FreeHGlobal (hGlobal);
  1608. }
  1609. CloseClipboard ();
  1610. }
  1611. }
  1612. void OpenClipboard ()
  1613. {
  1614. var num = 10;
  1615. while (true) {
  1616. if (OpenClipboard (default)) {
  1617. break;
  1618. }
  1619. if (--num == 0) {
  1620. ThrowWin32 ();
  1621. }
  1622. Thread.Sleep (100);
  1623. }
  1624. }
  1625. const uint _cfUnicodeText = 13;
  1626. void ThrowWin32 ()
  1627. {
  1628. throw new Win32Exception (Marshal.GetLastWin32Error ());
  1629. }
  1630. [DllImport ("User32.dll", SetLastError = true)]
  1631. [return: MarshalAs (UnmanagedType.Bool)]
  1632. static extern bool IsClipboardFormatAvailable (uint format);
  1633. [DllImport ("kernel32.dll", SetLastError = true)]
  1634. static extern int GlobalSize (IntPtr handle);
  1635. [DllImport ("kernel32.dll", SetLastError = true)]
  1636. static extern IntPtr GlobalLock (IntPtr hMem);
  1637. [DllImport ("kernel32.dll", SetLastError = true)]
  1638. [return: MarshalAs (UnmanagedType.Bool)]
  1639. static extern bool GlobalUnlock (IntPtr hMem);
  1640. [DllImport ("user32.dll", SetLastError = true)]
  1641. [return: MarshalAs (UnmanagedType.Bool)]
  1642. static extern bool OpenClipboard (IntPtr hWndNewOwner);
  1643. [DllImport ("user32.dll", SetLastError = true)]
  1644. [return: MarshalAs (UnmanagedType.Bool)]
  1645. static extern bool CloseClipboard ();
  1646. [DllImport ("user32.dll", SetLastError = true)]
  1647. static extern IntPtr SetClipboardData (uint uFormat, IntPtr data);
  1648. [DllImport ("user32.dll")]
  1649. static extern bool EmptyClipboard ();
  1650. [DllImport ("user32.dll", SetLastError = true)]
  1651. static extern IntPtr GetClipboardData (uint uFormat);
  1652. }