CursesDriver.cs 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  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. /// <inheritdoc />
  100. internal override void RawWrite (string str)
  101. {
  102. Console.Out.Write (str);
  103. }
  104. public override void Suspend ()
  105. {
  106. StopReportingMouseMoves ();
  107. if (!RunningUnitTests)
  108. {
  109. Platform.Suspend ();
  110. if (Force16Colors)
  111. {
  112. Curses.Window.Standard.redrawwin ();
  113. Curses.refresh ();
  114. }
  115. }
  116. StartReportingMouseMoves ();
  117. }
  118. public override void UpdateCursor ()
  119. {
  120. EnsureCursorVisibility ();
  121. if (!RunningUnitTests && Col >= 0 && Col < Cols && Row >= 0 && Row < Rows)
  122. {
  123. if (Force16Colors)
  124. {
  125. Curses.move (Row, Col);
  126. Curses.raw ();
  127. Curses.noecho ();
  128. Curses.refresh ();
  129. }
  130. else
  131. {
  132. _mainLoopDriver?.WriteRaw (EscSeqUtils.CSI_SetCursorPosition (Row + 1, Col + 1));
  133. }
  134. }
  135. }
  136. public override bool UpdateScreen ()
  137. {
  138. bool updated = false;
  139. if (Force16Colors)
  140. {
  141. for (var row = 0; row < Rows; row++)
  142. {
  143. if (!_dirtyLines! [row])
  144. {
  145. continue;
  146. }
  147. _dirtyLines [row] = false;
  148. for (var col = 0; col < Cols; col++)
  149. {
  150. if (Contents! [row, col].IsDirty == false)
  151. {
  152. continue;
  153. }
  154. if (RunningUnitTests)
  155. {
  156. // In unit tests, we don't want to actually write to the screen.
  157. continue;
  158. }
  159. Curses.attrset (Contents [row, col].Attribute.GetValueOrDefault ().PlatformColor);
  160. Rune rune = Contents [row, col].Rune;
  161. if (rune.IsBmp)
  162. {
  163. // 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.
  164. if (rune.GetColumns () < 2)
  165. {
  166. Curses.mvaddch (row, col, rune.Value);
  167. }
  168. else /*if (col + 1 < Cols)*/
  169. {
  170. Curses.mvaddwstr (row, col, rune.ToString ());
  171. }
  172. }
  173. else
  174. {
  175. Curses.mvaddwstr (row, col, rune.ToString ());
  176. if (rune.GetColumns () > 1 && col + 1 < Cols)
  177. {
  178. // TODO: This is a hack to deal with non-BMP and wide characters.
  179. //col++;
  180. Curses.mvaddch (row, ++col, '*');
  181. }
  182. }
  183. }
  184. }
  185. if (!RunningUnitTests)
  186. {
  187. Curses.move (Row, Col);
  188. _window?.wrefresh ();
  189. }
  190. }
  191. else
  192. {
  193. if (RunningUnitTests
  194. || Console.WindowHeight < 1
  195. || Contents!.Length != Rows * Cols
  196. || Rows != Console.WindowHeight)
  197. {
  198. return updated;
  199. }
  200. var top = 0;
  201. var left = 0;
  202. int rows = Rows;
  203. int cols = Cols;
  204. var output = new StringBuilder ();
  205. Attribute? redrawAttr = null;
  206. int lastCol = -1;
  207. CursorVisibility? savedVisibility = _currentCursorVisibility;
  208. SetCursorVisibility (CursorVisibility.Invisible);
  209. for (int row = top; row < rows; row++)
  210. {
  211. if (Console.WindowHeight < 1)
  212. {
  213. return updated;
  214. }
  215. if (!_dirtyLines! [row])
  216. {
  217. continue;
  218. }
  219. if (!SetCursorPosition (0, row))
  220. {
  221. return updated;
  222. }
  223. _dirtyLines [row] = false;
  224. output.Clear ();
  225. for (int col = left; col < cols; col++)
  226. {
  227. lastCol = -1;
  228. var outputWidth = 0;
  229. for (; col < cols; col++)
  230. {
  231. updated = true;
  232. if (!Contents [row, col].IsDirty)
  233. {
  234. if (output.Length > 0)
  235. {
  236. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  237. }
  238. else if (lastCol == -1)
  239. {
  240. lastCol = col;
  241. }
  242. if (lastCol + 1 < cols)
  243. {
  244. lastCol++;
  245. }
  246. continue;
  247. }
  248. if (lastCol == -1)
  249. {
  250. lastCol = col;
  251. }
  252. Attribute attr = Contents [row, col].Attribute!.Value;
  253. // Performance: Only send the escape sequence if the attribute has changed.
  254. if (attr != redrawAttr)
  255. {
  256. redrawAttr = attr;
  257. output.Append (
  258. EscSeqUtils.CSI_SetForegroundColorRGB (
  259. attr.Foreground.R,
  260. attr.Foreground.G,
  261. attr.Foreground.B
  262. )
  263. );
  264. output.Append (
  265. EscSeqUtils.CSI_SetBackgroundColorRGB (
  266. attr.Background.R,
  267. attr.Background.G,
  268. attr.Background.B
  269. )
  270. );
  271. }
  272. outputWidth++;
  273. Rune rune = Contents [row, col].Rune;
  274. output.Append (rune);
  275. if (Contents [row, col].CombiningMarks.Count > 0)
  276. {
  277. // AtlasEngine does not support NON-NORMALIZED combining marks in a way
  278. // compatible with the driver architecture. Any CMs (except in the first col)
  279. // are correctly combined with the base char, but are ALSO treated as 1 column
  280. // width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
  281. //
  282. // For now, we just ignore the list of CMs.
  283. //foreach (var combMark in Contents [row, col].CombiningMarks) {
  284. // output.Append (combMark);
  285. //}
  286. // WriteToConsole (output, ref lastCol, row, ref outputWidth);
  287. }
  288. else if (rune.IsSurrogatePair () && rune.GetColumns () < 2)
  289. {
  290. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  291. SetCursorPosition (col - 1, row);
  292. }
  293. Contents [row, col].IsDirty = false;
  294. }
  295. }
  296. if (output.Length > 0)
  297. {
  298. SetCursorPosition (lastCol, row);
  299. Console.Write (output);
  300. }
  301. }
  302. // SIXELS
  303. foreach (SixelToRender s in Application.Sixel)
  304. {
  305. SetCursorPosition (s.ScreenPosition.X, s.ScreenPosition.Y);
  306. Console.Write (s.SixelData);
  307. }
  308. SetCursorPosition (0, 0);
  309. _currentCursorVisibility = savedVisibility;
  310. void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
  311. {
  312. SetCursorPosition (lastCol, row);
  313. Console.Write (output);
  314. output.Clear ();
  315. lastCol += outputWidth;
  316. outputWidth = 0;
  317. }
  318. }
  319. return updated;
  320. }
  321. #region Color Handling
  322. public override bool SupportsTrueColor => true;
  323. /// <summary>Creates an Attribute from the provided curses-based foreground and background color numbers</summary>
  324. /// <param name="foreground">Contains the curses color number for the foreground (color, plus any attributes)</param>
  325. /// <param name="background">Contains the curses color number for the background (color, plus any attributes)</param>
  326. /// <returns></returns>
  327. private static Attribute MakeColor (short foreground, short background)
  328. {
  329. //var v = (short)((ushort)foreground | (background << 4));
  330. var v = (short)(((ushort)(foreground & 0xffff) << 16) | (background & 0xffff));
  331. // TODO: for TrueColor - Use InitExtendedPair
  332. Curses.InitColorPair (v, foreground, background);
  333. return new (
  334. Curses.ColorPair (v),
  335. CursesColorNumberToColorName16 (foreground),
  336. CursesColorNumberToColorName16 (background)
  337. );
  338. }
  339. /// <inheritdoc/>
  340. /// <remarks>
  341. /// In the CursesDriver, colors are encoded as an int. The foreground color is stored in the most significant 4
  342. /// bits, and the background color is stored in the least significant 4 bits. The Terminal.GUi Color values are
  343. /// converted to curses color encoding before being encoded.
  344. /// </remarks>
  345. public override Attribute MakeColor (in Color foreground, in Color background)
  346. {
  347. if (!RunningUnitTests && Force16Colors)
  348. {
  349. return MakeColor (
  350. ColorNameToCursesColorNumber (foreground.GetClosestNamedColor16 ()),
  351. ColorNameToCursesColorNumber (background.GetClosestNamedColor16 ())
  352. );
  353. }
  354. return new (
  355. 0,
  356. foreground,
  357. background
  358. );
  359. }
  360. private static short ColorNameToCursesColorNumber (ColorName16 color)
  361. {
  362. switch (color)
  363. {
  364. case ColorName16.Black:
  365. return Curses.COLOR_BLACK;
  366. case ColorName16.Blue:
  367. return Curses.COLOR_BLUE;
  368. case ColorName16.Green:
  369. return Curses.COLOR_GREEN;
  370. case ColorName16.Cyan:
  371. return Curses.COLOR_CYAN;
  372. case ColorName16.Red:
  373. return Curses.COLOR_RED;
  374. case ColorName16.Magenta:
  375. return Curses.COLOR_MAGENTA;
  376. case ColorName16.Yellow:
  377. return Curses.COLOR_YELLOW;
  378. case ColorName16.Gray:
  379. return Curses.COLOR_WHITE;
  380. case ColorName16.DarkGray:
  381. return Curses.COLOR_GRAY;
  382. case ColorName16.BrightBlue:
  383. return Curses.COLOR_BLUE | Curses.COLOR_GRAY;
  384. case ColorName16.BrightGreen:
  385. return Curses.COLOR_GREEN | Curses.COLOR_GRAY;
  386. case ColorName16.BrightCyan:
  387. return Curses.COLOR_CYAN | Curses.COLOR_GRAY;
  388. case ColorName16.BrightRed:
  389. return Curses.COLOR_RED | Curses.COLOR_GRAY;
  390. case ColorName16.BrightMagenta:
  391. return Curses.COLOR_MAGENTA | Curses.COLOR_GRAY;
  392. case ColorName16.BrightYellow:
  393. return Curses.COLOR_YELLOW | Curses.COLOR_GRAY;
  394. case ColorName16.White:
  395. return Curses.COLOR_WHITE | Curses.COLOR_GRAY;
  396. }
  397. throw new ArgumentException ("Invalid color code");
  398. }
  399. private static ColorName16 CursesColorNumberToColorName16 (short color)
  400. {
  401. switch (color)
  402. {
  403. case Curses.COLOR_BLACK:
  404. return ColorName16.Black;
  405. case Curses.COLOR_BLUE:
  406. return ColorName16.Blue;
  407. case Curses.COLOR_GREEN:
  408. return ColorName16.Green;
  409. case Curses.COLOR_CYAN:
  410. return ColorName16.Cyan;
  411. case Curses.COLOR_RED:
  412. return ColorName16.Red;
  413. case Curses.COLOR_MAGENTA:
  414. return ColorName16.Magenta;
  415. case Curses.COLOR_YELLOW:
  416. return ColorName16.Yellow;
  417. case Curses.COLOR_WHITE:
  418. return ColorName16.Gray;
  419. case Curses.COLOR_GRAY:
  420. return ColorName16.DarkGray;
  421. case Curses.COLOR_BLUE | Curses.COLOR_GRAY:
  422. return ColorName16.BrightBlue;
  423. case Curses.COLOR_GREEN | Curses.COLOR_GRAY:
  424. return ColorName16.BrightGreen;
  425. case Curses.COLOR_CYAN | Curses.COLOR_GRAY:
  426. return ColorName16.BrightCyan;
  427. case Curses.COLOR_RED | Curses.COLOR_GRAY:
  428. return ColorName16.BrightRed;
  429. case Curses.COLOR_MAGENTA | Curses.COLOR_GRAY:
  430. return ColorName16.BrightMagenta;
  431. case Curses.COLOR_YELLOW | Curses.COLOR_GRAY:
  432. return ColorName16.BrightYellow;
  433. case Curses.COLOR_WHITE | Curses.COLOR_GRAY:
  434. return ColorName16.White;
  435. }
  436. throw new ArgumentException ("Invalid curses color code");
  437. }
  438. #endregion
  439. private CursorVisibility? _currentCursorVisibility;
  440. private CursorVisibility? _initialCursorVisibility;
  441. /// <inheritdoc/>
  442. public override bool EnsureCursorVisibility ()
  443. {
  444. if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows))
  445. {
  446. GetCursorVisibility (out CursorVisibility cursorVisibility);
  447. _currentCursorVisibility = cursorVisibility;
  448. SetCursorVisibility (CursorVisibility.Invisible);
  449. return false;
  450. }
  451. SetCursorVisibility (_currentCursorVisibility ?? CursorVisibility.Default);
  452. return _currentCursorVisibility == CursorVisibility.Default;
  453. }
  454. /// <inheritdoc/>
  455. public override bool GetCursorVisibility (out CursorVisibility visibility)
  456. {
  457. visibility = CursorVisibility.Invisible;
  458. if (!_currentCursorVisibility.HasValue)
  459. {
  460. return false;
  461. }
  462. visibility = _currentCursorVisibility.Value;
  463. return true;
  464. }
  465. /// <inheritdoc/>
  466. public override bool SetCursorVisibility (CursorVisibility visibility)
  467. {
  468. if (_initialCursorVisibility.HasValue == false)
  469. {
  470. return false;
  471. }
  472. if (!RunningUnitTests)
  473. {
  474. Curses.curs_set (((int)visibility >> 16) & 0x000000FF);
  475. }
  476. if (visibility != CursorVisibility.Invisible)
  477. {
  478. _mainLoopDriver?.WriteRaw (
  479. EscSeqUtils.CSI_SetCursorStyle (
  480. (EscSeqUtils.DECSCUSR_Style)
  481. (((int)visibility >> 24)
  482. & 0xFF)
  483. )
  484. );
  485. }
  486. _currentCursorVisibility = visibility;
  487. return true;
  488. }
  489. private bool SetCursorPosition (int col, int row)
  490. {
  491. // + 1 is needed because non-Windows is based on 1 instead of 0 and
  492. // Console.CursorTop/CursorLeft isn't reliable.
  493. Console.Out.Write (EscSeqUtils.CSI_SetCursorPosition (row + 1, col + 1));
  494. return true;
  495. }
  496. #region Init/End/MainLoop
  497. private Curses.Window? _window;
  498. private UnixMainLoop? _mainLoopDriver;
  499. private object _processInputToken;
  500. public override MainLoop Init ()
  501. {
  502. _mainLoopDriver = new (this);
  503. if (!RunningUnitTests)
  504. {
  505. _window = Curses.initscr ();
  506. Curses.set_escdelay (10);
  507. // Ensures that all procedures are performed at some previous closing.
  508. Curses.doupdate ();
  509. //
  510. // We are setting Invisible as default, so we could ignore XTerm DECSUSR setting
  511. //
  512. switch (Curses.curs_set (0))
  513. {
  514. case 0:
  515. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Invisible;
  516. break;
  517. case 1:
  518. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Underline;
  519. Curses.curs_set (1);
  520. break;
  521. case 2:
  522. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Box;
  523. Curses.curs_set (2);
  524. break;
  525. default:
  526. _currentCursorVisibility = _initialCursorVisibility = null;
  527. break;
  528. }
  529. if (!Curses.HasColors)
  530. {
  531. throw new InvalidOperationException ("V2 - This should never happen. File an Issue if it does.");
  532. }
  533. Curses.raw ();
  534. Curses.noecho ();
  535. Curses.Window.Standard.keypad (true);
  536. Curses.StartColor ();
  537. Curses.UseDefaultColors ();
  538. if (!RunningUnitTests)
  539. {
  540. Curses.timeout (0);
  541. }
  542. _processInputToken = _mainLoopDriver.AddWatch (
  543. 0,
  544. UnixMainLoop.Condition.PollIn,
  545. x =>
  546. {
  547. ProcessInput ();
  548. return true;
  549. }
  550. );
  551. }
  552. CurrentAttribute = new (ColorName16.White, ColorName16.Black);
  553. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  554. {
  555. Clipboard = new FakeDriver.FakeClipboard ();
  556. }
  557. else
  558. {
  559. if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
  560. {
  561. Clipboard = new MacOSXClipboard ();
  562. }
  563. else
  564. {
  565. if (Is_WSL_Platform ())
  566. {
  567. Clipboard = new WSLClipboard ();
  568. }
  569. else
  570. {
  571. Clipboard = new CursesClipboard ();
  572. }
  573. }
  574. }
  575. ClearContents ();
  576. StartReportingMouseMoves ();
  577. if (!RunningUnitTests)
  578. {
  579. Curses.CheckWinChange ();
  580. // On Init this call is needed no mater Force16Colors or not
  581. Curses.refresh ();
  582. EscSeqUtils.ContinuousButtonPressed += EscSeqUtils_ContinuousButtonPressed;
  583. }
  584. return new (_mainLoopDriver);
  585. }
  586. private readonly AnsiResponseParser _parser = new ();
  587. /// <inheritdoc />
  588. internal override IAnsiResponseParser GetParser () => _parser;
  589. internal void ProcessInput ()
  590. {
  591. int wch;
  592. int code = Curses.get_wch (out wch);
  593. //System.Diagnostics.Debug.WriteLine ($"code: {code}; wch: {wch}");
  594. if (code == Curses.ERR)
  595. {
  596. return;
  597. }
  598. var k = KeyCode.Null;
  599. if (code == Curses.KEY_CODE_YES)
  600. {
  601. while (code == Curses.KEY_CODE_YES && wch == Curses.KeyResize)
  602. {
  603. ProcessWinChange ();
  604. code = Curses.get_wch (out wch);
  605. }
  606. if (wch == 0)
  607. {
  608. return;
  609. }
  610. if (wch == Curses.KeyMouse)
  611. {
  612. int wch2 = wch;
  613. while (wch2 == Curses.KeyMouse)
  614. {
  615. Key kea = null;
  616. ConsoleKeyInfo [] cki =
  617. {
  618. new ((char)KeyCode.Esc, 0, false, false, false),
  619. new ('[', 0, false, false, false),
  620. new ('<', 0, false, false, false)
  621. };
  622. code = 0;
  623. HandleEscSeqResponse (ref code, ref k, ref wch2, ref kea, ref cki);
  624. }
  625. return;
  626. }
  627. k = MapCursesKey (wch);
  628. if (wch >= 277 && wch <= 288)
  629. {
  630. // Shift+(F1 - F12)
  631. wch -= 12;
  632. k = KeyCode.ShiftMask | MapCursesKey (wch);
  633. }
  634. else if (wch >= 289 && wch <= 300)
  635. {
  636. // Ctrl+(F1 - F12)
  637. wch -= 24;
  638. k = KeyCode.CtrlMask | MapCursesKey (wch);
  639. }
  640. else if (wch >= 301 && wch <= 312)
  641. {
  642. // Ctrl+Shift+(F1 - F12)
  643. wch -= 36;
  644. k = KeyCode.CtrlMask | KeyCode.ShiftMask | MapCursesKey (wch);
  645. }
  646. else if (wch >= 313 && wch <= 324)
  647. {
  648. // Alt+(F1 - F12)
  649. wch -= 48;
  650. k = KeyCode.AltMask | MapCursesKey (wch);
  651. }
  652. else if (wch >= 325 && wch <= 327)
  653. {
  654. // Shift+Alt+(F1 - F3)
  655. wch -= 60;
  656. k = KeyCode.ShiftMask | KeyCode.AltMask | MapCursesKey (wch);
  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. 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. HandleEscSeqResponse (ref code, ref k, ref wch2, ref key, ref cki);
  701. return;
  702. }
  703. //else if (wch2 == Curses.KeyCSI)
  704. //{
  705. // ConsoleKeyInfo [] cki =
  706. // {
  707. // new ((char)KeyCode.Esc, 0, false, false, false), new ('[', 0, false, false, false)
  708. // };
  709. // HandleEscSeqResponse (ref code, ref k, ref wch2, ref key, ref cki);
  710. // return;
  711. //}
  712. //else
  713. //{
  714. // // Unfortunately there are no way to differentiate Ctrl+Alt+alfa and Ctrl+Shift+Alt+alfa.
  715. // if (((KeyCode)wch2 & KeyCode.CtrlMask) != 0)
  716. // {
  717. // k = (KeyCode)((uint)KeyCode.CtrlMask + (wch2 & ~(int)KeyCode.CtrlMask));
  718. // }
  719. // if (wch2 == 0)
  720. // {
  721. // k = KeyCode.CtrlMask | KeyCode.AltMask | KeyCode.Space;
  722. // }
  723. // //else if (wch >= (uint)KeyCode.A && wch <= (uint)KeyCode.Z)
  724. // //{
  725. // // k = KeyCode.ShiftMask | KeyCode.AltMask | KeyCode.Space;
  726. // //}
  727. // else if (wch2 < 256)
  728. // {
  729. // k = (KeyCode)wch2; // | KeyCode.AltMask;
  730. // }
  731. // else
  732. // {
  733. // k = (KeyCode)((uint)(KeyCode.AltMask | KeyCode.CtrlMask) + wch2);
  734. // }
  735. //}
  736. key = new Key (k);
  737. }
  738. else
  739. {
  740. key = Key.Esc;
  741. }
  742. OnKeyDown (key);
  743. OnKeyUp (key);
  744. }
  745. else if (wch == Curses.KeyTab)
  746. {
  747. k = MapCursesKey (wch);
  748. OnKeyDown (new Key (k));
  749. OnKeyUp (new Key (k));
  750. }
  751. else if (wch == 127)
  752. {
  753. // Backspace needed for macOS
  754. k = KeyCode.Backspace;
  755. OnKeyDown (new Key (k));
  756. OnKeyUp (new Key (k));
  757. }
  758. else
  759. {
  760. // Unfortunately there are no way to differentiate Ctrl+alfa and Ctrl+Shift+alfa.
  761. k = (KeyCode)wch;
  762. if (wch == 0)
  763. {
  764. k = KeyCode.CtrlMask | KeyCode.Space;
  765. }
  766. else if (wch >= (uint)KeyCode.A - 64 && wch <= (uint)KeyCode.Z - 64)
  767. {
  768. if ((KeyCode)(wch + 64) != KeyCode.J)
  769. {
  770. k = KeyCode.CtrlMask | (KeyCode)(wch + 64);
  771. }
  772. }
  773. else if (wch >= (uint)KeyCode.A && wch <= (uint)KeyCode.Z)
  774. {
  775. k = (KeyCode)wch | KeyCode.ShiftMask;
  776. }
  777. if (wch == '\n' || wch == '\r')
  778. {
  779. k = KeyCode.Enter;
  780. }
  781. // Strip the KeyCode.Space flag off if it's set
  782. //if (k != KeyCode.Space && k.HasFlag (KeyCode.Space))
  783. if (Key.GetIsKeyCodeAtoZ (k) && (k & KeyCode.Space) != 0)
  784. {
  785. k &= ~KeyCode.Space;
  786. }
  787. OnKeyDown (new Key (k));
  788. OnKeyUp (new Key (k));
  789. }
  790. }
  791. internal void ProcessWinChange ()
  792. {
  793. if (!RunningUnitTests && Curses.CheckWinChange ())
  794. {
  795. ClearContents ();
  796. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  797. }
  798. }
  799. private void HandleEscSeqResponse (
  800. ref int code,
  801. ref KeyCode k,
  802. ref int wch2,
  803. ref Key keyEventArgs,
  804. ref ConsoleKeyInfo [] cki
  805. )
  806. {
  807. ConsoleKey ck = 0;
  808. ConsoleModifiers mod = 0;
  809. while (code == 0)
  810. {
  811. code = Curses.get_wch (out wch2);
  812. var consoleKeyInfo = new ConsoleKeyInfo ((char)wch2, 0, false, false, false);
  813. if (wch2 == 0 || wch2 == 27 || wch2 == Curses.KeyMouse)
  814. {
  815. EscSeqUtils.DecodeEscSeq (
  816. ref consoleKeyInfo,
  817. ref ck,
  818. cki,
  819. ref mod,
  820. out _,
  821. out _,
  822. out _,
  823. out _,
  824. out bool isKeyMouse,
  825. out List<MouseFlags> mouseFlags,
  826. out Point pos,
  827. out _,
  828. EscSeqUtils.ProcessMouseEvent
  829. );
  830. if (isKeyMouse)
  831. {
  832. foreach (MouseFlags mf in mouseFlags)
  833. {
  834. OnMouseEvent (new () { Flags = mf, Position = pos });
  835. }
  836. cki = null;
  837. if (wch2 == 27)
  838. {
  839. cki = EscSeqUtils.ResizeArray (
  840. new ConsoleKeyInfo (
  841. (char)KeyCode.Esc,
  842. 0,
  843. false,
  844. false,
  845. false
  846. ),
  847. cki
  848. );
  849. }
  850. }
  851. else
  852. {
  853. if (cki != null)
  854. {
  855. foreach (var c in cki)
  856. {
  857. _parser.ProcessInput (c.KeyChar.ToString());
  858. }
  859. }
  860. k = ConsoleKeyMapping.MapConsoleKeyInfoToKeyCode (consoleKeyInfo);
  861. keyEventArgs = new Key (k);
  862. OnKeyDown (keyEventArgs);
  863. }
  864. }
  865. else
  866. {
  867. cki = EscSeqUtils.ResizeArray (consoleKeyInfo, cki);
  868. }
  869. }
  870. }
  871. private void EscSeqUtils_ContinuousButtonPressed (object? sender, MouseEventArgs e)
  872. {
  873. OnMouseEvent (e);
  874. }
  875. private static KeyCode MapCursesKey (int cursesKey)
  876. {
  877. switch (cursesKey)
  878. {
  879. case Curses.KeyF1: return KeyCode.F1;
  880. case Curses.KeyF2: return KeyCode.F2;
  881. case Curses.KeyF3: return KeyCode.F3;
  882. case Curses.KeyF4: return KeyCode.F4;
  883. case Curses.KeyF5: return KeyCode.F5;
  884. case Curses.KeyF6: return KeyCode.F6;
  885. case Curses.KeyF7: return KeyCode.F7;
  886. case Curses.KeyF8: return KeyCode.F8;
  887. case Curses.KeyF9: return KeyCode.F9;
  888. case Curses.KeyF10: return KeyCode.F10;
  889. case Curses.KeyF11: return KeyCode.F11;
  890. case Curses.KeyF12: return KeyCode.F12;
  891. case Curses.KeyUp: return KeyCode.CursorUp;
  892. case Curses.KeyDown: return KeyCode.CursorDown;
  893. case Curses.KeyLeft: return KeyCode.CursorLeft;
  894. case Curses.KeyRight: return KeyCode.CursorRight;
  895. case Curses.KeyHome: return KeyCode.Home;
  896. case Curses.KeyEnd: return KeyCode.End;
  897. case Curses.KeyNPage: return KeyCode.PageDown;
  898. case Curses.KeyPPage: return KeyCode.PageUp;
  899. case Curses.KeyDeleteChar: return KeyCode.Delete;
  900. case Curses.KeyInsertChar: return KeyCode.Insert;
  901. case Curses.KeyTab: return KeyCode.Tab;
  902. case Curses.KeyBackTab: return KeyCode.Tab | KeyCode.ShiftMask;
  903. case Curses.KeyBackspace: return KeyCode.Backspace;
  904. case Curses.ShiftKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask;
  905. case Curses.ShiftKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask;
  906. case Curses.ShiftKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask;
  907. case Curses.ShiftKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask;
  908. case Curses.ShiftKeyHome: return KeyCode.Home | KeyCode.ShiftMask;
  909. case Curses.ShiftKeyEnd: return KeyCode.End | KeyCode.ShiftMask;
  910. case Curses.ShiftKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask;
  911. case Curses.ShiftKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask;
  912. case Curses.AltKeyUp: return KeyCode.CursorUp | KeyCode.AltMask;
  913. case Curses.AltKeyDown: return KeyCode.CursorDown | KeyCode.AltMask;
  914. case Curses.AltKeyLeft: return KeyCode.CursorLeft | KeyCode.AltMask;
  915. case Curses.AltKeyRight: return KeyCode.CursorRight | KeyCode.AltMask;
  916. case Curses.AltKeyHome: return KeyCode.Home | KeyCode.AltMask;
  917. case Curses.AltKeyEnd: return KeyCode.End | KeyCode.AltMask;
  918. case Curses.AltKeyNPage: return KeyCode.PageDown | KeyCode.AltMask;
  919. case Curses.AltKeyPPage: return KeyCode.PageUp | KeyCode.AltMask;
  920. case Curses.CtrlKeyUp: return KeyCode.CursorUp | KeyCode.CtrlMask;
  921. case Curses.CtrlKeyDown: return KeyCode.CursorDown | KeyCode.CtrlMask;
  922. case Curses.CtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.CtrlMask;
  923. case Curses.CtrlKeyRight: return KeyCode.CursorRight | KeyCode.CtrlMask;
  924. case Curses.CtrlKeyHome: return KeyCode.Home | KeyCode.CtrlMask;
  925. case Curses.CtrlKeyEnd: return KeyCode.End | KeyCode.CtrlMask;
  926. case Curses.CtrlKeyNPage: return KeyCode.PageDown | KeyCode.CtrlMask;
  927. case Curses.CtrlKeyPPage: return KeyCode.PageUp | KeyCode.CtrlMask;
  928. case Curses.ShiftCtrlKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.CtrlMask;
  929. case Curses.ShiftCtrlKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.CtrlMask;
  930. case Curses.ShiftCtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.CtrlMask;
  931. case Curses.ShiftCtrlKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.CtrlMask;
  932. case Curses.ShiftCtrlKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.CtrlMask;
  933. case Curses.ShiftCtrlKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.CtrlMask;
  934. case Curses.ShiftCtrlKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.CtrlMask;
  935. case Curses.ShiftCtrlKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.CtrlMask;
  936. case Curses.ShiftAltKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.AltMask;
  937. case Curses.ShiftAltKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.AltMask;
  938. case Curses.ShiftAltKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.AltMask;
  939. case Curses.ShiftAltKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.AltMask;
  940. case Curses.ShiftAltKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.AltMask;
  941. case Curses.ShiftAltKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.AltMask;
  942. case Curses.ShiftAltKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.AltMask;
  943. case Curses.ShiftAltKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.AltMask;
  944. case Curses.AltCtrlKeyNPage: return KeyCode.PageDown | KeyCode.AltMask | KeyCode.CtrlMask;
  945. case Curses.AltCtrlKeyPPage: return KeyCode.PageUp | KeyCode.AltMask | KeyCode.CtrlMask;
  946. case Curses.AltCtrlKeyHome: return KeyCode.Home | KeyCode.AltMask | KeyCode.CtrlMask;
  947. case Curses.AltCtrlKeyEnd: return KeyCode.End | KeyCode.AltMask | KeyCode.CtrlMask;
  948. default: return KeyCode.Null;
  949. }
  950. }
  951. public override void End ()
  952. {
  953. EscSeqUtils.ContinuousButtonPressed -= EscSeqUtils_ContinuousButtonPressed;
  954. StopReportingMouseMoves ();
  955. SetCursorVisibility (CursorVisibility.Default);
  956. if (_mainLoopDriver is { })
  957. {
  958. _mainLoopDriver.RemoveWatch (_processInputToken);
  959. }
  960. if (RunningUnitTests)
  961. {
  962. return;
  963. }
  964. // throws away any typeahead that has been typed by
  965. // the user and has not yet been read by the program.
  966. Curses.flushinp ();
  967. Curses.endwin ();
  968. }
  969. #endregion Init/End/MainLoop
  970. public static bool Is_WSL_Platform ()
  971. {
  972. // xclip does not work on WSL, so we need to use the Windows clipboard vis Powershell
  973. //if (new CursesClipboard ().IsSupported) {
  974. // // If xclip is installed on Linux under WSL, this will return true.
  975. // return false;
  976. //}
  977. (int exitCode, string result) = ClipboardProcessRunner.Bash ("uname -a", waitForOutput: true);
  978. if (exitCode == 0 && result.Contains ("microsoft") && result.Contains ("WSL"))
  979. {
  980. return true;
  981. }
  982. return false;
  983. }
  984. /// <inheritdoc/>
  985. public override void WriteRaw (string ansi) { _mainLoopDriver?.WriteRaw (ansi); }
  986. }
  987. // TODO: One type per file - move to another file
  988. internal static class Platform
  989. {
  990. private static int _suspendSignal;
  991. /// <summary>Suspends the process by sending SIGTSTP to itself</summary>
  992. /// <returns>True if the suspension was successful.</returns>
  993. public static bool Suspend ()
  994. {
  995. int signal = GetSuspendSignal ();
  996. if (signal == -1)
  997. {
  998. return false;
  999. }
  1000. killpg (0, signal);
  1001. return true;
  1002. }
  1003. private static int GetSuspendSignal ()
  1004. {
  1005. if (_suspendSignal != 0)
  1006. {
  1007. return _suspendSignal;
  1008. }
  1009. nint buf = Marshal.AllocHGlobal (8192);
  1010. if (uname (buf) != 0)
  1011. {
  1012. Marshal.FreeHGlobal (buf);
  1013. _suspendSignal = -1;
  1014. return _suspendSignal;
  1015. }
  1016. try
  1017. {
  1018. switch (Marshal.PtrToStringAnsi (buf))
  1019. {
  1020. case "Darwin":
  1021. case "DragonFly":
  1022. case "FreeBSD":
  1023. case "NetBSD":
  1024. case "OpenBSD":
  1025. _suspendSignal = 18;
  1026. break;
  1027. case "Linux":
  1028. // TODO: should fetch the machine name and
  1029. // if it is MIPS return 24
  1030. _suspendSignal = 20;
  1031. break;
  1032. case "Solaris":
  1033. _suspendSignal = 24;
  1034. break;
  1035. default:
  1036. _suspendSignal = -1;
  1037. break;
  1038. }
  1039. return _suspendSignal;
  1040. }
  1041. finally
  1042. {
  1043. Marshal.FreeHGlobal (buf);
  1044. }
  1045. }
  1046. [DllImport ("libc")]
  1047. private static extern int killpg (int pgrp, int pid);
  1048. [DllImport ("libc")]
  1049. private static extern int uname (nint buf);
  1050. }