NetDriver.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. // TODO: #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. ;
  281. ResizeScreen ();
  282. ClearContents ();
  283. _winSizeChanging = false;
  284. OnSizeChanged (new (new (Cols, Rows)));
  285. break;
  286. case EventType.RequestResponse:
  287. break;
  288. case EventType.WindowPosition:
  289. break;
  290. default:
  291. throw new ArgumentOutOfRangeException ();
  292. }
  293. }
  294. internal override void End ()
  295. {
  296. if (IsWinPlatform)
  297. {
  298. NetWinConsole?.Cleanup ();
  299. }
  300. StopReportingMouseMoves ();
  301. _ansiResponseTokenSource?.Cancel ();
  302. _ansiResponseTokenSource?.Dispose ();
  303. _waitAnsiResponse?.Dispose ();
  304. if (!RunningUnitTests)
  305. {
  306. Console.ResetColor ();
  307. //Disable alternative screen buffer.
  308. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  309. //Set cursor key to cursor.
  310. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_ShowCursor);
  311. Console.Out.Close ();
  312. }
  313. }
  314. #endregion Init/End/MainLoop
  315. #region Color Handling
  316. public override bool SupportsTrueColor => Environment.OSVersion.Platform == PlatformID.Unix
  317. || (IsWinPlatform && Environment.OSVersion.Version.Build >= 14931);
  318. private const int COLOR_BLACK = 30;
  319. private const int COLOR_BLUE = 34;
  320. private const int COLOR_BRIGHT_BLACK = 90;
  321. private const int COLOR_BRIGHT_BLUE = 94;
  322. private const int COLOR_BRIGHT_CYAN = 96;
  323. private const int COLOR_BRIGHT_GREEN = 92;
  324. private const int COLOR_BRIGHT_MAGENTA = 95;
  325. private const int COLOR_BRIGHT_RED = 91;
  326. private const int COLOR_BRIGHT_WHITE = 97;
  327. private const int COLOR_BRIGHT_YELLOW = 93;
  328. private const int COLOR_CYAN = 36;
  329. private const int COLOR_GREEN = 32;
  330. private const int COLOR_MAGENTA = 35;
  331. private const int COLOR_RED = 31;
  332. private const int COLOR_WHITE = 37;
  333. private const int COLOR_YELLOW = 33;
  334. // Cache the list of ConsoleColor values.
  335. [UnconditionalSuppressMessage (
  336. "AOT",
  337. "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.",
  338. Justification = "<Pending>")]
  339. private static readonly HashSet<int> ConsoleColorValues = new (
  340. Enum.GetValues (typeof (ConsoleColor))
  341. .OfType<ConsoleColor> ()
  342. .Select (c => (int)c)
  343. );
  344. // Dictionary for mapping ConsoleColor values to the values used by System.Net.Console.
  345. private static readonly Dictionary<ConsoleColor, int> colorMap = new ()
  346. {
  347. { ConsoleColor.Black, COLOR_BLACK },
  348. { ConsoleColor.DarkBlue, COLOR_BLUE },
  349. { ConsoleColor.DarkGreen, COLOR_GREEN },
  350. { ConsoleColor.DarkCyan, COLOR_CYAN },
  351. { ConsoleColor.DarkRed, COLOR_RED },
  352. { ConsoleColor.DarkMagenta, COLOR_MAGENTA },
  353. { ConsoleColor.DarkYellow, COLOR_YELLOW },
  354. { ConsoleColor.Gray, COLOR_WHITE },
  355. { ConsoleColor.DarkGray, COLOR_BRIGHT_BLACK },
  356. { ConsoleColor.Blue, COLOR_BRIGHT_BLUE },
  357. { ConsoleColor.Green, COLOR_BRIGHT_GREEN },
  358. { ConsoleColor.Cyan, COLOR_BRIGHT_CYAN },
  359. { ConsoleColor.Red, COLOR_BRIGHT_RED },
  360. { ConsoleColor.Magenta, COLOR_BRIGHT_MAGENTA },
  361. { ConsoleColor.Yellow, COLOR_BRIGHT_YELLOW },
  362. { ConsoleColor.White, COLOR_BRIGHT_WHITE }
  363. };
  364. // Map a ConsoleColor to a platform dependent value.
  365. private int MapColors (ConsoleColor color, bool isForeground = true)
  366. {
  367. return colorMap.TryGetValue (color, out int colorValue) ? colorValue + (isForeground ? 0 : 10) : 0;
  368. }
  369. #endregion
  370. #region Cursor Handling
  371. private bool SetCursorPosition (int col, int row)
  372. {
  373. if (IsWinPlatform)
  374. {
  375. // Could happens that the windows is still resizing and the col is bigger than Console.WindowWidth.
  376. try
  377. {
  378. Console.SetCursorPosition (col, row);
  379. return true;
  380. }
  381. catch (Exception)
  382. {
  383. return false;
  384. }
  385. }
  386. // + 1 is needed because non-Windows is based on 1 instead of 0 and
  387. // Console.CursorTop/CursorLeft isn't reliable.
  388. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_SetCursorPosition (row + 1, col + 1));
  389. return true;
  390. }
  391. private CursorVisibility? _cachedCursorVisibility;
  392. public override void UpdateCursor ()
  393. {
  394. EnsureCursorVisibility ();
  395. if (Col >= 0 && Col < Cols && Row >= 0 && Row <= Rows)
  396. {
  397. SetCursorPosition (Col, Row);
  398. SetWindowPosition (0, Row);
  399. }
  400. }
  401. public override bool GetCursorVisibility (out CursorVisibility visibility)
  402. {
  403. visibility = _cachedCursorVisibility ?? CursorVisibility.Default;
  404. return visibility == CursorVisibility.Default;
  405. }
  406. public override bool SetCursorVisibility (CursorVisibility visibility)
  407. {
  408. _cachedCursorVisibility = visibility;
  409. Console.Out.Write (visibility == CursorVisibility.Default ? AnsiEscapeSequenceRequestUtils.CSI_ShowCursor : AnsiEscapeSequenceRequestUtils.CSI_HideCursor);
  410. return visibility == CursorVisibility.Default;
  411. }
  412. public override bool EnsureCursorVisibility ()
  413. {
  414. if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows))
  415. {
  416. GetCursorVisibility (out CursorVisibility cursorVisibility);
  417. _cachedCursorVisibility = cursorVisibility;
  418. SetCursorVisibility (CursorVisibility.Invisible);
  419. return false;
  420. }
  421. SetCursorVisibility (_cachedCursorVisibility ?? CursorVisibility.Default);
  422. return _cachedCursorVisibility == CursorVisibility.Default;
  423. }
  424. #endregion
  425. #region Mouse Handling
  426. public void StartReportingMouseMoves ()
  427. {
  428. if (!RunningUnitTests)
  429. {
  430. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_EnableMouseEvents);
  431. }
  432. }
  433. public void StopReportingMouseMoves ()
  434. {
  435. if (!RunningUnitTests)
  436. {
  437. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_DisableMouseEvents);
  438. }
  439. }
  440. private MouseEventArgs ToDriverMouse (MouseEvent me)
  441. {
  442. //System.Diagnostics.Debug.WriteLine ($"X: {me.Position.X}; Y: {me.Position.Y}; ButtonState: {me.ButtonState}");
  443. MouseFlags mouseFlag = 0;
  444. if ((me.ButtonState & MouseButtonState.Button1Pressed) != 0)
  445. {
  446. mouseFlag |= MouseFlags.Button1Pressed;
  447. }
  448. if ((me.ButtonState & MouseButtonState.Button1Released) != 0)
  449. {
  450. mouseFlag |= MouseFlags.Button1Released;
  451. }
  452. if ((me.ButtonState & MouseButtonState.Button1Clicked) != 0)
  453. {
  454. mouseFlag |= MouseFlags.Button1Clicked;
  455. }
  456. if ((me.ButtonState & MouseButtonState.Button1DoubleClicked) != 0)
  457. {
  458. mouseFlag |= MouseFlags.Button1DoubleClicked;
  459. }
  460. if ((me.ButtonState & MouseButtonState.Button1TripleClicked) != 0)
  461. {
  462. mouseFlag |= MouseFlags.Button1TripleClicked;
  463. }
  464. if ((me.ButtonState & MouseButtonState.Button2Pressed) != 0)
  465. {
  466. mouseFlag |= MouseFlags.Button2Pressed;
  467. }
  468. if ((me.ButtonState & MouseButtonState.Button2Released) != 0)
  469. {
  470. mouseFlag |= MouseFlags.Button2Released;
  471. }
  472. if ((me.ButtonState & MouseButtonState.Button2Clicked) != 0)
  473. {
  474. mouseFlag |= MouseFlags.Button2Clicked;
  475. }
  476. if ((me.ButtonState & MouseButtonState.Button2DoubleClicked) != 0)
  477. {
  478. mouseFlag |= MouseFlags.Button2DoubleClicked;
  479. }
  480. if ((me.ButtonState & MouseButtonState.Button2TripleClicked) != 0)
  481. {
  482. mouseFlag |= MouseFlags.Button2TripleClicked;
  483. }
  484. if ((me.ButtonState & MouseButtonState.Button3Pressed) != 0)
  485. {
  486. mouseFlag |= MouseFlags.Button3Pressed;
  487. }
  488. if ((me.ButtonState & MouseButtonState.Button3Released) != 0)
  489. {
  490. mouseFlag |= MouseFlags.Button3Released;
  491. }
  492. if ((me.ButtonState & MouseButtonState.Button3Clicked) != 0)
  493. {
  494. mouseFlag |= MouseFlags.Button3Clicked;
  495. }
  496. if ((me.ButtonState & MouseButtonState.Button3DoubleClicked) != 0)
  497. {
  498. mouseFlag |= MouseFlags.Button3DoubleClicked;
  499. }
  500. if ((me.ButtonState & MouseButtonState.Button3TripleClicked) != 0)
  501. {
  502. mouseFlag |= MouseFlags.Button3TripleClicked;
  503. }
  504. if ((me.ButtonState & MouseButtonState.ButtonWheeledUp) != 0)
  505. {
  506. mouseFlag |= MouseFlags.WheeledUp;
  507. }
  508. if ((me.ButtonState & MouseButtonState.ButtonWheeledDown) != 0)
  509. {
  510. mouseFlag |= MouseFlags.WheeledDown;
  511. }
  512. if ((me.ButtonState & MouseButtonState.ButtonWheeledLeft) != 0)
  513. {
  514. mouseFlag |= MouseFlags.WheeledLeft;
  515. }
  516. if ((me.ButtonState & MouseButtonState.ButtonWheeledRight) != 0)
  517. {
  518. mouseFlag |= MouseFlags.WheeledRight;
  519. }
  520. if ((me.ButtonState & MouseButtonState.Button4Pressed) != 0)
  521. {
  522. mouseFlag |= MouseFlags.Button4Pressed;
  523. }
  524. if ((me.ButtonState & MouseButtonState.Button4Released) != 0)
  525. {
  526. mouseFlag |= MouseFlags.Button4Released;
  527. }
  528. if ((me.ButtonState & MouseButtonState.Button4Clicked) != 0)
  529. {
  530. mouseFlag |= MouseFlags.Button4Clicked;
  531. }
  532. if ((me.ButtonState & MouseButtonState.Button4DoubleClicked) != 0)
  533. {
  534. mouseFlag |= MouseFlags.Button4DoubleClicked;
  535. }
  536. if ((me.ButtonState & MouseButtonState.Button4TripleClicked) != 0)
  537. {
  538. mouseFlag |= MouseFlags.Button4TripleClicked;
  539. }
  540. if ((me.ButtonState & MouseButtonState.ReportMousePosition) != 0)
  541. {
  542. mouseFlag |= MouseFlags.ReportMousePosition;
  543. }
  544. if ((me.ButtonState & MouseButtonState.ButtonShift) != 0)
  545. {
  546. mouseFlag |= MouseFlags.ButtonShift;
  547. }
  548. if ((me.ButtonState & MouseButtonState.ButtonCtrl) != 0)
  549. {
  550. mouseFlag |= MouseFlags.ButtonCtrl;
  551. }
  552. if ((me.ButtonState & MouseButtonState.ButtonAlt) != 0)
  553. {
  554. mouseFlag |= MouseFlags.ButtonAlt;
  555. }
  556. return new() { Position = me.Position, Flags = mouseFlag };
  557. }
  558. #endregion Mouse Handling
  559. #region Keyboard Handling
  560. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  561. {
  562. var input = new InputResult
  563. {
  564. EventType = EventType.Key, ConsoleKeyInfo = new (keyChar, key, shift, alt, control)
  565. };
  566. try
  567. {
  568. ProcessInput (input);
  569. }
  570. catch (OverflowException)
  571. { }
  572. }
  573. private ConsoleKeyInfo FromVKPacketToKConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo)
  574. {
  575. if (consoleKeyInfo.Key != ConsoleKey.Packet)
  576. {
  577. return consoleKeyInfo;
  578. }
  579. ConsoleModifiers mod = consoleKeyInfo.Modifiers;
  580. bool shift = (mod & ConsoleModifiers.Shift) != 0;
  581. bool alt = (mod & ConsoleModifiers.Alt) != 0;
  582. bool control = (mod & ConsoleModifiers.Control) != 0;
  583. ConsoleKeyInfo cKeyInfo = DecodeVKPacketToKConsoleKeyInfo (consoleKeyInfo);
  584. return new (cKeyInfo.KeyChar, cKeyInfo.Key, shift, alt, control);
  585. }
  586. #endregion Keyboard Handling
  587. #region Low-Level DotNet tuff
  588. private readonly ManualResetEventSlim _waitAnsiResponse = new (false);
  589. private readonly CancellationTokenSource _ansiResponseTokenSource = new ();
  590. /// <inheritdoc/>
  591. public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest)
  592. {
  593. if (_mainLoopDriver is null)
  594. {
  595. return string.Empty;
  596. }
  597. try
  598. {
  599. lock (ansiRequest._responseLock)
  600. {
  601. ansiRequest.ResponseFromInput += (s, e) =>
  602. {
  603. Debug.Assert (s == ansiRequest);
  604. Debug.Assert (e == ansiRequest.Response);
  605. _waitAnsiResponse.Set ();
  606. };
  607. _mainLoopDriver._netEvents.EscSeqRequests.Add (ansiRequest);
  608. _mainLoopDriver._netEvents._forceRead = true;
  609. }
  610. if (!_ansiResponseTokenSource.IsCancellationRequested)
  611. {
  612. _mainLoopDriver._netEvents._waitForStart.Set ();
  613. if (!_mainLoopDriver._waitForProbe.IsSet)
  614. {
  615. _mainLoopDriver._waitForProbe.Set ();
  616. }
  617. _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token);
  618. }
  619. }
  620. catch (OperationCanceledException)
  621. {
  622. return string.Empty;
  623. }
  624. lock (ansiRequest._responseLock)
  625. {
  626. _mainLoopDriver._netEvents._forceRead = false;
  627. if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus request))
  628. {
  629. if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.Count > 0
  630. && string.IsNullOrEmpty (request.AnsiRequest.Response))
  631. {
  632. lock (request!.AnsiRequest._responseLock)
  633. {
  634. // Bad request or no response at all
  635. _mainLoopDriver._netEvents.EscSeqRequests.Statuses.TryDequeue (out _);
  636. }
  637. }
  638. }
  639. _waitAnsiResponse.Reset ();
  640. return ansiRequest.Response;
  641. }
  642. }
  643. /// <inheritdoc/>
  644. public override void WriteRaw (string ansi) { throw new NotImplementedException (); }
  645. private volatile bool _winSizeChanging;
  646. private void SetWindowPosition (int col, int row)
  647. {
  648. if (!RunningUnitTests)
  649. {
  650. Top = Console.WindowTop;
  651. Left = Console.WindowLeft;
  652. }
  653. else
  654. {
  655. Top = row;
  656. Left = col;
  657. }
  658. }
  659. private void ResizeScreen ()
  660. {
  661. // Not supported on Unix.
  662. if (IsWinPlatform)
  663. {
  664. // Can raise an exception while is still resizing.
  665. try
  666. {
  667. #pragma warning disable CA1416
  668. if (Console.WindowHeight > 0)
  669. {
  670. Console.CursorTop = 0;
  671. Console.CursorLeft = 0;
  672. Console.WindowTop = 0;
  673. Console.WindowLeft = 0;
  674. if (Console.WindowHeight > Rows)
  675. {
  676. Console.SetWindowSize (Cols, Rows);
  677. }
  678. Console.SetBufferSize (Cols, Rows);
  679. }
  680. #pragma warning restore CA1416
  681. }
  682. // INTENT: Why are these eating the exceptions?
  683. // Comments would be good here.
  684. catch (IOException)
  685. {
  686. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  687. Clip = new (0, 0, Cols, Rows);
  688. }
  689. catch (ArgumentOutOfRangeException)
  690. {
  691. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  692. Clip = new (0, 0, Cols, Rows);
  693. }
  694. }
  695. else
  696. {
  697. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_SetTerminalWindowSize (Rows, Cols));
  698. }
  699. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  700. Clip = new (0, 0, Cols, Rows);
  701. }
  702. #endregion Low-Level DotNet tuff
  703. }