WindowsConsole.cs 38 KB

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