CursesDriver.cs 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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 => false;
  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. public override void Suspend ()
  161. {
  162. StopReportingMouseMoves ();
  163. if (!RunningUnitTests)
  164. {
  165. Platform.Suspend ();
  166. Curses.Window.Standard.redrawwin ();
  167. Curses.refresh ();
  168. }
  169. StartReportingMouseMoves ();
  170. }
  171. public override void UpdateCursor ()
  172. {
  173. EnsureCursorVisibility ();
  174. if (!RunningUnitTests && Col >= 0 && Col < Cols && Row >= 0 && Row < Rows)
  175. {
  176. Curses.move (Row, Col);
  177. }
  178. }
  179. public override void UpdateScreen ()
  180. {
  181. for (var row = 0; row < Rows; row++)
  182. {
  183. if (!_dirtyLines [row])
  184. {
  185. continue;
  186. }
  187. _dirtyLines [row] = false;
  188. for (var col = 0; col < Cols; col++)
  189. {
  190. if (Contents [row, col].IsDirty == false)
  191. {
  192. continue;
  193. }
  194. if (RunningUnitTests)
  195. {
  196. // In unit tests, we don't want to actually write to the screen.
  197. continue;
  198. }
  199. Curses.attrset (Contents [row, col].Attribute.GetValueOrDefault ().PlatformColor);
  200. Rune rune = Contents [row, col].Rune;
  201. if (rune.IsBmp)
  202. {
  203. // 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.
  204. if (rune.GetColumns () < 2)
  205. {
  206. Curses.mvaddch (row, col, rune.Value);
  207. }
  208. else /*if (col + 1 < Cols)*/
  209. {
  210. Curses.mvaddwstr (row, col, rune.ToString ());
  211. }
  212. }
  213. else
  214. {
  215. Curses.mvaddwstr (row, col, rune.ToString ());
  216. if (rune.GetColumns () > 1 && col + 1 < Cols)
  217. {
  218. // TODO: This is a hack to deal with non-BMP and wide characters.
  219. //col++;
  220. Curses.mvaddch (row, ++col, '*');
  221. }
  222. }
  223. }
  224. }
  225. if (!RunningUnitTests)
  226. {
  227. Curses.move (Row, Col);
  228. _window.wrefresh ();
  229. }
  230. }
  231. internal override void End ()
  232. {
  233. StopReportingMouseMoves ();
  234. SetCursorVisibility (CursorVisibility.Default);
  235. if (_mainLoopDriver is { })
  236. {
  237. _mainLoopDriver.RemoveWatch (_processInputToken);
  238. }
  239. if (RunningUnitTests)
  240. {
  241. return;
  242. }
  243. // throws away any typeahead that has been typed by
  244. // the user and has not yet been read by the program.
  245. Curses.flushinp ();
  246. Curses.endwin ();
  247. }
  248. internal override MainLoop Init ()
  249. {
  250. _mainLoopDriver = new UnixMainLoop (this);
  251. if (!RunningUnitTests)
  252. {
  253. _window = Curses.initscr ();
  254. Curses.set_escdelay (10);
  255. // Ensures that all procedures are performed at some previous closing.
  256. Curses.doupdate ();
  257. //
  258. // We are setting Invisible as default so we could ignore XTerm DECSUSR setting
  259. //
  260. switch (Curses.curs_set (0))
  261. {
  262. case 0:
  263. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Invisible;
  264. break;
  265. case 1:
  266. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Underline;
  267. Curses.curs_set (1);
  268. break;
  269. case 2:
  270. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Box;
  271. Curses.curs_set (2);
  272. break;
  273. default:
  274. _currentCursorVisibility = _initialCursorVisibility = null;
  275. break;
  276. }
  277. if (!Curses.HasColors)
  278. {
  279. throw new InvalidOperationException ("V2 - This should never happen. File an Issue if it does.");
  280. }
  281. Curses.raw ();
  282. Curses.noecho ();
  283. Curses.Window.Standard.keypad (true);
  284. Curses.StartColor ();
  285. Curses.UseDefaultColors ();
  286. if (!RunningUnitTests)
  287. {
  288. Curses.timeout (0);
  289. }
  290. _processInputToken = _mainLoopDriver?.AddWatch (
  291. 0,
  292. UnixMainLoop.Condition.PollIn,
  293. x =>
  294. {
  295. ProcessInput ();
  296. return true;
  297. }
  298. );
  299. }
  300. CurrentAttribute = new Attribute (ColorName.White, ColorName.Black);
  301. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  302. {
  303. Clipboard = new FakeDriver.FakeClipboard ();
  304. }
  305. else
  306. {
  307. if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
  308. {
  309. Clipboard = new MacOSXClipboard ();
  310. }
  311. else
  312. {
  313. if (Is_WSL_Platform ())
  314. {
  315. Clipboard = new WSLClipboard ();
  316. }
  317. else
  318. {
  319. Clipboard = new CursesClipboard ();
  320. }
  321. }
  322. }
  323. ClearContents ();
  324. StartReportingMouseMoves ();
  325. if (!RunningUnitTests)
  326. {
  327. Curses.CheckWinChange ();
  328. Curses.refresh ();
  329. }
  330. return new MainLoop (_mainLoopDriver);
  331. }
  332. internal void ProcessInput ()
  333. {
  334. int wch;
  335. int code = Curses.get_wch (out wch);
  336. //System.Diagnostics.Debug.WriteLine ($"code: {code}; wch: {wch}");
  337. if (code == Curses.ERR)
  338. {
  339. return;
  340. }
  341. var k = KeyCode.Null;
  342. if (code == Curses.KEY_CODE_YES)
  343. {
  344. while (code == Curses.KEY_CODE_YES && wch == Curses.KeyResize)
  345. {
  346. ProcessWinChange ();
  347. code = Curses.get_wch (out wch);
  348. }
  349. if (wch == 0)
  350. {
  351. return;
  352. }
  353. if (wch == Curses.KeyMouse)
  354. {
  355. int wch2 = wch;
  356. while (wch2 == Curses.KeyMouse)
  357. {
  358. Key kea = null;
  359. ConsoleKeyInfo [] cki =
  360. {
  361. new ((char)KeyCode.Esc, 0, false, false, false),
  362. new ('[', 0, false, false, false),
  363. new ('<', 0, false, false, false)
  364. };
  365. code = 0;
  366. HandleEscSeqResponse (ref code, ref k, ref wch2, ref kea, ref cki);
  367. }
  368. return;
  369. }
  370. k = MapCursesKey (wch);
  371. if (wch >= 277 && wch <= 288)
  372. {
  373. // Shift+(F1 - F12)
  374. wch -= 12;
  375. k = KeyCode.ShiftMask | MapCursesKey (wch);
  376. }
  377. else if (wch >= 289 && wch <= 300)
  378. {
  379. // Ctrl+(F1 - F12)
  380. wch -= 24;
  381. k = KeyCode.CtrlMask | MapCursesKey (wch);
  382. }
  383. else if (wch >= 301 && wch <= 312)
  384. {
  385. // Ctrl+Shift+(F1 - F12)
  386. wch -= 36;
  387. k = KeyCode.CtrlMask | KeyCode.ShiftMask | MapCursesKey (wch);
  388. }
  389. else if (wch >= 313 && wch <= 324)
  390. {
  391. // Alt+(F1 - F12)
  392. wch -= 48;
  393. k = KeyCode.AltMask | MapCursesKey (wch);
  394. }
  395. else if (wch >= 325 && wch <= 327)
  396. {
  397. // Shift+Alt+(F1 - F3)
  398. wch -= 60;
  399. k = KeyCode.ShiftMask | KeyCode.AltMask | MapCursesKey (wch);
  400. }
  401. OnKeyDown (new Key (k));
  402. OnKeyUp (new Key (k));
  403. return;
  404. }
  405. // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
  406. if (wch == 27)
  407. {
  408. Curses.timeout (10);
  409. code = Curses.get_wch (out int wch2);
  410. if (code == Curses.KEY_CODE_YES)
  411. {
  412. k = KeyCode.AltMask | MapCursesKey (wch);
  413. }
  414. Key key = null;
  415. if (code == 0)
  416. {
  417. // The ESC-number handling, debatable.
  418. // Simulates the AltMask itself by pressing Alt + Space.
  419. if (wch2 == (int)KeyCode.Space)
  420. {
  421. k = KeyCode.AltMask;
  422. }
  423. else if (wch2 - (int)KeyCode.Space >= (uint)KeyCode.A
  424. && wch2 - (int)KeyCode.Space <= (uint)KeyCode.Z)
  425. {
  426. k = (KeyCode)((uint)KeyCode.AltMask + (wch2 - (int)KeyCode.Space));
  427. }
  428. else if (wch2 >= (uint)KeyCode.A - 64 && wch2 <= (uint)KeyCode.Z - 64)
  429. {
  430. k = (KeyCode)((uint)(KeyCode.AltMask | KeyCode.CtrlMask) + (wch2 + 64));
  431. }
  432. else if (wch2 >= (uint)KeyCode.D0 && wch2 <= (uint)KeyCode.D9)
  433. {
  434. k = (KeyCode)((uint)KeyCode.AltMask + (uint)KeyCode.D0 + (wch2 - (uint)KeyCode.D0));
  435. }
  436. else if (wch2 == Curses.KeyCSI)
  437. {
  438. ConsoleKeyInfo [] cki =
  439. {
  440. new ((char)KeyCode.Esc, 0, false, false, false), new ('[', 0, false, false, false)
  441. };
  442. HandleEscSeqResponse (ref code, ref k, ref wch2, ref key, ref cki);
  443. return;
  444. }
  445. else
  446. {
  447. // Unfortunately there are no way to differentiate Ctrl+Alt+alfa and Ctrl+Shift+Alt+alfa.
  448. if (((KeyCode)wch2 & KeyCode.CtrlMask) != 0)
  449. {
  450. k = (KeyCode)((uint)KeyCode.CtrlMask + (wch2 & ~(int)KeyCode.CtrlMask));
  451. }
  452. if (wch2 == 0)
  453. {
  454. k = KeyCode.CtrlMask | KeyCode.AltMask | KeyCode.Space;
  455. }
  456. else if (wch >= (uint)KeyCode.A && wch <= (uint)KeyCode.Z)
  457. {
  458. k = KeyCode.ShiftMask | KeyCode.AltMask | KeyCode.Space;
  459. }
  460. else if (wch2 < 256)
  461. {
  462. k = (KeyCode)wch2; // | KeyCode.AltMask;
  463. }
  464. else
  465. {
  466. k = (KeyCode)((uint)(KeyCode.AltMask | KeyCode.CtrlMask) + wch2);
  467. }
  468. }
  469. key = new Key (k);
  470. }
  471. else
  472. {
  473. key = Key.Esc;
  474. }
  475. OnKeyDown (key);
  476. OnKeyUp (key);
  477. }
  478. else if (wch == Curses.KeyTab)
  479. {
  480. k = MapCursesKey (wch);
  481. OnKeyDown (new Key (k));
  482. OnKeyUp (new Key (k));
  483. }
  484. else
  485. {
  486. // Unfortunately there are no way to differentiate Ctrl+alfa and Ctrl+Shift+alfa.
  487. k = (KeyCode)wch;
  488. if (wch == 0)
  489. {
  490. k = KeyCode.CtrlMask | KeyCode.Space;
  491. }
  492. else if (wch >= (uint)KeyCode.A - 64 && wch <= (uint)KeyCode.Z - 64)
  493. {
  494. if ((KeyCode)(wch + 64) != KeyCode.J)
  495. {
  496. k = KeyCode.CtrlMask | (KeyCode)(wch + 64);
  497. }
  498. }
  499. else if (wch >= (uint)KeyCode.A && wch <= (uint)KeyCode.Z)
  500. {
  501. k = (KeyCode)wch | KeyCode.ShiftMask;
  502. }
  503. if (wch == '\n' || wch == '\r')
  504. {
  505. k = KeyCode.Enter;
  506. }
  507. OnKeyDown (new Key (k));
  508. OnKeyUp (new Key (k));
  509. }
  510. }
  511. internal void ProcessWinChange ()
  512. {
  513. if (!RunningUnitTests && Curses.CheckWinChange ())
  514. {
  515. ClearContents ();
  516. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  517. }
  518. }
  519. private void HandleEscSeqResponse (
  520. ref int code,
  521. ref KeyCode k,
  522. ref int wch2,
  523. ref Key keyEventArgs,
  524. ref ConsoleKeyInfo [] cki
  525. )
  526. {
  527. ConsoleKey ck = 0;
  528. ConsoleModifiers mod = 0;
  529. while (code == 0)
  530. {
  531. code = Curses.get_wch (out wch2);
  532. var consoleKeyInfo = new ConsoleKeyInfo ((char)wch2, 0, false, false, false);
  533. if (wch2 == 0 || wch2 == 27 || wch2 == Curses.KeyMouse)
  534. {
  535. EscSeqUtils.DecodeEscSeq (
  536. null,
  537. ref consoleKeyInfo,
  538. ref ck,
  539. cki,
  540. ref mod,
  541. out _,
  542. out _,
  543. out _,
  544. out _,
  545. out bool isKeyMouse,
  546. out List<MouseFlags> mouseFlags,
  547. out Point pos,
  548. out _,
  549. ProcessMouseEvent
  550. );
  551. if (isKeyMouse)
  552. {
  553. foreach (MouseFlags mf in mouseFlags)
  554. {
  555. ProcessMouseEvent (mf, pos);
  556. }
  557. cki = null;
  558. if (wch2 == 27)
  559. {
  560. cki = EscSeqUtils.ResizeArray (
  561. new ConsoleKeyInfo (
  562. (char)KeyCode.Esc,
  563. 0,
  564. false,
  565. false,
  566. false
  567. ),
  568. cki
  569. );
  570. }
  571. }
  572. else
  573. {
  574. k = ConsoleKeyMapping.MapConsoleKeyInfoToKeyCode (consoleKeyInfo);
  575. keyEventArgs = new Key (k);
  576. OnKeyDown (keyEventArgs);
  577. }
  578. }
  579. else
  580. {
  581. cki = EscSeqUtils.ResizeArray (consoleKeyInfo, cki);
  582. }
  583. }
  584. }
  585. private static KeyCode MapCursesKey (int cursesKey)
  586. {
  587. switch (cursesKey)
  588. {
  589. case Curses.KeyF1: return KeyCode.F1;
  590. case Curses.KeyF2: return KeyCode.F2;
  591. case Curses.KeyF3: return KeyCode.F3;
  592. case Curses.KeyF4: return KeyCode.F4;
  593. case Curses.KeyF5: return KeyCode.F5;
  594. case Curses.KeyF6: return KeyCode.F6;
  595. case Curses.KeyF7: return KeyCode.F7;
  596. case Curses.KeyF8: return KeyCode.F8;
  597. case Curses.KeyF9: return KeyCode.F9;
  598. case Curses.KeyF10: return KeyCode.F10;
  599. case Curses.KeyF11: return KeyCode.F11;
  600. case Curses.KeyF12: return KeyCode.F12;
  601. case Curses.KeyUp: return KeyCode.CursorUp;
  602. case Curses.KeyDown: return KeyCode.CursorDown;
  603. case Curses.KeyLeft: return KeyCode.CursorLeft;
  604. case Curses.KeyRight: return KeyCode.CursorRight;
  605. case Curses.KeyHome: return KeyCode.Home;
  606. case Curses.KeyEnd: return KeyCode.End;
  607. case Curses.KeyNPage: return KeyCode.PageDown;
  608. case Curses.KeyPPage: return KeyCode.PageUp;
  609. case Curses.KeyDeleteChar: return KeyCode.Delete;
  610. case Curses.KeyInsertChar: return KeyCode.Insert;
  611. case Curses.KeyTab: return KeyCode.Tab;
  612. case Curses.KeyBackTab: return KeyCode.Tab | KeyCode.ShiftMask;
  613. case Curses.KeyBackspace: return KeyCode.Backspace;
  614. case Curses.ShiftKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask;
  615. case Curses.ShiftKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask;
  616. case Curses.ShiftKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask;
  617. case Curses.ShiftKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask;
  618. case Curses.ShiftKeyHome: return KeyCode.Home | KeyCode.ShiftMask;
  619. case Curses.ShiftKeyEnd: return KeyCode.End | KeyCode.ShiftMask;
  620. case Curses.ShiftKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask;
  621. case Curses.ShiftKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask;
  622. case Curses.AltKeyUp: return KeyCode.CursorUp | KeyCode.AltMask;
  623. case Curses.AltKeyDown: return KeyCode.CursorDown | KeyCode.AltMask;
  624. case Curses.AltKeyLeft: return KeyCode.CursorLeft | KeyCode.AltMask;
  625. case Curses.AltKeyRight: return KeyCode.CursorRight | KeyCode.AltMask;
  626. case Curses.AltKeyHome: return KeyCode.Home | KeyCode.AltMask;
  627. case Curses.AltKeyEnd: return KeyCode.End | KeyCode.AltMask;
  628. case Curses.AltKeyNPage: return KeyCode.PageDown | KeyCode.AltMask;
  629. case Curses.AltKeyPPage: return KeyCode.PageUp | KeyCode.AltMask;
  630. case Curses.CtrlKeyUp: return KeyCode.CursorUp | KeyCode.CtrlMask;
  631. case Curses.CtrlKeyDown: return KeyCode.CursorDown | KeyCode.CtrlMask;
  632. case Curses.CtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.CtrlMask;
  633. case Curses.CtrlKeyRight: return KeyCode.CursorRight | KeyCode.CtrlMask;
  634. case Curses.CtrlKeyHome: return KeyCode.Home | KeyCode.CtrlMask;
  635. case Curses.CtrlKeyEnd: return KeyCode.End | KeyCode.CtrlMask;
  636. case Curses.CtrlKeyNPage: return KeyCode.PageDown | KeyCode.CtrlMask;
  637. case Curses.CtrlKeyPPage: return KeyCode.PageUp | KeyCode.CtrlMask;
  638. case Curses.ShiftCtrlKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.CtrlMask;
  639. case Curses.ShiftCtrlKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.CtrlMask;
  640. case Curses.ShiftCtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.CtrlMask;
  641. case Curses.ShiftCtrlKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.CtrlMask;
  642. case Curses.ShiftCtrlKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.CtrlMask;
  643. case Curses.ShiftCtrlKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.CtrlMask;
  644. case Curses.ShiftCtrlKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.CtrlMask;
  645. case Curses.ShiftCtrlKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.CtrlMask;
  646. case Curses.ShiftAltKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.AltMask;
  647. case Curses.ShiftAltKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.AltMask;
  648. case Curses.ShiftAltKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.AltMask;
  649. case Curses.ShiftAltKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.AltMask;
  650. case Curses.ShiftAltKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.AltMask;
  651. case Curses.ShiftAltKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.AltMask;
  652. case Curses.ShiftAltKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.AltMask;
  653. case Curses.ShiftAltKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.AltMask;
  654. case Curses.AltCtrlKeyNPage: return KeyCode.PageDown | KeyCode.AltMask | KeyCode.CtrlMask;
  655. case Curses.AltCtrlKeyPPage: return KeyCode.PageUp | KeyCode.AltMask | KeyCode.CtrlMask;
  656. case Curses.AltCtrlKeyHome: return KeyCode.Home | KeyCode.AltMask | KeyCode.CtrlMask;
  657. case Curses.AltCtrlKeyEnd: return KeyCode.End | KeyCode.AltMask | KeyCode.CtrlMask;
  658. default: return KeyCode.Null;
  659. }
  660. }
  661. private void ProcessMouseEvent (MouseFlags mouseFlag, Point pos)
  662. {
  663. bool WasButtonReleased (MouseFlags flag)
  664. {
  665. return flag.HasFlag (MouseFlags.Button1Released)
  666. || flag.HasFlag (MouseFlags.Button2Released)
  667. || flag.HasFlag (MouseFlags.Button3Released)
  668. || flag.HasFlag (MouseFlags.Button4Released);
  669. }
  670. bool IsButtonNotPressed (MouseFlags flag)
  671. {
  672. return !flag.HasFlag (MouseFlags.Button1Pressed)
  673. && !flag.HasFlag (MouseFlags.Button2Pressed)
  674. && !flag.HasFlag (MouseFlags.Button3Pressed)
  675. && !flag.HasFlag (MouseFlags.Button4Pressed);
  676. }
  677. bool IsButtonClickedOrDoubleClicked (MouseFlags flag)
  678. {
  679. return flag.HasFlag (MouseFlags.Button1Clicked)
  680. || flag.HasFlag (MouseFlags.Button2Clicked)
  681. || flag.HasFlag (MouseFlags.Button3Clicked)
  682. || flag.HasFlag (MouseFlags.Button4Clicked)
  683. || flag.HasFlag (MouseFlags.Button1DoubleClicked)
  684. || flag.HasFlag (MouseFlags.Button2DoubleClicked)
  685. || flag.HasFlag (MouseFlags.Button3DoubleClicked)
  686. || flag.HasFlag (MouseFlags.Button4DoubleClicked);
  687. }
  688. Debug.WriteLine ($"CursesDriver: ({pos.X},{pos.Y}) - {mouseFlag}");
  689. if ((WasButtonReleased (mouseFlag) && IsButtonNotPressed (_lastMouseFlags)) || (IsButtonClickedOrDoubleClicked (mouseFlag) && _lastMouseFlags == 0))
  690. {
  691. return;
  692. }
  693. _lastMouseFlags = mouseFlag;
  694. var me = new MouseEvent { Flags = mouseFlag, X = pos.X, Y = pos.Y };
  695. Debug.WriteLine ($"CursesDriver: ({me.X},{me.Y}) - {me.Flags}");
  696. OnMouseEvent (me);
  697. }
  698. #region Color Handling
  699. /// <summary>Creates an Attribute from the provided curses-based foreground and background color numbers</summary>
  700. /// <param name="foreground">Contains the curses color number for the foreground (color, plus any attributes)</param>
  701. /// <param name="background">Contains the curses color number for the background (color, plus any attributes)</param>
  702. /// <returns></returns>
  703. private static Attribute MakeColor (short foreground, short background)
  704. {
  705. var v = (short)(foreground | (background << 4));
  706. // TODO: for TrueColor - Use InitExtendedPair
  707. Curses.InitColorPair (v, foreground, background);
  708. return new Attribute (
  709. Curses.ColorPair (v),
  710. CursesColorNumberToColorName (foreground),
  711. CursesColorNumberToColorName (background)
  712. );
  713. }
  714. /// <inheritdoc/>
  715. /// <remarks>
  716. /// In the CursesDriver, colors are encoded as an int. The foreground color is stored in the most significant 4
  717. /// bits, and the background color is stored in the least significant 4 bits. The Terminal.GUi Color values are
  718. /// converted to curses color encoding before being encoded.
  719. /// </remarks>
  720. public override Attribute MakeColor (in Color foreground, in Color background)
  721. {
  722. if (!RunningUnitTests)
  723. {
  724. return MakeColor (
  725. ColorNameToCursesColorNumber (foreground.GetClosestNamedColor ()),
  726. ColorNameToCursesColorNumber (background.GetClosestNamedColor ())
  727. );
  728. }
  729. return new Attribute (
  730. 0,
  731. foreground,
  732. background
  733. );
  734. }
  735. private static short ColorNameToCursesColorNumber (ColorName color)
  736. {
  737. switch (color)
  738. {
  739. case ColorName.Black:
  740. return Curses.COLOR_BLACK;
  741. case ColorName.Blue:
  742. return Curses.COLOR_BLUE;
  743. case ColorName.Green:
  744. return Curses.COLOR_GREEN;
  745. case ColorName.Cyan:
  746. return Curses.COLOR_CYAN;
  747. case ColorName.Red:
  748. return Curses.COLOR_RED;
  749. case ColorName.Magenta:
  750. return Curses.COLOR_MAGENTA;
  751. case ColorName.Yellow:
  752. return Curses.COLOR_YELLOW;
  753. case ColorName.Gray:
  754. return Curses.COLOR_WHITE;
  755. case ColorName.DarkGray:
  756. return Curses.COLOR_GRAY;
  757. case ColorName.BrightBlue:
  758. return Curses.COLOR_BLUE | Curses.COLOR_GRAY;
  759. case ColorName.BrightGreen:
  760. return Curses.COLOR_GREEN | Curses.COLOR_GRAY;
  761. case ColorName.BrightCyan:
  762. return Curses.COLOR_CYAN | Curses.COLOR_GRAY;
  763. case ColorName.BrightRed:
  764. return Curses.COLOR_RED | Curses.COLOR_GRAY;
  765. case ColorName.BrightMagenta:
  766. return Curses.COLOR_MAGENTA | Curses.COLOR_GRAY;
  767. case ColorName.BrightYellow:
  768. return Curses.COLOR_YELLOW | Curses.COLOR_GRAY;
  769. case ColorName.White:
  770. return Curses.COLOR_WHITE | Curses.COLOR_GRAY;
  771. }
  772. throw new ArgumentException ("Invalid color code");
  773. }
  774. private static ColorName CursesColorNumberToColorName (short color)
  775. {
  776. switch (color)
  777. {
  778. case Curses.COLOR_BLACK:
  779. return ColorName.Black;
  780. case Curses.COLOR_BLUE:
  781. return ColorName.Blue;
  782. case Curses.COLOR_GREEN:
  783. return ColorName.Green;
  784. case Curses.COLOR_CYAN:
  785. return ColorName.Cyan;
  786. case Curses.COLOR_RED:
  787. return ColorName.Red;
  788. case Curses.COLOR_MAGENTA:
  789. return ColorName.Magenta;
  790. case Curses.COLOR_YELLOW:
  791. return ColorName.Yellow;
  792. case Curses.COLOR_WHITE:
  793. return ColorName.Gray;
  794. case Curses.COLOR_GRAY:
  795. return ColorName.DarkGray;
  796. case Curses.COLOR_BLUE | Curses.COLOR_GRAY:
  797. return ColorName.BrightBlue;
  798. case Curses.COLOR_GREEN | Curses.COLOR_GRAY:
  799. return ColorName.BrightGreen;
  800. case Curses.COLOR_CYAN | Curses.COLOR_GRAY:
  801. return ColorName.BrightCyan;
  802. case Curses.COLOR_RED | Curses.COLOR_GRAY:
  803. return ColorName.BrightRed;
  804. case Curses.COLOR_MAGENTA | Curses.COLOR_GRAY:
  805. return ColorName.BrightMagenta;
  806. case Curses.COLOR_YELLOW | Curses.COLOR_GRAY:
  807. return ColorName.BrightYellow;
  808. case Curses.COLOR_WHITE | Curses.COLOR_GRAY:
  809. return ColorName.White;
  810. }
  811. throw new ArgumentException ("Invalid curses color code");
  812. }
  813. #endregion
  814. }
  815. internal static class Platform
  816. {
  817. private static int _suspendSignal;
  818. /// <summary>Suspends the process by sending SIGTSTP to itself</summary>
  819. /// <returns>The suspend.</returns>
  820. public static bool Suspend ()
  821. {
  822. int signal = GetSuspendSignal ();
  823. if (signal == -1)
  824. {
  825. return false;
  826. }
  827. killpg (0, signal);
  828. return true;
  829. }
  830. private static int GetSuspendSignal ()
  831. {
  832. if (_suspendSignal != 0)
  833. {
  834. return _suspendSignal;
  835. }
  836. nint buf = Marshal.AllocHGlobal (8192);
  837. if (uname (buf) != 0)
  838. {
  839. Marshal.FreeHGlobal (buf);
  840. _suspendSignal = -1;
  841. return _suspendSignal;
  842. }
  843. try
  844. {
  845. switch (Marshal.PtrToStringAnsi (buf))
  846. {
  847. case "Darwin":
  848. case "DragonFly":
  849. case "FreeBSD":
  850. case "NetBSD":
  851. case "OpenBSD":
  852. _suspendSignal = 18;
  853. break;
  854. case "Linux":
  855. // TODO: should fetch the machine name and
  856. // if it is MIPS return 24
  857. _suspendSignal = 20;
  858. break;
  859. case "Solaris":
  860. _suspendSignal = 24;
  861. break;
  862. default:
  863. _suspendSignal = -1;
  864. break;
  865. }
  866. return _suspendSignal;
  867. }
  868. finally
  869. {
  870. Marshal.FreeHGlobal (buf);
  871. }
  872. }
  873. [DllImport ("libc")]
  874. private static extern int killpg (int pgrp, int pid);
  875. [DllImport ("libc")]
  876. private static extern int uname (nint buf);
  877. }