WindowsConsole.cs 39 KB

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