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