NetDriver.cs 27 KB

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