CursesDriver.cs 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  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. if (wch2 == (int)KeyCode.Space)
  423. {
  424. k = KeyCode.AltMask;
  425. }
  426. else if (wch2 - (int)KeyCode.Space >= (uint)KeyCode.A
  427. && wch2 - (int)KeyCode.Space <= (uint)KeyCode.Z)
  428. {
  429. k = (KeyCode)((uint)KeyCode.AltMask + (wch2 - (int)KeyCode.Space));
  430. }
  431. else if (wch2 >= (uint)KeyCode.A - 64 && wch2 <= (uint)KeyCode.Z - 64)
  432. {
  433. k = (KeyCode)((uint)(KeyCode.AltMask | KeyCode.CtrlMask) + (wch2 + 64));
  434. }
  435. else if (wch2 >= (uint)KeyCode.D0 && wch2 <= (uint)KeyCode.D9)
  436. {
  437. k = (KeyCode)((uint)KeyCode.AltMask + (uint)KeyCode.D0 + (wch2 - (uint)KeyCode.D0));
  438. }
  439. else if (wch2 == Curses.KeyCSI)
  440. {
  441. ConsoleKeyInfo [] cki =
  442. {
  443. new ((char)KeyCode.Esc, 0, false, false, false), new ('[', 0, false, false, false)
  444. };
  445. HandleEscSeqResponse (ref code, ref k, ref wch2, ref key, ref cki);
  446. return;
  447. }
  448. else
  449. {
  450. // Unfortunately there are no way to differentiate Ctrl+Alt+alfa and Ctrl+Shift+Alt+alfa.
  451. if (((KeyCode)wch2 & KeyCode.CtrlMask) != 0)
  452. {
  453. k = (KeyCode)((uint)KeyCode.CtrlMask + (wch2 & ~(int)KeyCode.CtrlMask));
  454. }
  455. if (wch2 == 0)
  456. {
  457. k = KeyCode.CtrlMask | KeyCode.AltMask | KeyCode.Space;
  458. }
  459. else if (wch >= (uint)KeyCode.A && wch <= (uint)KeyCode.Z)
  460. {
  461. k = KeyCode.ShiftMask | KeyCode.AltMask | KeyCode.Space;
  462. }
  463. else if (wch2 < 256)
  464. {
  465. k = (KeyCode)wch2; // | KeyCode.AltMask;
  466. }
  467. else
  468. {
  469. k = (KeyCode)((uint)(KeyCode.AltMask | KeyCode.CtrlMask) + wch2);
  470. }
  471. }
  472. key = new Key (k);
  473. }
  474. else
  475. {
  476. key = Key.Esc;
  477. }
  478. OnKeyDown (key);
  479. OnKeyUp (key);
  480. }
  481. else if (wch == Curses.KeyTab)
  482. {
  483. k = MapCursesKey (wch);
  484. OnKeyDown (new Key (k));
  485. OnKeyUp (new Key (k));
  486. }
  487. else
  488. {
  489. // Unfortunately there are no way to differentiate Ctrl+alfa and Ctrl+Shift+alfa.
  490. k = (KeyCode)wch;
  491. if (wch == 0)
  492. {
  493. k = KeyCode.CtrlMask | KeyCode.Space;
  494. }
  495. else if (wch >= (uint)KeyCode.A - 64 && wch <= (uint)KeyCode.Z - 64)
  496. {
  497. if ((KeyCode)(wch + 64) != KeyCode.J)
  498. {
  499. k = KeyCode.CtrlMask | (KeyCode)(wch + 64);
  500. }
  501. }
  502. else if (wch >= (uint)KeyCode.A && wch <= (uint)KeyCode.Z)
  503. {
  504. k = (KeyCode)wch | KeyCode.ShiftMask;
  505. }
  506. if (wch == '\n' || wch == '\r')
  507. {
  508. k = KeyCode.Enter;
  509. }
  510. // Strip the KeyCode.Space flag off if it's set
  511. if (k != KeyCode.Space && k.HasFlag (KeyCode.Space))
  512. {
  513. k &= ~KeyCode.Space;
  514. }
  515. OnKeyDown (new Key (k));
  516. OnKeyUp (new Key (k));
  517. }
  518. }
  519. internal void ProcessWinChange ()
  520. {
  521. if (!RunningUnitTests && Curses.CheckWinChange ())
  522. {
  523. ClearContents ();
  524. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  525. }
  526. }
  527. private void HandleEscSeqResponse (
  528. ref int code,
  529. ref KeyCode k,
  530. ref int wch2,
  531. ref Key keyEventArgs,
  532. ref ConsoleKeyInfo [] cki
  533. )
  534. {
  535. ConsoleKey ck = 0;
  536. ConsoleModifiers mod = 0;
  537. while (code == 0)
  538. {
  539. code = Curses.get_wch (out wch2);
  540. var consoleKeyInfo = new ConsoleKeyInfo ((char)wch2, 0, false, false, false);
  541. if (wch2 == 0 || wch2 == 27 || wch2 == Curses.KeyMouse)
  542. {
  543. EscSeqUtils.DecodeEscSeq (
  544. null,
  545. ref consoleKeyInfo,
  546. ref ck,
  547. cki,
  548. ref mod,
  549. out _,
  550. out _,
  551. out _,
  552. out _,
  553. out bool isKeyMouse,
  554. out List<MouseFlags> mouseFlags,
  555. out Point pos,
  556. out _,
  557. ProcessMouseEvent
  558. );
  559. if (isKeyMouse)
  560. {
  561. foreach (MouseFlags mf in mouseFlags)
  562. {
  563. ProcessMouseEvent (mf, pos);
  564. }
  565. cki = null;
  566. if (wch2 == 27)
  567. {
  568. cki = EscSeqUtils.ResizeArray (
  569. new ConsoleKeyInfo (
  570. (char)KeyCode.Esc,
  571. 0,
  572. false,
  573. false,
  574. false
  575. ),
  576. cki
  577. );
  578. }
  579. }
  580. else
  581. {
  582. k = ConsoleKeyMapping.MapConsoleKeyInfoToKeyCode (consoleKeyInfo);
  583. keyEventArgs = new Key (k);
  584. OnKeyDown (keyEventArgs);
  585. }
  586. }
  587. else
  588. {
  589. cki = EscSeqUtils.ResizeArray (consoleKeyInfo, cki);
  590. }
  591. }
  592. }
  593. private static KeyCode MapCursesKey (int cursesKey)
  594. {
  595. switch (cursesKey)
  596. {
  597. case Curses.KeyF1: return KeyCode.F1;
  598. case Curses.KeyF2: return KeyCode.F2;
  599. case Curses.KeyF3: return KeyCode.F3;
  600. case Curses.KeyF4: return KeyCode.F4;
  601. case Curses.KeyF5: return KeyCode.F5;
  602. case Curses.KeyF6: return KeyCode.F6;
  603. case Curses.KeyF7: return KeyCode.F7;
  604. case Curses.KeyF8: return KeyCode.F8;
  605. case Curses.KeyF9: return KeyCode.F9;
  606. case Curses.KeyF10: return KeyCode.F10;
  607. case Curses.KeyF11: return KeyCode.F11;
  608. case Curses.KeyF12: return KeyCode.F12;
  609. case Curses.KeyUp: return KeyCode.CursorUp;
  610. case Curses.KeyDown: return KeyCode.CursorDown;
  611. case Curses.KeyLeft: return KeyCode.CursorLeft;
  612. case Curses.KeyRight: return KeyCode.CursorRight;
  613. case Curses.KeyHome: return KeyCode.Home;
  614. case Curses.KeyEnd: return KeyCode.End;
  615. case Curses.KeyNPage: return KeyCode.PageDown;
  616. case Curses.KeyPPage: return KeyCode.PageUp;
  617. case Curses.KeyDeleteChar: return KeyCode.Delete;
  618. case Curses.KeyInsertChar: return KeyCode.Insert;
  619. case Curses.KeyTab: return KeyCode.Tab;
  620. case Curses.KeyBackTab: return KeyCode.Tab | KeyCode.ShiftMask;
  621. case Curses.KeyBackspace: return KeyCode.Backspace;
  622. case Curses.ShiftKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask;
  623. case Curses.ShiftKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask;
  624. case Curses.ShiftKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask;
  625. case Curses.ShiftKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask;
  626. case Curses.ShiftKeyHome: return KeyCode.Home | KeyCode.ShiftMask;
  627. case Curses.ShiftKeyEnd: return KeyCode.End | KeyCode.ShiftMask;
  628. case Curses.ShiftKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask;
  629. case Curses.ShiftKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask;
  630. case Curses.AltKeyUp: return KeyCode.CursorUp | KeyCode.AltMask;
  631. case Curses.AltKeyDown: return KeyCode.CursorDown | KeyCode.AltMask;
  632. case Curses.AltKeyLeft: return KeyCode.CursorLeft | KeyCode.AltMask;
  633. case Curses.AltKeyRight: return KeyCode.CursorRight | KeyCode.AltMask;
  634. case Curses.AltKeyHome: return KeyCode.Home | KeyCode.AltMask;
  635. case Curses.AltKeyEnd: return KeyCode.End | KeyCode.AltMask;
  636. case Curses.AltKeyNPage: return KeyCode.PageDown | KeyCode.AltMask;
  637. case Curses.AltKeyPPage: return KeyCode.PageUp | KeyCode.AltMask;
  638. case Curses.CtrlKeyUp: return KeyCode.CursorUp | KeyCode.CtrlMask;
  639. case Curses.CtrlKeyDown: return KeyCode.CursorDown | KeyCode.CtrlMask;
  640. case Curses.CtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.CtrlMask;
  641. case Curses.CtrlKeyRight: return KeyCode.CursorRight | KeyCode.CtrlMask;
  642. case Curses.CtrlKeyHome: return KeyCode.Home | KeyCode.CtrlMask;
  643. case Curses.CtrlKeyEnd: return KeyCode.End | KeyCode.CtrlMask;
  644. case Curses.CtrlKeyNPage: return KeyCode.PageDown | KeyCode.CtrlMask;
  645. case Curses.CtrlKeyPPage: return KeyCode.PageUp | KeyCode.CtrlMask;
  646. case Curses.ShiftCtrlKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.CtrlMask;
  647. case Curses.ShiftCtrlKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.CtrlMask;
  648. case Curses.ShiftCtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.CtrlMask;
  649. case Curses.ShiftCtrlKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.CtrlMask;
  650. case Curses.ShiftCtrlKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.CtrlMask;
  651. case Curses.ShiftCtrlKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.CtrlMask;
  652. case Curses.ShiftCtrlKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.CtrlMask;
  653. case Curses.ShiftCtrlKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.CtrlMask;
  654. case Curses.ShiftAltKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.AltMask;
  655. case Curses.ShiftAltKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.AltMask;
  656. case Curses.ShiftAltKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.AltMask;
  657. case Curses.ShiftAltKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.AltMask;
  658. case Curses.ShiftAltKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.AltMask;
  659. case Curses.ShiftAltKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.AltMask;
  660. case Curses.ShiftAltKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.AltMask;
  661. case Curses.ShiftAltKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.AltMask;
  662. case Curses.AltCtrlKeyNPage: return KeyCode.PageDown | KeyCode.AltMask | KeyCode.CtrlMask;
  663. case Curses.AltCtrlKeyPPage: return KeyCode.PageUp | KeyCode.AltMask | KeyCode.CtrlMask;
  664. case Curses.AltCtrlKeyHome: return KeyCode.Home | KeyCode.AltMask | KeyCode.CtrlMask;
  665. case Curses.AltCtrlKeyEnd: return KeyCode.End | KeyCode.AltMask | KeyCode.CtrlMask;
  666. default: return KeyCode.Null;
  667. }
  668. }
  669. private void ProcessMouseEvent (MouseFlags mouseFlag, Point pos)
  670. {
  671. bool WasButtonReleased (MouseFlags flag)
  672. {
  673. return flag.HasFlag (MouseFlags.Button1Released)
  674. || flag.HasFlag (MouseFlags.Button2Released)
  675. || flag.HasFlag (MouseFlags.Button3Released)
  676. || flag.HasFlag (MouseFlags.Button4Released);
  677. }
  678. bool IsButtonNotPressed (MouseFlags flag)
  679. {
  680. return !flag.HasFlag (MouseFlags.Button1Pressed)
  681. && !flag.HasFlag (MouseFlags.Button2Pressed)
  682. && !flag.HasFlag (MouseFlags.Button3Pressed)
  683. && !flag.HasFlag (MouseFlags.Button4Pressed);
  684. }
  685. bool IsButtonClickedOrDoubleClicked (MouseFlags flag)
  686. {
  687. return flag.HasFlag (MouseFlags.Button1Clicked)
  688. || flag.HasFlag (MouseFlags.Button2Clicked)
  689. || flag.HasFlag (MouseFlags.Button3Clicked)
  690. || flag.HasFlag (MouseFlags.Button4Clicked)
  691. || flag.HasFlag (MouseFlags.Button1DoubleClicked)
  692. || flag.HasFlag (MouseFlags.Button2DoubleClicked)
  693. || flag.HasFlag (MouseFlags.Button3DoubleClicked)
  694. || flag.HasFlag (MouseFlags.Button4DoubleClicked);
  695. }
  696. Debug.WriteLine ($"CursesDriver: ({pos.X},{pos.Y}) - {mouseFlag}");
  697. if ((WasButtonReleased (mouseFlag) && IsButtonNotPressed (_lastMouseFlags)) || (IsButtonClickedOrDoubleClicked (mouseFlag) && _lastMouseFlags == 0))
  698. {
  699. return;
  700. }
  701. _lastMouseFlags = mouseFlag;
  702. var me = new MouseEvent { Flags = mouseFlag, Position = pos };
  703. //Debug.WriteLine ($"CursesDriver: ({me.Position}) - {me.Flags}");
  704. OnMouseEvent (me);
  705. }
  706. #region Color Handling
  707. /// <summary>Creates an Attribute from the provided curses-based foreground and background color numbers</summary>
  708. /// <param name="foreground">Contains the curses color number for the foreground (color, plus any attributes)</param>
  709. /// <param name="background">Contains the curses color number for the background (color, plus any attributes)</param>
  710. /// <returns></returns>
  711. private static Attribute MakeColor (short foreground, short background)
  712. {
  713. var v = (short)((ushort)foreground | (background << 4));
  714. // TODO: for TrueColor - Use InitExtendedPair
  715. Curses.InitColorPair (v, foreground, background);
  716. return new Attribute (
  717. Curses.ColorPair (v),
  718. CursesColorNumberToColorName (foreground),
  719. CursesColorNumberToColorName (background)
  720. );
  721. }
  722. /// <inheritdoc/>
  723. /// <remarks>
  724. /// In the CursesDriver, colors are encoded as an int. The foreground color is stored in the most significant 4
  725. /// bits, and the background color is stored in the least significant 4 bits. The Terminal.GUi Color values are
  726. /// converted to curses color encoding before being encoded.
  727. /// </remarks>
  728. public override Attribute MakeColor (in Color foreground, in Color background)
  729. {
  730. if (!RunningUnitTests)
  731. {
  732. return MakeColor (
  733. ColorNameToCursesColorNumber (foreground.GetClosestNamedColor ()),
  734. ColorNameToCursesColorNumber (background.GetClosestNamedColor ())
  735. );
  736. }
  737. return new Attribute (
  738. 0,
  739. foreground,
  740. background
  741. );
  742. }
  743. private static short ColorNameToCursesColorNumber (ColorName color)
  744. {
  745. switch (color)
  746. {
  747. case ColorName.Black:
  748. return Curses.COLOR_BLACK;
  749. case ColorName.Blue:
  750. return Curses.COLOR_BLUE;
  751. case ColorName.Green:
  752. return Curses.COLOR_GREEN;
  753. case ColorName.Cyan:
  754. return Curses.COLOR_CYAN;
  755. case ColorName.Red:
  756. return Curses.COLOR_RED;
  757. case ColorName.Magenta:
  758. return Curses.COLOR_MAGENTA;
  759. case ColorName.Yellow:
  760. return Curses.COLOR_YELLOW;
  761. case ColorName.Gray:
  762. return Curses.COLOR_WHITE;
  763. case ColorName.DarkGray:
  764. return Curses.COLOR_GRAY;
  765. case ColorName.BrightBlue:
  766. return Curses.COLOR_BLUE | Curses.COLOR_GRAY;
  767. case ColorName.BrightGreen:
  768. return Curses.COLOR_GREEN | Curses.COLOR_GRAY;
  769. case ColorName.BrightCyan:
  770. return Curses.COLOR_CYAN | Curses.COLOR_GRAY;
  771. case ColorName.BrightRed:
  772. return Curses.COLOR_RED | Curses.COLOR_GRAY;
  773. case ColorName.BrightMagenta:
  774. return Curses.COLOR_MAGENTA | Curses.COLOR_GRAY;
  775. case ColorName.BrightYellow:
  776. return Curses.COLOR_YELLOW | Curses.COLOR_GRAY;
  777. case ColorName.White:
  778. return Curses.COLOR_WHITE | Curses.COLOR_GRAY;
  779. }
  780. throw new ArgumentException ("Invalid color code");
  781. }
  782. private static ColorName CursesColorNumberToColorName (short color)
  783. {
  784. switch (color)
  785. {
  786. case Curses.COLOR_BLACK:
  787. return ColorName.Black;
  788. case Curses.COLOR_BLUE:
  789. return ColorName.Blue;
  790. case Curses.COLOR_GREEN:
  791. return ColorName.Green;
  792. case Curses.COLOR_CYAN:
  793. return ColorName.Cyan;
  794. case Curses.COLOR_RED:
  795. return ColorName.Red;
  796. case Curses.COLOR_MAGENTA:
  797. return ColorName.Magenta;
  798. case Curses.COLOR_YELLOW:
  799. return ColorName.Yellow;
  800. case Curses.COLOR_WHITE:
  801. return ColorName.Gray;
  802. case Curses.COLOR_GRAY:
  803. return ColorName.DarkGray;
  804. case Curses.COLOR_BLUE | Curses.COLOR_GRAY:
  805. return ColorName.BrightBlue;
  806. case Curses.COLOR_GREEN | Curses.COLOR_GRAY:
  807. return ColorName.BrightGreen;
  808. case Curses.COLOR_CYAN | Curses.COLOR_GRAY:
  809. return ColorName.BrightCyan;
  810. case Curses.COLOR_RED | Curses.COLOR_GRAY:
  811. return ColorName.BrightRed;
  812. case Curses.COLOR_MAGENTA | Curses.COLOR_GRAY:
  813. return ColorName.BrightMagenta;
  814. case Curses.COLOR_YELLOW | Curses.COLOR_GRAY:
  815. return ColorName.BrightYellow;
  816. case Curses.COLOR_WHITE | Curses.COLOR_GRAY:
  817. return ColorName.White;
  818. }
  819. throw new ArgumentException ("Invalid curses color code");
  820. }
  821. #endregion
  822. }
  823. internal static class Platform
  824. {
  825. private static int _suspendSignal;
  826. /// <summary>Suspends the process by sending SIGTSTP to itself</summary>
  827. /// <returns>The suspend.</returns>
  828. public static bool Suspend ()
  829. {
  830. int signal = GetSuspendSignal ();
  831. if (signal == -1)
  832. {
  833. return false;
  834. }
  835. killpg (0, signal);
  836. return true;
  837. }
  838. private static int GetSuspendSignal ()
  839. {
  840. if (_suspendSignal != 0)
  841. {
  842. return _suspendSignal;
  843. }
  844. nint buf = Marshal.AllocHGlobal (8192);
  845. if (uname (buf) != 0)
  846. {
  847. Marshal.FreeHGlobal (buf);
  848. _suspendSignal = -1;
  849. return _suspendSignal;
  850. }
  851. try
  852. {
  853. switch (Marshal.PtrToStringAnsi (buf))
  854. {
  855. case "Darwin":
  856. case "DragonFly":
  857. case "FreeBSD":
  858. case "NetBSD":
  859. case "OpenBSD":
  860. _suspendSignal = 18;
  861. break;
  862. case "Linux":
  863. // TODO: should fetch the machine name and
  864. // if it is MIPS return 24
  865. _suspendSignal = 20;
  866. break;
  867. case "Solaris":
  868. _suspendSignal = 24;
  869. break;
  870. default:
  871. _suspendSignal = -1;
  872. break;
  873. }
  874. return _suspendSignal;
  875. }
  876. finally
  877. {
  878. Marshal.FreeHGlobal (buf);
  879. }
  880. }
  881. [DllImport ("libc")]
  882. private static extern int killpg (int pgrp, int pid);
  883. [DllImport ("libc")]
  884. private static extern int uname (nint buf);
  885. }