CursesDriver.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  1. #nullable enable
  2. //
  3. // Driver.cs: Curses-based Driver
  4. //
  5. using System.Runtime.InteropServices;
  6. using Unix.Terminal;
  7. namespace Terminal.Gui.Drivers;
  8. /// <summary>A Linux/Mac driver based on the Curses library.</summary>
  9. internal class CursesDriver : ConsoleDriver
  10. {
  11. public override string GetVersionInfo () { return $"{Curses.curses_version ()}"; }
  12. public override int Cols
  13. {
  14. get => Curses.Cols;
  15. set
  16. {
  17. Curses.Cols = value;
  18. ClearContents ();
  19. }
  20. }
  21. public override int Rows
  22. {
  23. get => Curses.Lines;
  24. set
  25. {
  26. Curses.Lines = value;
  27. ClearContents ();
  28. }
  29. }
  30. public override bool IsRuneSupported (Rune rune)
  31. {
  32. // See Issue #2615 - CursesDriver is broken with non-BMP characters
  33. return base.IsRuneSupported (rune) && rune.IsBmp;
  34. }
  35. public override void Move (int col, int row)
  36. {
  37. base.Move (col, row);
  38. if (RunningUnitTests)
  39. {
  40. return;
  41. }
  42. if (IsValidLocation (default, col, row))
  43. {
  44. Curses.move (row, col);
  45. }
  46. else
  47. {
  48. // Not a valid location (outside screen or clip region)
  49. // Move within the clip region, then AddRune will actually move to Col, Row
  50. Rectangle clipRect = Clip!.GetBounds ();
  51. Curses.move (clipRect.Y, clipRect.X);
  52. }
  53. }
  54. public override void SendKeys (char keyChar, ConsoleKey consoleKey, bool shift, bool alt, bool control)
  55. {
  56. KeyCode key;
  57. if (consoleKey == ConsoleKey.Packet)
  58. {
  59. //var mod = new ConsoleModifiers ();
  60. //if (shift)
  61. //{
  62. // mod |= ConsoleModifiers.Shift;
  63. //}
  64. //if (alt)
  65. //{
  66. // mod |= ConsoleModifiers.Alt;
  67. //}
  68. //if (control)
  69. //{
  70. // mod |= ConsoleModifiers.Control;
  71. //}
  72. var cKeyInfo = new ConsoleKeyInfo (keyChar, consoleKey, shift, alt, control);
  73. cKeyInfo = ConsoleKeyMapping.DecodeVKPacketToKConsoleKeyInfo (cKeyInfo);
  74. key = ConsoleKeyMapping.MapConsoleKeyInfoToKeyCode (cKeyInfo);
  75. }
  76. else
  77. {
  78. key = (KeyCode)keyChar;
  79. }
  80. OnKeyDown (new (key));
  81. OnKeyUp (new (key));
  82. //OnKeyPressed (new KeyEventArgsEventArgs (key));
  83. }
  84. public void StartReportingMouseMoves ()
  85. {
  86. if (!RunningUnitTests)
  87. {
  88. Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents);
  89. }
  90. }
  91. public void StopReportingMouseMoves ()
  92. {
  93. if (!RunningUnitTests)
  94. {
  95. Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
  96. }
  97. }
  98. public override void Suspend ()
  99. {
  100. StopReportingMouseMoves ();
  101. if (!RunningUnitTests)
  102. {
  103. Platform.Suspend ();
  104. if (Force16Colors)
  105. {
  106. Curses.Window.Standard.redrawwin ();
  107. Curses.refresh ();
  108. }
  109. }
  110. StartReportingMouseMoves ();
  111. }
  112. public override void UpdateCursor ()
  113. {
  114. EnsureCursorVisibility ();
  115. if (!RunningUnitTests && Col >= 0 && Col < Cols && Row >= 0 && Row < Rows)
  116. {
  117. if (Force16Colors)
  118. {
  119. Curses.move (Row, Col);
  120. Curses.raw ();
  121. Curses.noecho ();
  122. Curses.refresh ();
  123. }
  124. else
  125. {
  126. _mainLoopDriver?.WriteRaw (EscSeqUtils.CSI_SetCursorPosition (Row + 1, Col + 1));
  127. }
  128. }
  129. }
  130. public override bool UpdateScreen ()
  131. {
  132. bool updated = false;
  133. if (Force16Colors)
  134. {
  135. for (var row = 0; row < Rows; row++)
  136. {
  137. if (!_dirtyLines! [row])
  138. {
  139. continue;
  140. }
  141. _dirtyLines [row] = false;
  142. for (var col = 0; col < Cols; col++)
  143. {
  144. if (Contents! [row, col].IsDirty == false)
  145. {
  146. continue;
  147. }
  148. if (RunningUnitTests)
  149. {
  150. // In unit tests, we don't want to actually write to the screen.
  151. continue;
  152. }
  153. Curses.attrset (Contents [row, col].Attribute.GetValueOrDefault ().PlatformColor);
  154. Rune rune = Contents [row, col].Rune;
  155. if (rune.IsBmp)
  156. {
  157. // 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.
  158. if (rune.GetColumns () < 2)
  159. {
  160. Curses.mvaddch (row, col, rune.Value);
  161. }
  162. else /*if (col + 1 < Cols)*/
  163. {
  164. Curses.mvaddwstr (row, col, rune.ToString ());
  165. }
  166. }
  167. else
  168. {
  169. Curses.mvaddwstr (row, col, rune.ToString ());
  170. if (rune.GetColumns () > 1 && col + 1 < Cols)
  171. {
  172. // TODO: This is a hack to deal with non-BMP and wide characters.
  173. //col++;
  174. Curses.mvaddch (row, ++col, '*');
  175. }
  176. }
  177. }
  178. }
  179. if (!RunningUnitTests)
  180. {
  181. Curses.move (Row, Col);
  182. _window?.wrefresh ();
  183. }
  184. }
  185. else
  186. {
  187. if (RunningUnitTests
  188. || Console.WindowHeight < 1
  189. || Contents!.Length != Rows * Cols
  190. || Rows != Console.WindowHeight)
  191. {
  192. return updated;
  193. }
  194. var top = 0;
  195. var left = 0;
  196. int rows = Rows;
  197. int cols = Cols;
  198. var output = new StringBuilder ();
  199. Attribute? redrawAttr = null;
  200. int lastCol = -1;
  201. CursorVisibility? savedVisibility = _currentCursorVisibility;
  202. SetCursorVisibility (CursorVisibility.Invisible);
  203. for (int row = top; row < rows; row++)
  204. {
  205. if (Console.WindowHeight < 1)
  206. {
  207. return updated;
  208. }
  209. if (!_dirtyLines! [row])
  210. {
  211. continue;
  212. }
  213. if (!SetCursorPosition (0, row))
  214. {
  215. return updated;
  216. }
  217. _dirtyLines [row] = false;
  218. output.Clear ();
  219. for (int col = left; col < cols; col++)
  220. {
  221. lastCol = -1;
  222. var outputWidth = 0;
  223. for (; col < cols; col++)
  224. {
  225. updated = true;
  226. if (!Contents [row, col].IsDirty)
  227. {
  228. if (output.Length > 0)
  229. {
  230. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  231. }
  232. else if (lastCol == -1)
  233. {
  234. lastCol = col;
  235. }
  236. if (lastCol + 1 < cols)
  237. {
  238. lastCol++;
  239. }
  240. continue;
  241. }
  242. if (lastCol == -1)
  243. {
  244. lastCol = col;
  245. }
  246. Attribute attr = Contents [row, col].Attribute!.Value;
  247. // Performance: Only send the escape sequence if the attribute has changed.
  248. if (attr != redrawAttr)
  249. {
  250. redrawAttr = attr;
  251. output.Append (
  252. EscSeqUtils.CSI_SetForegroundColorRGB (
  253. attr.Foreground.R,
  254. attr.Foreground.G,
  255. attr.Foreground.B
  256. )
  257. );
  258. output.Append (
  259. EscSeqUtils.CSI_SetBackgroundColorRGB (
  260. attr.Background.R,
  261. attr.Background.G,
  262. attr.Background.B
  263. )
  264. );
  265. }
  266. outputWidth++;
  267. Rune rune = Contents [row, col].Rune;
  268. output.Append (rune);
  269. if (Contents [row, col].CombiningMarks.Count > 0)
  270. {
  271. // AtlasEngine does not support NON-NORMALIZED combining marks in a way
  272. // compatible with the driver architecture. Any CMs (except in the first col)
  273. // are correctly combined with the base char, but are ALSO treated as 1 column
  274. // width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
  275. //
  276. // For now, we just ignore the list of CMs.
  277. //foreach (var combMark in Contents [row, col].CombiningMarks) {
  278. // output.Append (combMark);
  279. //}
  280. // WriteToConsole (output, ref lastCol, row, ref outputWidth);
  281. }
  282. else if (rune.IsSurrogatePair () && rune.GetColumns () < 2)
  283. {
  284. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  285. SetCursorPosition (col - 1, row);
  286. }
  287. Contents [row, col].IsDirty = false;
  288. }
  289. }
  290. if (output.Length > 0)
  291. {
  292. SetCursorPosition (lastCol, row);
  293. Console.Write (output);
  294. }
  295. }
  296. // SIXELS
  297. foreach (SixelToRender s in Application.Sixel)
  298. {
  299. SetCursorPosition (s.ScreenPosition.X, s.ScreenPosition.Y);
  300. Console.Write (s.SixelData);
  301. }
  302. SetCursorPosition (0, 0);
  303. _currentCursorVisibility = savedVisibility;
  304. void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
  305. {
  306. SetCursorPosition (lastCol, row);
  307. Console.Write (output);
  308. output.Clear ();
  309. lastCol += outputWidth;
  310. outputWidth = 0;
  311. }
  312. }
  313. return updated;
  314. }
  315. #region Color Handling
  316. public override bool SupportsTrueColor => true;
  317. /// <summary>Creates an Attribute from the provided curses-based foreground and background color numbers</summary>
  318. /// <param name="foreground">Contains the curses color number for the foreground (color, plus any attributes)</param>
  319. /// <param name="background">Contains the curses color number for the background (color, plus any attributes)</param>
  320. /// <returns></returns>
  321. private static Attribute MakeColor (short foreground, short background)
  322. {
  323. //var v = (short)((ushort)foreground | (background << 4));
  324. var v = (short)(((ushort)(foreground & 0xffff) << 16) | (background & 0xffff));
  325. // TODO: for TrueColor - Use InitExtendedPair
  326. Curses.InitColorPair (v, foreground, background);
  327. return new (
  328. Curses.ColorPair (v),
  329. CursesColorNumberToColorName16 (foreground),
  330. CursesColorNumberToColorName16 (background)
  331. );
  332. }
  333. /// <inheritdoc/>
  334. /// <remarks>
  335. /// In the CursesDriver, colors are encoded as an int. The foreground color is stored in the most significant 4
  336. /// bits, and the background color is stored in the least significant 4 bits. The Terminal.GUi Color values are
  337. /// converted to curses color encoding before being encoded.
  338. /// </remarks>
  339. public override Attribute MakeColor (in Color foreground, in Color background)
  340. {
  341. if (!RunningUnitTests && Force16Colors)
  342. {
  343. return MakeColor (
  344. ColorNameToCursesColorNumber (foreground.GetClosestNamedColor16 ()),
  345. ColorNameToCursesColorNumber (background.GetClosestNamedColor16 ())
  346. );
  347. }
  348. return new (
  349. 0,
  350. foreground,
  351. background
  352. );
  353. }
  354. private static short ColorNameToCursesColorNumber (ColorName16 color)
  355. {
  356. switch (color)
  357. {
  358. case ColorName16.Black:
  359. return Curses.COLOR_BLACK;
  360. case ColorName16.Blue:
  361. return Curses.COLOR_BLUE;
  362. case ColorName16.Green:
  363. return Curses.COLOR_GREEN;
  364. case ColorName16.Cyan:
  365. return Curses.COLOR_CYAN;
  366. case ColorName16.Red:
  367. return Curses.COLOR_RED;
  368. case ColorName16.Magenta:
  369. return Curses.COLOR_MAGENTA;
  370. case ColorName16.Yellow:
  371. return Curses.COLOR_YELLOW;
  372. case ColorName16.Gray:
  373. return Curses.COLOR_WHITE;
  374. case ColorName16.DarkGray:
  375. return Curses.COLOR_GRAY;
  376. case ColorName16.BrightBlue:
  377. return Curses.COLOR_BLUE | Curses.COLOR_GRAY;
  378. case ColorName16.BrightGreen:
  379. return Curses.COLOR_GREEN | Curses.COLOR_GRAY;
  380. case ColorName16.BrightCyan:
  381. return Curses.COLOR_CYAN | Curses.COLOR_GRAY;
  382. case ColorName16.BrightRed:
  383. return Curses.COLOR_RED | Curses.COLOR_GRAY;
  384. case ColorName16.BrightMagenta:
  385. return Curses.COLOR_MAGENTA | Curses.COLOR_GRAY;
  386. case ColorName16.BrightYellow:
  387. return Curses.COLOR_YELLOW | Curses.COLOR_GRAY;
  388. case ColorName16.White:
  389. return Curses.COLOR_WHITE | Curses.COLOR_GRAY;
  390. }
  391. throw new ArgumentException ("Invalid color code");
  392. }
  393. private static ColorName16 CursesColorNumberToColorName16 (short color)
  394. {
  395. switch (color)
  396. {
  397. case Curses.COLOR_BLACK:
  398. return ColorName16.Black;
  399. case Curses.COLOR_BLUE:
  400. return ColorName16.Blue;
  401. case Curses.COLOR_GREEN:
  402. return ColorName16.Green;
  403. case Curses.COLOR_CYAN:
  404. return ColorName16.Cyan;
  405. case Curses.COLOR_RED:
  406. return ColorName16.Red;
  407. case Curses.COLOR_MAGENTA:
  408. return ColorName16.Magenta;
  409. case Curses.COLOR_YELLOW:
  410. return ColorName16.Yellow;
  411. case Curses.COLOR_WHITE:
  412. return ColorName16.Gray;
  413. case Curses.COLOR_GRAY:
  414. return ColorName16.DarkGray;
  415. case Curses.COLOR_BLUE | Curses.COLOR_GRAY:
  416. return ColorName16.BrightBlue;
  417. case Curses.COLOR_GREEN | Curses.COLOR_GRAY:
  418. return ColorName16.BrightGreen;
  419. case Curses.COLOR_CYAN | Curses.COLOR_GRAY:
  420. return ColorName16.BrightCyan;
  421. case Curses.COLOR_RED | Curses.COLOR_GRAY:
  422. return ColorName16.BrightRed;
  423. case Curses.COLOR_MAGENTA | Curses.COLOR_GRAY:
  424. return ColorName16.BrightMagenta;
  425. case Curses.COLOR_YELLOW | Curses.COLOR_GRAY:
  426. return ColorName16.BrightYellow;
  427. case Curses.COLOR_WHITE | Curses.COLOR_GRAY:
  428. return ColorName16.White;
  429. }
  430. throw new ArgumentException ("Invalid curses color code");
  431. }
  432. #endregion
  433. private CursorVisibility? _currentCursorVisibility;
  434. private CursorVisibility? _initialCursorVisibility;
  435. private void EnsureCursorVisibility ()
  436. {
  437. if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows))
  438. {
  439. GetCursorVisibility (out CursorVisibility cursorVisibility);
  440. _currentCursorVisibility = cursorVisibility;
  441. SetCursorVisibility (CursorVisibility.Invisible);
  442. return;
  443. }
  444. SetCursorVisibility (_currentCursorVisibility ?? CursorVisibility.Default);
  445. }
  446. /// <inheritdoc/>
  447. public override bool GetCursorVisibility (out CursorVisibility visibility)
  448. {
  449. visibility = CursorVisibility.Invisible;
  450. if (!_currentCursorVisibility.HasValue)
  451. {
  452. return false;
  453. }
  454. visibility = _currentCursorVisibility.Value;
  455. return true;
  456. }
  457. private EscSeqUtils.DECSCUSR_Style? _currentDecscusrStyle;
  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. Curses.leaveok (_window!.Handle, !Force16Colors);
  469. }
  470. if (visibility != CursorVisibility.Invisible)
  471. {
  472. if (_currentDecscusrStyle is null || _currentDecscusrStyle != (EscSeqUtils.DECSCUSR_Style)(((int)visibility >> 24) & 0xFF))
  473. {
  474. _currentDecscusrStyle = (EscSeqUtils.DECSCUSR_Style)(((int)visibility >> 24) & 0xFF);
  475. _mainLoopDriver?.WriteRaw (
  476. EscSeqUtils.CSI_SetCursorStyle ((EscSeqUtils.DECSCUSR_Style)_currentDecscusrStyle)
  477. );
  478. }
  479. }
  480. _currentCursorVisibility = visibility;
  481. return true;
  482. }
  483. private bool SetCursorPosition (int col, int row)
  484. {
  485. // + 1 is needed because non-Windows is based on 1 instead of 0 and
  486. // Console.CursorTop/CursorLeft isn't reliable.
  487. Console.Out.Write (EscSeqUtils.CSI_SetCursorPosition (row + 1, col + 1));
  488. return true;
  489. }
  490. #region Init/End/MainLoop
  491. private Curses.Window? _window;
  492. private UnixMainLoop? _mainLoopDriver;
  493. private object? _processInputToken;
  494. public 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. _processInputToken = _mainLoopDriver.AddWatch (
  537. 0,
  538. UnixMainLoop.Condition.PollIn,
  539. x =>
  540. {
  541. ProcessInput ();
  542. return true;
  543. }
  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. // On Init this call is needed no mater Force16Colors or not
  575. Curses.refresh ();
  576. EscSeqUtils.ContinuousButtonPressed += EscSeqUtils_ContinuousButtonPressed;
  577. }
  578. return new (_mainLoopDriver);
  579. }
  580. private readonly AnsiResponseParser _parser = new ();
  581. /// <inheritdoc />
  582. internal override IAnsiResponseParser GetParser () => _parser;
  583. internal void ProcessInput ()
  584. {
  585. int wch;
  586. int code = Curses.get_wch (out wch);
  587. //System.Diagnostics.Debug.WriteLine ($"code: {code}; wch: {wch}");
  588. if (code == Curses.ERR)
  589. {
  590. return;
  591. }
  592. var k = KeyCode.Null;
  593. if (code == Curses.KEY_CODE_YES)
  594. {
  595. while (code == Curses.KEY_CODE_YES && wch == Curses.KeyResize)
  596. {
  597. ProcessWinChange ();
  598. code = Curses.get_wch (out wch);
  599. }
  600. if (wch == 0)
  601. {
  602. return;
  603. }
  604. if (wch == Curses.KeyMouse)
  605. {
  606. int wch2 = wch;
  607. while (wch2 == Curses.KeyMouse)
  608. {
  609. // BUGBUG: Fix this nullable issue.
  610. Key kea = null;
  611. ConsoleKeyInfo [] cki =
  612. {
  613. new ((char)KeyCode.Esc, 0, false, false, false),
  614. new ('[', 0, false, false, false),
  615. new ('<', 0, false, false, false)
  616. };
  617. code = 0;
  618. // BUGBUG: Fix this nullable issue.
  619. HandleEscSeqResponse (ref code, ref k, ref wch2, ref kea, ref cki);
  620. }
  621. return;
  622. }
  623. k = MapCursesKey (wch);
  624. if (wch >= 277 && wch <= 288)
  625. {
  626. // Shift+(F1 - F12)
  627. wch -= 12;
  628. k = KeyCode.ShiftMask | MapCursesKey (wch);
  629. }
  630. else if (wch >= 289 && wch <= 300)
  631. {
  632. // Ctrl+(F1 - F12)
  633. wch -= 24;
  634. k = KeyCode.CtrlMask | MapCursesKey (wch);
  635. }
  636. else if (wch >= 301 && wch <= 312)
  637. {
  638. // Ctrl+Shift+(F1 - F12)
  639. wch -= 36;
  640. k = KeyCode.CtrlMask | KeyCode.ShiftMask | MapCursesKey (wch);
  641. }
  642. else if (wch >= 313 && wch <= 324)
  643. {
  644. // Alt+(F1 - F12)
  645. wch -= 48;
  646. k = KeyCode.AltMask | MapCursesKey (wch);
  647. }
  648. else if (wch >= 325 && wch <= 327)
  649. {
  650. // Shift+Alt+(F1 - F3)
  651. wch -= 60;
  652. k = KeyCode.ShiftMask | KeyCode.AltMask | MapCursesKey (wch);
  653. }
  654. else if (wch == 520) // Ctrl+Delete
  655. {
  656. k = KeyCode.CtrlMask | KeyCode.Delete;
  657. }
  658. OnKeyDown (new Key (k));
  659. OnKeyUp (new Key (k));
  660. return;
  661. }
  662. // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
  663. if (wch == 27)
  664. {
  665. Curses.timeout (10);
  666. code = Curses.get_wch (out int wch2);
  667. if (code == Curses.KEY_CODE_YES)
  668. {
  669. k = KeyCode.AltMask | MapCursesKey (wch);
  670. }
  671. // BUGBUG: Fix this nullable issue.
  672. Key key = null;
  673. if (code == 0)
  674. {
  675. // The ESC-number handling, debatable.
  676. // Simulates the AltMask itself by pressing Alt + Space.
  677. // Needed for macOS
  678. if (wch2 == (int)KeyCode.Space)
  679. {
  680. k = KeyCode.AltMask | KeyCode.Space;
  681. }
  682. else if (wch2 - (int)KeyCode.Space >= (uint)KeyCode.A
  683. && wch2 - (int)KeyCode.Space <= (uint)KeyCode.Z)
  684. {
  685. k = (KeyCode)((uint)KeyCode.AltMask + (wch2 - (int)KeyCode.Space));
  686. }
  687. else if (wch2 >= (uint)KeyCode.A - 64 && wch2 <= (uint)KeyCode.Z - 64)
  688. {
  689. k = (KeyCode)((uint)(KeyCode.AltMask | KeyCode.CtrlMask) + (wch2 + 64));
  690. }
  691. else if (wch2 >= (uint)KeyCode.D0 && wch2 <= (uint)KeyCode.D9)
  692. {
  693. k = (KeyCode)((uint)KeyCode.AltMask + (uint)KeyCode.D0 + (wch2 - (uint)KeyCode.D0));
  694. }
  695. else
  696. {
  697. ConsoleKeyInfo [] cki =
  698. [
  699. new ((char)KeyCode.Esc, 0, false, false, false), new ((char)wch2, 0, false, false, false)
  700. ];
  701. // BUGBUG: Fix this nullable issue.
  702. HandleEscSeqResponse (ref code, ref k, ref wch2, ref key, ref cki);
  703. return;
  704. }
  705. //else if (wch2 == Curses.KeyCSI)
  706. //{
  707. // ConsoleKeyInfo [] cki =
  708. // {
  709. // new ((char)KeyCode.Esc, 0, false, false, false), new ('[', 0, false, false, false)
  710. // };
  711. // HandleEscSeqResponse (ref code, ref k, ref wch2, ref key, ref cki);
  712. // return;
  713. //}
  714. //else
  715. //{
  716. // // Unfortunately there are no way to differentiate Ctrl+Alt+alfa and Ctrl+Shift+Alt+alfa.
  717. // if (((KeyCode)wch2 & KeyCode.CtrlMask) != 0)
  718. // {
  719. // k = (KeyCode)((uint)KeyCode.CtrlMask + (wch2 & ~(int)KeyCode.CtrlMask));
  720. // }
  721. // if (wch2 == 0)
  722. // {
  723. // k = KeyCode.CtrlMask | KeyCode.AltMask | KeyCode.Space;
  724. // }
  725. // //else if (wch >= (uint)KeyCode.A && wch <= (uint)KeyCode.Z)
  726. // //{
  727. // // k = KeyCode.ShiftMask | KeyCode.AltMask | KeyCode.Space;
  728. // //}
  729. // else if (wch2 < 256)
  730. // {
  731. // k = (KeyCode)wch2; // | KeyCode.AltMask;
  732. // }
  733. // else
  734. // {
  735. // k = (KeyCode)((uint)(KeyCode.AltMask | KeyCode.CtrlMask) + wch2);
  736. // }
  737. //}
  738. key = new Key (k);
  739. }
  740. else
  741. {
  742. key = Key.Esc;
  743. }
  744. OnKeyDown (key);
  745. OnKeyUp (key);
  746. }
  747. else if (wch == 8) // Ctrl+Backspace
  748. {
  749. k = KeyCode.Backspace | KeyCode.CtrlMask;
  750. OnKeyDown (new Key (k));
  751. OnKeyUp (new Key (k));
  752. }
  753. else if (wch == Curses.KeyTab)
  754. {
  755. k = MapCursesKey (wch);
  756. OnKeyDown (new Key (k));
  757. OnKeyUp (new Key (k));
  758. }
  759. else if (wch == 127)
  760. {
  761. // Backspace needed for macOS
  762. k = KeyCode.Backspace;
  763. OnKeyDown (new Key (k));
  764. OnKeyUp (new Key (k));
  765. }
  766. else
  767. {
  768. // Unfortunately there are no way to differentiate Ctrl+alfa and Ctrl+Shift+alfa.
  769. k = (KeyCode)wch;
  770. if (wch == 0)
  771. {
  772. k = KeyCode.CtrlMask | KeyCode.Space;
  773. }
  774. else if (wch >= (uint)KeyCode.A - 64 && wch <= (uint)KeyCode.Z - 64)
  775. {
  776. if ((KeyCode)(wch + 64) != KeyCode.J)
  777. {
  778. k = KeyCode.CtrlMask | (KeyCode)(wch + 64);
  779. }
  780. }
  781. else if (wch >= (uint)KeyCode.A && wch <= (uint)KeyCode.Z)
  782. {
  783. k = (KeyCode)wch | KeyCode.ShiftMask;
  784. }
  785. if (wch == '\n' || wch == '\r')
  786. {
  787. k = KeyCode.Enter;
  788. }
  789. // Strip the KeyCode.Space flag off if it's set
  790. //if (k != KeyCode.Space && k.HasFlag (KeyCode.Space))
  791. if (Key.GetIsKeyCodeAtoZ (k) && (k & KeyCode.Space) != 0)
  792. {
  793. k &= ~KeyCode.Space;
  794. }
  795. if (IsValidInput (k, out k))
  796. {
  797. OnKeyDown (new (k));
  798. OnKeyUp (new (k));
  799. }
  800. }
  801. }
  802. internal void ProcessWinChange ()
  803. {
  804. if (!RunningUnitTests && Curses.CheckWinChange ())
  805. {
  806. ClearContents ();
  807. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  808. }
  809. }
  810. static string ConvertToString (ConsoleKeyInfo [] keyInfos)
  811. {
  812. char [] chars = new char [keyInfos.Length];
  813. for (int i = 0; i < keyInfos.Length; i++)
  814. {
  815. chars [i] = keyInfos [i].KeyChar;
  816. }
  817. return new string (chars);
  818. }
  819. private void HandleEscSeqResponse (
  820. ref int code,
  821. ref KeyCode k,
  822. ref int wch2,
  823. ref Key keyEventArgs,
  824. ref ConsoleKeyInfo [] cki
  825. )
  826. {
  827. ConsoleKey ck = 0;
  828. ConsoleModifiers mod = 0;
  829. while (code == 0)
  830. {
  831. code = Curses.get_wch (out wch2);
  832. var consoleKeyInfo = new ConsoleKeyInfo ((char)wch2, 0, false, false, false);
  833. if (wch2 == 0 || wch2 == 27 || wch2 == Curses.KeyMouse)
  834. {
  835. // Give ansi parser a chance to deal with the escape sequence
  836. if (cki != null && string.IsNullOrEmpty(_parser.ProcessInput (ConvertToString(cki))))
  837. {
  838. // Parser fully consumed all keys meaning keys are processed - job done
  839. return;
  840. }
  841. // Ansi parser could not deal with it either because it is not expecting
  842. // the given terminator (e.g. mouse) or did not understand format somehow.
  843. // Carry on with the older code for processing curses escape codes
  844. // BUGBUG: Fix this nullable issue.
  845. EscSeqUtils.DecodeEscSeq (
  846. ref consoleKeyInfo,
  847. ref ck,
  848. cki,
  849. ref mod,
  850. out _,
  851. out _,
  852. out _,
  853. out _,
  854. out bool isKeyMouse,
  855. out List<MouseFlags> mouseFlags,
  856. out Point pos,
  857. out _,
  858. EscSeqUtils.ProcessMouseEvent
  859. );
  860. if (isKeyMouse)
  861. {
  862. foreach (MouseFlags mf in mouseFlags)
  863. {
  864. OnMouseEvent (new () { Flags = mf, Position = pos });
  865. }
  866. // BUGBUG: Fix this nullable issue.
  867. cki = null;
  868. if (wch2 == 27)
  869. {
  870. cki = EscSeqUtils.ResizeArray (
  871. new ConsoleKeyInfo (
  872. (char)KeyCode.Esc,
  873. 0,
  874. false,
  875. false,
  876. false
  877. ),
  878. cki
  879. );
  880. }
  881. }
  882. else
  883. {
  884. k = ConsoleKeyMapping.MapConsoleKeyInfoToKeyCode (consoleKeyInfo);
  885. keyEventArgs = new Key (k);
  886. OnKeyDown (keyEventArgs);
  887. }
  888. }
  889. else
  890. {
  891. cki = EscSeqUtils.ResizeArray (consoleKeyInfo, cki);
  892. }
  893. }
  894. }
  895. private void EscSeqUtils_ContinuousButtonPressed (object? sender, MouseEventArgs e)
  896. {
  897. OnMouseEvent (e);
  898. }
  899. private static KeyCode MapCursesKey (int cursesKey)
  900. {
  901. switch (cursesKey)
  902. {
  903. case Curses.KeyF1: return KeyCode.F1;
  904. case Curses.KeyF2: return KeyCode.F2;
  905. case Curses.KeyF3: return KeyCode.F3;
  906. case Curses.KeyF4: return KeyCode.F4;
  907. case Curses.KeyF5: return KeyCode.F5;
  908. case Curses.KeyF6: return KeyCode.F6;
  909. case Curses.KeyF7: return KeyCode.F7;
  910. case Curses.KeyF8: return KeyCode.F8;
  911. case Curses.KeyF9: return KeyCode.F9;
  912. case Curses.KeyF10: return KeyCode.F10;
  913. case Curses.KeyF11: return KeyCode.F11;
  914. case Curses.KeyF12: return KeyCode.F12;
  915. case Curses.KeyUp: return KeyCode.CursorUp;
  916. case Curses.KeyDown: return KeyCode.CursorDown;
  917. case Curses.KeyLeft: return KeyCode.CursorLeft;
  918. case Curses.KeyRight: return KeyCode.CursorRight;
  919. case Curses.KeyHome: return KeyCode.Home;
  920. case Curses.KeyEnd: return KeyCode.End;
  921. case Curses.KeyNPage: return KeyCode.PageDown;
  922. case Curses.KeyPPage: return KeyCode.PageUp;
  923. case Curses.KeyDeleteChar: return KeyCode.Delete;
  924. case Curses.KeyInsertChar: return KeyCode.Insert;
  925. case Curses.KeyTab: return KeyCode.Tab;
  926. case Curses.KeyBackTab: return KeyCode.Tab | KeyCode.ShiftMask;
  927. case Curses.KeyBackspace: return KeyCode.Backspace;
  928. case Curses.ShiftKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask;
  929. case Curses.ShiftKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask;
  930. case Curses.ShiftKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask;
  931. case Curses.ShiftKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask;
  932. case Curses.ShiftKeyHome: return KeyCode.Home | KeyCode.ShiftMask;
  933. case Curses.ShiftKeyEnd: return KeyCode.End | KeyCode.ShiftMask;
  934. case Curses.ShiftKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask;
  935. case Curses.ShiftKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask;
  936. case Curses.AltKeyUp: return KeyCode.CursorUp | KeyCode.AltMask;
  937. case Curses.AltKeyDown: return KeyCode.CursorDown | KeyCode.AltMask;
  938. case Curses.AltKeyLeft: return KeyCode.CursorLeft | KeyCode.AltMask;
  939. case Curses.AltKeyRight: return KeyCode.CursorRight | KeyCode.AltMask;
  940. case Curses.AltKeyHome: return KeyCode.Home | KeyCode.AltMask;
  941. case Curses.AltKeyEnd: return KeyCode.End | KeyCode.AltMask;
  942. case Curses.AltKeyNPage: return KeyCode.PageDown | KeyCode.AltMask;
  943. case Curses.AltKeyPPage: return KeyCode.PageUp | KeyCode.AltMask;
  944. case Curses.CtrlKeyUp: return KeyCode.CursorUp | KeyCode.CtrlMask;
  945. case Curses.CtrlKeyDown: return KeyCode.CursorDown | KeyCode.CtrlMask;
  946. case Curses.CtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.CtrlMask;
  947. case Curses.CtrlKeyRight: return KeyCode.CursorRight | KeyCode.CtrlMask;
  948. case Curses.CtrlKeyHome: return KeyCode.Home | KeyCode.CtrlMask;
  949. case Curses.CtrlKeyEnd: return KeyCode.End | KeyCode.CtrlMask;
  950. case Curses.CtrlKeyNPage: return KeyCode.PageDown | KeyCode.CtrlMask;
  951. case Curses.CtrlKeyPPage: return KeyCode.PageUp | KeyCode.CtrlMask;
  952. case Curses.ShiftCtrlKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.CtrlMask;
  953. case Curses.ShiftCtrlKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.CtrlMask;
  954. case Curses.ShiftCtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.CtrlMask;
  955. case Curses.ShiftCtrlKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.CtrlMask;
  956. case Curses.ShiftCtrlKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.CtrlMask;
  957. case Curses.ShiftCtrlKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.CtrlMask;
  958. case Curses.ShiftCtrlKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.CtrlMask;
  959. case Curses.ShiftCtrlKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.CtrlMask;
  960. case Curses.ShiftAltKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.AltMask;
  961. case Curses.ShiftAltKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.AltMask;
  962. case Curses.ShiftAltKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.AltMask;
  963. case Curses.ShiftAltKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.AltMask;
  964. case Curses.ShiftAltKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.AltMask;
  965. case Curses.ShiftAltKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.AltMask;
  966. case Curses.ShiftAltKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.AltMask;
  967. case Curses.ShiftAltKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.AltMask;
  968. case Curses.AltCtrlKeyNPage: return KeyCode.PageDown | KeyCode.AltMask | KeyCode.CtrlMask;
  969. case Curses.AltCtrlKeyPPage: return KeyCode.PageUp | KeyCode.AltMask | KeyCode.CtrlMask;
  970. case Curses.AltCtrlKeyHome: return KeyCode.Home | KeyCode.AltMask | KeyCode.CtrlMask;
  971. case Curses.AltCtrlKeyEnd: return KeyCode.End | KeyCode.AltMask | KeyCode.CtrlMask;
  972. default: return KeyCode.Null;
  973. }
  974. }
  975. public override void End ()
  976. {
  977. EscSeqUtils.ContinuousButtonPressed -= EscSeqUtils_ContinuousButtonPressed;
  978. StopReportingMouseMoves ();
  979. SetCursorVisibility (CursorVisibility.Default);
  980. if (_mainLoopDriver is { } && _processInputToken != null)
  981. {
  982. _mainLoopDriver.RemoveWatch (_processInputToken);
  983. }
  984. if (RunningUnitTests)
  985. {
  986. return;
  987. }
  988. // throws away any typeahead that has been typed by
  989. // the user and has not yet been read by the program.
  990. Curses.flushinp ();
  991. Curses.endwin ();
  992. }
  993. #endregion Init/End/MainLoop
  994. public static bool Is_WSL_Platform ()
  995. {
  996. // xclip does not work on WSL, so we need to use the Windows clipboard vis Powershell
  997. //if (new CursesClipboard ().IsSupported) {
  998. // // If xclip is installed on Linux under WSL, this will return true.
  999. // return false;
  1000. //}
  1001. (int exitCode, string result) = ClipboardProcessRunner.Bash ("uname -a", waitForOutput: true);
  1002. if (exitCode == 0 && result.Contains ("microsoft") && result.Contains ("WSL"))
  1003. {
  1004. return true;
  1005. }
  1006. return false;
  1007. }
  1008. /// <inheritdoc/>
  1009. public override void WriteRaw (string ansi) { _mainLoopDriver?.WriteRaw (ansi); }
  1010. }
  1011. // TODO: One type per file - move to another file
  1012. internal static class Platform
  1013. {
  1014. private static int _suspendSignal;
  1015. /// <summary>Suspends the process by sending SIGTSTP to itself</summary>
  1016. /// <returns>True if the suspension was successful.</returns>
  1017. public static bool Suspend ()
  1018. {
  1019. int signal = GetSuspendSignal ();
  1020. if (signal == -1)
  1021. {
  1022. return false;
  1023. }
  1024. killpg (0, signal);
  1025. return true;
  1026. }
  1027. private static int GetSuspendSignal ()
  1028. {
  1029. if (_suspendSignal != 0)
  1030. {
  1031. return _suspendSignal;
  1032. }
  1033. nint buf = Marshal.AllocHGlobal (8192);
  1034. if (uname (buf) != 0)
  1035. {
  1036. Marshal.FreeHGlobal (buf);
  1037. _suspendSignal = -1;
  1038. return _suspendSignal;
  1039. }
  1040. try
  1041. {
  1042. switch (Marshal.PtrToStringAnsi (buf))
  1043. {
  1044. case "Darwin":
  1045. case "DragonFly":
  1046. case "FreeBSD":
  1047. case "NetBSD":
  1048. case "OpenBSD":
  1049. _suspendSignal = 18;
  1050. break;
  1051. case "Linux":
  1052. // TODO: should fetch the machine name and
  1053. // if it is MIPS return 24
  1054. _suspendSignal = 20;
  1055. break;
  1056. case "Solaris":
  1057. _suspendSignal = 24;
  1058. break;
  1059. default:
  1060. _suspendSignal = -1;
  1061. break;
  1062. }
  1063. return _suspendSignal;
  1064. }
  1065. finally
  1066. {
  1067. Marshal.FreeHGlobal (buf);
  1068. }
  1069. }
  1070. [DllImport ("libc")]
  1071. private static extern int killpg (int pgrp, int pid);
  1072. [DllImport ("libc")]
  1073. private static extern int uname (nint buf);
  1074. }