CursesDriver.cs 43 KB

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