CursesDriver.cs 34 KB

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