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