CursesDriver.cs 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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 void StartReportingMouseMoves ()
  55. {
  56. if (!RunningUnitTests)
  57. {
  58. Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents);
  59. }
  60. }
  61. public void StopReportingMouseMoves ()
  62. {
  63. if (!RunningUnitTests)
  64. {
  65. Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
  66. }
  67. }
  68. public override void Suspend ()
  69. {
  70. StopReportingMouseMoves ();
  71. if (!RunningUnitTests)
  72. {
  73. Platform.Suspend ();
  74. }
  75. StartReportingMouseMoves ();
  76. }
  77. public override void UpdateCursor ()
  78. {
  79. EnsureCursorVisibility ();
  80. if (!RunningUnitTests && Col >= 0 && Col < Cols && Row >= 0 && Row < Rows)
  81. {
  82. _mainLoopDriver?.WriteRaw (EscSeqUtils.CSI_SetCursorPosition (Row + 1, Col + 1));
  83. }
  84. }
  85. public override bool UpdateScreen ()
  86. {
  87. bool updated = false;
  88. if (RunningUnitTests
  89. || Console.WindowHeight < 1
  90. || Contents?.Length != Rows * Cols
  91. || Rows != Console.WindowHeight)
  92. {
  93. return updated;
  94. }
  95. var top = 0;
  96. var left = 0;
  97. int rows = Rows;
  98. int cols = Cols;
  99. var output = new StringBuilder ();
  100. Attribute? redrawAttr = null;
  101. int lastCol = -1;
  102. CursorVisibility? savedVisibility = _currentCursorVisibility;
  103. SetCursorVisibility (CursorVisibility.Invisible);
  104. for (int row = top; row < rows; row++)
  105. {
  106. if (Console.WindowHeight < 1)
  107. {
  108. return updated;
  109. }
  110. if (!_dirtyLines! [row])
  111. {
  112. continue;
  113. }
  114. if (!SetCursorPosition (0, row))
  115. {
  116. return updated;
  117. }
  118. updated = true;
  119. _dirtyLines [row] = false;
  120. output.Clear ();
  121. for (int col = left; col < cols; col++)
  122. {
  123. lastCol = -1;
  124. var outputWidth = 0;
  125. for (; col < cols; col++)
  126. {
  127. if (!Contents [row, col].IsDirty)
  128. {
  129. if (output.Length > 0)
  130. {
  131. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  132. }
  133. else if (lastCol == -1)
  134. {
  135. lastCol = col;
  136. }
  137. if (lastCol + 1 < cols)
  138. {
  139. lastCol++;
  140. }
  141. continue;
  142. }
  143. if (lastCol == -1)
  144. {
  145. lastCol = col;
  146. }
  147. Attribute attr = Contents [row, col].Attribute!.Value;
  148. // Performance: Only send the escape sequence if the attribute has changed.
  149. if (attr != redrawAttr)
  150. {
  151. redrawAttr = attr;
  152. if (Force16Colors)
  153. {
  154. output.Append (EscSeqUtils.CSI_SetForegroundColor (attr.Foreground.GetAnsiColorCode ()));
  155. output.Append (EscSeqUtils.CSI_SetBackgroundColor (attr.Background.GetAnsiColorCode ()));
  156. }
  157. else
  158. {
  159. output.Append (
  160. EscSeqUtils.CSI_SetForegroundColorRGB (
  161. attr.Foreground.R,
  162. attr.Foreground.G,
  163. attr.Foreground.B
  164. )
  165. );
  166. output.Append (
  167. EscSeqUtils.CSI_SetBackgroundColorRGB (
  168. attr.Background.R,
  169. attr.Background.G,
  170. attr.Background.B
  171. )
  172. );
  173. }
  174. }
  175. outputWidth++;
  176. Rune rune = Contents [row, col].Rune;
  177. output.Append (rune);
  178. if (Contents [row, col].CombiningMarks.Count > 0)
  179. {
  180. // AtlasEngine does not support NON-NORMALIZED combining marks in a way
  181. // compatible with the driver architecture. Any CMs (except in the first col)
  182. // are correctly combined with the base char, but are ALSO treated as 1 column
  183. // width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
  184. //
  185. // For now, we just ignore the list of CMs.
  186. //foreach (var combMark in Contents [row, col].CombiningMarks) {
  187. // output.Append (combMark);
  188. //}
  189. // WriteToConsole (output, ref lastCol, row, ref outputWidth);
  190. }
  191. else if (rune.IsSurrogatePair () && rune.GetColumns () < 2)
  192. {
  193. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  194. SetCursorPosition (col - 1, row);
  195. }
  196. Contents [row, col].IsDirty = false;
  197. }
  198. }
  199. if (output.Length > 0)
  200. {
  201. SetCursorPosition (lastCol, row);
  202. Console.Write (output);
  203. }
  204. foreach (var s in Application.Sixel)
  205. {
  206. if (!string.IsNullOrWhiteSpace (s.SixelData))
  207. {
  208. SetCursorPosition (s.ScreenPosition.X, s.ScreenPosition.Y);
  209. Console.Write (s.SixelData);
  210. }
  211. }
  212. }
  213. SetCursorPosition (0, 0);
  214. _currentCursorVisibility = savedVisibility;
  215. void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
  216. {
  217. SetCursorPosition (lastCol, row);
  218. Console.Write (output);
  219. output.Clear ();
  220. lastCol += outputWidth;
  221. outputWidth = 0;
  222. }
  223. return updated;
  224. }
  225. #region Color Handling
  226. public override bool SupportsTrueColor => true;
  227. /// <summary>Creates an Attribute from the provided curses-based foreground and background color numbers</summary>
  228. /// <param name="foreground">Contains the curses color number for the foreground (color, plus any attributes)</param>
  229. /// <param name="background">Contains the curses color number for the background (color, plus any attributes)</param>
  230. /// <returns></returns>
  231. private static Attribute MakeColor (short foreground, short background)
  232. {
  233. //var v = (short)((ushort)foreground | (background << 4));
  234. var v = (short)(((ushort)(foreground & 0xffff) << 16) | (background & 0xffff));
  235. // TODO: for TrueColor - Use InitExtendedPair
  236. Curses.InitColorPair (v, foreground, background);
  237. return new (
  238. Curses.ColorPair (v),
  239. CursesColorNumberToColorName16 (foreground),
  240. CursesColorNumberToColorName16 (background)
  241. );
  242. }
  243. private static short ColorNameToCursesColorNumber (ColorName16 color)
  244. {
  245. switch (color)
  246. {
  247. case ColorName16.Black:
  248. return Curses.COLOR_BLACK;
  249. case ColorName16.Blue:
  250. return Curses.COLOR_BLUE;
  251. case ColorName16.Green:
  252. return Curses.COLOR_GREEN;
  253. case ColorName16.Cyan:
  254. return Curses.COLOR_CYAN;
  255. case ColorName16.Red:
  256. return Curses.COLOR_RED;
  257. case ColorName16.Magenta:
  258. return Curses.COLOR_MAGENTA;
  259. case ColorName16.Yellow:
  260. return Curses.COLOR_YELLOW;
  261. case ColorName16.Gray:
  262. return Curses.COLOR_WHITE;
  263. case ColorName16.DarkGray:
  264. return Curses.COLOR_GRAY;
  265. case ColorName16.BrightBlue:
  266. return Curses.COLOR_BLUE | Curses.COLOR_GRAY;
  267. case ColorName16.BrightGreen:
  268. return Curses.COLOR_GREEN | Curses.COLOR_GRAY;
  269. case ColorName16.BrightCyan:
  270. return Curses.COLOR_CYAN | Curses.COLOR_GRAY;
  271. case ColorName16.BrightRed:
  272. return Curses.COLOR_RED | Curses.COLOR_GRAY;
  273. case ColorName16.BrightMagenta:
  274. return Curses.COLOR_MAGENTA | Curses.COLOR_GRAY;
  275. case ColorName16.BrightYellow:
  276. return Curses.COLOR_YELLOW | Curses.COLOR_GRAY;
  277. case ColorName16.White:
  278. return Curses.COLOR_WHITE | Curses.COLOR_GRAY;
  279. }
  280. throw new ArgumentException ("Invalid color code");
  281. }
  282. private static ColorName16 CursesColorNumberToColorName16 (short color)
  283. {
  284. switch (color)
  285. {
  286. case Curses.COLOR_BLACK:
  287. return ColorName16.Black;
  288. case Curses.COLOR_BLUE:
  289. return ColorName16.Blue;
  290. case Curses.COLOR_GREEN:
  291. return ColorName16.Green;
  292. case Curses.COLOR_CYAN:
  293. return ColorName16.Cyan;
  294. case Curses.COLOR_RED:
  295. return ColorName16.Red;
  296. case Curses.COLOR_MAGENTA:
  297. return ColorName16.Magenta;
  298. case Curses.COLOR_YELLOW:
  299. return ColorName16.Yellow;
  300. case Curses.COLOR_WHITE:
  301. return ColorName16.Gray;
  302. case Curses.COLOR_GRAY:
  303. return ColorName16.DarkGray;
  304. case Curses.COLOR_BLUE | Curses.COLOR_GRAY:
  305. return ColorName16.BrightBlue;
  306. case Curses.COLOR_GREEN | Curses.COLOR_GRAY:
  307. return ColorName16.BrightGreen;
  308. case Curses.COLOR_CYAN | Curses.COLOR_GRAY:
  309. return ColorName16.BrightCyan;
  310. case Curses.COLOR_RED | Curses.COLOR_GRAY:
  311. return ColorName16.BrightRed;
  312. case Curses.COLOR_MAGENTA | Curses.COLOR_GRAY:
  313. return ColorName16.BrightMagenta;
  314. case Curses.COLOR_YELLOW | Curses.COLOR_GRAY:
  315. return ColorName16.BrightYellow;
  316. case Curses.COLOR_WHITE | Curses.COLOR_GRAY:
  317. return ColorName16.White;
  318. }
  319. throw new ArgumentException ("Invalid curses color code");
  320. }
  321. #endregion
  322. private CursorVisibility? _currentCursorVisibility;
  323. private CursorVisibility? _initialCursorVisibility;
  324. private void EnsureCursorVisibility ()
  325. {
  326. if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows))
  327. {
  328. GetCursorVisibility (out CursorVisibility cursorVisibility);
  329. _currentCursorVisibility = cursorVisibility;
  330. SetCursorVisibility (CursorVisibility.Invisible);
  331. return;
  332. }
  333. SetCursorVisibility (_currentCursorVisibility ?? CursorVisibility.Default);
  334. }
  335. /// <inheritdoc/>
  336. public override bool GetCursorVisibility (out CursorVisibility visibility)
  337. {
  338. visibility = CursorVisibility.Invisible;
  339. if (!_currentCursorVisibility.HasValue)
  340. {
  341. return false;
  342. }
  343. visibility = _currentCursorVisibility.Value;
  344. return true;
  345. }
  346. private EscSeqUtils.DECSCUSR_Style? _currentDecscusrStyle;
  347. /// <inheritdoc/>
  348. public override bool SetCursorVisibility (CursorVisibility visibility)
  349. {
  350. if (_initialCursorVisibility.HasValue == false)
  351. {
  352. return false;
  353. }
  354. if (!RunningUnitTests)
  355. {
  356. Curses.curs_set (((int)visibility >> 16) & 0x000000FF);
  357. Curses.leaveok (_window!.Handle, !Force16Colors);
  358. }
  359. if (visibility != CursorVisibility.Invisible)
  360. {
  361. if (_currentDecscusrStyle is null || _currentDecscusrStyle != (EscSeqUtils.DECSCUSR_Style)(((int)visibility >> 24) & 0xFF))
  362. {
  363. _currentDecscusrStyle = (EscSeqUtils.DECSCUSR_Style)(((int)visibility >> 24) & 0xFF);
  364. _mainLoopDriver?.WriteRaw (
  365. EscSeqUtils.CSI_SetCursorStyle ((EscSeqUtils.DECSCUSR_Style)_currentDecscusrStyle)
  366. );
  367. }
  368. }
  369. _currentCursorVisibility = visibility;
  370. return true;
  371. }
  372. private bool SetCursorPosition (int col, int row)
  373. {
  374. // + 1 is needed because non-Windows is based on 1 instead of 0 and
  375. // Console.CursorTop/CursorLeft isn't reliable.
  376. Console.Out.Write (EscSeqUtils.CSI_SetCursorPosition (row + 1, col + 1));
  377. return true;
  378. }
  379. #region Init/End/MainLoop
  380. private Curses.Window? _window;
  381. private UnixMainLoop? _mainLoopDriver;
  382. private object? _processInputToken;
  383. public override MainLoop Init ()
  384. {
  385. _mainLoopDriver = new (this);
  386. if (!RunningUnitTests)
  387. {
  388. _window = Curses.initscr ();
  389. Curses.set_escdelay (10);
  390. // Ensures that all procedures are performed at some previous closing.
  391. Curses.doupdate ();
  392. //
  393. // We are setting Invisible as default, so we could ignore XTerm DECSUSR setting
  394. //
  395. switch (Curses.curs_set (0))
  396. {
  397. case 0:
  398. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Invisible;
  399. break;
  400. case 1:
  401. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Underline;
  402. Curses.curs_set (1);
  403. break;
  404. case 2:
  405. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Box;
  406. Curses.curs_set (2);
  407. break;
  408. default:
  409. _currentCursorVisibility = _initialCursorVisibility = null;
  410. break;
  411. }
  412. if (!Curses.HasColors)
  413. {
  414. throw new InvalidOperationException ("V2 - This should never happen. File an Issue if it does.");
  415. }
  416. Curses.raw ();
  417. Curses.noecho ();
  418. Curses.Window.Standard.keypad (true);
  419. Curses.StartColor ();
  420. Curses.UseDefaultColors ();
  421. if (!RunningUnitTests)
  422. {
  423. Curses.timeout (0);
  424. }
  425. _processInputToken = _mainLoopDriver.AddWatch (
  426. 0,
  427. UnixMainLoop.Condition.PollIn,
  428. x =>
  429. {
  430. ProcessInput ();
  431. return true;
  432. }
  433. );
  434. }
  435. CurrentAttribute = new (ColorName16.White, ColorName16.Black);
  436. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  437. {
  438. Clipboard = new FakeDriver.FakeClipboard ();
  439. }
  440. else
  441. {
  442. if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
  443. {
  444. Clipboard = new MacOSXClipboard ();
  445. }
  446. else
  447. {
  448. if (Is_WSL_Platform ())
  449. {
  450. Clipboard = new WSLClipboard ();
  451. }
  452. else
  453. {
  454. Clipboard = new CursesClipboard ();
  455. }
  456. }
  457. }
  458. ClearContents ();
  459. StartReportingMouseMoves ();
  460. if (!RunningUnitTests)
  461. {
  462. Curses.CheckWinChange ();
  463. // On Init this call is needed no mater Force16Colors or not
  464. Curses.refresh ();
  465. EscSeqUtils.ContinuousButtonPressed += EscSeqUtils_ContinuousButtonPressed;
  466. }
  467. return new (_mainLoopDriver);
  468. }
  469. private readonly AnsiResponseParser _parser = new ();
  470. /// <inheritdoc />
  471. internal override IAnsiResponseParser GetParser () => _parser;
  472. internal void ProcessInput ()
  473. {
  474. int wch;
  475. int code = Curses.get_wch (out wch);
  476. //System.Diagnostics.Debug.WriteLine ($"code: {code}; wch: {wch}");
  477. if (code == Curses.ERR)
  478. {
  479. return;
  480. }
  481. var k = KeyCode.Null;
  482. if (code == Curses.KEY_CODE_YES)
  483. {
  484. while (code == Curses.KEY_CODE_YES && wch == Curses.KeyResize)
  485. {
  486. ProcessWinChange ();
  487. code = Curses.get_wch (out wch);
  488. }
  489. if (wch == 0)
  490. {
  491. return;
  492. }
  493. if (wch == Curses.KeyMouse)
  494. {
  495. int wch2 = wch;
  496. while (wch2 == Curses.KeyMouse)
  497. {
  498. Key? kea = null;
  499. ConsoleKeyInfo [] cki =
  500. {
  501. new ((char)KeyCode.Esc, 0, false, false, false),
  502. new ('[', 0, false, false, false),
  503. new ('<', 0, false, false, false)
  504. };
  505. code = 0;
  506. HandleEscSeqResponse (ref code, ref k, ref wch2, ref kea!, ref cki!);
  507. }
  508. return;
  509. }
  510. k = MapCursesKey (wch);
  511. if (wch >= 277 && wch <= 288)
  512. {
  513. // Shift+(F1 - F12)
  514. wch -= 12;
  515. k = KeyCode.ShiftMask | MapCursesKey (wch);
  516. }
  517. else if (wch >= 289 && wch <= 300)
  518. {
  519. // Ctrl+(F1 - F12)
  520. wch -= 24;
  521. k = KeyCode.CtrlMask | MapCursesKey (wch);
  522. }
  523. else if (wch >= 301 && wch <= 312)
  524. {
  525. // Ctrl+Shift+(F1 - F12)
  526. wch -= 36;
  527. k = KeyCode.CtrlMask | KeyCode.ShiftMask | MapCursesKey (wch);
  528. }
  529. else if (wch >= 313 && wch <= 324)
  530. {
  531. // Alt+(F1 - F12)
  532. wch -= 48;
  533. k = KeyCode.AltMask | MapCursesKey (wch);
  534. }
  535. else if (wch >= 325 && wch <= 327)
  536. {
  537. // Shift+Alt+(F1 - F3)
  538. wch -= 60;
  539. k = KeyCode.ShiftMask | KeyCode.AltMask | MapCursesKey (wch);
  540. }
  541. else if (wch == 520) // Ctrl+Delete
  542. {
  543. k = KeyCode.CtrlMask | KeyCode.Delete;
  544. }
  545. OnKeyDown (new Key (k));
  546. OnKeyUp (new Key (k));
  547. return;
  548. }
  549. // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
  550. if (wch == 27)
  551. {
  552. Curses.timeout (10);
  553. code = Curses.get_wch (out int wch2);
  554. if (code == Curses.KEY_CODE_YES)
  555. {
  556. k = KeyCode.AltMask | MapCursesKey (wch);
  557. }
  558. Key? key = null;
  559. if (code == 0)
  560. {
  561. // The ESC-number handling, debatable.
  562. // Simulates the AltMask itself by pressing Alt + Space.
  563. // Needed for macOS
  564. if (wch2 == (int)KeyCode.Space)
  565. {
  566. k = KeyCode.AltMask | KeyCode.Space;
  567. }
  568. else if (wch2 - (int)KeyCode.Space >= (uint)KeyCode.A
  569. && wch2 - (int)KeyCode.Space <= (uint)KeyCode.Z)
  570. {
  571. k = (KeyCode)((uint)KeyCode.AltMask + (wch2 - (int)KeyCode.Space));
  572. }
  573. else if (wch2 >= (uint)KeyCode.A - 64 && wch2 <= (uint)KeyCode.Z - 64)
  574. {
  575. k = (KeyCode)((uint)(KeyCode.AltMask | KeyCode.CtrlMask) + (wch2 + 64));
  576. }
  577. else if (wch2 >= (uint)KeyCode.D0 && wch2 <= (uint)KeyCode.D9)
  578. {
  579. k = (KeyCode)((uint)KeyCode.AltMask + (uint)KeyCode.D0 + (wch2 - (uint)KeyCode.D0));
  580. }
  581. else
  582. {
  583. ConsoleKeyInfo [] cki =
  584. [
  585. new ((char)KeyCode.Esc, 0, false, false, false), new ((char)wch2, 0, false, false, false)
  586. ];
  587. HandleEscSeqResponse (ref code, ref k, ref wch2, ref key!, ref cki!);
  588. return;
  589. }
  590. //else if (wch2 == Curses.KeyCSI)
  591. //{
  592. // ConsoleKeyInfo [] cki =
  593. // {
  594. // new ((char)KeyCode.Esc, 0, false, false, false), new ('[', 0, false, false, false)
  595. // };
  596. // HandleEscSeqResponse (ref code, ref k, ref wch2, ref key, ref cki);
  597. // return;
  598. //}
  599. //else
  600. //{
  601. // // Unfortunately there are no way to differentiate Ctrl+Alt+alfa and Ctrl+Shift+Alt+alfa.
  602. // if (((KeyCode)wch2 & KeyCode.CtrlMask) != 0)
  603. // {
  604. // k = (KeyCode)((uint)KeyCode.CtrlMask + (wch2 & ~(int)KeyCode.CtrlMask));
  605. // }
  606. // if (wch2 == 0)
  607. // {
  608. // k = KeyCode.CtrlMask | KeyCode.AltMask | KeyCode.Space;
  609. // }
  610. // //else if (wch >= (uint)KeyCode.A && wch <= (uint)KeyCode.Z)
  611. // //{
  612. // // k = KeyCode.ShiftMask | KeyCode.AltMask | KeyCode.Space;
  613. // //}
  614. // else if (wch2 < 256)
  615. // {
  616. // k = (KeyCode)wch2; // | KeyCode.AltMask;
  617. // }
  618. // else
  619. // {
  620. // k = (KeyCode)((uint)(KeyCode.AltMask | KeyCode.CtrlMask) + wch2);
  621. // }
  622. //}
  623. key = new Key (k);
  624. }
  625. else
  626. {
  627. key = Key.Esc;
  628. }
  629. OnKeyDown (key);
  630. OnKeyUp (key);
  631. }
  632. else if (wch == 8) // Ctrl+Backspace
  633. {
  634. k = KeyCode.Backspace | KeyCode.CtrlMask;
  635. OnKeyDown (new Key (k));
  636. OnKeyUp (new Key (k));
  637. }
  638. else if (wch == Curses.KeyTab)
  639. {
  640. k = MapCursesKey (wch);
  641. OnKeyDown (new Key (k));
  642. OnKeyUp (new Key (k));
  643. }
  644. else if (wch == 127)
  645. {
  646. // Backspace needed for macOS
  647. k = KeyCode.Backspace;
  648. OnKeyDown (new Key (k));
  649. OnKeyUp (new Key (k));
  650. }
  651. else
  652. {
  653. // Unfortunately there are no way to differentiate Ctrl+alfa and Ctrl+Shift+alfa.
  654. k = (KeyCode)wch;
  655. if (wch == 0)
  656. {
  657. k = KeyCode.CtrlMask | KeyCode.Space;
  658. }
  659. else if (wch >= (uint)KeyCode.A - 64 && wch <= (uint)KeyCode.Z - 64)
  660. {
  661. if ((KeyCode)(wch + 64) != KeyCode.J)
  662. {
  663. k = KeyCode.CtrlMask | (KeyCode)(wch + 64);
  664. }
  665. }
  666. else if (wch >= (uint)KeyCode.A && wch <= (uint)KeyCode.Z)
  667. {
  668. k = (KeyCode)wch | KeyCode.ShiftMask;
  669. }
  670. if (wch == '\n' || wch == '\r')
  671. {
  672. k = KeyCode.Enter;
  673. }
  674. // Strip the KeyCode.Space flag off if it's set
  675. //if (k != KeyCode.Space && k.HasFlag (KeyCode.Space))
  676. if (Key.GetIsKeyCodeAtoZ (k) && (k & KeyCode.Space) != 0)
  677. {
  678. k &= ~KeyCode.Space;
  679. }
  680. if (IsValidInput (k, out k))
  681. {
  682. OnKeyDown (new (k));
  683. OnKeyUp (new (k));
  684. }
  685. }
  686. }
  687. internal void ProcessWinChange ()
  688. {
  689. if (!RunningUnitTests && Curses.CheckWinChange ())
  690. {
  691. ClearContents ();
  692. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  693. }
  694. }
  695. static string ConvertToString (ConsoleKeyInfo [] keyInfos)
  696. {
  697. char [] chars = new char [keyInfos.Length];
  698. for (int i = 0; i < keyInfos.Length; i++)
  699. {
  700. chars [i] = keyInfos [i].KeyChar;
  701. }
  702. return new string (chars);
  703. }
  704. private void HandleEscSeqResponse (
  705. ref int code,
  706. ref KeyCode k,
  707. ref int wch2,
  708. ref Key keyEventArgs,
  709. ref ConsoleKeyInfo []? cki
  710. )
  711. {
  712. ConsoleKey ck = 0;
  713. ConsoleModifiers mod = 0;
  714. while (code == 0)
  715. {
  716. code = Curses.get_wch (out wch2);
  717. var consoleKeyInfo = new ConsoleKeyInfo ((char)wch2, 0, false, false, false);
  718. if (wch2 == 0 || wch2 == 27 || wch2 == Curses.KeyMouse)
  719. {
  720. // Give ansi parser a chance to deal with the escape sequence
  721. if (cki != null && string.IsNullOrEmpty(_parser.ProcessInput (ConvertToString(cki))))
  722. {
  723. // Parser fully consumed all keys meaning keys are processed - job done
  724. return;
  725. }
  726. // Ansi parser could not deal with it either because it is not expecting
  727. // the given terminator (e.g. mouse) or did not understand format somehow.
  728. // Carry on with the older code for processing curses escape codes
  729. EscSeqUtils.DecodeEscSeq (
  730. ref consoleKeyInfo,
  731. ref ck,
  732. cki!,
  733. ref mod,
  734. out _,
  735. out _,
  736. out _,
  737. out _,
  738. out bool isKeyMouse,
  739. out List<MouseFlags> mouseFlags,
  740. out Point pos,
  741. out _,
  742. EscSeqUtils.ProcessMouseEvent
  743. );
  744. if (isKeyMouse)
  745. {
  746. foreach (MouseFlags mf in mouseFlags)
  747. {
  748. OnMouseEvent (new () { Flags = mf, Position = pos });
  749. }
  750. cki = null;
  751. if (wch2 == 27)
  752. {
  753. cki = EscSeqUtils.ResizeArray (
  754. new ConsoleKeyInfo (
  755. (char)KeyCode.Esc,
  756. 0,
  757. false,
  758. false,
  759. false
  760. ),
  761. cki
  762. );
  763. }
  764. }
  765. else
  766. {
  767. k = ConsoleKeyMapping.MapConsoleKeyInfoToKeyCode (consoleKeyInfo);
  768. keyEventArgs = new Key (k);
  769. OnKeyDown (keyEventArgs);
  770. }
  771. }
  772. else
  773. {
  774. cki = EscSeqUtils.ResizeArray (consoleKeyInfo, cki);
  775. }
  776. }
  777. }
  778. private void EscSeqUtils_ContinuousButtonPressed (object? sender, MouseEventArgs e)
  779. {
  780. OnMouseEvent (e);
  781. }
  782. private static KeyCode MapCursesKey (int cursesKey)
  783. {
  784. switch (cursesKey)
  785. {
  786. case Curses.KeyF1: return KeyCode.F1;
  787. case Curses.KeyF2: return KeyCode.F2;
  788. case Curses.KeyF3: return KeyCode.F3;
  789. case Curses.KeyF4: return KeyCode.F4;
  790. case Curses.KeyF5: return KeyCode.F5;
  791. case Curses.KeyF6: return KeyCode.F6;
  792. case Curses.KeyF7: return KeyCode.F7;
  793. case Curses.KeyF8: return KeyCode.F8;
  794. case Curses.KeyF9: return KeyCode.F9;
  795. case Curses.KeyF10: return KeyCode.F10;
  796. case Curses.KeyF11: return KeyCode.F11;
  797. case Curses.KeyF12: return KeyCode.F12;
  798. case Curses.KeyUp: return KeyCode.CursorUp;
  799. case Curses.KeyDown: return KeyCode.CursorDown;
  800. case Curses.KeyLeft: return KeyCode.CursorLeft;
  801. case Curses.KeyRight: return KeyCode.CursorRight;
  802. case Curses.KeyHome: return KeyCode.Home;
  803. case Curses.KeyEnd: return KeyCode.End;
  804. case Curses.KeyNPage: return KeyCode.PageDown;
  805. case Curses.KeyPPage: return KeyCode.PageUp;
  806. case Curses.KeyDeleteChar: return KeyCode.Delete;
  807. case Curses.KeyInsertChar: return KeyCode.Insert;
  808. case Curses.KeyTab: return KeyCode.Tab;
  809. case Curses.KeyBackTab: return KeyCode.Tab | KeyCode.ShiftMask;
  810. case Curses.KeyBackspace: return KeyCode.Backspace;
  811. case Curses.ShiftKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask;
  812. case Curses.ShiftKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask;
  813. case Curses.ShiftKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask;
  814. case Curses.ShiftKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask;
  815. case Curses.ShiftKeyHome: return KeyCode.Home | KeyCode.ShiftMask;
  816. case Curses.ShiftKeyEnd: return KeyCode.End | KeyCode.ShiftMask;
  817. case Curses.ShiftKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask;
  818. case Curses.ShiftKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask;
  819. case Curses.AltKeyUp: return KeyCode.CursorUp | KeyCode.AltMask;
  820. case Curses.AltKeyDown: return KeyCode.CursorDown | KeyCode.AltMask;
  821. case Curses.AltKeyLeft: return KeyCode.CursorLeft | KeyCode.AltMask;
  822. case Curses.AltKeyRight: return KeyCode.CursorRight | KeyCode.AltMask;
  823. case Curses.AltKeyHome: return KeyCode.Home | KeyCode.AltMask;
  824. case Curses.AltKeyEnd: return KeyCode.End | KeyCode.AltMask;
  825. case Curses.AltKeyNPage: return KeyCode.PageDown | KeyCode.AltMask;
  826. case Curses.AltKeyPPage: return KeyCode.PageUp | KeyCode.AltMask;
  827. case Curses.CtrlKeyUp: return KeyCode.CursorUp | KeyCode.CtrlMask;
  828. case Curses.CtrlKeyDown: return KeyCode.CursorDown | KeyCode.CtrlMask;
  829. case Curses.CtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.CtrlMask;
  830. case Curses.CtrlKeyRight: return KeyCode.CursorRight | KeyCode.CtrlMask;
  831. case Curses.CtrlKeyHome: return KeyCode.Home | KeyCode.CtrlMask;
  832. case Curses.CtrlKeyEnd: return KeyCode.End | KeyCode.CtrlMask;
  833. case Curses.CtrlKeyNPage: return KeyCode.PageDown | KeyCode.CtrlMask;
  834. case Curses.CtrlKeyPPage: return KeyCode.PageUp | KeyCode.CtrlMask;
  835. case Curses.ShiftCtrlKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.CtrlMask;
  836. case Curses.ShiftCtrlKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.CtrlMask;
  837. case Curses.ShiftCtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.CtrlMask;
  838. case Curses.ShiftCtrlKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.CtrlMask;
  839. case Curses.ShiftCtrlKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.CtrlMask;
  840. case Curses.ShiftCtrlKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.CtrlMask;
  841. case Curses.ShiftCtrlKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.CtrlMask;
  842. case Curses.ShiftCtrlKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.CtrlMask;
  843. case Curses.ShiftAltKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.AltMask;
  844. case Curses.ShiftAltKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.AltMask;
  845. case Curses.ShiftAltKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.AltMask;
  846. case Curses.ShiftAltKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.AltMask;
  847. case Curses.ShiftAltKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.AltMask;
  848. case Curses.ShiftAltKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.AltMask;
  849. case Curses.ShiftAltKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.AltMask;
  850. case Curses.ShiftAltKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.AltMask;
  851. case Curses.AltCtrlKeyNPage: return KeyCode.PageDown | KeyCode.AltMask | KeyCode.CtrlMask;
  852. case Curses.AltCtrlKeyPPage: return KeyCode.PageUp | KeyCode.AltMask | KeyCode.CtrlMask;
  853. case Curses.AltCtrlKeyHome: return KeyCode.Home | KeyCode.AltMask | KeyCode.CtrlMask;
  854. case Curses.AltCtrlKeyEnd: return KeyCode.End | KeyCode.AltMask | KeyCode.CtrlMask;
  855. default: return KeyCode.Null;
  856. }
  857. }
  858. public override void End ()
  859. {
  860. EscSeqUtils.ContinuousButtonPressed -= EscSeqUtils_ContinuousButtonPressed;
  861. StopReportingMouseMoves ();
  862. SetCursorVisibility (CursorVisibility.Default);
  863. if (_mainLoopDriver is { } && _processInputToken != null)
  864. {
  865. _mainLoopDriver.RemoveWatch (_processInputToken);
  866. }
  867. if (RunningUnitTests)
  868. {
  869. return;
  870. }
  871. // throws away any typeahead that has been typed by
  872. // the user and has not yet been read by the program.
  873. Curses.flushinp ();
  874. Curses.endwin ();
  875. }
  876. #endregion Init/End/MainLoop
  877. public static bool Is_WSL_Platform ()
  878. {
  879. // xclip does not work on WSL, so we need to use the Windows clipboard vis Powershell
  880. //if (new CursesClipboard ().IsSupported) {
  881. // // If xclip is installed on Linux under WSL, this will return true.
  882. // return false;
  883. //}
  884. (int exitCode, string result) = ClipboardProcessRunner.Bash ("uname -a", waitForOutput: true);
  885. if (exitCode == 0 && result.Contains ("microsoft") && result.Contains ("WSL"))
  886. {
  887. return true;
  888. }
  889. return false;
  890. }
  891. /// <inheritdoc/>
  892. public override void WriteRaw (string ansi) { _mainLoopDriver?.WriteRaw (ansi); }
  893. }