CursesDriver.cs 43 KB

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