WindowsDriver.cs 58 KB

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