CursesDriver.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  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. // BUGBUG: Fix this nullable issue.
  495. private object _processInputToken;
  496. public override MainLoop Init ()
  497. {
  498. _mainLoopDriver = new (this);
  499. if (!RunningUnitTests)
  500. {
  501. _window = Curses.initscr ();
  502. Curses.set_escdelay (10);
  503. // Ensures that all procedures are performed at some previous closing.
  504. Curses.doupdate ();
  505. //
  506. // We are setting Invisible as default, so we could ignore XTerm DECSUSR setting
  507. //
  508. switch (Curses.curs_set (0))
  509. {
  510. case 0:
  511. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Invisible;
  512. break;
  513. case 1:
  514. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Underline;
  515. Curses.curs_set (1);
  516. break;
  517. case 2:
  518. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Box;
  519. Curses.curs_set (2);
  520. break;
  521. default:
  522. _currentCursorVisibility = _initialCursorVisibility = null;
  523. break;
  524. }
  525. if (!Curses.HasColors)
  526. {
  527. throw new InvalidOperationException ("V2 - This should never happen. File an Issue if it does.");
  528. }
  529. Curses.raw ();
  530. Curses.noecho ();
  531. Curses.Window.Standard.keypad (true);
  532. Curses.StartColor ();
  533. Curses.UseDefaultColors ();
  534. if (!RunningUnitTests)
  535. {
  536. Curses.timeout (0);
  537. }
  538. _processInputToken = _mainLoopDriver.AddWatch (
  539. 0,
  540. UnixMainLoop.Condition.PollIn,
  541. x =>
  542. {
  543. ProcessInput ();
  544. return true;
  545. }
  546. );
  547. }
  548. CurrentAttribute = new (ColorName16.White, ColorName16.Black);
  549. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  550. {
  551. Clipboard = new FakeDriver.FakeClipboard ();
  552. }
  553. else
  554. {
  555. if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
  556. {
  557. Clipboard = new MacOSXClipboard ();
  558. }
  559. else
  560. {
  561. if (Is_WSL_Platform ())
  562. {
  563. Clipboard = new WSLClipboard ();
  564. }
  565. else
  566. {
  567. Clipboard = new CursesClipboard ();
  568. }
  569. }
  570. }
  571. ClearContents ();
  572. StartReportingMouseMoves ();
  573. if (!RunningUnitTests)
  574. {
  575. Curses.CheckWinChange ();
  576. // On Init this call is needed no mater Force16Colors or not
  577. Curses.refresh ();
  578. EscSeqUtils.ContinuousButtonPressed += EscSeqUtils_ContinuousButtonPressed;
  579. }
  580. return new (_mainLoopDriver);
  581. }
  582. private readonly AnsiResponseParser _parser = new ();
  583. /// <inheritdoc />
  584. internal override IAnsiResponseParser GetParser () => _parser;
  585. internal void ProcessInput ()
  586. {
  587. int wch;
  588. int code = Curses.get_wch (out wch);
  589. //System.Diagnostics.Debug.WriteLine ($"code: {code}; wch: {wch}");
  590. if (code == Curses.ERR)
  591. {
  592. return;
  593. }
  594. var k = KeyCode.Null;
  595. if (code == Curses.KEY_CODE_YES)
  596. {
  597. while (code == Curses.KEY_CODE_YES && wch == Curses.KeyResize)
  598. {
  599. ProcessWinChange ();
  600. code = Curses.get_wch (out wch);
  601. }
  602. if (wch == 0)
  603. {
  604. return;
  605. }
  606. if (wch == Curses.KeyMouse)
  607. {
  608. int wch2 = wch;
  609. while (wch2 == Curses.KeyMouse)
  610. {
  611. // BUGBUG: Fix this nullable issue.
  612. Key kea = null;
  613. ConsoleKeyInfo [] cki =
  614. {
  615. new ((char)KeyCode.Esc, 0, false, false, false),
  616. new ('[', 0, false, false, false),
  617. new ('<', 0, false, false, false)
  618. };
  619. code = 0;
  620. // BUGBUG: Fix this nullable issue.
  621. HandleEscSeqResponse (ref code, ref k, ref wch2, ref kea, ref cki);
  622. }
  623. return;
  624. }
  625. k = MapCursesKey (wch);
  626. if (wch >= 277 && wch <= 288)
  627. {
  628. // Shift+(F1 - F12)
  629. wch -= 12;
  630. k = KeyCode.ShiftMask | MapCursesKey (wch);
  631. }
  632. else if (wch >= 289 && wch <= 300)
  633. {
  634. // Ctrl+(F1 - F12)
  635. wch -= 24;
  636. k = KeyCode.CtrlMask | MapCursesKey (wch);
  637. }
  638. else if (wch >= 301 && wch <= 312)
  639. {
  640. // Ctrl+Shift+(F1 - F12)
  641. wch -= 36;
  642. k = KeyCode.CtrlMask | KeyCode.ShiftMask | MapCursesKey (wch);
  643. }
  644. else if (wch >= 313 && wch <= 324)
  645. {
  646. // Alt+(F1 - F12)
  647. wch -= 48;
  648. k = KeyCode.AltMask | MapCursesKey (wch);
  649. }
  650. else if (wch >= 325 && wch <= 327)
  651. {
  652. // Shift+Alt+(F1 - F3)
  653. wch -= 60;
  654. k = KeyCode.ShiftMask | KeyCode.AltMask | MapCursesKey (wch);
  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 == Curses.KeyTab)
  746. {
  747. k = MapCursesKey (wch);
  748. OnKeyDown (new Key (k));
  749. OnKeyUp (new Key (k));
  750. }
  751. else if (wch == 127)
  752. {
  753. // Backspace needed for macOS
  754. k = KeyCode.Backspace;
  755. OnKeyDown (new Key (k));
  756. OnKeyUp (new Key (k));
  757. }
  758. else
  759. {
  760. // Unfortunately there are no way to differentiate Ctrl+alfa and Ctrl+Shift+alfa.
  761. k = (KeyCode)wch;
  762. if (wch == 0)
  763. {
  764. k = KeyCode.CtrlMask | KeyCode.Space;
  765. }
  766. else if (wch >= (uint)KeyCode.A - 64 && wch <= (uint)KeyCode.Z - 64)
  767. {
  768. if ((KeyCode)(wch + 64) != KeyCode.J)
  769. {
  770. k = KeyCode.CtrlMask | (KeyCode)(wch + 64);
  771. }
  772. }
  773. else if (wch >= (uint)KeyCode.A && wch <= (uint)KeyCode.Z)
  774. {
  775. k = (KeyCode)wch | KeyCode.ShiftMask;
  776. }
  777. if (wch == '\n' || wch == '\r')
  778. {
  779. k = KeyCode.Enter;
  780. }
  781. // Strip the KeyCode.Space flag off if it's set
  782. //if (k != KeyCode.Space && k.HasFlag (KeyCode.Space))
  783. if (Key.GetIsKeyCodeAtoZ (k) && (k & KeyCode.Space) != 0)
  784. {
  785. k &= ~KeyCode.Space;
  786. }
  787. OnKeyDown (new Key (k));
  788. OnKeyUp (new Key (k));
  789. }
  790. }
  791. internal void ProcessWinChange ()
  792. {
  793. if (!RunningUnitTests && Curses.CheckWinChange ())
  794. {
  795. ClearContents ();
  796. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  797. }
  798. }
  799. private void HandleEscSeqResponse (
  800. ref int code,
  801. ref KeyCode k,
  802. ref int wch2,
  803. ref Key keyEventArgs,
  804. ref ConsoleKeyInfo [] cki
  805. )
  806. {
  807. ConsoleKey ck = 0;
  808. ConsoleModifiers mod = 0;
  809. while (code == 0)
  810. {
  811. code = Curses.get_wch (out wch2);
  812. var consoleKeyInfo = new ConsoleKeyInfo ((char)wch2, 0, false, false, false);
  813. if (wch2 == 0 || wch2 == 27 || wch2 == Curses.KeyMouse)
  814. {
  815. // BUGBUG: Fix this nullable issue.
  816. EscSeqUtils.DecodeEscSeq (
  817. ref consoleKeyInfo,
  818. ref ck,
  819. cki,
  820. ref mod,
  821. out _,
  822. out _,
  823. out _,
  824. out _,
  825. out bool isKeyMouse,
  826. out List<MouseFlags> mouseFlags,
  827. out Point pos,
  828. out _,
  829. EscSeqUtils.ProcessMouseEvent
  830. );
  831. if (isKeyMouse)
  832. {
  833. foreach (MouseFlags mf in mouseFlags)
  834. {
  835. OnMouseEvent (new () { Flags = mf, Position = pos });
  836. }
  837. // BUGBUG: Fix this nullable issue.
  838. cki = null;
  839. if (wch2 == 27)
  840. {
  841. cki = EscSeqUtils.ResizeArray (
  842. new ConsoleKeyInfo (
  843. (char)KeyCode.Esc,
  844. 0,
  845. false,
  846. false,
  847. false
  848. ),
  849. cki
  850. );
  851. }
  852. }
  853. else
  854. {
  855. if (cki != null)
  856. {
  857. foreach (var c in cki)
  858. {
  859. _parser.ProcessInput (c.KeyChar.ToString());
  860. }
  861. }
  862. k = ConsoleKeyMapping.MapConsoleKeyInfoToKeyCode (consoleKeyInfo);
  863. keyEventArgs = new Key (k);
  864. OnKeyDown (keyEventArgs);
  865. }
  866. }
  867. else
  868. {
  869. cki = EscSeqUtils.ResizeArray (consoleKeyInfo, cki);
  870. }
  871. }
  872. }
  873. private void EscSeqUtils_ContinuousButtonPressed (object? sender, MouseEventArgs e)
  874. {
  875. OnMouseEvent (e);
  876. }
  877. private static KeyCode MapCursesKey (int cursesKey)
  878. {
  879. switch (cursesKey)
  880. {
  881. case Curses.KeyF1: return KeyCode.F1;
  882. case Curses.KeyF2: return KeyCode.F2;
  883. case Curses.KeyF3: return KeyCode.F3;
  884. case Curses.KeyF4: return KeyCode.F4;
  885. case Curses.KeyF5: return KeyCode.F5;
  886. case Curses.KeyF6: return KeyCode.F6;
  887. case Curses.KeyF7: return KeyCode.F7;
  888. case Curses.KeyF8: return KeyCode.F8;
  889. case Curses.KeyF9: return KeyCode.F9;
  890. case Curses.KeyF10: return KeyCode.F10;
  891. case Curses.KeyF11: return KeyCode.F11;
  892. case Curses.KeyF12: return KeyCode.F12;
  893. case Curses.KeyUp: return KeyCode.CursorUp;
  894. case Curses.KeyDown: return KeyCode.CursorDown;
  895. case Curses.KeyLeft: return KeyCode.CursorLeft;
  896. case Curses.KeyRight: return KeyCode.CursorRight;
  897. case Curses.KeyHome: return KeyCode.Home;
  898. case Curses.KeyEnd: return KeyCode.End;
  899. case Curses.KeyNPage: return KeyCode.PageDown;
  900. case Curses.KeyPPage: return KeyCode.PageUp;
  901. case Curses.KeyDeleteChar: return KeyCode.Delete;
  902. case Curses.KeyInsertChar: return KeyCode.Insert;
  903. case Curses.KeyTab: return KeyCode.Tab;
  904. case Curses.KeyBackTab: return KeyCode.Tab | KeyCode.ShiftMask;
  905. case Curses.KeyBackspace: return KeyCode.Backspace;
  906. case Curses.ShiftKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask;
  907. case Curses.ShiftKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask;
  908. case Curses.ShiftKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask;
  909. case Curses.ShiftKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask;
  910. case Curses.ShiftKeyHome: return KeyCode.Home | KeyCode.ShiftMask;
  911. case Curses.ShiftKeyEnd: return KeyCode.End | KeyCode.ShiftMask;
  912. case Curses.ShiftKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask;
  913. case Curses.ShiftKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask;
  914. case Curses.AltKeyUp: return KeyCode.CursorUp | KeyCode.AltMask;
  915. case Curses.AltKeyDown: return KeyCode.CursorDown | KeyCode.AltMask;
  916. case Curses.AltKeyLeft: return KeyCode.CursorLeft | KeyCode.AltMask;
  917. case Curses.AltKeyRight: return KeyCode.CursorRight | KeyCode.AltMask;
  918. case Curses.AltKeyHome: return KeyCode.Home | KeyCode.AltMask;
  919. case Curses.AltKeyEnd: return KeyCode.End | KeyCode.AltMask;
  920. case Curses.AltKeyNPage: return KeyCode.PageDown | KeyCode.AltMask;
  921. case Curses.AltKeyPPage: return KeyCode.PageUp | KeyCode.AltMask;
  922. case Curses.CtrlKeyUp: return KeyCode.CursorUp | KeyCode.CtrlMask;
  923. case Curses.CtrlKeyDown: return KeyCode.CursorDown | KeyCode.CtrlMask;
  924. case Curses.CtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.CtrlMask;
  925. case Curses.CtrlKeyRight: return KeyCode.CursorRight | KeyCode.CtrlMask;
  926. case Curses.CtrlKeyHome: return KeyCode.Home | KeyCode.CtrlMask;
  927. case Curses.CtrlKeyEnd: return KeyCode.End | KeyCode.CtrlMask;
  928. case Curses.CtrlKeyNPage: return KeyCode.PageDown | KeyCode.CtrlMask;
  929. case Curses.CtrlKeyPPage: return KeyCode.PageUp | KeyCode.CtrlMask;
  930. case Curses.ShiftCtrlKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.CtrlMask;
  931. case Curses.ShiftCtrlKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.CtrlMask;
  932. case Curses.ShiftCtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.CtrlMask;
  933. case Curses.ShiftCtrlKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.CtrlMask;
  934. case Curses.ShiftCtrlKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.CtrlMask;
  935. case Curses.ShiftCtrlKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.CtrlMask;
  936. case Curses.ShiftCtrlKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.CtrlMask;
  937. case Curses.ShiftCtrlKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.CtrlMask;
  938. case Curses.ShiftAltKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.AltMask;
  939. case Curses.ShiftAltKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.AltMask;
  940. case Curses.ShiftAltKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.AltMask;
  941. case Curses.ShiftAltKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.AltMask;
  942. case Curses.ShiftAltKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.AltMask;
  943. case Curses.ShiftAltKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.AltMask;
  944. case Curses.ShiftAltKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.AltMask;
  945. case Curses.ShiftAltKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.AltMask;
  946. case Curses.AltCtrlKeyNPage: return KeyCode.PageDown | KeyCode.AltMask | KeyCode.CtrlMask;
  947. case Curses.AltCtrlKeyPPage: return KeyCode.PageUp | KeyCode.AltMask | KeyCode.CtrlMask;
  948. case Curses.AltCtrlKeyHome: return KeyCode.Home | KeyCode.AltMask | KeyCode.CtrlMask;
  949. case Curses.AltCtrlKeyEnd: return KeyCode.End | KeyCode.AltMask | KeyCode.CtrlMask;
  950. default: return KeyCode.Null;
  951. }
  952. }
  953. public override void End ()
  954. {
  955. EscSeqUtils.ContinuousButtonPressed -= EscSeqUtils_ContinuousButtonPressed;
  956. StopReportingMouseMoves ();
  957. SetCursorVisibility (CursorVisibility.Default);
  958. if (_mainLoopDriver is { })
  959. {
  960. _mainLoopDriver.RemoveWatch (_processInputToken);
  961. }
  962. if (RunningUnitTests)
  963. {
  964. return;
  965. }
  966. // throws away any typeahead that has been typed by
  967. // the user and has not yet been read by the program.
  968. Curses.flushinp ();
  969. Curses.endwin ();
  970. }
  971. #endregion Init/End/MainLoop
  972. public static bool Is_WSL_Platform ()
  973. {
  974. // xclip does not work on WSL, so we need to use the Windows clipboard vis Powershell
  975. //if (new CursesClipboard ().IsSupported) {
  976. // // If xclip is installed on Linux under WSL, this will return true.
  977. // return false;
  978. //}
  979. (int exitCode, string result) = ClipboardProcessRunner.Bash ("uname -a", waitForOutput: true);
  980. if (exitCode == 0 && result.Contains ("microsoft") && result.Contains ("WSL"))
  981. {
  982. return true;
  983. }
  984. return false;
  985. }
  986. /// <inheritdoc/>
  987. public override void WriteRaw (string ansi) { _mainLoopDriver?.WriteRaw (ansi); }
  988. }
  989. // TODO: One type per file - move to another file
  990. internal static class Platform
  991. {
  992. private static int _suspendSignal;
  993. /// <summary>Suspends the process by sending SIGTSTP to itself</summary>
  994. /// <returns>True if the suspension was successful.</returns>
  995. public static bool Suspend ()
  996. {
  997. int signal = GetSuspendSignal ();
  998. if (signal == -1)
  999. {
  1000. return false;
  1001. }
  1002. killpg (0, signal);
  1003. return true;
  1004. }
  1005. private static int GetSuspendSignal ()
  1006. {
  1007. if (_suspendSignal != 0)
  1008. {
  1009. return _suspendSignal;
  1010. }
  1011. nint buf = Marshal.AllocHGlobal (8192);
  1012. if (uname (buf) != 0)
  1013. {
  1014. Marshal.FreeHGlobal (buf);
  1015. _suspendSignal = -1;
  1016. return _suspendSignal;
  1017. }
  1018. try
  1019. {
  1020. switch (Marshal.PtrToStringAnsi (buf))
  1021. {
  1022. case "Darwin":
  1023. case "DragonFly":
  1024. case "FreeBSD":
  1025. case "NetBSD":
  1026. case "OpenBSD":
  1027. _suspendSignal = 18;
  1028. break;
  1029. case "Linux":
  1030. // TODO: should fetch the machine name and
  1031. // if it is MIPS return 24
  1032. _suspendSignal = 20;
  1033. break;
  1034. case "Solaris":
  1035. _suspendSignal = 24;
  1036. break;
  1037. default:
  1038. _suspendSignal = -1;
  1039. break;
  1040. }
  1041. return _suspendSignal;
  1042. }
  1043. finally
  1044. {
  1045. Marshal.FreeHGlobal (buf);
  1046. }
  1047. }
  1048. [DllImport ("libc")]
  1049. private static extern int killpg (int pgrp, int pid);
  1050. [DllImport ("libc")]
  1051. private static extern int uname (nint buf);
  1052. }