CursesDriver.cs 43 KB

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