CursesDriver.cs 43 KB

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