WindowsConsole.cs 38 KB

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