CursesDriver.cs 42 KB

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