WindowsConsole.cs 38 KB

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