CursesDriver.cs 26 KB

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