CursesDriver.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. #nullable enable
  2. //
  3. // Driver.cs: Curses-based Driver
  4. //
  5. using System.Diagnostics;
  6. using System.Runtime.InteropServices;
  7. using Terminal.Gui.ConsoleDrivers;
  8. using Unix.Terminal;
  9. namespace Terminal.Gui;
  10. /// <summary>A Linux/Mac driver based on the Curses library.</summary>
  11. internal class CursesDriver : ConsoleDriver
  12. {
  13. public override string GetVersionInfo () { return $"{Curses.curses_version ()}"; }
  14. public override void Refresh ()
  15. {
  16. UpdateScreen ();
  17. UpdateCursor ();
  18. }
  19. public override void Suspend ()
  20. {
  21. StopReportingMouseMoves ();
  22. if (!RunningUnitTests)
  23. {
  24. Platform.Suspend ();
  25. if (Force16Colors)
  26. {
  27. Curses.Window.Standard.redrawwin ();
  28. Curses.refresh ();
  29. }
  30. }
  31. StartReportingMouseMoves ();
  32. }
  33. #region Screen and Contents
  34. public override int Cols
  35. {
  36. get => Curses.Cols;
  37. internal set
  38. {
  39. Curses.Cols = value;
  40. ClearContents ();
  41. }
  42. }
  43. public override int Rows
  44. {
  45. get => Curses.Lines;
  46. internal set
  47. {
  48. Curses.Lines = value;
  49. ClearContents ();
  50. }
  51. }
  52. public override bool IsRuneSupported (Rune rune)
  53. {
  54. // See Issue #2615 - CursesDriver is broken with non-BMP characters
  55. return base.IsRuneSupported (rune) && rune.IsBmp;
  56. }
  57. public override void Move (int col, int row)
  58. {
  59. base.Move (col, row);
  60. if (RunningUnitTests)
  61. {
  62. return;
  63. }
  64. if (IsValidLocation (col, row))
  65. {
  66. Curses.move (row, col);
  67. }
  68. else
  69. {
  70. // Not a valid location (outside screen or clip region)
  71. // Move within the clip region, then AddRune will actually move to Col, Row
  72. Curses.move (Clip.Y, Clip.X);
  73. }
  74. }
  75. public override void UpdateScreen ()
  76. {
  77. if (Force16Colors)
  78. {
  79. for (var row = 0; row < Rows; row++)
  80. {
  81. if (!_dirtyLines! [row])
  82. {
  83. continue;
  84. }
  85. _dirtyLines [row] = false;
  86. for (var col = 0; col < Cols; col++)
  87. {
  88. if (Contents! [row, col].IsDirty == false)
  89. {
  90. continue;
  91. }
  92. if (RunningUnitTests)
  93. {
  94. // In unit tests, we don't want to actually write to the screen.
  95. continue;
  96. }
  97. Curses.attrset (Contents [row, col].Attribute.GetValueOrDefault ().PlatformColor);
  98. Rune rune = Contents [row, col].Rune;
  99. if (rune.IsBmp)
  100. {
  101. // BUGBUG: CursesDriver doesn't render CharMap correctly for wide chars (and other Unicode) - Curses is doing something funky with glyphs that report GetColums() of 1 yet are rendered wide. E.g. 0x2064 (invisible times) is reported as 1 column but is rendered as 2. WindowsDriver & NetDriver correctly render this as 1 column, overlapping the next cell.
  102. if (rune.GetColumns () < 2)
  103. {
  104. Curses.mvaddch (row, col, rune.Value);
  105. }
  106. else /*if (col + 1 < Cols)*/
  107. {
  108. Curses.mvaddwstr (row, col, rune.ToString ());
  109. }
  110. }
  111. else
  112. {
  113. Curses.mvaddwstr (row, col, rune.ToString ());
  114. if (rune.GetColumns () > 1 && col + 1 < Cols)
  115. {
  116. // TODO: This is a hack to deal with non-BMP and wide characters.
  117. //col++;
  118. Curses.mvaddch (row, ++col, '*');
  119. }
  120. }
  121. }
  122. }
  123. if (!RunningUnitTests)
  124. {
  125. Curses.move (Row, Col);
  126. _window?.wrefresh ();
  127. }
  128. }
  129. else
  130. {
  131. if (RunningUnitTests
  132. || Console.WindowHeight < 1
  133. || Contents!.Length != Rows * Cols
  134. || Rows != Console.WindowHeight)
  135. {
  136. return;
  137. }
  138. var top = 0;
  139. var left = 0;
  140. int rows = Rows;
  141. int cols = Cols;
  142. var output = new StringBuilder ();
  143. Attribute? redrawAttr = null;
  144. int lastCol = -1;
  145. CursorVisibility? savedVisibility = _currentCursorVisibility;
  146. SetCursorVisibility (CursorVisibility.Invisible);
  147. for (int row = top; row < rows; row++)
  148. {
  149. if (Console.WindowHeight < 1)
  150. {
  151. return;
  152. }
  153. if (!_dirtyLines! [row])
  154. {
  155. continue;
  156. }
  157. if (!SetCursorPosition (0, row))
  158. {
  159. return;
  160. }
  161. _dirtyLines [row] = false;
  162. output.Clear ();
  163. for (int col = left; col < cols; col++)
  164. {
  165. lastCol = -1;
  166. var outputWidth = 0;
  167. for (; col < cols; col++)
  168. {
  169. if (!Contents [row, col].IsDirty)
  170. {
  171. if (output.Length > 0)
  172. {
  173. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  174. }
  175. else if (lastCol == -1)
  176. {
  177. lastCol = col;
  178. }
  179. if (lastCol + 1 < cols)
  180. {
  181. lastCol++;
  182. }
  183. continue;
  184. }
  185. if (lastCol == -1)
  186. {
  187. lastCol = col;
  188. }
  189. Attribute attr = Contents [row, col].Attribute!.Value;
  190. // Performance: Only send the escape sequence if the attribute has changed.
  191. if (attr != redrawAttr)
  192. {
  193. redrawAttr = attr;
  194. output.Append (
  195. AnsiEscapeSequenceRequestUtils.CSI_SetForegroundColorRGB (
  196. attr.Foreground.R,
  197. attr.Foreground.G,
  198. attr.Foreground.B
  199. )
  200. );
  201. output.Append (
  202. AnsiEscapeSequenceRequestUtils.CSI_SetBackgroundColorRGB (
  203. attr.Background.R,
  204. attr.Background.G,
  205. attr.Background.B
  206. )
  207. );
  208. }
  209. outputWidth++;
  210. Rune rune = Contents [row, col].Rune;
  211. output.Append (rune);
  212. if (Contents [row, col].CombiningMarks.Count > 0)
  213. {
  214. // AtlasEngine does not support NON-NORMALIZED combining marks in a way
  215. // compatible with the driver architecture. Any CMs (except in the first col)
  216. // are correctly combined with the base char, but are ALSO treated as 1 column
  217. // width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
  218. //
  219. // For now, we just ignore the list of CMs.
  220. //foreach (var combMark in Contents [row, col].CombiningMarks) {
  221. // output.Append (combMark);
  222. //}
  223. // WriteToConsole (output, ref lastCol, row, ref outputWidth);
  224. }
  225. else if (rune.IsSurrogatePair () && rune.GetColumns () < 2)
  226. {
  227. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  228. SetCursorPosition (col - 1, row);
  229. }
  230. Contents [row, col].IsDirty = false;
  231. }
  232. }
  233. if (output.Length > 0)
  234. {
  235. SetCursorPosition (lastCol, row);
  236. Console.Write (output);
  237. }
  238. }
  239. // SIXELS
  240. foreach (SixelToRender s in Application.Sixel)
  241. {
  242. SetCursorPosition (s.ScreenPosition.X, s.ScreenPosition.Y);
  243. Console.Write (s.SixelData);
  244. }
  245. SetCursorPosition (0, 0);
  246. _currentCursorVisibility = savedVisibility;
  247. void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
  248. {
  249. SetCursorPosition (lastCol, row);
  250. Console.Write (output);
  251. output.Clear ();
  252. lastCol += outputWidth;
  253. outputWidth = 0;
  254. }
  255. }
  256. }
  257. #endregion Screen and Contents
  258. #region Color Handling
  259. public override bool SupportsTrueColor => true;
  260. /// <summary>Creates an Attribute from the provided curses-based foreground and background color numbers</summary>
  261. /// <param name="foreground">Contains the curses color number for the foreground (color, plus any attributes)</param>
  262. /// <param name="background">Contains the curses color number for the background (color, plus any attributes)</param>
  263. /// <returns></returns>
  264. private static Attribute MakeColor (short foreground, short background)
  265. {
  266. //var v = (short)((ushort)foreground | (background << 4));
  267. var v = (short)(((ushort)(foreground & 0xffff) << 16) | (background & 0xffff));
  268. // TODO: for TrueColor - Use InitExtendedPair
  269. Curses.InitColorPair (v, foreground, background);
  270. return new (
  271. Curses.ColorPair (v),
  272. CursesColorNumberToColorName16 (foreground),
  273. CursesColorNumberToColorName16 (background)
  274. );
  275. }
  276. /// <inheritdoc/>
  277. /// <remarks>
  278. /// In the CursesDriver, colors are encoded as an int. The foreground color is stored in the most significant 4
  279. /// bits, and the background color is stored in the least significant 4 bits. The Terminal.GUi Color values are
  280. /// converted to curses color encoding before being encoded.
  281. /// </remarks>
  282. public override Attribute MakeColor (in Color foreground, in Color background)
  283. {
  284. if (!RunningUnitTests && Force16Colors)
  285. {
  286. return MakeColor (
  287. ColorNameToCursesColorNumber (foreground.GetClosestNamedColor16 ()),
  288. ColorNameToCursesColorNumber (background.GetClosestNamedColor16 ())
  289. );
  290. }
  291. return new (
  292. 0,
  293. foreground,
  294. background
  295. );
  296. }
  297. private static short ColorNameToCursesColorNumber (ColorName16 color)
  298. {
  299. switch (color)
  300. {
  301. case ColorName16.Black:
  302. return Curses.COLOR_BLACK;
  303. case ColorName16.Blue:
  304. return Curses.COLOR_BLUE;
  305. case ColorName16.Green:
  306. return Curses.COLOR_GREEN;
  307. case ColorName16.Cyan:
  308. return Curses.COLOR_CYAN;
  309. case ColorName16.Red:
  310. return Curses.COLOR_RED;
  311. case ColorName16.Magenta:
  312. return Curses.COLOR_MAGENTA;
  313. case ColorName16.Yellow:
  314. return Curses.COLOR_YELLOW;
  315. case ColorName16.Gray:
  316. return Curses.COLOR_WHITE;
  317. case ColorName16.DarkGray:
  318. return Curses.COLOR_GRAY;
  319. case ColorName16.BrightBlue:
  320. return Curses.COLOR_BLUE | Curses.COLOR_GRAY;
  321. case ColorName16.BrightGreen:
  322. return Curses.COLOR_GREEN | Curses.COLOR_GRAY;
  323. case ColorName16.BrightCyan:
  324. return Curses.COLOR_CYAN | Curses.COLOR_GRAY;
  325. case ColorName16.BrightRed:
  326. return Curses.COLOR_RED | Curses.COLOR_GRAY;
  327. case ColorName16.BrightMagenta:
  328. return Curses.COLOR_MAGENTA | Curses.COLOR_GRAY;
  329. case ColorName16.BrightYellow:
  330. return Curses.COLOR_YELLOW | Curses.COLOR_GRAY;
  331. case ColorName16.White:
  332. return Curses.COLOR_WHITE | Curses.COLOR_GRAY;
  333. }
  334. throw new ArgumentException ("Invalid color code");
  335. }
  336. private static ColorName16 CursesColorNumberToColorName16 (short color)
  337. {
  338. switch (color)
  339. {
  340. case Curses.COLOR_BLACK:
  341. return ColorName16.Black;
  342. case Curses.COLOR_BLUE:
  343. return ColorName16.Blue;
  344. case Curses.COLOR_GREEN:
  345. return ColorName16.Green;
  346. case Curses.COLOR_CYAN:
  347. return ColorName16.Cyan;
  348. case Curses.COLOR_RED:
  349. return ColorName16.Red;
  350. case Curses.COLOR_MAGENTA:
  351. return ColorName16.Magenta;
  352. case Curses.COLOR_YELLOW:
  353. return ColorName16.Yellow;
  354. case Curses.COLOR_WHITE:
  355. return ColorName16.Gray;
  356. case Curses.COLOR_GRAY:
  357. return ColorName16.DarkGray;
  358. case Curses.COLOR_BLUE | Curses.COLOR_GRAY:
  359. return ColorName16.BrightBlue;
  360. case Curses.COLOR_GREEN | Curses.COLOR_GRAY:
  361. return ColorName16.BrightGreen;
  362. case Curses.COLOR_CYAN | Curses.COLOR_GRAY:
  363. return ColorName16.BrightCyan;
  364. case Curses.COLOR_RED | Curses.COLOR_GRAY:
  365. return ColorName16.BrightRed;
  366. case Curses.COLOR_MAGENTA | Curses.COLOR_GRAY:
  367. return ColorName16.BrightMagenta;
  368. case Curses.COLOR_YELLOW | Curses.COLOR_GRAY:
  369. return ColorName16.BrightYellow;
  370. case Curses.COLOR_WHITE | Curses.COLOR_GRAY:
  371. return ColorName16.White;
  372. }
  373. throw new ArgumentException ("Invalid curses color code");
  374. }
  375. #endregion
  376. #region Cursor Support
  377. private CursorVisibility? _currentCursorVisibility;
  378. private CursorVisibility? _initialCursorVisibility;
  379. /// <inheritdoc/>
  380. public override bool EnsureCursorVisibility ()
  381. {
  382. if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows))
  383. {
  384. GetCursorVisibility (out CursorVisibility cursorVisibility);
  385. _currentCursorVisibility = cursorVisibility;
  386. SetCursorVisibility (CursorVisibility.Invisible);
  387. return false;
  388. }
  389. SetCursorVisibility (_currentCursorVisibility ?? CursorVisibility.Default);
  390. return _currentCursorVisibility == CursorVisibility.Default;
  391. }
  392. /// <inheritdoc/>
  393. public override bool GetCursorVisibility (out CursorVisibility visibility)
  394. {
  395. visibility = CursorVisibility.Invisible;
  396. if (!_currentCursorVisibility.HasValue)
  397. {
  398. return false;
  399. }
  400. visibility = _currentCursorVisibility.Value;
  401. return true;
  402. }
  403. /// <inheritdoc/>
  404. public override bool SetCursorVisibility (CursorVisibility visibility)
  405. {
  406. if (_initialCursorVisibility.HasValue == false)
  407. {
  408. return false;
  409. }
  410. if (!RunningUnitTests)
  411. {
  412. Curses.curs_set (((int)visibility >> 16) & 0x000000FF);
  413. }
  414. if (visibility != CursorVisibility.Invisible)
  415. {
  416. Console.Out.Write (
  417. AnsiEscapeSequenceRequestUtils.CSI_SetCursorStyle (
  418. (AnsiEscapeSequenceRequestUtils.DECSCUSR_Style)(((int)visibility >> 24)
  419. & 0xFF)
  420. )
  421. );
  422. }
  423. _currentCursorVisibility = visibility;
  424. return true;
  425. }
  426. public override void UpdateCursor ()
  427. {
  428. EnsureCursorVisibility ();
  429. if (!RunningUnitTests && Col >= 0 && Col < Cols && Row >= 0 && Row < Rows)
  430. {
  431. if (Force16Colors)
  432. {
  433. Curses.move (Row, Col);
  434. Curses.raw ();
  435. Curses.noecho ();
  436. Curses.refresh ();
  437. }
  438. else
  439. {
  440. _mainLoopDriver?.WriteRaw (AnsiEscapeSequenceRequestUtils.CSI_SetCursorPosition (Row + 1, Col + 1));
  441. }
  442. }
  443. }
  444. #endregion Cursor Support
  445. #region Keyboard Support
  446. public override void SendKeys (char keyChar, ConsoleKey consoleKey, bool shift, bool alt, bool control)
  447. {
  448. KeyCode key;
  449. if (consoleKey == ConsoleKey.Packet)
  450. {
  451. //var mod = new ConsoleModifiers ();
  452. //if (shift)
  453. //{
  454. // mod |= ConsoleModifiers.Shift;
  455. //}
  456. //if (alt)
  457. //{
  458. // mod |= ConsoleModifiers.Alt;
  459. //}
  460. //if (control)
  461. //{
  462. // mod |= ConsoleModifiers.Control;
  463. //}
  464. var cKeyInfo = new ConsoleKeyInfo (keyChar, consoleKey, shift, alt, control);
  465. cKeyInfo = ConsoleKeyMapping.DecodeVKPacketToKConsoleKeyInfo (cKeyInfo);
  466. key = ConsoleKeyMapping.MapConsoleKeyInfoToKeyCode (cKeyInfo);
  467. }
  468. else
  469. {
  470. key = (KeyCode)keyChar;
  471. }
  472. OnKeyDown (new (key));
  473. OnKeyUp (new (key));
  474. //OnKeyPressed (new KeyEventArgsEventArgs (key));
  475. }
  476. #endregion Keyboard Support
  477. #region Mouse Support
  478. public void StartReportingMouseMoves ()
  479. {
  480. if (!RunningUnitTests)
  481. {
  482. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_EnableMouseEvents);
  483. }
  484. }
  485. public void StopReportingMouseMoves ()
  486. {
  487. if (!RunningUnitTests)
  488. {
  489. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_DisableMouseEvents);
  490. }
  491. }
  492. #endregion Mouse Support
  493. private bool SetCursorPosition (int col, int row)
  494. {
  495. // + 1 is needed because non-Windows is based on 1 instead of 0 and
  496. // Console.CursorTop/CursorLeft isn't reliable.
  497. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_SetCursorPosition (row + 1, col + 1));
  498. return true;
  499. }
  500. #region Init/End/MainLoop
  501. public Curses.Window? _window;
  502. private UnixMainLoop? _mainLoopDriver;
  503. internal override MainLoop Init ()
  504. {
  505. _mainLoopDriver = new (this);
  506. if (!RunningUnitTests)
  507. {
  508. _window = Curses.initscr ();
  509. Curses.set_escdelay (10);
  510. // Ensures that all procedures are performed at some previous closing.
  511. Curses.doupdate ();
  512. //
  513. // We are setting Invisible as default, so we could ignore XTerm DECSUSR setting
  514. //
  515. switch (Curses.curs_set (0))
  516. {
  517. case 0:
  518. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Invisible;
  519. break;
  520. case 1:
  521. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Underline;
  522. Curses.curs_set (1);
  523. break;
  524. case 2:
  525. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Box;
  526. Curses.curs_set (2);
  527. break;
  528. default:
  529. _currentCursorVisibility = _initialCursorVisibility = null;
  530. break;
  531. }
  532. if (!Curses.HasColors)
  533. {
  534. throw new InvalidOperationException ("V2 - This should never happen. File an Issue if it does.");
  535. }
  536. Curses.raw ();
  537. Curses.noecho ();
  538. Curses.Window.Standard.keypad (true);
  539. Curses.StartColor ();
  540. Curses.UseDefaultColors ();
  541. if (!RunningUnitTests)
  542. {
  543. Curses.timeout (0);
  544. }
  545. }
  546. CurrentAttribute = new (ColorName16.White, ColorName16.Black);
  547. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  548. {
  549. Clipboard = new FakeDriver.FakeClipboard ();
  550. }
  551. else
  552. {
  553. if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
  554. {
  555. Clipboard = new MacOSXClipboard ();
  556. }
  557. else
  558. {
  559. if (Is_WSL_Platform ())
  560. {
  561. Clipboard = new WSLClipboard ();
  562. }
  563. else
  564. {
  565. Clipboard = new CursesClipboard ();
  566. }
  567. }
  568. }
  569. ClearContents ();
  570. StartReportingMouseMoves ();
  571. if (!RunningUnitTests)
  572. {
  573. Curses.CheckWinChange ();
  574. ClearContents ();
  575. if (Force16Colors)
  576. {
  577. Curses.refresh ();
  578. }
  579. }
  580. return new (_mainLoopDriver);
  581. }
  582. internal void ProcessInput (UnixMainLoop.PollData inputEvent)
  583. {
  584. switch (inputEvent.EventType)
  585. {
  586. case UnixMainLoop.EventType.Key:
  587. ConsoleKeyInfo consoleKeyInfo = inputEvent.KeyEvent;
  588. KeyCode map = AnsiEscapeSequenceRequestUtils.MapKey (consoleKeyInfo);
  589. if (map == KeyCode.Null)
  590. {
  591. break;
  592. }
  593. OnKeyDown (new (map));
  594. OnKeyUp (new (map));
  595. break;
  596. case UnixMainLoop.EventType.Mouse:
  597. var me = new MouseEventArgs { Position = inputEvent.MouseEvent.Position, Flags = inputEvent.MouseEvent.MouseFlags };
  598. OnMouseEvent (me);
  599. break;
  600. case UnixMainLoop.EventType.WindowSize:
  601. Size size = new (inputEvent.WindowSizeEvent.Size.Width, inputEvent.WindowSizeEvent.Size.Height);
  602. ProcessWinChange (size);
  603. break;
  604. default:
  605. throw new ArgumentOutOfRangeException ();
  606. }
  607. }
  608. private void ProcessWinChange (Size size)
  609. {
  610. if (!RunningUnitTests && Curses.ChangeWindowSize (size.Height, size.Width))
  611. {
  612. ClearContents ();
  613. OnSizeChanged (new (new (Cols, Rows)));
  614. }
  615. }
  616. internal override void End ()
  617. {
  618. _ansiResponseTokenSource?.Cancel ();
  619. _ansiResponseTokenSource?.Dispose ();
  620. _waitAnsiResponse.Dispose ();
  621. StopReportingMouseMoves ();
  622. SetCursorVisibility (CursorVisibility.Default);
  623. if (RunningUnitTests)
  624. {
  625. return;
  626. }
  627. // throws away any typeahead that has been typed by
  628. // the user and has not yet been read by the program.
  629. Curses.flushinp ();
  630. Curses.endwin ();
  631. }
  632. #endregion Init/End/MainLoop
  633. public static bool Is_WSL_Platform ()
  634. {
  635. // xclip does not work on WSL, so we need to use the Windows clipboard vis Powershell
  636. //if (new CursesClipboard ().IsSupported) {
  637. // // If xclip is installed on Linux under WSL, this will return true.
  638. // return false;
  639. //}
  640. (int exitCode, string result) = ClipboardProcessRunner.Bash ("uname -a", waitForOutput: true);
  641. if (exitCode == 0 && result.Contains ("microsoft") && result.Contains ("WSL"))
  642. {
  643. return true;
  644. }
  645. return false;
  646. }
  647. #region Low-Level Unix Stuff
  648. private readonly ManualResetEventSlim _waitAnsiResponse = new (false);
  649. private CancellationTokenSource? _ansiResponseTokenSource;
  650. /// <inheritdoc/>
  651. public override bool TryWriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest)
  652. {
  653. if (_mainLoopDriver is null)
  654. {
  655. return false;
  656. }
  657. _ansiResponseTokenSource ??= new ();
  658. try
  659. {
  660. lock (ansiRequest._responseLock)
  661. {
  662. ansiRequest.ResponseFromInput += (s, e) =>
  663. {
  664. Debug.Assert (s == ansiRequest);
  665. Debug.Assert (e == ansiRequest.AnsiEscapeSequenceResponse);
  666. _waitAnsiResponse.Set ();
  667. };
  668. _mainLoopDriver.EscSeqRequests.Add (ansiRequest, this);
  669. _mainLoopDriver._forceRead = true;
  670. }
  671. if (!_ansiResponseTokenSource.IsCancellationRequested)
  672. {
  673. _mainLoopDriver._waitForInput.Set ();
  674. _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token);
  675. }
  676. }
  677. catch (OperationCanceledException)
  678. {
  679. return false;
  680. }
  681. lock (ansiRequest._responseLock)
  682. {
  683. _mainLoopDriver._forceRead = false;
  684. if (_mainLoopDriver.EscSeqRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus? request))
  685. {
  686. if (_mainLoopDriver.EscSeqRequests.Statuses.Count > 0
  687. && string.IsNullOrEmpty (request.AnsiRequest.AnsiEscapeSequenceResponse?.Response))
  688. {
  689. lock (request.AnsiRequest._responseLock)
  690. {
  691. // Bad request or no response at all
  692. _mainLoopDriver.EscSeqRequests.Statuses.TryDequeue (out _);
  693. }
  694. }
  695. }
  696. _waitAnsiResponse.Reset ();
  697. return ansiRequest.AnsiEscapeSequenceResponse is { Valid: true };
  698. }
  699. }
  700. /// <inheritdoc/>
  701. internal override void WriteRaw (string ansi) { _mainLoopDriver?.WriteRaw (ansi); }
  702. }
  703. // TODO: One type per file - move to another file
  704. internal static class Platform
  705. {
  706. private static int _suspendSignal;
  707. /// <summary>Suspends the process by sending SIGTSTP to itself</summary>
  708. /// <returns>True if the suspension was successful.</returns>
  709. public static bool Suspend ()
  710. {
  711. int signal = GetSuspendSignal ();
  712. if (signal == -1)
  713. {
  714. return false;
  715. }
  716. killpg (0, signal);
  717. return true;
  718. }
  719. private static int GetSuspendSignal ()
  720. {
  721. if (_suspendSignal != 0)
  722. {
  723. return _suspendSignal;
  724. }
  725. nint buf = Marshal.AllocHGlobal (8192);
  726. if (uname (buf) != 0)
  727. {
  728. Marshal.FreeHGlobal (buf);
  729. _suspendSignal = -1;
  730. return _suspendSignal;
  731. }
  732. try
  733. {
  734. switch (Marshal.PtrToStringAnsi (buf))
  735. {
  736. case "Darwin":
  737. case "DragonFly":
  738. case "FreeBSD":
  739. case "NetBSD":
  740. case "OpenBSD":
  741. _suspendSignal = 18;
  742. break;
  743. case "Linux":
  744. // TODO: should fetch the machine name and
  745. // if it is MIPS return 24
  746. _suspendSignal = 20;
  747. break;
  748. case "Solaris":
  749. _suspendSignal = 24;
  750. break;
  751. default:
  752. _suspendSignal = -1;
  753. break;
  754. }
  755. return _suspendSignal;
  756. }
  757. finally
  758. {
  759. Marshal.FreeHGlobal (buf);
  760. }
  761. }
  762. [DllImport ("libc")]
  763. private static extern int killpg (int pgrp, int pid);
  764. [DllImport ("libc")]
  765. private static extern int uname (nint buf);
  766. }
  767. #endregion Low-Level Unix Stuff