CursesDriver.cs 42 KB

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