CursesDriver.cs 42 KB

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