WindowsConsole.cs 38 KB

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