NetDriver.cs 27 KB

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