CursesDriver.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  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. public override int Cols
  18. {
  19. get => Curses.Cols;
  20. internal set
  21. {
  22. Curses.Cols = value;
  23. ClearContents ();
  24. }
  25. }
  26. public override int Rows
  27. {
  28. get => Curses.Lines;
  29. internal set
  30. {
  31. Curses.Lines = value;
  32. ClearContents ();
  33. }
  34. }
  35. public override bool SupportsTrueColor => true;
  36. /// <inheritdoc/>
  37. public override bool EnsureCursorVisibility ()
  38. {
  39. if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows))
  40. {
  41. GetCursorVisibility (out CursorVisibility cursorVisibility);
  42. _currentCursorVisibility = cursorVisibility;
  43. SetCursorVisibility (CursorVisibility.Invisible);
  44. return false;
  45. }
  46. SetCursorVisibility (_currentCursorVisibility ?? CursorVisibility.Default);
  47. return _currentCursorVisibility == CursorVisibility.Default;
  48. }
  49. /// <inheritdoc/>
  50. public override bool GetCursorVisibility (out CursorVisibility visibility)
  51. {
  52. visibility = CursorVisibility.Invisible;
  53. if (!_currentCursorVisibility.HasValue)
  54. {
  55. return false;
  56. }
  57. visibility = _currentCursorVisibility.Value;
  58. return true;
  59. }
  60. public override string GetVersionInfo () { return $"{Curses.curses_version ()}"; }
  61. public static bool Is_WSL_Platform ()
  62. {
  63. // xclip does not work on WSL, so we need to use the Windows clipboard vis Powershell
  64. //if (new CursesClipboard ().IsSupported) {
  65. // // If xclip is installed on Linux under WSL, this will return true.
  66. // return false;
  67. //}
  68. (int exitCode, string result) = ClipboardProcessRunner.Bash ("uname -a", waitForOutput: true);
  69. if (exitCode == 0 && result.Contains ("microsoft") && result.Contains ("WSL"))
  70. {
  71. return true;
  72. }
  73. return false;
  74. }
  75. public override bool IsRuneSupported (Rune rune)
  76. {
  77. // See Issue #2615 - CursesDriver is broken with non-BMP characters
  78. return base.IsRuneSupported (rune) && rune.IsBmp;
  79. }
  80. public override void Move (int col, int row)
  81. {
  82. base.Move (col, row);
  83. if (RunningUnitTests)
  84. {
  85. return;
  86. }
  87. if (IsValidLocation (col, row))
  88. {
  89. Curses.move (row, col);
  90. }
  91. else
  92. {
  93. // Not a valid location (outside screen or clip region)
  94. // Move within the clip region, then AddRune will actually move to Col, Row
  95. Curses.move (Clip.Y, Clip.X);
  96. }
  97. }
  98. public override void Refresh ()
  99. {
  100. UpdateScreen ();
  101. UpdateCursor ();
  102. }
  103. public override void SendKeys (char keyChar, ConsoleKey consoleKey, bool shift, bool alt, bool control)
  104. {
  105. KeyCode key;
  106. if (consoleKey == ConsoleKey.Packet)
  107. {
  108. var mod = new ConsoleModifiers ();
  109. if (shift)
  110. {
  111. mod |= ConsoleModifiers.Shift;
  112. }
  113. if (alt)
  114. {
  115. mod |= ConsoleModifiers.Alt;
  116. }
  117. if (control)
  118. {
  119. mod |= ConsoleModifiers.Control;
  120. }
  121. var cKeyInfo = new ConsoleKeyInfo (keyChar, consoleKey, shift, alt, control);
  122. cKeyInfo = ConsoleKeyMapping.DecodeVKPacketToKConsoleKeyInfo (cKeyInfo);
  123. key = ConsoleKeyMapping.MapConsoleKeyInfoToKeyCode (cKeyInfo);
  124. }
  125. else
  126. {
  127. key = (KeyCode)keyChar;
  128. }
  129. OnKeyDown (new Key (key));
  130. OnKeyUp (new Key (key));
  131. //OnKeyPressed (new KeyEventArgsEventArgs (key));
  132. }
  133. /// <inheritdoc/>
  134. public override bool SetCursorVisibility (CursorVisibility visibility)
  135. {
  136. if (_initialCursorVisibility.HasValue == false)
  137. {
  138. return false;
  139. }
  140. if (!RunningUnitTests)
  141. {
  142. Curses.curs_set (((int)visibility >> 16) & 0x000000FF);
  143. }
  144. if (visibility != CursorVisibility.Invisible)
  145. {
  146. Console.Out.Write (
  147. EscSeqUtils.CSI_SetCursorStyle (
  148. (EscSeqUtils.DECSCUSR_Style)(((int)visibility >> 24)
  149. & 0xFF)
  150. )
  151. );
  152. }
  153. _currentCursorVisibility = visibility;
  154. return true;
  155. }
  156. public void StartReportingMouseMoves ()
  157. {
  158. if (!RunningUnitTests)
  159. {
  160. Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents);
  161. }
  162. }
  163. public void StopReportingMouseMoves ()
  164. {
  165. if (!RunningUnitTests)
  166. {
  167. Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
  168. }
  169. }
  170. private readonly ManualResetEventSlim _waitAnsiResponse = new (false);
  171. private readonly CancellationTokenSource _ansiResponseTokenSource = new ();
  172. /// <inheritdoc />
  173. public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest)
  174. {
  175. if (_mainLoopDriver is null)
  176. {
  177. return string.Empty;
  178. }
  179. var response = string.Empty;
  180. try
  181. {
  182. lock (ansiRequest._responseLock)
  183. {
  184. ansiRequest.ResponseFromInput += (s, e) =>
  185. {
  186. Debug.Assert (s == ansiRequest);
  187. ansiRequest.Response = response = e;
  188. _waitAnsiResponse.Set ();
  189. };
  190. _mainLoopDriver.EscSeqRequests.Add (ansiRequest, this);
  191. _mainLoopDriver._forceRead = true;
  192. }
  193. if (!_ansiResponseTokenSource.IsCancellationRequested)
  194. {
  195. _mainLoopDriver._waitForInput.Set ();
  196. _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token);
  197. }
  198. }
  199. catch (OperationCanceledException)
  200. {
  201. return string.Empty;
  202. }
  203. finally
  204. {
  205. _mainLoopDriver._forceRead = false;
  206. if (_mainLoopDriver.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus request))
  207. {
  208. if (_mainLoopDriver.EscSeqRequests.Statuses.Count > 0
  209. && string.IsNullOrEmpty (request.AnsiRequest.Response))
  210. {
  211. // Bad request or no response at all
  212. _mainLoopDriver.EscSeqRequests.Statuses.TryDequeue (out _);
  213. }
  214. }
  215. _waitAnsiResponse.Reset ();
  216. }
  217. return response;
  218. }
  219. /// <inheritdoc />
  220. public override void WriteRaw (string ansi)
  221. {
  222. _mainLoopDriver.WriteRaw (ansi);
  223. }
  224. public override void Suspend ()
  225. {
  226. StopReportingMouseMoves ();
  227. if (!RunningUnitTests)
  228. {
  229. Platform.Suspend ();
  230. if (Force16Colors)
  231. {
  232. Curses.Window.Standard.redrawwin ();
  233. Curses.refresh ();
  234. }
  235. }
  236. StartReportingMouseMoves ();
  237. }
  238. public override void UpdateCursor ()
  239. {
  240. EnsureCursorVisibility ();
  241. if (!RunningUnitTests && Col >= 0 && Col < Cols && Row >= 0 && Row < Rows)
  242. {
  243. if (Force16Colors)
  244. {
  245. Curses.move (Row, Col);
  246. Curses.raw ();
  247. Curses.noecho ();
  248. Curses.refresh ();
  249. }
  250. else
  251. {
  252. _mainLoopDriver.WriteRaw (EscSeqUtils.CSI_SetCursorPosition (Row + 1, Col + 1));
  253. }
  254. }
  255. }
  256. public override void UpdateScreen ()
  257. {
  258. if (Force16Colors)
  259. {
  260. for (var row = 0; row < Rows; row++)
  261. {
  262. if (!_dirtyLines [row])
  263. {
  264. continue;
  265. }
  266. _dirtyLines [row] = false;
  267. for (var col = 0; col < Cols; col++)
  268. {
  269. if (Contents [row, col].IsDirty == false)
  270. {
  271. continue;
  272. }
  273. if (RunningUnitTests)
  274. {
  275. // In unit tests, we don't want to actually write to the screen.
  276. continue;
  277. }
  278. Curses.attrset (Contents [row, col].Attribute.GetValueOrDefault ().PlatformColor);
  279. Rune rune = Contents [row, col].Rune;
  280. if (rune.IsBmp)
  281. {
  282. // 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.
  283. if (rune.GetColumns () < 2)
  284. {
  285. Curses.mvaddch (row, col, rune.Value);
  286. }
  287. else /*if (col + 1 < Cols)*/
  288. {
  289. Curses.mvaddwstr (row, col, rune.ToString ());
  290. }
  291. }
  292. else
  293. {
  294. Curses.mvaddwstr (row, col, rune.ToString ());
  295. if (rune.GetColumns () > 1 && col + 1 < Cols)
  296. {
  297. // TODO: This is a hack to deal with non-BMP and wide characters.
  298. //col++;
  299. Curses.mvaddch (row, ++col, '*');
  300. }
  301. }
  302. }
  303. }
  304. if (!RunningUnitTests)
  305. {
  306. Curses.move (Row, Col);
  307. _window.wrefresh ();
  308. }
  309. }
  310. else
  311. {
  312. if (RunningUnitTests
  313. || Console.WindowHeight < 1
  314. || Contents.Length != Rows * Cols
  315. || Rows != Console.WindowHeight)
  316. {
  317. return;
  318. }
  319. var top = 0;
  320. var left = 0;
  321. int rows = Rows;
  322. int cols = Cols;
  323. var output = new StringBuilder ();
  324. Attribute? redrawAttr = null;
  325. int lastCol = -1;
  326. CursorVisibility? savedVisibility = _currentCursorVisibility;
  327. SetCursorVisibility (CursorVisibility.Invisible);
  328. for (int row = top; row < rows; row++)
  329. {
  330. if (Console.WindowHeight < 1)
  331. {
  332. return;
  333. }
  334. if (!_dirtyLines [row])
  335. {
  336. continue;
  337. }
  338. if (!SetCursorPosition (0, row))
  339. {
  340. return;
  341. }
  342. _dirtyLines [row] = false;
  343. output.Clear ();
  344. for (int col = left; col < cols; col++)
  345. {
  346. lastCol = -1;
  347. var outputWidth = 0;
  348. for (; col < cols; col++)
  349. {
  350. if (!Contents [row, col].IsDirty)
  351. {
  352. if (output.Length > 0)
  353. {
  354. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  355. }
  356. else if (lastCol == -1)
  357. {
  358. lastCol = col;
  359. }
  360. if (lastCol + 1 < cols)
  361. {
  362. lastCol++;
  363. }
  364. continue;
  365. }
  366. if (lastCol == -1)
  367. {
  368. lastCol = col;
  369. }
  370. Attribute attr = Contents [row, col].Attribute.Value;
  371. // Performance: Only send the escape sequence if the attribute has changed.
  372. if (attr != redrawAttr)
  373. {
  374. redrawAttr = attr;
  375. output.Append (
  376. EscSeqUtils.CSI_SetForegroundColorRGB (
  377. attr.Foreground.R,
  378. attr.Foreground.G,
  379. attr.Foreground.B
  380. )
  381. );
  382. output.Append (
  383. EscSeqUtils.CSI_SetBackgroundColorRGB (
  384. attr.Background.R,
  385. attr.Background.G,
  386. attr.Background.B
  387. )
  388. );
  389. }
  390. outputWidth++;
  391. Rune rune = Contents [row, col].Rune;
  392. output.Append (rune);
  393. if (Contents [row, col].CombiningMarks.Count > 0)
  394. {
  395. // AtlasEngine does not support NON-NORMALIZED combining marks in a way
  396. // compatible with the driver architecture. Any CMs (except in the first col)
  397. // are correctly combined with the base char, but are ALSO treated as 1 column
  398. // width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
  399. //
  400. // For now, we just ignore the list of CMs.
  401. //foreach (var combMark in Contents [row, col].CombiningMarks) {
  402. // output.Append (combMark);
  403. //}
  404. // WriteToConsole (output, ref lastCol, row, ref outputWidth);
  405. }
  406. else if (rune.IsSurrogatePair () && rune.GetColumns () < 2)
  407. {
  408. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  409. SetCursorPosition (col - 1, row);
  410. }
  411. Contents [row, col].IsDirty = false;
  412. }
  413. }
  414. if (output.Length > 0)
  415. {
  416. SetCursorPosition (lastCol, row);
  417. Console.Write (output);
  418. }
  419. }
  420. // SIXELS
  421. foreach (var s in Application.Sixel)
  422. {
  423. SetCursorPosition (s.ScreenPosition.X, s.ScreenPosition.Y);
  424. Console.Write(s.SixelData);
  425. }
  426. SetCursorPosition (0, 0);
  427. _currentCursorVisibility = savedVisibility;
  428. void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
  429. {
  430. SetCursorPosition (lastCol, row);
  431. Console.Write (output);
  432. output.Clear ();
  433. lastCol += outputWidth;
  434. outputWidth = 0;
  435. }
  436. }
  437. }
  438. private bool SetCursorPosition (int col, int row)
  439. {
  440. // + 1 is needed because non-Windows is based on 1 instead of 0 and
  441. // Console.CursorTop/CursorLeft isn't reliable.
  442. Console.Out.Write (EscSeqUtils.CSI_SetCursorPosition (row + 1, col + 1));
  443. return true;
  444. }
  445. internal override void End ()
  446. {
  447. _ansiResponseTokenSource?.Cancel ();
  448. _ansiResponseTokenSource?.Dispose ();
  449. _waitAnsiResponse?.Dispose ();
  450. StopReportingMouseMoves ();
  451. SetCursorVisibility (CursorVisibility.Default);
  452. if (RunningUnitTests)
  453. {
  454. return;
  455. }
  456. // throws away any typeahead that has been typed by
  457. // the user and has not yet been read by the program.
  458. Curses.flushinp ();
  459. Curses.endwin ();
  460. }
  461. internal override MainLoop Init ()
  462. {
  463. _mainLoopDriver = new UnixMainLoop (this);
  464. if (!RunningUnitTests)
  465. {
  466. _window = Curses.initscr ();
  467. Curses.set_escdelay (10);
  468. // Ensures that all procedures are performed at some previous closing.
  469. Curses.doupdate ();
  470. //
  471. // We are setting Invisible as default, so we could ignore XTerm DECSUSR setting
  472. //
  473. switch (Curses.curs_set (0))
  474. {
  475. case 0:
  476. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Invisible;
  477. break;
  478. case 1:
  479. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Underline;
  480. Curses.curs_set (1);
  481. break;
  482. case 2:
  483. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Box;
  484. Curses.curs_set (2);
  485. break;
  486. default:
  487. _currentCursorVisibility = _initialCursorVisibility = null;
  488. break;
  489. }
  490. if (!Curses.HasColors)
  491. {
  492. throw new InvalidOperationException ("V2 - This should never happen. File an Issue if it does.");
  493. }
  494. Curses.raw ();
  495. Curses.noecho ();
  496. Curses.Window.Standard.keypad (true);
  497. Curses.StartColor ();
  498. Curses.UseDefaultColors ();
  499. if (!RunningUnitTests)
  500. {
  501. Curses.timeout (0);
  502. }
  503. }
  504. CurrentAttribute = new Attribute (ColorName16.White, ColorName16.Black);
  505. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  506. {
  507. Clipboard = new FakeDriver.FakeClipboard ();
  508. }
  509. else
  510. {
  511. if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
  512. {
  513. Clipboard = new MacOSXClipboard ();
  514. }
  515. else
  516. {
  517. if (Is_WSL_Platform ())
  518. {
  519. Clipboard = new WSLClipboard ();
  520. }
  521. else
  522. {
  523. Clipboard = new CursesClipboard ();
  524. }
  525. }
  526. }
  527. ClearContents ();
  528. StartReportingMouseMoves ();
  529. if (!RunningUnitTests)
  530. {
  531. Curses.CheckWinChange ();
  532. ClearContents ();
  533. if (Force16Colors)
  534. {
  535. Curses.refresh ();
  536. }
  537. }
  538. return new MainLoop (_mainLoopDriver);
  539. }
  540. internal void ProcessInput (UnixMainLoop.PollData inputEvent)
  541. {
  542. switch (inputEvent.EventType)
  543. {
  544. case UnixMainLoop.EventType.Key:
  545. ConsoleKeyInfo consoleKeyInfo = inputEvent.KeyEvent;
  546. KeyCode map = ConsoleKeyMapping.MapConsoleKeyInfoToKeyCode (consoleKeyInfo);
  547. if (map == KeyCode.Null)
  548. {
  549. break;
  550. }
  551. OnKeyDown (new Key (map));
  552. OnKeyUp (new Key (map));
  553. break;
  554. case UnixMainLoop.EventType.Mouse:
  555. MouseEventArgs me = new MouseEventArgs { Position = inputEvent.MouseEvent.Position, Flags = inputEvent.MouseEvent.MouseFlags };
  556. OnMouseEvent (me);
  557. break;
  558. case UnixMainLoop.EventType.WindowSize:
  559. Size size = new (inputEvent.WindowSizeEvent.Size.Width, inputEvent.WindowSizeEvent.Size.Height);
  560. ProcessWinChange (inputEvent.WindowSizeEvent.Size);
  561. break;
  562. default:
  563. throw new ArgumentOutOfRangeException ();
  564. }
  565. }
  566. private void ProcessWinChange (Size size)
  567. {
  568. if (!RunningUnitTests && Curses.ChangeWindowSize (size.Height, size.Width))
  569. {
  570. ClearContents ();
  571. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  572. }
  573. }
  574. private static KeyCode MapCursesKey (int cursesKey)
  575. {
  576. switch (cursesKey)
  577. {
  578. case Curses.KeyF1: return KeyCode.F1;
  579. case Curses.KeyF2: return KeyCode.F2;
  580. case Curses.KeyF3: return KeyCode.F3;
  581. case Curses.KeyF4: return KeyCode.F4;
  582. case Curses.KeyF5: return KeyCode.F5;
  583. case Curses.KeyF6: return KeyCode.F6;
  584. case Curses.KeyF7: return KeyCode.F7;
  585. case Curses.KeyF8: return KeyCode.F8;
  586. case Curses.KeyF9: return KeyCode.F9;
  587. case Curses.KeyF10: return KeyCode.F10;
  588. case Curses.KeyF11: return KeyCode.F11;
  589. case Curses.KeyF12: return KeyCode.F12;
  590. case Curses.KeyUp: return KeyCode.CursorUp;
  591. case Curses.KeyDown: return KeyCode.CursorDown;
  592. case Curses.KeyLeft: return KeyCode.CursorLeft;
  593. case Curses.KeyRight: return KeyCode.CursorRight;
  594. case Curses.KeyHome: return KeyCode.Home;
  595. case Curses.KeyEnd: return KeyCode.End;
  596. case Curses.KeyNPage: return KeyCode.PageDown;
  597. case Curses.KeyPPage: return KeyCode.PageUp;
  598. case Curses.KeyDeleteChar: return KeyCode.Delete;
  599. case Curses.KeyInsertChar: return KeyCode.Insert;
  600. case Curses.KeyTab: return KeyCode.Tab;
  601. case Curses.KeyBackTab: return KeyCode.Tab | KeyCode.ShiftMask;
  602. case Curses.KeyBackspace: return KeyCode.Backspace;
  603. case Curses.ShiftKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask;
  604. case Curses.ShiftKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask;
  605. case Curses.ShiftKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask;
  606. case Curses.ShiftKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask;
  607. case Curses.ShiftKeyHome: return KeyCode.Home | KeyCode.ShiftMask;
  608. case Curses.ShiftKeyEnd: return KeyCode.End | KeyCode.ShiftMask;
  609. case Curses.ShiftKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask;
  610. case Curses.ShiftKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask;
  611. case Curses.AltKeyUp: return KeyCode.CursorUp | KeyCode.AltMask;
  612. case Curses.AltKeyDown: return KeyCode.CursorDown | KeyCode.AltMask;
  613. case Curses.AltKeyLeft: return KeyCode.CursorLeft | KeyCode.AltMask;
  614. case Curses.AltKeyRight: return KeyCode.CursorRight | KeyCode.AltMask;
  615. case Curses.AltKeyHome: return KeyCode.Home | KeyCode.AltMask;
  616. case Curses.AltKeyEnd: return KeyCode.End | KeyCode.AltMask;
  617. case Curses.AltKeyNPage: return KeyCode.PageDown | KeyCode.AltMask;
  618. case Curses.AltKeyPPage: return KeyCode.PageUp | KeyCode.AltMask;
  619. case Curses.CtrlKeyUp: return KeyCode.CursorUp | KeyCode.CtrlMask;
  620. case Curses.CtrlKeyDown: return KeyCode.CursorDown | KeyCode.CtrlMask;
  621. case Curses.CtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.CtrlMask;
  622. case Curses.CtrlKeyRight: return KeyCode.CursorRight | KeyCode.CtrlMask;
  623. case Curses.CtrlKeyHome: return KeyCode.Home | KeyCode.CtrlMask;
  624. case Curses.CtrlKeyEnd: return KeyCode.End | KeyCode.CtrlMask;
  625. case Curses.CtrlKeyNPage: return KeyCode.PageDown | KeyCode.CtrlMask;
  626. case Curses.CtrlKeyPPage: return KeyCode.PageUp | KeyCode.CtrlMask;
  627. case Curses.ShiftCtrlKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.CtrlMask;
  628. case Curses.ShiftCtrlKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.CtrlMask;
  629. case Curses.ShiftCtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.CtrlMask;
  630. case Curses.ShiftCtrlKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.CtrlMask;
  631. case Curses.ShiftCtrlKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.CtrlMask;
  632. case Curses.ShiftCtrlKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.CtrlMask;
  633. case Curses.ShiftCtrlKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.CtrlMask;
  634. case Curses.ShiftCtrlKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.CtrlMask;
  635. case Curses.ShiftAltKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.AltMask;
  636. case Curses.ShiftAltKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.AltMask;
  637. case Curses.ShiftAltKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.AltMask;
  638. case Curses.ShiftAltKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.AltMask;
  639. case Curses.ShiftAltKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.AltMask;
  640. case Curses.ShiftAltKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.AltMask;
  641. case Curses.ShiftAltKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.AltMask;
  642. case Curses.ShiftAltKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.AltMask;
  643. case Curses.AltCtrlKeyNPage: return KeyCode.PageDown | KeyCode.AltMask | KeyCode.CtrlMask;
  644. case Curses.AltCtrlKeyPPage: return KeyCode.PageUp | KeyCode.AltMask | KeyCode.CtrlMask;
  645. case Curses.AltCtrlKeyHome: return KeyCode.Home | KeyCode.AltMask | KeyCode.CtrlMask;
  646. case Curses.AltCtrlKeyEnd: return KeyCode.End | KeyCode.AltMask | KeyCode.CtrlMask;
  647. default: return KeyCode.Null;
  648. }
  649. }
  650. #region Color Handling
  651. /// <summary>Creates an Attribute from the provided curses-based foreground and background color numbers</summary>
  652. /// <param name="foreground">Contains the curses color number for the foreground (color, plus any attributes)</param>
  653. /// <param name="background">Contains the curses color number for the background (color, plus any attributes)</param>
  654. /// <returns></returns>
  655. private static Attribute MakeColor (short foreground, short background)
  656. {
  657. //var v = (short)((ushort)foreground | (background << 4));
  658. var v = (short)(((ushort)(foreground & 0xffff) << 16) | (background & 0xffff));
  659. // TODO: for TrueColor - Use InitExtendedPair
  660. Curses.InitColorPair (v, foreground, background);
  661. return new Attribute (
  662. Curses.ColorPair (v),
  663. CursesColorNumberToColorName16 (foreground),
  664. CursesColorNumberToColorName16 (background)
  665. );
  666. }
  667. /// <inheritdoc/>
  668. /// <remarks>
  669. /// In the CursesDriver, colors are encoded as an int. The foreground color is stored in the most significant 4
  670. /// bits, and the background color is stored in the least significant 4 bits. The Terminal.GUi Color values are
  671. /// converted to curses color encoding before being encoded.
  672. /// </remarks>
  673. public override Attribute MakeColor (in Color foreground, in Color background)
  674. {
  675. if (!RunningUnitTests && Force16Colors)
  676. {
  677. return MakeColor (
  678. ColorNameToCursesColorNumber (foreground.GetClosestNamedColor16 ()),
  679. ColorNameToCursesColorNumber (background.GetClosestNamedColor16 ())
  680. );
  681. }
  682. return new Attribute (
  683. 0,
  684. foreground,
  685. background
  686. );
  687. }
  688. private static short ColorNameToCursesColorNumber (ColorName16 color)
  689. {
  690. switch (color)
  691. {
  692. case ColorName16.Black:
  693. return Curses.COLOR_BLACK;
  694. case ColorName16.Blue:
  695. return Curses.COLOR_BLUE;
  696. case ColorName16.Green:
  697. return Curses.COLOR_GREEN;
  698. case ColorName16.Cyan:
  699. return Curses.COLOR_CYAN;
  700. case ColorName16.Red:
  701. return Curses.COLOR_RED;
  702. case ColorName16.Magenta:
  703. return Curses.COLOR_MAGENTA;
  704. case ColorName16.Yellow:
  705. return Curses.COLOR_YELLOW;
  706. case ColorName16.Gray:
  707. return Curses.COLOR_WHITE;
  708. case ColorName16.DarkGray:
  709. return Curses.COLOR_GRAY;
  710. case ColorName16.BrightBlue:
  711. return Curses.COLOR_BLUE | Curses.COLOR_GRAY;
  712. case ColorName16.BrightGreen:
  713. return Curses.COLOR_GREEN | Curses.COLOR_GRAY;
  714. case ColorName16.BrightCyan:
  715. return Curses.COLOR_CYAN | Curses.COLOR_GRAY;
  716. case ColorName16.BrightRed:
  717. return Curses.COLOR_RED | Curses.COLOR_GRAY;
  718. case ColorName16.BrightMagenta:
  719. return Curses.COLOR_MAGENTA | Curses.COLOR_GRAY;
  720. case ColorName16.BrightYellow:
  721. return Curses.COLOR_YELLOW | Curses.COLOR_GRAY;
  722. case ColorName16.White:
  723. return Curses.COLOR_WHITE | Curses.COLOR_GRAY;
  724. }
  725. throw new ArgumentException ("Invalid color code");
  726. }
  727. private static ColorName16 CursesColorNumberToColorName16 (short color)
  728. {
  729. switch (color)
  730. {
  731. case Curses.COLOR_BLACK:
  732. return ColorName16.Black;
  733. case Curses.COLOR_BLUE:
  734. return ColorName16.Blue;
  735. case Curses.COLOR_GREEN:
  736. return ColorName16.Green;
  737. case Curses.COLOR_CYAN:
  738. return ColorName16.Cyan;
  739. case Curses.COLOR_RED:
  740. return ColorName16.Red;
  741. case Curses.COLOR_MAGENTA:
  742. return ColorName16.Magenta;
  743. case Curses.COLOR_YELLOW:
  744. return ColorName16.Yellow;
  745. case Curses.COLOR_WHITE:
  746. return ColorName16.Gray;
  747. case Curses.COLOR_GRAY:
  748. return ColorName16.DarkGray;
  749. case Curses.COLOR_BLUE | Curses.COLOR_GRAY:
  750. return ColorName16.BrightBlue;
  751. case Curses.COLOR_GREEN | Curses.COLOR_GRAY:
  752. return ColorName16.BrightGreen;
  753. case Curses.COLOR_CYAN | Curses.COLOR_GRAY:
  754. return ColorName16.BrightCyan;
  755. case Curses.COLOR_RED | Curses.COLOR_GRAY:
  756. return ColorName16.BrightRed;
  757. case Curses.COLOR_MAGENTA | Curses.COLOR_GRAY:
  758. return ColorName16.BrightMagenta;
  759. case Curses.COLOR_YELLOW | Curses.COLOR_GRAY:
  760. return ColorName16.BrightYellow;
  761. case Curses.COLOR_WHITE | Curses.COLOR_GRAY:
  762. return ColorName16.White;
  763. }
  764. throw new ArgumentException ("Invalid curses color code");
  765. }
  766. #endregion
  767. }
  768. internal static class Platform
  769. {
  770. private static int _suspendSignal;
  771. /// <summary>Suspends the process by sending SIGTSTP to itself</summary>
  772. /// <returns>True if the suspension was successful.</returns>
  773. public static bool Suspend ()
  774. {
  775. int signal = GetSuspendSignal ();
  776. if (signal == -1)
  777. {
  778. return false;
  779. }
  780. killpg (0, signal);
  781. return true;
  782. }
  783. private static int GetSuspendSignal ()
  784. {
  785. if (_suspendSignal != 0)
  786. {
  787. return _suspendSignal;
  788. }
  789. nint buf = Marshal.AllocHGlobal (8192);
  790. if (uname (buf) != 0)
  791. {
  792. Marshal.FreeHGlobal (buf);
  793. _suspendSignal = -1;
  794. return _suspendSignal;
  795. }
  796. try
  797. {
  798. switch (Marshal.PtrToStringAnsi (buf))
  799. {
  800. case "Darwin":
  801. case "DragonFly":
  802. case "FreeBSD":
  803. case "NetBSD":
  804. case "OpenBSD":
  805. _suspendSignal = 18;
  806. break;
  807. case "Linux":
  808. // TODO: should fetch the machine name and
  809. // if it is MIPS return 24
  810. _suspendSignal = 20;
  811. break;
  812. case "Solaris":
  813. _suspendSignal = 24;
  814. break;
  815. default:
  816. _suspendSignal = -1;
  817. break;
  818. }
  819. return _suspendSignal;
  820. }
  821. finally
  822. {
  823. Marshal.FreeHGlobal (buf);
  824. }
  825. }
  826. [DllImport ("libc")]
  827. private static extern int killpg (int pgrp, int pid);
  828. [DllImport ("libc")]
  829. private static extern int uname (nint buf);
  830. }