CursesDriver.cs 42 KB

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