CursesDriver.cs 43 KB

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