WindowsConsole.cs 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. #nullable enable
  2. using System.Collections.Concurrent;
  3. using System.ComponentModel;
  4. using System.Runtime.InteropServices;
  5. using Terminal.Gui.ConsoleDrivers;
  6. namespace Terminal.Gui;
  7. internal class WindowsConsole
  8. {
  9. private CancellationTokenSource? _inputReadyCancellationTokenSource;
  10. private readonly BlockingCollection<InputRecord> _inputQueue = new (new ConcurrentQueue<InputRecord> ());
  11. internal WindowsMainLoop? _mainLoop;
  12. public const int STD_OUTPUT_HANDLE = -11;
  13. public const int STD_INPUT_HANDLE = -10;
  14. private readonly nint _inputHandle;
  15. private nint _outputHandle;
  16. //private nint _screenBuffer;
  17. private readonly uint _originalConsoleMode;
  18. private CursorVisibility? _initialCursorVisibility;
  19. private CursorVisibility? _currentCursorVisibility;
  20. private CursorVisibility? _pendingCursorVisibility;
  21. private readonly StringBuilder _stringBuilder = new (256 * 1024);
  22. private string _lastWrite = string.Empty;
  23. public WindowsConsole ()
  24. {
  25. _inputHandle = GetStdHandle (STD_INPUT_HANDLE);
  26. _outputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
  27. _originalConsoleMode = ConsoleMode;
  28. uint newConsoleMode = _originalConsoleMode;
  29. newConsoleMode |= (uint)(ConsoleModes.EnableMouseInput | ConsoleModes.EnableExtendedFlags);
  30. newConsoleMode &= ~(uint)ConsoleModes.EnableQuickEditMode;
  31. newConsoleMode &= ~(uint)ConsoleModes.EnableProcessedInput;
  32. ConsoleMode = newConsoleMode;
  33. _inputReadyCancellationTokenSource = new ();
  34. Task.Run (ProcessInputQueue, _inputReadyCancellationTokenSource.Token);
  35. }
  36. public InputRecord? DequeueInput ()
  37. {
  38. while (_inputReadyCancellationTokenSource is { })
  39. {
  40. try
  41. {
  42. return _inputQueue.Take (_inputReadyCancellationTokenSource.Token);
  43. }
  44. catch (OperationCanceledException)
  45. {
  46. return null;
  47. }
  48. }
  49. return null;
  50. }
  51. public InputRecord? ReadConsoleInput ()
  52. {
  53. const int BUFFER_SIZE = 1;
  54. InputRecord inputRecord = default;
  55. uint numberEventsRead = 0;
  56. while (!_inputReadyCancellationTokenSource!.IsCancellationRequested)
  57. {
  58. try
  59. {
  60. // Peek to check if there is any input available
  61. if (PeekConsoleInput (_inputHandle, out _, BUFFER_SIZE, out uint eventsRead) && eventsRead > 0)
  62. {
  63. // Read the input since it is available
  64. ReadConsoleInput (
  65. _inputHandle,
  66. out inputRecord,
  67. BUFFER_SIZE,
  68. out numberEventsRead);
  69. }
  70. if (numberEventsRead > 0)
  71. {
  72. return inputRecord;
  73. }
  74. try
  75. {
  76. Task.Delay (100, _inputReadyCancellationTokenSource.Token).Wait (_inputReadyCancellationTokenSource.Token);
  77. }
  78. catch (OperationCanceledException)
  79. {
  80. return null;
  81. }
  82. }
  83. catch (Exception ex)
  84. {
  85. if (ex is OperationCanceledException or ObjectDisposedException)
  86. {
  87. return null;
  88. }
  89. throw;
  90. }
  91. }
  92. return null;
  93. }
  94. private void ProcessInputQueue ()
  95. {
  96. while (_inputReadyCancellationTokenSource is { IsCancellationRequested: false })
  97. {
  98. try
  99. {
  100. if (_inputQueue.Count == 0)
  101. {
  102. while (_inputReadyCancellationTokenSource is { IsCancellationRequested: false })
  103. {
  104. try
  105. {
  106. InputRecord? inpRec = ReadConsoleInput ();
  107. if (inpRec is { })
  108. {
  109. _inputQueue.Add (inpRec.Value);
  110. break;
  111. }
  112. }
  113. catch (OperationCanceledException)
  114. {
  115. return;
  116. }
  117. }
  118. }
  119. }
  120. catch (OperationCanceledException)
  121. {
  122. return;
  123. }
  124. }
  125. }
  126. private CharInfo []? _originalStdOutChars;
  127. public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord bufferSize, SmallRect window, bool force16Colors)
  128. {
  129. //Debug.WriteLine ("WriteToConsole");
  130. //if (_screenBuffer == nint.Zero)
  131. //{
  132. // ReadFromConsoleOutput (size, bufferSize, ref window);
  133. //}
  134. var result = false;
  135. if (force16Colors)
  136. {
  137. var i = 0;
  138. CharInfo [] ci = new CharInfo [charInfoBuffer.Length];
  139. foreach (ExtendedCharInfo info in charInfoBuffer)
  140. {
  141. ci [i++] = new CharInfo
  142. {
  143. Char = new CharUnion { UnicodeChar = info.Char },
  144. Attributes =
  145. (ushort)((int)info.Attribute.Foreground.GetClosestNamedColor16 () | ((int)info.Attribute.Background.GetClosestNamedColor16 () << 4))
  146. };
  147. }
  148. result = WriteConsoleOutput (_outputHandle, ci, bufferSize, new Coord { X = window.Left, Y = window.Top }, ref window);
  149. }
  150. else
  151. {
  152. _stringBuilder.Clear ();
  153. _stringBuilder.Append (EscSeqUtils.CSI_SaveCursorPosition);
  154. _stringBuilder.Append (EscSeqUtils.CSI_SetCursorPosition (0, 0));
  155. Attribute? prev = null;
  156. foreach (ExtendedCharInfo info in charInfoBuffer)
  157. {
  158. Attribute attr = info.Attribute;
  159. if (attr != prev)
  160. {
  161. prev = attr;
  162. _stringBuilder.Append (EscSeqUtils.CSI_SetForegroundColorRGB (attr.Foreground.R, attr.Foreground.G, attr.Foreground.B));
  163. _stringBuilder.Append (EscSeqUtils.CSI_SetBackgroundColorRGB (attr.Background.R, attr.Background.G, attr.Background.B));
  164. }
  165. if (info.Char != '\x1b')
  166. {
  167. if (!info.Empty)
  168. {
  169. _stringBuilder.Append (info.Char);
  170. }
  171. }
  172. else
  173. {
  174. _stringBuilder.Append (' ');
  175. }
  176. }
  177. _stringBuilder.Append (EscSeqUtils.CSI_RestoreCursorPosition);
  178. _stringBuilder.Append (EscSeqUtils.CSI_HideCursor);
  179. var s = _stringBuilder.ToString ();
  180. // TODO: requires extensive testing if we go down this route
  181. // If console output has changed
  182. if (s != _lastWrite)
  183. {
  184. // supply console with the new content
  185. result = WriteConsole (_outputHandle, s, (uint)s.Length, out uint _, nint.Zero);
  186. }
  187. _lastWrite = s;
  188. foreach (var sixel in Application.Sixel)
  189. {
  190. SetCursorPosition (new Coord ((short)sixel.ScreenPosition.X, (short)sixel.ScreenPosition.Y));
  191. WriteConsole (_outputHandle, sixel.SixelData, (uint)sixel.SixelData.Length, out uint _, nint.Zero);
  192. }
  193. }
  194. if (!result)
  195. {
  196. int err = Marshal.GetLastWin32Error ();
  197. if (err != 0)
  198. {
  199. throw new Win32Exception (err);
  200. }
  201. }
  202. return result;
  203. }
  204. internal bool WriteANSI (string ansi)
  205. {
  206. if (WriteConsole (_outputHandle, ansi, (uint)ansi.Length, out uint _, nint.Zero))
  207. {
  208. // Flush the output to make sure it's sent immediately
  209. return FlushFileBuffers (_outputHandle);
  210. }
  211. return false;
  212. }
  213. public void ReadFromConsoleOutput (Size size, Coord coords, ref SmallRect window)
  214. {
  215. //_screenBuffer = CreateConsoleScreenBuffer (
  216. // DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
  217. // ShareMode.FileShareRead | ShareMode.FileShareWrite,
  218. // nint.Zero,
  219. // 1,
  220. // nint.Zero
  221. // );
  222. //if (_screenBuffer == INVALID_HANDLE_VALUE)
  223. //{
  224. // int err = Marshal.GetLastWin32Error ();
  225. // if (err != 0)
  226. // {
  227. // throw new Win32Exception (err);
  228. // }
  229. //}
  230. SetInitialCursorVisibility ();
  231. //if (!SetConsoleActiveScreenBuffer (_screenBuffer))
  232. //{
  233. // throw new Win32Exception (Marshal.GetLastWin32Error ());
  234. //}
  235. _originalStdOutChars = new CharInfo [size.Height * size.Width];
  236. if (!ReadConsoleOutput (_outputHandle, _originalStdOutChars, coords, new Coord { X = 0, Y = 0 }, ref window))
  237. {
  238. throw new Win32Exception (Marshal.GetLastWin32Error ());
  239. }
  240. }
  241. public bool SetCursorPosition (Coord position)
  242. {
  243. return SetConsoleCursorPosition (_outputHandle, position);
  244. }
  245. public void SetInitialCursorVisibility ()
  246. {
  247. if (_initialCursorVisibility.HasValue == false && GetCursorVisibility (out CursorVisibility visibility))
  248. {
  249. _initialCursorVisibility = visibility;
  250. }
  251. }
  252. public bool GetCursorVisibility (out CursorVisibility visibility)
  253. {
  254. if (_outputHandle == nint.Zero)
  255. {
  256. visibility = CursorVisibility.Invisible;
  257. return false;
  258. }
  259. if (!GetConsoleCursorInfo (_outputHandle, out ConsoleCursorInfo info))
  260. {
  261. int err = Marshal.GetLastWin32Error ();
  262. if (err != 0)
  263. {
  264. throw new Win32Exception (err);
  265. }
  266. visibility = CursorVisibility.Default;
  267. return false;
  268. }
  269. if (!info.bVisible)
  270. {
  271. visibility = CursorVisibility.Invisible;
  272. }
  273. else if (info.dwSize > 50)
  274. {
  275. visibility = CursorVisibility.Default;
  276. }
  277. else
  278. {
  279. visibility = CursorVisibility.Default;
  280. }
  281. return visibility != CursorVisibility.Invisible;
  282. }
  283. public bool EnsureCursorVisibility ()
  284. {
  285. if (_initialCursorVisibility.HasValue && _pendingCursorVisibility.HasValue && SetCursorVisibility (_pendingCursorVisibility.Value))
  286. {
  287. _pendingCursorVisibility = null;
  288. return true;
  289. }
  290. return false;
  291. }
  292. public void ForceRefreshCursorVisibility ()
  293. {
  294. if (_currentCursorVisibility.HasValue)
  295. {
  296. _pendingCursorVisibility = _currentCursorVisibility;
  297. _currentCursorVisibility = null;
  298. }
  299. }
  300. public bool SetCursorVisibility (CursorVisibility visibility)
  301. {
  302. if (_initialCursorVisibility.HasValue == false)
  303. {
  304. _pendingCursorVisibility = visibility;
  305. return false;
  306. }
  307. if (_currentCursorVisibility.HasValue == false || _currentCursorVisibility.Value != visibility)
  308. {
  309. var info = new ConsoleCursorInfo
  310. {
  311. dwSize = (uint)visibility & 0x00FF,
  312. bVisible = ((uint)visibility & 0xFF00) != 0
  313. };
  314. if (!SetConsoleCursorInfo (_outputHandle, ref info))
  315. {
  316. return false;
  317. }
  318. _currentCursorVisibility = visibility;
  319. }
  320. return true;
  321. }
  322. public void Cleanup ()
  323. {
  324. if (_initialCursorVisibility.HasValue)
  325. {
  326. SetCursorVisibility (_initialCursorVisibility.Value);
  327. }
  328. //SetConsoleOutputWindow (out _);
  329. ConsoleMode = _originalConsoleMode;
  330. _outputHandle = CreateConsoleScreenBuffer (
  331. DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
  332. ShareMode.FileShareRead | ShareMode.FileShareWrite,
  333. nint.Zero,
  334. 1,
  335. nint.Zero
  336. );
  337. if (!SetConsoleActiveScreenBuffer (_outputHandle))
  338. {
  339. int err = Marshal.GetLastWin32Error ();
  340. Console.WriteLine ("Error: {0}", err);
  341. }
  342. //if (_screenBuffer != nint.Zero)
  343. //{
  344. // CloseHandle (_screenBuffer);
  345. //}
  346. //_screenBuffer = nint.Zero;
  347. _inputReadyCancellationTokenSource?.Cancel ();
  348. _inputReadyCancellationTokenSource?.Dispose ();
  349. _inputReadyCancellationTokenSource = null;
  350. }
  351. internal Size GetConsoleBufferWindow (out Point position)
  352. {
  353. if (_outputHandle == nint.Zero)
  354. {
  355. position = Point.Empty;
  356. return Size.Empty;
  357. }
  358. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  359. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  360. if (!GetConsoleScreenBufferInfoEx (_outputHandle, ref csbi))
  361. {
  362. //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  363. position = Point.Empty;
  364. return Size.Empty;
  365. }
  366. Size sz = new (
  367. csbi.srWindow.Right - csbi.srWindow.Left + 1,
  368. csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
  369. position = new (csbi.srWindow.Left, csbi.srWindow.Top);
  370. return sz;
  371. }
  372. internal Size GetConsoleOutputWindow (out Point position)
  373. {
  374. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  375. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  376. if (!GetConsoleScreenBufferInfoEx (_outputHandle, ref csbi))
  377. {
  378. throw new Win32Exception (Marshal.GetLastWin32Error ());
  379. }
  380. Size sz = new (
  381. csbi.srWindow.Right - csbi.srWindow.Left + 1,
  382. csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
  383. position = new (csbi.srWindow.Left, csbi.srWindow.Top);
  384. return sz;
  385. }
  386. //internal Size SetConsoleWindow (short cols, short rows)
  387. //{
  388. // var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  389. // csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  390. // if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi))
  391. // {
  392. // throw new Win32Exception (Marshal.GetLastWin32Error ());
  393. // }
  394. // Coord maxWinSize = GetLargestConsoleWindowSize (_screenBuffer);
  395. // short newCols = Math.Min (cols, maxWinSize.X);
  396. // short newRows = Math.Min (rows, maxWinSize.Y);
  397. // csbi.dwSize = new Coord (newCols, Math.Max (newRows, (short)1));
  398. // csbi.srWindow = new SmallRect (0, 0, newCols, newRows);
  399. // csbi.dwMaximumWindowSize = new Coord (newCols, newRows);
  400. // if (!SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi))
  401. // {
  402. // throw new Win32Exception (Marshal.GetLastWin32Error ());
  403. // }
  404. // var winRect = new SmallRect (0, 0, (short)(newCols - 1), (short)Math.Max (newRows - 1, 0));
  405. // if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect))
  406. // {
  407. // //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  408. // return new (cols, rows);
  409. // }
  410. // SetConsoleOutputWindow (csbi);
  411. // return new (winRect.Right + 1, newRows - 1 < 0 ? 0 : winRect.Bottom + 1);
  412. //}
  413. //private void SetConsoleOutputWindow (CONSOLE_SCREEN_BUFFER_INFOEX csbi)
  414. //{
  415. // if (_screenBuffer != nint.Zero && !SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi))
  416. // {
  417. // throw new Win32Exception (Marshal.GetLastWin32Error ());
  418. // }
  419. //}
  420. //internal Size SetConsoleOutputWindow (out Point position)
  421. //{
  422. // if (_screenBuffer == nint.Zero)
  423. // {
  424. // position = Point.Empty;
  425. // return Size.Empty;
  426. // }
  427. // var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  428. // csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  429. // if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi))
  430. // {
  431. // throw new Win32Exception (Marshal.GetLastWin32Error ());
  432. // }
  433. // Size sz = new (
  434. // csbi.srWindow.Right - csbi.srWindow.Left + 1,
  435. // Math.Max (csbi.srWindow.Bottom - csbi.srWindow.Top + 1, 0));
  436. // position = new (csbi.srWindow.Left, csbi.srWindow.Top);
  437. // SetConsoleOutputWindow (csbi);
  438. // var winRect = new SmallRect (0, 0, (short)(sz.Width - 1), (short)Math.Max (sz.Height - 1, 0));
  439. // if (!SetConsoleScreenBufferInfoEx (_outputHandle, ref csbi))
  440. // {
  441. // throw new Win32Exception (Marshal.GetLastWin32Error ());
  442. // }
  443. // if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect))
  444. // {
  445. // throw new Win32Exception (Marshal.GetLastWin32Error ());
  446. // }
  447. // return sz;
  448. //}
  449. private uint ConsoleMode
  450. {
  451. get
  452. {
  453. GetConsoleMode (_inputHandle, out uint v);
  454. return v;
  455. }
  456. set => SetConsoleMode (_inputHandle, value);
  457. }
  458. [Flags]
  459. public enum ConsoleModes : uint
  460. {
  461. EnableProcessedInput = 1,
  462. EnableMouseInput = 16,
  463. EnableQuickEditMode = 64,
  464. EnableExtendedFlags = 128
  465. }
  466. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  467. public struct KeyEventRecord
  468. {
  469. [FieldOffset (0)]
  470. [MarshalAs (UnmanagedType.Bool)]
  471. public bool bKeyDown;
  472. [FieldOffset (4)]
  473. [MarshalAs (UnmanagedType.U2)]
  474. public ushort wRepeatCount;
  475. [FieldOffset (6)]
  476. [MarshalAs (UnmanagedType.U2)]
  477. public ConsoleKeyMapping.VK wVirtualKeyCode;
  478. [FieldOffset (8)]
  479. [MarshalAs (UnmanagedType.U2)]
  480. public ushort wVirtualScanCode;
  481. [FieldOffset (10)]
  482. public char UnicodeChar;
  483. [FieldOffset (12)]
  484. [MarshalAs (UnmanagedType.U4)]
  485. public ControlKeyState dwControlKeyState;
  486. public readonly override string ToString ()
  487. {
  488. return
  489. $"[KeyEventRecord({(bKeyDown ? "down" : "up")},{wRepeatCount},{wVirtualKeyCode},{wVirtualScanCode},{new Rune (UnicodeChar).MakePrintable ()},{dwControlKeyState})]";
  490. }
  491. }
  492. [Flags]
  493. public enum ButtonState
  494. {
  495. NoButtonPressed = 0,
  496. Button1Pressed = 1,
  497. Button2Pressed = 4,
  498. Button3Pressed = 8,
  499. Button4Pressed = 16,
  500. RightmostButtonPressed = 2
  501. }
  502. [Flags]
  503. public enum ControlKeyState
  504. {
  505. NoControlKeyPressed = 0,
  506. RightAltPressed = 1,
  507. LeftAltPressed = 2,
  508. RightControlPressed = 4,
  509. LeftControlPressed = 8,
  510. ShiftPressed = 16,
  511. NumlockOn = 32,
  512. ScrolllockOn = 64,
  513. CapslockOn = 128,
  514. EnhancedKey = 256
  515. }
  516. [Flags]
  517. public enum EventFlags
  518. {
  519. NoEvent = 0,
  520. MouseMoved = 1,
  521. DoubleClick = 2,
  522. MouseWheeled = 4,
  523. MouseHorizontalWheeled = 8
  524. }
  525. [StructLayout (LayoutKind.Explicit)]
  526. public struct MouseEventRecord
  527. {
  528. [FieldOffset (0)]
  529. public Coord MousePosition;
  530. [FieldOffset (4)]
  531. public ButtonState ButtonState;
  532. [FieldOffset (8)]
  533. public ControlKeyState ControlKeyState;
  534. [FieldOffset (12)]
  535. public EventFlags EventFlags;
  536. public readonly override string ToString () { return $"[Mouse{MousePosition},{ButtonState},{ControlKeyState},{EventFlags}]"; }
  537. }
  538. public struct WindowBufferSizeRecord
  539. {
  540. public Coord _size;
  541. public WindowBufferSizeRecord (short x, short y) { _size = new Coord (x, y); }
  542. public readonly override string ToString () { return $"[WindowBufferSize{_size}"; }
  543. }
  544. [StructLayout (LayoutKind.Sequential)]
  545. public struct MenuEventRecord
  546. {
  547. public uint dwCommandId;
  548. }
  549. [StructLayout (LayoutKind.Sequential)]
  550. public struct FocusEventRecord
  551. {
  552. public uint bSetFocus;
  553. }
  554. public enum EventType : ushort
  555. {
  556. Focus = 0x10,
  557. Key = 0x1,
  558. Menu = 0x8,
  559. Mouse = 2,
  560. WindowBufferSize = 4
  561. }
  562. [StructLayout (LayoutKind.Explicit)]
  563. public struct InputRecord
  564. {
  565. [FieldOffset (0)]
  566. public EventType EventType;
  567. [FieldOffset (4)]
  568. public KeyEventRecord KeyEvent;
  569. [FieldOffset (4)]
  570. public MouseEventRecord MouseEvent;
  571. [FieldOffset (4)]
  572. public WindowBufferSizeRecord WindowBufferSizeEvent;
  573. [FieldOffset (4)]
  574. public MenuEventRecord MenuEvent;
  575. [FieldOffset (4)]
  576. public FocusEventRecord FocusEvent;
  577. public readonly override string ToString ()
  578. {
  579. return (EventType switch
  580. {
  581. EventType.Focus => FocusEvent.ToString (),
  582. EventType.Key => KeyEvent.ToString (),
  583. EventType.Menu => MenuEvent.ToString (),
  584. EventType.Mouse => MouseEvent.ToString (),
  585. EventType.WindowBufferSize => WindowBufferSizeEvent.ToString (),
  586. _ => "Unknown event type: " + EventType
  587. })!;
  588. }
  589. }
  590. [Flags]
  591. private enum ShareMode : uint
  592. {
  593. FileShareRead = 1,
  594. FileShareWrite = 2
  595. }
  596. [Flags]
  597. private enum DesiredAccess : uint
  598. {
  599. GenericRead = 2147483648,
  600. GenericWrite = 1073741824
  601. }
  602. [StructLayout (LayoutKind.Sequential)]
  603. public struct ConsoleScreenBufferInfo
  604. {
  605. public Coord dwSize;
  606. public Coord dwCursorPosition;
  607. public ushort wAttributes;
  608. public SmallRect srWindow;
  609. public Coord dwMaximumWindowSize;
  610. }
  611. [StructLayout (LayoutKind.Sequential)]
  612. public struct Coord
  613. {
  614. public short X;
  615. public short Y;
  616. public Coord (short x, short y)
  617. {
  618. X = x;
  619. Y = y;
  620. }
  621. public readonly override string ToString () { return $"({X},{Y})"; }
  622. }
  623. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  624. public struct CharUnion
  625. {
  626. [FieldOffset (0)]
  627. public char UnicodeChar;
  628. [FieldOffset (0)]
  629. public byte AsciiChar;
  630. }
  631. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  632. public struct CharInfo
  633. {
  634. [FieldOffset (0)]
  635. public CharUnion Char;
  636. [FieldOffset (2)]
  637. public ushort Attributes;
  638. }
  639. public struct ExtendedCharInfo
  640. {
  641. public char Char { get; set; }
  642. public Attribute Attribute { get; set; }
  643. public bool Empty { get; set; } // TODO: Temp hack until virtual terminal sequences
  644. public ExtendedCharInfo (char character, Attribute attribute)
  645. {
  646. Char = character;
  647. Attribute = attribute;
  648. Empty = false;
  649. }
  650. }
  651. [StructLayout (LayoutKind.Sequential)]
  652. public struct SmallRect
  653. {
  654. public short Left;
  655. public short Top;
  656. public short Right;
  657. public short Bottom;
  658. public SmallRect (short left, short top, short right, short bottom)
  659. {
  660. Left = left;
  661. Top = top;
  662. Right = right;
  663. Bottom = bottom;
  664. }
  665. public static void MakeEmpty (ref SmallRect rect) { rect.Left = -1; }
  666. public static void Update (ref SmallRect rect, short col, short row)
  667. {
  668. if (rect.Left == -1)
  669. {
  670. rect.Left = rect.Right = col;
  671. rect.Bottom = rect.Top = row;
  672. return;
  673. }
  674. if (col >= rect.Left && col <= rect.Right && row >= rect.Top && row <= rect.Bottom)
  675. {
  676. return;
  677. }
  678. if (col < rect.Left)
  679. {
  680. rect.Left = col;
  681. }
  682. if (col > rect.Right)
  683. {
  684. rect.Right = col;
  685. }
  686. if (row < rect.Top)
  687. {
  688. rect.Top = row;
  689. }
  690. if (row > rect.Bottom)
  691. {
  692. rect.Bottom = row;
  693. }
  694. }
  695. public readonly override string ToString () { return $"Left={Left},Top={Top},Right={Right},Bottom={Bottom}"; }
  696. }
  697. [StructLayout (LayoutKind.Sequential)]
  698. public struct ConsoleKeyInfoEx
  699. {
  700. public ConsoleKeyInfo ConsoleKeyInfo;
  701. public bool CapsLock;
  702. public bool NumLock;
  703. public bool ScrollLock;
  704. public ConsoleKeyInfoEx (ConsoleKeyInfo consoleKeyInfo, bool capslock, bool numlock, bool scrolllock)
  705. {
  706. ConsoleKeyInfo = consoleKeyInfo;
  707. CapsLock = capslock;
  708. NumLock = numlock;
  709. ScrollLock = scrolllock;
  710. }
  711. /// <summary>
  712. /// Prints a ConsoleKeyInfoEx structure
  713. /// </summary>
  714. /// <param name="ex"></param>
  715. /// <returns></returns>
  716. public readonly string ToString (ConsoleKeyInfoEx ex)
  717. {
  718. var ke = new Key ((KeyCode)ex.ConsoleKeyInfo.KeyChar);
  719. var sb = new StringBuilder ();
  720. sb.Append ($"Key: {(KeyCode)ex.ConsoleKeyInfo.Key} ({ex.ConsoleKeyInfo.Key})");
  721. sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0 ? " | Shift" : string.Empty);
  722. sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0 ? " | Control" : string.Empty);
  723. sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0 ? " | Alt" : string.Empty);
  724. sb.Append ($", KeyChar: {ke.AsRune.MakePrintable ()} ({(uint)ex.ConsoleKeyInfo.KeyChar}) ");
  725. sb.Append (ex.CapsLock ? "caps," : string.Empty);
  726. sb.Append (ex.NumLock ? "num," : string.Empty);
  727. sb.Append (ex.ScrollLock ? "scroll," : string.Empty);
  728. string s = sb.ToString ().TrimEnd (',').TrimEnd (' ');
  729. return $"[ConsoleKeyInfoEx({s})]";
  730. }
  731. }
  732. [DllImport ("kernel32.dll", SetLastError = true)]
  733. private static extern nint GetStdHandle (int nStdHandle);
  734. [DllImport ("kernel32.dll", SetLastError = true)]
  735. private static extern bool CloseHandle (nint handle);
  736. [DllImport ("kernel32.dll", SetLastError = true)]
  737. public static extern bool PeekConsoleInput (nint hConsoleInput, out InputRecord lpBuffer, uint nLength, out uint lpNumberOfEventsRead);
  738. [DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)]
  739. public static extern bool ReadConsoleInput (
  740. nint hConsoleInput,
  741. out InputRecord lpBuffer,
  742. uint nLength,
  743. out uint lpNumberOfEventsRead
  744. );
  745. [DllImport ("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  746. private static extern bool ReadConsoleOutput (
  747. nint hConsoleOutput,
  748. [Out] CharInfo [] lpBuffer,
  749. Coord dwBufferSize,
  750. Coord dwBufferCoord,
  751. ref SmallRect lpReadRegion
  752. );
  753. // TODO: This API is obsolete. See https://learn.microsoft.com/en-us/windows/console/writeconsoleoutput
  754. [DllImport ("kernel32.dll", EntryPoint = "WriteConsoleOutputW", SetLastError = true, CharSet = CharSet.Unicode)]
  755. public static extern bool WriteConsoleOutput (
  756. nint hConsoleOutput,
  757. CharInfo [] lpBuffer,
  758. Coord dwBufferSize,
  759. Coord dwBufferCoord,
  760. ref SmallRect lpWriteRegion
  761. );
  762. [DllImport ("kernel32.dll", EntryPoint = "WriteConsole", SetLastError = true, CharSet = CharSet.Unicode)]
  763. private static extern bool WriteConsole (
  764. nint hConsoleOutput,
  765. string lpbufer,
  766. uint NumberOfCharsToWriten,
  767. out uint lpNumberOfCharsWritten,
  768. nint lpReserved
  769. );
  770. [DllImport ("kernel32.dll", SetLastError = true)]
  771. static extern bool FlushFileBuffers (nint hFile);
  772. [DllImport ("kernel32.dll")]
  773. private static extern bool SetConsoleCursorPosition (nint hConsoleOutput, Coord dwCursorPosition);
  774. [StructLayout (LayoutKind.Sequential)]
  775. public struct ConsoleCursorInfo
  776. {
  777. /// <summary>
  778. /// The percentage of the character cell that is filled by the cursor.This value is between 1 and 100.
  779. /// The cursor appearance varies, ranging from completely filling the cell to showing up as a horizontal
  780. /// line at the bottom of the cell.
  781. /// </summary>
  782. public uint dwSize;
  783. public bool bVisible;
  784. }
  785. [DllImport ("kernel32.dll", SetLastError = true)]
  786. private static extern bool SetConsoleCursorInfo (nint hConsoleOutput, [In] ref ConsoleCursorInfo lpConsoleCursorInfo);
  787. [DllImport ("kernel32.dll", SetLastError = true)]
  788. private static extern bool GetConsoleCursorInfo (nint hConsoleOutput, out ConsoleCursorInfo lpConsoleCursorInfo);
  789. [DllImport ("kernel32.dll")]
  790. private static extern bool GetConsoleMode (nint hConsoleHandle, out uint lpMode);
  791. [DllImport ("kernel32.dll")]
  792. private static extern bool SetConsoleMode (nint hConsoleHandle, uint dwMode);
  793. [DllImport ("kernel32.dll", SetLastError = true)]
  794. private static extern nint CreateConsoleScreenBuffer (
  795. DesiredAccess dwDesiredAccess,
  796. ShareMode dwShareMode,
  797. nint secutiryAttributes,
  798. uint flags,
  799. nint screenBufferData
  800. );
  801. internal static nint INVALID_HANDLE_VALUE = new (-1);
  802. [DllImport ("kernel32.dll", SetLastError = true)]
  803. private static extern bool SetConsoleActiveScreenBuffer (nint handle);
  804. [DllImport ("kernel32.dll", SetLastError = true)]
  805. private static extern bool GetNumberOfConsoleInputEvents (nint handle, out uint lpcNumberOfEvents);
  806. internal uint GetNumberOfConsoleInputEvents ()
  807. {
  808. if (!GetNumberOfConsoleInputEvents (_inputHandle, out uint numOfEvents))
  809. {
  810. Console.WriteLine ($"Error: {Marshal.GetLastWin32Error ()}");
  811. return 0;
  812. }
  813. return numOfEvents;
  814. }
  815. [DllImport ("kernel32.dll", SetLastError = true)]
  816. private static extern bool FlushConsoleInputBuffer (nint handle);
  817. internal void FlushConsoleInputBuffer ()
  818. {
  819. if (!FlushConsoleInputBuffer (_inputHandle))
  820. {
  821. Console.WriteLine ($"Error: {Marshal.GetLastWin32Error ()}");
  822. }
  823. }
  824. #if false // Not needed on the constructor. Perhaps could be used on resizing. To study.
  825. [DllImport ("kernel32.dll", ExactSpelling = true)]
  826. static extern IntPtr GetConsoleWindow ();
  827. [DllImport ("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  828. static extern bool ShowWindow (IntPtr hWnd, int nCmdShow);
  829. public const int HIDE = 0;
  830. public const int MAXIMIZE = 3;
  831. public const int MINIMIZE = 6;
  832. public const int RESTORE = 9;
  833. internal void ShowWindow (int state)
  834. {
  835. IntPtr thisConsole = GetConsoleWindow ();
  836. ShowWindow (thisConsole, state);
  837. }
  838. #endif
  839. // See: https://github.com/gui-cs/Terminal.Gui/issues/357
  840. [StructLayout (LayoutKind.Sequential)]
  841. public struct CONSOLE_SCREEN_BUFFER_INFOEX
  842. {
  843. public uint cbSize;
  844. public Coord dwSize;
  845. public Coord dwCursorPosition;
  846. public ushort wAttributes;
  847. public SmallRect srWindow;
  848. public Coord dwMaximumWindowSize;
  849. public ushort wPopupAttributes;
  850. public bool bFullscreenSupported;
  851. [MarshalAs (UnmanagedType.ByValArray, SizeConst = 16)]
  852. public COLORREF [] ColorTable;
  853. }
  854. [StructLayout (LayoutKind.Explicit, Size = 4)]
  855. public struct COLORREF
  856. {
  857. public COLORREF (byte r, byte g, byte b)
  858. {
  859. Value = 0;
  860. R = r;
  861. G = g;
  862. B = b;
  863. }
  864. public COLORREF (uint value)
  865. {
  866. R = 0;
  867. G = 0;
  868. B = 0;
  869. Value = value & 0x00FFFFFF;
  870. }
  871. [FieldOffset (0)]
  872. public byte R;
  873. [FieldOffset (1)]
  874. public byte G;
  875. [FieldOffset (2)]
  876. public byte B;
  877. [FieldOffset (0)]
  878. public uint Value;
  879. }
  880. [DllImport ("kernel32.dll", SetLastError = true)]
  881. private static extern bool GetConsoleScreenBufferInfoEx (nint hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX csbi);
  882. [DllImport ("kernel32.dll", SetLastError = true)]
  883. private static extern bool SetConsoleScreenBufferInfoEx (nint hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX consoleScreenBufferInfo);
  884. [DllImport ("kernel32.dll", SetLastError = true)]
  885. private static extern bool SetConsoleWindowInfo (
  886. nint hConsoleOutput,
  887. bool bAbsolute,
  888. [In] ref SmallRect lpConsoleWindow
  889. );
  890. [DllImport ("kernel32.dll", SetLastError = true)]
  891. private static extern Coord GetLargestConsoleWindowSize (
  892. nint hConsoleOutput
  893. );
  894. }