CursesDriver.cs 43 KB

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