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