WindowsConsole.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  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 partial 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. EscSeqUtils.CSI_AppendCursorPosition (_stringBuilder, 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. EscSeqUtils.CSI_AppendForegroundColorRGB (_stringBuilder, attr.Foreground.R, attr.Foreground.G, attr.Foreground.B);
  163. EscSeqUtils.CSI_AppendBackgroundColorRGB (_stringBuilder, 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. [LibraryImport ("kernel32.dll", EntryPoint = "WriteConsoleW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
  763. [return: MarshalAs (UnmanagedType.Bool)]
  764. private static partial bool WriteConsole (
  765. nint hConsoleOutput,
  766. ReadOnlySpan<char> lpbufer,
  767. uint NumberOfCharsToWriten,
  768. out uint lpNumberOfCharsWritten,
  769. nint lpReserved
  770. );
  771. [DllImport ("kernel32.dll", SetLastError = true)]
  772. static extern bool FlushFileBuffers (nint hFile);
  773. [DllImport ("kernel32.dll")]
  774. private static extern bool SetConsoleCursorPosition (nint hConsoleOutput, Coord dwCursorPosition);
  775. [StructLayout (LayoutKind.Sequential)]
  776. public struct ConsoleCursorInfo
  777. {
  778. /// <summary>
  779. /// The percentage of the character cell that is filled by the cursor.This value is between 1 and 100.
  780. /// The cursor appearance varies, ranging from completely filling the cell to showing up as a horizontal
  781. /// line at the bottom of the cell.
  782. /// </summary>
  783. public uint dwSize;
  784. public bool bVisible;
  785. }
  786. [DllImport ("kernel32.dll", SetLastError = true)]
  787. private static extern bool SetConsoleCursorInfo (nint hConsoleOutput, [In] ref ConsoleCursorInfo lpConsoleCursorInfo);
  788. [DllImport ("kernel32.dll", SetLastError = true)]
  789. private static extern bool GetConsoleCursorInfo (nint hConsoleOutput, out ConsoleCursorInfo lpConsoleCursorInfo);
  790. [DllImport ("kernel32.dll")]
  791. private static extern bool GetConsoleMode (nint hConsoleHandle, out uint lpMode);
  792. [DllImport ("kernel32.dll")]
  793. private static extern bool SetConsoleMode (nint hConsoleHandle, uint dwMode);
  794. [DllImport ("kernel32.dll", SetLastError = true)]
  795. private static extern nint CreateConsoleScreenBuffer (
  796. DesiredAccess dwDesiredAccess,
  797. ShareMode dwShareMode,
  798. nint secutiryAttributes,
  799. uint flags,
  800. nint screenBufferData
  801. );
  802. internal static nint INVALID_HANDLE_VALUE = new (-1);
  803. [DllImport ("kernel32.dll", SetLastError = true)]
  804. private static extern bool SetConsoleActiveScreenBuffer (nint handle);
  805. [DllImport ("kernel32.dll", SetLastError = true)]
  806. private static extern bool GetNumberOfConsoleInputEvents (nint handle, out uint lpcNumberOfEvents);
  807. internal uint GetNumberOfConsoleInputEvents ()
  808. {
  809. if (!GetNumberOfConsoleInputEvents (_inputHandle, out uint numOfEvents))
  810. {
  811. Console.WriteLine ($"Error: {Marshal.GetLastWin32Error ()}");
  812. return 0;
  813. }
  814. return numOfEvents;
  815. }
  816. [DllImport ("kernel32.dll", SetLastError = true)]
  817. private static extern bool FlushConsoleInputBuffer (nint handle);
  818. internal void FlushConsoleInputBuffer ()
  819. {
  820. if (!FlushConsoleInputBuffer (_inputHandle))
  821. {
  822. Console.WriteLine ($"Error: {Marshal.GetLastWin32Error ()}");
  823. }
  824. }
  825. #if false // Not needed on the constructor. Perhaps could be used on resizing. To study.
  826. [DllImport ("kernel32.dll", ExactSpelling = true)]
  827. static extern IntPtr GetConsoleWindow ();
  828. [DllImport ("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  829. static extern bool ShowWindow (IntPtr hWnd, int nCmdShow);
  830. public const int HIDE = 0;
  831. public const int MAXIMIZE = 3;
  832. public const int MINIMIZE = 6;
  833. public const int RESTORE = 9;
  834. internal void ShowWindow (int state)
  835. {
  836. IntPtr thisConsole = GetConsoleWindow ();
  837. ShowWindow (thisConsole, state);
  838. }
  839. #endif
  840. // See: https://github.com/gui-cs/Terminal.Gui/issues/357
  841. [StructLayout (LayoutKind.Sequential)]
  842. public struct CONSOLE_SCREEN_BUFFER_INFOEX
  843. {
  844. public uint cbSize;
  845. public Coord dwSize;
  846. public Coord dwCursorPosition;
  847. public ushort wAttributes;
  848. public SmallRect srWindow;
  849. public Coord dwMaximumWindowSize;
  850. public ushort wPopupAttributes;
  851. public bool bFullscreenSupported;
  852. [MarshalAs (UnmanagedType.ByValArray, SizeConst = 16)]
  853. public COLORREF [] ColorTable;
  854. }
  855. [StructLayout (LayoutKind.Explicit, Size = 4)]
  856. public struct COLORREF
  857. {
  858. public COLORREF (byte r, byte g, byte b)
  859. {
  860. Value = 0;
  861. R = r;
  862. G = g;
  863. B = b;
  864. }
  865. public COLORREF (uint value)
  866. {
  867. R = 0;
  868. G = 0;
  869. B = 0;
  870. Value = value & 0x00FFFFFF;
  871. }
  872. [FieldOffset (0)]
  873. public byte R;
  874. [FieldOffset (1)]
  875. public byte G;
  876. [FieldOffset (2)]
  877. public byte B;
  878. [FieldOffset (0)]
  879. public uint Value;
  880. }
  881. [DllImport ("kernel32.dll", SetLastError = true)]
  882. private static extern bool GetConsoleScreenBufferInfoEx (nint hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX csbi);
  883. [DllImport ("kernel32.dll", SetLastError = true)]
  884. private static extern bool SetConsoleScreenBufferInfoEx (nint hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX consoleScreenBufferInfo);
  885. [DllImport ("kernel32.dll", SetLastError = true)]
  886. private static extern bool SetConsoleWindowInfo (
  887. nint hConsoleOutput,
  888. bool bAbsolute,
  889. [In] ref SmallRect lpConsoleWindow
  890. );
  891. [DllImport ("kernel32.dll", SetLastError = true)]
  892. private static extern Coord GetLargestConsoleWindowSize (
  893. nint hConsoleOutput
  894. );
  895. }