CursesDriver.cs 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241
  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. /// <inheritdoc />
  161. public override void RawWrite (string str)
  162. {
  163. Console.Out.Write (str);
  164. }
  165. public override void Suspend ()
  166. {
  167. StopReportingMouseMoves ();
  168. if (!RunningUnitTests)
  169. {
  170. Platform.Suspend ();
  171. if (Force16Colors)
  172. {
  173. Curses.Window.Standard.redrawwin ();
  174. Curses.refresh ();
  175. }
  176. }
  177. StartReportingMouseMoves ();
  178. }
  179. public override void UpdateCursor ()
  180. {
  181. EnsureCursorVisibility ();
  182. if (!RunningUnitTests && Col >= 0 && Col < Cols && Row >= 0 && Row < Rows)
  183. {
  184. Curses.move (Row, Col);
  185. if (Force16Colors)
  186. {
  187. Curses.raw ();
  188. Curses.noecho ();
  189. Curses.refresh ();
  190. }
  191. }
  192. }
  193. public override void UpdateScreen ()
  194. {
  195. if (Force16Colors)
  196. {
  197. for (var row = 0; row < Rows; row++)
  198. {
  199. if (!_dirtyLines [row])
  200. {
  201. continue;
  202. }
  203. _dirtyLines [row] = false;
  204. for (var col = 0; col < Cols; col++)
  205. {
  206. if (Contents [row, col].IsDirty == false)
  207. {
  208. continue;
  209. }
  210. if (RunningUnitTests)
  211. {
  212. // In unit tests, we don't want to actually write to the screen.
  213. continue;
  214. }
  215. Curses.attrset (Contents [row, col].Attribute.GetValueOrDefault ().PlatformColor);
  216. Rune rune = Contents [row, col].Rune;
  217. if (rune.IsBmp)
  218. {
  219. // 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.
  220. if (rune.GetColumns () < 2)
  221. {
  222. Curses.mvaddch (row, col, rune.Value);
  223. }
  224. else /*if (col + 1 < Cols)*/
  225. {
  226. Curses.mvaddwstr (row, col, rune.ToString ());
  227. }
  228. }
  229. else
  230. {
  231. Curses.mvaddwstr (row, col, rune.ToString ());
  232. if (rune.GetColumns () > 1 && col + 1 < Cols)
  233. {
  234. // TODO: This is a hack to deal with non-BMP and wide characters.
  235. //col++;
  236. Curses.mvaddch (row, ++col, '*');
  237. }
  238. }
  239. }
  240. }
  241. if (!RunningUnitTests)
  242. {
  243. Curses.move (Row, Col);
  244. _window.wrefresh ();
  245. }
  246. }
  247. else
  248. {
  249. if (RunningUnitTests
  250. || Console.WindowHeight < 1
  251. || Contents.Length != Rows * Cols
  252. || Rows != Console.WindowHeight)
  253. {
  254. return;
  255. }
  256. var top = 0;
  257. var left = 0;
  258. int rows = Rows;
  259. int cols = Cols;
  260. var output = new StringBuilder ();
  261. Attribute? redrawAttr = null;
  262. int lastCol = -1;
  263. CursorVisibility? savedVisibility = _currentCursorVisibility;
  264. SetCursorVisibility (CursorVisibility.Invisible);
  265. for (int row = top; row < rows; row++)
  266. {
  267. if (Console.WindowHeight < 1)
  268. {
  269. return;
  270. }
  271. if (!_dirtyLines [row])
  272. {
  273. continue;
  274. }
  275. if (!SetCursorPosition (0, row))
  276. {
  277. return;
  278. }
  279. _dirtyLines [row] = false;
  280. output.Clear ();
  281. for (int col = left; col < cols; col++)
  282. {
  283. lastCol = -1;
  284. var outputWidth = 0;
  285. for (; col < cols; col++)
  286. {
  287. if (!Contents [row, col].IsDirty)
  288. {
  289. if (output.Length > 0)
  290. {
  291. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  292. }
  293. else if (lastCol == -1)
  294. {
  295. lastCol = col;
  296. }
  297. if (lastCol + 1 < cols)
  298. {
  299. lastCol++;
  300. }
  301. continue;
  302. }
  303. if (lastCol == -1)
  304. {
  305. lastCol = col;
  306. }
  307. Attribute attr = Contents [row, col].Attribute.Value;
  308. // Performance: Only send the escape sequence if the attribute has changed.
  309. if (attr != redrawAttr)
  310. {
  311. redrawAttr = attr;
  312. output.Append (
  313. EscSeqUtils.CSI_SetForegroundColorRGB (
  314. attr.Foreground.R,
  315. attr.Foreground.G,
  316. attr.Foreground.B
  317. )
  318. );
  319. output.Append (
  320. EscSeqUtils.CSI_SetBackgroundColorRGB (
  321. attr.Background.R,
  322. attr.Background.G,
  323. attr.Background.B
  324. )
  325. );
  326. }
  327. outputWidth++;
  328. Rune rune = Contents [row, col].Rune;
  329. output.Append (rune);
  330. if (Contents [row, col].CombiningMarks.Count > 0)
  331. {
  332. // AtlasEngine does not support NON-NORMALIZED combining marks in a way
  333. // compatible with the driver architecture. Any CMs (except in the first col)
  334. // are correctly combined with the base char, but are ALSO treated as 1 column
  335. // width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
  336. //
  337. // For now, we just ignore the list of CMs.
  338. //foreach (var combMark in Contents [row, col].CombiningMarks) {
  339. // output.Append (combMark);
  340. //}
  341. // WriteToConsole (output, ref lastCol, row, ref outputWidth);
  342. }
  343. else if (rune.IsSurrogatePair () && rune.GetColumns () < 2)
  344. {
  345. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  346. SetCursorPosition (col - 1, row);
  347. }
  348. Contents [row, col].IsDirty = false;
  349. }
  350. }
  351. if (output.Length > 0)
  352. {
  353. SetCursorPosition (lastCol, row);
  354. Console.Write (output);
  355. }
  356. }
  357. SetCursorPosition (0, 0);
  358. _currentCursorVisibility = savedVisibility;
  359. void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
  360. {
  361. SetCursorPosition (lastCol, row);
  362. Console.Write (output);
  363. output.Clear ();
  364. lastCol += outputWidth;
  365. outputWidth = 0;
  366. }
  367. }
  368. }
  369. private bool SetCursorPosition (int col, int row)
  370. {
  371. // + 1 is needed because non-Windows is based on 1 instead of 0 and
  372. // Console.CursorTop/CursorLeft isn't reliable.
  373. Console.Out.Write (EscSeqUtils.CSI_SetCursorPosition (row + 1, col + 1));
  374. return true;
  375. }
  376. internal override void End ()
  377. {
  378. StopReportingMouseMoves ();
  379. SetCursorVisibility (CursorVisibility.Default);
  380. if (_mainLoopDriver is { })
  381. {
  382. _mainLoopDriver.RemoveWatch (_processInputToken);
  383. }
  384. if (RunningUnitTests)
  385. {
  386. return;
  387. }
  388. // throws away any typeahead that has been typed by
  389. // the user and has not yet been read by the program.
  390. Curses.flushinp ();
  391. Curses.endwin ();
  392. }
  393. internal override MainLoop Init ()
  394. {
  395. _mainLoopDriver = new UnixMainLoop (this);
  396. if (!RunningUnitTests)
  397. {
  398. _window = Curses.initscr ();
  399. Curses.set_escdelay (10);
  400. // Ensures that all procedures are performed at some previous closing.
  401. Curses.doupdate ();
  402. //
  403. // We are setting Invisible as default, so we could ignore XTerm DECSUSR setting
  404. //
  405. switch (Curses.curs_set (0))
  406. {
  407. case 0:
  408. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Invisible;
  409. break;
  410. case 1:
  411. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Underline;
  412. Curses.curs_set (1);
  413. break;
  414. case 2:
  415. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Box;
  416. Curses.curs_set (2);
  417. break;
  418. default:
  419. _currentCursorVisibility = _initialCursorVisibility = null;
  420. break;
  421. }
  422. if (!Curses.HasColors)
  423. {
  424. throw new InvalidOperationException ("V2 - This should never happen. File an Issue if it does.");
  425. }
  426. Curses.raw ();
  427. Curses.noecho ();
  428. Curses.Window.Standard.keypad (true);
  429. Curses.StartColor ();
  430. Curses.UseDefaultColors ();
  431. if (!RunningUnitTests)
  432. {
  433. Curses.timeout (0);
  434. }
  435. _processInputToken = _mainLoopDriver?.AddWatch (
  436. 0,
  437. UnixMainLoop.Condition.PollIn,
  438. x =>
  439. {
  440. ProcessInput ();
  441. return true;
  442. }
  443. );
  444. }
  445. CurrentAttribute = new Attribute (ColorName16.White, ColorName16.Black);
  446. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  447. {
  448. Clipboard = new FakeDriver.FakeClipboard ();
  449. }
  450. else
  451. {
  452. if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
  453. {
  454. Clipboard = new MacOSXClipboard ();
  455. }
  456. else
  457. {
  458. if (Is_WSL_Platform ())
  459. {
  460. Clipboard = new WSLClipboard ();
  461. }
  462. else
  463. {
  464. Clipboard = new CursesClipboard ();
  465. }
  466. }
  467. }
  468. ClearContents ();
  469. StartReportingMouseMoves ();
  470. if (!RunningUnitTests)
  471. {
  472. Curses.CheckWinChange ();
  473. if (Force16Colors)
  474. {
  475. Curses.refresh ();
  476. }
  477. }
  478. return new MainLoop (_mainLoopDriver);
  479. }
  480. private AnsiResponseParser Parser { get; set; } = new ();
  481. /// <inheritdoc />
  482. public override IAnsiResponseParser GetParser () => Parser;
  483. private List<int> seen = new List<int> ();
  484. internal void ProcessInput ()
  485. {
  486. int wch;
  487. int code = Curses.get_wch (out wch);
  488. //System.Diagnostics.Debug.WriteLine ($"code: {code}; wch: {wch}");
  489. if (code == Curses.ERR)
  490. {
  491. return;
  492. }
  493. var k = KeyCode.Null;
  494. seen.Add (wch);
  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. if (cki != null)
  751. {
  752. foreach (var c in cki)
  753. {
  754. Parser.ProcessInput (c.KeyChar.ToString());
  755. }
  756. }
  757. k = ConsoleKeyMapping.MapConsoleKeyInfoToKeyCode (consoleKeyInfo);
  758. keyEventArgs = new Key (k);
  759. OnKeyDown (keyEventArgs);
  760. }
  761. }
  762. else
  763. {
  764. cki = EscSeqUtils.ResizeArray (consoleKeyInfo, cki);
  765. }
  766. }
  767. }
  768. private static KeyCode MapCursesKey (int cursesKey)
  769. {
  770. switch (cursesKey)
  771. {
  772. case Curses.KeyF1: return KeyCode.F1;
  773. case Curses.KeyF2: return KeyCode.F2;
  774. case Curses.KeyF3: return KeyCode.F3;
  775. case Curses.KeyF4: return KeyCode.F4;
  776. case Curses.KeyF5: return KeyCode.F5;
  777. case Curses.KeyF6: return KeyCode.F6;
  778. case Curses.KeyF7: return KeyCode.F7;
  779. case Curses.KeyF8: return KeyCode.F8;
  780. case Curses.KeyF9: return KeyCode.F9;
  781. case Curses.KeyF10: return KeyCode.F10;
  782. case Curses.KeyF11: return KeyCode.F11;
  783. case Curses.KeyF12: return KeyCode.F12;
  784. case Curses.KeyUp: return KeyCode.CursorUp;
  785. case Curses.KeyDown: return KeyCode.CursorDown;
  786. case Curses.KeyLeft: return KeyCode.CursorLeft;
  787. case Curses.KeyRight: return KeyCode.CursorRight;
  788. case Curses.KeyHome: return KeyCode.Home;
  789. case Curses.KeyEnd: return KeyCode.End;
  790. case Curses.KeyNPage: return KeyCode.PageDown;
  791. case Curses.KeyPPage: return KeyCode.PageUp;
  792. case Curses.KeyDeleteChar: return KeyCode.Delete;
  793. case Curses.KeyInsertChar: return KeyCode.Insert;
  794. case Curses.KeyTab: return KeyCode.Tab;
  795. case Curses.KeyBackTab: return KeyCode.Tab | KeyCode.ShiftMask;
  796. case Curses.KeyBackspace: return KeyCode.Backspace;
  797. case Curses.ShiftKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask;
  798. case Curses.ShiftKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask;
  799. case Curses.ShiftKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask;
  800. case Curses.ShiftKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask;
  801. case Curses.ShiftKeyHome: return KeyCode.Home | KeyCode.ShiftMask;
  802. case Curses.ShiftKeyEnd: return KeyCode.End | KeyCode.ShiftMask;
  803. case Curses.ShiftKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask;
  804. case Curses.ShiftKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask;
  805. case Curses.AltKeyUp: return KeyCode.CursorUp | KeyCode.AltMask;
  806. case Curses.AltKeyDown: return KeyCode.CursorDown | KeyCode.AltMask;
  807. case Curses.AltKeyLeft: return KeyCode.CursorLeft | KeyCode.AltMask;
  808. case Curses.AltKeyRight: return KeyCode.CursorRight | KeyCode.AltMask;
  809. case Curses.AltKeyHome: return KeyCode.Home | KeyCode.AltMask;
  810. case Curses.AltKeyEnd: return KeyCode.End | KeyCode.AltMask;
  811. case Curses.AltKeyNPage: return KeyCode.PageDown | KeyCode.AltMask;
  812. case Curses.AltKeyPPage: return KeyCode.PageUp | KeyCode.AltMask;
  813. case Curses.CtrlKeyUp: return KeyCode.CursorUp | KeyCode.CtrlMask;
  814. case Curses.CtrlKeyDown: return KeyCode.CursorDown | KeyCode.CtrlMask;
  815. case Curses.CtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.CtrlMask;
  816. case Curses.CtrlKeyRight: return KeyCode.CursorRight | KeyCode.CtrlMask;
  817. case Curses.CtrlKeyHome: return KeyCode.Home | KeyCode.CtrlMask;
  818. case Curses.CtrlKeyEnd: return KeyCode.End | KeyCode.CtrlMask;
  819. case Curses.CtrlKeyNPage: return KeyCode.PageDown | KeyCode.CtrlMask;
  820. case Curses.CtrlKeyPPage: return KeyCode.PageUp | KeyCode.CtrlMask;
  821. case Curses.ShiftCtrlKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.CtrlMask;
  822. case Curses.ShiftCtrlKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.CtrlMask;
  823. case Curses.ShiftCtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.CtrlMask;
  824. case Curses.ShiftCtrlKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.CtrlMask;
  825. case Curses.ShiftCtrlKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.CtrlMask;
  826. case Curses.ShiftCtrlKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.CtrlMask;
  827. case Curses.ShiftCtrlKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.CtrlMask;
  828. case Curses.ShiftCtrlKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.CtrlMask;
  829. case Curses.ShiftAltKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.AltMask;
  830. case Curses.ShiftAltKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.AltMask;
  831. case Curses.ShiftAltKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.AltMask;
  832. case Curses.ShiftAltKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.AltMask;
  833. case Curses.ShiftAltKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.AltMask;
  834. case Curses.ShiftAltKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.AltMask;
  835. case Curses.ShiftAltKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.AltMask;
  836. case Curses.ShiftAltKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.AltMask;
  837. case Curses.AltCtrlKeyNPage: return KeyCode.PageDown | KeyCode.AltMask | KeyCode.CtrlMask;
  838. case Curses.AltCtrlKeyPPage: return KeyCode.PageUp | KeyCode.AltMask | KeyCode.CtrlMask;
  839. case Curses.AltCtrlKeyHome: return KeyCode.Home | KeyCode.AltMask | KeyCode.CtrlMask;
  840. case Curses.AltCtrlKeyEnd: return KeyCode.End | KeyCode.AltMask | KeyCode.CtrlMask;
  841. default: return KeyCode.Null;
  842. }
  843. }
  844. private void ProcessMouseEvent (MouseFlags mouseFlag, Point pos)
  845. {
  846. bool WasButtonReleased (MouseFlags flag)
  847. {
  848. return flag.HasFlag (MouseFlags.Button1Released)
  849. || flag.HasFlag (MouseFlags.Button2Released)
  850. || flag.HasFlag (MouseFlags.Button3Released)
  851. || flag.HasFlag (MouseFlags.Button4Released);
  852. }
  853. bool IsButtonNotPressed (MouseFlags flag)
  854. {
  855. return !flag.HasFlag (MouseFlags.Button1Pressed)
  856. && !flag.HasFlag (MouseFlags.Button2Pressed)
  857. && !flag.HasFlag (MouseFlags.Button3Pressed)
  858. && !flag.HasFlag (MouseFlags.Button4Pressed);
  859. }
  860. bool IsButtonClickedOrDoubleClicked (MouseFlags flag)
  861. {
  862. return flag.HasFlag (MouseFlags.Button1Clicked)
  863. || flag.HasFlag (MouseFlags.Button2Clicked)
  864. || flag.HasFlag (MouseFlags.Button3Clicked)
  865. || flag.HasFlag (MouseFlags.Button4Clicked)
  866. || flag.HasFlag (MouseFlags.Button1DoubleClicked)
  867. || flag.HasFlag (MouseFlags.Button2DoubleClicked)
  868. || flag.HasFlag (MouseFlags.Button3DoubleClicked)
  869. || flag.HasFlag (MouseFlags.Button4DoubleClicked);
  870. }
  871. Debug.WriteLine ($"CursesDriver: ({pos.X},{pos.Y}) - {mouseFlag}");
  872. if ((WasButtonReleased (mouseFlag) && IsButtonNotPressed (_lastMouseFlags)) || (IsButtonClickedOrDoubleClicked (mouseFlag) && _lastMouseFlags == 0))
  873. {
  874. return;
  875. }
  876. _lastMouseFlags = mouseFlag;
  877. var me = new MouseEvent { Flags = mouseFlag, Position = pos };
  878. //Debug.WriteLine ($"CursesDriver: ({me.Position}) - {me.Flags}");
  879. OnMouseEvent (me);
  880. }
  881. #region Color Handling
  882. /// <summary>Creates an Attribute from the provided curses-based foreground and background color numbers</summary>
  883. /// <param name="foreground">Contains the curses color number for the foreground (color, plus any attributes)</param>
  884. /// <param name="background">Contains the curses color number for the background (color, plus any attributes)</param>
  885. /// <returns></returns>
  886. private static Attribute MakeColor (short foreground, short background)
  887. {
  888. //var v = (short)((ushort)foreground | (background << 4));
  889. var v = (short)(((ushort)(foreground & 0xffff) << 16) | (background & 0xffff));
  890. // TODO: for TrueColor - Use InitExtendedPair
  891. Curses.InitColorPair (v, foreground, background);
  892. return new Attribute (
  893. Curses.ColorPair (v),
  894. CursesColorNumberToColorName16 (foreground),
  895. CursesColorNumberToColorName16 (background)
  896. );
  897. }
  898. /// <inheritdoc/>
  899. /// <remarks>
  900. /// In the CursesDriver, colors are encoded as an int. The foreground color is stored in the most significant 4
  901. /// bits, and the background color is stored in the least significant 4 bits. The Terminal.GUi Color values are
  902. /// converted to curses color encoding before being encoded.
  903. /// </remarks>
  904. public override Attribute MakeColor (in Color foreground, in Color background)
  905. {
  906. if (!RunningUnitTests && Force16Colors)
  907. {
  908. return MakeColor (
  909. ColorNameToCursesColorNumber (foreground.GetClosestNamedColor16 ()),
  910. ColorNameToCursesColorNumber (background.GetClosestNamedColor16 ())
  911. );
  912. }
  913. return new Attribute (
  914. 0,
  915. foreground,
  916. background
  917. );
  918. }
  919. private static short ColorNameToCursesColorNumber (ColorName16 color)
  920. {
  921. switch (color)
  922. {
  923. case ColorName16.Black:
  924. return Curses.COLOR_BLACK;
  925. case ColorName16.Blue:
  926. return Curses.COLOR_BLUE;
  927. case ColorName16.Green:
  928. return Curses.COLOR_GREEN;
  929. case ColorName16.Cyan:
  930. return Curses.COLOR_CYAN;
  931. case ColorName16.Red:
  932. return Curses.COLOR_RED;
  933. case ColorName16.Magenta:
  934. return Curses.COLOR_MAGENTA;
  935. case ColorName16.Yellow:
  936. return Curses.COLOR_YELLOW;
  937. case ColorName16.Gray:
  938. return Curses.COLOR_WHITE;
  939. case ColorName16.DarkGray:
  940. return Curses.COLOR_GRAY;
  941. case ColorName16.BrightBlue:
  942. return Curses.COLOR_BLUE | Curses.COLOR_GRAY;
  943. case ColorName16.BrightGreen:
  944. return Curses.COLOR_GREEN | Curses.COLOR_GRAY;
  945. case ColorName16.BrightCyan:
  946. return Curses.COLOR_CYAN | Curses.COLOR_GRAY;
  947. case ColorName16.BrightRed:
  948. return Curses.COLOR_RED | Curses.COLOR_GRAY;
  949. case ColorName16.BrightMagenta:
  950. return Curses.COLOR_MAGENTA | Curses.COLOR_GRAY;
  951. case ColorName16.BrightYellow:
  952. return Curses.COLOR_YELLOW | Curses.COLOR_GRAY;
  953. case ColorName16.White:
  954. return Curses.COLOR_WHITE | Curses.COLOR_GRAY;
  955. }
  956. throw new ArgumentException ("Invalid color code");
  957. }
  958. private static ColorName16 CursesColorNumberToColorName16 (short color)
  959. {
  960. switch (color)
  961. {
  962. case Curses.COLOR_BLACK:
  963. return ColorName16.Black;
  964. case Curses.COLOR_BLUE:
  965. return ColorName16.Blue;
  966. case Curses.COLOR_GREEN:
  967. return ColorName16.Green;
  968. case Curses.COLOR_CYAN:
  969. return ColorName16.Cyan;
  970. case Curses.COLOR_RED:
  971. return ColorName16.Red;
  972. case Curses.COLOR_MAGENTA:
  973. return ColorName16.Magenta;
  974. case Curses.COLOR_YELLOW:
  975. return ColorName16.Yellow;
  976. case Curses.COLOR_WHITE:
  977. return ColorName16.Gray;
  978. case Curses.COLOR_GRAY:
  979. return ColorName16.DarkGray;
  980. case Curses.COLOR_BLUE | Curses.COLOR_GRAY:
  981. return ColorName16.BrightBlue;
  982. case Curses.COLOR_GREEN | Curses.COLOR_GRAY:
  983. return ColorName16.BrightGreen;
  984. case Curses.COLOR_CYAN | Curses.COLOR_GRAY:
  985. return ColorName16.BrightCyan;
  986. case Curses.COLOR_RED | Curses.COLOR_GRAY:
  987. return ColorName16.BrightRed;
  988. case Curses.COLOR_MAGENTA | Curses.COLOR_GRAY:
  989. return ColorName16.BrightMagenta;
  990. case Curses.COLOR_YELLOW | Curses.COLOR_GRAY:
  991. return ColorName16.BrightYellow;
  992. case Curses.COLOR_WHITE | Curses.COLOR_GRAY:
  993. return ColorName16.White;
  994. }
  995. throw new ArgumentException ("Invalid curses color code");
  996. }
  997. #endregion
  998. }
  999. internal static class Platform
  1000. {
  1001. private static int _suspendSignal;
  1002. /// <summary>Suspends the process by sending SIGTSTP to itself</summary>
  1003. /// <returns>True if the suspension was successful.</returns>
  1004. public static bool Suspend ()
  1005. {
  1006. int signal = GetSuspendSignal ();
  1007. if (signal == -1)
  1008. {
  1009. return false;
  1010. }
  1011. killpg (0, signal);
  1012. return true;
  1013. }
  1014. private static int GetSuspendSignal ()
  1015. {
  1016. if (_suspendSignal != 0)
  1017. {
  1018. return _suspendSignal;
  1019. }
  1020. nint buf = Marshal.AllocHGlobal (8192);
  1021. if (uname (buf) != 0)
  1022. {
  1023. Marshal.FreeHGlobal (buf);
  1024. _suspendSignal = -1;
  1025. return _suspendSignal;
  1026. }
  1027. try
  1028. {
  1029. switch (Marshal.PtrToStringAnsi (buf))
  1030. {
  1031. case "Darwin":
  1032. case "DragonFly":
  1033. case "FreeBSD":
  1034. case "NetBSD":
  1035. case "OpenBSD":
  1036. _suspendSignal = 18;
  1037. break;
  1038. case "Linux":
  1039. // TODO: should fetch the machine name and
  1040. // if it is MIPS return 24
  1041. _suspendSignal = 20;
  1042. break;
  1043. case "Solaris":
  1044. _suspendSignal = 24;
  1045. break;
  1046. default:
  1047. _suspendSignal = -1;
  1048. break;
  1049. }
  1050. return _suspendSignal;
  1051. }
  1052. finally
  1053. {
  1054. Marshal.FreeHGlobal (buf);
  1055. }
  1056. }
  1057. [DllImport ("libc")]
  1058. private static extern int killpg (int pgrp, int pid);
  1059. [DllImport ("libc")]
  1060. private static extern int uname (nint buf);
  1061. }