NetDriver.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. #nullable enable
  2. //
  3. // NetDriver.cs: The System.Console-based .NET driver, works on Windows and Unix, but is not particularly efficient.
  4. //
  5. using System.Diagnostics;
  6. using System.Runtime.InteropServices;
  7. using static Terminal.Gui.NetEvents;
  8. namespace Terminal.Gui;
  9. internal class NetDriver : ConsoleDriver
  10. {
  11. public bool IsWinPlatform { get; private set; }
  12. public NetWinVTConsole? NetWinConsole { get; private set; }
  13. public override void Suspend ()
  14. {
  15. if (Environment.OSVersion.Platform != PlatformID.Unix)
  16. {
  17. return;
  18. }
  19. StopReportingMouseMoves ();
  20. if (!RunningUnitTests)
  21. {
  22. Console.ResetColor ();
  23. Console.Clear ();
  24. //Disable alternative screen buffer.
  25. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  26. //Set cursor key to cursor.
  27. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_ShowCursor);
  28. Platform.Suspend ();
  29. //Enable alternative screen buffer.
  30. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  31. SetContentsAsDirty ();
  32. Refresh ();
  33. }
  34. StartReportingMouseMoves ();
  35. }
  36. public override bool UpdateScreen ()
  37. {
  38. bool updated = false;
  39. if (RunningUnitTests
  40. || _winSizeChanging
  41. || Console.WindowHeight < 1
  42. || Contents?.Length != Rows * Cols
  43. || Rows != Console.WindowHeight)
  44. {
  45. return updated;
  46. }
  47. var top = 0;
  48. var left = 0;
  49. int rows = Rows;
  50. int cols = Cols;
  51. var output = new StringBuilder ();
  52. Attribute? redrawAttr = null;
  53. int lastCol = -1;
  54. CursorVisibility? savedVisibility = _cachedCursorVisibility;
  55. SetCursorVisibility (CursorVisibility.Invisible);
  56. for (int row = top; row < rows; row++)
  57. {
  58. if (Console.WindowHeight < 1)
  59. {
  60. return updated;
  61. }
  62. if (!_dirtyLines! [row])
  63. {
  64. continue;
  65. }
  66. if (!SetCursorPosition (0, row))
  67. {
  68. return updated;
  69. }
  70. updated = true;
  71. _dirtyLines [row] = false;
  72. output.Clear ();
  73. for (int col = left; col < cols; col++)
  74. {
  75. lastCol = -1;
  76. var outputWidth = 0;
  77. for (; col < cols; col++)
  78. {
  79. if (!Contents [row, col].IsDirty)
  80. {
  81. if (output.Length > 0)
  82. {
  83. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  84. }
  85. else if (lastCol == -1)
  86. {
  87. lastCol = col;
  88. }
  89. if (lastCol + 1 < cols)
  90. {
  91. lastCol++;
  92. }
  93. continue;
  94. }
  95. if (lastCol == -1)
  96. {
  97. lastCol = col;
  98. }
  99. Attribute attr = Contents [row, col].Attribute!.Value;
  100. // Performance: Only send the escape sequence if the attribute has changed.
  101. if (attr != redrawAttr)
  102. {
  103. redrawAttr = attr;
  104. if (Force16Colors)
  105. {
  106. output.Append (
  107. AnsiEscapeSequenceRequestUtils.CSI_SetGraphicsRendition (
  108. MapColors (
  109. (ConsoleColor)attr.Background
  110. .GetClosestNamedColor16 (),
  111. false
  112. ),
  113. MapColors (
  114. (ConsoleColor)attr.Foreground
  115. .GetClosestNamedColor16 ())
  116. )
  117. );
  118. }
  119. else
  120. {
  121. output.Append (
  122. AnsiEscapeSequenceRequestUtils.CSI_SetForegroundColorRGB (
  123. attr.Foreground.R,
  124. attr.Foreground.G,
  125. attr.Foreground.B
  126. )
  127. );
  128. output.Append (
  129. AnsiEscapeSequenceRequestUtils.CSI_SetBackgroundColorRGB (
  130. attr.Background.R,
  131. attr.Background.G,
  132. attr.Background.B
  133. )
  134. );
  135. }
  136. }
  137. outputWidth++;
  138. Rune rune = Contents [row, col].Rune;
  139. output.Append (rune);
  140. if (Contents [row, col].CombiningMarks.Count > 0)
  141. {
  142. // AtlasEngine does not support NON-NORMALIZED combining marks in a way
  143. // compatible with the driver architecture. Any CMs (except in the first col)
  144. // are correctly combined with the base char, but are ALSO treated as 1 column
  145. // width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
  146. //
  147. // For now, we just ignore the list of CMs.
  148. //foreach (var combMark in Contents [row, col].CombiningMarks) {
  149. // output.Append (combMark);
  150. //}
  151. // WriteToConsole (output, ref lastCol, row, ref outputWidth);
  152. }
  153. else if (rune.IsSurrogatePair () && rune.GetColumns () < 2)
  154. {
  155. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  156. SetCursorPosition (col - 1, row);
  157. }
  158. Contents [row, col].IsDirty = false;
  159. }
  160. }
  161. if (output.Length > 0)
  162. {
  163. SetCursorPosition (lastCol, row);
  164. Console.Write (output);
  165. }
  166. foreach (var s in Application.Sixel)
  167. {
  168. if (!string.IsNullOrWhiteSpace (s.SixelData))
  169. {
  170. SetCursorPosition (s.ScreenPosition.X, s.ScreenPosition.Y);
  171. Console.Write (s.SixelData);
  172. }
  173. }
  174. }
  175. SetCursorPosition (0, 0);
  176. _cachedCursorVisibility = savedVisibility;
  177. void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
  178. {
  179. SetCursorPosition (lastCol, row);
  180. Console.Write (output);
  181. output.Clear ();
  182. lastCol += outputWidth;
  183. outputWidth = 0;
  184. }
  185. return updated;
  186. }
  187. #region Init/End/MainLoop
  188. internal NetMainLoop? _mainLoopDriver;
  189. internal override MainLoop Init ()
  190. {
  191. PlatformID p = Environment.OSVersion.Platform;
  192. if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  193. {
  194. IsWinPlatform = true;
  195. try
  196. {
  197. NetWinConsole = new ();
  198. }
  199. catch (ApplicationException)
  200. {
  201. // Likely running as a unit test, or in a non-interactive session.
  202. }
  203. }
  204. if (IsWinPlatform)
  205. {
  206. Clipboard = new WindowsClipboard ();
  207. }
  208. else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
  209. {
  210. Clipboard = new MacOSXClipboard ();
  211. }
  212. else
  213. {
  214. if (CursesDriver.Is_WSL_Platform ())
  215. {
  216. Clipboard = new WSLClipboard ();
  217. }
  218. else
  219. {
  220. Clipboard = new CursesClipboard ();
  221. }
  222. }
  223. if (!RunningUnitTests)
  224. {
  225. Console.TreatControlCAsInput = true;
  226. Cols = Console.WindowWidth;
  227. Rows = Console.WindowHeight;
  228. //Enable alternative screen buffer.
  229. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  230. //Set cursor key to application.
  231. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_HideCursor);
  232. }
  233. else
  234. {
  235. // We are being run in an environment that does not support a console
  236. // such as a unit test, or a pipe.
  237. Cols = 80;
  238. Rows = 24;
  239. }
  240. ResizeScreen ();
  241. ClearContents ();
  242. CurrentAttribute = new (Color.White, Color.Black);
  243. StartReportingMouseMoves ();
  244. _mainLoopDriver = new (this);
  245. _mainLoopDriver.ProcessInput = ProcessInput;
  246. return new (_mainLoopDriver);
  247. }
  248. private void ProcessInput (InputResult inputEvent)
  249. {
  250. switch (inputEvent.EventType)
  251. {
  252. case EventType.Key:
  253. ConsoleKeyInfo consoleKeyInfo = inputEvent.ConsoleKeyInfo;
  254. //if (consoleKeyInfo.Key == ConsoleKey.Packet) {
  255. // consoleKeyInfo = FromVKPacketToKConsoleKeyInfo (consoleKeyInfo);
  256. //}
  257. //Debug.WriteLine ($"event: {inputEvent}");
  258. KeyCode map = AnsiEscapeSequenceRequestUtils.MapKey (consoleKeyInfo);
  259. if (map == KeyCode.Null)
  260. {
  261. break;
  262. }
  263. OnKeyDown (new (map));
  264. OnKeyUp (new (map));
  265. break;
  266. case EventType.Mouse:
  267. MouseEventArgs me = ToDriverMouse (inputEvent.MouseEvent);
  268. //Debug.WriteLine ($"NetDriver: ({me.X},{me.Y}) - {me.Flags}");
  269. OnMouseEvent (me);
  270. break;
  271. case EventType.WindowSize:
  272. _winSizeChanging = true;
  273. Top = 0;
  274. Left = 0;
  275. Cols = inputEvent.WindowSizeEvent.Size.Width;
  276. Rows = Math.Max (inputEvent.WindowSizeEvent.Size.Height, 0);
  277. ResizeScreen ();
  278. ClearContents ();
  279. _winSizeChanging = false;
  280. OnSizeChanged (new (new (Cols, Rows)));
  281. break;
  282. case EventType.RequestResponse:
  283. break;
  284. case EventType.WindowPosition:
  285. break;
  286. default:
  287. throw new ArgumentOutOfRangeException ();
  288. }
  289. }
  290. internal override void End ()
  291. {
  292. if (IsWinPlatform)
  293. {
  294. NetWinConsole?.Cleanup ();
  295. }
  296. StopReportingMouseMoves ();
  297. _ansiResponseTokenSource?.Cancel ();
  298. _ansiResponseTokenSource?.Dispose ();
  299. _waitAnsiResponse.Dispose ();
  300. if (!RunningUnitTests)
  301. {
  302. Console.ResetColor ();
  303. //Disable alternative screen buffer.
  304. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  305. //Set cursor key to cursor.
  306. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_ShowCursor);
  307. Console.Out.Close ();
  308. }
  309. }
  310. #endregion Init/End/MainLoop
  311. #region Color Handling
  312. public override bool SupportsTrueColor => Environment.OSVersion.Platform == PlatformID.Unix
  313. || (IsWinPlatform && Environment.OSVersion.Version.Build >= 14931);
  314. private const int COLOR_BLACK = 30;
  315. private const int COLOR_BLUE = 34;
  316. private const int COLOR_BRIGHT_BLACK = 90;
  317. private const int COLOR_BRIGHT_BLUE = 94;
  318. private const int COLOR_BRIGHT_CYAN = 96;
  319. private const int COLOR_BRIGHT_GREEN = 92;
  320. private const int COLOR_BRIGHT_MAGENTA = 95;
  321. private const int COLOR_BRIGHT_RED = 91;
  322. private const int COLOR_BRIGHT_WHITE = 97;
  323. private const int COLOR_BRIGHT_YELLOW = 93;
  324. private const int COLOR_CYAN = 36;
  325. private const int COLOR_GREEN = 32;
  326. private const int COLOR_MAGENTA = 35;
  327. private const int COLOR_RED = 31;
  328. private const int COLOR_WHITE = 37;
  329. private const int COLOR_YELLOW = 33;
  330. //// Cache the list of ConsoleColor values.
  331. //[UnconditionalSuppressMessage (
  332. // "AOT",
  333. // "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.",
  334. // Justification = "<Pending>")]
  335. //private static readonly HashSet<int> ConsoleColorValues = new (
  336. // Enum.GetValues (typeof (ConsoleColor))
  337. // .OfType<ConsoleColor> ()
  338. // .Select (c => (int)c)
  339. // );
  340. // Dictionary for mapping ConsoleColor values to the values used by System.Net.Console.
  341. private static readonly Dictionary<ConsoleColor, int> _colorMap = new ()
  342. {
  343. { ConsoleColor.Black, COLOR_BLACK },
  344. { ConsoleColor.DarkBlue, COLOR_BLUE },
  345. { ConsoleColor.DarkGreen, COLOR_GREEN },
  346. { ConsoleColor.DarkCyan, COLOR_CYAN },
  347. { ConsoleColor.DarkRed, COLOR_RED },
  348. { ConsoleColor.DarkMagenta, COLOR_MAGENTA },
  349. { ConsoleColor.DarkYellow, COLOR_YELLOW },
  350. { ConsoleColor.Gray, COLOR_WHITE },
  351. { ConsoleColor.DarkGray, COLOR_BRIGHT_BLACK },
  352. { ConsoleColor.Blue, COLOR_BRIGHT_BLUE },
  353. { ConsoleColor.Green, COLOR_BRIGHT_GREEN },
  354. { ConsoleColor.Cyan, COLOR_BRIGHT_CYAN },
  355. { ConsoleColor.Red, COLOR_BRIGHT_RED },
  356. { ConsoleColor.Magenta, COLOR_BRIGHT_MAGENTA },
  357. { ConsoleColor.Yellow, COLOR_BRIGHT_YELLOW },
  358. { ConsoleColor.White, COLOR_BRIGHT_WHITE }
  359. };
  360. // Map a ConsoleColor to a platform dependent value.
  361. private int MapColors (ConsoleColor color, bool isForeground = true)
  362. {
  363. return _colorMap.TryGetValue (color, out int colorValue) ? colorValue + (isForeground ? 0 : 10) : 0;
  364. }
  365. #endregion
  366. #region Cursor Handling
  367. private bool SetCursorPosition (int col, int row)
  368. {
  369. if (IsWinPlatform)
  370. {
  371. // Could happens that the windows is still resizing and the col is bigger than Console.WindowWidth.
  372. try
  373. {
  374. Console.SetCursorPosition (col, row);
  375. return true;
  376. }
  377. catch (Exception)
  378. {
  379. return false;
  380. }
  381. }
  382. // + 1 is needed because non-Windows is based on 1 instead of 0 and
  383. // Console.CursorTop/CursorLeft isn't reliable.
  384. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_SetCursorPosition (row + 1, col + 1));
  385. return true;
  386. }
  387. private CursorVisibility? _cachedCursorVisibility;
  388. public override void UpdateCursor ()
  389. {
  390. EnsureCursorVisibility ();
  391. if (Col >= 0 && Col < Cols && Row >= 0 && Row <= Rows)
  392. {
  393. SetCursorPosition (Col, Row);
  394. SetWindowPosition (0, Row);
  395. }
  396. }
  397. public override bool GetCursorVisibility (out CursorVisibility visibility)
  398. {
  399. visibility = _cachedCursorVisibility ?? CursorVisibility.Default;
  400. return visibility == CursorVisibility.Default;
  401. }
  402. public override bool SetCursorVisibility (CursorVisibility visibility)
  403. {
  404. _cachedCursorVisibility = visibility;
  405. Console.Out.Write (visibility == CursorVisibility.Default ? AnsiEscapeSequenceRequestUtils.CSI_ShowCursor : AnsiEscapeSequenceRequestUtils.CSI_HideCursor);
  406. return visibility == CursorVisibility.Default;
  407. }
  408. public override bool EnsureCursorVisibility ()
  409. {
  410. if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows))
  411. {
  412. GetCursorVisibility (out CursorVisibility cursorVisibility);
  413. _cachedCursorVisibility = cursorVisibility;
  414. SetCursorVisibility (CursorVisibility.Invisible);
  415. return false;
  416. }
  417. SetCursorVisibility (_cachedCursorVisibility ?? CursorVisibility.Default);
  418. return _cachedCursorVisibility == CursorVisibility.Default;
  419. }
  420. #endregion
  421. #region Mouse Handling
  422. public void StartReportingMouseMoves ()
  423. {
  424. if (!RunningUnitTests)
  425. {
  426. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_EnableMouseEvents);
  427. }
  428. }
  429. public void StopReportingMouseMoves ()
  430. {
  431. if (!RunningUnitTests)
  432. {
  433. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_DisableMouseEvents);
  434. }
  435. }
  436. private MouseEventArgs ToDriverMouse (MouseEvent me)
  437. {
  438. //System.Diagnostics.Debug.WriteLine ($"X: {me.Position.X}; Y: {me.Position.Y}; ButtonState: {me.ButtonState}");
  439. MouseFlags mouseFlag = 0;
  440. if ((me.ButtonState & MouseButtonState.Button1Pressed) != 0)
  441. {
  442. mouseFlag |= MouseFlags.Button1Pressed;
  443. }
  444. if ((me.ButtonState & MouseButtonState.Button1Released) != 0)
  445. {
  446. mouseFlag |= MouseFlags.Button1Released;
  447. }
  448. if ((me.ButtonState & MouseButtonState.Button1Clicked) != 0)
  449. {
  450. mouseFlag |= MouseFlags.Button1Clicked;
  451. }
  452. if ((me.ButtonState & MouseButtonState.Button1DoubleClicked) != 0)
  453. {
  454. mouseFlag |= MouseFlags.Button1DoubleClicked;
  455. }
  456. if ((me.ButtonState & MouseButtonState.Button1TripleClicked) != 0)
  457. {
  458. mouseFlag |= MouseFlags.Button1TripleClicked;
  459. }
  460. if ((me.ButtonState & MouseButtonState.Button2Pressed) != 0)
  461. {
  462. mouseFlag |= MouseFlags.Button2Pressed;
  463. }
  464. if ((me.ButtonState & MouseButtonState.Button2Released) != 0)
  465. {
  466. mouseFlag |= MouseFlags.Button2Released;
  467. }
  468. if ((me.ButtonState & MouseButtonState.Button2Clicked) != 0)
  469. {
  470. mouseFlag |= MouseFlags.Button2Clicked;
  471. }
  472. if ((me.ButtonState & MouseButtonState.Button2DoubleClicked) != 0)
  473. {
  474. mouseFlag |= MouseFlags.Button2DoubleClicked;
  475. }
  476. if ((me.ButtonState & MouseButtonState.Button2TripleClicked) != 0)
  477. {
  478. mouseFlag |= MouseFlags.Button2TripleClicked;
  479. }
  480. if ((me.ButtonState & MouseButtonState.Button3Pressed) != 0)
  481. {
  482. mouseFlag |= MouseFlags.Button3Pressed;
  483. }
  484. if ((me.ButtonState & MouseButtonState.Button3Released) != 0)
  485. {
  486. mouseFlag |= MouseFlags.Button3Released;
  487. }
  488. if ((me.ButtonState & MouseButtonState.Button3Clicked) != 0)
  489. {
  490. mouseFlag |= MouseFlags.Button3Clicked;
  491. }
  492. if ((me.ButtonState & MouseButtonState.Button3DoubleClicked) != 0)
  493. {
  494. mouseFlag |= MouseFlags.Button3DoubleClicked;
  495. }
  496. if ((me.ButtonState & MouseButtonState.Button3TripleClicked) != 0)
  497. {
  498. mouseFlag |= MouseFlags.Button3TripleClicked;
  499. }
  500. if ((me.ButtonState & MouseButtonState.ButtonWheeledUp) != 0)
  501. {
  502. mouseFlag |= MouseFlags.WheeledUp;
  503. }
  504. if ((me.ButtonState & MouseButtonState.ButtonWheeledDown) != 0)
  505. {
  506. mouseFlag |= MouseFlags.WheeledDown;
  507. }
  508. if ((me.ButtonState & MouseButtonState.ButtonWheeledLeft) != 0)
  509. {
  510. mouseFlag |= MouseFlags.WheeledLeft;
  511. }
  512. if ((me.ButtonState & MouseButtonState.ButtonWheeledRight) != 0)
  513. {
  514. mouseFlag |= MouseFlags.WheeledRight;
  515. }
  516. if ((me.ButtonState & MouseButtonState.Button4Pressed) != 0)
  517. {
  518. mouseFlag |= MouseFlags.Button4Pressed;
  519. }
  520. if ((me.ButtonState & MouseButtonState.Button4Released) != 0)
  521. {
  522. mouseFlag |= MouseFlags.Button4Released;
  523. }
  524. if ((me.ButtonState & MouseButtonState.Button4Clicked) != 0)
  525. {
  526. mouseFlag |= MouseFlags.Button4Clicked;
  527. }
  528. if ((me.ButtonState & MouseButtonState.Button4DoubleClicked) != 0)
  529. {
  530. mouseFlag |= MouseFlags.Button4DoubleClicked;
  531. }
  532. if ((me.ButtonState & MouseButtonState.Button4TripleClicked) != 0)
  533. {
  534. mouseFlag |= MouseFlags.Button4TripleClicked;
  535. }
  536. if ((me.ButtonState & MouseButtonState.ReportMousePosition) != 0)
  537. {
  538. mouseFlag |= MouseFlags.ReportMousePosition;
  539. }
  540. if ((me.ButtonState & MouseButtonState.ButtonShift) != 0)
  541. {
  542. mouseFlag |= MouseFlags.ButtonShift;
  543. }
  544. if ((me.ButtonState & MouseButtonState.ButtonCtrl) != 0)
  545. {
  546. mouseFlag |= MouseFlags.ButtonCtrl;
  547. }
  548. if ((me.ButtonState & MouseButtonState.ButtonAlt) != 0)
  549. {
  550. mouseFlag |= MouseFlags.ButtonAlt;
  551. }
  552. return new() { Position = me.Position, Flags = mouseFlag };
  553. }
  554. #endregion Mouse Handling
  555. #region Keyboard Handling
  556. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  557. {
  558. var input = new InputResult
  559. {
  560. EventType = EventType.Key, ConsoleKeyInfo = new (keyChar, key, shift, alt, control)
  561. };
  562. try
  563. {
  564. ProcessInput (input);
  565. }
  566. catch (OverflowException)
  567. { }
  568. }
  569. //private ConsoleKeyInfo FromVKPacketToKConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo)
  570. //{
  571. // if (consoleKeyInfo.Key != ConsoleKey.Packet)
  572. // {
  573. // return consoleKeyInfo;
  574. // }
  575. // ConsoleModifiers mod = consoleKeyInfo.Modifiers;
  576. // bool shift = (mod & ConsoleModifiers.Shift) != 0;
  577. // bool alt = (mod & ConsoleModifiers.Alt) != 0;
  578. // bool control = (mod & ConsoleModifiers.Control) != 0;
  579. // ConsoleKeyInfo cKeyInfo = DecodeVKPacketToKConsoleKeyInfo (consoleKeyInfo);
  580. // return new (cKeyInfo.KeyChar, cKeyInfo.Key, shift, alt, control);
  581. //}
  582. #endregion Keyboard Handling
  583. #region Low-Level DotNet tuff
  584. private readonly ManualResetEventSlim _waitAnsiResponse = new (false);
  585. private CancellationTokenSource? _ansiResponseTokenSource;
  586. /// <inheritdoc/>
  587. public override bool TryWriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest)
  588. {
  589. lock (ansiRequest._responseLock)
  590. {
  591. if (_mainLoopDriver is null)
  592. {
  593. return false;
  594. }
  595. }
  596. _ansiResponseTokenSource ??= new ();
  597. try
  598. {
  599. lock (ansiRequest._responseLock)
  600. {
  601. ansiRequest.ResponseFromInput += (s, e) =>
  602. {
  603. Debug.Assert (s == ansiRequest);
  604. Debug.Assert (e == ansiRequest.AnsiEscapeSequenceResponse);
  605. _waitAnsiResponse.Set ();
  606. };
  607. AnsiEscapeSequenceRequests.Add (ansiRequest);
  608. _mainLoopDriver._netEvents!._forceRead = true;
  609. }
  610. if (!_ansiResponseTokenSource.IsCancellationRequested)
  611. {
  612. lock (ansiRequest._responseLock)
  613. {
  614. _mainLoopDriver._waitForProbe.Set ();
  615. _mainLoopDriver._netEvents._waitForStart.Set ();
  616. WriteRaw (ansiRequest.Request);
  617. }
  618. _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token);
  619. }
  620. }
  621. catch (OperationCanceledException)
  622. {
  623. return false;
  624. }
  625. lock (ansiRequest._responseLock)
  626. {
  627. _mainLoopDriver._netEvents._forceRead = false;
  628. if (AnsiEscapeSequenceRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus? request))
  629. {
  630. if (AnsiEscapeSequenceRequests.Statuses.Count > 0
  631. && string.IsNullOrEmpty (request.AnsiRequest.AnsiEscapeSequenceResponse?.Response))
  632. {
  633. lock (request.AnsiRequest._responseLock)
  634. {
  635. // Bad request or no response at all
  636. AnsiEscapeSequenceRequests.Statuses.TryDequeue (out _);
  637. }
  638. }
  639. }
  640. _waitAnsiResponse.Reset ();
  641. return ansiRequest.AnsiEscapeSequenceResponse is { Valid: true };
  642. }
  643. }
  644. /// <inheritdoc/>
  645. internal override void WriteRaw (string ansi)
  646. {
  647. Console.Out.Write (ansi);
  648. Console.Out.Flush ();
  649. }
  650. private volatile bool _winSizeChanging;
  651. private void SetWindowPosition (int col, int row)
  652. {
  653. if (!RunningUnitTests)
  654. {
  655. Top = Console.WindowTop;
  656. Left = Console.WindowLeft;
  657. }
  658. else
  659. {
  660. Top = row;
  661. Left = col;
  662. }
  663. }
  664. public virtual void ResizeScreen ()
  665. {
  666. // Not supported on Unix.
  667. if (IsWinPlatform)
  668. {
  669. // Can raise an exception while is still resizing.
  670. try
  671. {
  672. #pragma warning disable CA1416
  673. if (Console.WindowHeight > 0)
  674. {
  675. Console.CursorTop = 0;
  676. Console.CursorLeft = 0;
  677. Console.WindowTop = 0;
  678. Console.WindowLeft = 0;
  679. if (Console.WindowHeight > Rows)
  680. {
  681. Console.SetWindowSize (Cols, Rows);
  682. }
  683. Console.SetBufferSize (Cols, Rows);
  684. }
  685. #pragma warning restore CA1416
  686. }
  687. // INTENT: Why are these eating the exceptions?
  688. // Comments would be good here.
  689. catch (IOException)
  690. {
  691. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  692. Clip = new (Screen);
  693. }
  694. catch (ArgumentOutOfRangeException)
  695. {
  696. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  697. Clip = new (Screen);
  698. }
  699. }
  700. else
  701. {
  702. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_SetTerminalWindowSize (Rows, Cols));
  703. }
  704. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  705. Clip = new (Screen);
  706. }
  707. #endregion Low-Level DotNet tuff
  708. }