CursesDriver.cs 43 KB

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