CursesDriver.cs 42 KB

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