WindowsConsole.cs 38 KB

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