WindowsDriver.cs 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955
  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.GetClosestNamedColor () | (int)info.Attribute.Background.GetClosestNamedColor () << 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 = _isWindowsTerminal = Environment.GetEnvironmentVariable ("WT_SESSION") != null ||
  695. Environment.GetEnvironmentVariable ("VSAPPIDNAME") != null;
  696. if (!_isWindowsTerminal) {
  697. Force16Colors = true;
  698. }
  699. }
  700. internal override MainLoop Init ()
  701. {
  702. _mainLoopDriver = new WindowsMainLoop (this);
  703. if (!RunningUnitTests) {
  704. try {
  705. if (WinConsole != null) {
  706. // BUGBUG: The results from GetConsoleOutputWindow are incorrect when called from Init.
  707. // Our thread in WindowsMainLoop.CheckWin will get the correct results. See #if HACK_CHECK_WINCHANGED
  708. var winSize = WinConsole.GetConsoleOutputWindow (out Point pos);
  709. Cols = winSize.Width;
  710. Rows = winSize.Height;
  711. }
  712. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  713. if (_isWindowsTerminal) {
  714. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  715. }
  716. } catch (Win32Exception e) {
  717. // We are being run in an environment that does not support a console
  718. // such as a unit test, or a pipe.
  719. Debug.WriteLine ($"Likely running unit tests. Setting WinConsole to null so we can test it elsewhere. Exception: {e}");
  720. WinConsole = null;
  721. }
  722. }
  723. CurrentAttribute = new Attribute (Color.White, Color.Black);
  724. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  725. Clip = new Rect (0, 0, Cols, Rows);
  726. _damageRegion = new WindowsConsole.SmallRect () {
  727. Top = 0,
  728. Left = 0,
  729. Bottom = (short)Rows,
  730. Right = (short)Cols
  731. };
  732. ClearContents ();
  733. #if HACK_CHECK_WINCHANGED
  734. _mainLoopDriver.WinChanged = ChangeWin;
  735. #endif
  736. return new MainLoop (_mainLoopDriver);
  737. }
  738. #if HACK_CHECK_WINCHANGED
  739. private void ChangeWin (Object s, SizeChangedEventArgs e)
  740. {
  741. var w = e.Size.Width;
  742. if (w == Cols - 3 && e.Size.Height < Rows) {
  743. w += 3;
  744. }
  745. Left = 0;
  746. Top = 0;
  747. Cols = e.Size.Width;
  748. Rows = e.Size.Height;
  749. if (!RunningUnitTests) {
  750. var newSize = WinConsole.SetConsoleWindow (
  751. (short)Math.Max (w, 16), (short)Math.Max (e.Size.Height, 0));
  752. Cols = newSize.Width;
  753. Rows = newSize.Height;
  754. }
  755. ResizeScreen ();
  756. ClearContents ();
  757. OnSizeChanged (new SizeChangedEventArgs (new Size (Cols, Rows)));
  758. }
  759. #endif
  760. KeyCode MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  761. {
  762. var keyInfo = keyInfoEx.ConsoleKeyInfo;
  763. switch (keyInfo.Key) {
  764. case ConsoleKey.D0:
  765. case ConsoleKey.D1:
  766. case ConsoleKey.D2:
  767. case ConsoleKey.D3:
  768. case ConsoleKey.D4:
  769. case ConsoleKey.D5:
  770. case ConsoleKey.D6:
  771. case ConsoleKey.D7:
  772. case ConsoleKey.D8:
  773. case ConsoleKey.D9:
  774. case ConsoleKey.NumPad0:
  775. case ConsoleKey.NumPad1:
  776. case ConsoleKey.NumPad2:
  777. case ConsoleKey.NumPad3:
  778. case ConsoleKey.NumPad4:
  779. case ConsoleKey.NumPad5:
  780. case ConsoleKey.NumPad6:
  781. case ConsoleKey.NumPad7:
  782. case ConsoleKey.NumPad8:
  783. case ConsoleKey.NumPad9:
  784. case ConsoleKey.Oem1:
  785. case ConsoleKey.Oem2:
  786. case ConsoleKey.Oem3:
  787. case ConsoleKey.Oem4:
  788. case ConsoleKey.Oem5:
  789. case ConsoleKey.Oem6:
  790. case ConsoleKey.Oem7:
  791. case ConsoleKey.Oem8:
  792. case ConsoleKey.Oem102:
  793. case ConsoleKey.Multiply:
  794. case ConsoleKey.Add:
  795. case ConsoleKey.Separator:
  796. case ConsoleKey.Subtract:
  797. case ConsoleKey.Decimal:
  798. case ConsoleKey.Divide:
  799. case ConsoleKey.OemPeriod:
  800. case ConsoleKey.OemComma:
  801. case ConsoleKey.OemPlus:
  802. case ConsoleKey.OemMinus:
  803. // These virtual key codes are mapped differently depending on the keyboard layout in use.
  804. // We use the Win32 API to map them to the correct character.
  805. var mapResult = MapVKtoChar ((VK)keyInfo.Key);
  806. if (mapResult == 0) {
  807. // There is no mapping - this should not happen
  808. Debug.Assert (mapResult != 0, $@"Unable to map the virtual key code {keyInfo.Key}.");
  809. return KeyCode.Null;
  810. }
  811. // An un-shifted character value is in the low order word of the return value.
  812. var mappedChar = (char)(mapResult & 0x0000FFFF);
  813. if (keyInfo.KeyChar == 0) {
  814. // If the keyChar is 0, keyInfo.Key value is not a printable character.
  815. // Dead keys (diacritics) are indicated by setting the top bit of the return value.
  816. if ((mapResult & 0x80000000) != 0) {
  817. // Dead key (e.g. Oem2 '~'/'^' on POR keyboard)
  818. // Option 1: Throw it out.
  819. // - Apps will never see the dead keys
  820. // - If user presses a key that can be combined with the dead key ('a'), the right thing happens (app will see 'ã').
  821. // - NOTE: With Dead Keys, KeyDown != KeyUp. The KeyUp event will have just the base char ('a').
  822. // - If user presses dead key again, the right thing happens (app will see `~~`)
  823. // - This is what Notepad etc... appear to do
  824. // Option 2: Expand the API to indicate the KeyCode is a dead key
  825. // - Enables apps to do their own dead key processing
  826. // - Adds complexity; no dev has asked for this (yet).
  827. // We choose Option 1 for now.
  828. return KeyCode.Null;
  829. // Note: Ctrl-Deadkey (like Oem3 '`'/'~` on ENG) can't be supported.
  830. // Sadly, the charVal is just the deadkey and subsequent key events do not contain
  831. // any info that the previous event was a deadkey.
  832. // Note WT does not support Ctrl-Deadkey either.
  833. }
  834. if (keyInfo.Modifiers != 0) {
  835. // These Oem keys have well defined chars. We ensure the representative char is used.
  836. // If we don't do this, then on some keyboard layouts the wrong char is
  837. // returned (e.g. on ENG OemPlus un-shifted is =, not +). This is important
  838. // for key persistence ("Ctrl++" vs. "Ctrl+=").
  839. mappedChar = keyInfo.Key switch {
  840. ConsoleKey.OemPeriod => '.',
  841. ConsoleKey.OemComma => ',',
  842. ConsoleKey.OemPlus => '+',
  843. ConsoleKey.OemMinus => '-',
  844. _ => mappedChar
  845. };
  846. }
  847. // Return the mappedChar with they modifiers. Because mappedChar is un-shifted, if Shift was down
  848. // we should keep it
  849. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)mappedChar);
  850. } else {
  851. // KeyChar is printable
  852. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) && keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)) {
  853. // AltGr support - AltGr is equivalent to Ctrl+Alt - the correct char is in KeyChar
  854. return (KeyCode)keyInfo.KeyChar;
  855. }
  856. if (keyInfo.Modifiers != ConsoleModifiers.Shift) {
  857. // If Shift wasn't down we don't need to do anything but return the mappedChar
  858. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(mappedChar));
  859. }
  860. // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "Ç")
  861. // and passing on Shift would be redundant.
  862. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  863. }
  864. }
  865. // A..Z are special cased:
  866. // - Alone, they represent lowercase a...z
  867. // - With ShiftMask they are A..Z
  868. // - If CapsLock is on the above is reversed.
  869. // - If Alt and/or Ctrl are present, treat as upper case
  870. if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z) {
  871. if (keyInfo.KeyChar == 0) {
  872. // KeyChar is not printable - possibly an AltGr key?
  873. // AltGr support - AltGr is equivalent to Ctrl+Alt
  874. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) && keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)) {
  875. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  876. }
  877. }
  878. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)) {
  879. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  880. }
  881. if (((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock))) {
  882. // If (ShiftMask is on and CapsLock is off) or (ShiftMask is off and CapsLock is on) add the ShiftMask
  883. if (char.IsUpper (keyInfo.KeyChar)) {
  884. return (KeyCode)((uint)keyInfo.Key) | KeyCode.ShiftMask;
  885. }
  886. }
  887. return (KeyCode)(uint)keyInfo.KeyChar;
  888. }
  889. // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC
  890. if (Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key)) {
  891. // If the key is JUST a modifier, return it as just that key
  892. if (keyInfo.Key == (ConsoleKey)VK.SHIFT) { // Shift 16
  893. return KeyCode.ShiftMask;
  894. }
  895. if (keyInfo.Key == (ConsoleKey)VK.CONTROL) { // Ctrl 17
  896. return KeyCode.CtrlMask;
  897. }
  898. if (keyInfo.Key == (ConsoleKey)VK.MENU) { // Alt 18
  899. return KeyCode.AltMask;
  900. }
  901. if (keyInfo.KeyChar == 0) {
  902. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(keyInfo.KeyChar));
  903. } else if (keyInfo.Key != ConsoleKey.None) {
  904. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(keyInfo.KeyChar));
  905. } else {
  906. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)(keyInfo.KeyChar));
  907. }
  908. }
  909. // Handle control keys (e.g. CursorUp)
  910. if (Enum.IsDefined (typeof (KeyCode), ((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint))) {
  911. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint));
  912. }
  913. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(keyInfo.KeyChar));
  914. }
  915. internal void ProcessInput (WindowsConsole.InputRecord inputEvent)
  916. {
  917. switch (inputEvent.EventType) {
  918. case WindowsConsole.EventType.Key:
  919. if (inputEvent.KeyEvent.wVirtualKeyCode == (VK)ConsoleKey.Packet) {
  920. // Used to pass Unicode characters as if they were keystrokes.
  921. // The VK_PACKET key is the low word of a 32-bit
  922. // Virtual Key value used for non-keyboard input methods.
  923. inputEvent.KeyEvent = FromVKPacketToKeyEventRecord (inputEvent.KeyEvent);
  924. }
  925. var keyInfo = ToConsoleKeyInfoEx (inputEvent.KeyEvent);
  926. //Debug.WriteLine ($"event: KBD: {GetKeyboardLayoutName()} {inputEvent.ToString ()} {keyInfo.ToString (keyInfo)}");
  927. var map = MapKey (keyInfo);
  928. if (map == KeyCode.Null) {
  929. break;
  930. }
  931. if (inputEvent.KeyEvent.bKeyDown) {
  932. // Avoid sending repeat key down events
  933. OnKeyDown (new Key (map));
  934. } else {
  935. OnKeyUp (new Key (map));
  936. }
  937. break;
  938. case WindowsConsole.EventType.Mouse:
  939. var me = ToDriverMouse (inputEvent.MouseEvent);
  940. OnMouseEvent (new MouseEventEventArgs (me));
  941. if (_processButtonClick) {
  942. OnMouseEvent (new MouseEventEventArgs (new MouseEvent () {
  943. X = me.X,
  944. Y = me.Y,
  945. Flags = ProcessButtonClick (inputEvent.MouseEvent)
  946. }));
  947. }
  948. break;
  949. case WindowsConsole.EventType.Focus:
  950. break;
  951. #if !HACK_CHECK_WINCHANGED
  952. case WindowsConsole.EventType.WindowBufferSize:
  953. Cols = inputEvent.WindowBufferSizeEvent._size.X;
  954. Rows = inputEvent.WindowBufferSizeEvent._size.Y;
  955. ResizeScreen ();
  956. ClearContents ();
  957. TerminalResized.Invoke ();
  958. break;
  959. #endif
  960. }
  961. }
  962. WindowsConsole.ButtonState? _lastMouseButtonPressed = null;
  963. bool _isButtonPressed = false;
  964. bool _isButtonReleased = false;
  965. bool _isButtonDoubleClicked = false;
  966. Point? _point;
  967. Point _pointMove;
  968. bool _isOneFingerDoubleClicked = false;
  969. bool _processButtonClick;
  970. MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  971. {
  972. MouseFlags mouseFlag = MouseFlags.AllEvents;
  973. //System.Diagnostics.Debug.WriteLine (
  974. // $"X:{mouseEvent.MousePosition.X};Y:{mouseEvent.MousePosition.Y};ButtonState:{mouseEvent.ButtonState};EventFlags:{mouseEvent.EventFlags}");
  975. if (_isButtonDoubleClicked || _isOneFingerDoubleClicked) {
  976. Application.MainLoop.AddIdle (() => {
  977. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  978. return false;
  979. });
  980. }
  981. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  982. // This will tell when a mouse button is pressed. When the button is released this event will
  983. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  984. // To map to the correct driver events we save the last pressed mouse button so we can
  985. // map to the correct clicked event.
  986. if ((_lastMouseButtonPressed != null || _isButtonReleased) && mouseEvent.ButtonState != 0) {
  987. _lastMouseButtonPressed = null;
  988. //isButtonPressed = false;
  989. _isButtonReleased = false;
  990. }
  991. var p = new Point () {
  992. X = mouseEvent.MousePosition.X,
  993. Y = mouseEvent.MousePosition.Y
  994. };
  995. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && _lastMouseButtonPressed == null && !_isButtonDoubleClicked) ||
  996. (_lastMouseButtonPressed == null && mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved) &&
  997. mouseEvent.ButtonState != 0 && !_isButtonReleased && !_isButtonDoubleClicked)) {
  998. switch (mouseEvent.ButtonState) {
  999. case WindowsConsole.ButtonState.Button1Pressed:
  1000. mouseFlag = MouseFlags.Button1Pressed;
  1001. break;
  1002. case WindowsConsole.ButtonState.Button2Pressed:
  1003. mouseFlag = MouseFlags.Button2Pressed;
  1004. break;
  1005. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1006. mouseFlag = MouseFlags.Button3Pressed;
  1007. break;
  1008. }
  1009. if (_point is null) {
  1010. _point = p;
  1011. }
  1012. if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved)) {
  1013. _pointMove = p;
  1014. mouseFlag |= MouseFlags.ReportMousePosition;
  1015. _isButtonReleased = false;
  1016. _processButtonClick = false;
  1017. }
  1018. _lastMouseButtonPressed = mouseEvent.ButtonState;
  1019. _isButtonPressed = true;
  1020. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  1021. Application.MainLoop.AddIdle (() => {
  1022. Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseFlag));
  1023. return false;
  1024. });
  1025. }
  1026. } else if (_lastMouseButtonPressed != null && mouseEvent.EventFlags == 0
  1027. && !_isButtonReleased && !_isButtonDoubleClicked && !_isOneFingerDoubleClicked) {
  1028. switch (_lastMouseButtonPressed) {
  1029. case WindowsConsole.ButtonState.Button1Pressed:
  1030. mouseFlag = MouseFlags.Button1Released;
  1031. break;
  1032. case WindowsConsole.ButtonState.Button2Pressed:
  1033. mouseFlag = MouseFlags.Button2Released;
  1034. break;
  1035. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1036. mouseFlag = MouseFlags.Button3Released;
  1037. break;
  1038. }
  1039. _isButtonPressed = false;
  1040. _isButtonReleased = true;
  1041. if (_point != null && (((Point)_point).X == mouseEvent.MousePosition.X && ((Point)_point).Y == mouseEvent.MousePosition.Y)) {
  1042. _processButtonClick = true;
  1043. } else {
  1044. _point = null;
  1045. }
  1046. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  1047. && !_isOneFingerDoubleClicked && _isButtonReleased && p == _point) {
  1048. mouseFlag = ProcessButtonClick (mouseEvent);
  1049. } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
  1050. switch (mouseEvent.ButtonState) {
  1051. case WindowsConsole.ButtonState.Button1Pressed:
  1052. mouseFlag = MouseFlags.Button1DoubleClicked;
  1053. break;
  1054. case WindowsConsole.ButtonState.Button2Pressed:
  1055. mouseFlag = MouseFlags.Button2DoubleClicked;
  1056. break;
  1057. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1058. mouseFlag = MouseFlags.Button3DoubleClicked;
  1059. break;
  1060. }
  1061. _isButtonDoubleClicked = true;
  1062. } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && _isButtonDoubleClicked) {
  1063. switch (mouseEvent.ButtonState) {
  1064. case WindowsConsole.ButtonState.Button1Pressed:
  1065. mouseFlag = MouseFlags.Button1TripleClicked;
  1066. break;
  1067. case WindowsConsole.ButtonState.Button2Pressed:
  1068. mouseFlag = MouseFlags.Button2TripleClicked;
  1069. break;
  1070. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1071. mouseFlag = MouseFlags.Button3TripleClicked;
  1072. break;
  1073. }
  1074. _isButtonDoubleClicked = false;
  1075. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
  1076. switch ((int)mouseEvent.ButtonState) {
  1077. case int v when v > 0:
  1078. mouseFlag = MouseFlags.WheeledUp;
  1079. break;
  1080. case int v when v < 0:
  1081. mouseFlag = MouseFlags.WheeledDown;
  1082. break;
  1083. }
  1084. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled &&
  1085. mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed) {
  1086. switch ((int)mouseEvent.ButtonState) {
  1087. case int v when v > 0:
  1088. mouseFlag = MouseFlags.WheeledLeft;
  1089. break;
  1090. case int v when v < 0:
  1091. mouseFlag = MouseFlags.WheeledRight;
  1092. break;
  1093. }
  1094. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseHorizontalWheeled) {
  1095. switch ((int)mouseEvent.ButtonState) {
  1096. case int v when v < 0:
  1097. mouseFlag = MouseFlags.WheeledLeft;
  1098. break;
  1099. case int v when v > 0:
  1100. mouseFlag = MouseFlags.WheeledRight;
  1101. break;
  1102. }
  1103. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  1104. mouseFlag = MouseFlags.ReportMousePosition;
  1105. if (mouseEvent.MousePosition.X != _pointMove.X || mouseEvent.MousePosition.Y != _pointMove.Y) {
  1106. _pointMove = new Point (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y);
  1107. }
  1108. } else if (mouseEvent.ButtonState == 0 && mouseEvent.EventFlags == 0) {
  1109. mouseFlag = 0;
  1110. }
  1111. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  1112. //System.Diagnostics.Debug.WriteLine (
  1113. // $"point.X:{(point != null ? ((Point)point).X : -1)};point.Y:{(point != null ? ((Point)point).Y : -1)}");
  1114. return new MouseEvent () {
  1115. X = mouseEvent.MousePosition.X,
  1116. Y = mouseEvent.MousePosition.Y,
  1117. Flags = mouseFlag
  1118. };
  1119. }
  1120. MouseFlags ProcessButtonClick (WindowsConsole.MouseEventRecord mouseEvent)
  1121. {
  1122. MouseFlags mouseFlag = 0;
  1123. switch (_lastMouseButtonPressed) {
  1124. case WindowsConsole.ButtonState.Button1Pressed:
  1125. mouseFlag = MouseFlags.Button1Clicked;
  1126. break;
  1127. case WindowsConsole.ButtonState.Button2Pressed:
  1128. mouseFlag = MouseFlags.Button2Clicked;
  1129. break;
  1130. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1131. mouseFlag = MouseFlags.Button3Clicked;
  1132. break;
  1133. }
  1134. _point = new Point () {
  1135. X = mouseEvent.MousePosition.X,
  1136. Y = mouseEvent.MousePosition.Y
  1137. };
  1138. _lastMouseButtonPressed = null;
  1139. _isButtonReleased = false;
  1140. _processButtonClick = false;
  1141. _point = null;
  1142. return mouseFlag;
  1143. }
  1144. async Task ProcessButtonDoubleClickedAsync ()
  1145. {
  1146. await Task.Delay (300);
  1147. _isButtonDoubleClicked = false;
  1148. _isOneFingerDoubleClicked = false;
  1149. //buttonPressedCount = 0;
  1150. }
  1151. async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag)
  1152. {
  1153. while (_isButtonPressed) {
  1154. await Task.Delay (100);
  1155. var me = new MouseEvent () {
  1156. X = _pointMove.X,
  1157. Y = _pointMove.Y,
  1158. Flags = mouseFlag
  1159. };
  1160. var view = Application.WantContinuousButtonPressedView;
  1161. if (view == null) {
  1162. break;
  1163. }
  1164. if (_isButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  1165. Application.Invoke (() => OnMouseEvent (new MouseEventEventArgs (me)));
  1166. }
  1167. }
  1168. }
  1169. static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  1170. {
  1171. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
  1172. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed)) {
  1173. mouseFlag |= MouseFlags.ButtonCtrl;
  1174. }
  1175. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed)) {
  1176. mouseFlag |= MouseFlags.ButtonShift;
  1177. }
  1178. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1179. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed)) {
  1180. mouseFlag |= MouseFlags.ButtonAlt;
  1181. }
  1182. return mouseFlag;
  1183. }
  1184. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  1185. {
  1186. var state = keyEvent.dwControlKeyState;
  1187. var shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  1188. var alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  1189. var control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  1190. var capslock = (state & WindowsConsole.ControlKeyState.CapslockOn) != 0;
  1191. var numlock = (state & WindowsConsole.ControlKeyState.NumlockOn) != 0;
  1192. var scrolllock = (state & WindowsConsole.ControlKeyState.ScrolllockOn) != 0;
  1193. var cki = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  1194. return new WindowsConsole.ConsoleKeyInfoEx (cki, capslock, numlock, scrolllock);
  1195. }
  1196. public WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent)
  1197. {
  1198. if (keyEvent.wVirtualKeyCode != (VK)ConsoleKey.Packet) {
  1199. return keyEvent;
  1200. }
  1201. var mod = new ConsoleModifiers ();
  1202. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed)) {
  1203. mod |= ConsoleModifiers.Shift;
  1204. }
  1205. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1206. keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed)) {
  1207. mod |= ConsoleModifiers.Alt;
  1208. }
  1209. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed) ||
  1210. keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed)) {
  1211. mod |= ConsoleModifiers.Control;
  1212. }
  1213. var cKeyInfo = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode,
  1214. mod.HasFlag (ConsoleModifiers.Shift), mod.HasFlag (ConsoleModifiers.Alt), mod.HasFlag (ConsoleModifiers.Control));
  1215. cKeyInfo = DecodeVKPacketToKConsoleKeyInfo (cKeyInfo);
  1216. var scanCode = GetScanCodeFromConsoleKeyInfo (cKeyInfo);
  1217. return new WindowsConsole.KeyEventRecord {
  1218. UnicodeChar = cKeyInfo.KeyChar,
  1219. bKeyDown = keyEvent.bKeyDown,
  1220. dwControlKeyState = keyEvent.dwControlKeyState,
  1221. wRepeatCount = keyEvent.wRepeatCount,
  1222. wVirtualKeyCode = (VK)cKeyInfo.Key,
  1223. wVirtualScanCode = (ushort)scanCode
  1224. };
  1225. }
  1226. public override bool IsRuneSupported (Rune rune)
  1227. {
  1228. return base.IsRuneSupported (rune) && rune.IsBmp;
  1229. }
  1230. void ResizeScreen ()
  1231. {
  1232. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  1233. Clip = new Rect (0, 0, Cols, Rows);
  1234. _damageRegion = new WindowsConsole.SmallRect () {
  1235. Top = 0,
  1236. Left = 0,
  1237. Bottom = (short)Rows,
  1238. Right = (short)Cols
  1239. };
  1240. _dirtyLines = new bool [Rows];
  1241. WinConsole?.ForceRefreshCursorVisibility ();
  1242. }
  1243. public override void UpdateScreen ()
  1244. {
  1245. var windowSize = WinConsole?.GetConsoleBufferWindow (out var _) ?? new Size (Cols, Rows);
  1246. if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows)) {
  1247. return;
  1248. }
  1249. var bufferCoords = new WindowsConsole.Coord () {
  1250. X = (short)Clip.Width,
  1251. Y = (short)Clip.Height
  1252. };
  1253. for (int row = 0; row < Rows; row++) {
  1254. if (!_dirtyLines [row]) {
  1255. continue;
  1256. }
  1257. _dirtyLines [row] = false;
  1258. for (int col = 0; col < Cols; col++) {
  1259. int position = row * Cols + col;
  1260. _outputBuffer [position].Attribute = Contents [row, col].Attribute.GetValueOrDefault ();
  1261. if (Contents [row, col].IsDirty == false) {
  1262. _outputBuffer [position].Empty = true;
  1263. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  1264. continue;
  1265. }
  1266. _outputBuffer [position].Empty = false;
  1267. if (Contents [row, col].Rune.IsBmp) {
  1268. _outputBuffer [position].Char = (char)Contents [row, col].Rune.Value;
  1269. } else {
  1270. //_outputBuffer [position].Empty = true;
  1271. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  1272. if (Contents [row, col].Rune.GetColumns () > 1 && col + 1 < Cols) {
  1273. // TODO: This is a hack to deal with non-BMP and wide characters.
  1274. col++;
  1275. position = row * Cols + col;
  1276. _outputBuffer [position].Empty = false;
  1277. _outputBuffer [position].Char = ' ';
  1278. }
  1279. }
  1280. }
  1281. }
  1282. _damageRegion = new WindowsConsole.SmallRect () {
  1283. Top = 0,
  1284. Left = 0,
  1285. Bottom = (short)Rows,
  1286. Right = (short)Cols
  1287. };
  1288. if (!RunningUnitTests && WinConsole != null && !WinConsole.WriteToConsole (new Size (Cols, Rows), _outputBuffer, bufferCoords, _damageRegion, Force16Colors)) {
  1289. var err = Marshal.GetLastWin32Error ();
  1290. if (err != 0) {
  1291. throw new System.ComponentModel.Win32Exception (err);
  1292. }
  1293. }
  1294. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  1295. }
  1296. public override void Refresh ()
  1297. {
  1298. UpdateScreen ();
  1299. WinConsole?.SetInitialCursorVisibility ();
  1300. UpdateCursor ();
  1301. }
  1302. CursorVisibility _cachedCursorVisibility;
  1303. public override void UpdateCursor ()
  1304. {
  1305. if (Col < 0 || Row < 0 || Col > Cols || Row > Rows) {
  1306. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1307. _cachedCursorVisibility = cursorVisibility;
  1308. SetCursorVisibility (CursorVisibility.Invisible);
  1309. return;
  1310. }
  1311. SetCursorVisibility (_cachedCursorVisibility);
  1312. var position = new WindowsConsole.Coord () {
  1313. X = (short)Col,
  1314. Y = (short)Row
  1315. };
  1316. WinConsole?.SetCursorPosition (position);
  1317. }
  1318. /// <inheritdoc/>
  1319. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1320. {
  1321. if (WinConsole != null) {
  1322. return WinConsole.GetCursorVisibility (out visibility);
  1323. }
  1324. visibility = _cachedCursorVisibility;
  1325. return true;
  1326. }
  1327. /// <inheritdoc/>
  1328. public override bool SetCursorVisibility (CursorVisibility visibility)
  1329. {
  1330. _cachedCursorVisibility = visibility;
  1331. return WinConsole == null || WinConsole.SetCursorVisibility (visibility);
  1332. }
  1333. /// <inheritdoc/>
  1334. public override bool EnsureCursorVisibility ()
  1335. {
  1336. return WinConsole == null || WinConsole.EnsureCursorVisibility ();
  1337. }
  1338. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  1339. {
  1340. WindowsConsole.InputRecord input = new WindowsConsole.InputRecord {
  1341. EventType = WindowsConsole.EventType.Key
  1342. };
  1343. WindowsConsole.KeyEventRecord keyEvent = new WindowsConsole.KeyEventRecord {
  1344. bKeyDown = true
  1345. };
  1346. WindowsConsole.ControlKeyState controlKey = new WindowsConsole.ControlKeyState ();
  1347. if (shift) {
  1348. controlKey |= WindowsConsole.ControlKeyState.ShiftPressed;
  1349. keyEvent.UnicodeChar = '\0';
  1350. keyEvent.wVirtualKeyCode = VK.SHIFT;
  1351. }
  1352. if (alt) {
  1353. controlKey |= WindowsConsole.ControlKeyState.LeftAltPressed;
  1354. controlKey |= WindowsConsole.ControlKeyState.RightAltPressed;
  1355. keyEvent.UnicodeChar = '\0';
  1356. keyEvent.wVirtualKeyCode = VK.MENU;
  1357. }
  1358. if (control) {
  1359. controlKey |= WindowsConsole.ControlKeyState.LeftControlPressed;
  1360. controlKey |= WindowsConsole.ControlKeyState.RightControlPressed;
  1361. keyEvent.UnicodeChar = '\0';
  1362. keyEvent.wVirtualKeyCode = VK.CONTROL;
  1363. }
  1364. keyEvent.dwControlKeyState = controlKey;
  1365. input.KeyEvent = keyEvent;
  1366. if (shift || alt || control) {
  1367. ProcessInput (input);
  1368. }
  1369. keyEvent.UnicodeChar = keyChar;
  1370. //if ((uint)key < 255) {
  1371. // keyEvent.wVirtualKeyCode = (ushort)key;
  1372. //} else {
  1373. // keyEvent.wVirtualKeyCode = '\0';
  1374. //}
  1375. keyEvent.wVirtualKeyCode = (VK)key;
  1376. input.KeyEvent = keyEvent;
  1377. try {
  1378. ProcessInput (input);
  1379. } catch (OverflowException) { } finally {
  1380. keyEvent.bKeyDown = false;
  1381. input.KeyEvent = keyEvent;
  1382. ProcessInput (input);
  1383. }
  1384. }
  1385. internal override void End ()
  1386. {
  1387. if (_mainLoopDriver != null) {
  1388. #if HACK_CHECK_WINCHANGED
  1389. //_mainLoop.WinChanged -= ChangeWin;
  1390. #endif
  1391. }
  1392. _mainLoopDriver = null;
  1393. WinConsole?.Cleanup ();
  1394. WinConsole = null;
  1395. if (!RunningUnitTests && _isWindowsTerminal) {
  1396. // Disable alternative screen buffer.
  1397. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  1398. }
  1399. }
  1400. #region Not Implemented
  1401. public override void Suspend ()
  1402. {
  1403. throw new NotImplementedException ();
  1404. }
  1405. #endregion
  1406. }
  1407. /// <summary>
  1408. /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
  1409. /// only be used on Windows.
  1410. /// </summary>
  1411. /// <remarks>
  1412. /// This implementation is used for WindowsDriver.
  1413. /// </remarks>
  1414. internal class WindowsMainLoop : IMainLoopDriver {
  1415. readonly ManualResetEventSlim _eventReady = new ManualResetEventSlim (false);
  1416. readonly ManualResetEventSlim _waitForProbe = new ManualResetEventSlim (false);
  1417. MainLoop _mainLoop;
  1418. readonly ConsoleDriver _consoleDriver;
  1419. readonly WindowsConsole _winConsole;
  1420. CancellationTokenSource _eventReadyTokenSource = new CancellationTokenSource ();
  1421. CancellationTokenSource _inputHandlerTokenSource = new CancellationTokenSource ();
  1422. // The records that we keep fetching
  1423. readonly Queue<WindowsConsole.InputRecord []> _resultQueue = new Queue<WindowsConsole.InputRecord []> ();
  1424. /// <summary>
  1425. /// Invoked when the window is changed.
  1426. /// </summary>
  1427. public EventHandler<SizeChangedEventArgs> WinChanged;
  1428. public WindowsMainLoop (ConsoleDriver consoleDriver = null)
  1429. {
  1430. _consoleDriver = consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver));
  1431. _winConsole = ((WindowsDriver)consoleDriver).WinConsole;
  1432. }
  1433. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1434. {
  1435. _mainLoop = mainLoop;
  1436. Task.Run (WindowsInputHandler, _inputHandlerTokenSource.Token);
  1437. #if HACK_CHECK_WINCHANGED
  1438. Task.Run (CheckWinChange);
  1439. #endif
  1440. }
  1441. void WindowsInputHandler ()
  1442. {
  1443. while (_mainLoop != null) {
  1444. try {
  1445. if (!_inputHandlerTokenSource.IsCancellationRequested) {
  1446. _waitForProbe.Wait (_inputHandlerTokenSource.Token);
  1447. }
  1448. } catch (OperationCanceledException) {
  1449. return;
  1450. } finally {
  1451. _waitForProbe.Reset ();
  1452. }
  1453. if (_resultQueue?.Count == 0) {
  1454. _resultQueue.Enqueue (_winConsole.ReadConsoleInput ());
  1455. }
  1456. _eventReady.Set ();
  1457. }
  1458. }
  1459. #if HACK_CHECK_WINCHANGED
  1460. readonly ManualResetEventSlim _winChange = new ManualResetEventSlim (false);
  1461. bool _winChanged;
  1462. Size _windowSize;
  1463. void CheckWinChange ()
  1464. {
  1465. while (_mainLoop != null) {
  1466. _winChange.Wait ();
  1467. _winChange.Reset ();
  1468. // Check if the window size changed every half second.
  1469. // We do this to minimize the weird tearing seen on Windows when resizing the console
  1470. while (_mainLoop != null) {
  1471. Task.Delay (500).Wait ();
  1472. _windowSize = _winConsole.GetConsoleBufferWindow (out _);
  1473. if (_windowSize != Size.Empty && (_windowSize.Width != _consoleDriver.Cols
  1474. || _windowSize.Height != _consoleDriver.Rows)) {
  1475. break;
  1476. }
  1477. }
  1478. _winChanged = true;
  1479. _eventReady.Set ();
  1480. }
  1481. }
  1482. #endif
  1483. void IMainLoopDriver.Wakeup ()
  1484. {
  1485. _eventReady.Set ();
  1486. }
  1487. bool IMainLoopDriver.EventsPending ()
  1488. {
  1489. _waitForProbe.Set ();
  1490. #if HACK_CHECK_WINCHANGED
  1491. _winChange.Set ();
  1492. #endif
  1493. if (_mainLoop.CheckTimersAndIdleHandlers (out var waitTimeout)) {
  1494. return true;
  1495. }
  1496. try {
  1497. if (!_eventReadyTokenSource.IsCancellationRequested) {
  1498. // Note: ManualResetEventSlim.Wait will wait indefinitely if the timeout is -1. The timeout is -1 when there
  1499. // are no timers, but there IS an idle handler waiting.
  1500. _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token);
  1501. }
  1502. } catch (OperationCanceledException) {
  1503. return true;
  1504. } finally {
  1505. _eventReady.Reset ();
  1506. }
  1507. if (!_eventReadyTokenSource.IsCancellationRequested) {
  1508. #if HACK_CHECK_WINCHANGED
  1509. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _) || _winChanged;
  1510. #else
  1511. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _);
  1512. #endif
  1513. }
  1514. _eventReadyTokenSource.Dispose ();
  1515. _eventReadyTokenSource = new CancellationTokenSource ();
  1516. return true;
  1517. }
  1518. void IMainLoopDriver.Iteration ()
  1519. {
  1520. while (_resultQueue.Count > 0) {
  1521. var inputRecords = _resultQueue.Dequeue ();
  1522. if (inputRecords is { Length: > 0 }) {
  1523. ((WindowsDriver)_consoleDriver).ProcessInput (inputRecords [0]);
  1524. }
  1525. }
  1526. #if HACK_CHECK_WINCHANGED
  1527. if (_winChanged) {
  1528. _winChanged = false;
  1529. WinChanged?.Invoke (this, new SizeChangedEventArgs (_windowSize));
  1530. }
  1531. #endif
  1532. }
  1533. void IMainLoopDriver.TearDown ()
  1534. {
  1535. _inputHandlerTokenSource?.Cancel ();
  1536. _inputHandlerTokenSource?.Dispose ();
  1537. _eventReadyTokenSource?.Cancel ();
  1538. _eventReadyTokenSource?.Dispose ();
  1539. _eventReady?.Dispose ();
  1540. _resultQueue?.Clear ();
  1541. #if HACK_CHECK_WINCHANGED
  1542. _winChange?.Dispose ();
  1543. #endif
  1544. //_waitForProbe?.Dispose ();
  1545. _mainLoop = null;
  1546. }
  1547. }
  1548. class WindowsClipboard : ClipboardBase {
  1549. public WindowsClipboard ()
  1550. {
  1551. IsSupported = IsClipboardFormatAvailable (_cfUnicodeText);
  1552. }
  1553. public override bool IsSupported { get; }
  1554. protected override string GetClipboardDataImpl ()
  1555. {
  1556. try {
  1557. if (!OpenClipboard (IntPtr.Zero)) {
  1558. return string.Empty;
  1559. }
  1560. IntPtr handle = GetClipboardData (_cfUnicodeText);
  1561. if (handle == IntPtr.Zero) {
  1562. return string.Empty;
  1563. }
  1564. IntPtr pointer = IntPtr.Zero;
  1565. try {
  1566. pointer = GlobalLock (handle);
  1567. if (pointer == IntPtr.Zero) {
  1568. return string.Empty;
  1569. }
  1570. int size = GlobalSize (handle);
  1571. byte [] buff = new byte [size];
  1572. Marshal.Copy (pointer, buff, 0, size);
  1573. return System.Text.Encoding.Unicode.GetString (buff).TrimEnd ('\0');
  1574. } finally {
  1575. if (pointer != IntPtr.Zero) {
  1576. GlobalUnlock (handle);
  1577. }
  1578. }
  1579. } finally {
  1580. CloseClipboard ();
  1581. }
  1582. }
  1583. protected override void SetClipboardDataImpl (string text)
  1584. {
  1585. OpenClipboard ();
  1586. EmptyClipboard ();
  1587. IntPtr hGlobal = default;
  1588. try {
  1589. var bytes = (text.Length + 1) * 2;
  1590. hGlobal = Marshal.AllocHGlobal (bytes);
  1591. if (hGlobal == default) {
  1592. ThrowWin32 ();
  1593. }
  1594. var target = GlobalLock (hGlobal);
  1595. if (target == default) {
  1596. ThrowWin32 ();
  1597. }
  1598. try {
  1599. Marshal.Copy (text.ToCharArray (), 0, target, text.Length);
  1600. } finally {
  1601. GlobalUnlock (target);
  1602. }
  1603. if (SetClipboardData (_cfUnicodeText, hGlobal) == default) {
  1604. ThrowWin32 ();
  1605. }
  1606. hGlobal = default;
  1607. } finally {
  1608. if (hGlobal != default) {
  1609. Marshal.FreeHGlobal (hGlobal);
  1610. }
  1611. CloseClipboard ();
  1612. }
  1613. }
  1614. void OpenClipboard ()
  1615. {
  1616. var num = 10;
  1617. while (true) {
  1618. if (OpenClipboard (default)) {
  1619. break;
  1620. }
  1621. if (--num == 0) {
  1622. ThrowWin32 ();
  1623. }
  1624. Thread.Sleep (100);
  1625. }
  1626. }
  1627. const uint _cfUnicodeText = 13;
  1628. void ThrowWin32 ()
  1629. {
  1630. throw new Win32Exception (Marshal.GetLastWin32Error ());
  1631. }
  1632. [DllImport ("User32.dll", SetLastError = true)]
  1633. [return: MarshalAs (UnmanagedType.Bool)]
  1634. static extern bool IsClipboardFormatAvailable (uint format);
  1635. [DllImport ("kernel32.dll", SetLastError = true)]
  1636. static extern int GlobalSize (IntPtr handle);
  1637. [DllImport ("kernel32.dll", SetLastError = true)]
  1638. static extern IntPtr GlobalLock (IntPtr hMem);
  1639. [DllImport ("kernel32.dll", SetLastError = true)]
  1640. [return: MarshalAs (UnmanagedType.Bool)]
  1641. static extern bool GlobalUnlock (IntPtr hMem);
  1642. [DllImport ("user32.dll", SetLastError = true)]
  1643. [return: MarshalAs (UnmanagedType.Bool)]
  1644. static extern bool OpenClipboard (IntPtr hWndNewOwner);
  1645. [DllImport ("user32.dll", SetLastError = true)]
  1646. [return: MarshalAs (UnmanagedType.Bool)]
  1647. static extern bool CloseClipboard ();
  1648. [DllImport ("user32.dll", SetLastError = true)]
  1649. static extern IntPtr SetClipboardData (uint uFormat, IntPtr data);
  1650. [DllImport ("user32.dll")]
  1651. static extern bool EmptyClipboard ();
  1652. [DllImport ("user32.dll", SetLastError = true)]
  1653. static extern IntPtr GetClipboardData (uint uFormat);
  1654. }