2
0

CursesDriver.cs 35 KB

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