WindowsConsole.cs 35 KB

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