CursesDriver.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  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. public override int Cols
  14. {
  15. get => Curses.Cols;
  16. set
  17. {
  18. Curses.Cols = value;
  19. ClearContents ();
  20. }
  21. }
  22. public 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 (EscSeqUtils.CSI_EnableMouseEvents);
  90. }
  91. }
  92. public void StopReportingMouseMoves ()
  93. {
  94. if (!RunningUnitTests)
  95. {
  96. Console.Out.Write (EscSeqUtils.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 (EscSeqUtils.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. EscSeqUtils.CSI_SetForegroundColorRGB (
  254. attr.Foreground.R,
  255. attr.Foreground.G,
  256. attr.Foreground.B
  257. )
  258. );
  259. output.Append (
  260. EscSeqUtils.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. private void EnsureCursorVisibility ()
  437. {
  438. if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows))
  439. {
  440. GetCursorVisibility (out CursorVisibility cursorVisibility);
  441. _currentCursorVisibility = cursorVisibility;
  442. SetCursorVisibility (CursorVisibility.Invisible);
  443. return;
  444. }
  445. SetCursorVisibility (_currentCursorVisibility ?? CursorVisibility.Default);
  446. }
  447. /// <inheritdoc/>
  448. public override bool GetCursorVisibility (out CursorVisibility visibility)
  449. {
  450. visibility = CursorVisibility.Invisible;
  451. if (!_currentCursorVisibility.HasValue)
  452. {
  453. return false;
  454. }
  455. visibility = _currentCursorVisibility.Value;
  456. return true;
  457. }
  458. /// <inheritdoc/>
  459. public override bool SetCursorVisibility (CursorVisibility visibility)
  460. {
  461. if (_initialCursorVisibility.HasValue == false)
  462. {
  463. return false;
  464. }
  465. if (!RunningUnitTests)
  466. {
  467. Curses.curs_set (((int)visibility >> 16) & 0x000000FF);
  468. }
  469. if (visibility != CursorVisibility.Invisible)
  470. {
  471. _mainLoopDriver?.WriteRaw (
  472. EscSeqUtils.CSI_SetCursorStyle (
  473. (EscSeqUtils.DECSCUSR_Style)
  474. (((int)visibility >> 24)
  475. & 0xFF)
  476. )
  477. );
  478. }
  479. _currentCursorVisibility = visibility;
  480. return true;
  481. }
  482. private bool SetCursorPosition (int col, int row)
  483. {
  484. // + 1 is needed because non-Windows is based on 1 instead of 0 and
  485. // Console.CursorTop/CursorLeft isn't reliable.
  486. Console.Out.Write (EscSeqUtils.CSI_SetCursorPosition (row + 1, col + 1));
  487. return true;
  488. }
  489. #region Init/End/MainLoop
  490. private Curses.Window? _window;
  491. private UnixMainLoop? _mainLoopDriver;
  492. private object? _processInputToken;
  493. public override MainLoop Init ()
  494. {
  495. _mainLoopDriver = new (this);
  496. if (!RunningUnitTests)
  497. {
  498. _window = Curses.initscr ();
  499. Curses.set_escdelay (10);
  500. // Ensures that all procedures are performed at some previous closing.
  501. Curses.doupdate ();
  502. //
  503. // We are setting Invisible as default, so we could ignore XTerm DECSUSR setting
  504. //
  505. switch (Curses.curs_set (0))
  506. {
  507. case 0:
  508. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Invisible;
  509. break;
  510. case 1:
  511. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Underline;
  512. Curses.curs_set (1);
  513. break;
  514. case 2:
  515. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Box;
  516. Curses.curs_set (2);
  517. break;
  518. default:
  519. _currentCursorVisibility = _initialCursorVisibility = null;
  520. break;
  521. }
  522. if (!Curses.HasColors)
  523. {
  524. throw new InvalidOperationException ("V2 - This should never happen. File an Issue if it does.");
  525. }
  526. Curses.raw ();
  527. Curses.noecho ();
  528. Curses.Window.Standard.keypad (true);
  529. Curses.StartColor ();
  530. Curses.UseDefaultColors ();
  531. if (!RunningUnitTests)
  532. {
  533. Curses.timeout (0);
  534. }
  535. _processInputToken = _mainLoopDriver.AddWatch (
  536. 0,
  537. UnixMainLoop.Condition.PollIn,
  538. x =>
  539. {
  540. ProcessInput ();
  541. return true;
  542. }
  543. );
  544. }
  545. CurrentAttribute = new (ColorName16.White, ColorName16.Black);
  546. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  547. {
  548. Clipboard = new FakeDriver.FakeClipboard ();
  549. }
  550. else
  551. {
  552. if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
  553. {
  554. Clipboard = new MacOSXClipboard ();
  555. }
  556. else
  557. {
  558. if (Is_WSL_Platform ())
  559. {
  560. Clipboard = new WSLClipboard ();
  561. }
  562. else
  563. {
  564. Clipboard = new CursesClipboard ();
  565. }
  566. }
  567. }
  568. ClearContents ();
  569. StartReportingMouseMoves ();
  570. if (!RunningUnitTests)
  571. {
  572. Curses.CheckWinChange ();
  573. // On Init this call is needed no mater Force16Colors or not
  574. Curses.refresh ();
  575. EscSeqUtils.ContinuousButtonPressed += EscSeqUtils_ContinuousButtonPressed;
  576. }
  577. return new (_mainLoopDriver);
  578. }
  579. private readonly AnsiResponseParser _parser = new ();
  580. /// <inheritdoc />
  581. internal override IAnsiResponseParser GetParser () => _parser;
  582. internal void ProcessInput ()
  583. {
  584. int wch;
  585. int code = Curses.get_wch (out wch);
  586. //System.Diagnostics.Debug.WriteLine ($"code: {code}; wch: {wch}");
  587. if (code == Curses.ERR)
  588. {
  589. return;
  590. }
  591. var k = KeyCode.Null;
  592. if (code == Curses.KEY_CODE_YES)
  593. {
  594. while (code == Curses.KEY_CODE_YES && wch == Curses.KeyResize)
  595. {
  596. ProcessWinChange ();
  597. code = Curses.get_wch (out wch);
  598. }
  599. if (wch == 0)
  600. {
  601. return;
  602. }
  603. if (wch == Curses.KeyMouse)
  604. {
  605. int wch2 = wch;
  606. while (wch2 == Curses.KeyMouse)
  607. {
  608. // BUGBUG: Fix this nullable issue.
  609. Key kea = null;
  610. ConsoleKeyInfo [] cki =
  611. {
  612. new ((char)KeyCode.Esc, 0, false, false, false),
  613. new ('[', 0, false, false, false),
  614. new ('<', 0, false, false, false)
  615. };
  616. code = 0;
  617. // BUGBUG: Fix this nullable issue.
  618. HandleEscSeqResponse (ref code, ref k, ref wch2, ref kea, ref cki);
  619. }
  620. return;
  621. }
  622. k = MapCursesKey (wch);
  623. if (wch >= 277 && wch <= 288)
  624. {
  625. // Shift+(F1 - F12)
  626. wch -= 12;
  627. k = KeyCode.ShiftMask | MapCursesKey (wch);
  628. }
  629. else if (wch >= 289 && wch <= 300)
  630. {
  631. // Ctrl+(F1 - F12)
  632. wch -= 24;
  633. k = KeyCode.CtrlMask | MapCursesKey (wch);
  634. }
  635. else if (wch >= 301 && wch <= 312)
  636. {
  637. // Ctrl+Shift+(F1 - F12)
  638. wch -= 36;
  639. k = KeyCode.CtrlMask | KeyCode.ShiftMask | MapCursesKey (wch);
  640. }
  641. else if (wch >= 313 && wch <= 324)
  642. {
  643. // Alt+(F1 - F12)
  644. wch -= 48;
  645. k = KeyCode.AltMask | MapCursesKey (wch);
  646. }
  647. else if (wch >= 325 && wch <= 327)
  648. {
  649. // Shift+Alt+(F1 - F3)
  650. wch -= 60;
  651. k = KeyCode.ShiftMask | KeyCode.AltMask | MapCursesKey (wch);
  652. }
  653. else if (wch == 520) // Ctrl+Delete
  654. {
  655. k = KeyCode.CtrlMask | KeyCode.Delete;
  656. }
  657. OnKeyDown (new Key (k));
  658. OnKeyUp (new Key (k));
  659. return;
  660. }
  661. // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
  662. if (wch == 27)
  663. {
  664. Curses.timeout (10);
  665. code = Curses.get_wch (out int wch2);
  666. if (code == Curses.KEY_CODE_YES)
  667. {
  668. k = KeyCode.AltMask | MapCursesKey (wch);
  669. }
  670. // BUGBUG: Fix this nullable issue.
  671. Key key = null;
  672. if (code == 0)
  673. {
  674. // The ESC-number handling, debatable.
  675. // Simulates the AltMask itself by pressing Alt + Space.
  676. // Needed for macOS
  677. if (wch2 == (int)KeyCode.Space)
  678. {
  679. k = KeyCode.AltMask | KeyCode.Space;
  680. }
  681. else if (wch2 - (int)KeyCode.Space >= (uint)KeyCode.A
  682. && wch2 - (int)KeyCode.Space <= (uint)KeyCode.Z)
  683. {
  684. k = (KeyCode)((uint)KeyCode.AltMask + (wch2 - (int)KeyCode.Space));
  685. }
  686. else if (wch2 >= (uint)KeyCode.A - 64 && wch2 <= (uint)KeyCode.Z - 64)
  687. {
  688. k = (KeyCode)((uint)(KeyCode.AltMask | KeyCode.CtrlMask) + (wch2 + 64));
  689. }
  690. else if (wch2 >= (uint)KeyCode.D0 && wch2 <= (uint)KeyCode.D9)
  691. {
  692. k = (KeyCode)((uint)KeyCode.AltMask + (uint)KeyCode.D0 + (wch2 - (uint)KeyCode.D0));
  693. }
  694. else
  695. {
  696. ConsoleKeyInfo [] cki =
  697. [
  698. new ((char)KeyCode.Esc, 0, false, false, false), new ((char)wch2, 0, false, false, false)
  699. ];
  700. // BUGBUG: Fix this nullable issue.
  701. HandleEscSeqResponse (ref code, ref k, ref wch2, ref key, ref cki);
  702. return;
  703. }
  704. //else if (wch2 == Curses.KeyCSI)
  705. //{
  706. // ConsoleKeyInfo [] cki =
  707. // {
  708. // new ((char)KeyCode.Esc, 0, false, false, false), new ('[', 0, false, false, false)
  709. // };
  710. // HandleEscSeqResponse (ref code, ref k, ref wch2, ref key, ref cki);
  711. // return;
  712. //}
  713. //else
  714. //{
  715. // // Unfortunately there are no way to differentiate Ctrl+Alt+alfa and Ctrl+Shift+Alt+alfa.
  716. // if (((KeyCode)wch2 & KeyCode.CtrlMask) != 0)
  717. // {
  718. // k = (KeyCode)((uint)KeyCode.CtrlMask + (wch2 & ~(int)KeyCode.CtrlMask));
  719. // }
  720. // if (wch2 == 0)
  721. // {
  722. // k = KeyCode.CtrlMask | KeyCode.AltMask | KeyCode.Space;
  723. // }
  724. // //else if (wch >= (uint)KeyCode.A && wch <= (uint)KeyCode.Z)
  725. // //{
  726. // // k = KeyCode.ShiftMask | KeyCode.AltMask | KeyCode.Space;
  727. // //}
  728. // else if (wch2 < 256)
  729. // {
  730. // k = (KeyCode)wch2; // | KeyCode.AltMask;
  731. // }
  732. // else
  733. // {
  734. // k = (KeyCode)((uint)(KeyCode.AltMask | KeyCode.CtrlMask) + wch2);
  735. // }
  736. //}
  737. key = new Key (k);
  738. }
  739. else
  740. {
  741. key = Key.Esc;
  742. }
  743. OnKeyDown (key);
  744. OnKeyUp (key);
  745. }
  746. else if (wch == 8) // Ctrl+Backspace
  747. {
  748. k = KeyCode.Backspace | KeyCode.CtrlMask;
  749. OnKeyDown (new Key (k));
  750. OnKeyUp (new Key (k));
  751. }
  752. else if (wch == Curses.KeyTab)
  753. {
  754. k = MapCursesKey (wch);
  755. OnKeyDown (new Key (k));
  756. OnKeyUp (new Key (k));
  757. }
  758. else if (wch == 127)
  759. {
  760. // Backspace needed for macOS
  761. k = KeyCode.Backspace;
  762. OnKeyDown (new Key (k));
  763. OnKeyUp (new Key (k));
  764. }
  765. else
  766. {
  767. // Unfortunately there are no way to differentiate Ctrl+alfa and Ctrl+Shift+alfa.
  768. k = (KeyCode)wch;
  769. if (wch == 0)
  770. {
  771. k = KeyCode.CtrlMask | KeyCode.Space;
  772. }
  773. else if (wch >= (uint)KeyCode.A - 64 && wch <= (uint)KeyCode.Z - 64)
  774. {
  775. if ((KeyCode)(wch + 64) != KeyCode.J)
  776. {
  777. k = KeyCode.CtrlMask | (KeyCode)(wch + 64);
  778. }
  779. }
  780. else if (wch >= (uint)KeyCode.A && wch <= (uint)KeyCode.Z)
  781. {
  782. k = (KeyCode)wch | KeyCode.ShiftMask;
  783. }
  784. if (wch == '\n' || wch == '\r')
  785. {
  786. k = KeyCode.Enter;
  787. }
  788. // Strip the KeyCode.Space flag off if it's set
  789. //if (k != KeyCode.Space && k.HasFlag (KeyCode.Space))
  790. if (Key.GetIsKeyCodeAtoZ (k) && (k & KeyCode.Space) != 0)
  791. {
  792. k &= ~KeyCode.Space;
  793. }
  794. if (IsValidInput (k, out k))
  795. {
  796. OnKeyDown (new (k));
  797. OnKeyUp (new (k));
  798. }
  799. }
  800. }
  801. internal void ProcessWinChange ()
  802. {
  803. if (!RunningUnitTests && Curses.CheckWinChange ())
  804. {
  805. ClearContents ();
  806. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  807. }
  808. }
  809. static string ConvertToString (ConsoleKeyInfo [] keyInfos)
  810. {
  811. char [] chars = new char [keyInfos.Length];
  812. for (int i = 0; i < keyInfos.Length; i++)
  813. {
  814. chars [i] = keyInfos [i].KeyChar;
  815. }
  816. return new string (chars);
  817. }
  818. private void HandleEscSeqResponse (
  819. ref int code,
  820. ref KeyCode k,
  821. ref int wch2,
  822. ref Key keyEventArgs,
  823. ref ConsoleKeyInfo [] cki
  824. )
  825. {
  826. ConsoleKey ck = 0;
  827. ConsoleModifiers mod = 0;
  828. while (code == 0)
  829. {
  830. code = Curses.get_wch (out wch2);
  831. var consoleKeyInfo = new ConsoleKeyInfo ((char)wch2, 0, false, false, false);
  832. if (wch2 == 0 || wch2 == 27 || wch2 == Curses.KeyMouse)
  833. {
  834. // Give ansi parser a chance to deal with the escape sequence
  835. if (cki != null && string.IsNullOrEmpty(_parser.ProcessInput (ConvertToString(cki))))
  836. {
  837. // Parser fully consumed all keys meaning keys are processed - job done
  838. return;
  839. }
  840. // Ansi parser could not deal with it either because it is not expecting
  841. // the given terminator (e.g. mouse) or did not understand format somehow.
  842. // Carry on with the older code for processing curses escape codes
  843. // BUGBUG: Fix this nullable issue.
  844. EscSeqUtils.DecodeEscSeq (
  845. ref consoleKeyInfo,
  846. ref ck,
  847. cki,
  848. ref mod,
  849. out _,
  850. out _,
  851. out _,
  852. out _,
  853. out bool isKeyMouse,
  854. out List<MouseFlags> mouseFlags,
  855. out Point pos,
  856. out _,
  857. EscSeqUtils.ProcessMouseEvent
  858. );
  859. if (isKeyMouse)
  860. {
  861. foreach (MouseFlags mf in mouseFlags)
  862. {
  863. OnMouseEvent (new () { Flags = mf, Position = pos });
  864. }
  865. // BUGBUG: Fix this nullable issue.
  866. cki = null;
  867. if (wch2 == 27)
  868. {
  869. cki = EscSeqUtils.ResizeArray (
  870. new ConsoleKeyInfo (
  871. (char)KeyCode.Esc,
  872. 0,
  873. false,
  874. false,
  875. false
  876. ),
  877. cki
  878. );
  879. }
  880. }
  881. else
  882. {
  883. k = ConsoleKeyMapping.MapConsoleKeyInfoToKeyCode (consoleKeyInfo);
  884. keyEventArgs = new Key (k);
  885. OnKeyDown (keyEventArgs);
  886. }
  887. }
  888. else
  889. {
  890. cki = EscSeqUtils.ResizeArray (consoleKeyInfo, cki);
  891. }
  892. }
  893. }
  894. private void EscSeqUtils_ContinuousButtonPressed (object? sender, MouseEventArgs e)
  895. {
  896. OnMouseEvent (e);
  897. }
  898. private static KeyCode MapCursesKey (int cursesKey)
  899. {
  900. switch (cursesKey)
  901. {
  902. case Curses.KeyF1: return KeyCode.F1;
  903. case Curses.KeyF2: return KeyCode.F2;
  904. case Curses.KeyF3: return KeyCode.F3;
  905. case Curses.KeyF4: return KeyCode.F4;
  906. case Curses.KeyF5: return KeyCode.F5;
  907. case Curses.KeyF6: return KeyCode.F6;
  908. case Curses.KeyF7: return KeyCode.F7;
  909. case Curses.KeyF8: return KeyCode.F8;
  910. case Curses.KeyF9: return KeyCode.F9;
  911. case Curses.KeyF10: return KeyCode.F10;
  912. case Curses.KeyF11: return KeyCode.F11;
  913. case Curses.KeyF12: return KeyCode.F12;
  914. case Curses.KeyUp: return KeyCode.CursorUp;
  915. case Curses.KeyDown: return KeyCode.CursorDown;
  916. case Curses.KeyLeft: return KeyCode.CursorLeft;
  917. case Curses.KeyRight: return KeyCode.CursorRight;
  918. case Curses.KeyHome: return KeyCode.Home;
  919. case Curses.KeyEnd: return KeyCode.End;
  920. case Curses.KeyNPage: return KeyCode.PageDown;
  921. case Curses.KeyPPage: return KeyCode.PageUp;
  922. case Curses.KeyDeleteChar: return KeyCode.Delete;
  923. case Curses.KeyInsertChar: return KeyCode.Insert;
  924. case Curses.KeyTab: return KeyCode.Tab;
  925. case Curses.KeyBackTab: return KeyCode.Tab | KeyCode.ShiftMask;
  926. case Curses.KeyBackspace: return KeyCode.Backspace;
  927. case Curses.ShiftKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask;
  928. case Curses.ShiftKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask;
  929. case Curses.ShiftKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask;
  930. case Curses.ShiftKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask;
  931. case Curses.ShiftKeyHome: return KeyCode.Home | KeyCode.ShiftMask;
  932. case Curses.ShiftKeyEnd: return KeyCode.End | KeyCode.ShiftMask;
  933. case Curses.ShiftKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask;
  934. case Curses.ShiftKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask;
  935. case Curses.AltKeyUp: return KeyCode.CursorUp | KeyCode.AltMask;
  936. case Curses.AltKeyDown: return KeyCode.CursorDown | KeyCode.AltMask;
  937. case Curses.AltKeyLeft: return KeyCode.CursorLeft | KeyCode.AltMask;
  938. case Curses.AltKeyRight: return KeyCode.CursorRight | KeyCode.AltMask;
  939. case Curses.AltKeyHome: return KeyCode.Home | KeyCode.AltMask;
  940. case Curses.AltKeyEnd: return KeyCode.End | KeyCode.AltMask;
  941. case Curses.AltKeyNPage: return KeyCode.PageDown | KeyCode.AltMask;
  942. case Curses.AltKeyPPage: return KeyCode.PageUp | KeyCode.AltMask;
  943. case Curses.CtrlKeyUp: return KeyCode.CursorUp | KeyCode.CtrlMask;
  944. case Curses.CtrlKeyDown: return KeyCode.CursorDown | KeyCode.CtrlMask;
  945. case Curses.CtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.CtrlMask;
  946. case Curses.CtrlKeyRight: return KeyCode.CursorRight | KeyCode.CtrlMask;
  947. case Curses.CtrlKeyHome: return KeyCode.Home | KeyCode.CtrlMask;
  948. case Curses.CtrlKeyEnd: return KeyCode.End | KeyCode.CtrlMask;
  949. case Curses.CtrlKeyNPage: return KeyCode.PageDown | KeyCode.CtrlMask;
  950. case Curses.CtrlKeyPPage: return KeyCode.PageUp | KeyCode.CtrlMask;
  951. case Curses.ShiftCtrlKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.CtrlMask;
  952. case Curses.ShiftCtrlKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.CtrlMask;
  953. case Curses.ShiftCtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.CtrlMask;
  954. case Curses.ShiftCtrlKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.CtrlMask;
  955. case Curses.ShiftCtrlKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.CtrlMask;
  956. case Curses.ShiftCtrlKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.CtrlMask;
  957. case Curses.ShiftCtrlKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.CtrlMask;
  958. case Curses.ShiftCtrlKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.CtrlMask;
  959. case Curses.ShiftAltKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.AltMask;
  960. case Curses.ShiftAltKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.AltMask;
  961. case Curses.ShiftAltKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.AltMask;
  962. case Curses.ShiftAltKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.AltMask;
  963. case Curses.ShiftAltKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.AltMask;
  964. case Curses.ShiftAltKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.AltMask;
  965. case Curses.ShiftAltKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.AltMask;
  966. case Curses.ShiftAltKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.AltMask;
  967. case Curses.AltCtrlKeyNPage: return KeyCode.PageDown | KeyCode.AltMask | KeyCode.CtrlMask;
  968. case Curses.AltCtrlKeyPPage: return KeyCode.PageUp | KeyCode.AltMask | KeyCode.CtrlMask;
  969. case Curses.AltCtrlKeyHome: return KeyCode.Home | KeyCode.AltMask | KeyCode.CtrlMask;
  970. case Curses.AltCtrlKeyEnd: return KeyCode.End | KeyCode.AltMask | KeyCode.CtrlMask;
  971. default: return KeyCode.Null;
  972. }
  973. }
  974. public override void End ()
  975. {
  976. EscSeqUtils.ContinuousButtonPressed -= EscSeqUtils_ContinuousButtonPressed;
  977. StopReportingMouseMoves ();
  978. SetCursorVisibility (CursorVisibility.Default);
  979. if (_mainLoopDriver is { } && _processInputToken != null)
  980. {
  981. _mainLoopDriver.RemoveWatch (_processInputToken);
  982. }
  983. if (RunningUnitTests)
  984. {
  985. return;
  986. }
  987. // throws away any typeahead that has been typed by
  988. // the user and has not yet been read by the program.
  989. Curses.flushinp ();
  990. Curses.endwin ();
  991. }
  992. #endregion Init/End/MainLoop
  993. public static bool Is_WSL_Platform ()
  994. {
  995. // xclip does not work on WSL, so we need to use the Windows clipboard vis Powershell
  996. //if (new CursesClipboard ().IsSupported) {
  997. // // If xclip is installed on Linux under WSL, this will return true.
  998. // return false;
  999. //}
  1000. (int exitCode, string result) = ClipboardProcessRunner.Bash ("uname -a", waitForOutput: true);
  1001. if (exitCode == 0 && result.Contains ("microsoft") && result.Contains ("WSL"))
  1002. {
  1003. return true;
  1004. }
  1005. return false;
  1006. }
  1007. /// <inheritdoc/>
  1008. public override void WriteRaw (string ansi) { _mainLoopDriver?.WriteRaw (ansi); }
  1009. }
  1010. // TODO: One type per file - move to another file
  1011. internal static class Platform
  1012. {
  1013. private static int _suspendSignal;
  1014. /// <summary>Suspends the process by sending SIGTSTP to itself</summary>
  1015. /// <returns>True if the suspension was successful.</returns>
  1016. public static bool Suspend ()
  1017. {
  1018. int signal = GetSuspendSignal ();
  1019. if (signal == -1)
  1020. {
  1021. return false;
  1022. }
  1023. killpg (0, signal);
  1024. return true;
  1025. }
  1026. private static int GetSuspendSignal ()
  1027. {
  1028. if (_suspendSignal != 0)
  1029. {
  1030. return _suspendSignal;
  1031. }
  1032. nint buf = Marshal.AllocHGlobal (8192);
  1033. if (uname (buf) != 0)
  1034. {
  1035. Marshal.FreeHGlobal (buf);
  1036. _suspendSignal = -1;
  1037. return _suspendSignal;
  1038. }
  1039. try
  1040. {
  1041. switch (Marshal.PtrToStringAnsi (buf))
  1042. {
  1043. case "Darwin":
  1044. case "DragonFly":
  1045. case "FreeBSD":
  1046. case "NetBSD":
  1047. case "OpenBSD":
  1048. _suspendSignal = 18;
  1049. break;
  1050. case "Linux":
  1051. // TODO: should fetch the machine name and
  1052. // if it is MIPS return 24
  1053. _suspendSignal = 20;
  1054. break;
  1055. case "Solaris":
  1056. _suspendSignal = 24;
  1057. break;
  1058. default:
  1059. _suspendSignal = -1;
  1060. break;
  1061. }
  1062. return _suspendSignal;
  1063. }
  1064. finally
  1065. {
  1066. Marshal.FreeHGlobal (buf);
  1067. }
  1068. }
  1069. [DllImport ("libc")]
  1070. private static extern int killpg (int pgrp, int pid);
  1071. [DllImport ("libc")]
  1072. private static extern int uname (nint buf);
  1073. }