CursesDriver.cs 41 KB

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